<commit_before>var events = require('events'),
    path = require('path');

var vows = require('../vows');
var Context = require('../vows/context').Context;

this.Suite = function (subject) {
    this.subject = subject;
    this.matcher = /.*/;
    this.reporter = require('./reporters/dot-matrix');
    this.batches = [];
    this.options = { error: true };
    this.reset();
};

this.Suite.prototype = new(function () {
    this.reset = function () {
        this.results = {
            honored: 0,
            broken:  0,
            errored: 0,
            pending: 0,
            total:   0,
            time:  null
        };
        this.batches.forEach(function (b) {
            b.lastContext = null;
            b.remaining = b._remaining;
            b.honored = b.broken = b.errored = b.total = b.pending = 0;
            b.vows.forEach(function (vow) { vow.status = null });
            b.teardowns = [];
        });
    };

    this.addBatch = function (tests) {
        this.batches.push({
            tests: tests,
            suite:  this,
            vows:     [],
            remaining: 0,
           _remaining: 0,
            honored:   0,
            broken:    0,
            errored:   0,
            pending:   0,
            total:     0,
            teardowns: []
        });
        return this;
    };
    this.addVows = this.addBatch;

    this.parseBatch = function (batch, matcher) {
        var tests = batch.tests;

        if ('topic' in tests) {
            throw new(Error)("missing top-level context.");
        }
        // Count the number of vows/promises expected to fire,
        // so we know when the tests are over.
        // We match the keys against `matcher`, to decide
        // whether or not they should be included in the test.
        // Any key, including assertion function keys can be matched.
        // If a child matches, then the n parent topics must not be skipped.
        (function count(tests, _match) {
            var match = false;

            var keys = Object.keys(tests).filter(function (k) {
                return k !== 'topic' && k !== 'teardown';
            });

            for (var i = 0, key; i < keys.length; i++) {
                key = keys[i];

                // If the parent node, or this one matches.
                match = _match || matcher.test(key);

                if (typeof(tests[key]) === 'object') {
                    match = count(tests[key], match);
                } else {
                    if (typeof(tests[key]) === 'string') {
                        tests[key] = new(String)(tests[key]);
                    }
                    if (! match) {
                        tests[key]._skip = true;
                    }
                }
            }

            // If any of the children matched,
            // don't skip this node.
            for (var i = 0; i < keys.length; i++) {
                if (! tests[keys[i]]._skip) { match = true }
            }

            if (match) { batch.remaining ++ }
            else       { tests._skip = true }

            return match;
        })(tests, false);

        batch._remaining = batch.remaining;
    };

    this.runBatch = function (batch) {
        var topic,
            tests   = batch.tests,
            promise = batch.promise = new(events.EventEmitter);

        var that = this;

        batch.status = 'begin';

        // The test runner, it calls itself recursively, passing the
        // previous context to the inner contexts. This is so the `topic`
        // functions have access to all the previous context topics in their
        // arguments list.
        // It is defined and invoked at the same time.
        // If it encounters a `topic` function, it waits for the returned
        // promise to emit (the topic), at which point it runs the functions under it,
        // passing the topic as an argument.
        (function run(ctx, lastTopic) {
            var old = false;
            topic = ctx.tests.topic;

            if (typeof(topic) === 'function') {
                if (ctx.isEvent || ctx.name === 'on') {
                    throw new Error('Event context cannot contain a topic');
                }

                // Run the topic, passing the previous context topics
                // If topic `throw`s an exception, pass it down as a value
                try {
                    topic = topic.apply(ctx.env, ctx.topics);
                }
                catch (ex) {
                    if(/ReferenceError/.test(ex)) throw ex;
                    topic = ex;
                }

                if (typeof(topic) === 'undefined') { ctx._callback = true }
            }

            // If this context has a topic, store it in `lastTopic`,
            // if not, use the last topic, passed down by a parent
            // context.
            if (typeof(topic) !== 'undefined' || ctx._callback) {
                lastTopic = topic;
            } else {
                old   = true;
                topic = lastTopic;
            }

            // If the topic doesn't return an event emitter (such as a promise),
            // we create it ourselves, and emit the value on the next tick.
            if (! (topic &&
                   topic.constructor === events.EventEmitter)) {
                // If the context is a traditional vow, then a topic can ONLY
                // be an EventEmitter.  However if the context is a sub-event
                // then the topic may be an instanceof EventEmitter
                if (!ctx.isEvent ||
                   (ctx.isEvent && !(topic instanceof events.EventEmitter))) {

                      ctx.emitter = new(events.EventEmitter);

                      if (! ctx._callback) {
                          process.nextTick(function (val) {
                              return function () {
                                ctx.emitter.emit("success", val)
                              };
                          }(topic));
                      }
                      // if I have a callback, push the new topic back up to
                      // lastTopic
                      if (ctx._callback) {
                          lastTopic = topic = ctx.emitter;
                      } else {
                          topic = ctx.emitter;
                      }
                }
            }

            topic.on(ctx.event, function (val) {
                // Once the topic fires, add the return value
                // to the beginning of the topics list, so it
                // becomes the first argument for the next topic.
                // If we're using the parent topic, no need to
                // prepend it to the topics list, or we'll get
                // duplicates.
                if (!old || ctx.isEvent) {
                    Array.prototype.unshift.apply(ctx.topics, arguments)
                };
            });
            if (topic.setMaxListeners) { topic.setMaxListeners(Infinity) }
            // Now run the tests, or sub-contexts
            Object.keys(ctx.tests).filter(function (k) {
                return ctx.tests[k] && k !== 'topic'    &&
                                       k !== 'teardown' && !ctx.tests[k]._skip;
            }).forEach(function (item) {
                // Create a new evaluation context,
                // inheriting from the parent one.
                var env = Object.create(ctx.env);
                env.suite = that;

                // Holds the current test or context
                var vow = Object.create({
                    callback: ctx.tests[item],
                    context: ctx.title,
                    description: item,
                    binding: ctx.env,
                    status: null,
                    batch: batch
                });

                // If we encounter a function, add it to the callbacks
                // of the `topic` function, so it'll get called once the
                // topic fires.
                // If we encounter an object literal, we recurse, sending it
                // our current context.
                if ((typeof(vow.callback) === 'function') ||
                    (vow.callback instanceof String)) {
                    topic.addVow(vow);
                } else if (typeof(vow.callback) === 'object') {
                    // If there's a setup stage, we have to wait for it to fire,
                    // before calling the inner context.
                    // If the event has already fired, the context is 'on' or
                    // there is no setup stage, just run the inner context
                    // synchronously.
                    if (topic &&
                        ctx.name !== 'on' &&
                        !topic._vowsEmitedEvents.hasOwnProperty(ctx.event)) {
                        topic.on(ctx.event, function (ctx) {
                            return function (val) {
                                return run(new(Context)(vow, ctx, env), lastTopic);
                            };
                        }(ctx));
                    } else {
                        run(new(Context)(vow, ctx, env), lastTopic);
                    }
                }
            });
            // Teardown
            if (ctx.tests.teardown) {
                batch.teardowns.push(ctx);
            }
            if (! ctx.tests._skip) {
                batch.remaining --;
            }
            // Check if we're done running the tests
            exports.tryEnd(batch);
        // This is our initial, empty context
        })(new(Context)({ callback: tests, context: null, description: null }, {}));
        return promise;
    };

    this.report = function () {
        return this.reporter.report.apply(this.reporter, arguments);
    };

    this.run = function (options, callback) {
        var that = this, start;

        options = options || {};

        Object.keys(options).forEach(function (k) {
            that.options[k] = options[k];
        });

        this.matcher  = this.options.matcher  || this.matcher;
        this.reporter = this.options.reporter || this.reporter;

        this.batches.forEach(function (batch) {
            that.parseBatch(batch, that.matcher);
        });

        this.reset();

        start = new(Date);

        if (this.batches.filter(function (b) { return b.remaining > 0 }).length) {
            this.report(['subject', this.subject]);
        }

        return (function run(batches) {
            var batch = batches.shift();

            if (batch) {
                // If the batch has no vows to run,
                // go to the next one.
                if (batch.remaining === 0) {
                    run(batches);
                } else {
                    that.runBatch(batch).on('end', function () {
                        run(batches);
                    });
                }
            } else {
                that.results.time = (new(Date) - start) / 1000;
                that.report(['finish', that.results]);

                if (callback) { callback(that.results) }

                if (that.results.honored + that.results.pending === that.results.total) {
                    return 0;
                } else {
                    return 1;
                }
            }
        })(this.batches.slice(0));
    };

    this.runParallel = function () {};

    this.export = function (module, options) {
        var that = this;

        Object.keys(options || {}).forEach(function (k) {
            that.options[k] = options[k];
        });

        if (require.main === module) {
            return this.run();
        } else {
            return module.exports[this.subject] = this;
        }
    };
    this.exportTo = function (module, options) { // Alias, for JSLint
        return this.export(module, options);
    };
});

//
// Checks if all the tests in the batch have been run,
// and triggers the next batch (if any), by emitting the 'end' event.
//
this.tryEnd = function (batch) {
    var result, style, time;

    if (batch.honored + batch.broken + batch.errored + batch.pending === batch.total &&
        batch.remaining === 0) {

        Object.keys(batch).forEach(function (k) {
            (k in batch.suite.results) && (batch.suite.results[k] += batch[k]);
        });

        if (batch.teardowns) {
            for (var i = batch.teardowns.length - 1, ctx; i >= 0; i--) {
                runTeardown(batch.teardowns[i]);
            }

            maybeFinish();
        }

        function runTeardown(teardown) {
            var env = Object.create(teardown.env);

            Object.defineProperty(env, "callback", {
                get: function () {
                    teardown.awaitingCallback = true;

                    return function () {
                        teardown.awaitingCallback = false;
                        maybeFinish();
                    };
                }
            });

            teardown.tests.teardown.apply(env, teardown.topics);
        }

        function maybeFinish() {
            var pending = batch.teardowns.filter(function (teardown) {
                return teardown.awaitingCallback;
            });

            if (pending.length === 0) {
                finish();
            }
        }

        function finish() {
            batch.status = 'end';
            batch.suite.report(['end']);
            batch.promise.emit('end', batch.honored, batch.broken, batch.errored, batch.pending);
        }
    }
};
<commit_msg>[fix] Fix crashes on node v0.9.3<commit_after>var events = require('events'),
    path = require('path');

