<commit_before>// @flow
import type { Placement, Boundary, RootBoundary } from '../enums';
import type { ModifierArguments, Modifier, Padding } from '../types';
import getOppositePlacement from '../utils/getOppositePlacement';
import getBasePlacement from '../utils/getBasePlacement';
import getOppositeVariationPlacement from '../utils/getOppositeVariationPlacement';
import detectOverflow from '../utils/detectOverflow';
import computeAutoPlacement from '../utils/computeAutoPlacement';
import uniqueBy from '../utils/uniqueBy';
import { bottom, top, start, right, left, auto } from '../enums';
import getVariation from '../utils/getVariation';

type Options = {
  fallbackPlacements: Array<Placement>,
  padding: Padding,
  boundary: Boundary,
  rootBoundary: RootBoundary,
  flipVariations: boolean,
};

function getExpandedFallbackPlacements(placement: Placement): Array<Placement> {
  if (getBasePlacement(placement) === auto) {
    return [];
  }

  const oppositePlacement = getOppositePlacement(placement);

  return [
    getOppositeVariationPlacement(placement),
    oppositePlacement,
    getOppositeVariationPlacement(oppositePlacement),
  ];
}

function flip({ state, options }: ModifierArguments<Options>) {
  const {
    fallbackPlacements: specifiedFallbackPlacements,
    padding,
    boundary,
    rootBoundary,
    flipVariations = true,
  } = options;

  const preferredPlacement = state.options.placement;
  const basePlacement = getBasePlacement(preferredPlacement);
  const isBasePlacement = basePlacement === preferredPlacement;

  const fallbackPlacements =
    specifiedFallbackPlacements ||
    (isBasePlacement
      ? [getOppositePlacement(preferredPlacement)]
      : getExpandedFallbackPlacements(preferredPlacement));

  const placements = uniqueBy(
    [preferredPlacement, ...fallbackPlacements].reduce((acc, placement) => {
      return getBasePlacement(placement) === auto
        ? acc.concat(
            computeAutoPlacement(state, {
              placement,
              boundary,
              rootBoundary,
              padding,
              flipVariations,
            })
          )
        : acc.concat(placement);
    }, []),
    placement => placement
  );

  const referenceRect = state.rects.reference;
  const popperRect = state.rects.popper;

  const placementOverflowData = placements.reduce((acc, placement) => {
    const basePlacement = getBasePlacement(placement);
    const isStartVariation = getVariation(placement) === start;
    const isVertical = [top, bottom].includes(basePlacement);
    const len = isVertical ? 'width' : 'height';

    const overflow = detectOverflow(state, {
      placement,
      boundary,
      rootBoundary,
      padding,
    });

    let mainVariationSide: any = isVertical
      ? isStartVariation
        ? right
        : left
      : isStartVariation
      ? bottom
      : top;

    if (referenceRect[len] > popperRect[len]) {
      mainVariationSide = getOppositePlacement(mainVariationSide);
    }

    const altVariationSide: any = getOppositePlacement(mainVariationSide);

    acc[placement] = [
      // checks
      overflow[basePlacement] <= 0,
      overflow[mainVariationSide] <= 0,
      overflow[altVariationSide] <= 0,
    ];

    return acc;
  }, {});

  // `2` may be desired in some cases – research later
  let checks = flipVariations ? 3 : 1;
  let firstFittingPlacement = placements[0];

  for (let i = checks; i >= 0; checks--) {
    const tryPlacement = placements.find(placement => {
      return placementOverflowData[placement]
        .slice(0, checks)
        .every(check => check);
    });

    if (tryPlacement) {
      firstFittingPlacement = tryPlacement;
      break;
    }
  }

  if (state.placement !== firstFittingPlacement) {
    state.placement = firstFittingPlacement;
    state.reset = true;
  }
}

