<commit_before>module.exports = {
  // Location(s) where custom commands will be loaded from.
  custom_commands_path: null,

  // Location(s) where custom assertions will be loaded from.
  custom_assertions_path: null,

  // Location(s) where page object files will be loaded from.
  page_objects_path: null,

  // Location of an external globals module which will be loaded and made available to the test as a
  //  property globals on the main client instance.
  globals_path: null,

  // An object which will be made available on the main test api, throughout the test execution
  globals: {
    // this controls whether to abort the test execution when an assertion failed and skip the rest
    // it's being used in waitFor commands and expect assertions
    abortOnAssertionFailure: true,

    // this will overwrite the default polling interval (currently 500ms) for waitFor commands
    // and expect assertions that use retry
    waitForConditionPollInterval: 500,

    // default timeout value in milliseconds for waitFor commands and implicit waitFor value for
    // expect assertions
    waitForConditionTimeout : 5000,

    // this will cause waitFor commands on elements to throw an error if multiple
    // elements are found using the given locate strategy and selector
    throwOnMultipleElementsReturned: false,

    // controls the timeout value for async hooks. Expects the done() callback to be invoked within this time
    // or an error is thrown
    asyncHookTimeout : 10000,

    // controls the timeout value for when running async unit tests. Expects the done() callback to be invoked within this time
    // or an error is thrown
    unitTestsTimeout : 2000,

    // controls the timeout value for when executing the global async reporter. Expects the done() callback to be invoked within this time
    // or an error is thrown
    customReporterCallbackTimeout: 20000,

    // Automatically retrying failed assertions - You can tell Nightwatch to automatically retry failed assertions until a given timeout is reached, before the test runner gives up and fails the test.
    retryAssertionTimeout: 1000,

    reporter: function(results, cb) {cb(results);}
  },

  // persist the same globals object between runs or have a (deep) copy of it per each test;
  // this can be useful when persisting data between test suites is needed, such as a cookie or session information
  persist_globals: false,

  // The location where the JUnit XML report files will be saved. Set this to false if you want to disable XML reporting
  output_folder: 'tests_output',

  // A string or array of folders (excluding subfolders) where the tests are located.
  src_folders: null,

  // Used when running in parallel to determine if the output should be collected and displayed at the end.
  live_output: false,

  // Used to disable colored output in the terminal.
  disable_colors: false,

  // Used when running in parallel to specify the delay (in milliseconds) between starting the child processes
  parallel_process_delay: 10,

  // An object containing Selenium Server related configuration options
  // @deprecated
  selenium: {
    start_process: false,
    cli_args: {},
    server_path: null,
    log_path: '',
    port: 4444,
    check_process_delay: 500
  },

  // Whether or not to automatically start the Selenium/WebDriver session. If running unit tests, this should be set tot false.
  start_session: true,

  // End the session automatically when the test is being terminated, usually after a failed assertion.
  end_session_on_fail: true,

  // Skip the remaining test cases from the current test suite, when one test case fails.
  skip_testcases_on_fail: undefined,

  // Whether or not to run individual test files in parallel.
  test_workers: false,

  // Specifies which test runner to use: default|mocha
  test_runner: 'default',

  // Defines options used to connect to the WebDriver/Selenium server
  webdriver : {
    start_process: false,
    cli_args: {},
    server_path: null,
    log_path: '',
    use_legacy_jsonwire: undefined,

    host: undefined,
    port: undefined,
    ssl: undefined,
    proxy: undefined,
    timeout_options: {
      timeout: undefined,
      retry_attempts: undefined
    },
    default_path_prefix: undefined,
    username: undefined,
    access_key: undefined
  },

  // A url which can be used later in the tests as the main url to load.
  launch_url: '',

  // set to false if you want to show the extended http traffic command logs from the WebDriver server.
  silent: true,

  // Used to disable terminal output completely.
  output: true,

  // Set this to false if you'd like to only see the test case name displayed and pass/fail status.
  detailed_output: true,

  // Take error and failure screenshots during test execution
  screenshots: false,

  // Used enable showing the Base64 image data in the (verbose) log when taking screenshots.
  log_screenshot_data: false,

  desiredCapabilities: {
    browserName: 'firefox',
    acceptSslCerts: true
  },

  // An array of folders or file patterns to be skipped (relative to the main source folder).
  exclude: null,

  // Folder or file pattern to be used when loading the tests. Files that don't match this pattern will be ignored.
  filter: null,

  // Skip a group of tests (a subfolder); can be a list of comma-separated values (no space)
  skipgroup: '',

  sync_test_names: true,

  // Skip tests by tag name; can be a list of comma-separated values (no space)
  skiptags: '',

  // Use xpath as the default locator strategy
  use_xpath: false,

  parallel_mode: false,

  report_prefix: '',

  unit_tests_mode: false,

  default_reporter: 'junit'
};<commit_msg>Set selenium.port to undefined.<commit_after>module.exports = {
  // Location(s) where custom commands will be loaded from.
  custom_commands_path: null,

  // Location(s) where custom assertions will be loaded from.
  custom_assertions_path: null,

  // Location(s) where page object files will be loaded from.
  page_objects_path: null,

  // Location of an external globals module which will be loaded and made available to the test as a
  //  property globals on the main client instance.
  globals_path: null,

  // An object which will be made available on the main test api, throughout the test execution
  globals: {
    // this controls whether to abort the test execution when an assertion failed and skip the rest
    // it's being used in waitFor commands and expect assertions
    abortOnAssertionFailure: true,

    // this will overwrite the default polling interval (currently 500ms) for waitFor commands
    // and expect assertions that use retry
    waitForConditionPollInterval: 500,

    // default timeout value in milliseconds for waitFor commands and implicit waitFor value for
    // expect assertions
    waitForConditionTimeout : 5000,

    // this will cause waitFor commands on elements to throw an error if multiple
    // elements are found using the given locate strategy and selector
    throwOnMultipleElementsReturned: false,

    // controls the timeout value for async hooks. Expects the done() callback to be invoked within this time
    // or an error is thrown
    asyncHookTimeout : 10000,

    // controls the timeout value for when running async unit tests. Expects the done() callback to be invoked within this time
    // or an error is thrown
    unitTestsTimeout : 2000,

    // controls the timeout value for when executing the global async reporter. Expects the done() callback to be invoked within this time
    // or an error is thrown
    customReporterCallbackTimeout: 20000,

    // Automatically retrying failed assertions - You can tell Nightwatch to automatically retry failed assertions until a given timeout is reached, before the test runner gives up and fails the test.
    retryAssertionTimeout: 1000,

    reporter: function(results, cb) {cb(results);}
  },

  // persist the same globals object between runs or have a (deep) copy of it per each test;
  // this can be useful when persisting data between test suites is needed, such as a cookie or session information
  persist_globals: false,

  // The location where the JUnit XML report files will be saved. Set this to false if you want to disable XML reporting
  output_folder: 'tests_output',

  // A string or array of folders (excluding subfolders) where the tests are located.
  src_folders: null,

  // Used when running in parallel to determine if the output should be collected and displayed at the end.
  live_output: false,

  // Used to disable colored output in the terminal.
  disable_colors: false,

  // Used when running in parallel to specify the delay (in milliseconds) between starting the child processes
  parallel_process_delay: 10,

  // An object containing Selenium Server related configuration options
  // @deprecated
  selenium: {
    start_process: false,
    cli_args: {},
    server_path: null,
    log_path: '',
    port: undefined,
    check_process_delay: 500
  },

  // Whether or not to automatically start the Selenium/WebDriver session. If running unit tests, this should be set tot false.
  start_session: true,

  // End the session automatically when the test is being terminated, usually after a failed assertion.
  end_session_on_fail: true,

  // Skip the remaining test cases from the current test suite, when one test case fails.
  skip_testcases_on_fail: undefined,

  // Whether or not to run individual test files in parallel.
  test_workers: false,

  // Specifies which test runner to use: default|mocha
  test_runner: 'default',

  // Defines options used to connect to the WebDriver/Selenium server
  webdriver : {
    start_process: false,
    cli_args: {},
    server_path: null,
    log_path: '',
    use_legacy_jsonwire: undefined,

    host: undefined,
    port: undefined,
    ssl: undefined,
    proxy: undefined,
    timeout_options: {
      timeout: undefined,
      retry_attempts: undefined
    },
    default_path_prefix: undefined,
    username: undefined,
    access_key: undefined
  },

  // A url which can be used later in the tests as the main url to load.
  launch_url: '',

  // set to false if you want to show the extended http traffic command logs from the WebDriver server.
  silent: true,

  // Used to disable terminal output completely.
  output: true,

  // Set this to false if you'd like to only see the test case name displayed and pass/fail status.
  detailed_output: true,

  // Take error and failure screenshots during test execution
  screenshots: false,

  // Used enable showing the Base64 image data in the (verbose) log when taking screenshots.
  log_screenshot_data: false,

  desiredCapabilities: {
    browserName: 'firefox',
    acceptSslCerts: true
  },

  // An array of folders or file patterns to be skipped (relative to the main source folder).
  exclude: null,

  // Folder or file pattern to be used when loading the tests. Files that don't match this pattern will be ignored.
  filter: null,

  // Skip a group of tests (a subfolder); can be a list of comma-separated values (no space)
  skipgroup: '',

  sync_test_names: true,

  // Skip tests by tag name; can be a list of comma-separated values (no space)
  skiptags: '',

  // Use xpath as the default locator strategy
  use_xpath: false,

  parallel_mode: false,

  report_prefix: '',

  unit_tests_mode: false,

  default_reporter: 'junit'
};
<|endoftext|>