var vows = require('../vows');
var Context = require('../vows/context').Context;

this.Suite = function (subject) {
    this.subject = subject;
    this.matcher = /.*/;
    this.reporter = require('./reporters/dot-matrix');
    this.batches = [];
    this.options = { error: true };
    this.reset();
};

this.Suite.prototype = new(function () {
    this.reset = function () {
        this.results = {
            honored: 0,
            broken:  0,
            errored: 0,
            pending: 0,
            total:   0,
            time:  null
        };
        this.batches.forEach(function (b) {
            b.lastContext = null;
            b.remaining = b._remaining;
            b.honored = b.broken = b.errored = b.total = b.pending = 0;
            b.vows.forEach(function (vow) { vow.status = null });
            b.teardowns = [];
        });
    };

    this.addBatch = function (tests) {
        this.batches.push({
            tests: tests,
            suite:  this,
            vows:     [],
            remaining: 0,
           _remaining: 0,
            honored:   0,
            broken:    0,
            errored:   0,
            pending:   0,
            total:     0,
            teardowns: []
        });
        return this;
    };
    this.addVows = this.addBatch;

    this.parseBatch = function (batch, matcher) {
        var tests = batch.tests;

        if ('topic' in tests) {
            throw new(Error)("missing top-level context.");
        }
        // Count the number of vows/promises expected to fire,
        // so we know when the tests are over.
        // We match the keys against `matcher`, to decide
        // whether or not they should be included in the test.
        // Any key, including assertion function keys can be matched.
        // If a child matches, then the n parent topics must not be skipped.
        (function count(tests, _match) {
            var match = false;

            var keys = Object.keys(tests).filter(function (k) {
                return k !== 'topic' && k !== 'teardown';
            });

            for (var i = 0, key; i < keys.length; i++) {
                key = keys[i];

                // If the parent node, or this one matches.
                match = _match || matcher.test(key);

                if (typeof(tests[key]) === 'object') {
                    match = count(tests[key], match);
                } else {
                    if (typeof(tests[key]) === 'string') {
                        tests[key] = new(String)(tests[key]);
                    }
                    if (! match) {
                        tests[key]._skip = true;
                    }
                }
            }

            // If any of the children matched,
            // don't skip this node.
            for (var i = 0; i < keys.length; i++) {
                if (! tests[keys[i]]._skip) { match = true }
            }

            if (match) { batch.remaining ++ }
            else       { tests._skip = true }

            return match;
        })(tests, false);

        batch._remaining = batch.remaining;
    };

    this.runBatch = function (batch) {
        var topic,
            tests   = batch.tests,
            promise = batch.promise = new(events.EventEmitter);

        var that = this;

        batch.status = 'begin';

        // The test runner, it calls itself recursively, passing the
        // previous context to the inner contexts. This is so the `topic`
        // functions have access to all the previous context topics in their
        // arguments list.
        // It is defined and invoked at the same time.
        // If it encounters a `topic` function, it waits for the returned
        // promise to emit (the topic), at which point it runs the functions under it,
        // passing the topic as an argument.
        (function run(ctx, lastTopic) {
            var old = false;
            topic = ctx.tests.topic;

            if (typeof(topic) === 'function') {
                if (ctx.isEvent || ctx.name === 'on') {
                    throw new Error('Event context cannot contain a topic');
                }

                // Run the topic, passing the previous context topics
                // If topic `throw`s an exception, pass it down as a value
                try {
                    topic = topic.apply(ctx.env, ctx.topics);
                }
                catch (ex) {
                    if(/ReferenceError/.test(ex)) throw ex;
                    topic = ex;
                }

                if (typeof(topic) === 'undefined') { ctx._callback = true }
            }

            // If this context has a topic, store it in `lastTopic`,
            // if not, use the last topic, passed down by a parent
            // context.
            if (typeof(topic) !== 'undefined' || ctx._callback) {
                lastTopic = topic;
            } else {
                old   = true;
                topic = lastTopic;
            }

            // If the topic doesn't return an event emitter (such as a promise),
            // we create it ourselves, and emit the value on the next tick.
            if (! (topic &&
                   topic.constructor === events.EventEmitter)) {
                // If the context is a traditional vow, then a topic can ONLY
                // be an EventEmitter.  However if the context is a sub-event
                // then the topic may be an instanceof EventEmitter
                if (!ctx.isEvent ||
                   (ctx.isEvent && !(topic instanceof events.EventEmitter))) {

                      ctx.emitter = new(events.EventEmitter);

                      if (! ctx._callback) {
                          process.nextTick(function (val) {
                              return function () {
                                ctx.emitter.emit("success", val)
                              };
                          }(topic));
                      }
                      // if I have a callback, push the new topic back up to
                      // lastTopic
                      if (ctx._callback) {
                          lastTopic = topic = ctx.emitter;
                      } else {
                          topic = ctx.emitter;
                      }
                }
            }

            topic.on(ctx.event, function (val) {
                // Once the topic fires, add the return value
                // to the beginning of the topics list, so it
                // becomes the first argument for the next topic.
                // If we're using the parent topic, no need to
                // prepend it to the topics list, or we'll get
                // duplicates.
                if (!old || ctx.isEvent) {
                    Array.prototype.unshift.apply(ctx.topics, arguments)
                };
            });
            if (topic.setMaxListeners) { topic.setMaxListeners(Infinity) }
            // Now run the tests, or sub-contexts
            Object.keys(ctx.tests).filter(function (k) {
                return ctx.tests[k] && k !== 'topic'    &&
                                       k !== 'teardown' && !ctx.tests[k]._skip;
            }).forEach(function (item) {
                // Create a new evaluation context,
                // inheriting from the parent one.
                var env = Object.create(ctx.env);
                env.suite = that;

                // Holds the current test or context
                var vow = Object.create({
                    callback: ctx.tests[item],
                    context: ctx.title,
                    description: item,
                    binding: ctx.env,
                    status: null,
                    batch: batch
                });

                // If we encounter a function, add it to the callbacks
                // of the `topic` function, so it'll get called once the
                // topic fires.
                // If we encounter an object literal, we recurse, sending it
                // our current context.
                if ((typeof(vow.callback) === 'function') ||
                    (vow.callback instanceof String)) {
                    topic.addVow(vow);
                } else if (typeof(vow.callback) === 'object') {
                    // If there's a setup stage, we have to wait for it to fire,
                    // before calling the inner context.
                    // If the event has already fired, the context is 'on' or
                    // there is no setup stage, just run the inner context
                    // synchronously.
                    if (topic &&
                        ctx.name !== 'on' &&
                        (!topic._vowsEmitedEvents || !topic._vowsEmitedEvents.hasOwnProperty(ctx.event))) {
                        topic.on(ctx.event, function (ctx) {
                            return function (val) {
                                return run(new(Context)(vow, ctx, env), lastTopic);
                            };
                        }(ctx));
                    } else {
                        run(new(Context)(vow, ctx, env), lastTopic);
                    }
                }
            });
            // Teardown
            if (ctx.tests.teardown) {
                batch.teardowns.push(ctx);
            }
            if (! ctx.tests._skip) {
                batch.remaining --;
            }
            // Check if we're done running the tests
            exports.tryEnd(batch);
        // This is our initial, empty context
        })(new(Context)({ callback: tests, context: null, description: null }, {}));
        return promise;
    };

    this.report = function () {
        return this.reporter.report.apply(this.reporter, arguments);
    };

    this.run = function (options, callback) {
        var that = this, start;

        options = options || {};

        Object.keys(options).forEach(function (k) {
            that.options[k] = options[k];
        });

        this.matcher  = this.options.matcher  || this.matcher;
        this.reporter = this.options.reporter || this.reporter;

        this.batches.forEach(function (batch) {
            that.parseBatch(batch, that.matcher);
        });

        this.reset();

        start = new(Date);

        if (this.batches.filter(function (b) { return b.remaining > 0 }).length) {
            this.report(['subject', this.subject]);
        }

        return (function run(batches) {
            var batch = batches.shift();

            if (batch) {
                // If the batch has no vows to run,
                // go to the next one.
                if (batch.remaining === 0) {
                    run(batches);
                } else {
                    that.runBatch(batch).on('end', function () {
                        run(batches);
                    });
                }
            } else {
                that.results.time = (new(Date) - start) / 1000;
                that.report(['finish', that.results]);

                if (callback) { callback(that.results) }

                if (that.results.honored + that.results.pending === that.results.total) {
                    return 0;
                } else {
                    return 1;
                }
            }
        })(this.batches.slice(0));
    };

    this.runParallel = function () {};

    this.export = function (module, options) {
        var that = this;

        Object.keys(options || {}).forEach(function (k) {
            that.options[k] = options[k];
        });

        if (require.main === module) {
            return this.run();
        } else {
            return module.exports[this.subject] = this;
        }
    };
    this.exportTo = function (module, options) { // Alias, for JSLint
        return this.export(module, options);
    };
});

//
// Checks if all the tests in the batch have been run,
// and triggers the next batch (if any), by emitting the 'end' event.
//
this.tryEnd = function (batch) {
    var result, style, time;

    if (batch.honored + batch.broken + batch.errored + batch.pending === batch.total &&
        batch.remaining === 0) {

        Object.keys(batch).forEach(function (k) {
            (k in batch.suite.results) && (batch.suite.results[k] += batch[k]);
        });

        if (batch.teardowns) {
            for (var i = batch.teardowns.length - 1, ctx; i >= 0; i--) {
                runTeardown(batch.teardowns[i]);
            }

            maybeFinish();
        }

        function runTeardown(teardown) {
            var env = Object.create(teardown.env);

            Object.defineProperty(env, "callback", {
                get: function () {
                    teardown.awaitingCallback = true;

                    return function () {
                        teardown.awaitingCallback = false;
                        maybeFinish();
                    };
                }
            });

            teardown.tests.teardown.apply(env, teardown.topics);
        }

        function maybeFinish() {
            var pending = batch.teardowns.filter(function (teardown) {
                return teardown.awaitingCallback;
            });

            if (pending.length === 0) {
                finish();
            }
        }

        function finish() {
            batch.status = 'end';
            batch.suite.report(['end']);
            batch.promise.emit('end', batch.honored, batch.broken, batch.errored, batch.pending);
        }
    }
};
<|endoftext|>