export default ({
  name: 'flip',
  enabled: true,
  phase: 'main',
  fn: flip,
  requiresIfExists: ['offset'],
}: Modifier<Options>);
<commit_msg>perf: optimize flip modifier (#951)<commit_after>// @flow
import type { Placement, Boundary, RootBoundary } from '../enums';
import type { ModifierArguments, Modifier, Padding } from '../types';
import getOppositePlacement from '../utils/getOppositePlacement';
import getBasePlacement from '../utils/getBasePlacement';
import getOppositeVariationPlacement from '../utils/getOppositeVariationPlacement';
import detectOverflow from '../utils/detectOverflow';
import computeAutoPlacement from '../utils/computeAutoPlacement';
import uniqueBy from '../utils/uniqueBy';
import { bottom, top, start, right, left, auto } from '../enums';
import getVariation from '../utils/getVariation';

type Options = {
  fallbackPlacements: Array<Placement>,
  padding: Padding,
  boundary: Boundary,
  rootBoundary: RootBoundary,
  flipVariations: boolean,
};

function getExpandedFallbackPlacements(placement: Placement): Array<Placement> {
  if (getBasePlacement(placement) === auto) {
    return [];
  }

  const oppositePlacement = getOppositePlacement(placement);

  return [
    getOppositeVariationPlacement(placement),
    oppositePlacement,
    getOppositeVariationPlacement(oppositePlacement),
  ];
}

function flip({ state, options, name }: ModifierArguments<Options>) {
  if (state.modifiersData[name].skip) {
    return;
  }

  const {
    fallbackPlacements: specifiedFallbackPlacements,
    padding,
    boundary,
    rootBoundary,
    flipVariations = true,
  } = options;

  const preferredPlacement = state.options.placement;
  const basePlacement = getBasePlacement(preferredPlacement);
  const isBasePlacement = basePlacement === preferredPlacement;

  const fallbackPlacements =
    specifiedFallbackPlacements ||
    (isBasePlacement
      ? [getOppositePlacement(preferredPlacement)]
      : getExpandedFallbackPlacements(preferredPlacement));

  const placements = uniqueBy(
    [preferredPlacement, ...fallbackPlacements].reduce((acc, placement) => {
      return getBasePlacement(placement) === auto
        ? acc.concat(
            computeAutoPlacement(state, {
              placement,
              boundary,
              rootBoundary,
              padding,
              flipVariations,
            })
          )
        : acc.concat(placement);
    }, []),
    placement => placement
  );

  const referenceRect = state.rects.reference;
  const popperRect = state.rects.popper;

  const checksMap: Map<string, Array<boolean>> = new Map();
  let makeFallbackChecks = true;
  let firstFittingPlacement = placements[0];

  for (let i = 0; i < placements.length; i++) {
    const placement = placements[i];
    const basePlacement = getBasePlacement(placement);
    const isStartVariation = getVariation(placement) === start;
    const isVertical = [top, bottom].includes(basePlacement);
    const len = isVertical ? 'width' : 'height';

    const overflow = detectOverflow(state, {
      placement,
      boundary,
      rootBoundary,
      padding,
    });

    let mainVariationSide: any = isVertical
      ? isStartVariation
        ? right
        : left
      : isStartVariation
      ? bottom
      : top;

    if (referenceRect[len] > popperRect[len]) {
      mainVariationSide = getOppositePlacement(mainVariationSide);
    }

    const altVariationSide: any = getOppositePlacement(mainVariationSide);

    const checks = [
      overflow[basePlacement] <= 0,
      overflow[mainVariationSide] <= 0,
      overflow[altVariationSide] <= 0,
    ];

    if (checks.every(check => check)) {
      firstFittingPlacement = placement;
      makeFallbackChecks = false;
      break;
    }

    checksMap.set(placement, checks);
  }

  if (makeFallbackChecks) {
    // `2` may be desired in some cases – research later
    const numberOfChecks = flipVariations ? 3 : 1;

    for (let i = numberOfChecks; i > 0; i--) {
      const fittingPlacement = placements.find(placement => {
        const checks = checksMap.get(placement);
        if (checks) {
          return checks.slice(0, i).every(check => check);
        }
      });

      if (fittingPlacement) {
        firstFittingPlacement = fittingPlacement;
        break;
      }
    }
  }

  if (state.placement !== firstFittingPlacement) {
    state.modifiersData[name].skip = true;
    state.placement = firstFittingPlacement;
    state.reset = true;
  }
}

export default ({
  name: 'flip',
  enabled: true,
  phase: 'main',
  fn: flip,
  requiresIfExists: ['offset'],
  data: { skip: false },
}: Modifier<Options>);
<|endoftext|>


<commit_before>kernel.module.manager = def(
  [
    kernel.fp.array,
    kernel.fp.object,
    kernel.module.loader,
    kernel.module.fetcher
  ],

  function (ar, obj, loader, fetcher) {
    var create = function (modulator, onerror) {
      var blueprints = {};  // id -> {id: string, dependencies: [string], definition: function}
      var modules = {};     // id -> module

      var validator = function (id) { return blueprints[id] !== undefined; };
      var fetcherer = fetcher.create(modulator, validator, onerror);

      var define = function (id, dependencies, definition) {
        if (blueprints[id] !== undefined)
          onerror("Define error: module '" + id + "' is already defined");
        else
          blueprints[id] = { id: id, dependencies: dependencies, definition: definition };
      };

      var require = function (ids, callback) {
        var onsuccess = function () {
          var instances = ar.map(ids, demand);
          callback.apply(null, instances);
        };

        var oncontinue = function () {
          var deps = obj.map(blueprints, function (k, v) {
            return v.dependencies;
          });
          loader.load(ids, deps, fetcherer, oncontinue, onsuccess, onerror);
        };

        oncontinue();
      };

      // Instantiates a module and all of its dependencies.
      var demand = function (id) {
        if (modules[id] !== undefined)
          return modules[id];
        if (blueprints[id] === undefined)
          throw "module '" + id + "' is not defined";
        var blueprint = blueprints[id];
        var args = ar.map(blueprint.dependencies, demand);  // Instantiate dependencies
        var result = blueprint.definition.apply(null, args);  // Instantiate self
        if (result === undefined)
          throw "module '" + id + "' returned undefined from definition function";
        modules[id] = result;
        return result;
      };

      return {
        define: define,
        require: require,
        demand: demand
      };
    };

    return {
      create: create
    };
  }
);
<commit_msg>undefined check for define module id<commit_after>kernel.module.manager = def(
  [
    kernel.fp.array,
    kernel.fp.object,
    kernel.module.loader,
    kernel.module.fetcher
  ],

  function (ar, obj, loader, fetcher) {
    var create = function (modulator, onerror) {
      var blueprints = {};  // id -> {id: string, dependencies: [string], definition: function}
      var modules = {};     // id -> module

      var validator = function (id) { return blueprints[id] !== undefined; };
      var fetcherer = fetcher.create(modulator, validator, onerror);

      var define = function (id, dependencies, definition) {
        if (id === undefined)
          onerror("Define error: module id can not be undefined");
        else if (blueprints[id] !== undefined)
          onerror("Define error: module '" + id + "' is already defined");
        else
          blueprints[id] = { id: id, dependencies: dependencies, definition: definition };
      };

      var require = function (ids, callback) {
        var onsuccess = function () {
          var instances = ar.map(ids, demand);
          callback.apply(null, instances);
        };

        var oncontinue = function () {
          var deps = obj.map(blueprints, function (k, v) {
            return v.dependencies;
          });
          loader.load(ids, deps, fetcherer, oncontinue, onsuccess, onerror);
        };

        oncontinue();
      };

      // Instantiates a module and all of its dependencies.
      var demand = function (id) {
        if (modules[id] !== undefined)
          return modules[id];
        if (blueprints[id] === undefined)
          throw "module '" + id + "' is not defined";
        var blueprint = blueprints[id];
        var args = ar.map(blueprint.dependencies, demand);  // Instantiate dependencies
        var result = blueprint.definition.apply(null, args);  // Instantiate self
        if (result === undefined)
          throw "module '" + id + "' returned undefined from definition function";
        modules[id] = result;
        return result;
      };

      return {
        define: define,
        require: require,
        demand: demand
      };
    };

    return {
      create: create
    };
  }
);
<|endoftext|>


<commit_before>// alguns métodos não devem ser herdados por todos, como check e uncheck. Ver como isso seria resolvido sem comprometimento do padrão builder

var
    // mudar para APIece ("apaiês")
    esPhinx,
    Iterable,
    Extender,
    SearchContext,
    Search;

// IIFE
(function($module) {
    "use strict";

    var
        NAME = "esPhinx",

        selectInBreadth = function(iterable, callback) {
            var
                returned,
                strategy,
                selected = [];

            if (iterable instanceof window.Node) {
                strategy = SearchContext.Proxy.new(Search.Graphs.BFS.Element
                                                   .new(iterable));
            } else {
                strategy = SearchContext.Proxy.new(Search.Graphs.BFS.Object
                                                   .new(iterable));
            }

            strategy.research(function(value, key, trace) {
                if (value instanceof window.Node) {
                    returned = callback.call(iterable, value, key);
                } else {
                    returned = callback.call(iterable, value, key, trace);
                }

                if (returned) {
                    selected.push(value);
                }
            });

            return selected;
        },

        resolveContext = function(context) {
            if (typeof context == "object") {
                if (context instanceof esPhinx ||
                    context instanceof Element) {
                    return context;
                }
            } else if (typeof context == "string") {
                // recursivity
                return esPhinx(context);
            }

            return window.document;
        };

    if (!$module["esPhinx"]) {
        try {
            Object.defineProperties($module, {

                esPhinx: {

                    // ver por que o nome na função está sendo necessário para alguns casos
                    value: function esPhinx(selector, context) {
                    // value: (function esPhinx(selector, context) {

                        var
                            self = esPhinx,
                            mainReference = this,
                            collection = [],

                            hasElement = function(iterable) {
                                var
                                    iterator,
                                    response = false;

                                iterator = Iterable.Proxy.new(iterable);
                                iterator.each(function(object) {
                                    if (object instanceof window.Element) {
                                        this.finalize();
                                        response = true;
                                    }
                                });
                                return response;
                            };

                        if (!(mainReference instanceof self)) {
                            return new self(selector, context);
                        }

                        context = resolveContext(context);

                        if (selector) {
                            if (selector instanceof self) {
                                return selector;
                            } else if (typeof selector == "function") {
                                // don't never pass a autoexecutable function as parameter
                                return window.document
                                    .addEventListener("DOMContentLoaded",
                                                      function(e) {
                                    selector.call(self, self, e);
                                });
                            // get children "".match(/(>)(<.(?=(<\/)))/)[0]
                            // add support to XPath
                            } else if (typeof selector == "string") {
                                collection = Array.from((new window.DOMParser())
                                    .parseFromString(selector, "text/html").body
                                    .childNodes);
                                // debugger
                                if (!hasElement(collection)) {
                                    collection = [];
                                    if (Iterable.isIterable(context)) {
                                        Array.from(context)
                                            .forEach(function(node) {
                                            collection = collection.concat(Array
                                                .from(node
                                                .querySelectorAll(selector)))
                                            .flatten();
                                        });
                                    } else {
                                        try {
                                            collection = Array.from(context
                                                .querySelectorAll(selector));
                                        } catch (e) {}
                                    }
                                }
                            } else if (selector instanceof window.Node) {
                                collection = [selector];
                            } else if (selector instanceof Object) {
                                collection = Array.from(selector);

                                if (selector.constructor !=
                                    window.HTMLCollection &&
                                    collection.length) {
                                    mainReference[0] = selector;

                                    if (selector == window) {
                                        collection = [];
                                    }
                                }
                            }

                            Object.assign(mainReference, collection);
                        }

                        Object.defineProperties(mainReference, {
                            splice: {
                                value: Array.prototype.splice
                            },

                            toString: {
                                value: function() {
                                    return "[object " + NAME + "]";
                                }
                            }
                        });
                        Iterable.toIterable(mainReference);

                        return mainReference;
                    }

                }

            });
        } catch(e) {};

        Object.defineProperties(esPhinx, {
            Extender: {
                value: {},
                enumerable: true
            }
        });
    }

    Extender.new(esPhinx.Extender, true, {
        new: function(object, final, structure) {
            Extender.new(object, final, structure);
        }
    });

    esPhinx.Extender.new(esPhinx, true, {
        extend: function() {
            // debugger
            this.Extender.new(this, arguments[0], arguments[1]);
        }
    });

    esPhinx.Extender.new(esPhinx.prototype, true, {
        extend: function() {
            // debugger
            esPhinx.Extender.new(this, arguments[0], arguments[1]);
        }
    });

    esPhinx.extend(true, {

        selectByText: function(text, context) {
            var
                collection = [];

            this.select(this(resolveContext(context)), function(element) {
                collection = collection.concat(document.evaluate(
                    "descendant-or-self::*[normalize-space(text())='" +
                    text.trim() + "']", element).elements()).flatten();
            });

            return esPhinx(collection);
        },

        isIterable: function(object) {
            return isIterable(object);
        },

        selectInBreadth: function(collection, callback) {
            return selectInBreadth(collection, callback);
        },

        each: function(collection, startIndex, callback) {
            var
                iterator = Iterable.Proxy.new(collection);

            if (typeof startIndex == "function" ) {
                callback = startIndex;
            }

            iterator.each(startIndex, function(item, i) {
                callback.call(this, item, i);
            });
        },

        reverseEach: function(collection, startIndex, callback) {
            var
                iterator = Iterable.Proxy.new(collection);

            if (typeof startIndex == "function") {
                callback = startIndex;
            }

            iterator.reverseEach(startIndex, function(item, i) {
                callback.call(this, item, i);
            });
        },

        select: function(collection, callback) {
            var
                returned,
                selected = [];

            esPhinx.each(collection, function(item, i) {
                returned = callback.call(collection, item, i);

                if (returned) {
                    selected.push(item);
                }
            });

            return selected;
        }

    });

})(window);

// recognize element attributes and properties

// recognize a element
// ^( *<)[a-z]+((\/)|(>.*<\/[a-z]+))(> *)$

// recognize attributes
// ((?: )+([a-z]+[-_a-z]*) *(= *(((?=").+")|((?=').+')|((?=\\").+\\")|((?=\\').+\\'))( *|(\/?>)))*)
<commit_msg>comment<commit_after>// alguns métodos não devem ser herdados por todos, como check e uncheck. Ver como isso seria resolvido sem comprometimento do padrão builder

var
    // mudar para APIece ("apaiês")
    esPhinx,
    Iterable,
    Extender,
    SearchContext,
    Search;

// IIFE
(function($module) {
    "use strict";

    var
        NAME = "esPhinx",

        selectInBreadth = function(iterable, callback) {
            var
                returned,
                strategy,
                selected = [];

            if (iterable instanceof window.Node) {
                strategy = SearchContext.Proxy.new(Search.Graphs.BFS.Element
                                                   .new(iterable));
            } else {
                strategy = SearchContext.Proxy.new(Search.Graphs.BFS.Object
                                                   .new(iterable));
            }

            strategy.research(function(value, key, trace) {
                if (value instanceof window.Node) {
                    returned = callback.call(iterable, value, key);
                } else {
                    returned = callback.call(iterable, value, key, trace);
                }

                if (returned) {
                    selected.push(value);
                }
            });

            return selected;
        },

        resolveContext = function(context) {
            if (typeof context == "object") {
                if (context instanceof esPhinx ||
                    context instanceof Element) {
                    return context;
                }
            } else if (typeof context == "string") {
                // recursivity
                return esPhinx(context);
            }

            return window.document;
        };

    if (!$module["esPhinx"]) {
        try {
            Object.defineProperties($module, {

                esPhinx: {

                    // ver por que o nome na função está sendo necessário para alguns casos
                    value: function esPhinx(selector, context) {
                    // value: (function esPhinx(selector, context) {

                        var
                            self = esPhinx,
                            mainReference = this,
                            collection = [],

                            hasElement = function(iterable) {
                                var
                                    iterator,
                                    response = false;

                                iterator = Iterable.Proxy.new(iterable);
                                iterator.each(function(object) {
                                    if (object instanceof window.Element) {
                                        this.finalize();
                                        response = true;
                                    }
                                });
                                return response;
                            };

                        if (!(mainReference instanceof self)) {
                            return new self(selector, context);
                        }

                        context = resolveContext(context);

                        if (selector) {
                            if (selector instanceof self) {
                                return selector;
                            } else if (typeof selector == "function") {
                                // don't never pass a autoexecutable function as parameter
                                return window.document
                                    .addEventListener("DOMContentLoaded",
                                                      function(e) {
                                    selector.call(self, self, e);
                                });
                            // get children "".match(/(>)(<.(?=(<\/)))/)[0]
                            // add support to XPath
                            } else if (typeof selector == "string") {
                                collection = Array.from((new window.DOMParser())
                                    .parseFromString(selector, "text/html").body
                                    .childNodes);
                                // debugger
                                if (!hasElement(collection)) {
                                    collection = [];
                                    if (Iterable.isIterable(context)) {
                                        Array.from(context)
                                            .forEach(function(node) {
                                            collection = collection.concat(Array
                                                .from(node
                                                .querySelectorAll(selector)))
                                            .flatten();
                                        });
                                    } else {
                                        try {
                                            collection = Array.from(context
                                                .querySelectorAll(selector));
                                        } catch (e) {}
                                    }
                                }
                            } else if (selector instanceof window.Node) {
                                collection = [selector];
                            } else if (selector instanceof Object) {
                                collection = Array.from(selector);

                                if (selector.constructor !=
                                    window.HTMLCollection &&
                                    collection.length) {
                                    mainReference[0] = selector;

                                    if (selector == window) {
                                        collection = [];
                                    }
                                }
                            }

                            Object.assign(mainReference, collection);
                        }

                        Object.defineProperties(mainReference, {
                            splice: {
                                value: Array.prototype.splice
                            },

                            toString: {
                                value: function() {
                                    return "[object " + NAME + "]";
                                }
                            }
                        });
                        Iterable.toIterable(mainReference);

                        return mainReference;
                    }

                }

            });
        } catch(e) {};

        Object.defineProperties(esPhinx, {
            Extender: {
                value: {},
                enumerable: true
            }
        });
    }

    Extender.new(esPhinx.Extender, true, {
        new: function(object, final, structure) {
            Extender.new(object, final, structure);
        }
    });

    esPhinx.Extender.new(esPhinx, true, {
        extend: function() {
            // debugger
            this.Extender.new(this, arguments[0], arguments[1]);
        }
    });

    esPhinx.Extender.new(esPhinx.prototype, true, {
        extend: function() {
            // debugger
            esPhinx.Extender.new(this, arguments[0], arguments[1]);
        }
    });

    esPhinx.extend(true, {

        selectByText: function(text, context) {
            var
                collection = [];

            this.select(this(resolveContext(context)), function(element) {
                collection = collection.concat(document.evaluate(
                    "descendant-or-self::*[normalize-space(text())='" +
                    text.trim() + "']", element).elements()).flatten();
            });

            return esPhinx(collection);
        },

        isIterable: function(object) {
            return isIterable(object);
        },

        selectInBreadth: function(collection, callback) {
            return selectInBreadth(collection, callback);
        },

        each: function(collection, startIndex, callback) {
            var
                iterator = Iterable.Proxy.new(collection);

            if (typeof startIndex == "function" ) {
                callback = startIndex;
            }

            iterator.each(startIndex, function(item, i) {
                callback.call(this, item, i);
            });
        },

        reverseEach: function(collection, startIndex, callback) {
            var
                iterator = Iterable.Proxy.new(collection);

            if (typeof startIndex == "function") {
                callback = startIndex;
            }

            iterator.reverseEach(startIndex, function(item, i) {
                callback.call(this, item, i);
            });
        },

        select: function(collection, callback) {
            var
                returned,
                selected = [];

            esPhinx.each(collection, function(item, i) {
                returned = callback.call(collection, item, i);

                if (returned) {
                    selected.push(item);
                }
            });

            return selected;
        }

    });

})(window);

// recognize element, his attributes, properties and his values

// recognize a element
// ^( *<)[a-z]+ *((\/)|(>.*<\/[a-z]+))(> *)$

// recognize attributes and values
// (([\w\$][\-]*)+ *= *(((?=").+")|((?=').+')|((?=\\").+\\")|((?=\\').+\\')))|([\w\$][\-]*)+
<|endoftext|>


<commit_before>"use strict";

var
    esPhinx;

(function ($) {

    $.extend({

        prototype: {

            //
|

            // text: function () {
            // },

            hasClass: function (classList) {
                var
                    self = this,
                    first = $(self.first()),
                    pattern;

                if (arguments.length > 1) {
                    classList = Array.prototype.slice.call(arguments);
                    pattern = new RegExp("\\b((" + classList
                        .join(")|(")  + "))(?=(\\b| ))", "g");
                } else {
                    pattern = new RegExp("\\b((" + classList.split(" ")
                        .join(")|(") + "))(?=(\\b| ))", "g");
                }

                if (pattern.test(first.attr("class"))) {
                    return true;
                }

                return false;
            },

            removeClass: function (classList) {
                var
                    self = this,
                    currentClassList,
                    pattern,
                    removed;

                if (arguments.length > 1) {
                    classList = Array.prototype.slice.call(arguments);
                    pattern = new RegExp("\\b((" + classList
                        .join(")|(")  + "))(?=(\\b| ))", "g");
                } else {
                    pattern = new RegExp("\\b((" + classList.split(" ")
                        .join(")|(") + "))(?=(\\b| ))", "g");
                }

                self.each(function (node) {
                    currentClassList = $(node).attr("class");
                    removed = currentClassList.replace(pattern, "");
                    $(node).attr("class", removed.replace(/(  )+/g, " ").trim());
                });

                return self;
            },

            addClass: function (classList) {
                var
                    self = this,
                    currentClassList,
                    asString;

                if (arguments.length > 1) {
                    classList = Array.prototype.slice.call(arguments);
                    asString = classList.join(" ");
                } else if (typeof classList === "string") {
                    asString = classList;
                }

                self.each(function (node) {
                    currentClassList = $(node).attr("class");
                    $(node).attr("class", currentClassList + " " + asString);
                });

                return self;
            },

            find: function (query) {
                var
                    self = this;

                return $(query, self.first());
            },

            check: function () {
                var
                    self = this;

                if (!self.checked()) {
                    self.property("checked", true);
                }

                return self;
            },

            uncheck: function () {
                var
                    self = this;

                return self.property("checked", false);
            },

            removeAttr: function (attrName) {
                var
                    self = this;

                self.each(function (node) {
                    node.removeAttribute(attrName);
                });

                return self;
            },

            attr: function (attrName, value) {
                var
                    self = this,
                    first = self.first();

                if (self.length === 0) {
                    return self;
                }

                if (typeof value === "boolean" || value || value === "") {
                    self.each(function (node) {
                        node.setAttribute(attrName, value);
                    });

                    return self;
                } else {
                    if (first.attributes[attrName]) {
                        return first.attributes[attrName].value;
                    }
                }

                return undefined;
            },

            property: function (propertyName, value) {
                var
                    self = this,
                    first = self.first();

                if (self.length === 0) {
                    return self;
                }

                if (typeof value === "boolean" || value || value === "") {
                    self.each(function (node) {
                        node[propertyName] = value;
                    });

                    return self;
                } else {
                    if (first[propertyName] ||
                        typeof first[propertyName] === "boolean") {
                        return first[propertyName];
                    }
                }

                return undefined;
            },

            firstNode: function () {
                var
                    self = this,
                    nodes = self.first().childNodes;

                return $(nodes[0]);
            },

            firstElement: function () {
                var
                    self = this,
                    elements = self.first().children;

                return $(elements[0]);
            },

            rootText: function () {
                var
                    self = this,
                    text = "";

                Enumerator.each(self.first().childNodes, function (v) {
                    if (v.nodeType === Node.TEXT_NODE) {
                        text += v.textContent.trim();
                    }
                });

                return text;
            },

            append: function(node) {
                var
                    self = this;

                if (typeof node === "string") {
                    node = document.createTextNode(node);
                } else if (node instanceof $) {
                    node = node.first();
                } else if (!node instanceof Node) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                self.each(function (element) {
                    element.appendChild(node);
                });

                return self;
            },

            prepend: function(node) {
                var
                    self = this,
                    firstNode;

                if (typeof node === "string") {
                    node = document.createTextNode(node);
                } else if (node instanceof $) {
                    node = node.first();
                } else if (!node instanceof Node) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                self.each(function (element) {
                    firstNode = $(element).firstNode();
                    $(node).insertBefore(firstNode);
                });

                return self;
            },

            insertBefore: function(node) {
                var
                    self = this;

                if (typeof node === "string") {
                    node = $(node).first();
                } else if (node instanceof $) {
                    node = node.first();
                } else if (!node instanceof Node) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                node.parentNode.insertBefore(self.first(), node);

                return self;
            },

            insertAfter: function(node) {
                var
                    self = this;

                if (typeof node === "string") {
                    node = $(node).first();
                } else if (node instanceof $) {
                    node = node.first();
                } else if (!node instanceof Node) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                node.parentNode.insertBefore(self.first(), node.nextSibling);

                return self;
            },

            parent: function (query) {
                var
                    self = this;

                if (query) {
                    return $(self.first().closest(query));
                } else {
                    return $(self.first().parentNode);
                }

                return $();
            },

            html: function (content) {
                var
                    self = this;

                if (typeof content === "string") {
                    self.each(function (node) {
                        node.innerHTML = content;
                    });
                } else if (content instanceof Node) {
                    self.each(function (node) {
                        node.innerHTML = null;
                        node.appendChild(content);
                    });
                }

                return self;
            },

            first: function () {
                return this[0];
            },

            count: function () {
                return Object.keys(this).length;
            }

        }

    });

}(esPhinx));

/*$.prototype.ancestors = function (nodeName) {
        var _parents = []
            ,parent = null
        ;
        collection.forEach(function (e) {
            parent = e.parentNode;
            if (nodeName) {
                if (parent.nodeName.toLowerCase() === nodeName) {
                    _parents.push(parent);
                } else {
                    while(true) {
                        parent = parent.parentNode;
                        if(parent){
                            if(parent.nodeName.toLowerCase() === nodeName) {
                                _parents.push(parent);
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                }
            } else {
                if(parent){
                    _parents.push(parent);
                }
            }
        });
        return _parents;
    }*/<commit_msg>improves addClass<commit_after>"use strict";

var
    esPhinx;

(function ($) {

    $.extend({

        prototype: {

            //
|

            // text: function () {
            // },

            hasClass: function (classList) {
                var
                    self = this,
                    first = $(self.first()),
                    pattern;

                if (arguments.length > 1) {
                    classList = Array.prototype.slice.call(arguments);
                    pattern = new RegExp("\\b((" + classList
                        .join(")|(")  + "))(?=(\\b| ))", "g");
                } else {
                    pattern = new RegExp("\\b((" + classList.split(" ")
                        .join(")|(") + "))(?=(\\b| ))", "g");
                }

                if (pattern.test(first.attr("class"))) {
                    return true;
                }

                return false;
            },

            removeClass: function (classList) {
                var
                    self = this,
                    currentClassList,
                    pattern,
                    removed;

                if (arguments.length > 1) {
                    classList = Array.prototype.slice.call(arguments);
                    pattern = new RegExp("\\b((" + classList
                        .join(")|(")  + "))(?=(\\b| ))", "g");
                } else {
                    pattern = new RegExp("\\b((" + classList.split(" ")
                        .join(")|(") + "))(?=(\\b| ))", "g");
                }

                self.each(function (node) {
                    currentClassList = $(node).attr("class");
                    removed = currentClassList.replace(pattern, "");
                    $(node).attr("class", removed.replace(/(  )+/g, " ").trim());
                });

                return self;
            },

            addClass: function (classList) {
                var
                    self = this,
                    currentClassList,
                    asString;

                if (arguments.length > 1) {
                    classList = Array.prototype.slice.call(arguments);
                    asString = classList.join(" ");
                } else if (typeof classList === "string") {
                    asString = classList;
                }

                self.each(function (node) {
                    currentClassList = $(node).attr("class");
                    $(node).attr("class", (currentClassList + " " + asString)
                        .trim());
                });

                return self;
            },

            find: function (query) {
                var
                    self = this;

                return $(query, self.first());
            },

            check: function () {
                var
                    self = this;

                if (!self.checked()) {
                    self.property("checked", true);
                }

                return self;
            },

            uncheck: function () {
                var
                    self = this;

                return self.property("checked", false);
            },

            removeAttr: function (attrName) {
                var
                    self = this;

                self.each(function (node) {
                    node.removeAttribute(attrName);
                });

                return self;
            },

            attr: function (attrName, value) {
                var
                    self = this,
                    first = self.first();

                if (self.length === 0) {
                    return self;
                }

                if (typeof value === "boolean" || value || value === "") {
                    self.each(function (node) {
                        node.setAttribute(attrName, value);
                    });

                    return self;
                } else {
                    if (first.attributes[attrName]) {
                        return first.attributes[attrName].value;
                    }
                }

                return undefined;
            },

            property: function (propertyName, value) {
                var
                    self = this,
                    first = self.first();

                if (self.length === 0) {
                    return self;
                }

                if (typeof value === "boolean" || value || value === "") {
                    self.each(function (node) {
                        node[propertyName] = value;
                    });

                    return self;
                } else {
                    if (first[propertyName] ||
                        typeof first[propertyName] === "boolean") {
                        return first[propertyName];
                    }
                }

                return undefined;
            },

            firstNode: function () {
                var
                    self = this,
                    nodes = self.first().childNodes;

                return $(nodes[0]);
            },

            firstElement: function () {
                var
                    self = this,
                    elements = self.first().children;

                return $(elements[0]);
            },

            rootText: function () {
                var
                    self = this,
                    text = "";

                Enumerator.each(self.first().childNodes, function (v) {
                    if (v.nodeType === Node.TEXT_NODE) {
                        text += v.textContent.trim();
                    }
                });

                return text;
            },

            append: function(node) {
                var
                    self = this;

                if (typeof node === "string") {
                    node = document.createTextNode(node);
                } else if (node instanceof $) {
                    node = node.first();
                } else if (!node instanceof Node) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                self.each(function (element) {
                    element.appendChild(node);
                });

                return self;
            },

            prepend: function(node) {
                var
                    self = this,
                    firstNode;

                if (typeof node === "string") {
                    node = document.createTextNode(node);
                } else if (node instanceof $) {
                    node = node.first();
                } else if (!node instanceof Node) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                self.each(function (element) {
                    firstNode = $(element).firstNode();
                    $(node).insertBefore(firstNode);
                });

                return self;
            },

            insertBefore: function(node) {
                var
                    self = this;

                if (typeof node === "string") {
                    node = $(node).first();
                } else if (node instanceof $) {
                    node = node.first();
                } else if (!node instanceof Node) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                node.parentNode.insertBefore(self.first(), node);

                return self;
            },

            insertAfter: function(node) {
                var
                    self = this;

                if (typeof node === "string") {
                    node = $(node).first();
                } else if (node instanceof $) {
                    node = node.first();
                } else if (!node instanceof Node) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                node.parentNode.insertBefore(self.first(), node.nextSibling);

                return self;
            },

            parent: function (query) {
                var
                    self = this;

                if (query) {
                    return $(self.first().closest(query));
                } else {
                    return $(self.first().parentNode);
                }

                return $();
            },

            html: function (content) {
                var
                    self = this;

                if (typeof content === "string") {
                    self.each(function (node) {
                        node.innerHTML = content;
                    });
                } else if (content instanceof Node) {
                    self.each(function (node) {
                        node.innerHTML = null;
                        node.appendChild(content);
                    });
                }

                return self;
            },

            first: function () {
                return this[0];
            },

            count: function () {
                return Object.keys(this).length;
            }

        }

    });

}(esPhinx));

/*$.prototype.ancestors = function (nodeName) {
        var _parents = []
            ,parent = null
        ;
        collection.forEach(function (e) {
            parent = e.parentNode;
            if (nodeName) {
                if (parent.nodeName.toLowerCase() === nodeName) {
                    _parents.push(parent);
                } else {
                    while(true) {
                        parent = parent.parentNode;
                        if(parent){
                            if(parent.nodeName.toLowerCase() === nodeName) {
                                _parents.push(parent);
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                }
            } else {
                if(parent){
                    _parents.push(parent);
                }
            }
        });
        return _parents;
    }*/<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;

module.exports = function augmentFunctionWithEventEmitter(func) {
    var augmentedFunc = func;

    EventEmitter.call(augmentedFunc);
    augmentedFunc.emit = EventEmitter.prototype.emit;
    augmentedFunc.on = EventEmitter.prototype.on;

    var wrappedFunc = function () {
        return augmentedFunc.apply(augmentedFunc, arguments);
    };

    wrappedFunc.on = augmentedFunc.on.bind(augmentedFunc);
    wrappedFunc.emit = augmentedFunc.emit.bind(augmentedFunc);

    return wrappedFunc;
};
<commit_msg>add comments to augmentFunctionWithEventEmitter<commit_after>var EventEmitter = require('events').EventEmitter;

module.exports = function augmentFunctionWithEventEmitter(func) {
    // First we augment the function with the necessary methods from
    // EventEmitter. Be aware that the function wont be an instance of
    // EventEmitter even though it will act like one.
    var augmentedFunc = func;

    EventEmitter.call(augmentedFunc);
    augmentedFunc.emit = EventEmitter.prototype.emit;
    augmentedFunc.on = EventEmitter.prototype.on;

    // In order to give the augmented function the correct context for
    // this, it needs to be applied on it self. This is done in the
    // wrapped method below, which is what will be returned from this
    // method.
    var wrappedFunc = function () {
        return augmentedFunc.apply(augmentedFunc, arguments);
    };

    // The on and emit methods on the wrappedFunction should be the
    // same as those on the augmented function that is returned from
    // the wrapped method.
    wrappedFunc.on = augmentedFunc.on.bind(augmentedFunc);
    wrappedFunc.emit = augmentedFunc.emit.bind(augmentedFunc);

    return wrappedFunc;
};
<|endoftext|>


<commit_before>// Init navit
//
'use strict';

/*global window, TEST*/
const _       = require('lodash');
const url     = require('url');

module.exports = function (N) {

  function navitPlugins(navit) {

    // Authenticate user by login. You should reload page after use this or use before `.open`
    //
    // - login (String) - if empty - do logout, if exists - login, if not exists - create and login
    // - callback(user) (Function) - optional
    //
    navit.registerMethod('do.auth', function do_auth(login, fn) {
      let userLogin = _.isFunction(login) ? login() : login;
      let domain = url.parse(TEST.N.config.bind.default.mount).hostname;

      // If `login` not specified - do logout
      if (!userLogin) {
        this.cookie({
          name: 'sid',
          value: '',
          domain,
          expires: Date.now() - 1000
        });

        return this;
      }

      let cookieObj = {
        name: 'sid',
        value: '', // changed by a function below
        domain,
        httponly: true,
        secure: false,
        expires: (new Date()).getTime() + (1000 * 60 * 60 * 24 * 365) // expires in 1 year
      };

      this.fn(async function auth() {
        let user = await TEST.N.models.users.User
                                 .findOne({ nick: userLogin })
                                 .lean(false); // some tests use user.save()

        // Create user entry if it doesn't exist
        //
        if (!user) {
          user = new TEST.N.models.users.User({ nick: userLogin });

          await user.save();
        }

        // Create user session auth record
        //
        let authSession = await TEST.N.models.users.AuthSession
                                  .findOne({ user: user._id })
                                  .lean(true);

        if (!authSession) {
          authSession = new TEST.N.models.users.AuthSession({ user: user._id });

          await authSession.save();
        }

        cookieObj.value = authSession.session_id;

        // Invoke callback for `do.auth(login, callback)`
        //
        if (fn) fn(user);

      });

      // Set cookie
      //
      this.cookie(function () {
        return cookieObj;
      });

      return this;
    });

    // Wait for nodeca scripts load and check status
    //
    navit.batch.create('waitNodecaBooted', function () {
      this
        .wait(function () {
          try {
            return window.NodecaLoader.booted;
          } catch (__) {}
          return false;
        })
        .test.status(200);
    });

    navit.afterOpen = function () {
      this.batch('waitNodecaBooted');
    };
  }

  N.wire.on('init:tests', function init_navit() {
    // Should not require this package on production installs
    const navit   = require('navit');

    global.TEST.browser = navit({
      engine: 'electron',
      timeout: 20000 // Increase waiting timeout, 5000ms not enougth for tests.
    })
    .use(navitPlugins);

    N.wire.before([ 'exit.shutdown', 'exit.terminate' ], function navit_shutdown(__, callback) {
      TEST.browser.exit(() => callback());
    });
  });
};
<commit_msg>navit: fix cookie set failure in `do.auth`<commit_after>// Init navit
//
'use strict';

/*global window, TEST*/
const _       = require('lodash');
const url     = require('url');

module.exports = function (N) {

  function navitPlugins(navit) {

    // Authenticate user by login. You should reload page after use this or use before `.open`
    //
    // - login (String) - if empty - do logout, if exists - login, if not exists - create and login
    // - callback(user) (Function) - optional
    //
    navit.registerMethod('do.auth', function do_auth(login, fn) {
      let userLogin = _.isFunction(login) ? login() : login;
      let domain = url.parse(TEST.N.config.bind.default.mount).hostname;

      // If `login` not specified - do logout
      if (!userLogin) {
        this.cookie({
          name: 'sid',
          value: '',
          domain,
          expires: Date.now() - 1000
        });

        return this;
      }

      let cookieObj = {
        name: 'sid',
        value: '', // changed by a function below
        domain,
        httponly: true,
        secure: false,
        expires: (new Date()).getTime() + (1000 * 60 * 60 * 24 * 365) // expires in 1 year
      };

      this.fn(async function auth() {
        let user = await TEST.N.models.users.User
                                 .findOne({ nick: userLogin })
                                 .lean(false); // some tests use user.save()

        // Create user entry if it doesn't exist
        //
        if (!user) {
          user = new TEST.N.models.users.User({ nick: userLogin });

          await user.save();
        }

        // Create user session auth record
        //
        let authSession = await TEST.N.models.users.AuthSession
                                  .findOne({ user: user._id })
                                  .lean(true);

        if (!authSession) {
          authSession = new TEST.N.models.users.AuthSession({ user: user._id });

          await authSession.save();
        }

        cookieObj.value = authSession.session_id;

        // Invoke callback for `do.auth(login, callback)`
        //
        if (fn) fn(user);

      });

      // Delete cookie first, because override may fail if previous garbage
      // exists with different security settings.
      //
      this.cookie(function () {
        return Object.assign({}, cookieObj, { expires: 0 });
      });

      // Set cookie
      //
      this.cookie(function () {
        return cookieObj;
      });

      return this;
    });

    // Wait for nodeca scripts load and check status
    //
    navit.batch.create('waitNodecaBooted', function () {
      this
        .wait(function () {
          try {
            return window.NodecaLoader.booted;
          } catch (__) {}
          return false;
        })
        .test.status(200);
    });

    navit.afterOpen = function () {
      this.batch('waitNodecaBooted');
    };
  }

  N.wire.on('init:tests', function init_navit() {
    // Should not require this package on production installs
    const navit   = require('navit');

    global.TEST.browser = navit({
      engine: 'electron',
      timeout: 20000 // Increase waiting timeout, 5000ms not enougth for tests.
    })
    .use(navitPlugins);

    N.wire.before([ 'exit.shutdown', 'exit.terminate' ], function navit_shutdown(__, callback) {
      TEST.browser.exit(() => callback());
    });
  });
};
<|endoftext|>


<commit_before>/**
 * ------------------------------------------
 * 桌面接口实现文件
 * @version  1.0
 * @author   yuqijun(yuqijun@corp.netease.com)
 * ------------------------------------------
 */
var f = function() {
    // variable declaration
    var _ = NEJ.P,
        _o = NEJ.O,
        _e = _('nej.e'),
        _u = _('nej.u'),
        _v = _('nej.v'),
        _n = _('nej.n'),
        _p = _('nej.cef');
    /**
     * 配置窗体信息
     * @see    {nej.cef._$configWindowPosition}
     * @see    {nej.cef._$configWindowSizeLimit}
     * @param  {Object} 配置信息，其他参数详情见@see指定接口配置信息
     * @return {Void}
     */
    _p._$configWindow = function(_options){
        _p._$configWindowSizeLimit(_options);
        _p._$configWindowPosition(_options);
    };
    /**
     * 配置窗体位置，对齐方式定义如下

     * 水平对齐方式：
     * [ntb]
     *   名称            |  描述
     *   ----------------------
     *   left   |  左侧对齐
     *   center |  中间对齐
     *   right  |  右侧对齐
     * [/ntb]
     *
     * 垂直对齐方式：
     * [ntb]
     *   名称              |  描述
     *   ---------------------
     *   top     |  顶部对齐
     *   center  |  中间对齐
     *   bottom  |  底部对齐
     * [/ntb]
     * @api    {nej.cef._$configWindowPosition}
     * @param  {Object} 配置信息
     * @config {String}  name     窗体名称
     * @config {Number}  width    窗体宽度
     * @config {Number}  height   窗体高度
     * @config {Boolean} topmost  窗体是否置顶
     * @config {String}  align    对齐方式，格式定义：水平对齐方式+空格+垂直对齐方式，如 left top
     * @return {Void}
     */
    _p._$configWindowPosition = (function(){
        var _reg0 = /\s+/,
            _fmap = {
                left:function(_mbox,_total){
                    return 0;
                },
                center:function(_mbox,_total){
                    return Math.floor((_total-_mbox)/2);
                },
                right:function(_mbox,_total){
                    return _total;
                }
            };
        _fmap.top = _fmap.left;
        _fmap.bottom = _fmap.right;
        return function(_options){
            _options = _options||_o;
            // set window position
            var _aligns = (_options.align||'').trim().split(_reg0),
                _position = NEJ.EX({width:0,height:0,topmost:!1},_options),
                _wkarea = (_n._$exec('os.getSystemInfo','desktop')||_o).workArea||_o;
            _position.x = (_fmap[_aligns[0]]||_fmap.center)(_position.width,_wkarea.width);
            _position.y = (_fmap[_aligns[1]]||_fmap.center)(_position.height,_wkarea.height);
            if (!_options.name){
                _n._$exec('winhelper.setWindowPosition',_position);
            }else{
                _position.name = _options.name;
                _n._$exec('winhelper.setNativeWindowRect',_position);
            }
        };
    })();
    /**
     * 配置窗体大小限制
     * @api    {nej.cef._$configWindowSizeLimit}
     * @param  {Object} 配置信息
     * @config {Number}  minWidth  窗体最小宽度
     * @config {Number}  maxWidth  窗体最大宽度
     * @config {Number}  minHeight 窗体最小高度
     * @config {Number}  maxHeight 窗体最大高度
     */
    _p._$configWindowSizeLimit = (function(){
        // parse min/max - width/height
        var _doParseBox = function(_width,_height){
            _width = parseInt(_width);
            _height = parseInt(_height);
            var _result;
            if (!isNaN(_width)){
                _result = _result||{};
                _result.x = _width;
            }
            if (!isNaN(_height)){
                _result = _result||{};
                _result.y = _height;
            }
            return _result;
        };
        return function(_options){
            _options = _options||_o;
            _n._$exec(
                'winhelper.setWindowSizeLimit',
                _doParseBox(_options.minWidth,_options.minHeight),
                _doParseBox(_options.maxWidth,_options.maxHeight)
            );
        };
    })();
    /**
     * 显示窗体,但窗体不会放在最上层
     * @api    {nej.cef._$showWindow}
     * @return {Void}
     */
    _p._$showWindow = function(){
        _n._$exec('winhelper.showWindow','show');
    };
    /**
     * 隐藏窗体
     * @api    {nej.cef._$hideWindow}
     * @return {Void}
     */
    _p._$hideWindow = function(){
        _n._$exec('winhelper.showWindow','hide');
    };
    /**
     * 切换窗体
     * @api    {nej.cef._$switchWindow}
     * @see    {nej.cef._$configWindowPosition}
     * @param  {String}  窗体名称
     * @param  {Object}  窗体配置信息
     * @return {Void}
     */
    _p._$switchWindow = function(_name,_options){
        _p._$hideWindow();
        _options = NEJ.X({name:_name},_options);
        _p._$configWindowPosition(_options);
        _n._$exec('winhelper.setNativeWindowShow',_name,!0);
    };
    /**
     * 打开新窗体
     * @param  {String} 新窗口地址，参数通过查询形式输入，如?width=1000&height=200
     * @return {Void}
     */
    _p._$open = (function(){
        var _doParseInt = function(_value,_key,_map){
            var _int = parseInt(_value);
            if (!isNaN(_int)){
                _map[_key] = _int;
            }else if(_value=='true'||_value=='false'){
                _map[_key] = _value=='true';
            }
        };
        return function(_url){
            // TODO parse param
            var _param = _u._$query2object(_url.split('?')[1]||'');
            _u._$forIn(_param,_doParseInt);
            _n._$exec('winhelper.launchWindow',_url,_param,_param);
        };
    })();

    // /**
     // * 将窗体置于最前
     // */
    // _p._$bringToTop = function() {
        // _n._$exec('winhelper.bringWindowToTop');
    // };
    // /**
     // * 隐藏窗体
     // */
    // _p._$hideWindow = function(){
        // _n._$exec('winhelper.showWindow','hide');
    // };
    // /**
     // * 程序退出
     // */
    // _p._$appExit = function(){
        // var _trayIcon = _n._$exec('app.getTrayIcon');
        // if (!!_trayIcon)
          // _trayIcon.uninstall();
        // _n._$exec('app.exit');
    // };
    // /**
     // * 获取托盘对象
     // * @return {Object}        托盘对象
     // */
    // _p._$getTrayIcon = function(){
        // return _n._$exec('app.getTrayIcon');
    // };
    // /**
     // * 程序退出
     // * @param    {Array}        菜单列表结构如下：
     // *                         [{menu:true,separator:false,text:'播放',enable:true,menu_id:1000,children:null}]
     // */
    // _p._$popMenu = function(_menu){
        // _n._$exec('winhelper.popUpMenu',JSON.stringify(_menu));
    // };
    // /**
     // * 气泡
     // * @param    {Object}    _balloonInfo
     // *                                         title        气泡标题
     // *                                         cnt            气泡内容
     // *                                         hasSound    是否播放声音
     // *                                         delay        延时多少时间
     // *                                         icon        气泡图标
     // */
    // _p._$popBalloon = function(_balloonInfo){
        // var _trayIcon = _n._$exec('app.getTrayIcon');
        // _trayIcon.popBalloon({
            // title : _balloonInfo.title,
            // text : _balloonInfo.cnt,
            // icon : _trayIcon.icon,
            // hasSound : _balloonInfo.hasSound,
            // delayTime : _balloonInfo.delay
        // });
    // };
    // /**
     // * 设置任务栏图标和任务栏title
     // * @param    _iconInfo
     // *                     url        任务栏图标地址，如果没有icon从托盘里取icon地址
     // *                     title    任务栏标题
     // */
    // _p._$setTaskIcon = function(_iconInfo){
        // if(!_iconInfo.url){
            // var _trayIcon = _n._$exec('app.getTrayIcon');
            // _n._$exec('winhelper.setWindowIconFromLocalFile', _trayIcon.icon);
        // }
        // else
            // _n._$exec('winhelper.setWindowIconFromLocalFile', _iconInfo.url);
        // _n._$exec('winhelper.setWindowTitle', _iconInfo.title||'');
    // };
    // /**
     // * 在浏览器中打开url
     // * @param    {String}    _url    网页地址,必须是网页上地址http：//开头
     // * @return    {Void}
     // */
    // _p._$openInNavigate = function(_url) {
        // _n._$exec('os.navigateExternal', _url);
    // };
    // /**
     // * 在新窗体中打开页面
     // *
     // * @param {String}
     // *            _url 页面地址
     // * @param {Object}
     // *            _info
     // *                    x         x坐标
     // *                    y         y坐标
     // *                    width     窗体宽度
     // *                    height     窗体高度
     // * @param {Object}
     // *            _setting
     // *                    visible                 打开窗体后是否可见
     // *                    resizable                 窗体是否可缩放
     // *                    taskbarButton           窗体是否要在任务栏显示
     // * @param {Boolean}
     // *            _openInNewWindow 强制在新窗体中打开
     // * @return {Obejct} 新开窗的引用
     // */
    // _p._$open = (function() {
            // var _windowHander = {};
            // return function(_url, _info, _setting, _openInNewWindow){
                // var _absoluteUrl = _u._$absolute(_url,location.href);
                // if (!!_info.center) {
                    // var _pos = _p._$getWindowPos(_info);
                    // _info.x = _pos.x;
                    // _info.y = _pos.y;
                // }
                // if (!!_openInNewWindow) {
                    // return _n._$exec('winhelper.launchWindow', _absoluteUrl, _info,
                            // _setting);
                // } else {
                    // var _page = _absoluteUrl;
                    // if (!_windowHander[_page])
                        // _windowHander[_page] = _n._$exec('winhelper.launchWindow',
                                // _absoluteUrl, _info, _setting);
                    // else if (!!_windowHander[_page] && !_windowHander[_page].location)
                        // _windowHander[_page] = _n._$exec('winhelper.launchWindow',
                                // _absoluteUrl, _info, _setting);
                    // else
                        // _windowHander[_page].location.href = _absoluteUrl;
                    // return _windowHander[_page];
                // }
        // };
    // })();
    // /**
     // * 设置开机启动
     // * @param    {String}    程序代号
     // * @param    {String}    开机启动时参数
     // * 设置后开机启动会是　xxx-startup=auto  xxx是程序名
     // */
    // _p._$setAutoRun = function(){
        // _n._$exec('app.setAutoRun', _name, _param);
    // };
    // /**
     // * 取消开机启动
     // * @return {String}    _name    程序代号
     // */
    // _p._$cancelAutoRun = function(_name){
        // _n._$exec('app.cancelAutoRun', _name);
    // };
    // /**
     // * 获取是否设置了开机启动
     // *
     // * @param {String}
     // *            _name 程序名字
     // * @param {Boolean}
     // *            是否已设置
     // */
    // _p._$getAutoRunState = function(_name) {
        // return _n._$exec('app.getAutoRunState', _name);
    // };
    // /**
     // * 移除指定域上的cookie
     // *
     // * @param {String}
     // *            _url 指定域 例：http://163.com
     // * @param {String}
     // *            _cookieName cookie名
     // */
    // _p._$removeCookie = function(_url, _cookieName) {
        // _n._$exec('browser.removeCookie', _url, _cookieName);
    // };
    // /**
     // * 移动cookie
     // *
     // * @param {String}
     // *            _fromDomain 源域 例：163.com
     // * @param {String}
     // *            _targetDomain 目标域 例：126.com
     // * @param {String}
     // *            _cookieName cookie名
     // */
    // _p._$moveCookie = function(_fromDomain, _targetDomain, _cookieName) {
        // _n._$exec('browser.moveCookie', _fromDomain, _targetDomain,
                // _cookieName);
    // };
    // /**
     // * 设置指定域上的cookie
     // *
     // * @param {String}
     // *            _url 指定域 例：http://.163.com
     // * @param {String
     // *            _cookieName cookie名
     // * @param {String}
     // *            _cookie cookie值
     // */
    // _p._$setCookie = function(_url, _cookieName, _cookie) {
        // _n._$exec('browser.setCookie', _url, _cookieName, _cookie);
    // };
    // /**
     // * 点击节点移动窗体
     // * 由于native的drag是鼠标按下时进行拖动
     // * 但native又没要在mouseup时形成一个完整的鼠标click事件，所以普通的click事件在这些节点上都是无效的
     // * 有多少个节点可以拖动，就添加多少个节点，只有事件源是这些节点的会触发拖动，事件源是他的子节点触发的不会拖动
     // * @param {Element}
     // *            _elm 节点
     // */
    // _p._$onDragWindow = (function() {
        // var _dragElm =[];
        // return function(_elm){
            // var _elm = _e._$get(_elm);
            // _dragElm.push(_elm);
            // _v._$addEvent(_elm, 'mousedown', function(_event){
                // var _elm = _v._$getElement(_event);
                // var _index = _u._$indexOf(_dragElm, _elm);
                // if (_event.which == 1 && _index != -1)
                    // _n._$exec('winhelper.dragWindow');
            // });
        // };
    // })();
    // /**
     // * 获取桌面的大小
     // *
     // * @return {Object} 桌面大小
     // */
    // _p._$geDesktopSize = function() {
        // var _position = _n._$exec('os.getSystemInfo', 'desktop');
        // if(!!_position)
            // return;
        // else
            // return _position.workArea;
    // };
    // /**
     // * 获取当前窗体的位置信息
     // *
     // * @returns {Object} _info height 窗体高度 width 窗体宽度 x 窗体x坐标 y 窗体y坐标
     // */
    // _p._$getWindowInfo = function() {
        // var _info = _n._$exec('winhelper.getWindowPosition');
        // return _info;
    // };
};
NEJ.define('{lib}native/cef/api.js', ['{lib}native/command.js','{lib}base/util.js','{lib}base/element.js'], f);<commit_msg>cef window api<commit_after>/**
 * ------------------------------------------
 * 桌面接口实现文件
 * @version  1.0
 * @author   yuqijun(yuqijun@corp.netease.com)
 * ------------------------------------------
 */
var f = function() {
    // variable declaration
    var _ = NEJ.P,
        _o = NEJ.O,
        _e = _('nej.e'),
        _u = _('nej.u'),
        _v = _('nej.v'),
        _n = _('nej.n'),
        _p = _('nej.cef');
    /**
     * 配置窗体信息
     * @see    {nej.cef._$configWindowPosition}
     * @see    {nej.cef._$configWindowSizeLimit}
     * @param  {Object} 配置信息，其他参数详情见@see指定接口配置信息
     * @return {Void}
     */
    _p._$configWindow = function(_options){
        _p._$configWindowSizeLimit(_options);
        _p._$configWindowPosition(_options);
    };
    /**
     * 配置窗体位置，对齐方式定义如下

     * 水平对齐方式：
     * [ntb]
     *   名称            |  描述
     *   ----------------------
     *   left   |  左侧对齐
     *   center |  中间对齐
     *   right  |  右侧对齐
     * [/ntb]
     *
     * 垂直对齐方式：
     * [ntb]
     *   名称              |  描述
     *   ---------------------
     *   top     |  顶部对齐
     *   center  |  中间对齐
     *   bottom  |  底部对齐
     * [/ntb]
     * @api    {nej.cef._$configWindowPosition}
     * @param  {Object} 配置信息
     * @config {String}  name     窗体名称
     * @config {Number}  width    窗体宽度
     * @config {Number}  height   窗体高度
     * @config {Boolean} topmost  窗体是否置顶
     * @config {String}  align    对齐方式，格式定义：水平对齐方式+空格+垂直对齐方式，如 left top
     * @return {Void}
     */
    _p._$configWindowPosition = (function(){
        var _reg0 = /\s+/,
            _fmap = {
                left:function(_mbox,_total){
                    return 0;
                },
                center:function(_mbox,_total){
                    return Math.floor((_total-_mbox)/2);
                },
                right:function(_mbox,_total){
                    return _total;
                }
            };
        _fmap.top = _fmap.left;
        _fmap.bottom = _fmap.right;
        return function(_options){
            _options = _options||_o;
            // set window position
            var _aligns = (_options.align||'').trim().split(_reg0),
                _position = NEJ.EX({width:0,height:0,topmost:!1},_options),
                _wkarea = (_n._$exec('os.getSystemInfo','desktop')||_o).workArea||_o;
            _position.x = (_fmap[_aligns[0]]||_fmap.center)(_position.width,_wkarea.width);
            _position.y = (_fmap[_aligns[1]]||_fmap.center)(_position.height,_wkarea.height);
            if (!_options.name){
                _n._$exec('winhelper.setWindowPosition',_position);
            }else{
                _position.name = _options.name;
                _n._$exec('winhelper.setNativeWindowRect',_position);
            }
        };
    })();
    /**
     * 配置窗体大小限制
     * @api    {nej.cef._$configWindowSizeLimit}
     * @param  {Object} 配置信息
     * @config {Number}  minWidth  窗体最小宽度
     * @config {Number}  maxWidth  窗体最大宽度
     * @config {Number}  minHeight 窗体最小高度
     * @config {Number}  maxHeight 窗体最大高度
     */
    _p._$configWindowSizeLimit = (function(){
        // parse min/max - width/height
        var _doParseBox = function(_width,_height){
            _width = parseInt(_width);
            _height = parseInt(_height);
            var _result;
            if (!isNaN(_width)){
                _result = _result||{};
                _result.x = _width;
            }
            if (!isNaN(_height)){
                _result = _result||{};
                _result.y = _height;
            }
            return _result;
        };
        return function(_options){
            _options = _options||_o;
            _n._$exec(
                'winhelper.setWindowSizeLimit',
                _doParseBox(_options.minWidth,_options.minHeight),
                _doParseBox(_options.maxWidth,_options.maxHeight)
            );
        };
    })();
    /**
     * 显示窗体,但窗体不会放在最上层
     * @api    {nej.cef._$showWindow}
     * @return {Void}
     */
    _p._$showWindow = function(_name){
        if (!_name){
            _n._$exec('winhelper.showWindow','show');
        }else{
            _n._$exec('winhelper.setNativeWindowShow',_name,!0);
        }
    };
    /**
     * 隐藏窗体
     * @api    {nej.cef._$hideWindow}
     * @return {Void}
     */
    _p._$hideWindow = function(_name){
        if (!_name){
            _n._$exec('winhelper.showWindow','hide');
        }else{
            _n._$exec('winhelper.setNativeWindowShow',_name,!1);
        }
    };
    /**
     * 打开新窗体
     * @param  {String} 新窗口地址，参数通过查询形式输入，如?width=1000&height=200
     * @return {Void}
     */
    _p._$open = (function(){
        var _doParseInt = function(_value,_key,_map){
            var _int = parseInt(_value);
            if (!isNaN(_int)){
                _map[_key] = _int;
            }else if(_value=='true'||_value=='false'){
                _map[_key] = _value=='true';
            }
        };
        return function(_url){
            // TODO parse param
            var _param = _u._$query2object(_url.split('?')[1]||'');
            _u._$forIn(_param,_doParseInt);
            _n._$exec('winhelper.launchWindow',_url,_param,_param);
        };
    })();

    // /**
     // * 将窗体置于最前
     // */
    // _p._$bringToTop = function() {
        // _n._$exec('winhelper.bringWindowToTop');
    // };
    // /**
     // * 隐藏窗体
     // */
    // _p._$hideWindow = function(){
        // _n._$exec('winhelper.showWindow','hide');
    // };
    // /**
     // * 程序退出
     // */
    // _p._$appExit = function(){
        // var _trayIcon = _n._$exec('app.getTrayIcon');
        // if (!!_trayIcon)
          // _trayIcon.uninstall();
        // _n._$exec('app.exit');
    // };
    // /**
     // * 获取托盘对象
     // * @return {Object}        托盘对象
     // */
    // _p._$getTrayIcon = function(){
        // return _n._$exec('app.getTrayIcon');
    // };
    // /**
     // * 程序退出
     // * @param    {Array}        菜单列表结构如下：
     // *                         [{menu:true,separator:false,text:'播放',enable:true,menu_id:1000,children:null}]
     // */
    // _p._$popMenu = function(_menu){
        // _n._$exec('winhelper.popUpMenu',JSON.stringify(_menu));
    // };
    // /**
     // * 气泡
     // * @param    {Object}    _balloonInfo
     // *                                         title        气泡标题
     // *                                         cnt            气泡内容
     // *                                         hasSound    是否播放声音
     // *                                         delay        延时多少时间
     // *                                         icon        气泡图标
     // */
    // _p._$popBalloon = function(_balloonInfo){
        // var _trayIcon = _n._$exec('app.getTrayIcon');
        // _trayIcon.popBalloon({
            // title : _balloonInfo.title,
            // text : _balloonInfo.cnt,
            // icon : _trayIcon.icon,
            // hasSound : _balloonInfo.hasSound,
            // delayTime : _balloonInfo.delay
        // });
    // };
    // /**
     // * 设置任务栏图标和任务栏title
     // * @param    _iconInfo
     // *                     url        任务栏图标地址，如果没有icon从托盘里取icon地址
     // *                     title    任务栏标题
     // */
    // _p._$setTaskIcon = function(_iconInfo){
        // if(!_iconInfo.url){
            // var _trayIcon = _n._$exec('app.getTrayIcon');
            // _n._$exec('winhelper.setWindowIconFromLocalFile', _trayIcon.icon);
        // }
        // else
            // _n._$exec('winhelper.setWindowIconFromLocalFile', _iconInfo.url);
        // _n._$exec('winhelper.setWindowTitle', _iconInfo.title||'');
    // };
    // /**
     // * 在浏览器中打开url
     // * @param    {String}    _url    网页地址,必须是网页上地址http：//开头
     // * @return    {Void}
     // */
    // _p._$openInNavigate = function(_url) {
        // _n._$exec('os.navigateExternal', _url);
    // };
    // /**
     // * 在新窗体中打开页面
     // *
     // * @param {String}
     // *            _url 页面地址
     // * @param {Object}
     // *            _info
     // *                    x         x坐标
     // *                    y         y坐标
     // *                    width     窗体宽度
     // *                    height     窗体高度
     // * @param {Object}
     // *            _setting
     // *                    visible                 打开窗体后是否可见
     // *                    resizable                 窗体是否可缩放
     // *                    taskbarButton           窗体是否要在任务栏显示
     // * @param {Boolean}
     // *            _openInNewWindow 强制在新窗体中打开
     // * @return {Obejct} 新开窗的引用
     // */
    // _p._$open = (function() {
            // var _windowHander = {};
            // return function(_url, _info, _setting, _openInNewWindow){
                // var _absoluteUrl = _u._$absolute(_url,location.href);
                // if (!!_info.center) {
                    // var _pos = _p._$getWindowPos(_info);
                    // _info.x = _pos.x;
                    // _info.y = _pos.y;
                // }
                // if (!!_openInNewWindow) {
                    // return _n._$exec('winhelper.launchWindow', _absoluteUrl, _info,
                            // _setting);
                // } else {
                    // var _page = _absoluteUrl;
                    // if (!_windowHander[_page])
                        // _windowHander[_page] = _n._$exec('winhelper.launchWindow',
                                // _absoluteUrl, _info, _setting);
                    // else if (!!_windowHander[_page] && !_windowHander[_page].location)
                        // _windowHander[_page] = _n._$exec('winhelper.launchWindow',
                                // _absoluteUrl, _info, _setting);
                    // else
                        // _windowHander[_page].location.href = _absoluteUrl;
                    // return _windowHander[_page];
                // }
        // };
    // })();
    // /**
     // * 设置开机启动
     // * @param    {String}    程序代号
     // * @param    {String}    开机启动时参数
     // * 设置后开机启动会是　xxx-startup=auto  xxx是程序名
     // */
    // _p._$setAutoRun = function(){
        // _n._$exec('app.setAutoRun', _name, _param);
    // };
    // /**
     // * 取消开机启动
     // * @return {String}    _name    程序代号
     // */
    // _p._$cancelAutoRun = function(_name){
        // _n._$exec('app.cancelAutoRun', _name);
    // };
    // /**
     // * 获取是否设置了开机启动
     // *
     // * @param {String}
     // *            _name 程序名字
     // * @param {Boolean}
     // *            是否已设置
     // */
    // _p._$getAutoRunState = function(_name) {
        // return _n._$exec('app.getAutoRunState', _name);
    // };
    // /**
     // * 移除指定域上的cookie
     // *
     // * @param {String}
     // *            _url 指定域 例：http://163.com
     // * @param {String}
     // *            _cookieName cookie名
     // */
    // _p._$removeCookie = function(_url, _cookieName) {
        // _n._$exec('browser.removeCookie', _url, _cookieName);
    // };
    // /**
     // * 移动cookie
     // *
     // * @param {String}
     // *            _fromDomain 源域 例：163.com
     // * @param {String}
     // *            _targetDomain 目标域 例：126.com
     // * @param {String}
     // *            _cookieName cookie名
     // */
    // _p._$moveCookie = function(_fromDomain, _targetDomain, _cookieName) {
        // _n._$exec('browser.moveCookie', _fromDomain, _targetDomain,
                // _cookieName);
    // };
    // /**
     // * 设置指定域上的cookie
     // *
     // * @param {String}
     // *            _url 指定域 例：http://.163.com
     // * @param {String
     // *            _cookieName cookie名
     // * @param {String}
     // *            _cookie cookie值
     // */
    // _p._$setCookie = function(_url, _cookieName, _cookie) {
        // _n._$exec('browser.setCookie', _url, _cookieName, _cookie);
    // };
    // /**
     // * 点击节点移动窗体
     // * 由于native的drag是鼠标按下时进行拖动
     // * 但native又没要在mouseup时形成一个完整的鼠标click事件，所以普通的click事件在这些节点上都是无效的
     // * 有多少个节点可以拖动，就添加多少个节点，只有事件源是这些节点的会触发拖动，事件源是他的子节点触发的不会拖动
     // * @param {Element}
     // *            _elm 节点
     // */
    // _p._$onDragWindow = (function() {
        // var _dragElm =[];
        // return function(_elm){
            // var _elm = _e._$get(_elm);
            // _dragElm.push(_elm);
            // _v._$addEvent(_elm, 'mousedown', function(_event){
                // var _elm = _v._$getElement(_event);
                // var _index = _u._$indexOf(_dragElm, _elm);
                // if (_event.which == 1 && _index != -1)
                    // _n._$exec('winhelper.dragWindow');
            // });
        // };
    // })();
    // /**
     // * 获取桌面的大小
     // *
     // * @return {Object} 桌面大小
     // */
    // _p._$geDesktopSize = function() {
        // var _position = _n._$exec('os.getSystemInfo', 'desktop');
        // if(!!_position)
            // return;
        // else
            // return _position.workArea;
    // };
    // /**
     // * 获取当前窗体的位置信息
     // *
     // * @returns {Object} _info height 窗体高度 width 窗体宽度 x 窗体x坐标 y 窗体y坐标
     // */
    // _p._$getWindowInfo = function() {
        // var _info = _n._$exec('winhelper.getWindowPosition');
        // return _info;
    // };
};
NEJ.define('{lib}native/cef/api.js', ['{lib}native/command.js','{lib}base/util.js','{lib}base/element.js'], f);<|endoftext|>