<commit_before>/*global window, require, console */
/*
 * dataSource.js
 *
 * Copyright (c) 2014 James G Jenner
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

// "use strict"

var node = false;

if (typeof module == "undefined") {
  var module = function () {};
  var exports = this.dataSource = {};
  module.exports = exports;
}
if (typeof require != "undefined") {
  var uuid = require('node-uuid');
  var Widget = require('./widget.js');
}

module.exports = DataSource;

DataSource.KEY = 'DataSource';

DataSource.TYPE_VERSION_ONE = 'Version One';
DataSource.TYPE_JENKINS = 'Jenkins';
DataSource.TYPE_SALES_FORCE = 'Sales Force';
DataSource.TYPE_INTERNAL = 'Internal';

DataSource.VERSION_ONE_ELEMENTS = {
  SPRINT: {
    TOTAL_PROGRESS: {
      name: "Total Progress",
      display: [
        Widget.DISPLAY_TYPE_VALUE,
        Widget.DISPLAY_TYPE_PROGRESS,
      ],
    },
    PROGRESS_BY_STATE: {
      name: "Progress by State",
      display: [
        Widget.DISPLAY_TYPE_GRAPH_PIE,
        Widget.DISPLAY_TYPE_GRAPH_DONUT,
        Widget.DISPLAY_TYPE_GRAPH_SINGLE_BAR_VERTICAL,
        Widget.DISPLAY_TYPE_GRAPH_SINGLE_BAR_HORIZONTAL
      ],
    },
    BURN_DOWN: {
      name: "Burn Down",
      display: [
        Widget.DISPLAY_TYPE_GRAPH_CHART,
      ],
    },
    BURN_UP: {
      name: "Burn Up",
      display: [
        Widget.DISPLAY_TYPE_GRAPH_CHART,
      ],
    },
    DAYS_LEFT: {
      name: "Days Left",
      display: [
        Widget.DISPLAY_TYPE_VALUE,
        Widget.DISPLAY_TYPE_PROGRESS,
      ],
    },
    COMPLETE: {
      name: "Complete",
      display: [
        Widget.DISPLAY_TYPE_VALUE,
      ],
    },
    WIP: {
      name: "WIP",
      display: [
        Widget.DISPLAY_TYPE_VALUE,
      ],
    },
    NOT_STARTED: {
      name: "Not Started",
      display: [
        Widget.DISPLAY_TYPE_VALUE,
      ],
    },
    BLOCKED: {
      name: "Blocked",
      display: [
        Widget.DISPLAY_TYPE_VALUE,
      ],
    },
  },
  QUARTER: {
    TOTAL_PROGRESS: {
      name: "Total Progress",
      display: [
        Widget.DISPLAY_TYPE_VALUE,
        Widget.DISPLAY_TYPE_PROGRESS,
      ],
    },
  },
  RELEASE: {
    TOTAL_PROGRESS: {
      name: "Total Progress",
      display: [
        Widget.DISPLAY_TYPE_VALUE,
        Widget.DISPLAY_TYPE_PROGRESS,
      ],
    },
  },
};

DataSource.JENKINS_ELEMENTS = {
};

DataSource.DEFAULT_NAME = 'DataSource Name';
DataSource.DEFAULT_TYPE = DataSource.TYPE_VERSION_ONE;

DataSource.MESSAGE_ADD_DATA_SOURCE = 'addDataSource';
DataSource.MESSAGE_DELETE_DATA_SOURCE = 'deleteDataSource';
DataSource.MESSAGE_UPDATE_DATA_SOURCE = 'updateDataSource';
DataSource.MESSAGE_GET_DATA_SOURCES = 'getDataSources';
DataSource.MESSAGE_DATA_SOURCES = 'dataSources';

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

  var uuidV1 = ((options.uuidV1 !== null && options.uuidV1 !== undefined) ? options.uuidV1 : false);

  this.id = ((options.id !== null && options.id !== undefined) ? options.id : uuidV1 ? uuid.v1() : uuid.v4());
  this.type = ((options.type !== null && options.type !== undefined) ? options.type : DataSource.DEFAULT_TYPE);
  this.name = ((options.name !== null && options.name !== undefined) ? options.name : DataSource.DEFAULT_NAME);

  this.protocol = ((options.protocol !== null && options.protocol !== undefined) ? options.protocol : '');
  this.hostname = ((options.hostname !== null && options.hostname !== undefined) ? options.hostname : '');
  this.port = ((options.port !== null && options.port !== undefined) ? options.port : '');
  this.instance = ((options.instance !== null && options.instance !== undefined) ? options.instance : '');
  this.username = ((options.username !== null && options.username !== undefined) ? options.username : '');
  this.password = ((options.password !== null && options.password !== undefined) ? options.password : '');

}

/*
 * merge
 */
DataSource.merge = function (d1, d2) {
  mergeAttribute(d1, d2, 'type');
  mergeAttribute(d1, d2, 'name');
  mergeAttribute(d1, d2, 'protocol');
  mergeAttribute(d1, d2, 'hostname');
  mergeAttribute(d1, d2, 'port');
  mergeAttribute(d1, d2, 'instance');
  mergeAttribute(d1, d2, 'username');
  mergeAttribute(d1, d2, 'password');
};

function mergeAttribute(object, modifiedObject, attribute) {
  object[attribute] = ((modifiedObject[attribute] !== null && modifiedObject[attribute] !== undefined) ? modifiedObject[attribute] : object[attribute]);
}<commit_msg>Reworked display matrix structure<commit_after>/*global window, require, console */
/*
 * dataSource.js
 *
 * Copyright (c) 2014 James G Jenner
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

// "use strict"

var node = false;

if (typeof module == "undefined") {
  var module = function () {};
  var exports = this.dataSource = {};
  module.exports = exports;
}
if (typeof require != "undefined") {
  var uuid = require('node-uuid');
  var Widget = require('./widget.js');
}

module.exports = DataSource;

DataSource.KEY = 'DataSource';

DataSource.TYPE_VERSION_ONE = 'Version One';
DataSource.TYPE_JENKINS = 'Jenkins';
DataSource.TYPE_SALES_FORCE = 'Sales Force';
DataSource.TYPE_INTERNAL = 'Internal';

DataSource.DISPLAY_OPTIONS = {};

DataSource.DISPLAY_OPTIONS[DataSource.TYPE_VERSION_ONE] = {
//    SPRINT: {
      TOTAL_PROGRESS: {
        name: "Total Progress",
        display: [
          Widget.DISPLAY_TYPE_VALUE,
          Widget.DISPLAY_TYPE_PROGRESS,
        ],
      },
      PROGRESS_BY_STATE: {
        name: "Progress by State",
        display: [
          Widget.DISPLAY_TYPE_GRAPH_PIE,
          Widget.DISPLAY_TYPE_GRAPH_DONUT,
          Widget.DISPLAY_TYPE_GRAPH_SINGLE_BAR_VERTICAL,
          Widget.DISPLAY_TYPE_GRAPH_SINGLE_BAR_HORIZONTAL
        ],
      },
      BURN_DOWN: {
        name: "Burn Down",
        display: [
          Widget.DISPLAY_TYPE_GRAPH_CHART,
        ],
      },
      BURN_UP: {
        name: "Burn Up",
        display: [
          Widget.DISPLAY_TYPE_GRAPH_CHART,
        ],
      },
      DAYS_LEFT: {
        name: "Days Left",
        display: [
          Widget.DISPLAY_TYPE_VALUE,
          Widget.DISPLAY_TYPE_PROGRESS,
        ],
      },
      COMPLETE: {
        name: "Complete",
        display: [
          Widget.DISPLAY_TYPE_VALUE,
        ],
      },
      WIP: {
        name: "WIP",
        display: [
          Widget.DISPLAY_TYPE_VALUE,
        ],
      },
      NOT_STARTED: {
        name: "Not Started",
        display: [
          Widget.DISPLAY_TYPE_VALUE,
        ],
      },
      BLOCKED: {
        name: "Blocked",
        display: [
          Widget.DISPLAY_TYPE_VALUE,
        ],
      },
//    },
//    QUARTER: {
//      TOTAL_PROGRESS: {
//        name: "Total Progress",
//        display: [
//          Widget.DISPLAY_TYPE_VALUE,
//          Widget.DISPLAY_TYPE_PROGRESS,
//        ],
//      },
//    },
//    RELEASE: {
//      TOTAL_PROGRESS: {
//        name: "Total Progress",
//        display: [
//          Widget.DISPLAY_TYPE_VALUE,
//          Widget.DISPLAY_TYPE_PROGRESS,
//        ],
//      },
//    },
  };

DataSource.JENKINS_ELEMENTS = {
};

DataSource.DEFAULT_NAME = 'DataSource Name';
DataSource.DEFAULT_TYPE = DataSource.TYPE_VERSION_ONE;

DataSource.MESSAGE_ADD_DATA_SOURCE = 'addDataSource';
DataSource.MESSAGE_DELETE_DATA_SOURCE = 'deleteDataSource';
DataSource.MESSAGE_UPDATE_DATA_SOURCE = 'updateDataSource';
DataSource.MESSAGE_GET_DATA_SOURCES = 'getDataSources';
DataSource.MESSAGE_DATA_SOURCES = 'dataSources';

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

  var uuidV1 = ((options.uuidV1 !== null && options.uuidV1 !== undefined) ? options.uuidV1 : false);

  this.id = ((options.id !== null && options.id !== undefined) ? options.id : uuidV1 ? uuid.v1() : uuid.v4());
  this.type = ((options.type !== null && options.type !== undefined) ? options.type : DataSource.DEFAULT_TYPE);
  this.name = ((options.name !== null && options.name !== undefined) ? options.name : DataSource.DEFAULT_NAME);

  this.protocol = ((options.protocol !== null && options.protocol !== undefined) ? options.protocol : '');
  this.hostname = ((options.hostname !== null && options.hostname !== undefined) ? options.hostname : '');
  this.port = ((options.port !== null && options.port !== undefined) ? options.port : '');
  this.instance = ((options.instance !== null && options.instance !== undefined) ? options.instance : '');
  this.username = ((options.username !== null && options.username !== undefined) ? options.username : '');
  this.password = ((options.password !== null && options.password !== undefined) ? options.password : '');

}

/*
 * merge
 */
DataSource.merge = function (d1, d2) {
  mergeAttribute(d1, d2, 'type');
  mergeAttribute(d1, d2, 'name');
  mergeAttribute(d1, d2, 'protocol');
  mergeAttribute(d1, d2, 'hostname');
  mergeAttribute(d1, d2, 'port');
  mergeAttribute(d1, d2, 'instance');
  mergeAttribute(d1, d2, 'username');
  mergeAttribute(d1, d2, 'password');
};