<commit_before>import React, { PropTypes as PT } from 'react'
import { connect } from 'react-redux'
import { actions as issuesActions } from '../../redux/modules/IssuesActions'
import Icons from '../../components/Icons'
import { Link } from 'react-router'
// import styles from './IssuesListView.scss'

class NoIssues extends React.Component {
  render() {
    return (

Hey, there are no issues yet. You can <Link to='/issues/new'>create one</Link> right now!

    )
  }
}

class Issues extends React.Component {
  static propTypes = {
    issues: PT.any
  };

  render () {
    var children = this.props.issues.map((issue, idx) => {
      return (

              <Link to={'/issues/' + issue.id}>{issue.summary}</Link>

            {issue.description}

        )
    })
    return (

            {children}

)
  }
}

// We define mapStateToProps where we'd normally use
// the @connect decorator so the data requirements are clear upfront, but then
// export the decorated component after the main class definition so
// the component can be tested w/ and w/o being connected.
// See: http://rackt.github.io/redux/docs/recipes/WritingTests.html
const mapStateToProps = (state, ownProps) => ({
  currentProject: ownProps.currentProject,
  fetchingOpen: state.issues.fetchingOpen,
  issues: state.issues.open
})
export class IssueListView extends React.Component {
  static propTypes = {
    currentProject: PT.shape({
      id: PT.number,
      name: PT.string,
      key: PT.string,
      isSyncing: PT.bool.isRequired,
      description: PT.string
    }),
    fetchingOpen: PT.bool,
    issues: PT.any,
    fetchByProject: PT.func.isRequired
  };

  componentDidMount () {
    this.props.fetchByProject(this.props.currentProject.id)
  }

  render () {
    var children = []

    if (!this.props.fetchingOpen) {
      if (this.props.issues && this.props.issues.length > 0) {
        children.push(<Issues key="issues" {...this.props}/>)
      } else {
        children.push(<NoIssues key="zero"/>)
      }
    } else {
      children.push(<Icons.Loading key="loading"/>)
    }

    return (

Open issues:

        {children}

    )
  }
}
export default connect(mapStateToProps, issuesActions)(IssueListView)
<commit_msg>using different key is issue list view<commit_after>import React, { PropTypes as PT } from 'react'
import { connect } from 'react-redux'
import { actions as issuesActions } from '../../redux/modules/IssuesActions'
import Icons from '../../components/Icons'
import { Link } from 'react-router'
// import styles from './IssuesListView.scss'

class NoIssues extends React.Component {
  render() {
    return (

Hey, there are no issues yet. You can <Link to='/issues/new'>create one</Link> right now!

    )
  }
}

class Issues extends React.Component {
  static propTypes = {
    issues: PT.any
  };

  render () {
    var children = this.props.issues.map((issue) => {
      return (

              <Link to={'/issues/' + issue.id}>{issue.summary}</Link>

            {issue.description}

        )
    })
    return (

            {children}

)
  }
}

// We define mapStateToProps where we'd normally use
// the @connect decorator so the data requirements are clear upfront, but then
// export the decorated component after the main class definition so
// the component can be tested w/ and w/o being connected.
// See: http://rackt.github.io/redux/docs/recipes/WritingTests.html
const mapStateToProps = (state, ownProps) => ({
  currentProject: ownProps.currentProject,
  fetchingOpen: state.issues.fetchingOpen,
  issues: state.issues.open
})
export class IssueListView extends React.Component {
  static propTypes = {
    currentProject: PT.shape({
      id: PT.number,
      name: PT.string,
      key: PT.string,
      isSyncing: PT.bool.isRequired,
      description: PT.string
    }),
    fetchingOpen: PT.bool,
    issues: PT.any,
    fetchByProject: PT.func.isRequired
  };

  componentDidMount () {
    this.props.fetchByProject(this.props.currentProject.id)
  }

  render () {
    var children = []

    if (!this.props.fetchingOpen) {
      if (this.props.issues && this.props.issues.length > 0) {
        children.push(<Issues key="issues" {...this.props}/>)
      } else {
        children.push(<NoIssues key="zero"/>)
      }
    } else {
      children.push(<Icons.Loading key="loading"/>)
    }

    return (

Open issues:

        {children}

    )
  }
}
export default connect(mapStateToProps, issuesActions)(IssueListView)
<|endoftext|>


<commit_before>;define(function(require, exports, module){
//---------------------------
var Util            = require("mod/se/util");
var CMD             = require("mod/se/cmd");
var DataType        = require("mod/se/datatype");
var DataProxy       = require("mod/se/dataproxy");
var Request         = require("mod/se/request");
var Storage         = require("mod/se/storage");
var TemplateEngine  = require("mod/se/template");

var ErrorTypes = CMD.ErrorTypes;
var RespTypes = CMD.ResponseTypes;
var ResponseProxy = DataProxy.ResponseProxy;
var DataCache =  DataProxy.DataCache;

var Persistent = Storage.Persistent;
var Session = Storage.Session;

var PreventDefaultLink = function(){
    $("body").on("click", 'a[href="#none"]', function(e){
        e.preventDefault();
    }).on("click", 'a[href="#"]', function(e){
        e.preventDefault();
    }).on("click", 'a[href="###"]', function(e){
        e.preventDefault();
    });
};

var SecurityURL = {
    verify: function(url, defaultURL){
        var info = Request.parseURL(url);
        var host = info.host;

        var pattern = /(seshenghuo\.com)$/i

        if(pattern.test(host)){
            return url;
        }else{
            console.warn("The URL(" + url + ") is not allowed.");
            console.warn("The default URL is `" + defaultURL + "`");
        }

        return defaultURL || "";
    },
    fixed: function(url){
        var URLInfo = Request.parseURL(url);
        var mergeKeys = [];
        var locData = Request.serialized(location.search);
        var data = Request.serialized(URLInfo.search);
        var key = null;

        if(!mergeKeys || mergeKeys.length == 0){
            return url;
        }

        for(var i = 0; i < mergeKeys.length; i++){
            key = mergeKeys[i];

            if(key in locData){
                data[key] = locData[key];
            }
        }

        url = Request.append(url, Request.stringify(data));

        return url;
    }
};

var AppSchema = {
    schema: "app",
    //--------------------------
    //data ==> [flag,action]
    invoke: function(data, node, e, type){
        var args = (data || "").split(",");
        var flag = Number(args[0] || 0); // 0, 1, 2, 4, ...
        var action = args[1];

        if(!action){
            return ;
        }

        if(e && Util.checkBitFlag(3, 1)){
            e.preventDefault();
        }

        if(e && Util.checkBitFlag(3, 2)){
            e.stopPropagation();
        }

        Util.requestExternal(action, [node, e, type]);
    }
};

var GoSchema = {
    schema: "go",
    //--------------------------
    url: function(data, node, e, type){
        var args = (data || "").split(",");
        var url = args[0];

        if(node && node.hasClass("disabled")){
            return ;
        }

        if(!url || !SecurityURL.verify(url)){
            return ;
        }

        location.href = SecurityURL.fixed(url);
    },
    open: function(data, node, e, type){
        var args = (data || "").split(",");
        var url = args[0];
        var target = args[1] || "_blank";

        if(node && node.hasClass("disabled")){
            return ;
        }

        if(!url || !SecurityURL.verify(url)){
            return ;
        }

        window.open(SecurityURL.fixed(url), target);
    },
    refresh: function(data, node, e, type){
        var url = document.URL;

        if(node && node.hasClass("disabled")){
            return ;
        }

        location.replace(SecurityURL.fixed(url));
    },
    replace: function(data, node, e, type){
        var args = (data || "").split(",");
        var url = args[0];

        if(node && node.hasClass("disabled")){
            return ;
        }

        if(!url || !SecurityURL.verify(url)){
            return ;
        }

        location.replace(SecurityURL.fixed(url));
    },
    sego: function(data, node, e, type){
        var args = (data || "").split(",");
        var name = args[0] || "segoto";
        var url = Request.getParameter(name);

        if(url){
            try{
                url = decodeURIComponent(url);
                url = SecurityURL.verify(url);
            }catch(e){
                url = "";
            }
        }

        if(node && node.hasClass("disabled")){
            return ;
        }

        if(url){
            location.href = SecurityURL.fixed(url);
        }
    },
    tab: function(data, node, e, type){
        var args = (data || "").split(",");
        var name = args[0];
        var requestHandler = null;

        var menu = $('[data-tab-menu="' + name + '"]');
        var body = $('[data-tab-body="' + name + '"]');

        var menusRoot = menu.parents(".tab-menus");
        var bodiesRoot = body.parents(".tab-bodies");

        var menus = menusRoot.find('[data-tab-menu]');
        var bodies = bodiesRoot.find('[data-tab-body]');

        if(node && node.hasClass("disabled")){
            return ;
        }

        menus.removeClass("on");
        bodies.addClass("hide");

        requestHandler = menu.attr("data-tab-request") || null;

        menu.addClass("on");

        if(requestHandler){
            Util.requestExternal(requestHandler, [node, e, type, {
                "name": name,
                "menu": menu,
                "body": body,
                "root": {
                    "menu": menusRoot,
                    "body": bodiesRoot
                }
            }]);
        }

        body.removeClass("hide");
    }
};

var InputSchema = {
    schema: "input",
    sync: {
        radio: function(data, node, e, type){
            var args = (data || "").split(",");
            var name = args[0];
            var container = args[1];
            var containerNode = null;
            var targetInput = null;

            if(container){
                containerNode = $(container);

                if(containerNode.length == 0){
                    containerNode = null;
                }
            }

            if(containerNode){
                targetInput = containerNode.find('input[name="' + name + '"]');
            }else{
                targetInput = $('input[name="' + name + '"]');
            }

            targetInput.val(node.val());
        },
        checkbox: function(data, node, e, type){
            var args = (data || "").split(",");
            var name = args[0];
            var container = args[1];
            var checkedValue = args[2];
            var uncheckedValue = args[3];
            var containerNode = null;
            var targetInput = null;

            if(container){
                containerNode = $(container);

                if(containerNode.length == 0){
                    containerNode = null;
                }
            }

            if(containerNode){
                targetInput = containerNode.find('input[name="' + name + '"]');
            }else{
                targetInput = $('input[name="' + name + '"]');
            }

            var dom = node[0];

            if(dom.checked){
                targetInput.val(checkedValue);
            }else{
                targetInput.val(uncheckedValue);
            }
        }
    },
    tab: {
        radio: function(data, node, e, type){
            var args = (data || "").split(",");
            var tabType = args[0];
            var val = node.val();

            var tabs = $('[data-tabfor^="' + tabType + '."]');
            var tab = $('[data-tabfor="' + tabType + '.' + val + '"]');

            if(node && (node[0].disabled || node.parents(".disabled").length > 0)){
                return ;
            }

            tabs.addClass("hide");
            tab.removeClass("hide");
        }
    },
    label: {
        radio: function(data, node, e, type){
            var args = (data || "").split(",");
            var tabType = args[0];
            var val = node.val();

            if(node && (node[0].disabled || node.parents(".disabled").length > 0)){
                return ;
            }

            var labels = (node.attr("data-labels") || "").split(",");
            var labelNodes = $('[data-labelfor="' + tabType + '"]');
            var labelNode = null;
            var label = null;

            for(var i = 0; i < labelNodes.length; i++){
                label = labels[i];
                labelNode = labelNodes[i];

                if(label && labelNode){
                    labelNode.innerHTML = label;
                }
            }
        }
    }
};

var _App = {
    _conf: {},
    conf: function(){
        var args = arguments;
        var size = args.length;

        if(size <= 0 || size > 2){
            return ;
        }

        var key = "";
        var value = "";

        if(size == 2){
            key = args[0];
            value = args[1];

            if(key in _App._conf){
                if(DataType.isObject(value)){
                    var tmp = _App._conf[key];

                    _App._conf[key] = $.extend(true, {}, tmp, value);
                }else{
                    _App._conf[key] = value;
                }
            }else{
                _App._conf[key] = value;
            }
        }else{
            key = args[0];
            if(key in _App._conf){
                return _App._conf[key];
            }

            return undefined;
        }
    },
    init: function(conf){
        _App._conf = conf;

        var alias = _App.conf("alias");

        Util.watchAction("body", [
            {type: "click", mapping: null, compatible: null},
            {type: "input", mapping: null, compatible: null}
        ], null);

        Util.source(AppSchema);
        Util.source(GoSchema);
        Util.source(InputSchema);

        if(conf.message){
            CMD.setBubbleTips(conf.message);
        }
        PreventDefaultLink();
    }
};

module.exports = {
    "version": "R17B0430.01",
    "init": _App.init,
    "conf": _App.conf,
    "expando": {
        "util": Util,
        "cmd": CMD,
        "errors": ErrorTypes,
        "types": RespTypes,
        "request": Request,
        "response": ResponseProxy,
        "cache": DataCache,
        "template": TemplateEngine,
        "persistent": Persistent,
        "session": Session,
        "typeof": DataType
    }
}
//---------------------------
});<commit_msg>优化tpl_main.js的go://sego方法<commit_after>;define(function(require, exports, module){
//---------------------------
var Util            = require("mod/se/util");
var CMD             = require("mod/se/cmd");
var DataType        = require("mod/se/datatype");
var DataProxy       = require("mod/se/dataproxy");
var Request         = require("mod/se/request");
var Storage         = require("mod/se/storage");
var TemplateEngine  = require("mod/se/template");