function mergeAttribute(object, modifiedObject, attribute) {
  object[attribute] = ((modifiedObject[attribute] !== null && modifiedObject[attribute] !== undefined) ? modifiedObject[attribute] : object[attribute]);
}<|endoftext|>


<commit_before>///import core
///import plugins\removeformat.js
///commands 字体颜色,背景色,字号,字体,下划线,删除线
///commandsName  ForeColor,BackColor,FontSize,FontFamily,Underline,StrikeThrough
///commandsTitle  字体颜色,背景色,字号,字体,下划线,删除线
/**
 * @description 字体
 * @name baidu.editor.execCommand
 * @param {String}     cmdName    执行的功能名称
 * @param {String}    value             传入的值
 */
UE.plugins['font'] = function () {
    var me = this,
        fonts = {
            'forecolor': 'color',
            'backcolor': 'background-color',
            'fontsize': 'font-size',
            'fontfamily': 'font-family',
            'underline': 'text-decoration',
            'strikethrough': 'text-decoration',
            'fontborder': 'border'
        },
        needCmd = {'underline': 1, 'strikethrough': 1, 'fontborder': 1},
        needSetChild = {
            'forecolor': 'color',
            'backcolor': 'background-color',
            'fontsize': 'font-size',
            'fontfamily': 'font-family'

        }
    me.setOpt({
        'fontfamily': [
            { name: 'songti', val: '宋体,SimSun'},
            { name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
            { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
            { name: 'heiti', val: '黑体, SimHei'},
            { name: 'lishu', val: '隶书, SimLi'},
            { name: 'andaleMono', val: 'andale mono'},
            { name: 'arial', val: 'arial, helvetica,sans-serif'},
            { name: 'arialBlack', val: 'arial black,avant garde'},
            { name: 'comicSansMs', val: 'comic sans ms'},
            { name: 'impact', val: 'impact,chicago'},
            { name: 'timesNewRoman', val: 'times new roman'}
        ],
        'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36]
    });

    function mergeWithParent(node){
        var parent;
        while(parent = node.parentNode){
            if(parent.tagName == 'SPAN' && domUtils.getChildCount(parent,function(child){
                return !domUtils.isBookmarkNode(child) && !domUtils.isBr(child)
            }) == 1) {
                parent.style.cssText += node.style.cssText;
                domUtils.remove(node,true);
                node = parent;

            }else{
                break;
            }
        }

    }
    function mergeChild(rng,cmdName,value){
        if(needSetChild[cmdName]){
            var tmpRng = rng.cloneRange();
            tmpRng.adjustmentBoundary();
            if(!tmpRng.collapsed && tmpRng.startContainer.nodeType == 1){
                var start = tmpRng.startContainer.childNodes[tmpRng.startOffset];
                if(start && domUtils.isTagNode(start,'span')){
                    utils.each(domUtils.getElementsByTagName(start, 'span'), function (span) {
                        if (!span.parentNode)return;

                        //span.style[needSetChild[cmdName]] =  start.style[needSetChild[cmdName]];
                        domUtils.removeStyle(span,needSetChild[cmdName]);
                        if(span.style.cssText.replace(/^\s+$/,'').length == 0){
                            domUtils.remove(span,true)
                        }
                    });
                }
            }
        }

    }
    function mergesibling(rng,cmdName,value) {
        var collapsed = rng.collapsed,
            bk = rng.createBookmark(), common;
        if (collapsed) {
            common = bk.start.parentNode;
            while (dtd.$inline[common.tagName]) {
                common = common.parentNode;
            }
        } else {
            common = domUtils.getCommonAncestor(bk.start, bk.end);
        }
        utils.each(domUtils.getElementsByTagName(common, 'span'), function (span) {
            if (!span.parentNode || domUtils.isBookmarkNode(span))return;
            if (/\s*border\s*:\s*none;?\s*/i.test(span.style.cssText)) {
                if(/^\s*border\s*:\s*none;?\s*$/.test(span.style.cssText)){
                    domUtils.remove(span, true);
                }else{
                    domUtils.removeStyle(span,'border');
                }
                return
            }
            if (/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)) {
                span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi, '');
            }
            var next = span.nextSibling;
            while (next && next.nodeType == 1 && next.tagName == 'SPAN') {
                if (domUtils.isBookmarkNode(next)) {
                    span.appendChild(next);
                } else {
                    if (next.style.cssText == span.style.cssText) {
                        domUtils.moveChild(next, span);
                        domUtils.remove(next);
                    }
                }
                if (span.nextSibling === next)
                    break;
                next = span.nextSibling;
            }

            mergeWithParent(span);
            if(browser.ie && browser.version > 8 ){
                //拷贝父亲们的特别的属性,这里只做背景颜色的处理
                var parent = domUtils.findParent(span,function(n){return n.tagName == 'SPAN' && /background-color/.test(n.style.cssText)});
                if(parent && !/background-color/.test(span.style.cssText)){
                    span.style.backgroundColor = parent.style.backgroundColor;
                }
            }

        });
        rng.moveToBookmark(bk);
        mergeChild(rng,cmdName,value)
    }

    me.addInputRule(function (root) {
        utils.each(root.getNodesByTagName('u s del font'), function (node) {
            if (node.tagName == 'font') {
                var cssStyle = [];
                for (var p in node.attrs) {
                    switch (p) {
                        case 'size':
                            cssStyle.push('font-size:' + node.attrs[p] + 'px');
                            break;
                        case 'color':
                            cssStyle.push('color:' + node.attrs[p]);
                            break;
                        case 'face':
                            cssStyle.push('font-family:' + node.attrs[p]);
                            break;
                        case 'style':
                            cssStyle.push(node.attrs[p]);
                    }
                }
                node.attrs = {
                    'style': cssStyle.join(';')
                };
            } else {
                var val = node.tagName == 'u' ? 'underline' : 'line-through';
                node.attrs = {
                    'style': (node.getAttr('style') || '') + 'text-decoration:' + val + ';'
                }
            }
            node.tagName = 'span';
        });
//        utils.each(root.getNodesByTagName('span'), function (node) {
//            var val;
//            if(val = node.getAttr('class')){
//                if(/fontstrikethrough/.test(val)){
//                    node.setStyle('text-decoration','line-through');
//                    if(node.attrs['class']){
//                        node.attrs['class'] = node.attrs['class'].replace(/fontstrikethrough/,'');
//                    }else{
//                        node.setAttr('class')
//                    }
//                }
//                if(/fontborder/.test(val)){
//                    node.setStyle('border','1px solid #000');
//                    if(node.attrs['class']){
//                        node.attrs['class'] = node.attrs['class'].replace(/fontborder/,'');
//                    }else{
//                        node.setAttr('class')
//                    }
//                }
//            }
//        });
    });
//    me.addOutputRule(function(root){
//        utils.each(root.getNodesByTagName('span'), function (node) {
//            var val;
//            if(val = node.getStyle('text-decoration')){
//                if(/line-through/.test(val)){
//                    if(node.attrs['class']){
//                        node.attrs['class'] += ' fontstrikethrough';
//                    }else{
//                        node.setAttr('class','fontstrikethrough')
//                    }
//                }
//
//                node.setStyle('text-decoration')
//            }
//            if(val = node.getStyle('border')){
//                if(/1px/.test(val) && /solid/.test(val)){
//                    if(node.attrs['class']){
//                        node.attrs['class'] += ' fontborder';
//
//                    }else{
//                        node.setAttr('class','fontborder')
//                    }
//                }
//                node.setStyle('border')
//
//            }
//        });
//    });
    for (var p in fonts) {
        (function (cmd, style) {
            UE.commands[cmd] = {
                execCommand: function (cmdName, value) {
                    value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' :
                        cmdName == 'fontborder' ? '1px solid #000' :
                            'line-through');
                    var me = this,
                        range = this.selection.getRange(),
                        text;

                    if (value == 'default') {

                        if (range.collapsed) {
                            text = me.document.createTextNode('font');
                            range.insertNode(text).select();

                        }
                        me.execCommand('removeFormat', 'span,a', style);
                        if (text) {
                            range.setStartBefore(text).setCursor();
                            domUtils.remove(text);
                        }

                        mergesibling(range,cmdName,value);
                        range.select()
                    } else {
                        if (!range.collapsed) {
                            if (needCmd[cmd] && me.queryCommandValue(cmd)) {
                                me.execCommand('removeFormat', 'span,a', style);
                            }
                            range = me.selection.getRange();

                            range.applyInlineStyle('span', {'style': style + ':' + value});
                            mergesibling(range, cmdName,value);
                            range.select();
                        } else {

                            var span = domUtils.findParentByTagName(range.startContainer, 'span', true);
                            text = me.document.createTextNode('font');
                            if (span && !span.children.length && !span[browser.ie ? 'innerText' : 'textContent'].replace(fillCharReg, '').length) {
                                //for ie hack when enter
                                range.insertNode(text);
                                if (needCmd[cmd]) {
                                    range.selectNode(text).select();
                                    me.execCommand('removeFormat', 'span,a', style, null);

                                    span = domUtils.findParentByTagName(text, 'span', true);
                                    range.setStartBefore(text);

                                }
                                span && (span.style.cssText += ';' + style + ':' + value);
                                range.collapse(true).select();

                            } else {
                                range.insertNode(text);
                                range.selectNode(text).select();
                                span = range.document.createElement('span');

                                if (needCmd[cmd]) {
                                    //a标签内的不处理跳过
                                    if (domUtils.findParentByTagName(text, 'a', true)) {
                                        range.setStartBefore(text).setCursor();
                                        domUtils.remove(text);
                                        return;
                                    }
                                    me.execCommand('removeFormat', 'span,a', style);
                                }

                                span.style.cssText = style + ':' + value;

                                text.parentNode.insertBefore(span, text);
                                //修复，span套span 但样式不继承的问题
                                if (!browser.ie || browser.ie && browser.version == 9) {
                                    var spanParent = span.parentNode;
                                    while (!domUtils.isBlockElm(spanParent)) {
                                        if (spanParent.tagName == 'SPAN') {
                                            //opera合并style不会加入";"
                                            span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText;
                                        }
                                        spanParent = spanParent.parentNode;
                                    }
                                }

                                if (opera) {
                                    setTimeout(function () {
                                        range.setStart(span, 0).collapse(true);
                                        mergesibling(range, cmdName,value);
                                        range.select();
                                    });
                                } else {
                                    range.setStart(span, 0).collapse(true);
                                    mergesibling(range,cmdName,value);
                                    range.select();
                                }

                                //trace:981
                                //domUtils.mergeToParent(span)
                            }
                            domUtils.remove(text);
                        }

                    }
                    return true;
                },
                queryCommandValue: function (cmdName) {
                    var startNode = this.selection.getStart();

                    //trace:946
                    if (cmdName == 'underline' || cmdName == 'strikethrough') {
                        var tmpNode = startNode, value;
                        while (tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)) {
                            if (tmpNode.nodeType == 1) {
                                value = domUtils.getComputedStyle(tmpNode, style);

                                if (value != 'none') {
                                    return value;
                                }
                            }

                            tmpNode = tmpNode.parentNode;
                        }
                        return 'none';
                    }
                    if (cmdName == 'fontborder') {
                        var tmp = startNode, val;
                        while (tmp && dtd.$inline[tmp.tagName]) {
                            if (val = domUtils.getComputedStyle(tmp, 'border')) {
                                if (/1px/.test(val) && /solid/.test(val)) {
                                    return val;
                                }
                            }
                            tmp = tmp.parentNode;
                        }
                        return ''
                    }

                    if( cmdName == 'FontSize' ) {
                        var styleVal = domUtils.getComputedStyle(startNode, style),
                            tmp = /^([\d\.]+)(\w+)$/.exec( styleVal );

                        if( tmp ) {

                            return Math.floor( tmp[1] ) + tmp[2];

                        }

                        return styleVal;

                    }

                    return  domUtils.getComputedStyle(startNode, style);
                },
                queryCommandState: function (cmdName) {
                    if (!needCmd[cmdName])
                        return 0;
                    var val = this.queryCommandValue(cmdName);
                    if (cmdName == 'fontborder') {
                        return /1px/.test(val) && /solid/.test(val)
                    } else {
                        return  val == (cmdName == 'underline' ?
                            'underline' : 'line-through');
                    }

                }
            };
        })(p, fonts[p]);
    }
};<commit_msg>by zhanyi<commit_after>///import core
///import plugins\removeformat.js
///commands 字体颜色,背景色,字号,字体,下划线,删除线
///commandsName  ForeColor,BackColor,FontSize,FontFamily,Underline,StrikeThrough
///commandsTitle  字体颜色,背景色,字号,字体,下划线,删除线
/**
 * @description 字体
 * @name baidu.editor.execCommand
 * @param {String}     cmdName    执行的功能名称
 * @param {String}    value             传入的值
 */