var ErrorTypes = CMD.ErrorTypes;
var RespTypes = CMD.ResponseTypes;
var ResponseProxy = DataProxy.ResponseProxy;
var DataCache =  DataProxy.DataCache;

var Persistent = Storage.Persistent;
var Session = Storage.Session;

var PreventDefaultLink = function(){
    $("body").on("click", 'a[href="#none"]', function(e){
        e.preventDefault();
    }).on("click", 'a[href="#"]', function(e){
        e.preventDefault();
    }).on("click", 'a[href="###"]', function(e){
        e.preventDefault();
    });
};

var SecurityURL = {
    verify: function(url, defaultURL){
        var info = Request.parseURL(url);
        var host = info.host;

        var pattern = /(seshenghuo\.com)$/i

        if(pattern.test(host)){
            return url;
        }else{
            console.warn("The URL(" + url + ") is not allowed.");
            console.warn("The default URL is `" + defaultURL + "`");
        }

        return defaultURL || "";
    },
    fixed: function(url){
        var URLInfo = Request.parseURL(url);
        var mergeKeys = [];
        var locData = Request.serialized(location.search);
        var data = Request.serialized(URLInfo.search);
        var key = null;

        if(!mergeKeys || mergeKeys.length == 0){
            return url;
        }

        for(var i = 0; i < mergeKeys.length; i++){
            key = mergeKeys[i];

            if(key in locData){
                data[key] = locData[key];
            }
        }

        url = Request.append(url, Request.stringify(data));

        return url;
    }
};

var AppSchema = {
    schema: "app",
    //--------------------------
    //data ==> [flag,action]
    invoke: function(data, node, e, type){
        var args = (data || "").split(",");
        var flag = Number(args[0] || 0); // 0, 1, 2, 4, ...
        var action = args[1];

        if(!action){
            return ;
        }

        if(e && Util.checkBitFlag(3, 1)){
            e.preventDefault();
        }

        if(e && Util.checkBitFlag(3, 2)){
            e.stopPropagation();
        }

        Util.requestExternal(action, [node, e, type]);
    }
};

var GoSchema = {
    schema: "go",
    //--------------------------
    url: function(data, node, e, type){
        var args = (data || "").split(",");
        var url = args[0];

        if(node && node.hasClass("disabled")){
            return ;
        }

        if(!url || !SecurityURL.verify(url)){
            return ;
        }

        location.href = SecurityURL.fixed(url);
    },
    open: function(data, node, e, type){
        var args = (data || "").split(",");
        var url = args[0];
        var target = args[1] || "_blank";

        if(node && node.hasClass("disabled")){
            return ;
        }

        if(!url || !SecurityURL.verify(url)){
            return ;
        }

        window.open(SecurityURL.fixed(url), target);
    },
    refresh: function(data, node, e, type){
        var url = document.URL;

        if(node && node.hasClass("disabled")){
            return ;
        }

        location.replace(SecurityURL.fixed(url));
    },
    replace: function(data, node, e, type){
        var args = (data || "").split(",");
        var url = args[0];

        if(node && node.hasClass("disabled")){
            return ;
        }

        if(!url || !SecurityURL.verify(url)){
            return ;
        }

        location.replace(SecurityURL.fixed(url));
    },
    sego: function(data, node, e, type){
        var args = (data || "").split(",");
        var name = args[0] || "segoto";
        var defaultURL = args[1] || null;
        var url = Request.getParameter(name) || defaultURL;

        if(url){
            try{
                url = decodeURIComponent(url);
                url = SecurityURL.verify(url);
            }catch(e){
                url = "";
            }
        }

        if(node && node.hasClass("disabled")){
            return ;
        }

        if(url){
            location.href = SecurityURL.fixed(url);
        }
    },
    tab: function(data, node, e, type){
        var args = (data || "").split(",");
        var name = args[0];
        var requestHandler = null;

        var menu = $('[data-tab-menu="' + name + '"]');
        var body = $('[data-tab-body="' + name + '"]');

        var menusRoot = menu.parents(".tab-menus");
        var bodiesRoot = body.parents(".tab-bodies");

        var menus = menusRoot.find('[data-tab-menu]');
        var bodies = bodiesRoot.find('[data-tab-body]');

        if(node && node.hasClass("disabled")){
            return ;
        }

        menus.removeClass("on");
        bodies.addClass("hide");

        requestHandler = menu.attr("data-tab-request") || null;

        menu.addClass("on");

        if(requestHandler){
            Util.requestExternal(requestHandler, [node, e, type, {
                "name": name,
                "menu": menu,
                "body": body,
                "root": {
                    "menu": menusRoot,
                    "body": bodiesRoot
                }
            }]);
        }

        body.removeClass("hide");
    }
};

var InputSchema = {
    schema: "input",
    sync: {
        radio: function(data, node, e, type){
            var args = (data || "").split(",");
            var name = args[0];
            var container = args[1];
            var containerNode = null;
            var targetInput = null;

            if(container){
                containerNode = $(container);

                if(containerNode.length == 0){
                    containerNode = null;
                }
            }

            if(containerNode){
                targetInput = containerNode.find('input[name="' + name + '"]');
            }else{
                targetInput = $('input[name="' + name + '"]');
            }

            targetInput.val(node.val());
        },
        checkbox: function(data, node, e, type){
            var args = (data || "").split(",");
            var name = args[0];
            var container = args[1];
            var checkedValue = args[2];
            var uncheckedValue = args[3];
            var containerNode = null;
            var targetInput = null;

            if(container){
                containerNode = $(container);

                if(containerNode.length == 0){
                    containerNode = null;
                }
            }

            if(containerNode){
                targetInput = containerNode.find('input[name="' + name + '"]');
            }else{
                targetInput = $('input[name="' + name + '"]');
            }

            var dom = node[0];

            if(dom.checked){
                targetInput.val(checkedValue);
            }else{
                targetInput.val(uncheckedValue);
            }
        }
    },
    tab: {
        radio: function(data, node, e, type){
            var args = (data || "").split(",");
            var tabType = args[0];
            var val = node.val();

            var tabs = $('[data-tabfor^="' + tabType + '."]');
            var tab = $('[data-tabfor="' + tabType + '.' + val + '"]');

            if(node && (node[0].disabled || node.parents(".disabled").length > 0)){
                return ;
            }

            tabs.addClass("hide");
            tab.removeClass("hide");
        }
    },
    label: {
        radio: function(data, node, e, type){
            var args = (data || "").split(",");
            var tabType = args[0];
            var val = node.val();

            if(node && (node[0].disabled || node.parents(".disabled").length > 0)){
                return ;
            }

            var labels = (node.attr("data-labels") || "").split(",");
            var labelNodes = $('[data-labelfor="' + tabType + '"]');
            var labelNode = null;
            var label = null;

            for(var i = 0; i < labelNodes.length; i++){
                label = labels[i];
                labelNode = labelNodes[i];

                if(label && labelNode){
                    labelNode.innerHTML = label;
                }
            }
        }
    }
};

var _App = {
    _conf: {},
    conf: function(){
        var args = arguments;
        var size = args.length;

        if(size <= 0 || size > 2){
            return ;
        }

        var key = "";
        var value = "";

        if(size == 2){
            key = args[0];
            value = args[1];

            if(key in _App._conf){
                if(DataType.isObject(value)){
                    var tmp = _App._conf[key];

                    _App._conf[key] = $.extend(true, {}, tmp, value);
                }else{
                    _App._conf[key] = value;
                }
            }else{
                _App._conf[key] = value;
            }
        }else{
            key = args[0];
            if(key in _App._conf){
                return _App._conf[key];
            }

            return undefined;
        }
    },
    init: function(conf){
        _App._conf = conf;

        var alias = _App.conf("alias");

        Util.watchAction("body", [
            {type: "click", mapping: null, compatible: null},
            {type: "input", mapping: null, compatible: null}
        ], null);

        Util.source(AppSchema);
        Util.source(GoSchema);
        Util.source(InputSchema);

        if(conf.message){
            CMD.setBubbleTips(conf.message);
        }
        PreventDefaultLink();
    }
};

module.exports = {
    "version": "R17B0430.01",
    "init": _App.init,
    "conf": _App.conf,
    "expando": {
        "util": Util,
        "cmd": CMD,
        "errors": ErrorTypes,
        "types": RespTypes,
        "request": Request,
        "response": ResponseProxy,
        "cache": DataCache,
        "template": TemplateEngine,
        "persistent": Persistent,
        "session": Session,
        "typeof": DataType
    }
}
//---------------------------
});<|endoftext|>


<commit_before>goog.require('i18n.phonenumbers.AsYouTypeFormatter');
goog.require('i18n.phonenumbers.PhoneNumberFormat');
goog.require('i18n.phonenumbers.PhoneNumberType');
goog.require('i18n.phonenumbers.PhoneNumberUtil');
goog.require('i18n.phonenumbers.PhoneNumberUtil.ValidationResult');

var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance();

// stateless AsYouTypeFormatter (pass full string to it each time)
// designed as stateless to work with ADVANCED_OPTIMIZATIONS
function formatAsTyped(phoneNumber, regionCode) {
  regionCode = regionCode || "us";

  var formatter = new i18n.phonenumbers.AsYouTypeFormatter(regionCode);

  var output;

  // loop over phone number and input digits one by one, then return final output
  if (phoneNumber && typeof phoneNumber === 'string') {
    for (var i = 0; i < phoneNumber.length; i++) {
      output = formatter.inputDigit(phoneNumber.charAt(i));
    }
  }

  return output;
}

function countryCodeToRegionCodeMap() {
  return i18n.phonenumbers.metadata.countryCodeToRegionCodeMap;
}

function isPossibleNumber(phoneNumber, regionCode) {
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.isPossibleNumber(number);
}

function isPossibleNumberWithReason(phoneNumber, regionCode) {
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.isPossibleNumberWithReason(number);
}

function isValidNumber(phoneNumber, regionCode) {
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.isValidNumber(number);
}

function isValidNumberForRegion(phoneNumber, regionCode) {
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.isValidNumberForRegion(number, regionCode);
}

function getCountryCodeForRegion(regionCode) {
  regionCode = regionCode || "us";
  return phoneUtil.getCountryCodeForRegion(regionCode);
}

function getRegionCodeForNumber(phoneNumber, regionCode) {
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.getRegionCodeForNumber(number);
}

function getNumberType(phoneNumber, regionCode) {
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  var output;
  var PNT = i18n.phonenumbers.PhoneNumberType;
  switch (phoneUtil.getNumberType(number)) {
    case PNT.FIXED_LINE:
      output = 'FIXED_LINE';
      break;
    case PNT.MOBILE:
      output = 'MOBILE';
      break;
    case PNT.FIXED_LINE_OR_MOBILE:
      output = 'FIXED_LINE_OR_MOBILE';
      break;
    case PNT.TOLL_FREE:
      output = 'TOLL_FREE';
      break;
    case PNT.PREMIUM_RATE:
      output = 'PREMIUM_RATE';
      break;
    case PNT.SHARED_COST:
      output = 'SHARED_COST';
      break;
    case PNT.VOIP:
      output = 'VOIP';
      break;
    case PNT.PERSONAL_NUMBER:
      output = 'PERSONAL_NUMBER';
      break;
    case PNT.PAGER:
      output = 'PAGER';
      break;
    case PNT.UAN:
      output = 'UAN';
      break;
    case PNT.UNKNOWN:
      output = 'UNKNOWN';
      break;
  }
  return output;
}

function getSupportedRegions() {
  return phoneUtil.getSupportedRegions();
}

function formatE164(phoneNumber, regionCode) {
  var PNF = i18n.phonenumbers.PhoneNumberFormat;
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.format(number, PNF.E164);
}

function formatNational(phoneNumber, regionCode) {
  var PNF = i18n.phonenumbers.PhoneNumberFormat;
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.format(number, PNF.NATIONAL);
}

function formatInternational(phoneNumber, regionCode) {
  var PNF = i18n.phonenumbers.PhoneNumberFormat;
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.format(number, PNF.INTERNATIONAL);
}

function formatInOriginalFormat(phoneNumber, regionCode) {
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.formatInOriginalFormat(number, regionCode);
}

function formatOutOfCountryCallingNumber(phoneNumber, regionCode, target) {
  if (!target) { return; }
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.formatOutOfCountryCallingNumber(number, target);
}

goog.exportSymbol('phoneUtils.countryCodeToRegionCodeMap', countryCodeToRegionCodeMap);
goog.exportSymbol('phoneUtils.isPossibleNumber', isPossibleNumber);
goog.exportSymbol('phoneUtils.isPossibleNumberWithReason', isPossibleNumberWithReason);
goog.exportSymbol('phoneUtils.isValidNumber', isValidNumber);
goog.exportSymbol('phoneUtils.isValidNumberForRegion', isValidNumberForRegion);
goog.exportSymbol('phoneUtils.getCountryCodeForRegion', getCountryCodeForRegion);
goog.exportSymbol('phoneUtils.getRegionCodeForNumber', getRegionCodeForNumber);
goog.exportSymbol('phoneUtils.getNumberType', getNumberType);
goog.exportSymbol('phoneUtils.getSupportedRegions', getSupportedRegions);
goog.exportSymbol('phoneUtils.formatE164', formatE164);
goog.exportSymbol('phoneUtils.formatNational', formatNational);
goog.exportSymbol('phoneUtils.formatInternational', formatInternational);
goog.exportSymbol('phoneUtils.formatInOriginalFormat', formatInOriginalFormat);
goog.exportSymbol('phoneUtils.formatOutOfCountryCallingNumber', formatOutOfCountryCallingNumber);
goog.exportSymbol('phoneUtils.formatAsTyped', formatAsTyped);
<commit_msg>Restore debugging code to formatAsTyped<commit_after>goog.require('i18n.phonenumbers.AsYouTypeFormatter');
goog.require('i18n.phonenumbers.PhoneNumberFormat');
goog.require('i18n.phonenumbers.PhoneNumberType');
goog.require('i18n.phonenumbers.PhoneNumberUtil');
goog.require('i18n.phonenumbers.PhoneNumberUtil.ValidationResult');

var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance();

// stateless AsYouTypeFormatter (pass full string to it each time)
// designed as stateless to work with ADVANCED_OPTIMIZATIONS
function formatAsTyped(phoneNumber, regionCode) {
  regionCode = regionCode || "us";

  console.log('Instantiating AsYouTypeFormatter for', regionCode);

  var formatter = new i18n.phonenumbers.AsYouTypeFormatter(regionCode);

  var output;

  // loop over phone number and input digits one by one, then return final output
  if (phoneNumber && typeof phoneNumber === 'string') {
    for (var i = 0; i < phoneNumber.length; i++) {
      output = formatter.inputDigit(phoneNumber.charAt(i));
      console.log('char:', phoneNumber.charAt(i), 'output:', output);
    }
  }

  return output;
}

function countryCodeToRegionCodeMap() {
  return i18n.phonenumbers.metadata.countryCodeToRegionCodeMap;
}

function isPossibleNumber(phoneNumber, regionCode) {
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.isPossibleNumber(number);
}

function isPossibleNumberWithReason(phoneNumber, regionCode) {
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.isPossibleNumberWithReason(number);
}

function isValidNumber(phoneNumber, regionCode) {
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.isValidNumber(number);
}

function isValidNumberForRegion(phoneNumber, regionCode) {
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.isValidNumberForRegion(number, regionCode);
}

function getCountryCodeForRegion(regionCode) {
  regionCode = regionCode || "us";
  return phoneUtil.getCountryCodeForRegion(regionCode);
}

function getRegionCodeForNumber(phoneNumber, regionCode) {
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.getRegionCodeForNumber(number);
}