UE.plugins['font'] = function () {
    var me = this,
        fonts = {
            'forecolor': 'color',
            'backcolor': 'background-color',
            'fontsize': 'font-size',
            'fontfamily': 'font-family',
            'underline': 'text-decoration',
            'strikethrough': 'text-decoration',
            'fontborder': 'border'
        },
        needCmd = {'underline': 1, 'strikethrough': 1, 'fontborder': 1},
        needSetChild = {
            'forecolor': 'color',
            'backcolor': 'background-color',
            'fontsize': 'font-size',
            'fontfamily': 'font-family'

        }
    me.setOpt({
        'fontfamily': [
            { name: 'songti', val: '宋体,SimSun'},
            { name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
            { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
            { name: 'heiti', val: '黑体, SimHei'},
            { name: 'lishu', val: '隶书, SimLi'},
            { name: 'andaleMono', val: 'andale mono'},
            { name: 'arial', val: 'arial, helvetica,sans-serif'},
            { name: 'arialBlack', val: 'arial black,avant garde'},
            { name: 'comicSansMs', val: 'comic sans ms'},
            { name: 'impact', val: 'impact,chicago'},
            { name: 'timesNewRoman', val: 'times new roman'}
        ],
        'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36]
    });

    function mergeWithParent(node){
        var parent;
        while(parent = node.parentNode){
            if(parent.tagName == 'SPAN' && domUtils.getChildCount(parent,function(child){
                return !domUtils.isBookmarkNode(child) && !domUtils.isBr(child)
            }) == 1) {
                parent.style.cssText += node.style.cssText;
                domUtils.remove(node,true);
                node = parent;

            }else{
                break;
            }
        }

    }
    function mergeChild(rng,cmdName,value){
        if(needSetChild[cmdName]){
            rng.adjustmentBoundary();
            if(!rng.collapsed && rng.startContainer.nodeType == 1){
                var start = rng.startContainer.childNodes[rng.startOffset];
                if(start && domUtils.isTagNode(start,'span')){
                    var bk = rng.createBookmark();
                    utils.each(domUtils.getElementsByTagName(start, 'span'), function (span) {
                        if (!span.parentNode || domUtils.isBookmarkNode(span))return;
                        domUtils.removeStyle(span,needSetChild[cmdName]);
                        if(span.style.cssText.replace(/^\s+$/,'').length == 0){
                            domUtils.remove(span,true)
                        }
                    });
                    rng.moveToBookmark(bk)
                }
            }
        }

    }
    function mergesibling(rng,cmdName,value) {
        var collapsed = rng.collapsed,
            bk = rng.createBookmark(), common;
        if (collapsed) {
            common = bk.start.parentNode;
            while (dtd.$inline[common.tagName]) {
                common = common.parentNode;
            }
        } else {
            common = domUtils.getCommonAncestor(bk.start, bk.end);
        }
        utils.each(domUtils.getElementsByTagName(common, 'span'), function (span) {
            if (!span.parentNode || domUtils.isBookmarkNode(span))return;
            if (/\s*border\s*:\s*none;?\s*/i.test(span.style.cssText)) {
                if(/^\s*border\s*:\s*none;?\s*$/.test(span.style.cssText)){
                    domUtils.remove(span, true);
                }else{
                    domUtils.removeStyle(span,'border');
                }
                return
            }
            if (/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)) {
                span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi, '');
            }
            var next = span.nextSibling;
            while (next && next.nodeType == 1 && next.tagName == 'SPAN') {
                if (domUtils.isBookmarkNode(next)) {
                    span.appendChild(next);
                } else {
                    if (next.style.cssText == span.style.cssText) {
                        domUtils.moveChild(next, span);
                        domUtils.remove(next);
                    }
                }
                if (span.nextSibling === next)
                    break;
                next = span.nextSibling;
            }

            mergeWithParent(span);
            if(browser.ie && browser.version > 8 ){
                //拷贝父亲们的特别的属性,这里只做背景颜色的处理
                var parent = domUtils.findParent(span,function(n){return n.tagName == 'SPAN' && /background-color/.test(n.style.cssText)});
                if(parent && !/background-color/.test(span.style.cssText)){
                    span.style.backgroundColor = parent.style.backgroundColor;
                }
            }

        });
        rng.moveToBookmark(bk);
        mergeChild(rng,cmdName,value)
    }

    me.addInputRule(function (root) {
        utils.each(root.getNodesByTagName('u s del font'), function (node) {
            if (node.tagName == 'font') {
                var cssStyle = [];
                for (var p in node.attrs) {
                    switch (p) {
                        case 'size':
                            cssStyle.push('font-size:' + node.attrs[p] + 'px');
                            break;
                        case 'color':
                            cssStyle.push('color:' + node.attrs[p]);
                            break;
                        case 'face':
                            cssStyle.push('font-family:' + node.attrs[p]);
                            break;
                        case 'style':
                            cssStyle.push(node.attrs[p]);
                    }
                }
                node.attrs = {
                    'style': cssStyle.join(';')
                };
            } else {
                var val = node.tagName == 'u' ? 'underline' : 'line-through';
                node.attrs = {
                    'style': (node.getAttr('style') || '') + 'text-decoration:' + val + ';'
                }
            }
            node.tagName = 'span';
        });
//        utils.each(root.getNodesByTagName('span'), function (node) {
//            var val;
//            if(val = node.getAttr('class')){
//                if(/fontstrikethrough/.test(val)){
//                    node.setStyle('text-decoration','line-through');
//                    if(node.attrs['class']){
//                        node.attrs['class'] = node.attrs['class'].replace(/fontstrikethrough/,'');
//                    }else{
//                        node.setAttr('class')
//                    }
//                }
//                if(/fontborder/.test(val)){
//                    node.setStyle('border','1px solid #000');
//                    if(node.attrs['class']){
//                        node.attrs['class'] = node.attrs['class'].replace(/fontborder/,'');
//                    }else{
//                        node.setAttr('class')
//                    }
//                }
//            }
//        });
    });
//    me.addOutputRule(function(root){
//        utils.each(root.getNodesByTagName('span'), function (node) {
//            var val;
//            if(val = node.getStyle('text-decoration')){
//                if(/line-through/.test(val)){
//                    if(node.attrs['class']){
//                        node.attrs['class'] += ' fontstrikethrough';
//                    }else{
//                        node.setAttr('class','fontstrikethrough')
//                    }
//                }
//
//                node.setStyle('text-decoration')
//            }
//            if(val = node.getStyle('border')){
//                if(/1px/.test(val) && /solid/.test(val)){
//                    if(node.attrs['class']){
//                        node.attrs['class'] += ' fontborder';
//
//                    }else{
//                        node.setAttr('class','fontborder')
//                    }
//                }
//                node.setStyle('border')
//
//            }
//        });
//    });
    for (var p in fonts) {
        (function (cmd, style) {
            UE.commands[cmd] = {
                execCommand: function (cmdName, value) {
                    value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' :
                        cmdName == 'fontborder' ? '1px solid #000' :
                            'line-through');
                    var me = this,
                        range = this.selection.getRange(),
                        text;

                    if (value == 'default') {

                        if (range.collapsed) {
                            text = me.document.createTextNode('font');
                            range.insertNode(text).select();

                        }
                        me.execCommand('removeFormat', 'span,a', style);
                        if (text) {
                            range.setStartBefore(text).setCursor();
                            domUtils.remove(text);
                        }

                        mergesibling(range,cmdName,value);
                        range.select()
                    } else {
                        if (!range.collapsed) {
                            if (needCmd[cmd] && me.queryCommandValue(cmd)) {
                                me.execCommand('removeFormat', 'span,a', style);
                            }
                            range = me.selection.getRange();

                            range.applyInlineStyle('span', {'style': style + ':' + value});
                            mergesibling(range, cmdName,value);
                            range.select();
                        } else {

                            var span = domUtils.findParentByTagName(range.startContainer, 'span', true);
                            text = me.document.createTextNode('font');
                            if (span && !span.children.length && !span[browser.ie ? 'innerText' : 'textContent'].replace(fillCharReg, '').length) {
                                //for ie hack when enter
                                range.insertNode(text);
                                if (needCmd[cmd]) {
                                    range.selectNode(text).select();
                                    me.execCommand('removeFormat', 'span,a', style, null);

                                    span = domUtils.findParentByTagName(text, 'span', true);
                                    range.setStartBefore(text);

                                }
                                span && (span.style.cssText += ';' + style + ':' + value);
                                range.collapse(true).select();

                            } else {
                                range.insertNode(text);
                                range.selectNode(text).select();
                                span = range.document.createElement('span');

                                if (needCmd[cmd]) {
                                    //a标签内的不处理跳过
                                    if (domUtils.findParentByTagName(text, 'a', true)) {
                                        range.setStartBefore(text).setCursor();
                                        domUtils.remove(text);
                                        return;
                                    }
                                    me.execCommand('removeFormat', 'span,a', style);
                                }

                                span.style.cssText = style + ':' + value;

                                text.parentNode.insertBefore(span, text);
                                //修复，span套span 但样式不继承的问题
                                if (!browser.ie || browser.ie && browser.version == 9) {
                                    var spanParent = span.parentNode;
                                    while (!domUtils.isBlockElm(spanParent)) {
                                        if (spanParent.tagName == 'SPAN') {
                                            //opera合并style不会加入";"
                                            span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText;
                                        }
                                        spanParent = spanParent.parentNode;
                                    }
                                }

                                if (opera) {
                                    setTimeout(function () {
                                        range.setStart(span, 0).collapse(true);
                                        mergesibling(range, cmdName,value);
                                        range.select();
                                    });
                                } else {
                                    range.setStart(span, 0).collapse(true);
                                    mergesibling(range,cmdName,value);
                                    range.select();
                                }

                                //trace:981
                                //domUtils.mergeToParent(span)
                            }
                            domUtils.remove(text);
                        }

                    }
                    return true;
                },
                queryCommandValue: function (cmdName) {
                    var startNode = this.selection.getStart();

                    //trace:946
                    if (cmdName == 'underline' || cmdName == 'strikethrough') {
                        var tmpNode = startNode, value;
                        while (tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)) {
                            if (tmpNode.nodeType == 1) {
                                value = domUtils.getComputedStyle(tmpNode, style);

                                if (value != 'none') {
                                    return value;
                                }
                            }

                            tmpNode = tmpNode.parentNode;
                        }
                        return 'none';
                    }
                    if (cmdName == 'fontborder') {
                        var tmp = startNode, val;
                        while (tmp && dtd.$inline[tmp.tagName]) {
                            if (val = domUtils.getComputedStyle(tmp, 'border')) {
                                if (/1px/.test(val) && /solid/.test(val)) {
                                    return val;
                                }
                            }
                            tmp = tmp.parentNode;
                        }
                        return ''
                    }

                    if( cmdName == 'FontSize' ) {
                        var styleVal = domUtils.getComputedStyle(startNode, style),
                            tmp = /^([\d\.]+)(\w+)$/.exec( styleVal );

                        if( tmp ) {

                            return Math.floor( tmp[1] ) + tmp[2];

                        }

                        return styleVal;

                    }

                    return  domUtils.getComputedStyle(startNode, style);
                },
                queryCommandState: function (cmdName) {
                    if (!needCmd[cmdName])
                        return 0;
                    var val = this.queryCommandValue(cmdName);
                    if (cmdName == 'fontborder') {
                        return /1px/.test(val) && /solid/.test(val)
                    } else {
                        return  val == (cmdName == 'underline' ?
                            'underline' : 'line-through');
                    }

                }
            };
        })(p, fonts[p]);
    }
};<|endoftext|>


<commit_before>/* Copyright (c) 2013 Rod Vagg, MIT License */

function AbstractIterator (db) {
  this.db = db
  this._ended = false
  this._nexting = false
}

AbstractIterator.prototype.next = function (callback) {
  if (typeof callback != 'function')
    throw new Error('next() requires a callback argument')

  if (this._ended)
    return callback(new Error('cannot call next() after end()'))
  if (this._nexting)
    return callback(new Error('cannot call next() before previous next() has completed'))

  this._nexting = true
  if (typeof this._next == 'function') {
    return this._next(function () {
      this._nexting = false
      callback.apply(null, arguments)
    }.bind(this))
  }

  process.nextTick(function () {
    this._nexting = false
    callback()
  }.bind(this))
}

AbstractIterator.prototype.end = function (callback) {
  if (typeof callback != 'function')
    throw new Error('end() requires a callback argument')

  if (this._ended)
    throw new Error('end() already called on iterator')

  this._ended = true

  if (typeof this._end == 'function')
    return this._end(callback)

  process.nextTick(callback)
}

module.exports = AbstractIterator
<commit_msg>I forgot to convert one more throw in a callback in the AbstractIterator#end()<commit_after>/* Copyright (c) 2013 Rod Vagg, MIT License */

function AbstractIterator (db) {
  this.db = db
  this._ended = false
  this._nexting = false
}

AbstractIterator.prototype.next = function (callback) {
  if (typeof callback != 'function')
    throw new Error('next() requires a callback argument')

  if (this._ended)
    return callback(new Error('cannot call next() after end()'))
  if (this._nexting)
    return callback(new Error('cannot call next() before previous next() has completed'))

  this._nexting = true
  if (typeof this._next == 'function') {
    return this._next(function () {
      this._nexting = false
      callback.apply(null, arguments)
    }.bind(this))
  }

  process.nextTick(function () {
    this._nexting = false
    callback()
  }.bind(this))
}

AbstractIterator.prototype.end = function (callback) {
  if (typeof callback != 'function')
    throw new Error('end() requires a callback argument')

  if (this._ended)
    return callback(new Error('end() already called on iterator'))

  this._ended = true

  if (typeof this._end == 'function')
    return this._end(callback)

  process.nextTick(callback)
}

module.exports = AbstractIterator
<|endoftext|>


<commit_before>var clone = require('clone');

module.exports = function(deps){

    this.get = function(params){
        var self = this;

        if (params.length > 0) {
            return this.getOne(params);
        }

        return deps.pluginPrefs.findAsync({}).then(function(docs){
            var prefs = [],
                returnDocs = [],
                listenerAliases = [],
                formattedDoc;

            for (var i = 0, len = docs.length; i < len; i++) {
                formattedDoc = self.formatDoc(docs[i]);
                returnDocs.push(formattedDoc.plugins);

                if (formattedDoc.prefs.length > 0) {
                    Array.prototype.push.apply(prefs, formattedDoc.prefs)
                }

                if (formattedDoc.prefs.length > 0) {
                    Array.prototype.push.apply(prefs, formattedDoc.prefs)
                }

                if (formattedDoc.listeneraliases.length > 0) {
                    Array.prototype.push.apply(listenerAliases, formattedDoc.listeneraliases)
                }
            }

            return {plugins: returnDocs, prefs: prefs, listeneraliases: listenerAliases};
        })
    };

    this.getOne = function(params){
        var self = this;

        return deps.pluginPrefs.findOneAsync({name: params[0]}).then(function(doc){
            return self.formatDoc(doc);
        });
    };

    this.formatDoc = function(doc){
        var prefs = [],
            prefIds = [],
            newPrefsTemplateIds = [],
            newDoc = clone(doc),
            listeners = {},
            listenerAliases = [],
            listenerAliasIds = [];

        newDoc.id = newDoc.name;
        delete newDoc._id;

        for (var key in deps.api.listeners) {
            if (deps.api.listeners[key].module.name === doc.name && !deps.api.listeners[key].isAlias) {
                listeners[deps.api.listeners[key].listener] = {
                    id: deps.api.listeners[key].module.name + deps.api.listeners[key].listener,
                    listener: deps.api.listeners[key].listener.replace(
                        /(\((:<(.+?)>)*([\(].+?[\)])*(.+?)\))/g,
                        function (group, groupinner, namegroup, name) {
                            if (typeof name !== 'undefined') {
                                return '<<' + name + '>>'
                            }

                            return group;
                        }
                    ),
                    alias: ''
                };
                listenerAliasIds.push(deps.api.listeners[key].module.name + deps.api.listeners[key].listener)
            }
        }

        if (doc.listeneraliases && doc.listeneraliases.length > 0) {
            doc.listeneraliases.forEach(function() {
                listeners[deps.api.listeners[key].listener].alias = doc.listeneraliases.alias
            });
        }

        listenerAliases = Object.keys(listeners).map(function (key) {return listeners[key]});
        newDoc.listeneraliases = listenerAliasIds;

        if (typeof newDoc.prefs !== 'undefined') {

            for (var a = 0, preflen = newDoc.prefs.length; a < preflen; a++) {
                newDoc.prefs[a].id = newDoc.name + newDoc.prefs[a].name;

                if (newDoc.prefs[a].group) {
                    newDoc.prefs[a].id += newDoc.prefs[a].group;
                }

                newDoc.prefs[a].plugin = newDoc.id;

                if (newDoc.prefs[a].type === 'password') {
                    newDoc.prefs[a].value = '';
                }

                prefs.push(newDoc.prefs[a]);
                prefIds.push(newDoc.prefs[a].id);
            }

        }
        newDoc.prefs = prefIds;

        if (typeof newDoc.newPrefsTemplate !== 'undefined') {
            for (var a = 0, preflen = newDoc.newPrefsTemplate.length; a < preflen; a++) {
                newDoc.newPrefsTemplate[a].id = newDoc.name + newDoc.newPrefsTemplate[a].name;
                newDoc.newPrefsTemplate[a].plugin = newDoc.id;

                prefs.push(newDoc.newPrefsTemplate[a]);
                newPrefsTemplateIds.push(newDoc.newPrefsTemplate[a].id);
            }
        }

        newDoc.newPrefsTemplate = newPrefsTemplateIds
        return {plugins: newDoc, prefs: prefs, listeneraliases: listenerAliases};
    }

    this.put = function(params, body){
        if (params.length > 0) {
            return this.putOne(params, body);
        }
    };

    this.putOne = function(params, body){
        var self = this;

        return deps.pluginPrefs.updateAsync({name: params[0]}, {$set: body.plugin}).then(function(){
            return deps.pluginPrefs.findOneAsync({name: params[0]}).then(function(doc){
                deps.api.reloadModule(doc.name, 'plugins');

                return self.formatDoc(doc);
            });
        });
    };

    return this;
}
<commit_msg>Loop wasn't where it should have been, why did it work locally?<commit_after>var clone = require('clone');