function getNumberType(phoneNumber, regionCode) {
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  var output;
  var PNT = i18n.phonenumbers.PhoneNumberType;
  switch (phoneUtil.getNumberType(number)) {
    case PNT.FIXED_LINE:
      output = 'FIXED_LINE';
      break;
    case PNT.MOBILE:
      output = 'MOBILE';
      break;
    case PNT.FIXED_LINE_OR_MOBILE:
      output = 'FIXED_LINE_OR_MOBILE';
      break;
    case PNT.TOLL_FREE:
      output = 'TOLL_FREE';
      break;
    case PNT.PREMIUM_RATE:
      output = 'PREMIUM_RATE';
      break;
    case PNT.SHARED_COST:
      output = 'SHARED_COST';
      break;
    case PNT.VOIP:
      output = 'VOIP';
      break;
    case PNT.PERSONAL_NUMBER:
      output = 'PERSONAL_NUMBER';
      break;
    case PNT.PAGER:
      output = 'PAGER';
      break;
    case PNT.UAN:
      output = 'UAN';
      break;
    case PNT.UNKNOWN:
      output = 'UNKNOWN';
      break;
  }
  return output;
}

function getSupportedRegions() {
  return phoneUtil.getSupportedRegions();
}

function formatE164(phoneNumber, regionCode) {
  var PNF = i18n.phonenumbers.PhoneNumberFormat;
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.format(number, PNF.E164);
}

function formatNational(phoneNumber, regionCode) {
  var PNF = i18n.phonenumbers.PhoneNumberFormat;
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.format(number, PNF.NATIONAL);
}

function formatInternational(phoneNumber, regionCode) {
  var PNF = i18n.phonenumbers.PhoneNumberFormat;
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.format(number, PNF.INTERNATIONAL);
}

function formatInOriginalFormat(phoneNumber, regionCode) {
  regionCode = regionCode || "us";
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.formatInOriginalFormat(number, regionCode);
}

function formatOutOfCountryCallingNumber(phoneNumber, regionCode, target) {
  if (!target) { return; }
  var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
  return phoneUtil.formatOutOfCountryCallingNumber(number, target);
}

goog.exportSymbol('phoneUtils.countryCodeToRegionCodeMap', countryCodeToRegionCodeMap);
goog.exportSymbol('phoneUtils.isPossibleNumber', isPossibleNumber);
goog.exportSymbol('phoneUtils.isPossibleNumberWithReason', isPossibleNumberWithReason);
goog.exportSymbol('phoneUtils.isValidNumber', isValidNumber);
goog.exportSymbol('phoneUtils.isValidNumberForRegion', isValidNumberForRegion);
goog.exportSymbol('phoneUtils.getCountryCodeForRegion', getCountryCodeForRegion);
goog.exportSymbol('phoneUtils.getRegionCodeForNumber', getRegionCodeForNumber);
goog.exportSymbol('phoneUtils.getNumberType', getNumberType);
goog.exportSymbol('phoneUtils.getSupportedRegions', getSupportedRegions);
goog.exportSymbol('phoneUtils.formatE164', formatE164);
goog.exportSymbol('phoneUtils.formatNational', formatNational);
goog.exportSymbol('phoneUtils.formatInternational', formatInternational);
goog.exportSymbol('phoneUtils.formatInOriginalFormat', formatInOriginalFormat);
goog.exportSymbol('phoneUtils.formatOutOfCountryCallingNumber', formatOutOfCountryCallingNumber);
goog.exportSymbol('phoneUtils.formatAsTyped', formatAsTyped);
<|endoftext|>


<commit_before>var MEOWTO = "__MEOWTO__";  // LocalStorage goes here
var aliases = {};

(function() {
  // Read aliases from local storage, if there are any.
  if (!localStorage[MEOWTO])
    updateLocalStorage();
  else
    aliases = JSON.parse(localStorage[MEOWTO]);

  var query = window.location.search.substring(1);

  switch(query) {
    case '':
      show('setup');
      showList();
      show('help');
      break;
    case 'setup':
      show('setup');
      show('help');
    case 'list':
      showList();
      break;
    case 'help':
    case 'halp':
      show('help');
      break;
    case 'nukeall':
      aliases = {};
      updateLocalStorage();
      redirectToList();
    default:
      if (query.indexOf('add') == 0)
        addAlias(query);
      else if (query.indexOf('nuke') == 0)
        nukeAlias(query);
      else
        redirectTo(query);
}
})();

function addAlias(query) {
  var cleanQuery = queryWithoutCommand(query, 'add');
  if (cleanQuery == '') {
    show('error');
    show('help');
    return;
  }

  var parsedQuery = cleanQuery.split('->');

  if (parsedQuery.length != 2) {
    show('error');
    show('help');
    return;
  }

  var name = parsedQuery[0].trim();
  var url = parsedQuery[1].trim();

  // If there wasn't an http://, add one.
  if (url.indexOf('http') == -1)
    url = 'http://' + url;

  aliases[name] = url;
  updateLocalStorage();
  redirectToList();
}

function nukeAlias(query) {
  var cleanQuery = queryWithoutCommand(query, 'nuke');
  if (cleanQuery == '') {
    show('error');
    show('help');
    return;
  }

  delete aliases[cleanQuery];
  updateLocalStorage();
  redirectToList()
}

function redirectTo(query) {
  query = decodeURIComponent(query.trim());
  var url = aliases[query];
  if (url && url != '')
    window.location.replace(url);
  else
    show('add');
}

function queryWithoutCommand(query, command) {
  var cleanQuery = decodeURIComponent(query.trim());
  // You might have +s. You shouldn't.
  cleanQuery = cleanQuery.replace(/\+/g, ' ');

  if (cleanQuery.indexOf(command) != 0)
    return ''
  return cleanQuery.substring(command.length).trim();
}

function redirectToList() {
  window.location.replace('?list');
}
function showList() {
  document.getElementById('list-box').hidden = false;
  if (Object.keys(aliases).length == 0) {
    document.getElementById('no-items').hidden = false;
    return;
  }

  var ul = document.getElementById('list')

  for (var name in aliases) {
    var li = document.createElement('li');

    var span = document.createElement('span');
    span.className = 'meow';
    span.innerHTML = name;

    var a = document.createElement('a');
    a.innerHTML = aliases[name];
    a.href = aliases[name];
    a.target = '_blank';

    var del = document.createElement('a');
    del.className = 'meow nuke';
    del.innerHTML = 'x';
    del.href = '?nuke ' + name;

    li.appendChild(span);
    li.appendChild(a);
    li.appendChild(del);

    ul.appendChild(li);
  }

  var li = document.createElement('li');
  var span = document.createElement('span');
  span.className = 'red';
  span.innerHTML = ' [for reals. no confirmation]';
  var a = document.createElement('a');
  a.className = 'meow';
  a.innerHTML = 'delete all aliases';
  a.href = '?nukeall';
  a.appendChild(span);
  li.appendChild(a);
  ul.appendChild(li);
}

function updateLocalStorage() {
  localStorage[MEOWTO] = JSON.stringify(aliases);
}

function show(what) {
  document.getElementById(what + '-box').hidden = false;
}
<commit_msg>fix delete link styles<commit_after>var MEOWTO = "__MEOWTO__";  // LocalStorage goes here
var aliases = {};

(function() {
  // Read aliases from local storage, if there are any.
  if (!localStorage[MEOWTO])
    updateLocalStorage();
  else
    aliases = JSON.parse(localStorage[MEOWTO]);

  var query = window.location.search.substring(1);

  switch(query) {
    case '':
      show('setup');
      showList();
      show('help');
      break;
    case 'setup':
      show('setup');
      show('help');
    case 'list':
      showList();
      break;
    case 'help':
    case 'halp':
      show('help');
      break;
    case 'nukeall':
      aliases = {};
      updateLocalStorage();
      redirectToList();
    default:
      if (query.indexOf('add') == 0)
        addAlias(query);
      else if (query.indexOf('nuke') == 0 || query.indexOf('del') == 0)
        nukeAlias(query);
      else
        redirectTo(query);
}
})();

function addAlias(query) {
  var cleanQuery = queryWithoutCommand(query, 'add');
  if (cleanQuery == '') {
    show('error');
    show('help');
    return;
  }

  var parsedQuery = cleanQuery.split('->');

  if (parsedQuery.length != 2) {
    show('error');
    show('help');
    return;
  }

  var name = parsedQuery[0].trim();
  var url = parsedQuery[1].trim();

  // If there wasn't an http://, add one.
  if (url.indexOf('http') == -1)
    url = 'http://' + url;

  aliases[name] = url;
  updateLocalStorage();
  redirectToList();
}

function nukeAlias(query) {
  var cleanQuery = queryWithoutCommand(query, 'nuke');
  if (cleanQuery == '') {
    show('error');
    show('help');
    return;
  }

  delete aliases[cleanQuery];
  updateLocalStorage();
  redirectToList()
}

function redirectTo(query) {
  query = decodeURIComponent(query.trim());
  var url = aliases[query];
  if (url && url != '')
    window.location.replace(url);
  else
    show('add');
}

function queryWithoutCommand(query, command) {
  var cleanQuery = decodeURIComponent(query.trim());
  // You might have +s. You shouldn't.
  cleanQuery = cleanQuery.replace(/\+/g, ' ');

  if (cleanQuery.indexOf(command) != 0)
    return ''
  return cleanQuery.substring(command.length).trim();
}

function redirectToList() {
  window.location.replace('?list');
}
function showList() {
  document.getElementById('list-box').hidden = false;
  if (Object.keys(aliases).length == 0) {
    document.getElementById('no-items').hidden = false;
    return;
  }

  var ul = document.getElementById('list')

  for (var name in aliases) {
    var li = document.createElement('li');

    var span = document.createElement('span');
    span.className = 'meow';
    span.innerHTML = name;

    var a = document.createElement('a');
    a.innerHTML = aliases[name];
    a.href = aliases[name];
    a.target = '_blank';

    var del = document.createElement('a');
    del.className = 'meow nuke red';
    del.innerHTML = '[delete]';
    del.href = '?nuke ' + name;

    li.appendChild(span);
    li.appendChild(a);
    li.appendChild(del);

    ul.appendChild(li);
  }

  var li = document.createElement('li');
  var span = document.createElement('span');
  span.className = 'red';
  span.innerHTML = ' [for reals. no confirmation]';
  var a = document.createElement('a');
  a.className = 'meow';
  a.innerHTML = 'delete all aliases';
  a.href = '?nukeall';
  a.appendChild(span);
  li.appendChild(a);
  ul.appendChild(li);
}