module.exports = function(deps){

    this.get = function(params){
        var self = this;

        if (params.length > 0) {
            return this.getOne(params);
        }

        return deps.pluginPrefs.findAsync({}).then(function(docs){
            var prefs = [],
                returnDocs = [],
                listenerAliases = [],
                formattedDoc;

            for (var i = 0, len = docs.length; i < len; i++) {
                formattedDoc = self.formatDoc(docs[i]);
                returnDocs.push(formattedDoc.plugins);

                if (formattedDoc.prefs.length > 0) {
                    Array.prototype.push.apply(prefs, formattedDoc.prefs)
                }

                if (formattedDoc.prefs.length > 0) {
                    Array.prototype.push.apply(prefs, formattedDoc.prefs)
                }

                if (formattedDoc.listeneraliases.length > 0) {
                    Array.prototype.push.apply(listenerAliases, formattedDoc.listeneraliases)
                }
            }

            return {plugins: returnDocs, prefs: prefs, listeneraliases: listenerAliases};
        })
    };

    this.getOne = function(params){
        var self = this;

        return deps.pluginPrefs.findOneAsync({name: params[0]}).then(function(doc){
            return self.formatDoc(doc);
        });
    };

    this.formatDoc = function(doc){
        var prefs = [],
            prefIds = [],
            newPrefsTemplateIds = [],
            newDoc = clone(doc),
            listeners = {},
            listenerAliases = [],
            listenerAliasIds = [];

        newDoc.id = newDoc.name;
        delete newDoc._id;

        for (var key in deps.api.listeners) {
            if (deps.api.listeners[key].module.name === doc.name && !deps.api.listeners[key].isAlias) {
                listeners[deps.api.listeners[key].listener] = {
                    id: deps.api.listeners[key].module.name + deps.api.listeners[key].listener,
                    listener: deps.api.listeners[key].listener.replace(
                        /(\((:<(.+?)>)*([\(].+?[\)])*(.+?)\))/g,
                        function (group, groupinner, namegroup, name) {
                            if (typeof name !== 'undefined') {
                                return '<<' + name + '>>'
                            }

                            return group;
                        }
                    ),
                    alias: ''
                };
                listenerAliasIds.push(deps.api.listeners[key].module.name + deps.api.listeners[key].listener);

                if (doc.listeneraliases && doc.listeneraliases.length > 0) {
                    doc.listeneraliases.forEach(function() {
                        listeners[deps.api.listeners[key].listener].alias = doc.listeneraliases.alias
                    });
                }
            }
        }

        listenerAliases = Object.keys(listeners).map(function (key) {return listeners[key]});
        newDoc.listeneraliases = listenerAliasIds;

        if (typeof newDoc.prefs !== 'undefined') {

            for (var a = 0, preflen = newDoc.prefs.length; a < preflen; a++) {
                newDoc.prefs[a].id = newDoc.name + newDoc.prefs[a].name;

                if (newDoc.prefs[a].group) {
                    newDoc.prefs[a].id += newDoc.prefs[a].group;
                }

                newDoc.prefs[a].plugin = newDoc.id;

                if (newDoc.prefs[a].type === 'password') {
                    newDoc.prefs[a].value = '';
                }

                prefs.push(newDoc.prefs[a]);
                prefIds.push(newDoc.prefs[a].id);
            }

        }
        newDoc.prefs = prefIds;

        if (typeof newDoc.newPrefsTemplate !== 'undefined') {
            for (var a = 0, preflen = newDoc.newPrefsTemplate.length; a < preflen; a++) {
                newDoc.newPrefsTemplate[a].id = newDoc.name + newDoc.newPrefsTemplate[a].name;
                newDoc.newPrefsTemplate[a].plugin = newDoc.id;

                prefs.push(newDoc.newPrefsTemplate[a]);
                newPrefsTemplateIds.push(newDoc.newPrefsTemplate[a].id);
            }
        }

        newDoc.newPrefsTemplate = newPrefsTemplateIds
        return {plugins: newDoc, prefs: prefs, listeneraliases: listenerAliases};
    }

    this.put = function(params, body){
        if (params.length > 0) {
            return this.putOne(params, body);
        }
    };

    this.putOne = function(params, body){
        var self = this;

        return deps.pluginPrefs.updateAsync({name: params[0]}, {$set: body.plugin}).then(function(){
            return deps.pluginPrefs.findOneAsync({name: params[0]}).then(function(doc){
                deps.api.reloadModule(doc.name, 'plugins');

                return self.formatDoc(doc);
            });
        });
    };

    return this;
}
<|endoftext|>


<commit_before>if (!dp) var dp = {};

dp.test = {
    failed: false,
    init: function() {
        var wait = 10;

        dp_assert(function() {
            return _el('#input-test').length;
        }, 'test-el');

        dp_assert(dp.helper.string.uniqid(), 'test-uniqid');
        dp_assert(dp.helper.string.uniqid('prefix_'), 'test-uniqid-with-prefix');
        dp_assert(dp.helper.string.uniqid('prefix_', true), 'test-uniqid-with-entropy');
        dp_assert(dp.helper.string.uniqid('prefix_', true, '-'), 'test-uniqid-with-entropy-separator');

        var temp_prefix = dp.vars.prefix;

        dp.vars.prefix = '/front';

        dp_assert(dp.helper.prefixize('/front') === '/', 'helper-prefixize-global-prefix');
        dp_assert(dp.helper.prefixize('/front/') === '/', 'helper-prefixize-global-prefix');
        dp_assert(dp.helper.prefixize('/front/foo/bar') === '/foo/bar', 'helper-prefixize-global-prefix');

        dp.vars.prefix = undefined;

        dp_assert(dp.helper.prefixize('/front/foo/bar') === '/front/foo/bar', 'helper-prefixize-no-prefix');
        dp_assert(dp.helper.prefixize('/front/foo/bar', '/front') === '/foo/bar', 'helper-prefixize-with-prefix');
        dp_assert(dp.helper.prefixize('/front/foo/bar', '/front/') === '/foo/bar', 'helper-prefixize-with-prefix-slash');
        dp_assert(dp.helper.prefixize('/front', '/front') === '/', 'helper-prefixize-with-prefix');
        dp_assert(dp.helper.prefixize('/front', '/front/') === '/', 'helper-prefixize-with-prefix-slash');

        dp.vars.prefix = temp_prefix;

        dp_assert(dp.helper.validator.email('email@valid.com'), 'helper-validator-email');
        dp_assert(dp.helper.validator.email('email@.invalid.com') == false, 'helper-validator-email');

        dp_assert(dp.helper.validator.url('http://www.google.com'), 'helper-validator-url');
        dp_assert(dp.helper.validator.url('http://www.google'), 'helper-validator-url');
        dp_assert(dp.helper.validator.url('http://123.123.123.123'), 'helper-validator-url');
        dp_assert(dp.helper.validator.url('http://123.123.123.256') == false, 'helper-validator-url');
        dp_assert(dp.helper.validator.url('https://www.google.') == false, 'helper-validator-url');

        dp_assert(dp.helper.string.replaceAll('abcd', 'a', '-') === '-bcd', 'helper-string-replaceAll');

        var a_wait = 280;
        var a_done = 550;
        var an_done = 700;

        // dp.req

        var r1 = dp.req(_el('#req-test-case-1'), {
            'before': function() {
                return false;
            }
        });

        dp_assert(r1 == false, 'helper-req-before-false');

        //

        _el('#req-test-case-1 input[name="email"]').val('');

        var r2 = dp.req(_el('#req-test-case-1'));

        setTimeout(function() {
            dp_assert(r2.find('._msg').text() == _el('#req-test-case-1 input[name="email"]').attr('dp-req-missing'), 'helper-req-field-missing');
            dp_jqlib(r2.find('button').get(0)).trigger('click');
        }, a_done);

        //

        _el('#req-test-case-1 input[name="email"]').val('invalid@email@address.com');

        var r3 = dp.req(_el('#req-test-case-1'));

        setTimeout(function() {
            dp_assert(r3.find('._msg').text() == _el('#req-test-case-1 input[name="email"]').attr('dp-req-invalid'), 'helper-req-field-invalid');
            dp_jqlib(r3.find('button').get(0)).trigger('click');
        }, a_done);

        //

        _el('#req-test-case-1 input[name="email"]').val('john@email.com');

        var r4 = dp.req(_el('#req-test-case-1'), {
            success: function(data) {
                dp_assert(data.result, 'helper-req-field-confirm-response-success');
            },
            error: function() {
                dp_assert(false, 'helper-req-field-confirm-response-error');
            }
        });

        setTimeout(function() {
            dp_assert(r4.find('._msg').text() == _el('#req-test-case-1 button').attr('dp-req-confirm'), 'helper-req-field-confirm');
            dp_jqlib(r4.find('button').get(0)).trigger('click');
        }, a_done);

        //

        var r5 = dp.req(_el('#req-test-case-1'));

        dp_assert(r5 == false, 'helper-req-no-multiple');

        //

        _el('#req-test-case-1 button').attr('dp-req-multiple', 'yes');

        var r6 = dp.req(_el('#req-test-case-1'));
        var r7 = dp.req(_el('#req-test-case-1'));

        setTimeout(function() {
            dp_assert(r6.find('._msg').text() == _el('#req-test-case-1 button').attr('dp-req-confirm'), 'helper-req-multiple-first');
            dp_jqlib(r6.find('button').get(1)).trigger('click');
        }, a_done);

        setTimeout(function() {
            dp_assert(r7.find('._msg').text() == _el('#req-test-case-1 button').attr('dp-req-confirm'), 'helper-req-multiple-second');
            dp_jqlib(r7.find('button').get(1)).trigger('click');
        }, a_done);

        //

        var r8_id = dp.helper.string.uniqid();
        _el('#req-test-case-1').clone().attr('id', r8_id).appendTo(_el('body'));
        _el('#' + r8_id + ' input[name="name"]').val('short');

        var r8 = dp.req(_el('#' + r8_id));

        setTimeout(function() {
            dp_assert(r8.find('._msg').text() == _el('#' + r8_id + ' input[name="name"]').attr('dp-req-invalid'), 'helper-req-field-too-short');
            dp_jqlib(r8.find('button').get(0)).trigger('click');

            _el('#' + r8_id).remove();
        }, a_done);

        //

        var r9_id = dp.helper.string.uniqid();
        _el('#req-test-case-1').clone().attr('id', r9_id).appendTo(_el('body'));
        _el('#' + r9_id + ' input[name="name"]').val('too loooooooooooooooooong');

        var r9 = dp.req(_el('#' + r8_id));

        setTimeout(function() {
            dp_assert(r9.find('._msg').text() == _el('#' + r9_id + ' input[name="name"]').attr('dp-req-invalid'), 'helper-req-field-too-long');
            dp_jqlib(r9.find('button').get(0)).trigger('click');

            _el('#' + r9_id).remove();
        }, a_done);

        // dp.alert

        setTimeout(function() {
            var a1 = dp.alert('text message', 'Okay');

            setTimeout(function () {
                dp_assert(a1.length > 0, 'helper-alert-msg-confirm');
                dp_jqlib(a1.find('button').get(0)).trigger('click');
            }, a_done);
        }, 10);

        setTimeout(function() {
            var a2_done = false;
            var a2 = dp.alert('text message\nwith confirm delegate', function() { a2_done = true; });

            setTimeout(function() {
                dp_jqlib(a2.find('button').get(0)).trigger('click');

                setTimeout(function() {
                    dp_assert(a2_done, 'helper-alert-msg-cf-delegate!');
                }, an_done);
            }, a_done);
        }, a_wait);

        setTimeout(function() {
            var a3_done = false;
            var a3 = dp.alert('text message with\nconfirm and dismiss delegate', function() { a3_done = false; }, function() { a3_done = true; });

            setTimeout(function() {
                dp_jqlib(a3.find('button').get(1)).trigger('click');

                setTimeout(function() {
                    dp_assert(a3_done, 'helper-alert-msg-cf-delegate-ds-delegate');
                }, an_done);
            }, a_done);
        }, a_wait * 2);

        setTimeout(function() {
            var a4_done = false;
            var a4 = dp.alert('text message with\nconfirm text and delegate,\ndismiss delegate', function() { a4_done = true; }, 'Okay', function() { a4_done = false; });

            setTimeout(function() {
                a4.find('button').each(function(i, e) {
                    if (dp_jqlib(e).text() == 'Okay') {
                        dp_jqlib(e).trigger('click');
                        return false;
                    }
                });

                setTimeout(function() {
                    dp_assert(a4_done, 'helper-alert-msg-cf-text-delegate-ds-delegate');
                }, an_done);
            }, a_done);
        }, a_wait * 3);

        setTimeout(function() {
            var a5_done = false;
            var a5 = dp.alert('text message with\nconfirm text and delegate,\ndismiss text and delegate', function() { a5_done = false; }, 'Okay', function() { a5_done = true; }, 'Dismiss');

            setTimeout(function() {
                a5.find('button').each(function(i, e) {
                    if (dp_jqlib(e).text() == 'Dismiss') {
                        dp_jqlib(e).trigger('click');
                        return false;
                    }
                });

                setTimeout(function() {
                    dp_assert(a5_done, 'helper-alert-msg-cf-text-delegate-ds-text-delegate');
                }, an_done);
            }, a_done);
        }, a_wait * 4);

        setTimeout(function() {
            var a6_done = false;
            var a6 = dp.alert({
                'message': 'html message <b>this is bold</b>',
                'html': true,
                'buttons': [
                    ['button 1', function() {
                        a6_done = false;
                    }],
                    ['button 2', function() {
                        a6_done = true;
                    }],
                    ['button 3', function() {
                        a6_done = false;
                    }]
                ]
            });

            setTimeout(function() {
                a6.find('button').each(function(i, e) {
                    if (dp_jqlib(e).text() == 'button 2') {
                        dp_jqlib(e).trigger('click');
                        return false;
                    }
                });

                setTimeout(function() {
                    dp_assert(a6_done, 'helper-alert-custom');
                }, an_done);
            }, a_done);
        }, a_wait * 5);

        dp_assert(
            function() {
                return dp.test.ui.element.input.delegate.on_focus_called;
            },
            'test-ui-element-input-delegate-on-focus',
            function() {
                _el('#input-test').focus();
            },
            wait
        );

        dp_assert(
            function() {
                return dp.test.ui.element.input.delegate.on_return_called;
            },
            'test-ui-element-input-delegate-on-return',
            function() {
                var e = dp_jqlib.Event('keypress');
                e.keyCode = 13;

                _el('#input-test').trigger(e);
            },
            wait
        );

        setTimeout(function() {
            dp_assert(!dp.test.failed, 'all-test-cases');

            if (!dp.test.failed) {
                dp_jqlib('<h3 />').attr('id', 'result-message').text('succeed').appendTo('body');
            }
        }, wait * 500);
    },
    ui: {
        element: {
            input: {
                delegate: {
                    on_return_called: false,
                    on_return: function() {
                        dp.test.ui.element.input.delegate.on_return_called = true;
                        console.log('* dp.test.ui.element.input.delegate.on_return called.');
                    },
                    on_focus_called: false,
                    on_focus: function() {
                        dp.test.ui.element.input.delegate.on_focus_called = true;
                        console.log('* dp.test.ui.element.input.delegate.on_focus called.');
                    }
                }
            }
        }
    }
};

var dp_assert = function(eq, identifier, before, delay) {
    if (before) {
        before();
    }

    if (delay) {
        setTimeout(function() {
            dp_assert(eq, identifier);
        }, delay);
        return;
    }

    if (typeof eq == 'function') {
        eq = eq();
    }

    if (!eq) {
        if (dp.test.failed) return;

        console.log('* Assertion Failed, ' + identifier);
        dp_jqlib('body').append(dp_jqlib('<p />').addClass('assert').addClass('fail').text('* Assertion Failed, ' + identifier));
        dp.test.failed = true;

        throw new Error('* Assertion Failed, ' + identifier);
    }
    else {
        console.log('* Assertion Succeed, ' + identifier);
        dp_jqlib('body').append(dp_jqlib('<p />').addClass('assert').addClass('succ').text('* Assertion Succeed, ' + identifier));
    }
};

dp_init(function() {
    dp.test.init();
});<commit_msg>add unittest.<commit_after>if (!dp) var dp = {};