function updateLocalStorage() {
  localStorage[MEOWTO] = JSON.stringify(aliases);
}

function show(what) {
  document.getElementById(what + '-box').hidden = false;
}
<|endoftext|>


<commit_before>var page = [doc currentPage],
  artboard = [page currentArtboard],
  current = artboard ? artboard : page,
  prefix = 'utom',
  configs = {},
  resolution = {
          'LDPI @0.75x (dp)': .75,
          'MDPI @1x (dp)': 1,
          'HDPI @1.5x (dp)': 1.5,
         'XHDPI @2x (dp)': 2,
        'XXHDPI @3x (dp)': 3,
       'XXXHDPI @4x (dp)': 4,
      'Standard @1x (px)': 1,
        'Retina @2x (pt)': 2,
     'Retina HD @3x (pt)': 3
  };

function is(layer, theClass){
  var klass = [layer class];
  return klass === theClass;
}

function isPage(layer){
  return is(layer, MSPage);
}

function isGroup(layer){
  return is(layer, MSLayerGroup);
}

function isText(layer){
  return is(layer, MSTextLayer);
}

function isShape(layer){
  return is(layer, MSRectangleShape);
}

function addLayer(name, type, parent) {
  var parent = parent ? parent : current,
    layer = [parent addLayerOfType: type];
  if (name)[layer setName: name];
  return layer;
}

function addGroup(name, parent) {
  return addLayer(name, 'group', parent);
}

function addShape(name, parent) {
  return addLayer(name, 'rectangle', parent);
}

function addText(name, parent) {
  return addLayer(name, 'text', parent);
}

function removeLayer(layer) {
  var parent = [layer parentGroup];
  if (parent)[parent removeLayer: layer];
}

function setColor(layer, hex, alpha) {
  var color = [[MSColor alloc] init],
      rgb = hexToRgb(hex),
      red = rgb.r / 255,
      green = rgb.g / 255,
      blue = rgb.b / 255,
      alpha = (alpha && !isNaN(alpha) && (alpha <= 1 || alpha >= 0))? alpha: 1;

  [color setRed: red];
  [color setGreen: green];
  [color setBlue: blue];
  [color setAlpha: alpha];

  if( isText(layer) ) {
    [layer setTextColor: color];
  }
  else if( isShape(layer) ) {
    layer = [layer embedInShapeGroup];

    var fills = [[layer style] fills];
    if([fills count] <= 0) [fills addNewStylePart];
    [[[layer style] fill] setColor: color];
  }
}

function setSize(layer, width, height, absolute) {
  if(absolute){
    [[layer absoluteRect] setWidth: width];
    [[layer absoluteRect] setHeight: height];
  }
  else{
    [[layer frame] setWidth: width];
    [[layer frame] setHeight: height];
  }

  return layer;
}

function setPosition(layer, x, y, absolute) {
  if(absolute){
    [[layer absoluteRect] setX: x];
    [[layer absoluteRect] setY: y];
  }
  else{
    [[layer frame] setX: x];
    [[layer frame] setY: y];
  }

  return layer;
}

function getFrame(layer) {
  var frame = [layer frame];

  return {
    x: Math.round([frame x]),
    y: Math.round([frame y]),
    width: Math.round([frame width]),
    height: Math.round([frame height])
  };
}

function getRect(layer) {
  var rect = [layer absoluteRect];
  return {
    x: Math.round([rect x]),
    y: Math.round([rect y]),
    width: Math.round([rect width]),
    height: Math.round([rect height])
  };
}

function getGuides(layers) {
  var guides = [],
      getFn = function( layers ){
        var layers = [layers array];
        for (var i = 0; i < [layers count]; i++) {
          var layer = layers[i];
          if (
            isGroup(layer) &&
            /\$SIZE|\$WIDTH|\$HEIGHT|\$DISTANCE|\$PROPERTY|\$LABEL|\$OVERLAYER|\$COORDINATE/.exec([layer name])
          ) {
            guides.push(layer);
          }
          else if( isGroup(layer) ){
            getFn([layer layers]);
          }

        }
      }
  getFn(layers);
  return guides;

}

function updateLength(length, scale, sp){
  var scale = (scale)? scale: configs.resolution,
      length = Math.round(length / resolution[scale]),
        unit = (scale.match(/\(dp\)/))? 'dp' : 'px',
        unit = (scale.match(/\(pt\)/))? 'pt' : unit,
        unit = (scale.match(/\(dp\)/) && sp)? 'sp' : unit;

  return length + unit;
}

function toPositive(number) {
  return (number < 0) ? -(number) : number;
}