dp.test = {
    failed: false,
    init: function() {
        var wait = 10;

        dp_assert(function() {
            return _el('#input-test').length;
        }, 'test-el');

        dp_assert(dp.helper.string.uniqid(), 'test-uniqid');
        dp_assert(dp.helper.string.uniqid('prefix_'), 'test-uniqid-with-prefix');
        dp_assert(dp.helper.string.uniqid('prefix_', true), 'test-uniqid-with-entropy');
        dp_assert(dp.helper.string.uniqid('prefix_', true, '-'), 'test-uniqid-with-entropy-separator');

        var temp_prefix = dp.vars.prefix;

        dp.vars.prefix = '/front';

        dp_assert(dp.helper.prefixize('/front') === '/', 'helper-prefixize-global-prefix');
        dp_assert(dp.helper.prefixize('/front/') === '/', 'helper-prefixize-global-prefix');
        dp_assert(dp.helper.prefixize('/front/foo/bar') === '/foo/bar', 'helper-prefixize-global-prefix');

        dp.vars.prefix = undefined;

        dp_assert(dp.helper.prefixize('/front/foo/bar') === '/front/foo/bar', 'helper-prefixize-no-prefix');
        dp_assert(dp.helper.prefixize('/front/foo/bar', '/front') === '/foo/bar', 'helper-prefixize-with-prefix');
        dp_assert(dp.helper.prefixize('/front/foo/bar', '/front/') === '/foo/bar', 'helper-prefixize-with-prefix-slash');
        dp_assert(dp.helper.prefixize('/front', '/front') === '/', 'helper-prefixize-with-prefix');
        dp_assert(dp.helper.prefixize('/front', '/front/') === '/', 'helper-prefixize-with-prefix-slash');

        dp.vars.prefix = temp_prefix;

        dp_assert(dp.helper.validator.email('email@valid.com'), 'helper-validator-email');
        dp_assert(dp.helper.validator.email('email@.invalid.com') == false, 'helper-validator-email');

        dp_assert(dp.helper.validator.url('http://www.google.com'), 'helper-validator-url');
        dp_assert(dp.helper.validator.url('http://www.google'), 'helper-validator-url');
        dp_assert(dp.helper.validator.url('http://123.123.123.123'), 'helper-validator-url');
        dp_assert(dp.helper.validator.url('http://123.123.123.256') == false, 'helper-validator-url');
        dp_assert(dp.helper.validator.url('https://www.google.') == false, 'helper-validator-url');

        dp_assert(dp.helper.string.replaceAll('abcd', 'a', '-') === '-bcd', 'helper-string-replaceAll');

        var a_wait = 280;
        var a_done = 550;
        var an_done = 700;

        // dp.req

        var r1 = dp.req(_el('#req-test-case-1'), {
            'before': function() {
                return false;
            }
        });

        dp_assert(r1 == false, 'helper-req-before-false');

        //

        _el('#req-test-case-1 input[name="email"]').val('');

        var r2 = dp.req(_el('#req-test-case-1'));

        setTimeout(function() {
            dp_assert(r2.find('._msg').text() == _el('#req-test-case-1 input[name="email"]').attr('dp-req-missing'), 'helper-req-field-missing');
            dp_jqlib(r2.find('button').get(0)).trigger('click');
        }, a_done);

        //

        _el('#req-test-case-1 input[name="email"]').val('invalid@email@address.com');

        var r3 = dp.req(_el('#req-test-case-1'));

        setTimeout(function() {
            dp_assert(r3.find('._msg').text() == _el('#req-test-case-1 input[name="email"]').attr('dp-req-invalid'), 'helper-req-field-invalid');
            dp_jqlib(r3.find('button').get(0)).trigger('click');
        }, a_done);

        //

        _el('#req-test-case-1 input[name="email"]').val('john@email.com');

        var r4 = dp.req(_el('#req-test-case-1'), {
            success: function(data) {
                dp_assert(data.result, 'helper-req-field-confirm-response-success');
            },
            error: function() {
                dp_assert(false, 'helper-req-field-confirm-response-error');
            }
        });

        setTimeout(function() {
            dp_assert(r4.find('._msg').text() == _el('#req-test-case-1 button').attr('dp-req-confirm'), 'helper-req-field-confirm');
            dp_jqlib(r4.find('button').get(0)).trigger('click');
        }, a_done);

        //

        var r5 = dp.req(_el('#req-test-case-1'));

        dp_assert(r5 == false, 'helper-req-no-multiple');

        //

        _el('#req-test-case-1 button').attr('dp-req-multiple', 'yes');

        var r6 = dp.req(_el('#req-test-case-1'));
        var r7 = dp.req(_el('#req-test-case-1'));

        setTimeout(function() {
            dp_assert(r6.find('._msg').text() == _el('#req-test-case-1 button').attr('dp-req-confirm'), 'helper-req-multiple-first');
            dp_jqlib(r6.find('button').get(1)).trigger('click');
        }, a_done);

        setTimeout(function() {
            dp_assert(r7.find('._msg').text() == _el('#req-test-case-1 button').attr('dp-req-confirm'), 'helper-req-multiple-second');
            dp_jqlib(r7.find('button').get(1)).trigger('click');
        }, a_done);

        //

        var r8_id = dp.helper.string.uniqid();
        _el('#req-test-case-1').clone().attr('id', r8_id).appendTo(_el('body'));
        _el('#' + r8_id + ' input[name="name"]').val('short');

        var r8 = dp.req(_el('#' + r8_id));

        setTimeout(function() {
            dp_assert(r8.find('._msg').text() == _el('#' + r8_id + ' input[name="name"]').attr('dp-req-invalid'), 'helper-req-field-too-short');
            dp_jqlib(r8.find('button').get(0)).trigger('click');

            _el('#' + r8_id).remove();
        }, a_done);

        //

        var r9_id = dp.helper.string.uniqid();
        _el('#req-test-case-1').clone().attr('id', r9_id).appendTo(_el('body'));
        _el('#' + r9_id + ' input[name="name"]').val('too loooooooooooooooooong');

        var r9 = dp.req(_el('#' + r8_id));

        setTimeout(function() {
            dp_assert(r9.find('._msg').text() == _el('#' + r9_id + ' input[name="name"]').attr('dp-req-invalid'), 'helper-req-field-too-long');
            dp_jqlib(r9.find('button').get(0)).trigger('click');

            _el('#' + r9_id).remove();
        }, a_done);

        // dp.alert

        setTimeout(function() {
            var a1 = dp.alert('text message', 'Okay');

            setTimeout(function () {
                dp_assert(a1.length > 0, 'helper-alert-msg-confirm');
                dp_jqlib(a1.find('button').get(0)).trigger('click');
            }, a_done);
        }, 10);

        setTimeout(function() {
            var a2_done = false;
            var a2 = dp.alert('text message\nwith confirm delegate', function() { a2_done = true; });

            setTimeout(function() {
                dp_jqlib(a2.find('button').get(0)).trigger('click');

                setTimeout(function() {
                    dp_assert(a2_done, 'helper-alert-msg-cf-delegate!');
                }, an_done);
            }, a_done);
        }, a_wait);

        setTimeout(function() {
            var a3_done = false;
            var a3 = dp.alert('text message with\nconfirm and dismiss delegate', function() { a3_done = false; }, function() { a3_done = true; });

            setTimeout(function() {
                dp_jqlib(a3.find('button').get(1)).trigger('click');

                setTimeout(function() {
                    dp_assert(a3_done, 'helper-alert-msg-cf-delegate-ds-delegate');
                }, an_done);
            }, a_done);
        }, a_wait * 2);

        setTimeout(function() {
            var a4_done = false;
            var a4 = dp.alert('text message with\nconfirm text and delegate,\ndismiss delegate', function() { a4_done = true; }, 'Okay', function() { a4_done = false; });

            setTimeout(function() {
                a4.find('button').each(function(i, e) {
                    if (dp_jqlib(e).text() == 'Okay') {
                        dp_jqlib(e).trigger('click');
                        return false;
                    }
                });

                setTimeout(function() {
                    dp_assert(a4_done, 'helper-alert-msg-cf-text-delegate-ds-delegate');
                }, an_done);
            }, a_done);
        }, a_wait * 3);

        setTimeout(function() {
            var a5_done = false;
            var a5 = dp.alert('text message with\nconfirm text and delegate,\ndismiss text and delegate', function() { a5_done = false; }, 'Okay', function() { a5_done = true; }, 'Dismiss');

            setTimeout(function() {
                a5.find('button').each(function(i, e) {
                    if (dp_jqlib(e).text() == 'Dismiss') {
                        dp_jqlib(e).trigger('click');
                        return false;
                    }
                });

                setTimeout(function() {
                    dp_assert(a5_done, 'helper-alert-msg-cf-text-delegate-ds-text-delegate');
                }, an_done);
            }, a_done);
        }, a_wait * 4);

        setTimeout(function() {
            var a6_done = false;
            var a6 = dp.alert({
                'message': 'html message <b>this is bold</b>',
                'html': true,
                'buttons': [
                    ['button 1', function() {
                        a6_done = false;
                    }],
                    ['button 2', function() {
                        a6_done = true;
                    }],
                    ['button 3', function() {
                        a6_done = false;
                    }]
                ]
            });

            setTimeout(function() {
                a6.find('button').each(function(i, e) {
                    if (dp_jqlib(e).text() == 'button 2') {
                        dp_jqlib(e).trigger('click');
                        return false;
                    }
                });

                setTimeout(function() {
                    dp_assert(a6_done, 'helper-alert-custom');
                }, an_done);
            }, a_done);
        }, a_wait * 5);

        dp_assert(
            function() {
                return dp.test.ui.element.input.delegate.on_focus_called;
            },
            'test-ui-element-input-delegate-on-focus',
            function() {
                _el('#input-test').focus();
            },
            wait
        );

        dp_assert(
            function() {
                return dp.test.ui.element.input.delegate.on_focusout_called;
            },
            'test-ui-element-input-delegate-on-focusout',
            function() {
                _el('#input-test').focus();
                _el('#input-test-2').focus();
            },
            wait
        );

        dp_assert(
            function() {
                return dp.test.ui.element.input.delegate.on_return_called;
            },
            'test-ui-element-input-delegate-on-return',
            function() {
                var e = dp_jqlib.Event('keypress');
                e.keyCode = 13;

                _el('#input-test').trigger(e);
            },
            wait
        );

        dp_assert(
            function() {
                return dp.test.ui.element.input.delegate.on_keydown_called;
            },
            'test-ui-element-input-delegate-on-keydown',
            function() {
                var e = dp_jqlib.Event('keydown');
                e.keyCode = 65;

                _el('#input-test').trigger(e);
            },
            wait
        );

        setTimeout(function() {
            dp_assert(!dp.test.failed, 'all-test-cases');

            if (!dp.test.failed) {
                dp_jqlib('<h3 />').attr('id', 'result-message').text('succeed').appendTo('body');
            }
        }, wait * 500);
    },
    ui: {
        element: {
            input: {
                delegate: {
                    on_return_called: false,
                    on_return: function() {
                        dp.test.ui.element.input.delegate.on_return_called = true;
                        console.log('* dp.test.ui.element.input.delegate.on_return called.');
                    },
                    on_focus_called: false,
                    on_focus: function() {
                        dp.test.ui.element.input.delegate.on_focus_called = true;
                        console.log('* dp.test.ui.element.input.delegate.on_focus called.');
                    },
                    on_focusout_called: false,
                    on_focusout: function() {
                        dp.test.ui.element.input.delegate.on_focusout_called = true;
                        console.log('* dp.test.ui.element.input.delegate.on_focusout called.');
                    },
                    on_keydown_called: false,
                    on_keydown: function() {
                        dp.test.ui.element.input.delegate.on_keydown_called = true;
                        console.log('* dp.test.ui.element.input.delegate.on_keydown called.');
                    }
                }
            }
        }
    }
};

var dp_assert = function(eq, identifier, before, delay) {
    if (before) {
        before();
    }

    if (delay) {
        setTimeout(function() {
            dp_assert(eq, identifier);
        }, delay);
        return;
    }

    if (typeof eq == 'function') {
        eq = eq();
    }

    if (!eq) {
        if (dp.test.failed) return;

        console.log('* Assertion Failed, ' + identifier);
        dp_jqlib('body').append(dp_jqlib('<p />').addClass('assert').addClass('fail').text('* Assertion Failed, ' + identifier));
        dp.test.failed = true;

        throw new Error('* Assertion Failed, ' + identifier);
    }
    else {
        console.log('* Assertion Succeed, ' + identifier);
        dp_jqlib('body').append(dp_jqlib('<p />').addClass('assert').addClass('succ').text('* Assertion Succeed, ' + identifier));
    }
};

dp_init(function() {
    dp.test.init();
});
<|endoftext|>