function componentToHex(c) {
  var hex = c.toString(16);
  return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
  return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

function getIndex(items, content) {
  var index = 0;
  for (var i = 0; i < items.length; i++) {
    if(items[i] == content) index = i;
  };
  return index;
}

function getConfig(key) {
  var defaults = [NSUserDefaults standardUserDefaults];

  return [defaults objectForKey: '-' + prefix + '-' + key];
}

function setConfig(key, value) {
  var defaults = [NSUserDefaults standardUserDefaults],
      configs  = [NSMutableDictionary dictionary];

  [configs setObject: value forKey: '-' + prefix + '-' + key]

  return [defaults registerDefaults: configs];
}
function elementAtIndex (view, index) {
  return [view viewAtIndex: index]
}
function valueAtIndex (view, index) {
  var element = elementAtIndex(view, index);
  return [element stringValue]
}
function checkedAtIndex (view, index) {
  var element = elementAtIndex(view, index);
  return [element state]
}

function createAlertBase () {
  var alert = [COSAlertWindow new];

  [alert addButtonWithTitle: 'OK'];
  [alert addButtonWithTitle: 'Cancel'];

  return alert;
}

function alert (message) {
  var alert = [COSAlertWindow new];
  [alert setMessageText: 'Sketch Measure']
  [alert setInformativeText: message]
  [alert runModal]
}

function createSelect (items, selectedItemIndex) {
  selectedItemIndex = selectedItemIndex || 0
  var comboBox = [[NSComboBox alloc] initWithFrame: NSMakeRect(0, 0, 300, 25)];
  [comboBox addItemsWithObjectValues: items]
  [comboBox selectItemAtIndex: selectedItemIndex]
  return comboBox;
}

function creatCheckbox (item, checked) {
  checked = (checked == false)? NSOffState: NSOnState;
  var checkbox = [[NSButton alloc] initWithFrame: NSMakeRect(0, 0, 300, 25)];
  [checkbox setButtonType: NSSwitchButton]
  [checkbox setBezelStyle: 0]
  [checkbox setTitle: item.name]
  [checkbox setTag: item.value]
  [checkbox setState: checked]
  return checkbox;
}

function initConfigs(){
  var version = getConfig('version');
  if(!version){
    setConfig('version', '0.0.3.1');
    setConfig('resolution', 'Standard @1x (px)');
    setConfig('font-size', 12);
    setConfig('font-type', 'Helvetica');
    setConfig('size-basic', '#FF5500');
    setConfig('size-text', '#FFFFFF');
    setConfig('distance-basic', '#50E3C2');
    setConfig('distance-text', '#FFFFFF');
    setConfig('label-basic', '#7BD228');
    setConfig('label-text', '#FFFFFF');
    setConfig('property-basic', '#F5A623');
    setConfig('property-text', '#FFFFFF');
    setConfig('coordinate-basic', '#7ED321');
    setConfig('coordinate-text', '#FFFFFF');
    setConfig('remenber-size-width', 'top');
    setConfig('remenber-size-height', 'none');
    setConfig('remenber-size-overlayer', true);
    setConfig('remenber-spacing-top', true);
    setConfig('remenber-spacing-right', false);
    setConfig('remenber-spacing-bottom', false);
    setConfig('remenber-spacing-left', true);
    setConfig('remenber-property-font', false);
    setConfig('remenber-property-size', true);
    setConfig('remenber-property-color', true);
    setConfig('remenber-property-line', false);
    setConfig('remenber-property-border', false);
    setConfig('remenber-property-shadow', false);
    setConfig('remenber-property-inner-shadow', false);
    setConfig('remenber-property-opacity', false);
    setConfig('remenber-property-at', 'top');
  }

  configs.version  = getConfig('version');
  configs.resolution  = getConfig('resolution');
  configs.fontSize = getConfig('font-size');
  configs.fontType = getConfig('font-type');
  configs.sizeBasic = getConfig('size-basic');
  configs.sizeText = getConfig('size-text');
  configs.distanceBasic = getConfig('distance-basic');
  configs.distanceText = getConfig('distance-text');
  configs.labelBasic = getConfig('label-basic');
  configs.labelText = getConfig('label-text');
  configs.propertyBasic = getConfig('property-basic');
  configs.propertyText = getConfig('property-text');
  configs.coordinateBasic = getConfig('coordinate-basic');
  configs.coordinateText = getConfig('coordinate-text');
  configs.remenberSizeWidth = getConfig('remenber-size-width');
  configs.remenberSizeHeight = getConfig('remenber-size-height');
  configs.remenberSizeOverlayer = getConfig('remenber-size-overlayer');
  configs.remenberSpacingTop = getConfig('remenber-spacing-top');
  configs.remenberSpacingRight = getConfig('remenber-spacing-right');
  configs.remenberSpacingBottom = getConfig('remenber-spacing-bottom');
  configs.remenberSpacingLeft = getConfig('remenber-spacing-left');
  configs.remenberPropertyFont = getConfig('remenber-property-font');
  configs.remenberPropertySize = getConfig('remenber-property-size');
  configs.remenberPropertyColor = getConfig('remenber-property-color');
  configs.remenberPropertyLine = getConfig('remenber-property-line');
  configs.remenberPropertyBorder = getConfig('remenber-property-border');
  configs.remenberPropertyShadow = getConfig('remenber-property-shadow');
  configs.remenberPropertyInnerShadow = getConfig('remenber-property-inner-shadow');
  configs.remenberPropertyOpacity = getConfig('remenber-property-opacity');
  configs.remenberPropertyAt = getConfig('remenber-property-at');
}

initConfigs();<commit_msg>Backwards compatibility<commit_after>var page = [doc currentPage],
  artboard = [page currentArtboard],
  current = artboard ? artboard : page,
  prefix = 'utom',
  configs = {},
  resolution = {
          'LDPI @0.75x (dp)': .75,
          'MDPI @1x (dp)': 1,
          'HDPI @1.5x (dp)': 1.5,
         'XHDPI @2x (dp)': 2,
        'XXHDPI @3x (dp)': 3,
       'XXXHDPI @4x (dp)': 4,
      'Standard @1x (px)': 1,
        'Retina @2x (pt)': 2,
     'Retina HD @3x (pt)': 3
  };

function is(layer, theClass){
  var klass = [layer class];
  return klass === theClass;
}

function isPage(layer){
  return is(layer, MSPage);
}

function isGroup(layer){
  return is(layer, MSLayerGroup);
}

function isText(layer){
  return is(layer, MSTextLayer);
}

function isShape(layer){
  return is(layer, MSRectangleShape) || is(layer, MSShapeGroup);
}

function addLayer(name, type, parent) {
  var parent = parent ? parent : current,
    layer = [parent addLayerOfType: type];
  if (name)[layer setName: name];
  return layer;
}

function addGroup(name, parent) {
  return addLayer(name, 'group', parent);
}

function addShape(name, parent) {
  return addLayer(name, 'rectangle', parent);
}

function addText(name, parent) {
  return addLayer(name, 'text', parent);
}

function removeLayer(layer) {
  var parent = [layer parentGroup];
  if (parent)[parent removeLayer: layer];
}

function setColor(layer, hex, alpha) {
  var color = [[MSColor alloc] init],
      rgb = hexToRgb(hex),
      red = rgb.r / 255,
      green = rgb.g / 255,
      blue = rgb.b / 255,
      alpha = (alpha && !isNaN(alpha) && (alpha <= 1 || alpha >= 0))? alpha: 1;

  [color setRed: red];
  [color setGreen: green];
  [color setBlue: blue];
  [color setAlpha: alpha];

  if( isText(layer) ) {
    [layer setTextColor: color];
  }
  else if( isShape(layer) ) {
    if (is(layer, 'MSRectangleShape')) {
      layer = [layer embedInShapeGroup];
    }

    var fills = [[layer style] fills];
    if([fills count] <= 0) [fills addNewStylePart];
    [[[layer style] fill] setColor: color];
  }
}

function setSize(layer, width, height, absolute) {
  if(absolute){
    [[layer absoluteRect] setWidth: width];
    [[layer absoluteRect] setHeight: height];
  }
  else{
    [[layer frame] setWidth: width];
    [[layer frame] setHeight: height];
  }

  return layer;
}

function setPosition(layer, x, y, absolute) {
  if(absolute){
    [[layer absoluteRect] setX: x];
    [[layer absoluteRect] setY: y];
  }
  else{
    [[layer frame] setX: x];
    [[layer frame] setY: y];
  }

  return layer;
}

function getFrame(layer) {
  var frame = [layer frame];

  return {
    x: Math.round([frame x]),
    y: Math.round([frame y]),
    width: Math.round([frame width]),
    height: Math.round([frame height])
  };
}

function getRect(layer) {
  var rect = [layer absoluteRect];
  return {
    x: Math.round([rect x]),
    y: Math.round([rect y]),
    width: Math.round([rect width]),
    height: Math.round([rect height])
  };
}

function getGuides(layers) {
  var guides = [],
      getFn = function( layers ){
        var layers = [layers array];
        for (var i = 0; i < [layers count]; i++) {
          var layer = layers[i];
          if (
            isGroup(layer) &&
            /\$SIZE|\$WIDTH|\$HEIGHT|\$DISTANCE|\$PROPERTY|\$LABEL|\$OVERLAYER|\$COORDINATE/.exec([layer name])
          ) {
            guides.push(layer);
          }
          else if( isGroup(layer) ){
            getFn([layer layers]);
          }

        }
      }
  getFn(layers);
  return guides;

}

function updateLength(length, scale, sp){
  var scale = (scale)? scale: configs.resolution,
      length = Math.round(length / resolution[scale]),
        unit = (scale.match(/\(dp\)/))? 'dp' : 'px',
        unit = (scale.match(/\(pt\)/))? 'pt' : unit,
        unit = (scale.match(/\(dp\)/) && sp)? 'sp' : unit;

  return length + unit;
}

function toPositive(number) {
  return (number < 0) ? -(number) : number;
}

function componentToHex(c) {
  var hex = c.toString(16);
  return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
  return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

function getIndex(items, content) {
  var index = 0;
  for (var i = 0; i < items.length; i++) {
    if(items[i] == content) index = i;
  };
  return index;
}

function getConfig(key) {
  var defaults = [NSUserDefaults standardUserDefaults];

  return [defaults objectForKey: '-' + prefix + '-' + key];
}

function setConfig(key, value) {
  var defaults = [NSUserDefaults standardUserDefaults],
      configs  = [NSMutableDictionary dictionary];

  [configs setObject: value forKey: '-' + prefix + '-' + key]

  return [defaults registerDefaults: configs];
}
function elementAtIndex (view, index) {
  return [view viewAtIndex: index]
}
function valueAtIndex (view, index) {
  var element = elementAtIndex(view, index);
  return [element stringValue]
}
function checkedAtIndex (view, index) {
  var element = elementAtIndex(view, index);
  return [element state]
}

function createAlertBase () {
  var alert = [COSAlertWindow new];

  [alert addButtonWithTitle: 'OK'];
  [alert addButtonWithTitle: 'Cancel'];

  return alert;
}

function alert (message) {
  var alert = [COSAlertWindow new];
  [alert setMessageText: 'Sketch Measure']
  [alert setInformativeText: message]
  [alert runModal]
}

function createSelect (items, selectedItemIndex) {
  selectedItemIndex = selectedItemIndex || 0
  var comboBox = [[NSComboBox alloc] initWithFrame: NSMakeRect(0, 0, 300, 25)];
  [comboBox addItemsWithObjectValues: items]
  [comboBox selectItemAtIndex: selectedItemIndex]
  return comboBox;
}

function creatCheckbox (item, checked) {
  checked = (checked == false)? NSOffState: NSOnState;
  var checkbox = [[NSButton alloc] initWithFrame: NSMakeRect(0, 0, 300, 25)];
  [checkbox setButtonType: NSSwitchButton]
  [checkbox setBezelStyle: 0]
  [checkbox setTitle: item.name]
  [checkbox setTag: item.value]
  [checkbox setState: checked]
  return checkbox;
}

function initConfigs(){
  var version = getConfig('version');
  if(!version){
    setConfig('version', '0.0.3.1');
    setConfig('resolution', 'Standard @1x (px)');
    setConfig('font-size', 12);
    setConfig('font-type', 'Helvetica');
    setConfig('size-basic', '#FF5500');
    setConfig('size-text', '#FFFFFF');
    setConfig('distance-basic', '#50E3C2');
    setConfig('distance-text', '#FFFFFF');
    setConfig('label-basic', '#7BD228');
    setConfig('label-text', '#FFFFFF');
    setConfig('property-basic', '#F5A623');
    setConfig('property-text', '#FFFFFF');
    setConfig('coordinate-basic', '#7ED321');
    setConfig('coordinate-text', '#FFFFFF');
    setConfig('remenber-size-width', 'top');
    setConfig('remenber-size-height', 'none');
    setConfig('remenber-size-overlayer', true);
    setConfig('remenber-spacing-top', true);
    setConfig('remenber-spacing-right', false);
    setConfig('remenber-spacing-bottom', false);
    setConfig('remenber-spacing-left', true);
    setConfig('remenber-property-font', false);
    setConfig('remenber-property-size', true);
    setConfig('remenber-property-color', true);
    setConfig('remenber-property-line', false);
    setConfig('remenber-property-border', false);
    setConfig('remenber-property-shadow', false);
    setConfig('remenber-property-inner-shadow', false);
    setConfig('remenber-property-opacity', false);
    setConfig('remenber-property-at', 'top');
  }

  configs.version  = getConfig('version');
  configs.resolution  = getConfig('resolution');
  configs.fontSize = getConfig('font-size');
  configs.fontType = getConfig('font-type');
  configs.sizeBasic = getConfig('size-basic');
  configs.sizeText = getConfig('size-text');
  configs.distanceBasic = getConfig('distance-basic');
  configs.distanceText = getConfig('distance-text');
  configs.labelBasic = getConfig('label-basic');
  configs.labelText = getConfig('label-text');
  configs.propertyBasic = getConfig('property-basic');
  configs.propertyText = getConfig('property-text');
  configs.coordinateBasic = getConfig('coordinate-basic');
  configs.coordinateText = getConfig('coordinate-text');
  configs.remenberSizeWidth = getConfig('remenber-size-width');
  configs.remenberSizeHeight = getConfig('remenber-size-height');
  configs.remenberSizeOverlayer = getConfig('remenber-size-overlayer');
  configs.remenberSpacingTop = getConfig('remenber-spacing-top');
  configs.remenberSpacingRight = getConfig('remenber-spacing-right');
  configs.remenberSpacingBottom = getConfig('remenber-spacing-bottom');
  configs.remenberSpacingLeft = getConfig('remenber-spacing-left');
  configs.remenberPropertyFont = getConfig('remenber-property-font');
  configs.remenberPropertySize = getConfig('remenber-property-size');
  configs.remenberPropertyColor = getConfig('remenber-property-color');
  configs.remenberPropertyLine = getConfig('remenber-property-line');
  configs.remenberPropertyBorder = getConfig('remenber-property-border');
  configs.remenberPropertyShadow = getConfig('remenber-property-shadow');
  configs.remenberPropertyInnerShadow = getConfig('remenber-property-inner-shadow');
  configs.remenberPropertyOpacity = getConfig('remenber-property-opacity');
  configs.remenberPropertyAt = getConfig('remenber-property-at');
}

initConfigs();<|endoftext|>