code stringlengths 2 1.05M |
|---|
var buster = require("buster");
var assert = buster.assert;
var streamLogger = require("./../lib/stream-logger");
buster.testCase("stream logger", {
setUp: function () {
var self = this;
this.stdout = "";
this.stderr = "";
var join = function (arr, sep) { return [].join.call(arr, sep); };
this.logger = streamLogger(
{ write: function () { self.stdout += join(arguments, " "); } },
{ write: function () { self.stderr += join(arguments, " "); } }
);
},
"should write debug messages to stdout": function () {
this.logger.d("Hey");
this.logger.d("There");
assert.equals(this.stdout, "Hey\nThere\n");
},
"should write info messages to stdout": function () {
this.logger.info("Hey");
this.logger.i("There");
assert.equals(this.stdout, "Hey\nThere\n");
},
"should write log messages to stdout": function () {
this.logger.log("Hey");
this.logger.l("There");
assert.equals(this.stdout, "Hey\nThere\n");
},
"should write warning messages to stderr": function () {
this.logger.warn("Hey");
this.logger.w("There");
assert.equals(this.stderr, "Hey\nThere\n");
},
"should write error messages to stderr": function () {
this.logger.error("Hey");
this.logger.e("There");
assert.equals(this.stderr, "Hey\nThere\n");
},
"should prefix with log level when being verbose": function () {
this.logger.verbose = true;
this.logger.d("Hey");
this.logger.i("There");
this.logger.l("Fella");
this.logger.w("Woops");
this.logger.e("Game over");
assert.equals(this.stdout, "[DEBUG] Hey\n[INFO] There\n[LOG] Fella\n");
assert.equals(this.stderr, "[WARN] Woops\n[ERROR] Game over\n");
},
"default io": {
setUp: function () {
var self = this;
this.process = global.process;
global.process = {
stdout: { write: function (str) { self.stdout += str; } },
stderr: { write: function (str) { self.stderr += str; } }
};
},
tearDown: function () {
global.process = this.process;
},
"should default to console for stdio": function () {
var logger = streamLogger();
logger.i("Hey");
logger.e("Game over");
assert.equals(this.stdout, "Hey\n");
assert.equals(this.stderr, "Game over\n");
}
},
"should print inline message without line-break": function () {
this.logger.inline.l("Hey there");
assert.equals(this.stdout, "Hey there");
},
"should print inline message with long method name": function () {
this.logger.inline.debug("Hey there");
assert.equals(this.stdout, "Hey there");
},
"inline logger should inherit level from logger": function () {
this.logger.level = "warn";
this.logger.inline.debug("Hey there");
this.logger.inline.warn("Watch out!");
assert.equals(this.stdout, "");
assert.equals(this.stderr, "Watch out!");
},
"as stream": {
"should return a stream that logs at level 'log'": function () {
var logStream = this.logger.streamForLevel("log");
var infoStream = this.logger.streamForLevel("info");
this.logger.level = "log";
logStream.write("Hey");
infoStream.write("Yo");
assert.equals(this.stdout, "Hey");
},
"should respond to changes in level": function () {
var logStream = this.logger.streamForLevel("log");
logStream.write("Before");
this.logger.level = "warn";
logStream.write("After");
assert.equals(this.stdout, "Before");
}
}
});
|
/*
* Copyright (c) 2014 - present Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*global $, define, describe, it, expect, jasmine */
/*unittests: FileTreeView*/
define(function (require, exports, module) {
"use strict";
var FileTreeView = require("project/FileTreeView"),
FileTreeViewModel = require("project/FileTreeViewModel"),
React = require("thirdparty/react"),
ReactDOM = require("thirdparty/react-dom"),
Immutable = require("thirdparty/immutable"),
RTU = React.addons.TestUtils,
_ = require("thirdparty/lodash");
describe("FileTreeView", function () {
describe("_fileNode", function () {
it("should create a component with the right information", function () {
var rendered = RTU.renderIntoDocument(FileTreeView._fileNode({
name: "afile.js",
entry: Immutable.Map()
}));
var a = RTU.findRenderedDOMComponentWithTag(rendered, "a");
expect(a.children[1].textContent).toBe("afile");
expect(a.children[2].textContent).toBe(".js");
expect(a.children[0].textContent).toBe(" ");
});
it("should call icon extensions to replace the default icon", function () {
var extensionCalls = 0,
rendered = RTU.renderIntoDocument(FileTreeView._fileNode({
name: "afile.js",
entry: Immutable.Map(),
parentPath: "/foo/",
extensions: Immutable.fromJS({
icons: [function (data) {
extensionCalls++;
expect(data.name).toBe("afile.js");
expect(data.isFile).toBe(true);
expect(data.fullPath).toBe("/foo/afile.js");
return React.DOM.ins({}, "ICON");
}]
})
}));
expect(extensionCalls).toBe(1);
var a = RTU.findRenderedDOMComponentWithTag(rendered, "a");
expect(a.children[1].textContent).toBe("afile");
expect(a.children[2].textContent).toBe(".js");
expect(a.children[0].textContent).toBe("ICON");
});
it("should allow icon extensions to return a string for the icon", function () {
var extensionCalls = 0,
rendered = RTU.renderIntoDocument(FileTreeView._fileNode({
name: "afile.js",
entry: Immutable.Map(),
parentPath: "/foo/",
extensions: Immutable.fromJS({
icons: [function (data) {
extensionCalls++;
return "<ins>ICON</ins>";
}]
})
}));
expect(extensionCalls).toBe(1);
var a = RTU.findRenderedDOMComponentWithTag(rendered, "a");
expect(a.children[1].textContent).toBe("afile");
expect(a.children[2].textContent).toBe(".js");
var $a = $(ReactDOM.findDOMNode(a)),
$ins = $a.find("ins");
expect($ins.text()).toBe("ICON");
});
it("should set context on a node by right click", function () {
var actions = jasmine.createSpyObj("actions", ["setContext"]);
var rendered = RTU.renderIntoDocument(FileTreeView._fileNode({
name: "afile.js",
entry: Immutable.Map(),
actions: actions,
parentPath: "/foo/"
}));
var node = ReactDOM.findDOMNode(rendered);
React.addons.TestUtils.Simulate.mouseDown(node, {
button: 2
});
expect(actions.setContext).toHaveBeenCalledWith("/foo/afile.js");
});
it("should set context on a node by control click on Mac", function () {
var actions = jasmine.createSpyObj("actions", ["setContext"]);
var rendered = RTU.renderIntoDocument(FileTreeView._fileNode({
name: "afile.js",
entry: Immutable.Map(),
actions: actions,
parentPath: "/foo/",
platform: "mac"
}));
var node = ReactDOM.findDOMNode(rendered);
React.addons.TestUtils.Simulate.mouseDown(node, {
button: 0,
ctrlKey: true
});
expect(actions.setContext).toHaveBeenCalledWith("/foo/afile.js");
});
it("should not set context on a node by control click on Windows", function () {
var actions = jasmine.createSpyObj("actions", ["setContext"]);
var rendered = RTU.renderIntoDocument(FileTreeView._fileNode({
name: "afile.js",
entry: Immutable.Map(),
actions: actions,
parentPath: "/foo/",
platform: "win"
}));
var node = ReactDOM.findDOMNode(rendered);
React.addons.TestUtils.Simulate.mouseDown(node, {
button: 0,
ctrlKey: true
});
expect(actions.setContext).not.toHaveBeenCalled();
});
it("should allow icon extensions to return a jQuery object for the icon", function () {
var extensionCalls = 0,
rendered = RTU.renderIntoDocument(FileTreeView._fileNode({
name: "afile.js",
entry: Immutable.Map(),
parentPath: "/foo/",
extensions: Immutable.fromJS({
icons: [function (data) {
extensionCalls++;
return $("<ins/>").text("ICON");
}]
})
}));
expect(extensionCalls).toBe(1);
var a = RTU.findRenderedDOMComponentWithTag(rendered, "a");
expect(a.children[1].textContent).toBe("afile");
expect(a.children[2].textContent).toBe(".js");
var $a = $(a),
$ins = $a.find("ins");
expect($ins.text()).toBe("ICON");
});
it("should call addClass extensions", function () {
var extensionCalls = 0,
rendered = RTU.renderIntoDocument(FileTreeView._fileNode({
name: "afile.js",
entry: Immutable.Map(),
parentPath: "/foo/",
extensions: Immutable.fromJS({
addClass: [function (data) {
extensionCalls++;
expect(data.name).toBe("afile.js");
expect(data.isFile).toBe(true);
expect(data.fullPath).toBe("/foo/afile.js");
return "new";
}, function (data) {
return "classes are cool";
}]
})
}));
expect(extensionCalls).toBe(1);
var li = RTU.findRenderedDOMComponentWithTag(rendered, "li");
expect(li.className).toBe("jstree-leaf new classes are cool");
});
it("should render a rename component", function () {
var rendered = RTU.renderIntoDocument(FileTreeView._fileNode({
name: "afile.js",
entry: Immutable.Map({
rename: true
})
}));
var input = RTU.findRenderedDOMComponentWithTag(rendered, "input");
expect(input.value).toBe("afile.js");
});
it("should re-render as needed", function () {
var props = {
name : "afile.js",
entry : Immutable.Map(),
parentPath: "/foo/",
extensions: Immutable.Map()
};
var rendered = RTU.renderIntoDocument(FileTreeView._fileNode(props));
var newProps = _.clone(props);
expect(rendered.shouldComponentUpdate(newProps)).toBe(false);
newProps = _.clone(props);
newProps.entry = Immutable.Map({
selected: true
});
expect(rendered.shouldComponentUpdate(newProps)).toBe(true);
newProps = _.clone(props);
newProps.forceRender = true;
expect(rendered.shouldComponentUpdate(newProps)).toBe(true);
newProps = _.clone(props);
newProps.extensions = Immutable.Map({
addClasses: Immutable.List()
});
expect(rendered.shouldComponentUpdate(newProps)).toBe(true);
});
});
describe("_sortFormattedDirectory", function () {
it("should sort alphabetically", function () {
var formatted = Immutable.fromJS({
"README.md": {},
"afile.js": {},
subdir: {
children: null
}
});
expect(FileTreeView._sortFormattedDirectory(formatted).toJS()).toEqual([
"afile.js", "README.md", "subdir"
]);
});
it("should include the extension in the sort", function () {
var formatted = Immutable.fromJS({
"README.txt": {},
"README.md": {},
"README": {}
});
expect(FileTreeView._sortFormattedDirectory(formatted).toJS()).toEqual([
"README", "README.md", "README.txt"
]);
});
it("can sort by directories first", function () {
var formatted = Immutable.fromJS({
"README.md": {},
"afile.js": {},
subdir: {
children: null
}
});
expect(FileTreeView._sortFormattedDirectory(formatted, true).toJS()).toEqual([
"subdir", "afile.js", "README.md"
]);
});
});
var twoLevel = Immutable.fromJS({
open: true,
children: {
subdir: {
open: true,
children: {
"afile.js": {}
}
}
}
});
describe("_directoryNode and _directoryContents", function () {
it("should format a closed directory", function () {
var rendered = RTU.renderIntoDocument(FileTreeView._directoryNode({
name: "thedir",
parentPath: "/foo/",
entry: Immutable.fromJS({
children: null
})
}));
var dirLI = ReactDOM.findDOMNode(rendered),
dirA = $(dirLI).find("a")[0];
expect(dirLI.children[1].textContent).toBe(" thedir");
expect(rendered.myPath()).toBe("/foo/thedir/");
});
it("should rerender as needed", function () {
var props = {
name : "thedir",
parentPath : "/foo/",
entry : Immutable.fromJS({
children: null
}),
extensions : Immutable.Map(),
sortDirectoriesFirst: false
};
var rendered = RTU.renderIntoDocument(FileTreeView._directoryNode(props));
var newProps = _.clone(props);
expect(rendered.shouldComponentUpdate(newProps)).toBe(false);
newProps = _.clone(props);
newProps.entry = Immutable.fromJS({
children: []
});
expect(rendered.shouldComponentUpdate(newProps)).toBe(true);
newProps = _.clone(props);
newProps.forceRender = true;
expect(rendered.shouldComponentUpdate(newProps)).toBe(true);
newProps = _.clone(props);
newProps.extensions = Immutable.Map({
addClasses: Immutable.List()
});
expect(rendered.shouldComponentUpdate(newProps)).toBe(true);
newProps = _.clone(props);
newProps.sortDirectoriesFirst = true;
expect(rendered.shouldComponentUpdate(newProps)).toBe(true);
});
it("should call extensions for directories", function () {
var extensionCalled = false,
rendered = RTU.renderIntoDocument(FileTreeView._directoryNode({
name: "thedir",
parentPath: "/foo/",
entry: Immutable.fromJS({
children: null
}),
extensions: Immutable.fromJS({
icons: [function (data) {
return React.DOM.ins({}, "ICON");
}],
addClass: [function (data) {
extensionCalled = true;
expect(data.name).toBe("thedir");
expect(data.isFile).toBe(false);
expect(data.fullPath).toBe("/foo/thedir/");
return "new";
}, function (data) {
return "classes are cool";
}]
})
}));
expect(extensionCalled).toBe(true);
var dirLI = ReactDOM.findDOMNode(rendered),
dirA = $(dirLI).find("a")[0];
expect(dirLI.className).toBe("jstree-closed new classes are cool");
var icon = dirA.children[0];
expect(icon.textContent).toBe("ICON");
});
it("should allow renaming a closed directory", function () {
var rendered = RTU.renderIntoDocument(FileTreeView._directoryNode({
name: "thedir",
entry: Immutable.fromJS({
children: null,
rename: true
})
}));
var input = RTU.findRenderedDOMComponentWithTag(rendered, "input");
expect(input.value).toBe("thedir");
});
it("should be able to list files", function () {
var rendered = RTU.renderIntoDocument(FileTreeView._directoryContents({
contents: Immutable.fromJS({
"afile.js": {}
})
}));
var fileLI = ReactDOM.findDOMNode(rendered),
fileA = $(fileLI).find("a")[0];
expect(fileA.children[1].textContent).toBe("afile");
});
it("should be able to list closed directories", function () {
var rendered = RTU.renderIntoDocument(FileTreeView._directoryNode({
name: "thedir",
entry: Immutable.fromJS({
open: true,
children: {
"subdir": {
children: null
}
}
})
}));
var subdirLI = ReactDOM.findDOMNode(rendered),
subdirA = $(subdirLI).find(".jstree-closed > a")[0];
expect(subdirA.children[1].textContent).toBe("subdir");
});
it("should be able to list open subdirectories", function () {
var rendered = RTU.renderIntoDocument(FileTreeView._directoryNode({
name: "twoLevel",
entry: twoLevel
}));
var dirLI = ReactDOM.findDOMNode(rendered);
var subdirLI = $(dirLI).find(".jstree-open"),
aTags = subdirLI.find("a");
expect(aTags.length).toBe(2);
expect(aTags[0].children[1].textContent).toBe("subdir");
expect(aTags[1].children[1].textContent).toBe("afile");
});
it("should sort directory contents according to the flag", function () {
var directory = Immutable.fromJS({
children: {
"afile.js": {},
"subdir": {
children: {}
}
},
open: true
});
var rendered = RTU.renderIntoDocument(FileTreeView._directoryNode({
name: "hasDirs",
entry: directory,
sortDirectoriesFirst: true
}));
var html = ReactDOM.findDOMNode(rendered).outerHTML;
expect(html.indexOf("subdir")).toBeLessThan(html.indexOf("afile"));
});
it("should rerender contents as needed", function () {
var props = {
parentPath : "/foo/",
contents : Immutable.Map(),
sortDirectoriesFirst: false,
extensions : Immutable.Map()
};
var rendered = RTU.renderIntoDocument(FileTreeView._directoryContents(props));
var newProps = _.clone(props);
expect(rendered.shouldComponentUpdate(newProps)).toBe(false);
newProps = _.clone(props);
newProps.contents = Immutable.fromJS({
somefile: {}
});
expect(rendered.shouldComponentUpdate(newProps)).toBe(true);
newProps = _.clone(props);
newProps.forceRender = true;
expect(rendered.shouldComponentUpdate(newProps)).toBe(true);
newProps = _.clone(props);
newProps.extensions = Immutable.Map({
addClasses: Immutable.List()
});
expect(rendered.shouldComponentUpdate(newProps)).toBe(true);
newProps = _.clone(props);
newProps.sortDirectoriesFirst = true;
expect(rendered.shouldComponentUpdate(newProps)).toBe(true);
});
});
describe("_fileTreeView", function () {
var selectionViewInfo = new Immutable.Map({
hasSelection: true,
width: 100,
hasContext: false,
scrollTop: 0,
scrollLeft: 0,
offsetTop: 0
});
it("should render the directory", function () {
var rendered = RTU.renderIntoDocument(FileTreeView._fileTreeView({
projectRoot: {},
treeData: new Immutable.Map({
"subdir": twoLevel.getIn(["children", "subdir"])
}),
selectionViewInfo: selectionViewInfo,
sortDirectoriesFirst: false
}));
var rootNode = ReactDOM.findDOMNode(rendered),
aTags = $(rootNode).find("a");
expect(aTags.length).toBe(2);
expect(aTags[0].children[1].textContent).toBe("subdir");
expect(aTags[1].children[1].textContent).toBe("afile");
});
it("should rerender contents as needed", function () {
var props = {
parentPath : "/foo/",
treeData : Immutable.Map(),
selectionViewInfo : selectionViewInfo,
sortDirectoriesFirst: false,
extensions : Immutable.Map()
};
var rendered = RTU.renderIntoDocument(FileTreeView._fileTreeView(props));
var newProps = _.clone(props);
expect(rendered.shouldComponentUpdate(newProps)).toBe(false);
newProps = _.clone(props);
newProps.treeData = Immutable.fromJS({
somefile: {}
});
expect(rendered.shouldComponentUpdate(newProps)).toBe(true);
newProps = _.clone(props);
newProps.forceRender = true;
expect(rendered.shouldComponentUpdate(newProps)).toBe(true);
newProps = _.clone(props);
newProps.extensions = Immutable.Map({
addClasses: Immutable.List()
});
expect(rendered.shouldComponentUpdate(newProps)).toBe(true);
newProps = _.clone(props);
newProps.sortDirectoriesFirst = true;
expect(rendered.shouldComponentUpdate(newProps)).toBe(true);
});
});
describe("render", function () {
it("should render into the given element", function () {
var el = document.createElement("div"),
viewModel = new FileTreeViewModel.FileTreeViewModel();
viewModel._treeData = new Immutable.Map({
"subdir": twoLevel.getIn(["children", "subdir"])
});
FileTreeView.render(el, viewModel, {
fullPath: "/foo/"
});
expect($(".jstree-no-dots", el).length).toBe(1);
});
});
});
});
|
import { keyframeSelectorKeywords } from "../reference/keywordSets"
/**
* Check whether a string is a keyframe selector.
*
* @param {string} selector
* @return {boolean} If `true`, the selector is a keyframe selector
*/
export default function (selector) {
if (keyframeSelectorKeywords.has(selector)) { return true }
// Percentages
if (/^(?:\d+\.?\d*|\d*\.?\d+)%$/.test(selector)) { return true }
return false
}
|
/**
* @fileoverview Rule to flag block statements that do not use the one true brace style
* @author Ian Christian Myers
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = function(context) {
var style = context.options[0] || "1tbs";
var params = context.options[1] || {};
var OPEN_MESSAGE = "Opening curly brace does not appear on the same line as controlling statement.",
OPEN_MESSAGE_ALLMAN = "Opening curly brace appears on the same line as controlling statement.",
BODY_MESSAGE = "Statement inside of curly braces should be on next line.",
CLOSE_MESSAGE = "Closing curly brace does not appear on the same line as the subsequent block.",
CLOSE_MESSAGE_SINGLE = "Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.",
CLOSE_MESSAGE_STROUSTRUP = "Closing curly brace appears on the same line as the subsequent block.";
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
/**
* Determines if a given node is a block statement.
* @param {ASTNode} node The node to check.
* @returns {boolean} True if the node is a block statement, false if not.
* @private
*/
function isBlock(node) {
return node && node.type === "BlockStatement";
}
/**
* Check if the token is an punctuator with a value of curly brace
* @param {object} token - Token to check
* @returns {boolean} true if its a curly punctuator
* @private
*/
function isCurlyPunctuator(token) {
return token.value === "{" || token.value === "}";
}
/**
* Binds a list of properties to a function that verifies that the opening
* curly brace is on the same line as its controlling statement of a given
* node.
* @param {...string} The properties to check on the node.
* @returns {Function} A function that will perform the check on a node
* @private
*/
function checkBlock() {
var blockProperties = arguments;
return function(node) {
[].forEach.call(blockProperties, function(blockProp) {
var block = node[blockProp], previousToken, curlyToken, curlyTokenEnd, curlyTokensOnSameLine;
if (isBlock(block)) {
previousToken = context.getTokenBefore(block);
curlyToken = context.getFirstToken(block);
curlyTokenEnd = context.getLastToken(block);
curlyTokensOnSameLine = curlyToken.loc.start.line === curlyTokenEnd.loc.start.line;
if (style !== "allman" && previousToken.loc.start.line !== curlyToken.loc.start.line) {
context.report(node, OPEN_MESSAGE);
} else if (style === "allman" && previousToken.loc.start.line === curlyToken.loc.start.line && !params.allowSingleLine) {
context.report(node, OPEN_MESSAGE_ALLMAN);
} else if (block.body.length && params.allowSingleLine) {
if (curlyToken.loc.start.line === block.body[0].loc.start.line && !curlyTokensOnSameLine) {
context.report(block.body[0], BODY_MESSAGE);
} else if (curlyTokenEnd.loc.start.line === block.body[block.body.length - 1].loc.start.line && !curlyTokensOnSameLine) {
context.report(block.body[block.body.length - 1], CLOSE_MESSAGE_SINGLE);
}
} else if (block.body.length && curlyToken.loc.start.line === block.body[0].loc.start.line) {
context.report(block.body[0], BODY_MESSAGE);
}
}
});
};
}
/**
* Enforces the configured brace style on IfStatements
* @param {ASTNode} node An IfStatement node.
* @returns {void}
* @private
*/
function checkIfStatement(node) {
var tokens,
alternateIsBlock = false,
alternateIsIfBlock = false;
checkBlock("consequent", "alternate")(node);
if (node.alternate) {
alternateIsBlock = isBlock(node.alternate);
alternateIsIfBlock = node.alternate.type === "IfStatement" && isBlock(node.alternate.consequent);
if (alternateIsBlock || alternateIsIfBlock) {
tokens = context.getTokensBefore(node.alternate, 2);
if (style === "1tbs") {
if (tokens[0].loc.start.line !== tokens[1].loc.start.line && isCurlyPunctuator(tokens[0]) ) {
context.report(node.alternate, CLOSE_MESSAGE);
}
} else if (style === "stroustrup") {
if (tokens[0].loc.start.line === tokens[1].loc.start.line) {
context.report(node.alternate, CLOSE_MESSAGE_STROUSTRUP);
}
}
}
}
}
/**
* Enforces the configured brace style on TryStatements
* @param {ASTNode} node A TryStatement node.
* @returns {void}
* @private
*/
function checkTryStatement(node) {
var tokens;
checkBlock("block", "finalizer")(node);
if (isBlock(node.finalizer)) {
tokens = context.getTokensBefore(node.finalizer, 2);
if (style === "1tbs") {
if (tokens[0].loc.start.line !== tokens[1].loc.start.line) {
context.report(node.finalizer, CLOSE_MESSAGE);
}
} else if (style === "stroustrup") {
if (tokens[0].loc.start.line === tokens[1].loc.start.line) {
context.report(node.finalizer, CLOSE_MESSAGE_STROUSTRUP);
}
}
}
}
/**
* Enforces the configured brace style on CatchClauses
* @param {ASTNode} node A CatchClause node.
* @returns {void}
* @private
*/
function checkCatchClause(node) {
var previousToken = context.getTokenBefore(node),
firstToken = context.getFirstToken(node);
checkBlock("body")(node);
if (isBlock(node.body)) {
if (style === "1tbs") {
if (previousToken.loc.start.line !== firstToken.loc.start.line) {
context.report(node, CLOSE_MESSAGE);
}
} else if (style === "stroustrup") {
if (previousToken.loc.start.line === firstToken.loc.start.line) {
context.report(node, CLOSE_MESSAGE_STROUSTRUP);
}
}
}
}
/**
* Enforces the configured brace style on SwitchStatements
* @param {ASTNode} node A SwitchStatement node.
* @returns {void}
* @private
*/
function checkSwitchStatement(node) {
var tokens;
if (node.cases && node.cases.length) {
tokens = context.getTokensBefore(node.cases[0], 2);
if (tokens[0].loc.start.line !== tokens[1].loc.start.line) {
context.report(node, OPEN_MESSAGE);
}
} else {
tokens = context.getLastTokens(node, 3);
if (tokens[0].loc.start.line !== tokens[1].loc.start.line) {
context.report(node, OPEN_MESSAGE);
}
}
}
//--------------------------------------------------------------------------
// Public API
//--------------------------------------------------------------------------
return {
"FunctionDeclaration": checkBlock("body"),
"FunctionExpression": checkBlock("body"),
"ArrowFunctionExpression": checkBlock("body"),
"IfStatement": checkIfStatement,
"TryStatement": checkTryStatement,
"CatchClause": checkCatchClause,
"DoWhileStatement": checkBlock("body"),
"WhileStatement": checkBlock("body"),
"WithStatement": checkBlock("body"),
"ForStatement": checkBlock("body"),
"ForInStatement": checkBlock("body"),
"ForOfStatement": checkBlock("body"),
"SwitchStatement": checkSwitchStatement
};
};
module.exports.schema = [
{
"enum": ["1tbs", "stroustrup", "allman"]
},
{
"type": "object",
"properties": {
"allowSingleLine": {
"type": "boolean"
}
},
"additionalProperties": false
}
];
|
import './jumpToMessage';
import './providers';
import { OEmbed } from './server';
export {
OEmbed,
};
|
/**
* @author spidersharma / http://eduperiment.com/
*/
/**
* UnrealBloomPass is inspired by the bloom pass of Unreal Engine. It creates a
* mip map chain of bloom textures and blurs them with different radii. Because
* of the weighted combination of mips, and because larger blurs are done on
* higher mips, this effect provides good quality and performance.
*
* Reference:
* - https://docs.unrealengine.com/latest/INT/Engine/Rendering/PostProcessEffects/Bloom/
*/
THREE.UnrealBloomPass = function ( resolution, strength, radius, threshold ) {
THREE.Pass.call( this );
this.strength = ( strength !== undefined ) ? strength : 1;
this.radius = radius;
this.threshold = threshold;
this.resolution = ( resolution !== undefined ) ? new THREE.Vector2( resolution.x, resolution.y ) : new THREE.Vector2( 256, 256 );
// create color only once here, reuse it later inside the render function
this.clearColor = new THREE.Color( 0, 0, 0 );
// render targets
var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
this.renderTargetsHorizontal = [];
this.renderTargetsVertical = [];
this.nMips = 5;
var resx = Math.round( this.resolution.x / 2 );
var resy = Math.round( this.resolution.y / 2 );
this.renderTargetBright = new THREE.WebGLRenderTarget( resx, resy, pars );
this.renderTargetBright.texture.name = "UnrealBloomPass.bright";
this.renderTargetBright.texture.generateMipmaps = false;
for ( var i = 0; i < this.nMips; i ++ ) {
var renderTargetHorizonal = new THREE.WebGLRenderTarget( resx, resy, pars );
renderTargetHorizonal.texture.name = "UnrealBloomPass.h" + i;
renderTargetHorizonal.texture.generateMipmaps = false;
this.renderTargetsHorizontal.push( renderTargetHorizonal );
var renderTargetVertical = new THREE.WebGLRenderTarget( resx, resy, pars );
renderTargetVertical.texture.name = "UnrealBloomPass.v" + i;
renderTargetVertical.texture.generateMipmaps = false;
this.renderTargetsVertical.push( renderTargetVertical );
resx = Math.round( resx / 2 );
resy = Math.round( resy / 2 );
}
// luminosity high pass material
if ( THREE.LuminosityHighPassShader === undefined )
console.error( "THREE.UnrealBloomPass relies on THREE.LuminosityHighPassShader" );
var highPassShader = THREE.LuminosityHighPassShader;
this.highPassUniforms = THREE.UniformsUtils.clone( highPassShader.uniforms );
this.highPassUniforms[ "luminosityThreshold" ].value = threshold;
this.highPassUniforms[ "smoothWidth" ].value = 0.01;
this.materialHighPassFilter = new THREE.ShaderMaterial( {
uniforms: this.highPassUniforms,
vertexShader: highPassShader.vertexShader,
fragmentShader: highPassShader.fragmentShader,
defines: {}
} );
// Gaussian Blur Materials
this.separableBlurMaterials = [];
var kernelSizeArray = [ 3, 5, 7, 9, 11 ];
var resx = Math.round( this.resolution.x / 2 );
var resy = Math.round( this.resolution.y / 2 );
for ( var i = 0; i < this.nMips; i ++ ) {
this.separableBlurMaterials.push( this.getSeperableBlurMaterial( kernelSizeArray[ i ] ) );
this.separableBlurMaterials[ i ].uniforms[ "texSize" ].value = new THREE.Vector2( resx, resy );
resx = Math.round( resx / 2 );
resy = Math.round( resy / 2 );
}
// Composite material
this.compositeMaterial = this.getCompositeMaterial( this.nMips );
this.compositeMaterial.uniforms[ "blurTexture1" ].value = this.renderTargetsVertical[ 0 ].texture;
this.compositeMaterial.uniforms[ "blurTexture2" ].value = this.renderTargetsVertical[ 1 ].texture;
this.compositeMaterial.uniforms[ "blurTexture3" ].value = this.renderTargetsVertical[ 2 ].texture;
this.compositeMaterial.uniforms[ "blurTexture4" ].value = this.renderTargetsVertical[ 3 ].texture;
this.compositeMaterial.uniforms[ "blurTexture5" ].value = this.renderTargetsVertical[ 4 ].texture;
this.compositeMaterial.uniforms[ "bloomStrength" ].value = strength;
this.compositeMaterial.uniforms[ "bloomRadius" ].value = 0.1;
this.compositeMaterial.needsUpdate = true;
var bloomFactors = [ 1.0, 0.8, 0.6, 0.4, 0.2 ];
this.compositeMaterial.uniforms[ "bloomFactors" ].value = bloomFactors;
this.bloomTintColors = [ new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 1, 1, 1 ),
new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 1, 1, 1 ) ];
this.compositeMaterial.uniforms[ "bloomTintColors" ].value = this.bloomTintColors;
// copy material
if ( THREE.CopyShader === undefined ) {
console.error( "THREE.UnrealBloomPass relies on THREE.CopyShader" );
}
var copyShader = THREE.CopyShader;
this.copyUniforms = THREE.UniformsUtils.clone( copyShader.uniforms );
this.copyUniforms[ "opacity" ].value = 1.0;
this.materialCopy = new THREE.ShaderMaterial( {
uniforms: this.copyUniforms,
vertexShader: copyShader.vertexShader,
fragmentShader: copyShader.fragmentShader,
blending: THREE.AdditiveBlending,
depthTest: false,
depthWrite: false,
transparent: true
} );
this.enabled = true;
this.needsSwap = false;
this.oldClearColor = new THREE.Color();
this.oldClearAlpha = 1;
this.basic = new THREE.MeshBasicMaterial();
this.fsQuad = new THREE.Pass.FullScreenQuad( null );
};
THREE.UnrealBloomPass.prototype = Object.assign( Object.create( THREE.Pass.prototype ), {
constructor: THREE.UnrealBloomPass,
dispose: function () {
for ( var i = 0; i < this.renderTargetsHorizontal.length; i ++ ) {
this.renderTargetsHorizontal[ i ].dispose();
}
for ( var i = 0; i < this.renderTargetsVertical.length; i ++ ) {
this.renderTargetsVertical[ i ].dispose();
}
this.renderTargetBright.dispose();
},
setSize: function ( width, height ) {
var resx = Math.round( width / 2 );
var resy = Math.round( height / 2 );
this.renderTargetBright.setSize( resx, resy );
for ( var i = 0; i < this.nMips; i ++ ) {
this.renderTargetsHorizontal[ i ].setSize( resx, resy );
this.renderTargetsVertical[ i ].setSize( resx, resy );
this.separableBlurMaterials[ i ].uniforms[ "texSize" ].value = new THREE.Vector2( resx, resy );
resx = Math.round( resx / 2 );
resy = Math.round( resy / 2 );
}
},
render: function ( renderer, writeBuffer, readBuffer, deltaTime, maskActive ) {
this.oldClearColor.copy( renderer.getClearColor() );
this.oldClearAlpha = renderer.getClearAlpha();
var oldAutoClear = renderer.autoClear;
renderer.autoClear = false;
renderer.setClearColor( this.clearColor, 0 );
if ( maskActive ) renderer.state.buffers.stencil.setTest( false );
// Render input to screen
if ( this.renderToScreen ) {
this.fsQuad.material = this.basic;
this.basic.map = readBuffer.texture;
renderer.setRenderTarget( null );
renderer.clear();
this.fsQuad.render( renderer );
}
// 1. Extract Bright Areas
this.highPassUniforms[ "tDiffuse" ].value = readBuffer.texture;
this.highPassUniforms[ "luminosityThreshold" ].value = this.threshold;
this.fsQuad.material = this.materialHighPassFilter;
renderer.setRenderTarget( this.renderTargetBright );
renderer.clear();
this.fsQuad.render( renderer );
// 2. Blur All the mips progressively
var inputRenderTarget = this.renderTargetBright;
for ( var i = 0; i < this.nMips; i ++ ) {
this.fsQuad.material = this.separableBlurMaterials[ i ];
this.separableBlurMaterials[ i ].uniforms[ "colorTexture" ].value = inputRenderTarget.texture;
this.separableBlurMaterials[ i ].uniforms[ "direction" ].value = THREE.UnrealBloomPass.BlurDirectionX;
renderer.setRenderTarget( this.renderTargetsHorizontal[ i ] );
renderer.clear();
this.fsQuad.render( renderer );
this.separableBlurMaterials[ i ].uniforms[ "colorTexture" ].value = this.renderTargetsHorizontal[ i ].texture;
this.separableBlurMaterials[ i ].uniforms[ "direction" ].value = THREE.UnrealBloomPass.BlurDirectionY;
renderer.setRenderTarget( this.renderTargetsVertical[ i ] );
renderer.clear();
this.fsQuad.render( renderer );
inputRenderTarget = this.renderTargetsVertical[ i ];
}
// Composite All the mips
this.fsQuad.material = this.compositeMaterial;
this.compositeMaterial.uniforms[ "bloomStrength" ].value = this.strength;
this.compositeMaterial.uniforms[ "bloomRadius" ].value = this.radius;
this.compositeMaterial.uniforms[ "bloomTintColors" ].value = this.bloomTintColors;
renderer.setRenderTarget( this.renderTargetsHorizontal[ 0 ] );
renderer.clear();
this.fsQuad.render( renderer );
// Blend it additively over the input texture
this.fsQuad.material = this.materialCopy;
this.copyUniforms[ "tDiffuse" ].value = this.renderTargetsHorizontal[ 0 ].texture;
if ( maskActive ) renderer.state.buffers.stencil.setTest( true );
if ( this.renderToScreen ) {
renderer.setRenderTarget( null );
this.fsQuad.render( renderer );
} else {
renderer.setRenderTarget( readBuffer );
this.fsQuad.render( renderer );
}
// Restore renderer settings
renderer.setClearColor( this.oldClearColor, this.oldClearAlpha );
renderer.autoClear = oldAutoClear;
},
getSeperableBlurMaterial: function ( kernelRadius ) {
return new THREE.ShaderMaterial( {
defines: {
"KERNEL_RADIUS": kernelRadius,
"SIGMA": kernelRadius
},
uniforms: {
"colorTexture": { value: null },
"texSize": { value: new THREE.Vector2( 0.5, 0.5 ) },
"direction": { value: new THREE.Vector2( 0.5, 0.5 ) }
},
vertexShader:
"varying vec2 vUv;\n\
void main() {\n\
vUv = uv;\n\
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
}",
fragmentShader:
"#include <common>\
varying vec2 vUv;\n\
uniform sampler2D colorTexture;\n\
uniform vec2 texSize;\
uniform vec2 direction;\
\
float gaussianPdf(in float x, in float sigma) {\
return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma;\
}\
void main() {\n\
vec2 invSize = 1.0 / texSize;\
float fSigma = float(SIGMA);\
float weightSum = gaussianPdf(0.0, fSigma);\
vec3 diffuseSum = texture2D( colorTexture, vUv).rgb * weightSum;\
for( int i = 1; i < KERNEL_RADIUS; i ++ ) {\
float x = float(i);\
float w = gaussianPdf(x, fSigma);\
vec2 uvOffset = direction * invSize * x;\
vec3 sample1 = texture2D( colorTexture, vUv + uvOffset).rgb;\
vec3 sample2 = texture2D( colorTexture, vUv - uvOffset).rgb;\
diffuseSum += (sample1 + sample2) * w;\
weightSum += 2.0 * w;\
}\
gl_FragColor = vec4(diffuseSum/weightSum, 1.0);\n\
}"
} );
},
getCompositeMaterial: function ( nMips ) {
return new THREE.ShaderMaterial( {
defines: {
"NUM_MIPS": nMips
},
uniforms: {
"blurTexture1": { value: null },
"blurTexture2": { value: null },
"blurTexture3": { value: null },
"blurTexture4": { value: null },
"blurTexture5": { value: null },
"dirtTexture": { value: null },
"bloomStrength": { value: 1.0 },
"bloomFactors": { value: null },
"bloomTintColors": { value: null },
"bloomRadius": { value: 0.0 }
},
vertexShader:
"varying vec2 vUv;\n\
void main() {\n\
vUv = uv;\n\
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
}",
fragmentShader:
"varying vec2 vUv;\
uniform sampler2D blurTexture1;\
uniform sampler2D blurTexture2;\
uniform sampler2D blurTexture3;\
uniform sampler2D blurTexture4;\
uniform sampler2D blurTexture5;\
uniform sampler2D dirtTexture;\
uniform float bloomStrength;\
uniform float bloomRadius;\
uniform float bloomFactors[NUM_MIPS];\
uniform vec3 bloomTintColors[NUM_MIPS];\
\
float lerpBloomFactor(const in float factor) { \
float mirrorFactor = 1.2 - factor;\
return mix(factor, mirrorFactor, bloomRadius);\
}\
\
void main() {\
gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) + \
lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) + \
lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) + \
lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) + \
lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) );\
}"
} );
}
} );
THREE.UnrealBloomPass.BlurDirectionX = new THREE.Vector2( 1.0, 0.0 );
THREE.UnrealBloomPass.BlurDirectionY = new THREE.Vector2( 0.0, 1.0 );
|
(function() {
var Declaration, TransformDecl,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Declaration = require('../declaration');
TransformDecl = (function(_super) {
__extends(TransformDecl, _super);
function TransformDecl() {
return TransformDecl.__super__.constructor.apply(this, arguments);
}
TransformDecl.names = ['transform', 'transform-origin'];
TransformDecl.prototype.keykrameParents = function(decl) {
var parent;
parent = decl.parent;
while (parent) {
if (parent.type === 'atrule' && parent.name === 'keyframes') {
return true;
}
parent = parent.parent;
}
return false;
};
TransformDecl.prototype.insert = function(decl, prefix, prefixes) {
if (prefix !== '-ms-' || !this.keykrameParents(decl)) {
return TransformDecl.__super__.insert.apply(this, arguments);
}
};
return TransformDecl;
})(Declaration);
module.exports = TransformDecl;
}).call(this);
|
'use strict'
const addNestedValue = require('./add-nested-value')
const getFormFields = (form) => {
const target = {}
const elements = form.elements || []
for (let i = 0; i < elements.length; i++) {
const e = elements[i]
if (!e.hasAttribute('name')) {
continue
}
let type = 'TEXT'
switch (e.nodeName.toUpperCase()) {
case 'SELECT':
type = e.hasAttribute('multiple') ? 'MULTIPLE' : type
break
case 'INPUT':
type = e.getAttribute('type').toUpperCase()
break
}
const name = e.getAttribute('name')
if (type === 'MULTIPLE') {
for (let i = 0; i < e.length; i++) {
if (e[i].selected) {
addNestedValue(target, name, e[i].value)
}
}
} else if ((type !== 'RADIO' && type !== 'CHECKBOX') || e.checked) {
addNestedValue(target, name, e.value)
}
}
return target
}
module.exports = getFormFields
|
!function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror"),require("./runmode")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","./runmode"],e):e(CodeMirror)}(function(d){"use strict";var n=/^(p|li|div|h\\d|pre|blockquote|td)$/;function u(e,o){if(3==e.nodeType)return o.push(e.nodeValue);for(var r=e.firstChild;r;r=r.nextSibling)u(r,o),n.test(e.nodeType)&&o.push("\n")}d.colorize=function(e,o){e=e||document.body.getElementsByTagName("pre");for(var r=0;r<e.length;++r){var n,t=e[r],i=t.getAttribute("data-lang")||o;i&&(u(t,n=[]),t.innerHTML="",d.runMode(n.join(""),i,t),t.className+=" cm-s-default")}}}); |
'use strict';
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _container = require('./container');
var _container2 = _interopRequireDefault(_container);
var _warnOnce = require('./warn-once');
var _warnOnce2 = _interopRequireDefault(_warnOnce);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Represents an at-rule.
*
* If it’s followed in the CSS by a {} block, this node will have
* a nodes property representing its children.
*
* @extends Container
*
* @example
* const root = postcss.parse('@charset "UTF-8"; @media print {}');
*
* const charset = root.first;
* charset.type //=> 'atrule'
* charset.nodes //=> undefined
*
* const media = root.last;
* media.nodes //=> []
*/
var AtRule = function (_Container) {
_inherits(AtRule, _Container);
function AtRule(defaults) {
_classCallCheck(this, AtRule);
var _this = _possibleConstructorReturn(this, _Container.call(this, defaults));
_this.type = 'atrule';
return _this;
}
AtRule.prototype.append = function append() {
var _Container$prototype$;
if (!this.nodes) this.nodes = [];
for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) {
children[_key] = arguments[_key];
}
return (_Container$prototype$ = _Container.prototype.append).call.apply(_Container$prototype$, [this].concat(children));
};
AtRule.prototype.prepend = function prepend() {
var _Container$prototype$2;
if (!this.nodes) this.nodes = [];
for (var _len2 = arguments.length, children = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
children[_key2] = arguments[_key2];
}
return (_Container$prototype$2 = _Container.prototype.prepend).call.apply(_Container$prototype$2, [this].concat(children));
};
_createClass(AtRule, [{
key: 'afterName',
get: function get() {
(0, _warnOnce2.default)('AtRule#afterName was deprecated. Use AtRule#raws.afterName');
return this.raws.afterName;
},
set: function set(val) {
(0, _warnOnce2.default)('AtRule#afterName was deprecated. Use AtRule#raws.afterName');
this.raws.afterName = val;
}
}, {
key: '_params',
get: function get() {
(0, _warnOnce2.default)('AtRule#_params was deprecated. Use AtRule#raws.params');
return this.raws.params;
},
set: function set(val) {
(0, _warnOnce2.default)('AtRule#_params was deprecated. Use AtRule#raws.params');
this.raws.params = val;
}
/**
* @memberof AtRule#
* @member {string} name - the at-rule’s name immediately follows the `@`
*
* @example
* const root = postcss.parse('@media print {}');
* media.name //=> 'media'
* const media = root.first;
*/
/**
* @memberof AtRule#
* @member {string} params - the at-rule’s parameters, the values
* that follow the at-rule’s name but precede
* any {} block
*
* @example
* const root = postcss.parse('@media print, screen {}');
* const media = root.first;
* media.params //=> 'print, screen'
*/
/**
* @memberof AtRule#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains true if the last child has
* an (optional) semicolon.
* * `afterName`: the space between the at-rule name and its parameters.
*
* PostCSS cleans at-rule parameters from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse(' @media\nprint {\n}')
* root.first.first.raws //=> { before: ' ',
* // between: ' ',
* // afterName: '\n',
* // after: '\n' }
*/
}]);
return AtRule;
}(_container2.default);
exports.default = AtRule;
module.exports = exports['default']; |
/*
GRUNT instructions
1. ensure you have dependencies installed run `npm install` in the root directory of the repo to get dev dependencies
2. run `grunt` in root dir of the repo in a shell to get the watcher started
The watcher looks at files. When a file is added or changed it passes the file through jshint
3. run `grunt test` to execute all unit tests and get output
4. run `grunt jshint` to pass all files through linter
MADGE instructions
1. run `npm install -g madge` to get madge executable
2. Insure graphviz is installed and the bin folder is in your path.
3. run `madge -x "node_modules|util|stream|os|assert|fs|http" -i graph.png ./` to generate graph.png
which is the dependency graph for the current build.
*/
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.loadTasks('./devops/grunt-wiki');
var files = ['Gruntfile.js', 'libs/**/*.js', 'libs/**/**/*.js', 'test/*.js', 'bin/csvtojson',
'bin/csvtojson.js', 'devops/*.js'
];
grunt.initConfig({
uglify: {
client: {
options: {
mangle: true,
banner:"/*Automatically Generated. Do not modify.*/\n"
},
src: "./dist/csvtojson.js",
dest: "./dist/csvtojson.min.js",
}
},
browserify: {
dist: {
src: "./browser_index.js",
dest: "./dist/csvtojson.js"
}
},
jshint: {
all: {
src: files,
options: {
'globals': { // false makes global variable readonly true is read/write
'describe': false,
'it': false
},
// see the docs for full list of options http://jshint.com/docs/options/
'bitwise': true,
'curly': true,
'eqeqeq': true,
'forin': true,
'freeze': true,
'funcscope': true,
'futurehostile': true,
'latedef': false,
'maxcomplexity': 10, // arbitrary but anything over 10 quickly becomes hard to think about
'maxdepth': 3, // also arbitrary. Deeply nested functions should be refactored to use helper functions.
'maxparams': 4, // arbitrary. Consider using an object literal instead of list of params.
'nocomma': true,
//'nonew': true, // In the future when all objects are refactored to avoid new.
//'strict': true, // in the future when all functions are closer to adhering to strict.
'notypeof': true,
'undef': true,
'unused': true,
'node': true // defines node globals
}
}
},
mochaTest: {
test: {
src: [files[3]]
}
},
watch: {
files: files,
tasks: ['newer:jshint:all', 'mochaTest'],
options: {
spawn: false,
event: ['changed', 'added']
}
},
wiki: {},
});
grunt.registerTask('default', ['watch']);
grunt.registerTask('test', ['mochaTest']);
grunt.registerTask("build:browser",["browserify:dist","uglify:client"]);
};
|
/*
This file is part of Ext JS 4.2
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
Commercial Usage
Licensees holding valid commercial licenses may use this file in accordance with the Commercial
Software License Agreement provided with the Software or, alternatively, in accordance with the
terms contained in a written agreement between you and Sencha.
If you are unsure which license is appropriate for your use, please contact the sales department
at http://www.sencha.com/contact.
Build date: 2013-09-18 17:18:59 (940c324ac822b840618a3a8b2b4b873f83a1a9b1)
*/
/**
* Defines a mask for a chart's series.
* The 'chart' member must be set prior to rendering.
*
* A Mask can be used to select a certain region in a chart.
* When enabled, the `select` event will be triggered when a
* region is selected by the mask, allowing the user to perform
* other tasks like zooming on that region, etc.
*
* In order to use the mask one has to set the Chart `mask` option to
* `true`, `vertical` or `horizontal`. Then a possible configuration for the
* listener could be:
*
* items: {
* xtype: 'chart',
* animate: true,
* store: store1,
* mask: 'horizontal',
* listeners: {
* select: {
* fn: function(me, selection) {
* me.setZoom(selection);
* me.mask.hide();
* }
* }
* }
* }
*
* In this example we zoom the chart to that particular region. You can also get
* a handle to a mask instance from the chart object. The `chart.mask` element is a
* `Ext.Panel`.
*
*/
Ext.define('Ext.chart.Mask', {
requires: [
'Ext.chart.MaskLayer'
],
/**
* @cfg {Boolean/String} mask
* Enables selecting a region on chart. True to enable any selection,
* 'horizontal' or 'vertical' to restrict the selection to X or Y axis.
*
* The mask in itself will do nothing but fire 'select' event.
* See {@link Ext.chart.Mask} for example.
*/
/**
* Creates new Mask.
* @param {Object} [config] Config object.
*/
constructor: function(config) {
var me = this;
me.addEvents('select');
if (config) {
Ext.apply(me, config);
}
if (me.enableMask) {
me.on('afterrender', function() {
//create a mask layer component
var comp = new Ext.chart.MaskLayer({
renderTo: me.el,
hidden: true
});
comp.el.on({
'mousemove': function(e) {
me.onMouseMove(e);
},
'mouseup': function(e) {
me.onMouseUp(e);
}
});
comp.initDraggable();
me.maskType = me.mask;
me.mask = comp;
me.maskSprite = me.surface.add({
type: 'path',
path: ['M', 0, 0],
zIndex: 1001,
opacity: 0.6,
hidden: true,
stroke: '#00f',
cursor: 'crosshair'
});
}, me, { single: true });
}
},
onMouseUp: function(e) {
var me = this,
bbox = me.bbox || me.chartBBox,
sel;
me.maskMouseDown = false;
me.mouseDown = false;
if (me.mouseMoved) {
me.handleMouseEvent(e);
me.mouseMoved = false;
sel = me.maskSelection;
me.fireEvent('select', me, {
x: sel.x - bbox.x,
y: sel.y - bbox.y,
width: sel.width,
height: sel.height
});
}
},
onMouseDown: function(e) {
this.handleMouseEvent(e);
},
onMouseMove: function(e) {
this.handleMouseEvent(e);
},
handleMouseEvent: function(e) {
var me = this,
mask = me.maskType,
bbox = me.bbox || me.chartBBox,
x = bbox.x,
y = bbox.y,
math = Math,
floor = math.floor,
abs = math.abs,
min = math.min,
max = math.max,
height = floor(y + bbox.height),
width = floor(x + bbox.width),
staticX = e.getPageX() - me.el.getX(),
staticY = e.getPageY() - me.el.getY(),
maskMouseDown = me.maskMouseDown,
path;
staticX = max(staticX, x);
staticY = max(staticY, y);
staticX = min(staticX, width);
staticY = min(staticY, height);
if (e.type === 'mousedown') {
// remember the cursor location
me.mouseDown = true;
me.mouseMoved = false;
me.maskMouseDown = {
x: staticX,
y: staticY
};
}
else {
// mousedown or mouseup:
// track the cursor to display the selection
me.mouseMoved = me.mouseDown;
if (maskMouseDown && me.mouseDown) {
if (mask == 'horizontal') {
staticY = y;
maskMouseDown.y = height;
}
else if (mask == 'vertical') {
staticX = x;
maskMouseDown.x = width;
}
width = maskMouseDown.x - staticX;
height = maskMouseDown.y - staticY;
path = ['M', staticX, staticY, 'l', width, 0, 0, height, -width, 0, 'z'];
me.maskSelection = {
x: (width > 0 ? staticX : staticX + width) + me.el.getX(),
y: (height > 0 ? staticY : staticY + height) + me.el.getY(),
width: abs(width),
height: abs(height)
};
me.mask.updateBox(me.maskSelection);
me.mask.show();
me.maskSprite.setAttributes({
hidden: true
}, true);
}
else {
if (mask == 'horizontal') {
path = ['M', staticX, y, 'L', staticX, height];
}
else if (mask == 'vertical') {
path = ['M', x, staticY, 'L', width, staticY];
}
else {
path = ['M', staticX, y, 'L', staticX, height, 'M', x, staticY, 'L', width, staticY];
}
me.maskSprite.setAttributes({
path: path,
'stroke-width': mask === true ? 1 : 1,
hidden: false
}, true);
}
}
},
onMouseLeave: function(e) {
var me = this;
me.mouseMoved = false;
me.mouseDown = false;
me.maskMouseDown = false;
me.mask.hide();
me.maskSprite.hide(true);
}
});
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'format', 'gl', {
label: 'Formato',
panelTitle: 'Formato',
tag_address: 'Enderezo',
tag_div: 'Paragraph (DIV)',
tag_h1: 'Enacabezado 1',
tag_h2: 'Encabezado 2',
tag_h3: 'Encabezado 3',
tag_h4: 'Encabezado 4',
tag_h5: 'Encabezado 5',
tag_h6: 'Encabezado 6',
tag_p: 'Normal',
tag_pre: 'Formateado'
});
|
// moment.js language configuration
// language : german (de)
// author : lluchs : https://github.com/lluchs
// author: Menelion Elensúle: https://github.com/Oire
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['moment'], factory); // AMD
} else if (typeof exports === 'object') {
module.exports = factory(require('../moment')); // Node
} else {
factory(window.moment); // Browser global
}
}(function (moment) {
function processRelativeTime(number, withoutSuffix, key, isFuture) {
var format = {
'm': ['eine Minute', 'einer Minute'],
'h': ['eine Stunde', 'einer Stunde'],
'd': ['ein Tag', 'einem Tag'],
'dd': [number + ' Tage', number + ' Tagen'],
'M': ['ein Monat', 'einem Monat'],
'MM': [number + ' Monate', number + ' Monaten'],
'y': ['ein Jahr', 'einem Jahr'],
'yy': [number + ' Jahre', number + ' Jahren']
};
return withoutSuffix ? format[key][0] : format[key][1];
}
return moment.lang('de', {
months : "Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),
monthsShort : "Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"),
weekdays : "Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"),
weekdaysShort : "So._Mo._Di._Mi._Do._Fr._Sa.".split("_"),
weekdaysMin : "So_Mo_Di_Mi_Do_Fr_Sa".split("_"),
longDateFormat : {
LT: "H:mm [Uhr]",
L : "DD.MM.YYYY",
LL : "D. MMMM YYYY",
LLL : "D. MMMM YYYY LT",
LLLL : "dddd, D. MMMM YYYY LT"
},
calendar : {
sameDay: "[Heute um] LT",
sameElse: "L",
nextDay: '[Morgen um] LT',
nextWeek: 'dddd [um] LT',
lastDay: '[Gestern um] LT',
lastWeek: '[letzten] dddd [um] LT'
},
relativeTime : {
future : "in %s",
past : "vor %s",
s : "ein paar Sekunden",
m : processRelativeTime,
mm : "%d Minuten",
h : processRelativeTime,
hh : "%d Stunden",
d : processRelativeTime,
dd : processRelativeTime,
M : processRelativeTime,
MM : processRelativeTime,
y : processRelativeTime,
yy : processRelativeTime
},
ordinal : '%d.',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
}));
|
version https://git-lfs.github.com/spec/v1
oid sha256:c8fac8516afadc98edd20403611c110a4ca1165abd2c4314b1492a5e8b70d860
size 570
|
/**
* Created by aleckim on 2018. 1. 2..
*/
var start = angular.module('controller.nation', []);
start.controller('NationCtrl', function($scope, Util, WeatherUtil, $ionicHistory, $ionicLoading, Units) {
var TYPE_SKY_TEMP = 0;
var TYPE_RAIN = 1;
var TYPE_WIND = 2;
var weatherDataList = [];
var weatherType = TYPE_SKY_TEMP;
//0 = sky/temp, 1 = rain, 2 = wind
$scope.getNationName = function () {
if (Util.region === 'KR') {
return 'LOC_KOREA';
}
else if (Util.region === 'JP') {
return 'LOC_CHINA';
}
else if (Util.region === 'CN') {
return 'LOC_CHINA';
}
else if (Util.region === 'US') {
return 'LOC_USA';
}
else if (Util.region === 'GB') {
return 'LOC_UK';
}
};
$scope.cityList = [
{name:"서울", top: 60, left: 100},
{name:"춘천", top: 20, left: 160},
{name:"강릉", top: 40, left: 230},
{name:"대전", top: 155, left: 90},
{name:"청주", top: 130, left: 164},
{name:"전주", top: 240, left: 78},
{name:"광주", top: 322, left: 74},
{name:"대구", top: 220, left: 190},
{name:"부산", top: 300, left: 230},
{name:"제주", top: 420, left: 60},
{name:"인천", top: 70, left: 36},
{name:"목포", top: 360, left: 0},
{name:"여수", top: 320, left: 135},
{name:"안동", top: 130, left: 225},
{name:"울산", top: 220, left: 270}
];
$scope.onClose = function() {
Util.ga.trackEvent('action', 'click', 'nation back');
//convertUnits
$ionicHistory.goBack();
};
$scope.region = Util.region;
$scope.changeWeatherType = function (type) {
weatherType = type;
};
function _findCity(name, list) {
return list.find(function (obj) {
var str = obj.regionName+"/"+obj.cityName+"/"+obj.townName;
return str.indexOf(name) != -1;
});
}
$scope.getIcon = function (name) {
var icon;
var city;
try {
if (!Array.isArray(weatherDataList)) {
return icon;
}
city = _findCity(name, weatherDataList);
if (city) {
if (weatherType === TYPE_SKY_TEMP || weatherType === TYPE_RAIN) {
icon = city.current.skyIcon;
}
else if (weatherType === TYPE_WIND) {
}
}
}
catch (err) {
Util.ga.trackException(err, false);
}
return icon;
};
$scope.getText1 = function (name) {
var text1;
var city;
try {
if (!Array.isArray(weatherDataList)) {
return text1;
}
city = _findCity(name, weatherDataList);
if (city) {
if (weatherType === TYPE_SKY_TEMP) {
text1 = city.current.t1h;
}
else if (weatherType === TYPE_RAIN) {
text1 = city.current.rn1;
}
else if (weatherType === TYPE_WIND) {
text1 = city.current.wdd;
}
$scope.hasText1 = true;
}
}
catch (err) {
Util.ga.trackException(err, false);
}
return text1;
};
$scope.getText2 = function (name) {
var text2;
var city;
try {
if (!Array.isArray(weatherDataList)) {
return text2;
}
city = _findCity(name, weatherDataList);
if (city) {
if (weatherType === TYPE_SKY_TEMP) {
}
else if (weatherType === TYPE_RAIN) {
}
else if (weatherType === TYPE_WIND) {
text2 = city.current.wsd;
}
}
}
catch (err) {
Util.ga.trackException(err, false);
}
return text2;
};
$scope.getText1Unit = function () {
switch (weatherType) {
case TYPE_RAIN:
return Units.getUnit('precipitationUnit');
}
};
$scope.getText2Unit = function () {
switch (weatherType) {
case TYPE_WIND:
return Units.getUnit('windSpeedUnit');
}
};
function init() {
$ionicLoading.show();
WeatherUtil.getNationWeather(Util.region)
.then(
function (data) {
weatherDataList = data.weather;
},
function (err) {
Util.ga.trackException(err, false);
}
)
.finally(function () {
$ionicLoading.hide();
console.info('National weather is loaded');
});
}
init();
});
|
Package.describe({
summary: "Make HTTP calls to remote servers",
version: '1.1.1'
});
Npm.depends({request: "2.53.0"});
Package.onUse(function (api) {
api.use([
'underscore',
'url',
'ecmascript'
]);
api.export('HTTP');
api.export('HTTPInternals', 'server');
api.addFiles('httpcall_common.js', ['client', 'server']);
api.addFiles('httpcall_client.js', 'client');
api.addFiles('httpcall_server.js', 'server');
api.addFiles('deprecated.js', ['client', 'server']);
});
Package.onTest(function (api) {
api.use('webapp', 'server');
api.use('underscore');
api.use('random');
api.use('jquery', 'client');
api.use('http', ['client', 'server']);
api.use('tinytest');
api.use('test-helpers', ['client', 'server']);
api.addFiles('test_responder.js', 'server');
api.addFiles('httpcall_tests.js', ['client', 'server']);
api.addAssets('test_static.serveme', 'client');
});
|
/* global require, module */
/* jshint node: true*/
var EmberApp = require('ember-cli/lib/broccoli/ember-addon');
var merge = require('broccoli-merge-trees');
var globals = require('./lib/globals');
var yuidoc = require('./lib/yuidoc');
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
jscsOptions: {
enabled: true,
excludeFiles: ['tests/dummy/config']
}
// Add options here
});
/*
This build file specifes the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
var appTree = app.toTree();
if (process.env.EMBER_ENV === 'production') {
var globalsBuild = globals('addon', 'config/package-manager-files');
return merge([appTree, globalsBuild, yuidoc()]);
} else {
return appTree;
}
};
|
module.exports = {
parse : {
appKey:'UF8d6AANHEJQF16gli8iFuxm4M8lkkX1fOQUwy76',
restKey:'nIIafPJCIxjKPoRqGiXc5YCrQ8D08F1qef8vcxrZ'
}
, screenshots : {
apiUrl:'http://site2img-api.herokuapp.com/'
}
, site: {
baseUrl: 'http://in1-app.herokuapp.com'
}
}; |
import t from "../../lib/index.js";
import definitions from "../../lib/definitions/index.js";
import formatBuilderName from "../utils/formatBuilderName.js";
import lowerFirst from "../utils/lowerFirst.js";
import stringifyValidator from "../utils/stringifyValidator.js";
function areAllRemainingFieldsNullable(fieldName, fieldNames, fields) {
const index = fieldNames.indexOf(fieldName);
return fieldNames.slice(index).every(_ => isNullable(fields[_]));
}
function hasDefault(field) {
return field.default != null;
}
function isNullable(field) {
return field.optional || hasDefault(field);
}
function sortFieldNames(fields, type) {
return fields.sort((fieldA, fieldB) => {
const indexA = t.BUILDER_KEYS[type].indexOf(fieldA);
const indexB = t.BUILDER_KEYS[type].indexOf(fieldB);
if (indexA === indexB) return fieldA < fieldB ? -1 : 1;
if (indexA === -1) return 1;
if (indexB === -1) return -1;
return indexA - indexB;
});
}
function generateBuilderArgs(type) {
const fields = t.NODE_FIELDS[type];
const fieldNames = sortFieldNames(Object.keys(t.NODE_FIELDS[type]), type);
const builderNames = t.BUILDER_KEYS[type];
const args = [];
fieldNames.forEach(fieldName => {
const field = fields[fieldName];
// Future / annoying TODO:
// MemberExpression.property, ObjectProperty.key and ObjectMethod.key need special cases; either:
// - convert the declaration to chain() like ClassProperty.key and ClassMethod.key,
// - declare an alias type for valid keys, detect the case and reuse it here,
// - declare a disjoint union with, for example, ObjectPropertyBase,
// ObjectPropertyLiteralKey and ObjectPropertyComputedKey, and declare ObjectProperty
// as "ObjectPropertyBase & (ObjectPropertyLiteralKey | ObjectPropertyComputedKey)"
let typeAnnotation = stringifyValidator(field.validate, "t.");
if (isNullable(field) && !hasDefault(field)) {
typeAnnotation += " | null";
}
if (builderNames.includes(fieldName)) {
const bindingIdentifierName = t.toBindingIdentifierName(fieldName);
if (areAllRemainingFieldsNullable(fieldName, builderNames, fields)) {
args.push(
`${bindingIdentifierName}${
isNullable(field) ? "?:" : ":"
} ${typeAnnotation}`
);
} else {
args.push(
`${bindingIdentifierName}: ${typeAnnotation}${
isNullable(field) ? " | undefined" : ""
}`
);
}
}
});
return args;
}
export default function generateBuilders(kind) {
return kind === "uppercase.js"
? generateUppercaseBuilders()
: generateLowercaseBuilders();
}
function generateLowercaseBuilders() {
let output = `/*
* This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build'
*/
import builder from "../builder";
import type * as t from "../..";
/* eslint-disable @typescript-eslint/no-unused-vars */
`;
const reservedNames = new Set(["super", "import"]);
Object.keys(definitions.BUILDER_KEYS).forEach(type => {
const defArgs = generateBuilderArgs(type);
const formatedBuilderName = formatBuilderName(type);
const formatedBuilderNameLocal = reservedNames.has(formatedBuilderName)
? `_${formatedBuilderName}`
: formatedBuilderName;
output += `${
formatedBuilderNameLocal === formatedBuilderName ? "export " : ""
}function ${formatedBuilderNameLocal}(${defArgs.join(
", "
)}): t.${type} { return builder("${type}", ...arguments); }\n`;
if (formatedBuilderNameLocal !== formatedBuilderName) {
output += `export { ${formatedBuilderNameLocal} as ${formatedBuilderName} };\n`;
}
// This is needed for backwards compatibility.
// It should be removed in the next major version.
// JSXIdentifier -> jSXIdentifier
if (/^[A-Z]{2}/.test(type)) {
output += `export { ${formatedBuilderNameLocal} as ${lowerFirst(
type
)} }\n`;
}
});
Object.keys(definitions.DEPRECATED_KEYS).forEach(type => {
const newType = definitions.DEPRECATED_KEYS[type];
const formatedBuilderName = formatBuilderName(type);
output += `/** @deprecated */
function ${type}(...args: Array<any>): any {
console.trace("The node type ${type} has been renamed to ${newType}");
return builder("${type}", ...args);
}
export { ${type} as ${formatedBuilderName} };\n`;
// This is needed for backwards compatibility.
// It should be removed in the next major version.
// JSXIdentifier -> jSXIdentifier
if (/^[A-Z]{2}/.test(type)) {
output += `export { ${type} as ${lowerFirst(type)} }\n`;
}
});
return output;
}
function generateUppercaseBuilders() {
let output = `/*
* This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build'
*/
/**
* This file is written in JavaScript and not TypeScript because uppercase builders
* conflict with AST types. TypeScript reads the uppercase.d.ts file instead.
*/
export {\n`;
Object.keys(definitions.BUILDER_KEYS).forEach(type => {
const formatedBuilderName = formatBuilderName(type);
output += ` ${formatedBuilderName} as ${type},\n`;
});
Object.keys(definitions.DEPRECATED_KEYS).forEach(type => {
const formatedBuilderName = formatBuilderName(type);
output += ` ${formatedBuilderName} as ${type},\n`;
});
output += ` } from './index';\n`;
return output;
}
|
Craft.StructureTableSorter = Garnish.DragSort.extend({
// Properties
// =========================================================================
tableView: null,
structureId: null,
maxLevels: null,
_helperMargin: null,
_$firstRowCells: null,
_$titleHelperCell: null,
_titleHelperCellOuterWidth: null,
_ancestors: null,
_updateAncestorsFrame: null,
_updateAncestorsProxy: null,
_draggeeLevel: null,
_draggeeLevelDelta: null,
draggingLastElements: null,
_loadingDraggeeLevelDelta: false,
_targetLevel: null,
_targetLevelBounds: null,
_positionChanged: null,
// Public methods
// =========================================================================
/**
* Constructor
*/
init: function(tableView, $elements, settings)
{
this.tableView = tableView;
this.structureId = this.tableView.$table.data('structure-id');
this.maxLevels = parseInt(this.tableView.$table.attr('data-max-levels'));
settings = $.extend({}, Craft.StructureTableSorter.defaults, settings, {
handle: '.move',
collapseDraggees: true,
singleHelper: true,
helperSpacingY: 2,
magnetStrength: 4,
helper: $.proxy(this, 'getHelper'),
helperLagBase: 1.5,
axis: Garnish.Y_AXIS
});
this.base($elements, settings);
},
/**
* Start Dragging
*/
startDragging: function()
{
this._helperMargin = Craft.StructureTableSorter.HELPER_MARGIN + (this.tableView.elementIndex.actions ? 24 : 0);
this.base();
},
/**
* Returns the draggee rows (including any descendent rows).
*/
findDraggee: function()
{
this._draggeeLevel = this._targetLevel = this.$targetItem.data('level');
this._draggeeLevelDelta = 0;
var $draggee = $(this.$targetItem),
$nextRow = this.$targetItem.next();
while ($nextRow.length)
{
// See if this row is a descendant of the draggee
var nextRowLevel = $nextRow.data('level');
if (nextRowLevel <= this._draggeeLevel)
{
break;
}
// Is this the deepest descendant we've seen so far?
var nextRowLevelDelta = nextRowLevel - this._draggeeLevel;
if (nextRowLevelDelta > this._draggeeLevelDelta)
{
this._draggeeLevelDelta = nextRowLevelDelta;
}
// Add it and prep the next row
$draggee = $draggee.add($nextRow);
$nextRow = $nextRow.next();
}
// Are we dragging the last elements on the page?
this.draggingLastElements = !$nextRow.length;
// Do we have a maxLevels to enforce,
// and does it look like this draggee has descendants we don't know about yet?
if (
this.maxLevels &&
this.draggingLastElements &&
this.tableView.getMorePending()
)
{
// Only way to know the true descendant level delta is to ask PHP
this._loadingDraggeeLevelDelta = true;
var data = this._getAjaxBaseData(this.$targetItem);
Craft.postActionRequest('structures/getElementLevelDelta', data, $.proxy(function(response, textStatus)
{
if (textStatus == 'success')
{
this._loadingDraggeeLevelDelta = false;
if (this.dragging)
{
this._draggeeLevelDelta = response.delta;
this.drag(false);
}
}
}, this));
}
return $draggee;
},
/**
* Returns the drag helper.
*/
getHelper: function($helperRow)
{
var $outerContainer = $('<div class="elements datatablesorthelper"/>').appendTo(Garnish.$bod),
$innerContainer = $('<div class="tableview"/>').appendTo($outerContainer),
$table = $('<table class="data"/>').appendTo($innerContainer),
$tbody = $('<tbody/>').appendTo($table);
$helperRow.appendTo($tbody);
// Copy the column widths
this._$firstRowCells = this.tableView.$elementContainer.children('tr:first').children();
var $helperCells = $helperRow.children();
for (var i = 0; i < $helperCells.length; i++)
{
var $helperCell = $($helperCells[i]);
// Skip the checkbox cell
if ($helperCell.hasClass('checkbox-cell'))
{
$helperCell.remove();
continue;
}
// Hard-set the cell widths
var $firstRowCell = $(this._$firstRowCells[i]),
width = $firstRowCell.width();
$firstRowCell.width(width);
$helperCell.width(width);
// Is this the title cell?
if (Garnish.hasAttr($firstRowCell, 'data-titlecell'))
{
this._$titleHelperCell = $helperCell;
var padding = parseInt($firstRowCell.css('padding-'+Craft.left));
this._titleHelperCellOuterWidth = width + padding - (this.tableView.elementIndex.actions ? 12 : 0);
$helperCell.css('padding-'+Craft.left, Craft.StructureTableSorter.BASE_PADDING);
}
}
return $outerContainer;
},
/**
* Returns whether the draggee can be inserted before a given item.
*/
canInsertBefore: function($item)
{
if (this._loadingDraggeeLevelDelta)
{
return false;
}
return (this._getLevelBounds($item.prev(), $item) !== false);
},
/**
* Returns whether the draggee can be inserted after a given item.
*/
canInsertAfter: function($item)
{
if (this._loadingDraggeeLevelDelta)
{
return false;
}
return (this._getLevelBounds($item, $item.next()) !== false);
},
// Events
// -------------------------------------------------------------------------
/**
* On Drag Start
*/
onDragStart: function()
{
// Get the initial set of ancestors, before the item gets moved
this._ancestors = this._getAncestors(this.$targetItem, this.$targetItem.data('level'));
// Set the initial target level bounds
this._setTargetLevelBounds();
// Check to see if we should load more elements now
this.tableView.maybeLoadMore();
this.base();
},
/**
* On Drag
*/
onDrag: function()
{
this.base();
this._updateIndent();
},
/**
* On Insertion Point Change
*/
onInsertionPointChange: function()
{
this._setTargetLevelBounds();
this._updateAncestorsBeforeRepaint();
this.base();
},
/**
* On Drag Stop
*/
onDragStop: function()
{
this._positionChanged = false;
this.base();
// Update the draggee's padding if the position just changed
// ---------------------------------------------------------------------
if (this._targetLevel != this._draggeeLevel)
{
var levelDiff = this._targetLevel - this._draggeeLevel;
for (var i = 0; i < this.$draggee.length; i++)
{
var $draggee = $(this.$draggee[i]),
oldLevel = $draggee.data('level'),
newLevel = oldLevel + levelDiff,
padding = Craft.StructureTableSorter.BASE_PADDING + (this.tableView.elementIndex.actions ? 7 : 0) + this._getLevelIndent(newLevel);
$draggee.data('level', newLevel);
$draggee.find('.element').data('level', newLevel);
$draggee.children('[data-titlecell]:first').css('padding-'+Craft.left, padding);
}
this._positionChanged = true;
}
// Keep in mind this could have also been set by onSortChange()
if (this._positionChanged)
{
// Tell the server about the new position
// -----------------------------------------------------------------
var data = this._getAjaxBaseData(this.$draggee);
// Find the previous sibling/parent, if there is one
var $prevRow = this.$draggee.first().prev();
while ($prevRow.length)
{
var prevRowLevel = $prevRow.data('level');
if (prevRowLevel == this._targetLevel)
{
data.prevId = $prevRow.data('id');
break;
}
if (prevRowLevel < this._targetLevel)
{
data.parentId = $prevRow.data('id');
// Is this row collapsed?
var $toggle = $prevRow.find('> td > .toggle');
if (!$toggle.hasClass('expanded'))
{
// Make it look expanded
$toggle.addClass('expanded');
// Add a temporary row
var $spinnerRow = this.tableView._createSpinnerRowAfter($prevRow);
// Remove the target item
if (this.tableView.elementSelect)
{
this.tableView.elementSelect.removeItems(this.$targetItem);
}
this.removeItems(this.$targetItem);
this.$targetItem.remove();
this.tableView._totalVisible--;
}
break;
}
$prevRow = $prevRow.prev();
}
Craft.postActionRequest('structures/moveElement', data, $.proxy(function(response, textStatus)
{
if (textStatus == 'success')
{
Craft.cp.displayNotice(Craft.t('New position saved.'));
this.onPositionChange();
// Were we waiting on this to complete so we can expand the new parent?
if ($spinnerRow && $spinnerRow.parent().length)
{
$spinnerRow.remove();
this.tableView._expandElement($toggle, true);
}
// See if we should run any pending tasks
Craft.cp.runPendingTasks();
}
}, this));
}
},
onSortChange: function()
{
if (this.tableView.elementSelect)
{
this.tableView.elementSelect.resetItemOrder();
}
this._positionChanged = true;
this.base();
},
onPositionChange: function()
{
Garnish.requestAnimationFrame($.proxy(function()
{
this.trigger('positionChange');
this.settings.onPositionChange();
}, this));
},
onReturnHelpersToDraggees: function()
{
this._$firstRowCells.css('width', '');
// If we were dragging the last elements on the page and ended up loading any additional elements in,
// there could be a gap between the last draggee item and whatever now comes after it.
// So remove the post-draggee elements and possibly load up the next batch.
if (this.draggingLastElements && this.tableView.getMorePending())
{
// Update the element index's record of how many items are actually visible
this.tableView._totalVisible += (this.newDraggeeIndexes[0] - this.oldDraggeeIndexes[0]);
var $postDraggeeItems = this.$draggee.last().nextAll();
if ($postDraggeeItems.length)
{
this.removeItems($postDraggeeItems);
$postDraggeeItems.remove();
this.tableView.maybeLoadMore();
}
}
this.base();
},
// Private methods
// =========================================================================
/**
* Returns the min and max levels that the draggee could occupy between
* two given rows, or false if it’s not going to work out.
*/
_getLevelBounds: function($prevRow, $nextRow)
{
// Can't go any lower than the next row, if there is one
if ($nextRow && $nextRow.length)
{
this._getLevelBounds._minLevel = $nextRow.data('level');
}
else
{
this._getLevelBounds._minLevel = 1;
}
// Can't go any higher than the previous row + 1
if ($prevRow && $prevRow.length)
{
this._getLevelBounds._maxLevel = $prevRow.data('level') + 1;
}
else
{
this._getLevelBounds._maxLevel = 1;
}
// Does this structure have a max level?
if (this.maxLevels)
{
// Make sure it's going to fit at all here
if (
this._getLevelBounds._minLevel != 1 &&
this._getLevelBounds._minLevel + this._draggeeLevelDelta > this.maxLevels
)
{
return false;
}
// Limit the max level if we have to
if (this._getLevelBounds._maxLevel + this._draggeeLevelDelta > this.maxLevels)
{
this._getLevelBounds._maxLevel = this.maxLevels - this._draggeeLevelDelta;
if (this._getLevelBounds._maxLevel < this._getLevelBounds._minLevel)
{
this._getLevelBounds._maxLevel = this._getLevelBounds._minLevel;
}
}
}
return {
min: this._getLevelBounds._minLevel,
max: this._getLevelBounds._maxLevel
};
},
/**
* Determines the min and max possible levels at the current draggee's position.
*/
_setTargetLevelBounds: function()
{
this._targetLevelBounds = this._getLevelBounds(
this.$draggee.first().prev(),
this.$draggee.last().next()
);
},
/**
* Determines the target level based on the current mouse position.
*/
_updateIndent: function(forcePositionChange)
{
// Figure out the target level
// ---------------------------------------------------------------------
// How far has the cursor moved?
this._updateIndent._mouseDist = this.realMouseX - this.mousedownX;
// Flip that if this is RTL
if (Craft.orientation == 'rtl')
{
this._updateIndent._mouseDist *= -1;
}
// What is that in indentation levels?
this._updateIndent._indentationDist = Math.round(this._updateIndent._mouseDist / Craft.StructureTableSorter.LEVEL_INDENT);
// Combine with the original level to get the new target level
this._updateIndent._targetLevel = this._draggeeLevel + this._updateIndent._indentationDist;
// Contain it within our min/max levels
if (this._updateIndent._targetLevel < this._targetLevelBounds.min)
{
this._updateIndent._indentationDist += (this._targetLevelBounds.min - this._updateIndent._targetLevel);
this._updateIndent._targetLevel = this._targetLevelBounds.min;
}
else if (this._updateIndent._targetLevel > this._targetLevelBounds.max)
{
this._updateIndent._indentationDist -= (this._updateIndent._targetLevel - this._targetLevelBounds.max);
this._updateIndent._targetLevel = this._targetLevelBounds.max;
}
// Has the target level changed?
if (this._targetLevel !== (this._targetLevel = this._updateIndent._targetLevel))
{
// Target level is changing, so update the ancestors
this._updateAncestorsBeforeRepaint();
}
// Update the UI
// ---------------------------------------------------------------------
// How far away is the cursor from the exact target level distance?
this._updateIndent._targetLevelMouseDiff = this._updateIndent._mouseDist - (this._updateIndent._indentationDist * Craft.StructureTableSorter.LEVEL_INDENT);
// What's the magnet impact of that?
this._updateIndent._magnetImpact = Math.round(this._updateIndent._targetLevelMouseDiff / 15);
// Put it on a leash
if (Math.abs(this._updateIndent._magnetImpact) > Craft.StructureTableSorter.MAX_GIVE)
{
this._updateIndent._magnetImpact = (this._updateIndent._magnetImpact > 0 ? 1 : -1) * Craft.StructureTableSorter.MAX_GIVE;
}
// Apply the new margin/width
this._updateIndent._closestLevelMagnetIndent = this._getLevelIndent(this._targetLevel) + this._updateIndent._magnetImpact;
this.helpers[0].css('margin-'+Craft.left, this._updateIndent._closestLevelMagnetIndent + this._helperMargin);
this._$titleHelperCell.width(this._titleHelperCellOuterWidth - (this._updateIndent._closestLevelMagnetIndent + Craft.StructureTableSorter.BASE_PADDING));
},
/**
* Returns the indent size for a given level
*/
_getLevelIndent: function(level)
{
return (level - 1) * Craft.StructureTableSorter.LEVEL_INDENT;
},
/**
* Returns the base data that should be sent with StructureController Ajax requests.
*/
_getAjaxBaseData: function($row)
{
return {
structureId: this.structureId,
elementId: $row.data('id'),
locale: $row.find('.element:first').data('locale')
};
},
/**
* Returns a row's ancestor rows
*/
_getAncestors: function($row, targetLevel)
{
this._getAncestors._ancestors = [];
if (targetLevel != 0)
{
this._getAncestors._level = targetLevel;
this._getAncestors._$prevRow = $row.prev();
while (this._getAncestors._$prevRow.length)
{
if (this._getAncestors._$prevRow.data('level') < this._getAncestors._level)
{
this._getAncestors._ancestors.unshift(this._getAncestors._$prevRow);
this._getAncestors._level = this._getAncestors._$prevRow.data('level');
// Did we just reach the top?
if (this._getAncestors._level == 0)
{
break;
}
}
this._getAncestors._$prevRow = this._getAncestors._$prevRow.prev();
}
}
return this._getAncestors._ancestors;
},
/**
* Prepares to have the ancestors updated before the screen is repainted.
*/
_updateAncestorsBeforeRepaint: function()
{
if (this._updateAncestorsFrame)
{
Garnish.cancelAnimationFrame(this._updateAncestorsFrame);
}
if (!this._updateAncestorsProxy)
{
this._updateAncestorsProxy = $.proxy(this, '_updateAncestors');
}
this._updateAncestorsFrame = Garnish.requestAnimationFrame(this._updateAncestorsProxy);
},
_updateAncestors: function()
{
this._updateAncestorsFrame = null;
// Update the old ancestors
// -----------------------------------------------------------------
for (this._updateAncestors._i = 0; this._updateAncestors._i < this._ancestors.length; this._updateAncestors._i++)
{
this._updateAncestors._$ancestor = this._ancestors[this._updateAncestors._i];
// One less descendant now
this._updateAncestors._$ancestor.data('descendants', this._updateAncestors._$ancestor.data('descendants') - 1);
// Is it now childless?
if (this._updateAncestors._$ancestor.data('descendants') == 0)
{
// Remove its toggle
this._updateAncestors._$ancestor.find('> td > .toggle:first').remove();
}
}
// Update the new ancestors
// -----------------------------------------------------------------
this._updateAncestors._newAncestors = this._getAncestors(this.$targetItem, this._targetLevel);
for (this._updateAncestors._i = 0; this._updateAncestors._i < this._updateAncestors._newAncestors.length; this._updateAncestors._i++)
{
this._updateAncestors._$ancestor = this._updateAncestors._newAncestors[this._updateAncestors._i];
// One more descendant now
this._updateAncestors._$ancestor.data('descendants', this._updateAncestors._$ancestor.data('descendants') + 1);
// Is this its first child?
if (this._updateAncestors._$ancestor.data('descendants') == 1)
{
// Create its toggle
$('<span class="toggle expanded" title="'+Craft.t('Show/hide children')+'"></span>')
.insertAfter(this._updateAncestors._$ancestor.find('> td .move:first'));
}
}
this._ancestors = this._updateAncestors._newAncestors;
delete this._updateAncestors._i;
delete this._updateAncestors._$ancestor;
delete this._updateAncestors._newAncestors;
}
},
// Static Properties
// =============================================================================
{
BASE_PADDING: 36,
HELPER_MARGIN: -7,
LEVEL_INDENT: 44,
MAX_GIVE: 22,
defaults: {
onPositionChange: $.noop
}
});
|
// define global object
sentinel = this.sentinel || (function () {
var isArray = Array.isArray,
selectorToAnimationMap = {},
animationCallbacks = {},
styleEl,
styleSheet,
cssRules;
return {
/**
* Add watcher.
* @param {array} cssSelectors - List of CSS selector strings
* @param {Function} callback - The callback function
*/
on: function(cssSelectors, callback) {
if (!callback) return;
// initialize animationstart event listener
if (!styleEl) {
var doc = document,
head = doc.head;
// add animationstart event listener
doc.addEventListener('animationstart', function(ev, callbacks, l, i) {
callbacks = animationCallbacks[ev.animationName];
// exit if callbacks haven't been registered
if (!callbacks) return;
// stop other callbacks from firing
ev.stopImmediatePropagation();
// iterate through callbacks
l = callbacks.length;
for (i=0; i < l; i++) callbacks[i](ev.target);
}, true);
// add stylesheet to document
styleEl = doc.createElement('style');
head.insertBefore(styleEl, head.firstChild);
styleSheet = styleEl.sheet;
cssRules = styleSheet.cssRules;
}
// listify argument and add css rules/ cache callbacks
(isArray(cssSelectors) ? cssSelectors : [cssSelectors])
.map(function(selector, animId, isCustomName) {
animId = selectorToAnimationMap[selector];
if (!animId) {
isCustomName = selector[0] == '!';
// define animation name and add to map
selectorToAnimationMap[selector] = animId =
isCustomName ? selector.slice(1) : 'sentinel-' +
Math.random().toString(16).slice(2);
// add keyframe rule
cssRules[styleSheet.insertRule(
'@keyframes ' + animId +
'{from{transform:none;}to{transform:none;}}',
cssRules.length)]
._id = selector;
// add selector animation rule
if (!isCustomName) {
cssRules[styleSheet.insertRule(
selector + '{animation-duration:0.0001s;animation-name:' +
animId + ';}',
cssRules.length)]
._id = selector;
}
// add to map
selectorToAnimationMap[selector] = animId;
}
// add to callbacks
(animationCallbacks[animId] = animationCallbacks[animId] || [])
.push(callback);
});
},
/**
* Remove watcher.
* @param {array} cssSelectors - List of CSS selector strings
* @param {Function} callback - The callback function (optional)
*/
off: function(cssSelectors, callback) {
// listify argument and iterate through rules
(isArray(cssSelectors) ? cssSelectors : [cssSelectors])
.map(function(selector, animId, callbackList, i) {
// get animId
if (!(animId = selectorToAnimationMap[selector])) return;
// get callbacks
callbackList = animationCallbacks[animId];
// remove callback from list
if (callback) {
i = callbackList.length;
while (i--) {
if (callbackList[i] === callback) callbackList.splice(i, 1);
}
} else {
callbackList = [];
}
// exit if callbacks still exist
if (callbackList.length) return;
// clear cache and remove css rules
i = cssRules.length;
while (i--) {
if (cssRules[i]._id == selector) styleSheet.deleteRule(i);
}
delete selectorToAnimationMap[selector];
delete animationCallbacks[animId];
});
},
/**
* Reset watchers and cache
*/
reset: function() {
selectorToAnimationMap = {};
animationCallbacks = {};
if (styleEl) styleEl.parentNode.removeChild(styleEl);
styleEl = 0;
}
};
})();
|
'use strict';
module.exports = function (math) {
var util = require('../../util/index'),
BigNumber = math.type.BigNumber,
Complex = require('../../type/Complex'),
collection = math.collection,
isNumber = util.number.isNumber,
isBoolean = util['boolean'].isBoolean,
isComplex = Complex.isComplex,
isCollection = collection.isCollection;
/**
* Compute the square of a value, `x * x`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.square(x)
*
* Examples:
*
* math.square(2); // returns Number 4
* math.square(3); // returns Number 9
* math.pow(3, 2); // returns Number 9
* math.multiply(3, 3); // returns Number 9
*
* math.square([1, 2, 3, 4]); // returns Array [1, 4, 9, 16]
*
* See also:
*
* multiply, cube, sqrt, pow
*
* @param {Number | BigNumber | Boolean | Complex | Array | Matrix | null} x
* Number for which to calculate the square
* @return {Number | BigNumber | Complex | Array | Matrix}
* Squared value
*/
math.square = function square(x) {
if (arguments.length != 1) {
throw new math.error.ArgumentsError('square', arguments.length, 1);
}
if (isNumber(x)) {
return x * x;
}
if (isComplex(x)) {
return math.multiply(x, x);
}
if (x instanceof BigNumber) {
return x.times(x);
}
if (isCollection(x)) {
// deep map collection, skip zeros since square(0) = 0
return collection.deepMap(x, square, true);
}
if (isBoolean(x) || x === null) {
return x * x;
}
throw new math.error.UnsupportedTypeError('square', math['typeof'](x));
};
};
|
/**
*
* Get current device activity.
*
* <example>
:getCurrentDeviceActivity.js
it('should get current Android activity', function () {
var activity = browser.getCurrentDeviceActivity();
console.log(activity); // returns ".MainActivity"
});
* </example>
*
* @see https://github.com/appium/appium/blob/master/docs/en/appium-bindings.md#current-activity
* @type mobile
* @for android
*
*/
let getCurrentDeviceActivity = function () {
return this.unify(this.requestHandler.create({
path: '/session/:sessionId/appium/device/current_activity',
method: 'GET'
}), {
extractValue: true
})
}
export default getCurrentDeviceActivity
|
'use strict';
exports.__esModule = true;
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');
var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _elementType = require('react-prop-types/lib/elementType');
var _elementType2 = _interopRequireDefault(_elementType);
var _ListGroupItem = require('./ListGroupItem');
var _ListGroupItem2 = _interopRequireDefault(_ListGroupItem);
var _bootstrapUtils = require('./utils/bootstrapUtils');
var _ValidComponentChildren = require('./utils/ValidComponentChildren');
var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var propTypes = {
/**
* You can use a custom element type for this component.
*
* If not specified, it will be treated as `'li'` if every child is a
* non-actionable `<ListGroupItem>`, and `'div'` otherwise.
*/
componentClass: _elementType2['default']
};
function getDefaultComponent(children) {
if (!children) {
// FIXME: This is the old behavior. Is this right?
return 'div';
}
if (_ValidComponentChildren2['default'].some(children, function (child) {
return child.type !== _ListGroupItem2['default'] || child.props.href || child.props.onClick;
})) {
return 'div';
}
return 'ul';
}
var ListGroup = function (_React$Component) {
(0, _inherits3['default'])(ListGroup, _React$Component);
function ListGroup() {
(0, _classCallCheck3['default'])(this, ListGroup);
return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments));
}
ListGroup.prototype.render = function render() {
var _props = this.props;
var children = _props.children;
var _props$componentClass = _props.componentClass;
var Component = _props$componentClass === undefined ? getDefaultComponent(children) : _props$componentClass;
var className = _props.className;
var props = (0, _objectWithoutProperties3['default'])(_props, ['children', 'componentClass', 'className']);
var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props);
var bsProps = _splitBsProps[0];
var elementProps = _splitBsProps[1];
var classes = (0, _bootstrapUtils.getClassSet)(bsProps);
var useListItem = Component === 'ul' && _ValidComponentChildren2['default'].every(children, function (child) {
return child.type === _ListGroupItem2['default'];
});
return _react2['default'].createElement(
Component,
(0, _extends3['default'])({}, elementProps, {
className: (0, _classnames2['default'])(className, classes)
}),
useListItem ? _ValidComponentChildren2['default'].map(children, function (child) {
return (0, _react.cloneElement)(child, { listItem: true });
}) : children
);
};
return ListGroup;
}(_react2['default'].Component);
ListGroup.propTypes = propTypes;
exports['default'] = (0, _bootstrapUtils.bsClass)('list-group', ListGroup);
module.exports = exports['default']; |
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _useDrop=require("./useDrop");Object.keys(_useDrop).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===_useDrop[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return _useDrop[e]}}))}); |
$(function() {
}); |
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component } from 'angular2/core';
import { MinLengthValidator, MaxLengthValidator } from 'angular2/common';
// #docregion min
let MinLengthTestComponent = class MinLengthTestComponent {
};
MinLengthTestComponent = __decorate([
Component({
selector: 'min-cmp',
directives: [MinLengthValidator],
template: `
<form>
<p>Year: <input ngControl="year" minlength="2"></p>
</form>
`
}),
__metadata('design:paramtypes', [])
], MinLengthTestComponent);
// #enddocregion
// #docregion max
let MaxLengthTestComponent = class MaxLengthTestComponent {
};
MaxLengthTestComponent = __decorate([
Component({
selector: 'max-cmp',
directives: [MaxLengthValidator],
template: `
<form>
<p>Year: <input ngControl="year" maxlength="4"></p>
</form>
`
}),
__metadata('design:paramtypes', [])
], MaxLengthTestComponent);
// #enddocregion
|
import { Directive, HostListener, Input } from '@angular/core';
import { MenuController } from './menu-controller';
/**
* @name MenuClose
* @description
* The `menuClose` directive can be placed on any button to close an open menu.
*
* @usage
*
* A simple `menuClose` button can be added using the following markup:
*
* ```html
* <button ion-button menuClose>Close Menu</button>
* ```
*
* To close a certain menu by its id or side, give the `menuClose`
* directive a value.
*
* ```html
* <button ion-button menuClose="left">Close Left Menu</button>
* ```
*
* @demo /docs/v2/demos/src/menu/
* @see {@link /docs/v2/components#menus Menu Component Docs}
* @see {@link ../../menu/Menu Menu API Docs}
*/
export var MenuClose = (function () {
function MenuClose(_menu) {
this._menu = _menu;
}
/**
* @private
*/
MenuClose.prototype.close = function () {
var menu = this._menu.get(this.menuClose);
menu && menu.close();
};
MenuClose.decorators = [
{ type: Directive, args: [{
selector: '[menuClose]'
},] },
];
/** @nocollapse */
MenuClose.ctorParameters = [
{ type: MenuController, },
];
MenuClose.propDecorators = {
'menuClose': [{ type: Input },],
'close': [{ type: HostListener, args: ['click',] },],
};
return MenuClose;
}());
//# sourceMappingURL=menu-close.js.map |
import EmberObject from 'ember-runtime/system/object';
import {SuiteModuleBuilder} from 'ember-runtime/tests/suites/suite';
var suite = SuiteModuleBuilder.create();
// ..........................................................
// filter()
//
suite.module('filter');
suite.test('filter should invoke on each item', function() {
var obj = this.newObject();
var ary = this.toArray(obj);
var cnt = ary.length - 2;
var found = [];
var result;
// return true on all but the last two
result = obj.filter(function(i) { found.push(i); return --cnt>=0; });
deepEqual(found, ary, 'should have invoked on each item');
deepEqual(result, ary.slice(0,-2), 'filtered array should exclude items');
});
// ..........................................................
// filterBy()
//
suite.module('filterBy');
suite.test('should filter based on object', function() {
var obj, ary;
ary = [
{ foo: 'foo', bar: 'BAZ' },
EmberObject.create({ foo: 'foo', bar: 'bar' })
];
obj = this.newObject(ary);
deepEqual(obj.filterBy('foo', 'foo'), ary, 'filterBy(foo)');
deepEqual(obj.filterBy('bar', 'bar'), [ary[1]], 'filterBy(bar)');
});
suite.test('should include in result if property is true', function() {
var obj, ary;
ary = [
{ foo: 'foo', bar: true },
EmberObject.create({ foo: 'bar', bar: false })
];
obj = this.newObject(ary);
// different values - all eval to true
deepEqual(obj.filterBy('foo'), ary, 'filterBy(foo)');
deepEqual(obj.filterBy('bar'), [ary[0]], 'filterBy(bar)');
});
suite.test('should filter on second argument if provided', function() {
var obj, ary;
ary = [
{ name: 'obj1', foo: 3},
EmberObject.create({ name: 'obj2', foo: 2}),
{ name: 'obj3', foo: 2},
EmberObject.create({ name: 'obj4', foo: 3})
];
obj = this.newObject(ary);
deepEqual(obj.filterBy('foo', 3), [ary[0], ary[3]], "filterBy('foo', 3)')");
});
suite.test('should correctly filter null second argument', function() {
var obj, ary;
ary = [
{ name: 'obj1', foo: 3},
EmberObject.create({ name: 'obj2', foo: null}),
{ name: 'obj3', foo: null},
EmberObject.create({ name: 'obj4', foo: 3})
];
obj = this.newObject(ary);
deepEqual(obj.filterBy('foo', null), [ary[1], ary[2]], "filterBy('foo', 3)')");
});
suite.test('should not return all objects on undefined second argument', function() {
var obj, ary;
ary = [
{ name: 'obj1', foo: 3},
EmberObject.create({ name: 'obj2', foo: 2})
];
obj = this.newObject(ary);
deepEqual(obj.filterBy('foo', undefined), [], "filterBy('foo', 3)')");
});
suite.test('should correctly filter explicit undefined second argument', function() {
var obj, ary;
ary = [
{ name: 'obj1', foo: 3},
EmberObject.create({ name: 'obj2', foo: 3}),
{ name: 'obj3', foo: undefined},
EmberObject.create({ name: 'obj4', foo: undefined}),
{ name: 'obj5'},
EmberObject.create({ name: 'obj6'})
];
obj = this.newObject(ary);
deepEqual(obj.filterBy('foo', undefined), ary.slice(2), "filterBy('foo', 3)')");
});
suite.test('should not match undefined properties without second argument', function() {
var obj, ary;
ary = [
{ name: 'obj1', foo: 3},
EmberObject.create({ name: 'obj2', foo: 3}),
{ name: 'obj3', foo: undefined},
EmberObject.create({ name: 'obj4', foo: undefined}),
{ name: 'obj5'},
EmberObject.create({ name: 'obj6'})
];
obj = this.newObject(ary);
deepEqual(obj.filterBy('foo'), ary.slice(0, 2), "filterBy('foo', 3)')");
});
suite.test('should be aliased to filterProperty', function() {
var ary = [];
equal(ary.filterProperty, ary.filterBy);
});
export default suite;
|
const Server = require('karma').Server;
const ROOT = require('../const').ROOT;
exports.task = function(done) {
const srv = new Server({
logLevel: 'warn',
configFile: ROOT + '/config/karma-sauce.conf.js'
}, done);
srv.start();
};
|
module.exports={A:{A:{"2":"H E G C B A WB"},B:{"2":"D u g I J"},C:{"1":"0 1 2 4 5 6 K","2":"3 UB x F L H E G C B A D u g I J Y O e P Q R S T U V W X v Z a b c d N f M h i j k l m n o p q r s t y SB RB"},D:{"1":"5 6 GB AB CB VB DB EB","2":"0 1 2 3 4 F L H E G C B A D u g I J Y O e P Q R S T U V W X v Z a b c d N f M h i j k l m n o p q r s t y K"},E:{"2":"9 F L H E G C B A FB HB IB JB KB LB MB"},F:{"1":"o p q r s t","2":"7 8 C A D I J Y O e P Q R S T U V W X v Z a b c d N f M h i j k l m n NB OB PB QB TB w"},G:{"2":"9 G A BB z XB YB ZB aB bB cB dB eB"},H:{"2":"fB"},I:{"1":"K","2":"x F gB hB iB jB z kB lB"},J:{"2":"E B"},K:{"2":"7 8 B A D M w"},L:{"1":"AB"},M:{"1":"K"},N:{"2":"B A"},O:{"2":"mB"},P:{"2":"F L"},Q:{"2":"nB"},R:{"2":"oB"}},B:5,C:"display: flow-root"};
|
//将路由注入进来
var showApp= angular.module('show', ['ngRoute']);
//配置路由
showApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'main.html'
})
.when('/hot-site/', {redirectTo: '/hot-site/0'})
.when('/hot-site/:index', {
templateUrl : 'template/show.html',
controller : 'hotSiteController'
})
.when('/mobile', {redirectTo: '/mobile/0'})
.when('/mobile/:index', {
templateUrl : 'template/show-m.html',
controller : 'mobileController'
})
.when('/project/', {
templateUrl : 'template/about.html',
controller : 'projectController'
})
.when('/base/', {redirectTo: '/base/0'})
.when('/base/:index', {
templateUrl : 'template/show.html',
controller : 'baseController'
})
});
showApp.controller('hotSiteController', function($scope, $routeParams) {
var index = $routeParams.index;
$scope.routeName = 'hot-site';
$scope.works = data.hotSite;
document.getElementById('mainIframe').setAttribute('src', $scope.works[index].url);
});
showApp.controller('baseController', function($scope, $routeParams) {
var index = $routeParams.index;
$scope.routeName = 'base';
$scope.works = data.base;
document.getElementById('mainIframe').setAttribute('src', $scope.works[index].url);
});
showApp.controller('mobileController', function($scope, $routeParams) {
var index = $routeParams.index;
$scope.routeName = 'mobile';
$scope.works = data.mobile;
document.getElementById('mainIframe').setAttribute('src', $scope.works[index].url);
});
showApp.controller('projectController', function($scope, $routeParams) {
$scope.works = data.project;
}); |
var assert = require('assert');
// assert up here to ensure that hoisting works as expected
assert('gen' == gen.name);
assert('GeneratorFunction' == gen.constructor.name);
function *gen () {}
var g = gen();
assert('function' == typeof g.next);
assert('function' == typeof g.throw);
|
const normalizeMin = (value, previousValue, allValues, previousAllValues) => {
if (allValues.max !== previousAllValues.max) {
// max changed
if (value === undefined || Number(allValues.max) < Number(value)) {
return allValues.max
}
}
return value
}
export default normalizeMin
|
/*
Highcharts JS v6.1.0 (2018-04-13)
Money Flow Index indicator for Highstock
(c) 2010-2017 Grzegorz Blachliski
License: www.highcharts.com/license
*/
(function(e){"object"===typeof module&&module.exports?module.exports=e:e(Highcharts)})(function(e){(function(e){function p(b){return b.reduce(function(c,b){return c+b})}function m(b){return(b[1]+b[2]+b[3])/3}var u=e.isArray;e.seriesType("mfi","sma",{params:{period:14,volumeSeriesID:"volume",decimals:4}},{nameBase:"Money Flow Index",getValues:function(b,c){var d=c.period,n=b.xData,g=b.yData,v=g?g.length:0,w=c.decimals,h=1,a=b.chart.get(c.volumeSeriesID);b=a&&a.yData;var q=[],r=[],t=[],k=[],l=[],f;
if(!a)return e.error("Series "+c.volumeSeriesID+" not found! Check `volumeSeriesID`.",!0);if(n.length<=d||!u(g[0])||4!==g[0].length||!b)return!1;for(c=m(g[h]);h<d+1;)a=c,c=m(g[h]),a=c>=a?!0:!1,f=c*b[h],k.push(a?f:0),l.push(a?0:f),h++;for(d=h-1;d<v;d++)d>h-1&&(k.shift(),l.shift(),a=c,c=m(g[d]),a=c>a?!0:!1,f=c*b[d],k.push(a?f:0),l.push(a?0:f)),a=p(l),f=p(k),a=f/a,a=parseFloat((100-100/(1+a)).toFixed(w)),q.push([n[d],a]),r.push(n[d]),t.push(a);return{values:q,xData:r,yData:t}}})})(e)});
|
steal('funcunit/qunit','jquery/lang/observe/delegate',function(){
module('jquery/lang/observe')
test("Basic Observe",9,function(){
var state = new $.O({
category : 5,
productType : 4,
properties : {
brand: [],
model : [],
price : []
}
});
var added;
state.bind("change", function(ev, attr, how, val, old){
equals(attr, "properties.brand.0", "correct change name")
equals(how, "add")
equals(val[0].attr("foo"),"bar", "correct")
added = val[0];
});
state.attr("properties.brand").push({foo: "bar"});
state.unbind("change");
added.bind("change", function(ev, attr, how, val, old){
equals(attr, "foo")
equals(how, "set")
equals(val, "zoo")
})
state.bind("change", function(ev, attr, how, val, old){
equals(attr, "properties.brand.0.foo")
equals(how, "set")
equals(val,"zoo")
});
added.attr("foo", "zoo");
});
test("list splice", function(){
var l = new $.Observe.List([0,1,2,3]),
first = true;
l.bind('change', function( ev, attr, how, newVals, oldVals ) {
equals (attr, "1")
// where comes from the attr ...
//equals(where, 1)
if(first){
equals( how, "remove", "removing items" )
equals( newVals, undefined, "no new Vals" )
} else {
same( newVals, ["a","b"] , "got the right newVals")
equals( how, "add", "adding items" )
}
first = false;
})
l.splice(1,2, "a", "b");
same(l.serialize(), [0,"a","b", 3], "serialized")
});
test("list pop", function(){
var l = new $.Observe.List([0,1,2,3]);
l.bind('change', function( ev, attr, how, newVals, oldVals ) {
equals (attr, "3")
equals( how, "remove" )
equals( newVals, undefined )
same( oldVals, [3] )
})
l.pop();
same(l.serialize(), [0,1,2])
})
test("changing an object unbinds", function(){
var state = new $.Observe({
category : 5,
productType : 4,
properties : {
brand: [],
model : [],
price : []
}
}),
count = 0;
var brand = state.attr("properties.brand");
state.bind("change", function(ev, attr, how, val, old){
equals(attr,"properties.brand");
equals(count, 0, "count called once");
count++;
equals(how, "set")
equals(val[0], "hi")
});
if (typeof console != "undefined") console.log("before")
state.attr("properties.brand",["hi"]);
if (typeof console != "undefined") console.log("after")
brand.push(1,2,3);
});
test("replacing with an object that object becomes observable",function(){
var state = new $.Observe({
properties : {
brand: [],
model : [],
price : []
}
});
ok(state.attr("properties").bind, "has bind function");
state.attr("properties",{});
ok(state.attr("properties").bind, "has bind function");
});
test("remove attr", function(){
var state = new $.Observe({
properties : {
brand: [],
model : [],
price : []
}
});
state.bind("change", function(ev, attr, how, newVal, old){
equals(attr, "properties");
equals(how, "remove")
same(old.serialize() ,{
brand: [],
model : [],
price : []
} );
})
state.removeAttr("properties");
equals(undefined, state.attr("properties") );
});
test("attrs", function(){
var state = new $.Observe({
properties : {
foo: "bar",
brand: []
}
});
state.bind("change", function(ev, attr, how, newVal){
equals(attr, "properties.foo")
equals(newVal, "bad")
})
state.attrs({
properties : {
foo: "bar",
brand: []
}
})
state.attrs({
properties : {
foo: "bad",
brand: []
}
});
state.unbind("change");
state.bind("change", function(ev, attr, how, newVal){
equals(attr, "properties.brand.0")
equals(how,"add")
same(newVal, ["bad"])
});
state.attrs({
properties : {
foo: "bad",
brand: ["bad"]
}
});
});
test("empty get", function(){
var state = new $.Observe({});
equals(state.attr('foo.bar'), undefined)
});
test("attrs deep array ", function(){
var state = new $.Observe({});
var arr = [{
foo: "bar"
}],
thing = {
arr: arr
};
state.attrs({
thing: thing
}, true);
ok(thing.arr === arr, "thing unmolested");
});
test('attrs semi-serialize', function(){
var first = {
foo : {bar: 'car'},
arr: [1,2,3, {four: '5'}
]
},
compare = $.extend(true, {}, first);
var res = new $.Observe(first).attrs();
same(res,compare, "test")
})
test("attrs sends events after it is done", function(){
var state = new $.Observe({foo: 1, bar: 2})
state.bind('change', function(){
equals(state.attr('foo'), -1, "foo set");
equals(state.attr('bar'), -2, "bar set")
})
state.attrs({foo: -1, bar: -2});
})
test("direct property access", function(){
var state = new $.Observe({foo: 1, attrs: 2});
equals(state.foo,1);
equals(typeof state.attrs, 'function')
})
test("pop unbinds", function(){
var l = new $.O([{foo: 'bar'}]);
var o = l.attr(0),
count = 0;
l.bind('change', function(ev, attr, how, newVal, oldVal){
count++;
if(count == 1){
// the prop change
equals(attr, '0.foo', "count is set");
} else if(count === 2 ){
equals(how, "remove");
equals(attr, "0")
} else {
ok(false, "called too many times")
}
})
equals( o.attr('foo') , 'bar');
o.attr('foo','car')
l.pop();
o.attr('foo','bad')
})
test("splice unbinds", function(){
var l = new $.Observe.List([{foo: 'bar'}]);
var o = l.attr(0),
count = 0;
l.bind('change', function(ev, attr, how, newVal, oldVal){
count++;
if(count == 1){
// the prop change
equals(attr, '0.foo', "count is set");
} else if(count === 2 ){
equals(how, "remove");
equals(attr, "0")
} else {
ok(false, "called too many times")
}
})
equals( o.attr('foo') , 'bar');
o.attr('foo','car')
l.splice(0,1);
o.attr('foo','bad')
});
test("always gets right attr even after moving array items", function(){
var l = new $.Observe.List([{foo: 'bar'}]);
var o = l.attr(0);
l.unshift("A new Value")
l.bind('change', function(ev, attr, how){
equals(attr, "1.foo")
})
o.attr('foo','led you')
})
}).then('./delegate/delegate_test.js');
|
var R = require('..');
var eq = require('./shared/eq');
describe('apply', function() {
it('applies function to argument list', function() {
eq(R.apply(Math.max, [1, 2, 3, -99, 42, 6, 7]), 42);
});
it('is curried', function() {
eq(R.apply(Math.max)([1, 2, 3, -99, 42, 6, 7]), 42);
});
it('provides no way to specify context', function() {
var obj = {method: function() { return this === obj; }};
eq(R.apply(obj.method, []), false);
eq(R.apply(R.bind(obj.method, obj), []), true);
});
});
|
// Custom events are not natively supported, so you have to hijack a random
// event.
//
// Just use jQuery.
|
//===============================================================================================================
// System : Sandcastle Help File Builder
// File : branding-Website.js
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 03/04/2015
// Note : Copyright 2014-2015, Eric Woodruff, All rights reserved
// Portions Copyright 2014 Sam Harwell, All rights reserved
//
// This file contains the methods necessary to implement the lightweight TOC and search functionality.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy of the license should be
// distributed with the code. It can also be found at the project website: https://GitHub.com/EWSoftware/SHFB. This
// notice, the author's name, and all copyright notices must remain intact in all applications, documentation,
// and source files.
//
// Date Who Comments
// ==============================================================================================================
// 05/04/2014 EFW Created the code based on a combination of the lightweight TOC code from Sam Harwell and
// the existing search code from SHFB.
//===============================================================================================================
// Width of the TOC
var tocWidth;
// Search method (0 = To be determined, 1 = ASPX, 2 = PHP, anything else = client-side script
var searchMethod = 0;
// Table of contents script
// Initialize the TOC by restoring its width from the cookie if present
function InitializeToc()
{
tocWidth = parseInt(GetCookie("TocWidth", "280"));
ResizeToc();
$(window).resize(SetNavHeight)
}
function SetNavHeight()
{
$leftNav = $("#leftNav")
$topicContent = $("#TopicContent")
leftNavPadding = $leftNav.outerHeight() - $leftNav.height()
contentPadding = $topicContent.outerHeight() - $topicContent.height()
// want outer height of left navigation div to match outer height of content
leftNavHeight = $topicContent.outerHeight() - leftNavPadding
$leftNav.css("min-height", leftNavHeight + "px")
}
// Increase the TOC width
function OnIncreaseToc()
{
if(tocWidth < 1)
tocWidth = 280;
else
tocWidth += 100;
if(tocWidth > 680)
tocWidth = 0;
ResizeToc();
SetCookie("TocWidth", tocWidth);
}
// Reset the TOC to its default width
function OnResetToc()
{
tocWidth = 0;
ResizeToc();
SetCookie("TocWidth", tocWidth);
}
// Resize the TOC width
function ResizeToc()
{
var toc = document.getElementById("leftNav");
if(toc)
{
// Set TOC width
toc.style.width = tocWidth + "px";
var leftNavPadding = 10;
document.getElementById("TopicContent").style.marginLeft = (tocWidth + leftNavPadding) + "px";
// Position images
document.getElementById("TocResize").style.left = (tocWidth + leftNavPadding) + "px";
// Hide/show increase TOC width image
document.getElementById("ResizeImageIncrease").style.display = (tocWidth >= 680) ? "none" : "";
// Hide/show reset TOC width image
document.getElementById("ResizeImageReset").style.display = (tocWidth < 680) ? "none" : "";
}
SetNavHeight()
}
// Toggle a TOC entry between its collapsed and expanded state
function Toggle(item)
{
var isExpanded = $(item).hasClass("tocExpanded");
$(item).toggleClass("tocExpanded tocCollapsed");
if(isExpanded)
{
Collapse($(item).parent());
}
else
{
var childrenLoaded = $(item).parent().attr("data-childrenloaded");
if(childrenLoaded)
{
Expand($(item).parent());
}
else
{
var tocid = $(item).next().attr("tocid");
$.ajax({
url: "../toc/" + tocid + ".xml",
async: true,
dataType: "xml",
success: function(data)
{
BuildChildren($(item).parent(), data);
}
});
}
}
}
// HTML encode a value for use on the page
function HtmlEncode(value)
{
// Create an in-memory div, set it's inner text (which jQuery automatically encodes) then grab the encoded
// contents back out. The div never exists on the page.
return $('<div/>').text(value).html();
}
// Build the child entries of a TOC entry
function BuildChildren(tocDiv, data)
{
var childLevel = +tocDiv.attr("data-toclevel") + 1;
var childTocLevel = childLevel >= 10 ? 10 : childLevel;
var elements = data.getElementsByTagName("HelpTOCNode");
var isRoot = true;
if(data.getElementsByTagName("HelpTOC").length == 0)
{
// The first node is the root node of this group, don't show it again
isRoot = false;
}
for(var i = elements.length - 1; i > 0 || (isRoot && i == 0); i--)
{
var childHRef, childId = elements[i].getAttribute("Url");
if(childId != null && childId.length > 5)
{
// The Url attribute has the form "html/{childId}.htm"
childHRef = "../" + childId;
childId = childId.substring(childId.lastIndexOf("/") + 1, childId.lastIndexOf("."));
}
else
{
// The Id attribute is in raw form. There is no URL (empty container node). In this case, we'll
// just ignore it and go nowhere. It's a rare case that isn't worth trying to get the first child.
// Instead, we'll just expand the node (see below).
childHRef = "#";
childId = elements[i].getAttribute("Id");
}
var existingItem = null;
tocDiv.nextAll().each(function()
{
if(!existingItem && $(this).children().last("a").attr("tocid") == childId)
{
existingItem = $(this);
}
});
if(existingItem != null)
{
// First move the children of the existing item
var existingChildLevel = +existingItem.attr("data-toclevel");
var doneMoving = false;
var inserter = tocDiv;
existingItem.nextAll().each(function()
{
if(!doneMoving && +$(this).attr("data-toclevel") > existingChildLevel)
{
inserter.after($(this));
inserter = $(this);
$(this).attr("data-toclevel", +$(this).attr("data-toclevel") + childLevel - existingChildLevel);
if($(this).hasClass("current"))
$(this).attr("class", "toclevel" + (+$(this).attr("data-toclevel") + " current"));
else
$(this).attr("class", "toclevel" + (+$(this).attr("data-toclevel")));
}
else
{
doneMoving = true;
}
});
// Now move the existing item itself
tocDiv.after(existingItem);
existingItem.attr("data-toclevel", childLevel);
existingItem.attr("class", "toclevel" + childLevel);
}
else
{
var hasChildren = elements[i].getAttribute("HasChildren");
var childTitle = HtmlEncode(elements[i].getAttribute("Title"));
var expander = "";
if(hasChildren)
expander = "<a class=\"tocCollapsed\" onclick=\"javascript: Toggle(this);\" href=\"#!\"></a>";
var text = "<div class=\"toclevel" + childTocLevel + "\" data-toclevel=\"" + childLevel + "\">" +
expander + "<a data-tochassubtree=\"" + hasChildren + "\" href=\"" + childHRef + "\" title=\"" +
childTitle + "\" tocid=\"" + childId + "\"" +
(childHRef == "#" ? " onclick=\"javascript: Toggle(this.previousSibling);\"" : "") + ">" +
childTitle + "</a></div>";
tocDiv.after(text);
}
}
tocDiv.attr("data-childrenloaded", true);
}
// Collapse a TOC entry
function Collapse(tocDiv)
{
// Hide all the TOC elements after item, until we reach one with a data-toclevel less than or equal to the
// current item's value.
var tocLevel = +tocDiv.attr("data-toclevel");
var done = false;
tocDiv.nextAll().each(function()
{
if(!done && +$(this).attr("data-toclevel") > tocLevel)
{
$(this).hide();
}
else
{
done = true;
}
});
}
// Expand a TOC entry
function Expand(tocDiv)
{
// Show all the TOC elements after item, until we reach one with a data-toclevel less than or equal to the
// current item's value
var tocLevel = +tocDiv.attr("data-toclevel");
var done = false;
tocDiv.nextAll().each(function()
{
if(done)
{
return;
}
var childTocLevel = +$(this).attr("data-toclevel");
if(childTocLevel == tocLevel + 1)
{
$(this).show();
if($(this).children("a").first().hasClass("tocExpanded"))
{
Expand($(this));
}
}
else if(childTocLevel > tocLevel + 1)
{
// Ignore this node, handled by recursive calls
}
else
{
done = true;
}
});
}
// This is called to prepare for dragging the sizer div
function OnMouseDown(event)
{
document.addEventListener("mousemove", OnMouseMove, true);
document.addEventListener("mouseup", OnMouseUp, true);
event.preventDefault();
}
// Resize the TOC as the sizer is dragged
function OnMouseMove(event)
{
tocWidth = (event.clientX > 700) ? 700 : (event.clientX < 100) ? 100 : event.clientX;
ResizeToc();
}
// Finish the drag operation when the mouse button is released
function OnMouseUp(event)
{
document.removeEventListener("mousemove", OnMouseMove, true);
document.removeEventListener("mouseup", OnMouseUp, true);
SetCookie("TocWidth", tocWidth);
}
// Search functions
// Transfer to the search page from a topic
function TransferToSearchPage()
{
var searchText = document.getElementById("SearchTextBox").value.trim();
if(searchText.length != 0)
document.location.replace(encodeURI("../search.html?SearchText=" + searchText));
}
// Initiate a search when the search page loads
function OnSearchPageLoad()
{
var queryString = decodeURI(document.location.search);
if(queryString != "")
{
var idx, options = queryString.split(/[\?\=\&]/);
for(idx = 0; idx < options.length; idx++)
if(options[idx] == "SearchText" && idx + 1 < options.length)
{
document.getElementById("txtSearchText").value = options[idx + 1];
PerformSearch();
break;
}
}
}
// Perform a search using the best available method
function PerformSearch()
{
var searchText = document.getElementById("txtSearchText").value;
var sortByTitle = document.getElementById("chkSortByTitle").checked;
var searchResults = document.getElementById("searchResults");
if(searchText.length == 0)
{
searchResults.innerHTML = "<strong>Nothing found</strong>";
return;
}
searchResults.innerHTML = "Searching...";
// Determine the search method if not done already. The ASPX and PHP searches are more efficient as they
// run asynchronously server-side. If they can't be used, it defaults to the client-side script below which
// will work but has to download the index files. For large help sites, this can be inefficient.
if(searchMethod == 0)
searchMethod = DetermineSearchMethod();
if(searchMethod == 1)
{
$.ajax({
type: "GET",
url: encodeURI("SearchHelp.aspx?Keywords=" + searchText + "&SortByTitle=" + sortByTitle),
success: function(html)
{
searchResults.innerHTML = html;
}
});
return;
}
if(searchMethod == 2)
{
$.ajax({
type: "GET",
url: encodeURI("SearchHelp.php?Keywords=" + searchText + "&SortByTitle=" + sortByTitle),
success: function(html)
{
searchResults.innerHTML = html;
}
});
return;
}
// Parse the keywords
var keywords = ParseKeywords(searchText);
// Get the list of files. We'll be getting multiple files so we need to do this synchronously.
var fileList = [];
$.ajax({
type: "GET",
url: "fti/FTI_Files.json",
dataType: "json",
async: false,
success: function(data)
{
$.each(data, function(key, val)
{
fileList[key] = val;
});
}
});
var letters = [];
var wordDictionary = {};
var wordNotFound = false;
// Load the keyword files for each keyword starting letter
for(var idx = 0; idx < keywords.length && !wordNotFound; idx++)
{
var letter = keywords[idx].substring(0, 1);
if($.inArray(letter, letters) == -1)
{
letters.push(letter);
$.ajax({
type: "GET",
url: "fti/FTI_" + letter.charCodeAt(0) + ".json",
dataType: "json",
async: false,
success: function(data)
{
var wordCount = 0;
$.each(data, function(key, val)
{
wordDictionary[key] = val;
wordCount++;
});
if(wordCount == 0)
wordNotFound = true;
}
});
}
}
if(wordNotFound)
searchResults.innerHTML = "<strong>Nothing found</strong>";
else
searchResults.innerHTML = SearchForKeywords(keywords, fileList, wordDictionary, sortByTitle);
}
// Determine the search method by seeing if the ASPX or PHP search pages are present and working
function DetermineSearchMethod()
{
var method = 3;
try
{
$.ajax({
type: "GET",
url: "SearchHelp.aspx",
async: false,
success: function(html)
{
if(html.substring(0, 8) == "<strong>")
method = 1;
}
});
if(method == 3)
$.ajax({
type: "GET",
url: "SearchHelp.php",
async: false,
success: function(html)
{
if(html.substring(0, 8) == "<strong>")
method = 2;
}
});
}
catch(e)
{
}
return method;
}
// Split the search text up into keywords
function ParseKeywords(keywords)
{
var keywordList = [];
var checkWord;
var words = keywords.split(/[\s!@#$%^&*()\-=+\[\]{}\\|<>;:'",.<>/?`~]+/);
for(var idx = 0; idx < words.length; idx++)
{
checkWord = words[idx].toLowerCase();
if(checkWord.length > 2)
{
var charCode = checkWord.charCodeAt(0);
if((charCode < 48 || charCode > 57) && $.inArray(checkWord, keywordList) == -1)
keywordList.push(checkWord);
}
}
return keywordList;
}
// Search for keywords and generate a block of HTML containing the results
function SearchForKeywords(keywords, fileInfo, wordDictionary, sortByTitle)
{
var matches = [], matchingFileIndices = [], rankings = [];
var isFirst = true;
for(var idx = 0; idx < keywords.length; idx++)
{
var word = keywords[idx];
var occurrences = wordDictionary[word];
// All keywords must be found
if(occurrences == null)
return "<strong>Nothing found</strong>";
matches[word] = occurrences;
var occurrenceIndices = [];
// Get a list of the file indices for this match. These are 64-bit numbers but JavaScript only does
// bit shifts on 32-bit values so we divide by 2^16 to get the same effect as ">> 16" and use floor()
// to truncate the result.
for(var ind in occurrences)
occurrenceIndices.push(Math.floor(occurrences[ind] / Math.pow(2, 16)));
if(isFirst)
{
isFirst = false;
for(var matchInd in occurrenceIndices)
matchingFileIndices.push(occurrenceIndices[matchInd]);
}
else
{
// After the first match, remove files that do not appear for all found keywords
for(var checkIdx = 0; checkIdx < matchingFileIndices.length; checkIdx++)
if($.inArray(matchingFileIndices[checkIdx], occurrenceIndices) == -1)
{
matchingFileIndices.splice(checkIdx, 1);
checkIdx--;
}
}
}
if(matchingFileIndices.length == 0)
return "<strong>Nothing found</strong>";
// Rank the files based on the number of times the words occurs
for(var fileIdx = 0; fileIdx < matchingFileIndices.length; fileIdx++)
{
// Split out the title, filename, and word count
var matchingIdx = matchingFileIndices[fileIdx];
var fileIndex = fileInfo[matchingIdx].split(/\0/);
var title = fileIndex[0];
var filename = fileIndex[1];
var wordCount = parseInt(fileIndex[2]);
var matchCount = 0;
for(var idx = 0; idx < keywords.length; idx++)
{
occurrences = matches[keywords[idx]];
for(var ind in occurrences)
{
var entry = occurrences[ind];
// These are 64-bit numbers but JavaScript only does bit shifts on 32-bit values so we divide
// by 2^16 to get the same effect as ">> 16" and use floor() to truncate the result.
if(Math.floor(entry / Math.pow(2, 16)) == matchingIdx)
matchCount += (entry & 0xFFFF);
}
}
rankings.push({ Filename: filename, PageTitle: title, Rank: matchCount * 1000 / wordCount });
if(rankings.length > 99)
break;
}
rankings.sort(function(x, y)
{
if(!sortByTitle)
return y.Rank - x.Rank;
return x.PageTitle.localeCompare(y.PageTitle);
});
// Format and return the results
var content = "<ol>";
for(var r in rankings)
content += "<li><a href=\"" + rankings[r].Filename + "\" target=\"_blank\">" +
rankings[r].PageTitle + "</a></li>";
content += "</ol>";
if(rankings.length < matchingFileIndices.length)
content += "<p>Omitted " + (matchingFileIndices.length - rankings.length) + " more results</p>";
return content;
}
|
enum E {
"foo",
"bar" = 1,
} |
(function(){/*
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
'use strict';var nb="undefined"!=typeof window&&window===this?this:"undefined"!=typeof global&&null!=global?global:this;
(function(){function k(){var a=this;this.s={};this.g=document.documentElement;var b=new za;b.rules=[];this.h=y.set(this.g,new y(b));this.i=!1;this.b=this.a=null;ob(function(){a.c()})}function F(){this.customStyles=[];this.enqueued=!1}function pb(){}function ha(a){this.cache={};this.c=void 0===a?100:a}function p(){}function y(a,b,c,d,e){this.G=a||null;this.b=b||null;this.sa=c||[];this.P=null;this.Y=e||"";this.a=this.B=this.K=null}function r(){}function za(){this.end=this.start=0;this.rules=this.parent=
this.previous=null;this.cssText=this.parsedCssText="";this.atRule=!1;this.type=0;this.parsedSelector=this.selector=this.keyframesName=""}function $c(a){function b(b,c){Object.defineProperty(b,"innerHTML",{enumerable:c.enumerable,configurable:!0,get:c.get,set:function(b){var d=this,e=void 0;n(this)&&(e=[],M(this,function(a){a!==d&&e.push(a)}));c.set.call(this,b);if(e)for(var f=0;f<e.length;f++){var g=e[f];1===g.__CE_state&&a.disconnectedCallback(g)}this.ownerDocument.__CE_hasRegistry?a.f(this):a.l(this);
return b}})}function c(b,c){t(b,"insertAdjacentElement",function(b,d){var e=n(d);b=c.call(this,b,d);e&&a.a(d);n(b)&&a.b(d);return b})}qb?t(Element.prototype,"attachShadow",function(a){return this.__CE_shadowRoot=a=qb.call(this,a)}):console.warn("Custom Elements: `Element#attachShadow` was not patched.");if(Aa&&Aa.get)b(Element.prototype,Aa);else if(Ba&&Ba.get)b(HTMLElement.prototype,Ba);else{var d=Ca.call(document,"div");a.v(function(a){b(a,{enumerable:!0,configurable:!0,get:function(){return rb.call(this,
!0).innerHTML},set:function(a){var b="template"===this.localName?this.content:this;for(d.innerHTML=a;0<b.childNodes.length;)Da.call(b,b.childNodes[0]);for(;0<d.childNodes.length;)ja.call(b,d.childNodes[0])}})})}t(Element.prototype,"setAttribute",function(b,c){if(1!==this.__CE_state)return sb.call(this,b,c);var d=Ea.call(this,b);sb.call(this,b,c);c=Ea.call(this,b);a.attributeChangedCallback(this,b,d,c,null)});t(Element.prototype,"setAttributeNS",function(b,c,d){if(1!==this.__CE_state)return tb.call(this,
b,c,d);var e=ka.call(this,b,c);tb.call(this,b,c,d);d=ka.call(this,b,c);a.attributeChangedCallback(this,c,e,d,b)});t(Element.prototype,"removeAttribute",function(b){if(1!==this.__CE_state)return ub.call(this,b);var c=Ea.call(this,b);ub.call(this,b);null!==c&&a.attributeChangedCallback(this,b,c,null,null)});t(Element.prototype,"removeAttributeNS",function(b,c){if(1!==this.__CE_state)return vb.call(this,b,c);var d=ka.call(this,b,c);vb.call(this,b,c);var e=ka.call(this,b,c);d!==e&&a.attributeChangedCallback(this,
c,d,e,b)});wb?c(HTMLElement.prototype,wb):xb?c(Element.prototype,xb):console.warn("Custom Elements: `Element#insertAdjacentElement` was not patched.");yb(a,Element.prototype,{La:ad,append:bd});cd(a,{lb:dd,kb:ed,vb:fd,remove:gd})}function cd(a,b){var c=Element.prototype;c.before=function(c){for(var d=[],f=0;f<arguments.length;++f)d[f-0]=arguments[f];f=d.filter(function(a){return a instanceof Node&&n(a)});b.lb.apply(this,d);for(var g=0;g<f.length;g++)a.a(f[g]);if(n(this))for(f=0;f<d.length;f++)g=d[f],
g instanceof Element&&a.b(g)};c.after=function(c){for(var d=[],f=0;f<arguments.length;++f)d[f-0]=arguments[f];f=d.filter(function(a){return a instanceof Node&&n(a)});b.kb.apply(this,d);for(var g=0;g<f.length;g++)a.a(f[g]);if(n(this))for(f=0;f<d.length;f++)g=d[f],g instanceof Element&&a.b(g)};c.replaceWith=function(c){for(var d=[],f=0;f<arguments.length;++f)d[f-0]=arguments[f];f=d.filter(function(a){return a instanceof Node&&n(a)});var g=n(this);b.vb.apply(this,d);for(var h=0;h<f.length;h++)a.a(f[h]);
if(g)for(a.a(this),f=0;f<d.length;f++)g=d[f],g instanceof Element&&a.b(g)};c.remove=function(){var c=n(this);b.remove.call(this);c&&a.a(this)}}function hd(a){function b(b,d){Object.defineProperty(b,"textContent",{enumerable:d.enumerable,configurable:!0,get:d.get,set:function(b){if(this.nodeType===Node.TEXT_NODE)d.set.call(this,b);else{var c=void 0;if(this.firstChild){var e=this.childNodes,h=e.length;if(0<h&&n(this)){c=Array(h);for(var m=0;m<h;m++)c[m]=e[m]}}d.set.call(this,b);if(c)for(b=0;b<c.length;b++)a.a(c[b])}}})}
t(Node.prototype,"insertBefore",function(b,d){if(b instanceof DocumentFragment){var c=Array.prototype.slice.apply(b.childNodes);b=zb.call(this,b,d);if(n(this))for(d=0;d<c.length;d++)a.b(c[d]);return b}c=n(b);d=zb.call(this,b,d);c&&a.a(b);n(this)&&a.b(b);return d});t(Node.prototype,"appendChild",function(b){if(b instanceof DocumentFragment){var c=Array.prototype.slice.apply(b.childNodes);b=ja.call(this,b);if(n(this))for(var e=0;e<c.length;e++)a.b(c[e]);return b}c=n(b);e=ja.call(this,b);c&&a.a(b);n(this)&&
a.b(b);return e});t(Node.prototype,"cloneNode",function(b){b=rb.call(this,b);this.ownerDocument.__CE_hasRegistry?a.f(b):a.l(b);return b});t(Node.prototype,"removeChild",function(b){var c=n(b),e=Da.call(this,b);c&&a.a(b);return e});t(Node.prototype,"replaceChild",function(b,d){if(b instanceof DocumentFragment){var c=Array.prototype.slice.apply(b.childNodes);b=Ab.call(this,b,d);if(n(this))for(a.a(d),d=0;d<c.length;d++)a.b(c[d]);return b}c=n(b);var f=Ab.call(this,b,d),g=n(this);g&&a.a(d);c&&a.a(b);g&&
a.b(b);return f});Fa&&Fa.get?b(Node.prototype,Fa):a.v(function(a){b(a,{enumerable:!0,configurable:!0,get:function(){for(var a=[],b=0;b<this.childNodes.length;b++)a.push(this.childNodes[b].textContent);return a.join("")},set:function(a){for(;this.firstChild;)Da.call(this,this.firstChild);ja.call(this,document.createTextNode(a))}})})}function id(a){t(Document.prototype,"createElement",function(b){if(this.__CE_hasRegistry){var c=a.c(b);if(c)return new c.constructor}b=Ca.call(this,b);a.g(b);return b});
t(Document.prototype,"importNode",function(b,c){b=jd.call(this,b,c);this.__CE_hasRegistry?a.f(b):a.l(b);return b});t(Document.prototype,"createElementNS",function(b,c){if(this.__CE_hasRegistry&&(null===b||"http://www.w3.org/1999/xhtml"===b)){var d=a.c(c);if(d)return new d.constructor}b=kd.call(this,b,c);a.g(b);return b});yb(a,Document.prototype,{La:ld,append:md})}function yb(a,b,c){b.prepend=function(b){for(var d=[],f=0;f<arguments.length;++f)d[f-0]=arguments[f];f=d.filter(function(a){return a instanceof
Node&&n(a)});c.La.apply(this,d);for(var g=0;g<f.length;g++)a.a(f[g]);if(n(this))for(f=0;f<d.length;f++)g=d[f],g instanceof Element&&a.b(g)};b.append=function(b){for(var d=[],f=0;f<arguments.length;++f)d[f-0]=arguments[f];f=d.filter(function(a){return a instanceof Node&&n(a)});c.append.apply(this,d);for(var g=0;g<f.length;g++)a.a(f[g]);if(n(this))for(f=0;f<d.length;f++)g=d[f],g instanceof Element&&a.b(g)}}function nd(a){window.HTMLElement=function(){function b(){var b=this.constructor,d=a.C(b);if(!d)throw Error("The custom element being constructed was not registered with `customElements`.");
var e=d.constructionStack;if(!e.length)return e=Ca.call(document,d.localName),Object.setPrototypeOf(e,b.prototype),e.__CE_state=1,e.__CE_definition=d,a.g(e),e;d=e.length-1;var f=e[d];if(f===Bb)throw Error("The HTMLElement constructor was either called reentrantly for this constructor or called multiple times.");e[d]=Bb;Object.setPrototypeOf(f,b.prototype);a.g(f);return f}b.prototype=od.prototype;return b}()}function q(a){this.c=!1;this.a=a;this.h=new Map;this.f=function(a){return a()};this.b=!1;this.g=
[];this.i=new Ga(a,document)}function Cb(){var a=this;this.b=this.a=void 0;this.c=new Promise(function(b){a.b=b;a.a&&b(a.a)})}function Ga(a,b){this.b=a;this.a=b;this.N=void 0;this.b.f(this.a);"loading"===this.a.readyState&&(this.N=new MutationObserver(this.f.bind(this)),this.N.observe(this.a,{childList:!0,subtree:!0}))}function A(){this.u=new Map;this.s=new Map;this.j=[];this.h=!1}function l(a,b,c){if(a!==Db)throw new TypeError("Illegal constructor");a=document.createDocumentFragment();a.__proto__=
l.prototype;a.D(b,c);return a}function la(a){if(!a.__shady||void 0===a.__shady.firstChild){a.__shady=a.__shady||{};a.__shady.firstChild=Ha(a);a.__shady.lastChild=Ia(a);Eb(a);for(var b=a.__shady.childNodes=S(a),c=0,d;c<b.length&&(d=b[c]);c++)d.__shady=d.__shady||{},d.__shady.parentNode=a,d.__shady.nextSibling=b[c+1]||null,d.__shady.previousSibling=b[c-1]||null,Fb(d)}}function pd(a){var b=a&&a.N;b&&(b.ba.delete(a.bb),b.ba.size||(a.gb.__shady.W=null))}function qd(a,b){a.__shady=a.__shady||{};a.__shady.W||
(a.__shady.W=new ma);a.__shady.W.ba.add(b);var c=a.__shady.W;return{bb:b,N:c,gb:a,takeRecords:function(){return c.takeRecords()}}}function ma(){this.a=!1;this.addedNodes=[];this.removedNodes=[];this.ba=new Set}function T(a){return a.__shady&&void 0!==a.__shady.firstChild}function B(a){return"ShadyRoot"===a.Xa}function Z(a){a=a.getRootNode();if(B(a))return a}function Ja(a,b){if(a&&b)for(var c=Object.getOwnPropertyNames(b),d=0,e;d<c.length&&(e=c[d]);d++){var f=Object.getOwnPropertyDescriptor(b,e);f&&
Object.defineProperty(a,e,f)}}function Ka(a,b){for(var c=[],d=1;d<arguments.length;++d)c[d-1]=arguments[d];for(d=0;d<c.length;d++)Ja(a,c[d]);return a}function rd(a,b){for(var c in b)a[c]=b[c]}function Gb(a){La.push(a);Ma.textContent=Hb++}function Ib(a){Na||(Na=!0,Gb(na));aa.push(a)}function na(){Na=!1;for(var a=!!aa.length;aa.length;)aa.shift()();return a}function sd(a,b){var c=b.getRootNode();return a.map(function(a){var b=c===a.target.getRootNode();if(b&&a.addedNodes){if(b=Array.from(a.addedNodes).filter(function(a){return c===
a.getRootNode()}),b.length)return a=Object.create(a),Object.defineProperty(a,"addedNodes",{value:b,configurable:!0}),a}else if(b)return a}).filter(function(a){return a})}function Jb(a){switch(a){case "&":return"&";case "<":return"<";case ">":return">";case '"':return""";case "\u00a0":return" "}}function Kb(a){for(var b={},c=0;c<a.length;c++)b[a[c]]=!0;return b}function Oa(a,b){"template"===a.localName&&(a=a.content);for(var c="",d=b?b(a):a.childNodes,e=0,f=d.length,g;e<f&&(g=d[e]);e++){a:{var h=
g;var m=a;var Q=b;switch(h.nodeType){case Node.ELEMENT_NODE:for(var k=h.localName,ia="<"+k,l=h.attributes,n=0;m=l[n];n++)ia+=" "+m.name+'="'+m.value.replace(td,Jb)+'"';ia+=">";h=ud[k]?ia:ia+Oa(h,Q)+"</"+k+">";break a;case Node.TEXT_NODE:h=h.data;h=m&&vd[m.localName]?h:h.replace(wd,Jb);break a;case Node.COMMENT_NODE:h="\x3c!--"+h.data+"--\x3e";break a;default:throw window.console.error(h),Error("not implemented");}}c+=h}return c}function U(a){v.currentNode=a;return v.parentNode()}function Ha(a){v.currentNode=
a;return v.firstChild()}function Ia(a){v.currentNode=a;return v.lastChild()}function Lb(a){v.currentNode=a;return v.previousSibling()}function Mb(a){v.currentNode=a;return v.nextSibling()}function S(a){var b=[];v.currentNode=a;for(a=v.firstChild();a;)b.push(a),a=v.nextSibling();return b}function Nb(a){C.currentNode=a;return C.parentNode()}function Ob(a){C.currentNode=a;return C.firstChild()}function Pb(a){C.currentNode=a;return C.lastChild()}function Qb(a){C.currentNode=a;return C.previousSibling()}
function Rb(a){C.currentNode=a;return C.nextSibling()}function Sb(a){var b=[];C.currentNode=a;for(a=C.firstChild();a;)b.push(a),a=C.nextSibling();return b}function Tb(a){return Oa(a,function(a){return S(a)})}function Ub(a){switch(a.nodeType){case Node.ELEMENT_NODE:case Node.DOCUMENT_FRAGMENT_NODE:a=document.createTreeWalker(a,NodeFilter.SHOW_TEXT,null,!1);for(var b="",c;c=a.nextNode();)b+=c.nodeValue;return b;default:return a.nodeValue}}function G(a,b,c){for(var d in b){var e=Object.getOwnPropertyDescriptor(a,
d);e&&e.configurable||!e&&c?Object.defineProperty(a,d,b[d]):c&&console.warn("Could not define",d,"on",a)}}function O(a){G(a,Vb);G(a,Pa);G(a,Qa)}function Wb(a,b,c){Fb(a);c=c||null;a.__shady=a.__shady||{};b.__shady=b.__shady||{};c&&(c.__shady=c.__shady||{});a.__shady.previousSibling=c?c.__shady.previousSibling:b.lastChild;var d=a.__shady.previousSibling;d&&d.__shady&&(d.__shady.nextSibling=a);(d=a.__shady.nextSibling=c)&&d.__shady&&(d.__shady.previousSibling=a);a.__shady.parentNode=b;c?c===b.__shady.firstChild&&
(b.__shady.firstChild=a):(b.__shady.lastChild=a,b.__shady.firstChild||(b.__shady.firstChild=a));b.__shady.childNodes=null}function Ra(a,b,c){if(b===a)throw Error("Failed to execute 'appendChild' on 'Node': The new child element contains the parent.");if(c){var d=c.__shady&&c.__shady.parentNode;if(void 0!==d&&d!==a||void 0===d&&U(c)!==a)throw Error("Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.");}if(c===b)return b;b.parentNode&&
Sa(b.parentNode,b);d=Z(a);var e;if(e=d)a:{if(!b.__noInsertionPoint){var f;"slot"===b.localName?f=[b]:b.querySelectorAll&&(f=b.querySelectorAll("slot"));if(f&&f.length){e=f;break a}}e=void 0}f=e;d&&("slot"===a.localName||f)&&d.M();if(T(a)){e=c;Eb(a);a.__shady=a.__shady||{};void 0!==a.__shady.firstChild&&(a.__shady.childNodes=null);if(b.nodeType===Node.DOCUMENT_FRAGMENT_NODE){for(var g=b.childNodes,h=0;h<g.length;h++)Wb(g[h],a,e);b.__shady=b.__shady||{};e=void 0!==b.__shady.firstChild?null:void 0;b.__shady.firstChild=
b.__shady.lastChild=e;b.__shady.childNodes=e}else Wb(b,a,e);if(Ta(a)){a.__shady.root.M();var m=!0}else a.__shady.root&&(m=!0)}m||(m=B(a)?a.host:a,c?(c=Xb(c),Ua.call(m,b,c)):Yb.call(m,b));Zb(a,b);f&&d.ab(f);return b}function Sa(a,b){if(b.parentNode!==a)throw Error("The node to be removed is not a child of this node: "+b);var c=Z(b);if(T(a)){b.__shady=b.__shady||{};a.__shady=a.__shady||{};b===a.__shady.firstChild&&(a.__shady.firstChild=b.__shady.nextSibling);b===a.__shady.lastChild&&(a.__shady.lastChild=
b.__shady.previousSibling);var d=b.__shady.previousSibling;var e=b.__shady.nextSibling;d&&(d.__shady=d.__shady||{},d.__shady.nextSibling=e);e&&(e.__shady=e.__shady||{},e.__shady.previousSibling=d);b.__shady.parentNode=b.__shady.previousSibling=b.__shady.nextSibling=void 0;void 0!==a.__shady.childNodes&&(a.__shady.childNodes=null);if(Ta(a)){a.__shady.root.M();var f=!0}}$b(b);c&&((e=a&&"slot"===a.localName)&&(f=!0),((d=c.hb(b))||e)&&c.M());f||(f=B(a)?a.host:a,(!a.__shady.root&&"slot"!==b.localName||
f===U(b))&&ba.call(f,b));Zb(a,null,b);return b}function $b(a){if(a.__shady&&void 0!==a.__shady.ta)for(var b=a.childNodes,c=0,d=b.length,e;c<d&&(e=b[c]);c++)$b(e);a.__shady&&(a.__shady.ta=void 0)}function Xb(a){var b=a;a&&"slot"===a.localName&&(b=(b=a.__shady&&a.__shady.U)&&b.length?b[0]:Xb(a.nextSibling));return b}function Ta(a){return(a=a&&a.__shady&&a.__shady.root)&&a.Ba()}function ac(a,b){"slot"===b?(a=a.parentNode,Ta(a)&&a.__shady.root.M()):"slot"===a.localName&&"name"===b&&(b=Z(a))&&(b.jb(a),
b.M())}function Zb(a,b,c){if(a=a.__shady&&a.__shady.W)b&&a.addedNodes.push(b),c&&a.removedNodes.push(c),a.xb()}function bc(a){if(a&&a.nodeType){a.__shady=a.__shady||{};var b=a.__shady.ta;void 0===b&&(B(a)?b=a:b=(b=a.parentNode)?bc(b):a,document.documentElement.contains(a)&&(a.__shady.ta=b));return b}}function oa(a,b,c){var d=[];cc(a.childNodes,b,c,d);return d}function cc(a,b,c,d){for(var e=0,f=a.length,g;e<f&&(g=a[e]);e++){var h;if(h=g.nodeType===Node.ELEMENT_NODE){h=g;var m=b,Q=c,k=d,l=m(h);l&&k.push(h);
Q&&Q(l)?h=l:(cc(h.childNodes,m,Q,k),h=void 0)}if(h)break}}function dc(a){a=a.getRootNode();B(a)&&a.Ea()}function ec(a,b,c){pa||(pa=window.ShadyCSS&&window.ShadyCSS.ScopingShim);pa&&"class"===b?pa.setElementClass(a,c):(fc.call(a,b,c),ac(a,b))}function gc(a,b){if(a.ownerDocument!==document)return Va.call(document,a,b);var c=Va.call(document,a,!1);if(b){a=a.childNodes;b=0;for(var d;b<a.length;b++)d=gc(a[b],!0),c.appendChild(d)}return c}function Wa(a,b){var c=[],d=a;for(a=a===window?window:a.getRootNode();d;)c.push(d),
d=d.assignedSlot?d.assignedSlot:d.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&d.host&&(b||d!==a)?d.host:d.parentNode;c[c.length-1]===document&&c.push(window);return c}function hc(a,b){if(!B)return a;a=Wa(a,!0);for(var c=0,d,e,f,g;c<b.length;c++)if(d=b[c],f=d===window?window:d.getRootNode(),f!==e&&(g=a.indexOf(f),e=f),!B(f)||-1<g)return d}function Xa(a){function b(b,d){b=new a(b,d);b.ja=d&&!!d.composed;return b}rd(b,a);b.prototype=a.prototype;return b}function ic(a,b,c){if(c=b.__handlers&&b.__handlers[a.type]&&
b.__handlers[a.type][c])for(var d=0,e;(e=c[d])&&a.target!==a.relatedTarget&&(e.call(b,a),!a.Va);d++);}function xd(a){var b=a.composedPath();Object.defineProperty(a,"currentTarget",{get:function(){return d},configurable:!0});for(var c=b.length-1;0<=c;c--){var d=b[c];ic(a,d,"capture");if(a.ka)return}Object.defineProperty(a,"eventPhase",{get:function(){return Event.AT_TARGET}});var e;for(c=0;c<b.length;c++){d=b[c];var f=d.__shady&&d.__shady.root;if(!c||f&&f===e)if(ic(a,d,"bubble"),d!==window&&(e=d.getRootNode()),
a.ka)break}}function jc(a,b,c,d,e,f){for(var g=0;g<a.length;g++){var h=a[g],m=h.type,Q=h.capture,k=h.once,l=h.passive;if(b===h.node&&c===m&&d===Q&&e===k&&f===l)return g}return-1}function kc(a,b,c){if(b){if("object"===typeof c){var d=!!c.capture;var e=!!c.once;var f=!!c.passive}else d=!!c,f=e=!1;var g=c&&c.la||this,h=b.Z;if(h){if(-1<jc(h,g,a,d,e,f))return}else b.Z=[];h=function(d){e&&this.removeEventListener(a,b,c);d.__target||lc(d);if(g!==this){var f=Object.getOwnPropertyDescriptor(d,"currentTarget");
Object.defineProperty(d,"currentTarget",{get:function(){return g},configurable:!0})}if(d.composed||-1<d.composedPath().indexOf(g))if(d.target===d.relatedTarget)d.eventPhase===Event.BUBBLING_PHASE&&d.stopImmediatePropagation();else if(d.eventPhase===Event.CAPTURING_PHASE||d.bubbles||d.target===g){var h="object"===typeof b&&b.handleEvent?b.handleEvent(d):b.call(g,d);g!==this&&(f?(Object.defineProperty(d,"currentTarget",f),f=null):delete d.currentTarget);return h}};b.Z.push({node:this,type:a,capture:d,
once:e,passive:f,Bb:h});Ya[a]?(this.__handlers=this.__handlers||{},this.__handlers[a]=this.__handlers[a]||{capture:[],bubble:[]},this.__handlers[a][d?"capture":"bubble"].push(h)):(this instanceof Window?mc:nc).call(this,a,h,c)}}function oc(a,b,c){if(b){if("object"===typeof c){var d=!!c.capture;var e=!!c.once;var f=!!c.passive}else d=!!c,f=e=!1;var g=c&&c.la||this,h=void 0;var m=null;try{m=b.Z}catch(Q){}m&&(e=jc(m,g,a,d,e,f),-1<e&&(h=m.splice(e,1)[0].Bb,m.length||(b.Z=void 0)));(this instanceof Window?
pc:qc).call(this,a,h||b,c);h&&Ya[a]&&this.__handlers&&this.__handlers[a]&&(a=this.__handlers[a][d?"capture":"bubble"],h=a.indexOf(h),-1<h&&a.splice(h,1))}}function yd(){for(var a in Ya)window.addEventListener(a,function(a){a.__target||(lc(a),xd(a))},!0)}function lc(a){a.__target=a.target;a.za=a.relatedTarget;if(D.V){var b=rc,c=Object.getPrototypeOf(a);if(!c.hasOwnProperty("__patchProto")){var d=Object.create(c);d.Db=c;Ja(d,b);c.__patchProto=d}a.__proto__=c.__patchProto}else Ja(a,rc)}function ca(a,
b){return{index:a,X:[],aa:b}}function zd(a,b,c,d){var e=0,f=0,g=0,h=0,m=Math.min(b-e,d-f);if(0==e&&0==f)a:{for(g=0;g<m;g++)if(a[g]!==c[g])break a;g=m}if(b==a.length&&d==c.length){h=a.length;for(var k=c.length,l=0;l<m-g&&Ad(a[--h],c[--k]);)l++;h=l}e+=g;f+=g;b-=h;d-=h;if(!(b-e||d-f))return[];if(e==b){for(b=ca(e,0);f<d;)b.X.push(c[f++]);return[b]}if(f==d)return[ca(e,b-e)];m=e;g=f;d=d-g+1;h=b-m+1;b=Array(d);for(k=0;k<d;k++)b[k]=Array(h),b[k][0]=k;for(k=0;k<h;k++)b[0][k]=k;for(k=1;k<d;k++)for(l=1;l<h;l++)if(a[m+
l-1]===c[g+k-1])b[k][l]=b[k-1][l-1];else{var n=b[k-1][l]+1,p=b[k][l-1]+1;b[k][l]=n<p?n:p}m=b.length-1;g=b[0].length-1;d=b[m][g];for(a=[];0<m||0<g;)m?g?(h=b[m-1][g-1],k=b[m-1][g],l=b[m][g-1],n=k<l?k<h?k:h:l<h?l:h,n==h?(h==d?a.push(0):(a.push(1),d=h),m--,g--):n==k?(a.push(3),m--,d=k):(a.push(2),g--,d=l)):(a.push(3),m--):(a.push(2),g--);a.reverse();b=void 0;m=[];for(g=0;g<a.length;g++)switch(a[g]){case 0:b&&(m.push(b),b=void 0);e++;f++;break;case 1:b||(b=ca(e,0));b.aa++;e++;b.X.push(c[f]);f++;break;
case 2:b||(b=ca(e,0));b.aa++;e++;break;case 3:b||(b=ca(e,0)),b.X.push(c[f]),f++}b&&m.push(b);return m}function Ad(a,b){return a===b}function sc(a){var b=[];do b.unshift(a);while(a=a.parentNode);return b}function tc(a){dc(a);return a.__shady&&a.__shady.assignedSlot||null}function I(a,b){for(var c=Object.getOwnPropertyNames(b),d=0;d<c.length;d++){var e=c[d],f=Object.getOwnPropertyDescriptor(b,e);f.value?a[e]=f.value:Object.defineProperty(a,e,f)}}function Bd(){var a=window.customElements&&window.customElements.nativeHTMLElement||
HTMLElement;I(window.Node.prototype,Cd);I(window.Window.prototype,Dd);I(window.Text.prototype,Ed);I(window.DocumentFragment.prototype,Za);I(window.Element.prototype,uc);I(window.Document.prototype,vc);window.HTMLSlotElement&&I(window.HTMLSlotElement.prototype,wc);I(a.prototype,Fd);D.V&&(O(window.Node.prototype),O(window.Text.prototype),O(window.DocumentFragment.prototype),O(window.Element.prototype),O(a.prototype),O(window.Document.prototype),window.HTMLSlotElement&&O(window.HTMLSlotElement.prototype))}
function xc(a){var b=Gd.has(a);a=/^[a-z][.0-9_a-z]*-[\-.0-9_a-z]*$/.test(a);return!b&&a}function n(a){var b=a.isConnected;if(void 0!==b)return b;for(;a&&!(a.__CE_isImportDocument||a instanceof Document);)a=a.parentNode||(window.ShadowRoot&&a instanceof ShadowRoot?a.host:void 0);return!(!a||!(a.__CE_isImportDocument||a instanceof Document))}function $a(a,b){for(;b&&b!==a&&!b.nextSibling;)b=b.parentNode;return b&&b!==a?b.nextSibling:null}function M(a,b,c){c=c?c:new Set;for(var d=a;d;){if(d.nodeType===
Node.ELEMENT_NODE){var e=d;b(e);var f=e.localName;if("link"===f&&"import"===e.getAttribute("rel")){d=e.import;if(d instanceof Node&&!c.has(d))for(c.add(d),d=d.firstChild;d;d=d.nextSibling)M(d,b,c);d=$a(a,e);continue}else if("template"===f){d=$a(a,e);continue}if(e=e.__CE_shadowRoot)for(e=e.firstChild;e;e=e.nextSibling)M(e,b,c)}d=d.firstChild?d.firstChild:$a(a,d)}}function t(a,b,c){a[b]=c}function ab(a){a=a.replace(J.nb,"").replace(J.port,"");var b=yc,c=a,d=new za;d.start=0;d.end=c.length;for(var e=
d,f=0,g=c.length;f<g;f++)if("{"===c[f]){e.rules||(e.rules=[]);var h=e,m=h.rules[h.rules.length-1]||null;e=new za;e.start=f+1;e.parent=h;e.previous=m;h.rules.push(e)}else"}"===c[f]&&(e.end=f+1,e=e.parent||d);return b(d,a)}function yc(a,b){var c=b.substring(a.start,a.end-1);a.parsedCssText=a.cssText=c.trim();a.parent&&((c=b.substring(a.previous?a.previous.end:a.parent.start,a.start-1),c=Hd(c),c=c.replace(J.Ka," "),c=c.substring(c.lastIndexOf(";")+1),c=a.parsedSelector=a.selector=c.trim(),a.atRule=!c.indexOf("@"),
a.atRule)?c.indexOf("@media")?c.match(J.sb)&&(a.type=K.ia,a.keyframesName=a.selector.split(J.Ka).pop()):a.type=K.MEDIA_RULE:a.type=c.indexOf("--")?K.STYLE_RULE:K.va);if(c=a.rules)for(var d=0,e=c.length,f;d<e&&(f=c[d]);d++)yc(f,b);return a}function Hd(a){return a.replace(/\\([0-9a-f]{1,6})\s/gi,function(a,c){a=c;for(c=6-a.length;c--;)a="0"+a;return"\\"+a})}function zc(a,b,c){c=void 0===c?"":c;var d="";if(a.cssText||a.rules){var e=a.rules,f;if(f=e)f=e[0],f=!(f&&f.selector&&0===f.selector.indexOf("--"));
if(f){f=0;for(var g=e.length,h;f<g&&(h=e[f]);f++)d=zc(h,b,d)}else b?b=a.cssText:(b=a.cssText,b=b.replace(J.Fa,"").replace(J.Ja,""),b=b.replace(J.tb,"").replace(J.zb,"")),(d=b.trim())&&(d=" "+d+"\n")}d&&(a.selector&&(c+=a.selector+" {\n"),c+=d,a.selector&&(c+="}\n\n"));return c}function Ac(a){w=a&&a.shimcssproperties?!1:u||!(navigator.userAgent.match("AppleWebKit/601")||!window.CSS||!CSS.supports||!CSS.supports("box-shadow","0 0 0 var(--foo)"))}function V(a,b){if(!a)return"";"string"===typeof a&&
(a=ab(a));b&&W(a,b);return zc(a,w)}function qa(a){!a.__cssRules&&a.textContent&&(a.__cssRules=ab(a.textContent));return a.__cssRules||null}function Bc(a){return!!a.parent&&a.parent.type===K.ia}function W(a,b,c,d){if(a){var e=!1,f=a.type;if(d&&f===K.MEDIA_RULE){var g=a.selector.match(Id);g&&(window.matchMedia(g[1]).matches||(e=!0))}f===K.STYLE_RULE?b(a):c&&f===K.ia?c(a):f===K.va&&(e=!0);if((a=a.rules)&&!e){e=0;f=a.length;for(var h;e<f&&(h=a[e]);e++)W(h,b,c,d)}}}function bb(a,b,c,d){var e=document.createElement("style");
b&&e.setAttribute("scope",b);e.textContent=a;Cc(e,c,d);return e}function Cc(a,b,c){b=b||document.head;b.insertBefore(a,c&&c.nextSibling||b.firstChild);P?a.compareDocumentPosition(P)===Node.DOCUMENT_POSITION_PRECEDING&&(P=a):P=a}function Dc(a,b){var c=a.indexOf("var(");if(-1===c)return b(a,"","","");a:{var d=0;var e=c+3;for(var f=a.length;e<f;e++)if("("===a[e])d++;else if(")"===a[e]&&!--d)break a;e=-1}d=a.substring(c+4,e);c=a.substring(0,c);a=Dc(a.substring(e+1),b);e=d.indexOf(",");return-1===e?b(c,
d.trim(),"",a):b(c,d.substring(0,e).trim(),d.substring(e+1).trim(),a)}function ra(a,b){u?a.setAttribute("class",b):window.ShadyDOM.nativeMethods.setAttribute.call(a,"class",b)}function R(a){var b=a.localName,c="";b?-1<b.indexOf("-")||(c=b,b=a.getAttribute&&a.getAttribute("is")||""):(b=a.is,c=a.extends);return{is:b,Y:c}}function Ec(a){for(var b=0;b<a.length;b++){var c=a[b];if(c.target!==document.documentElement&&c.target!==document.head)for(var d=0;d<c.addedNodes.length;d++){var e=c.addedNodes[d];
if(e.nodeType===Node.ELEMENT_NODE){var f=e.getRootNode();var g=e;var h=[];g.classList?h=Array.from(g.classList):g instanceof window.SVGElement&&g.hasAttribute("class")&&(h=g.getAttribute("class").split(/\s+/));g=h;h=g.indexOf(x.c);(g=-1<h?g[h+1]:"")&&f===e.ownerDocument?x.a(e,g,!0):f.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&(f=f.host)&&(f=R(f).is,g!==f&&(g&&x.a(e,g,!0),x.a(e,f)))}}}}function Jd(a){if(a=sa[a])a._applyShimCurrentVersion=a._applyShimCurrentVersion||0,a._applyShimValidatingVersion=a._applyShimValidatingVersion||
0,a._applyShimNextVersion=(a._applyShimNextVersion||0)+1}function Fc(a){return a._applyShimCurrentVersion===a._applyShimNextVersion}function Kd(a){a._applyShimValidatingVersion=a._applyShimNextVersion;a.b||(a.b=!0,Ld.then(function(){a._applyShimCurrentVersion=a._applyShimNextVersion;a.b=!1}))}function ob(a){requestAnimationFrame(function(){Gc?Gc(a):(cb||(cb=new Promise(function(a){db=a}),"complete"===document.readyState?db():document.addEventListener("readystatechange",function(){"complete"===document.readyState&&
db()})),cb.then(function(){a&&a()}))})}(function(){if(!function(){var a=document.createEvent("Event");a.initEvent("foo",!0,!0);a.preventDefault();return a.defaultPrevented}()){var a=Event.prototype.preventDefault;Event.prototype.preventDefault=function(){this.cancelable&&(a.call(this),Object.defineProperty(this,"defaultPrevented",{get:function(){return!0},configurable:!0}))}}var b=/Trident/.test(navigator.userAgent);if(!window.CustomEvent||b&&"function"!==typeof window.CustomEvent)window.CustomEvent=
function(a,b){b=b||{};var c=document.createEvent("CustomEvent");c.initCustomEvent(a,!!b.bubbles,!!b.cancelable,b.detail);return c},window.CustomEvent.prototype=window.Event.prototype;if(!window.Event||b&&"function"!==typeof window.Event){var c=window.Event;window.Event=function(a,b){b=b||{};var c=document.createEvent("Event");c.initEvent(a,!!b.bubbles,!!b.cancelable);return c};if(c)for(var d in c)window.Event[d]=c[d];window.Event.prototype=c.prototype}if(!window.MouseEvent||b&&"function"!==typeof window.MouseEvent){b=
window.MouseEvent;window.MouseEvent=function(a,b){b=b||{};var c=document.createEvent("MouseEvent");c.initMouseEvent(a,!!b.bubbles,!!b.cancelable,b.view||window,b.detail,b.screenX,b.screenY,b.clientX,b.clientY,b.ctrlKey,b.altKey,b.shiftKey,b.metaKey,b.button,b.relatedTarget);return c};if(b)for(d in b)window.MouseEvent[d]=b[d];window.MouseEvent.prototype=b.prototype}Array.from||(Array.from=function(a){return[].slice.call(a)});Object.assign||(Object.assign=function(a,b){for(var c=[].slice.call(arguments,
1),d=0,e;d<c.length;d++)if(e=c[d])for(var f=a,k=e,l=Object.getOwnPropertyNames(k),n=0;n<l.length;n++)e=l[n],f[e]=k[e];return a})})(window.WebComponents);(function(){function a(){}var b="undefined"===typeof HTMLTemplateElement;/Trident/.test(navigator.userAgent)&&function(){var a=Document.prototype.importNode;Document.prototype.importNode=function(){var b=a.apply(this,arguments);if(b.nodeType===Node.DOCUMENT_FRAGMENT_NODE){var c=this.createDocumentFragment();c.appendChild(b);return c}return b}}();
var c=Node.prototype.cloneNode,d=Document.prototype.createElement,e=Document.prototype.importNode,f=function(){if(!b){var a=document.createElement("template"),c=document.createElement("template");c.content.appendChild(document.createElement("div"));a.content.appendChild(c);a=a.cloneNode(!0);return 0===a.content.childNodes.length||0===a.content.firstChild.content.childNodes.length||!(document.createDocumentFragment().cloneNode()instanceof DocumentFragment)}}();if(b){var g=function(a){switch(a){case "&":return"&";
case "<":return"<";case ">":return">";case "\u00a0":return" "}},h=function(b){Object.defineProperty(b,"innerHTML",{get:function(){for(var a="",b=this.content.firstChild;b;b=b.nextSibling)a+=b.outerHTML||b.data.replace(r,g);return a},set:function(b){m.body.innerHTML=b;for(a.b(m);this.content.firstChild;)this.content.removeChild(this.content.firstChild);for(;m.body.firstChild;)this.content.appendChild(m.body.firstChild)},configurable:!0})},m=document.implementation.createHTMLDocument("template"),
k=!0,l=document.createElement("style");l.textContent="template{display:none;}";var n=document.head;n.insertBefore(l,n.firstElementChild);a.prototype=Object.create(HTMLElement.prototype);var p=!document.createElement("div").hasOwnProperty("innerHTML");a.O=function(b){if(!b.content){b.content=m.createDocumentFragment();for(var c;c=b.firstChild;)b.content.appendChild(c);if(p)b.__proto__=a.prototype;else if(b.cloneNode=function(b){return a.a(this,b)},k)try{h(b)}catch(z){k=!1}a.b(b.content)}};h(a.prototype);
a.b=function(b){b=b.querySelectorAll("template");for(var c=0,d=b.length,e;c<d&&(e=b[c]);c++)a.O(e)};document.addEventListener("DOMContentLoaded",function(){a.b(document)});Document.prototype.createElement=function(){var b=d.apply(this,arguments);"template"===b.localName&&a.O(b);return b};var r=/[&\u00A0<>]/g}if(b||f)a.a=function(a,b){var d=c.call(a,!1);this.O&&this.O(d);b&&(d.content.appendChild(c.call(a.content,!0)),this.ra(d.content,a.content));return d},a.prototype.cloneNode=function(b){return a.a(this,
b)},a.ra=function(a,b){if(b.querySelectorAll){b=b.querySelectorAll("template");a=a.querySelectorAll("template");for(var c=0,d=a.length,e,f;c<d;c++)f=b[c],e=a[c],this.O&&this.O(f),e.parentNode.replaceChild(f.cloneNode(!0),e)}},Node.prototype.cloneNode=function(b){if(this instanceof DocumentFragment)if(b)var d=this.ownerDocument.importNode(this,!0);else return this.ownerDocument.createDocumentFragment();else d=c.call(this,b);b&&a.ra(d,this);return d},Document.prototype.importNode=function(b,c){if("template"===
b.localName)return a.a(b,c);var d=e.call(this,b,c);c&&a.ra(d,b);return d},f&&(window.HTMLTemplateElement.prototype.cloneNode=function(b){return a.a(this,b)});b&&(window.HTMLTemplateElement=a)})();!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.Gb?define(b):a.ES6Promise=b()}(window,function(){function a(a,b){B[v]=a;B[v+1]=b;v+=2;2===v&&(D?D(g):N())}function b(){return function(){return process.Jb(g)}}function c(){return"undefined"!=
typeof C?function(){C(g)}:f()}function d(){var a=0,b=new J(g),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){c.data=a=++a%2}}function e(){var a=new MessageChannel;return a.port1.onmessage=g,function(){return a.port2.postMessage(0)}}function f(){var a=setTimeout;return function(){return a(g,1)}}function g(){for(var a=0;a<v;a+=2)(0,B[a])(B[a+1]),B[a]=void 0,B[a+1]=void 0;v=0}function h(){try{var a=require("vertx");return C=a.Lb||a.Kb,c()}catch(Hc){return f()}}function m(b,
c){var d=arguments,e=this,f=new this.constructor(l);void 0===f[K]&&Ic(f);var g=e.o;return g?!function(){var b=d[g-1];a(function(){return Jc(g,f,b,e.m)})}():w(e,f,b,c),f}function k(a){if(a&&"object"==typeof a&&a.constructor===this)return a;var b=new this(l);return z(b,a),b}function l(){}function n(a){try{return a.then}catch(Hc){return M.error=Hc,M}}function p(a,b,c,d){try{a.call(b,c,d)}catch(Od){return Od}}function r(b,c,d){a(function(a){var b=!1,e=p(d,c,function(d){b||(b=!0,c!==d?z(a,d):q(a,d))},
function(c){b||(b=!0,L(a,c))});!b&&e&&(b=!0,L(a,e))},b)}function y(a,b){b.o===I?q(a,b.m):b.o===H?L(a,b.m):w(b,void 0,function(b){return z(a,b)},function(b){return L(a,b)})}function x(a,b,c){b.constructor===a.constructor&&c===m&&b.constructor.resolve===k?y(a,b):c===M?(L(a,M.error),M.error=null):void 0===c?q(a,b):"function"==typeof c?r(a,b,c):q(a,b)}function z(a,b){if(a===b)L(a,new TypeError("You cannot resolve a promise with itself"));else{var c=typeof b;null===b||"object"!==c&&"function"!==c?q(a,
b):x(a,b,n(b))}}function u(a){a.Ca&&a.Ca(a.m);X(a)}function q(b,c){b.o===G&&(b.m=c,b.o=I,0!==b.T.length&&a(X,b))}function L(b,c){b.o===G&&(b.o=H,b.m=c,a(u,b))}function w(b,c,d,e){var f=b.T,g=f.length;b.Ca=null;f[g]=c;f[g+I]=d;f[g+H]=e;0===g&&b.o&&a(X,b)}function X(a){var b=a.T,c=a.o;if(0!==b.length){for(var d,e,f=a.m,g=0;g<b.length;g+=3)d=b[g],e=b[g+c],d?Jc(c,d,e,f):e(f);a.T.length=0}}function Kc(){this.error=null}function Jc(a,b,c,d){var e="function"==typeof c,f=void 0,g=void 0,h=void 0,X=void 0;
if(e){try{var k=c(d)}catch(Pd){k=(O.error=Pd,O)}if(f=k,f===O?(X=!0,g=f.error,f.error=null):h=!0,b===f)return void L(b,new TypeError("A promises callback cannot return that same promise."))}else f=d,h=!0;b.o!==G||(e&&h?z(b,f):X?L(b,g):a===I?q(b,f):a===H&&L(b,f))}function Lc(a,b){try{b(function(b){z(a,b)},function(b){L(a,b)})}catch(Md){L(a,Md)}}function Ic(a){a[K]=P++;a.o=void 0;a.m=void 0;a.T=[]}function da(a,b){this.fb=a;this.J=new a(l);this.J[K]||Ic(this.J);A(b)?(this.length=b.length,this.$=b.length,
this.m=Array(this.length),0===this.length?q(this.J,this.m):(this.length=this.length||0,this.eb(b),0===this.$&&q(this.J,this.m))):L(this.J,Error("Array Methods must be provided an Array"))}function E(a){this[K]=P++;this.m=this.o=void 0;this.T=[];if(l!==a){if("function"!=typeof a)throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(this instanceof E)Lc(this,a);else throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}}var t=void 0,A=t=Array.isArray?Array.isArray:function(a){return"[object Array]"===Object.prototype.toString.call(a)},v=0,C=void 0,D=void 0,F=(t="undefined"!=typeof window?window:void 0)||{},J=F.MutationObserver||F.WebKitMutationObserver;F="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;var B=Array(1E3),N=void 0;N="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process)?b():J?d():F?e():t||"function"!=
typeof require?f():h();var K=Math.random().toString(36).substring(16),G=void 0,I=1,H=2,M=new Kc,O=new Kc,P=0;return da.prototype.eb=function(a){for(var b=0;this.o===G&&b<a.length;b++)this.cb(a[b],b)},da.prototype.cb=function(a,b){var c=this.fb,d=c.resolve;d===k?(d=n(a),d===m&&a.o!==G?this.oa(a.o,b,a.m):"function"!=typeof d?(this.$--,this.m[b]=a):c===E?(c=new c(l),x(c,a,d),this.pa(c,b)):this.pa(new c(function(b){return b(a)}),b)):this.pa(d(a),b)},da.prototype.oa=function(a,b,c){var d=this.J;d.o===
G&&(this.$--,a===H?L(d,c):this.m[b]=c);0===this.$&&q(d,this.m)},da.prototype.pa=function(a,b){var c=this;w(a,void 0,function(a){return c.oa(I,b,a)},function(a){return c.oa(H,b,a)})},E.g=function(a){return(new da(this,a)).J},E.h=function(a){var b=this;return new b(A(a)?function(c,d){for(var e=a.length,f=0;f<e;f++)b.resolve(a[f]).then(c,d)}:function(a,b){return b(new TypeError("You must pass an array to race."))})},E.resolve=k,E.i=function(a){var b=new this(l);return L(b,a),b},E.f=function(a){D=a},
E.c=function(b){a=b},E.b=a,E.prototype={constructor:E,then:m,"catch":function(a){return this.then(null,a)}},E.a=function(){var a=void 0;if("undefined"!=typeof global)a=global;else if("undefined"!=typeof self)a=self;else try{a=Function("return this")()}catch(Nd){throw Error("polyfill failed because global object is unavailable in this environment");}var b=a.Promise;if(b){var c=null;try{c=Object.prototype.toString.call(b.resolve())}catch(Nd){}if("[object Promise]"===c&&!b.Hb)return}a.Promise=E},E.Promise=
E,E.a(),E});(function(a){function b(a,b){if("function"===typeof window.CustomEvent)return new CustomEvent(a,b);var c=document.createEvent("CustomEvent");c.initCustomEvent(a,!!b.bubbles,!!b.cancelable,b.detail);return c}function c(a){if(n)return a.ownerDocument!==document?a.ownerDocument:null;var b=a.__importDoc;if(!b&&a.parentNode){b=a.parentNode;if("function"===typeof b.closest)b=b.closest("link[rel=import]");else for(;!h(b)&&(b=b.parentNode););a.__importDoc=b}return b}function d(a){var b=document.querySelectorAll("link[rel=import]:not(import-dependency)"),
c=b.length;c?l(b,function(b){return g(b,function(){--c||a()})}):a()}function e(a){function b(){"loading"!==document.readyState&&document.body&&(document.removeEventListener("readystatechange",b),a())}document.addEventListener("readystatechange",b);b()}function f(a){e(function(){return d(function(){return a&&a()})})}function g(a,b){if(a.__loaded)b&&b();else if("script"===a.localName&&!a.src||"style"===a.localName&&!a.firstChild)a.__loaded=!0,b&&b();else{var c=function(d){a.removeEventListener(d.type,
c);a.__loaded=!0;b&&b()};a.addEventListener("load",c);w&&"style"===a.localName||a.addEventListener("error",c)}}function h(a){return a.nodeType===Node.ELEMENT_NODE&&"link"===a.localName&&"import"===a.rel}function k(){var a=this;this.a={};this.b=0;this.f=new MutationObserver(function(b){return a.l(b)});this.f.observe(document.head,{childList:!0,subtree:!0});this.c(document)}function l(a,b,c){var d=a?a.length:0,e=c?-1:1;for(c=c?d-1:0;c<d&&0<=c;c+=e)b(a[c],c)}var n="import"in document.createElement("link"),
p=null;!1==="currentScript"in document&&Object.defineProperty(document,"currentScript",{get:function(){return p||("complete"!==document.readyState?document.scripts[document.scripts.length-1]:null)},configurable:!0});var q=/(^\/)|(^#)|(^[\w-\d]*:)/,r=/(url\()([^)]*)(\))/g,x=/(@import[\s]+(?!url\())([^;]*)(;)/g,y=/(<link[^>]*)(rel=['|"]?stylesheet['|"]?[^>]*>)/g,z={ob:function(a,b){a.href&&a.setAttribute("href",z.ua(a.getAttribute("href"),b));a.src&&a.setAttribute("src",z.ua(a.getAttribute("src"),b));
if("style"===a.localName){var c=z.Ma(a.textContent,b,r);a.textContent=z.Ma(c,b,x)}},Ma:function(a,b,c){return a.replace(c,function(a,c,d,e){a=d.replace(/["']/g,"");b&&(a=z.Na(a,b));return c+"'"+a+"'"+e})},ua:function(a,b){return a&&q.test(a)?a:z.Na(a,b)},Na:function(a,b){if(void 0===z.ma){z.ma=!1;try{var c=new URL("b","http://a");c.pathname="c%20d";z.ma="http://a/c%20d"===c.href}catch(Lc){}}if(z.ma)return(new URL(a,b)).href;c=z.$a;c||(c=document.implementation.createHTMLDocument("temp"),z.$a=c,c.xa=
c.createElement("base"),c.head.appendChild(c.xa),c.wa=c.createElement("a"));c.xa.href=b;c.wa.href=a;return c.wa.href||a}},v={async:!0,load:function(a,b,c){if(a)if(a.match(/^data:/)){a=a.split(",");var d=a[1];d=-1<a[0].indexOf(";base64")?atob(d):decodeURIComponent(d);b(d)}else{var e=new XMLHttpRequest;e.open("GET",a,v.async);e.onload=function(){var a=e.responseURL||e.getResponseHeader("Location");a&&!a.indexOf("/")&&(a=(location.origin||location.protocol+"//"+location.host)+a);var d=e.response||e.responseText;
304===e.status||!e.status||200<=e.status&&300>e.status?b(d,a):c(d)};e.send()}else c("error: href must be specified")}},w=/Trident/.test(navigator.userAgent)||/Edge\/\d./i.test(navigator.userAgent);k.prototype.c=function(a){var b=this;a=a.querySelectorAll("link[rel=import]");l(a,function(a){return b.h(a)})};k.prototype.h=function(a){var b=this,c=a.href;if(void 0!==this.a[c]){var d=this.a[c];d&&d.__loaded&&(a.import=d,this.g(a))}else this.b++,this.a[c]="pending",v.load(c,function(a,d){a=b.s(a,d||c);
b.a[c]=a;b.b--;b.c(a);b.i()},function(){b.a[c]=null;b.b--;b.i()})};k.prototype.s=function(a,b){if(!a)return document.createDocumentFragment();w&&(a=a.replace(y,function(a,b,c){return-1===a.indexOf("type=")?b+" type=import-disable "+c:a}));var c=document.createElement("template");c.innerHTML=a;if(c.content)a=c.content;else for(a=document.createDocumentFragment();c.firstChild;)a.appendChild(c.firstChild);if(c=a.querySelector("base"))b=z.ua(c.getAttribute("href"),b),c.removeAttribute("href");c=a.querySelectorAll('link[rel=import], link[rel=stylesheet][href][type=import-disable],\n style:not([type]), link[rel=stylesheet][href]:not([type]),\n script:not([type]), script[type="application/javascript"],\n script[type="text/javascript"]');
var d=0;l(c,function(a){g(a);z.ob(a,b);a.setAttribute("import-dependency","");"script"===a.localName&&!a.src&&a.textContent&&(a.setAttribute("src","data:text/javascript;charset=utf-8,"+encodeURIComponent(a.textContent+("\n//# sourceURL="+b+(d?"-"+d:"")+".js\n"))),a.textContent="",d++)});return a};k.prototype.i=function(){var a=this;if(!this.b){this.f.disconnect();this.flatten(document);var b=!1,c=!1,d=function(){c&&b&&(a.c(document),a.b||(a.f.observe(document.head,{childList:!0,subtree:!0}),a.j()))};
this.v(function(){c=!0;d()});this.u(function(){b=!0;d()})}};k.prototype.flatten=function(a){var b=this;a=a.querySelectorAll("link[rel=import]");l(a,function(a){var c=b.a[a.href];(a.import=c)&&c.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&(b.a[a.href]=a,a.readyState="loading",a.import=a,b.flatten(c),a.appendChild(c))})};k.prototype.u=function(a){function b(e){if(e<d){var f=c[e],h=document.createElement("script");f.removeAttribute("import-dependency");l(f.attributes,function(a){return h.setAttribute(a.name,
a.value)});p=h;f.parentNode.replaceChild(h,f);g(h,function(){p=null;b(e+1)})}else a()}var c=document.querySelectorAll("script[import-dependency]"),d=c.length;b(0)};k.prototype.v=function(a){var b=document.querySelectorAll("style[import-dependency],\n link[rel=stylesheet][import-dependency]"),d=b.length;if(d){var e=w&&!!document.querySelector("link[rel=stylesheet][href][type=import-disable]");l(b,function(b){g(b,function(){b.removeAttribute("import-dependency");--d||a()});if(e&&b.parentNode!==document.head){var f=
document.createElement(b.localName);f.__appliedElement=b;f.setAttribute("type","import-placeholder");b.parentNode.insertBefore(f,b.nextSibling);for(f=c(b);f&&c(f);)f=c(f);f.parentNode!==document.head&&(f=null);document.head.insertBefore(b,f);b.removeAttribute("type")}})}else a()};k.prototype.j=function(){var a=this,b=document.querySelectorAll("link[rel=import]");l(b,function(b){return a.g(b)},!0)};k.prototype.g=function(a){a.__loaded||(a.__loaded=!0,a.import&&(a.import.readyState="complete"),a.dispatchEvent(b(a.import?
"load":"error",{bubbles:!1,cancelable:!1,detail:void 0})))};k.prototype.l=function(a){var b=this;l(a,function(a){return l(a.addedNodes,function(a){a&&a.nodeType===Node.ELEMENT_NODE&&(h(a)?b.h(a):b.c(a))})})};if(n){var u=document.querySelectorAll("link[rel=import]");l(u,function(a){a.import&&"loading"===a.import.readyState||(a.__loaded=!0)});u=function(a){a=a.target;h(a)&&(a.__loaded=!0)};document.addEventListener("load",u,!0);document.addEventListener("error",u,!0)}else{var t=Object.getOwnPropertyDescriptor(Node.prototype,
"baseURI");Object.defineProperty((!t||t.configurable?Node:Element).prototype,"baseURI",{get:function(){var a=h(this)?this:c(this);return a?a.href:t&&t.get?t.get.call(this):(document.querySelector("base")||window.location).href},configurable:!0,enumerable:!0});e(function(){return new k})}f(function(){return document.dispatchEvent(b("HTMLImportsLoaded",{cancelable:!0,bubbles:!0,detail:void 0}))});a.useNative=n;a.whenReady=f;a.importForElement=c})(window.HTMLImports=window.HTMLImports||{});(function(){window.WebComponents=
window.WebComponents||{flags:{}};var a=document.querySelector('script[src*="webcomponents-lite.js"]'),b=/wc-(.+)/,c={};if(!c.noOpts){location.search.slice(1).split("&").forEach(function(a){a=a.split("=");var d;a[0]&&(d=a[0].match(b))&&(c[d[1]]=a[1]||!0)});if(a)for(var d=0,e;e=a.attributes[d];d++)"src"!==e.name&&(c[e.name]=e.value||!0);c.log&&c.log.split?(a=c.log.split(","),c.log={},a.forEach(function(a){c.log[a]=!0})):c.log={}}window.WebComponents.flags=c;if(a=c.shadydom)window.ShadyDOM=window.ShadyDOM||
{},window.ShadyDOM.force=a;(a=c.register||c.ce)&&window.customElements&&(window.customElements.forcePolyfill=a)})();var D=window.ShadyDOM||{};D.pb=!(!Element.prototype.attachShadow||!Node.prototype.getRootNode);var eb=Object.getOwnPropertyDescriptor(Node.prototype,"firstChild");D.V=!!(eb&&eb.configurable&&eb.get);D.Ia=D.force||!D.pb;var Y=Element.prototype,Mc=Y.matches||Y.matchesSelector||Y.mozMatchesSelector||Y.msMatchesSelector||Y.oMatchesSelector||Y.webkitMatchesSelector,Ma=document.createTextNode(""),
Hb=0,La=[];(new MutationObserver(function(){for(;La.length;)try{La.shift()()}catch(a){throw Ma.textContent=Hb++,a;}})).observe(Ma,{characterData:!0});var aa=[],Na;na.list=aa;ma.prototype.xb=function(){var a=this;this.a||(this.a=!0,Gb(function(){a.b()}))};ma.prototype.b=function(){if(this.a){this.a=!1;var a=this.takeRecords();a.length&&this.ba.forEach(function(b){b(a)})}};ma.prototype.takeRecords=function(){if(this.addedNodes.length||this.removedNodes.length){var a=[{addedNodes:this.addedNodes,removedNodes:this.removedNodes}];
this.addedNodes=[];this.removedNodes=[];return a}return[]};var Yb=Element.prototype.appendChild,Ua=Element.prototype.insertBefore,ba=Element.prototype.removeChild,fc=Element.prototype.setAttribute,Nc=Element.prototype.removeAttribute,fb=Element.prototype.cloneNode,Va=Document.prototype.importNode,nc=Element.prototype.addEventListener,qc=Element.prototype.removeEventListener,mc=Window.prototype.addEventListener,pc=Window.prototype.removeEventListener,gb=Element.prototype.dispatchEvent,Qd=Object.freeze({appendChild:Yb,
insertBefore:Ua,removeChild:ba,setAttribute:fc,removeAttribute:Nc,cloneNode:fb,importNode:Va,addEventListener:nc,removeEventListener:qc,Mb:mc,Nb:pc,dispatchEvent:gb,querySelector:Element.prototype.querySelector,querySelectorAll:Element.prototype.querySelectorAll}),td=/[&\u00A0"]/g,wd=/[&\u00A0<>]/g,ud=Kb("area base br col command embed hr img input keygen link meta param source track wbr".split(" ")),vd=Kb("style script xmp iframe noembed noframes plaintext noscript".split(" ")),v=document.createTreeWalker(document,
NodeFilter.SHOW_ALL,null,!1),C=document.createTreeWalker(document,NodeFilter.SHOW_ELEMENT,null,!1),Rd=Object.freeze({parentNode:U,firstChild:Ha,lastChild:Ia,previousSibling:Lb,nextSibling:Mb,childNodes:S,parentElement:Nb,firstElementChild:Ob,lastElementChild:Pb,previousElementSibling:Qb,nextElementSibling:Rb,children:Sb,innerHTML:Tb,textContent:Ub}),hb=Object.getOwnPropertyDescriptor(Element.prototype,"innerHTML")||Object.getOwnPropertyDescriptor(HTMLElement.prototype,"innerHTML"),ta=document.implementation.createHTMLDocument("inert").createElement("div"),
ib=Object.getOwnPropertyDescriptor(Document.prototype,"activeElement"),Vb={parentElement:{get:function(){var a=this.__shady&&this.__shady.parentNode;a&&a.nodeType!==Node.ELEMENT_NODE&&(a=null);return void 0!==a?a:Nb(this)},configurable:!0},parentNode:{get:function(){var a=this.__shady&&this.__shady.parentNode;return void 0!==a?a:U(this)},configurable:!0},nextSibling:{get:function(){var a=this.__shady&&this.__shady.nextSibling;return void 0!==a?a:Mb(this)},configurable:!0},previousSibling:{get:function(){var a=
this.__shady&&this.__shady.previousSibling;return void 0!==a?a:Lb(this)},configurable:!0},className:{get:function(){return this.getAttribute("class")||""},set:function(a){this.setAttribute("class",a)},configurable:!0},nextElementSibling:{get:function(){if(this.__shady&&void 0!==this.__shady.nextSibling){for(var a=this.nextSibling;a&&a.nodeType!==Node.ELEMENT_NODE;)a=a.nextSibling;return a}return Rb(this)},configurable:!0},previousElementSibling:{get:function(){if(this.__shady&&void 0!==this.__shady.previousSibling){for(var a=
this.previousSibling;a&&a.nodeType!==Node.ELEMENT_NODE;)a=a.previousSibling;return a}return Qb(this)},configurable:!0}},Pa={childNodes:{get:function(){if(T(this)){if(!this.__shady.childNodes){this.__shady.childNodes=[];for(var a=this.firstChild;a;a=a.nextSibling)this.__shady.childNodes.push(a)}var b=this.__shady.childNodes}else b=S(this);b.item=function(a){return b[a]};return b},configurable:!0},childElementCount:{get:function(){return this.children.length},configurable:!0},firstChild:{get:function(){var a=
this.__shady&&this.__shady.firstChild;return void 0!==a?a:Ha(this)},configurable:!0},lastChild:{get:function(){var a=this.__shady&&this.__shady.lastChild;return void 0!==a?a:Ia(this)},configurable:!0},textContent:{get:function(){if(T(this)){for(var a=[],b=0,c=this.childNodes,d;d=c[b];b++)d.nodeType!==Node.COMMENT_NODE&&a.push(d.textContent);return a.join("")}return Ub(this)},set:function(a){switch(this.nodeType){case Node.ELEMENT_NODE:case Node.DOCUMENT_FRAGMENT_NODE:for(;this.firstChild;)this.removeChild(this.firstChild);
this.appendChild(document.createTextNode(a));break;default:this.nodeValue=a}},configurable:!0},firstElementChild:{get:function(){if(this.__shady&&void 0!==this.__shady.firstChild){for(var a=this.firstChild;a&&a.nodeType!==Node.ELEMENT_NODE;)a=a.nextSibling;return a}return Ob(this)},configurable:!0},lastElementChild:{get:function(){if(this.__shady&&void 0!==this.__shady.lastChild){for(var a=this.lastChild;a&&a.nodeType!==Node.ELEMENT_NODE;)a=a.previousSibling;return a}return Pb(this)},configurable:!0},
children:{get:function(){var a;T(this)?a=Array.prototype.filter.call(this.childNodes,function(a){return a.nodeType===Node.ELEMENT_NODE}):a=Sb(this);a.item=function(b){return a[b]};return a},configurable:!0},innerHTML:{get:function(){var a="template"===this.localName?this.content:this;return T(this)?Oa(a):Tb(a)},set:function(a){for(var b="template"===this.localName?this.content:this;b.firstChild;)b.removeChild(b.firstChild);for(hb&&hb.set?hb.set.call(ta,a):ta.innerHTML=a;ta.firstChild;)b.appendChild(ta.firstChild)},
configurable:!0}},Oc={shadowRoot:{get:function(){return this.__shady&&this.__shady.ub||null},configurable:!0}},Qa={activeElement:{get:function(){var a=ib&&ib.get?ib.get.call(document):D.V?void 0:document.activeElement;if(a&&a.nodeType){var b=!!B(this);if(this===document||b&&this.host!==a&&this.host.contains(a)){for(b=Z(a);b&&b!==this;)a=b.host,b=Z(a);a=this===document?b?null:a:b===this?a:null}else a=null}else a=null;return a},set:function(){},configurable:!0}},Fb=D.V?function(){}:function(a){a.__shady&&
a.__shady.Ya||(a.__shady=a.__shady||{},a.__shady.Ya=!0,G(a,Vb,!0))},Eb=D.V?function(){}:function(a){a.__shady&&a.__shady.Wa||(a.__shady=a.__shady||{},a.__shady.Wa=!0,G(a,Pa,!0),G(a,Oc,!0))},pa=null,Sd={blur:!0,focus:!0,focusin:!0,focusout:!0,click:!0,dblclick:!0,mousedown:!0,mouseenter:!0,mouseleave:!0,mousemove:!0,mouseout:!0,mouseover:!0,mouseup:!0,wheel:!0,beforeinput:!0,input:!0,keydown:!0,keyup:!0,compositionstart:!0,compositionupdate:!0,compositionend:!0,touchstart:!0,touchend:!0,touchmove:!0,
touchcancel:!0,pointerover:!0,pointerenter:!0,pointerdown:!0,pointermove:!0,pointerup:!0,pointercancel:!0,pointerout:!0,pointerleave:!0,gotpointercapture:!0,lostpointercapture:!0,dragstart:!0,drag:!0,dragenter:!0,dragleave:!0,dragover:!0,drop:!0,dragend:!0,DOMActivate:!0,DOMFocusIn:!0,DOMFocusOut:!0,keypress:!0},rc={get composed(){!1!==this.isTrusted&&void 0===this.ja&&(this.ja=Sd[this.type]);return this.ja||!1},composedPath:function(){this.ya||(this.ya=Wa(this.__target,this.composed));return this.ya},
get target(){return hc(this.currentTarget,this.composedPath())},get relatedTarget(){if(!this.za)return null;this.Aa||(this.Aa=Wa(this.za,!0));return hc(this.currentTarget,this.Aa)},stopPropagation:function(){Event.prototype.stopPropagation.call(this);this.ka=!0},stopImmediatePropagation:function(){Event.prototype.stopImmediatePropagation.call(this);this.ka=this.Va=!0}},Ya={focus:!0,blur:!0},Td=Xa(window.Event),Ud=Xa(window.CustomEvent),Vd=Xa(window.MouseEvent),Db={};l.prototype=Object.create(DocumentFragment.prototype);
l.prototype.D=function(a,b){this.Xa="ShadyRoot";la(a);la(this);this.host=a;this.L=b&&b.mode;a.__shady=a.__shady||{};a.__shady.root=this;a.__shady.ub="closed"!==this.L?this:null;this.S=!1;this.b=[];this.a=null;b=S(a);for(var c=0,d=b.length;c<d;c++)ba.call(a,b[c])};l.prototype.M=function(){var a=this;this.S||(this.S=!0,Ib(function(){return a.Ea()}))};l.prototype.C=function(){for(var a=this,b=this;b;)b.S&&(a=b),b=b.ib();return a};l.prototype.ib=function(){var a=this.host.getRootNode();if(B(a))for(var b=
this.host.childNodes,c=0,d;c<b.length;c++)if(d=b[c],this.h(d))return a};l.prototype.Ea=function(){this.S&&this.C()._renderRoot()};l.prototype._renderRoot=function(){this.S=!1;this.v();this.s()};l.prototype.v=function(){for(var a=0,b;a<this.b.length;a++)b=this.b[a],this.l(b);for(b=this.host.firstChild;b;b=b.nextSibling)this.f(b);for(a=0;a<this.b.length;a++){b=this.b[a];if(!b.__shady.assignedNodes.length)for(var c=b.firstChild;c;c=c.nextSibling)this.f(c,b);c=b.parentNode;(c=c.__shady&&c.__shady.root)&&
c.Ba()&&c._renderRoot();this.c(b.__shady.U,b.__shady.assignedNodes);if(c=b.__shady.Da){for(var d=0;d<c.length;d++)c[d].__shady.na=null;b.__shady.Da=null;c.length>b.__shady.assignedNodes.length&&(b.__shady.qa=!0)}b.__shady.qa&&(b.__shady.qa=!1,this.g(b))}};l.prototype.f=function(a,b){a.__shady=a.__shady||{};var c=a.__shady.na;a.__shady.na=null;b||(b=(b=this.a[a.slot||"__catchall"])&&b[0]);b?(b.__shady.assignedNodes.push(a),a.__shady.assignedSlot=b):a.__shady.assignedSlot=void 0;c!==a.__shady.assignedSlot&&
a.__shady.assignedSlot&&(a.__shady.assignedSlot.__shady.qa=!0)};l.prototype.l=function(a){var b=a.__shady.assignedNodes;a.__shady.assignedNodes=[];a.__shady.U=[];if(a.__shady.Da=b)for(var c=0;c<b.length;c++){var d=b[c];d.__shady.na=d.__shady.assignedSlot;d.__shady.assignedSlot===a&&(d.__shady.assignedSlot=null)}};l.prototype.c=function(a,b){for(var c=0,d;c<b.length&&(d=b[c]);c++)"slot"==d.localName?this.c(a,d.__shady.assignedNodes):a.push(b[c])};l.prototype.g=function(a){gb.call(a,new Event("slotchange"));
a.__shady.assignedSlot&&this.g(a.__shady.assignedSlot)};l.prototype.s=function(){for(var a=this.b,b=[],c=0;c<a.length;c++){var d=a[c].parentNode;d.__shady&&d.__shady.root||!(0>b.indexOf(d))||b.push(d)}for(a=0;a<b.length;a++)c=b[a],this.I(c===this?this.host:c,this.u(c))};l.prototype.u=function(a){var b=[];a=a.childNodes;for(var c=0;c<a.length;c++){var d=a[c];if(this.h(d)){d=d.__shady.U;for(var e=0;e<d.length;e++)b.push(d[e])}else b.push(d)}return b};l.prototype.h=function(a){return"slot"==a.localName};
l.prototype.I=function(a,b){for(var c=S(a),d=zd(b,b.length,c,c.length),e=0,f=0,g;e<d.length&&(g=d[e]);e++){for(var h=0,k;h<g.X.length&&(k=g.X[h]);h++)U(k)===a&&ba.call(a,k),c.splice(g.index+f,1);f-=g.aa}for(e=0;e<d.length&&(g=d[e]);e++)for(f=c[g.index],h=g.index;h<g.index+g.aa;h++)k=b[h],Ua.call(a,k,f),c.splice(h,0,k)};l.prototype.ab=function(a){this.a=this.a||{};this.b=this.b||[];for(var b=0;b<a.length;b++){var c=a[b];c.__shady=c.__shady||{};la(c);la(c.parentNode);var d=this.i(c);if(this.a[d]){var e=
e||{};e[d]=!0;this.a[d].push(c)}else this.a[d]=[c];this.b.push(c)}if(e)for(var f in e)this.a[f]=this.j(this.a[f])};l.prototype.i=function(a){var b=a.name||a.getAttribute("name")||"__catchall";return a.Za=b};l.prototype.j=function(a){return a.sort(function(a,c){a=sc(a);for(var b=sc(c),e=0;e<a.length;e++){c=a[e];var f=b[e];if(c!==f)return a=Array.from(c.parentNode.childNodes),a.indexOf(c)-a.indexOf(f)}})};l.prototype.hb=function(a){this.a=this.a||{};this.b=this.b||[];var b=this.a,c;for(c in b)for(var d=
b[c],e=0;e<d.length;e++){var f=d[e],g;a:{for(g=f;g;){if(g==a){g=!0;break a}g=g.parentNode}g=void 0}if(g){d.splice(e,1);var h=this.b.indexOf(f);0<=h&&this.b.splice(h,1);e--;this.H(f);h=!0}}return h};l.prototype.jb=function(a){var b=a.Za,c=this.i(a);if(c!==b){b=this.a[b];var d=b.indexOf(a);0<=d&&b.splice(d,1);b=this.a[c]||(this.a[c]=[]);b.push(a);1<b.length&&(this.a[c]=this.j(b))}};l.prototype.H=function(a){if(a=a.__shady.U)for(var b=0;b<a.length;b++){var c=a[b],d=U(c);d&&ba.call(d,c)}};l.prototype.Ba=
function(){return!!this.b.length};l.prototype.addEventListener=function(a,b,c){"object"!==typeof c&&(c={capture:!!c});c.la=this;this.host.addEventListener(a,b,c)};l.prototype.removeEventListener=function(a,b,c){"object"!==typeof c&&(c={capture:!!c});c.la=this;this.host.removeEventListener(a,b,c)};l.prototype.getElementById=function(a){return oa(this,function(b){return b.id==a},function(a){return!!a})[0]||null};(function(a){G(a,Pa,!0);G(a,Qa,!0)})(l.prototype);var Dd={addEventListener:kc.bind(window),
removeEventListener:oc.bind(window)},Cd={addEventListener:kc,removeEventListener:oc,appendChild:function(a){return Ra(this,a)},insertBefore:function(a,b){return Ra(this,a,b)},removeChild:function(a){return Sa(this,a)},replaceChild:function(a,b){Ra(this,a,b);Sa(this,b);return a},cloneNode:function(a){if("template"==this.localName)var b=fb.call(this,a);else if(b=fb.call(this,!1),a){a=this.childNodes;for(var c=0,d;c<a.length;c++)d=a[c].cloneNode(!0),b.appendChild(d)}return b},getRootNode:function(){return bc(this)},
get isConnected(){var a=this.ownerDocument;if(a&&a.contains&&a.contains(this)||(a=a.documentElement)&&a.contains&&a.contains(this))return!0;for(a=this;a&&!(a instanceof Document);)a=a.parentNode||(a instanceof l?a.host:void 0);return!!(a&&a instanceof Document)},dispatchEvent:function(a){na();return gb.call(this,a)}},Ed={get assignedSlot(){return tc(this)}},Za={querySelector:function(a){return oa(this,function(b){return Mc.call(b,a)},function(a){return!!a})[0]||null},querySelectorAll:function(a){return oa(this,
function(b){return Mc.call(b,a)})}},wc={assignedNodes:function(a){if("slot"===this.localName)return dc(this),this.__shady?(a&&a.flatten?this.__shady.U:this.__shady.assignedNodes)||[]:[]}},uc=Ka({setAttribute:function(a,b){ec(this,a,b)},removeAttribute:function(a){Nc.call(this,a);ac(this,a)},attachShadow:function(a){if(!this)throw"Must provide a host.";if(!a)throw"Not enough arguments.";return new l(Db,this,a)},get slot(){return this.getAttribute("slot")},set slot(a){ec(this,"slot",a)},get assignedSlot(){return tc(this)}},
Za,wc);Object.defineProperties(uc,Oc);var vc=Ka({importNode:function(a,b){return gc(a,b)},getElementById:function(a){return oa(this,function(b){return b.id==a},function(a){return!!a})[0]||null}},Za);Object.defineProperties(vc,{_activeElement:Qa.activeElement});var Wd=HTMLElement.prototype.blur,Fd=Ka({blur:function(){var a=this.__shady&&this.__shady.root;(a=a&&a.activeElement)?a.blur():Wd.call(this)}});D.Ia&&(window.ShadyDOM={inUse:D.Ia,patch:function(a){return a},isShadyRoot:B,enqueue:Ib,flush:na,
settings:D,filterMutations:sd,observeChildren:qd,unobserveChildren:pd,nativeMethods:Qd,nativeTree:Rd},window.Event=Td,window.CustomEvent=Ud,window.MouseEvent=Vd,yd(),Bd(),window.ShadowRoot=l);var Gd=new Set("annotation-xml color-profile font-face font-face-src font-face-uri font-face-format font-face-name missing-glyph".split(" "));A.prototype.D=function(a,b){this.u.set(a,b);this.s.set(b.constructor,b)};A.prototype.c=function(a){return this.u.get(a)};A.prototype.C=function(a){return this.s.get(a)};
A.prototype.v=function(a){this.h=!0;this.j.push(a)};A.prototype.l=function(a){var b=this;this.h&&M(a,function(a){return b.g(a)})};A.prototype.g=function(a){if(this.h&&!a.__CE_patched){a.__CE_patched=!0;for(var b=0;b<this.j.length;b++)this.j[b](a)}};A.prototype.b=function(a){var b=[];M(a,function(a){return b.push(a)});for(a=0;a<b.length;a++){var c=b[a];1===c.__CE_state?this.connectedCallback(c):this.i(c)}};A.prototype.a=function(a){var b=[];M(a,function(a){return b.push(a)});for(a=0;a<b.length;a++){var c=
b[a];1===c.__CE_state&&this.disconnectedCallback(c)}};A.prototype.f=function(a,b){var c=this;b=b?b:{};var d=b.Ab||new Set,e=b.Oa||function(a){return c.i(a)},f=[];M(a,function(a){if("link"===a.localName&&"import"===a.getAttribute("rel")){var b=a.import;b instanceof Node&&"complete"===b.readyState?(b.__CE_isImportDocument=!0,b.__CE_hasRegistry=!0):a.addEventListener("load",function(){var b=a.import;b.__CE_documentLoadHandled||(b.__CE_documentLoadHandled=!0,b.__CE_isImportDocument=!0,b.__CE_hasRegistry=
!0,d.delete(b),c.f(b,{Ab:d,Oa:e}))})}else f.push(a)},d);if(this.h)for(a=0;a<f.length;a++)this.g(f[a]);for(a=0;a<f.length;a++)e(f[a])};A.prototype.i=function(a){if(void 0===a.__CE_state){var b=this.c(a.localName);if(b){b.constructionStack.push(a);var c=b.constructor;try{try{if(new c!==a)throw Error("The custom element constructor did not produce the element being upgraded.");}finally{b.constructionStack.pop()}}catch(f){throw a.__CE_state=2,f;}a.__CE_state=1;a.__CE_definition=b;if(b.attributeChangedCallback)for(b=
b.observedAttributes,c=0;c<b.length;c++){var d=b[c],e=a.getAttribute(d);null!==e&&this.attributeChangedCallback(a,d,null,e,null)}n(a)&&this.connectedCallback(a)}}};A.prototype.connectedCallback=function(a){var b=a.__CE_definition;b.connectedCallback&&b.connectedCallback.call(a)};A.prototype.disconnectedCallback=function(a){var b=a.__CE_definition;b.disconnectedCallback&&b.disconnectedCallback.call(a)};A.prototype.attributeChangedCallback=function(a,b,c,d,e){var f=a.__CE_definition;f.attributeChangedCallback&&
-1<f.observedAttributes.indexOf(b)&&f.attributeChangedCallback.call(a,b,c,d,e)};Ga.prototype.c=function(){this.N&&this.N.disconnect()};Ga.prototype.f=function(a){var b=this.a.readyState;"interactive"!==b&&"complete"!==b||this.c();for(b=0;b<a.length;b++)for(var c=a[b].addedNodes,d=0;d<c.length;d++)this.b.f(c[d])};Cb.prototype.resolve=function(a){if(this.a)throw Error("Already resolved.");this.a=a;this.b&&this.b(a)};q.prototype.define=function(a,b){var c=this;if(!(b instanceof Function))throw new TypeError("Custom element constructors must be functions.");
if(!xc(a))throw new SyntaxError("The element name '"+a+"' is not valid.");if(this.a.c(a))throw Error("A custom element with name '"+a+"' has already been defined.");if(this.c)throw Error("A custom element is already being defined.");this.c=!0;try{var d=function(a){var b=e[a];if(void 0!==b&&!(b instanceof Function))throw Error("The '"+a+"' callback must be a function.");return b},e=b.prototype;if(!(e instanceof Object))throw new TypeError("The custom element constructor's prototype is not an object.");
var f=d("connectedCallback");var g=d("disconnectedCallback");var h=d("adoptedCallback");var k=d("attributeChangedCallback");var l=b.observedAttributes||[]}catch(le){return}finally{this.c=!1}b={localName:a,constructor:b,connectedCallback:f,disconnectedCallback:g,adoptedCallback:h,attributeChangedCallback:k,observedAttributes:l,constructionStack:[]};this.a.D(a,b);this.g.push(b);this.b||(this.b=!0,this.f(function(){return c.j()}))};q.prototype.j=function(){var a=this;if(!1!==this.b){this.b=!1;for(var b=
this.g,c=[],d=new Map,e=0;e<b.length;e++)d.set(b[e].localName,[]);this.a.f(document,{Oa:function(b){if(void 0===b.__CE_state){var e=b.localName,f=d.get(e);f?f.push(b):a.a.c(e)&&c.push(b)}}});for(e=0;e<c.length;e++)this.a.i(c[e]);for(;0<b.length;){var f=b.shift();e=f.localName;f=d.get(f.localName);for(var g=0;g<f.length;g++)this.a.i(f[g]);(e=this.h.get(e))&&e.resolve(void 0)}}};q.prototype.get=function(a){if(a=this.a.c(a))return a.constructor};q.prototype.whenDefined=function(a){if(!xc(a))return Promise.reject(new SyntaxError("'"+
a+"' is not a valid custom element name."));var b=this.h.get(a);if(b)return b.c;b=new Cb;this.h.set(a,b);this.a.c(a)&&!this.g.some(function(b){return b.localName===a})&&b.resolve(void 0);return b.c};q.prototype.l=function(a){this.i.c();var b=this.f;this.f=function(c){return a(function(){return b(c)})}};window.CustomElementRegistry=q;q.prototype.define=q.prototype.define;q.prototype.get=q.prototype.get;q.prototype.whenDefined=q.prototype.whenDefined;q.prototype.polyfillWrapFlushCallback=q.prototype.l;
var Ca=window.Document.prototype.createElement,kd=window.Document.prototype.createElementNS,jd=window.Document.prototype.importNode,ld=window.Document.prototype.prepend,md=window.Document.prototype.append,rb=window.Node.prototype.cloneNode,ja=window.Node.prototype.appendChild,zb=window.Node.prototype.insertBefore,Da=window.Node.prototype.removeChild,Ab=window.Node.prototype.replaceChild,Fa=Object.getOwnPropertyDescriptor(window.Node.prototype,"textContent"),qb=window.Element.prototype.attachShadow,
Aa=Object.getOwnPropertyDescriptor(window.Element.prototype,"innerHTML"),Ea=window.Element.prototype.getAttribute,sb=window.Element.prototype.setAttribute,ub=window.Element.prototype.removeAttribute,ka=window.Element.prototype.getAttributeNS,tb=window.Element.prototype.setAttributeNS,vb=window.Element.prototype.removeAttributeNS,xb=window.Element.prototype.insertAdjacentElement,ad=window.Element.prototype.prepend,bd=window.Element.prototype.append,dd=window.Element.prototype.before,ed=window.Element.prototype.after,
fd=window.Element.prototype.replaceWith,gd=window.Element.prototype.remove,od=window.HTMLElement,Ba=Object.getOwnPropertyDescriptor(window.HTMLElement.prototype,"innerHTML"),wb=window.HTMLElement.prototype.insertAdjacentElement,Bb=new function(){},ua=window.customElements;if(!ua||ua.forcePolyfill||"function"!=typeof ua.define||"function"!=typeof ua.get){var ea=new A;nd(ea);id(ea);hd(ea);$c(ea);document.__CE_hasRegistry=!0;var Xd=new q(ea);Object.defineProperty(window,"customElements",{configurable:!0,
enumerable:!0,value:Xd})}var K={STYLE_RULE:1,ia:7,MEDIA_RULE:4,va:1E3},J={nb:/\/\*[^*]*\*+([^/*][^*]*\*+)*\//gim,port:/@import[^;]*;/gim,Fa:/(?:^[^;\-\s}]+)?--[^;{}]*?:[^{};]*?(?:[;\n]|$)/gim,Ja:/(?:^[^;\-\s}]+)?--[^;{}]*?:[^{};]*?{[^}]*?}(?:[;\n]|$)?/gim,tb:/@apply\s*\(?[^);]*\)?\s*(?:[;\n]|$)?/gim,zb:/[^;:]*?:[^;]*?var\([^;]*\)(?:[;\n]|$)?/gim,sb:/^@[^\s]*keyframes/,Ka:/\s+/g},u=!(window.ShadyDOM&&window.ShadyDOM.inUse);if(window.ShadyCSS&&void 0!==window.ShadyCSS.nativeCss)var w=window.ShadyCSS.nativeCss;
else window.ShadyCSS?(Ac(window.ShadyCSS),window.ShadyCSS=void 0):Ac(window.WebComponents&&window.WebComponents.flags);var va=/(?:^|[;\s{]\s*)(--[\w-]*?)\s*:\s*(?:((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};{])+)|\{([^}]*)\}(?:(?=[;\s}])|$))/gi,wa=/(?:^|\W+)@apply\s*\(?([^);\n]*)\)?/gi,Yd=/(--[\w-]+)\s*([:,;)]|$)/gi,Zd=/(animation\s*:)|(animation-name\s*:)/,Id=/@media\s(.*)/,$d=/\{[^}]*\}/g,P=null;r.prototype.a=function(a,b,c){a.__styleScoped?a.__styleScoped=null:this.i(a,b||"",c)};r.prototype.i=
function(a,b,c){a.nodeType===Node.ELEMENT_NODE&&this.v(a,b,c);if(a="template"===a.localName?(a.content||a.Eb).childNodes:a.children||a.childNodes)for(var d=0;d<a.length;d++)this.i(a[d],b,c)};r.prototype.v=function(a,b,c){if(b)if(a.classList)c?(a.classList.remove("style-scope"),a.classList.remove(b)):(a.classList.add("style-scope"),a.classList.add(b));else if(a.getAttribute){var d=a.getAttribute(ae);c?d&&(b=d.replace("style-scope","").replace(b,""),ra(a,b)):ra(a,(d?d+" ":"")+"style-scope "+b)}};r.prototype.b=
function(a,b,c){var d=a.__cssBuild;u||"shady"===d?b=V(b,c):(a=R(a),b=this.H(b,a.is,a.Y,c)+"\n\n");return b.trim()};r.prototype.H=function(a,b,c,d){var e=this.f(b,c);b=this.h(b);var f=this;return V(a,function(a){a.c||(f.R(a,b,e),a.c=!0);d&&d(a,b,e)})};r.prototype.h=function(a){return a?be+a:""};r.prototype.f=function(a,b){return b?"[is="+a+"]":a};r.prototype.R=function(a,b,c){this.j(a,this.g,b,c)};r.prototype.j=function(a,b,c,d){a.selector=a.A=this.l(a,b,c,d)};r.prototype.l=function(a,b,c,d){var e=
a.selector.split(Pc);if(!Bc(a)){a=0;for(var f=e.length,g;a<f&&(g=e[a]);a++)e[a]=b.call(this,g,c,d)}return e.join(Pc)};r.prototype.g=function(a,b,c){var d=this,e=!1;a=a.trim();a=a.replace(ce,function(a,b,c){return":"+b+"("+c.replace(/\s/g,"")+")"});a=a.replace(de,jb+" $1");return a=a.replace(ee,function(a,g,h){e||(a=d.C(h,g,b,c),e=e||a.stop,g=a.mb,h=a.value);return g+h})};r.prototype.C=function(a,b,c,d){var e=a.indexOf(kb);0<=a.indexOf(jb)?a=this.L(a,d):0!==e&&(a=c?this.s(a,c):a);c=!1;0<=e&&(b="",
c=!0);if(c){var f=!0;c&&(a=a.replace(fe,function(a,b){return" > "+b}))}a=a.replace(ge,function(a,b,c){return'[dir="'+c+'"] '+b+", "+b+'[dir="'+c+'"]'});return{value:a,mb:b,stop:f}};r.prototype.s=function(a,b){a=a.split(Qc);a[0]+=b;return a.join(Qc)};r.prototype.L=function(a,b){var c=a.match(Rc);return(c=c&&c[2].trim()||"")?c[0].match(Sc)?a.replace(Rc,function(a,c,f){return b+f}):c.split(Sc)[0]===b?c:he:a.replace(jb,b)};r.prototype.I=function(a){a.selector=a.parsedSelector;this.u(a);this.j(a,this.D)};
r.prototype.u=function(a){a.selector===ie&&(a.selector="html")};r.prototype.D=function(a){return a.match(kb)?this.g(a,Tc):this.s(a.trim(),Tc)};nb.Object.defineProperties(r.prototype,{c:{configurable:!0,enumerable:!0,get:function(){return"style-scope"}}});var ce=/:(nth[-\w]+)\(([^)]+)\)/,Tc=":not(.style-scope)",Pc=",",ee=/(^|[\s>+~]+)((?:\[.+?\]|[^\s>+~=[])+)/g,Sc=/[[.:#*]/,jb=":host",ie=":root",kb="::slotted",de=new RegExp("^("+kb+")"),Rc=/(:host)(?:\(((?:\([^)(]*\)|[^)(]*)+?)\))/,fe=/(?:::slotted)(?:\(((?:\([^)(]*\)|[^)(]*)+?)\))/,
ge=/(.*):dir\((?:(ltr|rtl))\)/,be=".",Qc=":",ae="class",he="should_not_match",x=new r;y.get=function(a){return a?a.__styleInfo:null};y.set=function(a,b){return a.__styleInfo=b};y.prototype.c=function(){return this.G};y.prototype._getStyleRules=y.prototype.c;var Uc=function(a){return a.matches||a.matchesSelector||a.mozMatchesSelector||a.msMatchesSelector||a.oMatchesSelector||a.webkitMatchesSelector}(window.Element.prototype),je=navigator.userAgent.match("Trident");p.prototype.R=function(a){var b=this,
c={},d=[],e=0;W(a,function(a){b.c(a);a.index=e++;b.I(a.w.cssText,c)},function(a){d.push(a)});a.b=d;a=[];for(var f in c)a.push(f);return a};p.prototype.c=function(a){if(!a.w){var b={},c={};this.b(a,c)&&(b.F=c,a.rules=null);b.cssText=this.H(a);a.w=b}};p.prototype.b=function(a,b){var c=a.w;if(c){if(c.F)return Object.assign(b,c.F),!0}else{c=a.parsedCssText;for(var d;a=va.exec(c);){d=(a[2]||a[3]).trim();if("inherit"!==d||"unset"!==d)b[a[1].trim()]=d;d=!0}return d}};p.prototype.H=function(a){return this.L(a.parsedCssText)};
p.prototype.L=function(a){return a.replace($d,"").replace(va,"")};p.prototype.I=function(a,b){for(var c;c=Yd.exec(a);){var d=c[1];":"!==c[2]&&(b[d]=!0)}};p.prototype.fa=function(a){for(var b=Object.getOwnPropertyNames(a),c=0,d;c<b.length;c++)d=b[c],a[d]=this.a(a[d],a)};p.prototype.a=function(a,b){if(a)if(0<=a.indexOf(";"))a=this.f(a,b);else{var c=this;a=Dc(a,function(a,e,f,g){if(!e)return a+g;(e=c.a(b[e],b))&&"initial"!==e?"apply-shim-inherit"===e&&(e="inherit"):e=c.a(b[f]||f,b)||f;return a+(e||"")+
g})}return a&&a.trim()||""};p.prototype.f=function(a,b){a=a.split(";");for(var c=0,d,e;c<a.length;c++)if(d=a[c]){wa.lastIndex=0;if(e=wa.exec(d))d=this.a(b[e[1]],b);else if(e=d.indexOf(":"),-1!==e){var f=d.substring(e);f=f.trim();f=this.a(f,b)||f;d=d.substring(0,e)+f}a[c]=d&&d.lastIndexOf(";")===d.length-1?d.slice(0,-1):d||""}return a.join(";")};p.prototype.D=function(a,b){var c="";a.w||this.c(a);a.w.cssText&&(c=this.f(a.w.cssText,b));a.cssText=c};p.prototype.C=function(a,b){var c=a.cssText,d=a.cssText;
null==a.Ha&&(a.Ha=Zd.test(c));if(a.Ha)if(null==a.ca){a.ca=[];for(var e in b)d=b[e],d=d(c),c!==d&&(c=d,a.ca.push(e))}else{for(e=0;e<a.ca.length;++e)d=b[a.ca[e]],c=d(c);d=c}a.cssText=d};p.prototype.ea=function(a,b){var c={},d=this,e=[];W(a,function(a){a.w||d.c(a);var f=a.A||a.parsedSelector;b&&a.w.F&&f&&Uc.call(b,f)&&(d.b(a,c),a=a.index,f=parseInt(a/32,10),e[f]=(e[f]||0)|1<<a%32)},null,!0);return{F:c,key:e}};p.prototype.ha=function(a,b,c,d){b.w||this.c(b);if(b.w.F){var e=R(a);a=e.is;e=e.Y;e=a?x.f(a,
e):"html";var f=b.parsedSelector,g=":host > *"===f||"html"===f,h=0===f.indexOf(":host")&&!g;"shady"===c&&(g=f===e+" > *."+e||-1!==f.indexOf("html"),h=!g&&0===f.indexOf(e));"shadow"===c&&(g=":host > *"===f||"html"===f,h=h&&!g);if(g||h)c=e,h&&(u&&!b.A&&(b.A=x.l(b,x.g,x.h(a),e)),c=b.A||e),d({yb:c,rb:h,Ib:g})}};p.prototype.da=function(a,b){var c={},d={},e=this,f=b&&b.__cssBuild;W(b,function(b){e.ha(a,b,f,function(f){Uc.call(a.Fb||a,f.yb)&&(f.rb?e.b(b,c):e.b(b,d))})},null,!0);return{wb:d,qb:c}};p.prototype.ga=
function(a,b,c){var d=this,e=R(a),f=x.f(e.is,e.Y),g=new RegExp("(?:^|[^.#[:])"+(a.extends?"\\"+f.slice(0,-1)+"\\]":f)+"($|[.:[\\s>+~])");e=y.get(a).G;var h=this.h(e,c);return x.b(a,e,function(a){d.D(a,b);u||Bc(a)||!a.cssText||(d.C(a,h),d.l(a,g,f,c))})};p.prototype.h=function(a,b){a=a.b;var c={};if(!u&&a)for(var d=0,e=a[d];d<a.length;e=a[++d])this.j(e,b),c[e.keyframesName]=this.i(e);return c};p.prototype.i=function(a){return function(b){return b.replace(a.f,a.a)}};p.prototype.j=function(a,b){a.f=new RegExp(a.keyframesName,
"g");a.a=a.keyframesName+"-"+b;a.A=a.A||a.selector;a.selector=a.A.replace(a.keyframesName,a.a)};p.prototype.l=function(a,b,c,d){a.A=a.A||a.selector;d="."+d;for(var e=a.A.split(","),f=0,g=e.length,h;f<g&&(h=e[f]);f++)e[f]=h.match(b)?h.replace(c,d):d+" "+h;a.selector=e.join(",")};p.prototype.u=function(a,b,c){var d=a.getAttribute("class")||"",e=d;c&&(e=d.replace(new RegExp("\\s*x-scope\\s*"+c+"\\s*","g")," "));e+=(e?" ":"")+"x-scope "+b;d!==e&&ra(a,e)};p.prototype.v=function(a,b,c,d){b=d?d.textContent||
"":this.ga(a,b,c);var e=y.get(a),f=e.a;f&&!u&&f!==d&&(f._useCount--,0>=f._useCount&&f.parentNode&&f.parentNode.removeChild(f));u?e.a?(e.a.textContent=b,d=e.a):b&&(d=bb(b,c,a.shadowRoot,e.b)):d?d.parentNode||(je&&-1<b.indexOf("@media")&&(d.textContent=b),Cc(d,null,e.b)):b&&(d=bb(b,c,null,e.b));d&&(d._useCount=d._useCount||0,e.a!=d&&d._useCount++,e.a=d);return d};p.prototype.s=function(a,b){var c=qa(a),d=this;a.textContent=V(c,function(a){var c=a.cssText=a.parsedCssText;a.w&&a.w.cssText&&(c=c.replace(J.Fa,
"").replace(J.Ja,""),a.cssText=d.f(c,b))})};nb.Object.defineProperties(p.prototype,{g:{configurable:!0,enumerable:!0,get:function(){return"x-scope"}}});var H=new p,lb={},xa=window.customElements;if(xa&&!u){var ke=xa.define;xa.define=function(a,b,c){var d=document.createComment(" Shady DOM styles for "+a+" "),e=document.head;e.insertBefore(d,(P?P.nextSibling:null)||e.firstChild);P=d;lb[a]=d;return ke.call(xa,a,b,c)}}ha.prototype.a=function(a,b,c){for(var d=0;d<c.length;d++){var e=c[d];if(a.F[e]!==
b[e])return!1}return!0};ha.prototype.b=function(a,b,c,d){var e=this.cache[a]||[];e.push({F:b,styleElement:c,B:d});e.length>this.c&&e.shift();this.cache[a]=e};ha.prototype.fetch=function(a,b,c){if(a=this.cache[a])for(var d=a.length-1;0<=d;d--){var e=a[d];if(this.a(e,b,c))return e}};if(!u){var Vc=new MutationObserver(Ec),Wc=function(a){Vc.observe(a,{childList:!0,subtree:!0})};if(window.customElements&&!window.customElements.polyfillWrapFlushCallback)Wc(document);else{var mb=function(){Wc(document.body)};
window.HTMLImports?window.HTMLImports.whenReady(mb):requestAnimationFrame(function(){if("loading"===document.readyState){var a=function(){mb();document.removeEventListener("readystatechange",a)};document.addEventListener("readystatechange",a)}else mb()})}pb=function(){Ec(Vc.takeRecords())}}var sa={},Ld=Promise.resolve(),cb=null,Gc=window.HTMLImports&&window.HTMLImports.whenReady||null,db,ya=null,fa=null;F.prototype.Ga=function(){!this.enqueued&&fa&&(this.enqueued=!0,ob(fa))};F.prototype.b=function(a){a.__seenByShadyCSS||
(a.__seenByShadyCSS=!0,this.customStyles.push(a),this.Ga())};F.prototype.a=function(a){return a.__shadyCSSCachedStyle?a.__shadyCSSCachedStyle:a.getStyle?a.getStyle():a};F.prototype.c=function(){for(var a=this.customStyles,b=0;b<a.length;b++){var c=a[b];if(!c.__shadyCSSCachedStyle){var d=this.a(c);d&&(d=d.__appliedElement||d,ya&&ya(d),c.__shadyCSSCachedStyle=d)}}return a};F.prototype.addCustomStyle=F.prototype.b;F.prototype.getStyleForCustomStyle=F.prototype.a;F.prototype.processStyles=F.prototype.c;
Object.defineProperties(F.prototype,{transformCallback:{get:function(){return ya},set:function(a){ya=a}},validateCallback:{get:function(){return fa},set:function(a){var b=!1;fa||(b=!0);fa=a;b&&this.Ga()}}});var Xc=new ha;k.prototype.C=function(){pb()};k.prototype.da=function(a){var b=this.s[a]=(this.s[a]||0)+1;return a+"-"+b};k.prototype.Sa=function(a){return qa(a)};k.prototype.Ua=function(a){return V(a)};k.prototype.R=function(a){a=a.content.querySelectorAll("style");for(var b=[],c=0;c<a.length;c++){var d=
a[c];b.push(d.textContent);d.parentNode.removeChild(d)}return b.join("").trim()};k.prototype.fa=function(a){return(a=a.content.querySelector("style"))?a.getAttribute("css-build")||"":""};k.prototype.prepareTemplate=function(a,b,c){if(!a.f){a.f=!0;a.name=b;a.extends=c;sa[b]=a;var d=this.fa(a),e=this.R(a);c={is:b,extends:c,Cb:d};u||x.a(a.content,b);this.c();var f=wa.test(e)||va.test(e);wa.lastIndex=0;va.lastIndex=0;e=ab(e);f&&w&&this.a&&this.a.transformRules(e,b);a._styleAst=e;a.g=d;d=[];w||(d=H.R(a._styleAst));
if(!d.length||w)b=this.ea(c,a._styleAst,u?a.content:null,lb[b]),a.a=b;a.c=d}};k.prototype.ea=function(a,b,c,d){b=x.b(a,b);if(b.length)return bb(b,a.is,c,d)};k.prototype.ha=function(a){var b=R(a),c=b.is;b=b.Y;var d=lb[c];c=sa[c];if(c){var e=c._styleAst;var f=c.c}return y.set(a,new y(e,d,f,0,b))};k.prototype.H=function(){!this.a&&window.ShadyCSS&&window.ShadyCSS.ApplyShim&&(this.a=window.ShadyCSS.ApplyShim,this.a.invalidCallback=Jd)};k.prototype.I=function(){var a=this;!this.b&&window.ShadyCSS&&window.ShadyCSS.CustomStyleInterface&&
(this.b=window.ShadyCSS.CustomStyleInterface,this.b.transformCallback=function(b){a.v(b)},this.b.validateCallback=function(){requestAnimationFrame(function(){(a.b.enqueued||a.i)&&a.f()})})};k.prototype.c=function(){this.H();this.I()};k.prototype.f=function(){this.c();if(this.b){var a=this.b.processStyles();this.b.enqueued&&(w?this.Qa(a):(this.u(this.g,this.h),this.D(a)),this.b.enqueued=!1,this.i&&!w&&this.styleDocument())}};k.prototype.styleElement=function(a,b){var c=R(a).is,d=y.get(a);d||(d=this.ha(a));
this.j(a)||(this.i=!0);b&&(d.P=d.P||{},Object.assign(d.P,b));if(w){if(d.P){b=d.P;for(var e in b)null===e?a.style.removeProperty(e):a.style.setProperty(e,b[e])}if(((e=sa[c])||this.j(a))&&e&&e.a&&!Fc(e)){if(Fc(e)||e._applyShimValidatingVersion!==e._applyShimNextVersion)this.c(),this.a&&this.a.transformRules(e._styleAst,c),e.a.textContent=x.b(a,d.G),Kd(e);u&&(c=a.shadowRoot)&&(c.querySelector("style").textContent=x.b(a,d.G));d.G=e._styleAst}}else this.u(a,d),d.sa&&d.sa.length&&this.L(a,d)};k.prototype.l=
function(a){return(a=a.getRootNode().host)?y.get(a)?a:this.l(a):this.g};k.prototype.j=function(a){return a===this.g};k.prototype.L=function(a,b){var c=R(a).is,d=Xc.fetch(c,b.K,b.sa),e=d?d.styleElement:null,f=b.B;b.B=d&&d.B||this.da(c);e=H.v(a,b.K,b.B,e);u||H.u(a,b.B,f);d||Xc.b(c,b.K,e,b.B)};k.prototype.u=function(a,b){var c=this.l(a),d=y.get(c);c=Object.create(d.K||null);var e=H.da(a,b.G);a=H.ea(d.G,a).F;Object.assign(c,e.qb,a,e.wb);this.ga(c,b.P);H.fa(c);b.K=c};k.prototype.ga=function(a,b){for(var c in b){var d=
b[c];if(d||0===d)a[c]=d}};k.prototype.styleDocument=function(a){this.styleSubtree(this.g,a)};k.prototype.styleSubtree=function(a,b){var c=a.shadowRoot;(c||this.j(a))&&this.styleElement(a,b);if(b=c&&(c.children||c.childNodes))for(a=0;a<b.length;a++)this.styleSubtree(b[a]);else if(a=a.children||a.childNodes)for(b=0;b<a.length;b++)this.styleSubtree(a[b])};k.prototype.Qa=function(a){for(var b=0;b<a.length;b++){var c=this.b.getStyleForCustomStyle(a[b]);c&&this.Pa(c)}};k.prototype.D=function(a){for(var b=
0;b<a.length;b++){var c=this.b.getStyleForCustomStyle(a[b]);c&&H.s(c,this.h.K)}};k.prototype.v=function(a){var b=this,c=qa(a);W(c,function(a){u?x.u(a):x.I(a);w&&(b.c(),b.a&&b.a.transformRule(a))});w?a.textContent=V(c):this.h.G.rules.push(c)};k.prototype.Pa=function(a){if(w&&this.a){var b=qa(a);this.c();this.a.transformRules(b);a.textContent=V(b)}};k.prototype.getComputedStyleValue=function(a,b){var c;w||(c=(y.get(a)||y.get(this.l(a))).K[b]);return(c=c||window.getComputedStyle(a).getPropertyValue(b))?
c.trim():""};k.prototype.Ta=function(a,b){var c=a.getRootNode();b=b?b.split(/\s/):[];c=c.host&&c.host.localName;if(!c){var d=a.getAttribute("class");if(d){d=d.split(/\s/);for(var e=0;e<d.length;e++)if(d[e]===x.c){c=d[e+1];break}}}c&&b.push(x.c,c);w||(c=y.get(a))&&c.B&&b.push(H.g,c.B);ra(a,b.join(" "))};k.prototype.Ra=function(a){return y.get(a)};k.prototype.flush=k.prototype.C;k.prototype.prepareTemplate=k.prototype.prepareTemplate;k.prototype.styleElement=k.prototype.styleElement;k.prototype.styleDocument=
k.prototype.styleDocument;k.prototype.styleSubtree=k.prototype.styleSubtree;k.prototype.getComputedStyleValue=k.prototype.getComputedStyleValue;k.prototype.setElementClass=k.prototype.Ta;k.prototype._styleInfoForNode=k.prototype.Ra;k.prototype.transformCustomStyleForDocument=k.prototype.v;k.prototype.getStyleAst=k.prototype.Sa;k.prototype.styleAstToString=k.prototype.Ua;k.prototype.flushCustomStyles=k.prototype.f;Object.defineProperties(k.prototype,{nativeShadow:{get:function(){return u}},nativeCss:{get:function(){return w}}});
var N=new k;if(window.ShadyCSS){var Yc=window.ShadyCSS.ApplyShim;var Zc=window.ShadyCSS.CustomStyleInterface}window.ShadyCSS={ScopingShim:N,prepareTemplate:function(a,b,c){N.f();N.prepareTemplate(a,b,c)},styleSubtree:function(a,b){N.f();N.styleSubtree(a,b)},styleElement:function(a){N.f();N.styleElement(a)},styleDocument:function(a){N.f();N.styleDocument(a)},getComputedStyleValue:function(a,b){return N.getComputedStyleValue(a,b)},nativeCss:w,nativeShadow:u};Yc&&(window.ShadyCSS.ApplyShim=Yc);Zc&&(window.ShadyCSS.CustomStyleInterface=
Zc);(function(){var a=window.customElements,b=window.HTMLImports;window.WebComponents=window.WebComponents||{};if(a&&a.polyfillWrapFlushCallback){var c,d=function(){if(c){var a=c;c=null;a();return!0}},e=b.whenReady;a.polyfillWrapFlushCallback(function(a){c=a;e(d)});b.whenReady=function(a){e(function(){d()?b.whenReady(a):a()})}}b.whenReady(function(){requestAnimationFrame(function(){window.WebComponents.ready=!0;document.dispatchEvent(new CustomEvent("WebComponentsReady",{bubbles:!0}))})})})();(function(){var a=
document.createElement("style");a.textContent="body {transition: opacity ease-in 0.2s; } \nbody[unresolved] {opacity: 0; display: block; overflow: hidden; position: relative; } \n";var b=document.querySelector("head");b.insertBefore(a,b.firstChild)})()})();}).call(this);
//# sourceMappingURL=webcomponents-lite.js.map
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.scrollDir = factory());
}(this, (function () { 'use strict';
var defaults = {
el: document.documentElement,
win: window,
attribute: 'data-scrolldir'
};
var el = void 0;
var win = void 0;
var attribute = void 0;
var body = document.body;
var historyLength = 32; // Ticks to keep in history.
var historyMaxAge = 512; // History data time-to-live (ms).
var thresholdPixels = 64; // Ignore moves smaller than this.
var history = Array(historyLength);
var dir = 'down'; // 'up' or 'down'
var e = void 0; // last scroll event
var pivot = void 0; // "high-water mark"
var pivotTime = 0;
function tick() {
var y = win.scrollY || win.pageYOffset;
var t = e.timeStamp;
var furthest = dir === 'down' ? Math.max : Math.min;
// Apply bounds to handle rubber banding
var yMax = body.offsetHeight - win.innerHeight;
y = Math.max(0, y);
y = Math.min(yMax, y);
// Update history
history.unshift({ y: y, t: t });
history.pop();
// Are we continuing in the same direction?
if (y === furthest(pivot, y)) {
// Update "high-water mark" for current direction
pivotTime = t;
pivot = y;
return;
}
// else we have backed off high-water mark
// Apply max age to find current reference point
var cutoffTime = t - historyMaxAge;
if (cutoffTime > pivotTime) {
pivot = y;
for (var i = 0; i < historyLength; i += 1) {
if (!history[i] || history[i].t < cutoffTime) break;
pivot = furthest(pivot, history[i].y);
}
}
// Have we exceeded threshold?
if (Math.abs(y - pivot) > thresholdPixels) {
pivot = y;
pivotTime = t;
dir = dir === 'down' ? 'up' : 'down';
el.setAttribute(attribute, dir);
}
}
function handler(event) {
e = event;
return win.requestAnimationFrame(tick);
}
function scrollDir(opts) {
el = opts && opts.el || defaults.el;
win = opts && opts.win || defaults.win;
attribute = opts && opts.attribute || defaults.attribute;
// If opts.off, turn it off
// - set html[data-scrolldir="off"]
// - remove the event listener
if (opts && opts.off === true) {
el.setAttribute(attribute, 'off');
return win.removeEventListener('scroll', handler);
}
// else, turn it on
// - set html[data-scrolldir="down"]
// - add the event listener
pivot = win.scrollY || win.pageYOffset;
el.setAttribute(attribute, dir);
return win.addEventListener('scroll', handler);
}
return scrollDir;
})));
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Cleave"] = factory();
else
root["Cleave"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {'use strict';
/**
* Construct a new Cleave instance by passing the configuration object
*
* @param {String / HTMLElement} element
* @param {Object} opts
*/
var Cleave = function (element, opts) {
var owner = this;
if (typeof element === 'string') {
owner.element = document.querySelector(element);
} else {
owner.element = ((typeof element.length !== 'undefined') && element.length > 0) ? element[0] : element;
}
if (!owner.element) {
throw new Error('[cleave.js] Please check the element');
}
opts.initValue = owner.element.value;
owner.properties = Cleave.DefaultProperties.assign({}, opts);
owner.init();
};
Cleave.prototype = {
init: function () {
var owner = this, pps = owner.properties;
// no need to use this lib
if (!pps.numeral && !pps.phone && !pps.creditCard && !pps.date && (pps.blocksLength === 0 && !pps.prefix)) {
return;
}
pps.maxLength = Cleave.Util.getMaxLength(pps.blocks);
owner.isAndroid = Cleave.Util.isAndroid();
owner.lastInputValue = '';
owner.onChangeListener = owner.onChange.bind(owner);
owner.onKeyDownListener = owner.onKeyDown.bind(owner);
owner.onCutListener = owner.onCut.bind(owner);
owner.onCopyListener = owner.onCopy.bind(owner);
owner.element.addEventListener('input', owner.onChangeListener);
owner.element.addEventListener('keydown', owner.onKeyDownListener);
owner.element.addEventListener('cut', owner.onCutListener);
owner.element.addEventListener('copy', owner.onCopyListener);
owner.initPhoneFormatter();
owner.initDateFormatter();
owner.initNumeralFormatter();
owner.onInput(pps.initValue);
},
initNumeralFormatter: function () {
var owner = this, pps = owner.properties;
if (!pps.numeral) {
return;
}
pps.numeralFormatter = new Cleave.NumeralFormatter(
pps.numeralDecimalMark,
pps.numeralIntegerScale,
pps.numeralDecimalScale,
pps.numeralThousandsGroupStyle,
pps.numeralPositiveOnly,
pps.delimiter
);
},
initDateFormatter: function () {
var owner = this, pps = owner.properties;
if (!pps.date) {
return;
}
pps.dateFormatter = new Cleave.DateFormatter(pps.datePattern);
pps.blocks = pps.dateFormatter.getBlocks();
pps.blocksLength = pps.blocks.length;
pps.maxLength = Cleave.Util.getMaxLength(pps.blocks);
},
initPhoneFormatter: function () {
var owner = this, pps = owner.properties;
if (!pps.phone) {
return;
}
// Cleave.AsYouTypeFormatter should be provided by
// external google closure lib
try {
pps.phoneFormatter = new Cleave.PhoneFormatter(
new pps.root.Cleave.AsYouTypeFormatter(pps.phoneRegionCode),
pps.delimiter
);
} catch (ex) {
throw new Error('[cleave.js] Please include phone-type-formatter.{country}.js lib');
}
},
onKeyDown: function (event) {
var owner = this, pps = owner.properties,
charCode = event.which || event.keyCode,
Util = Cleave.Util,
currentValue = owner.element.value;
if (Util.isAndroidBackspaceKeydown(owner.lastInputValue, currentValue)) {
charCode = 8;
}
owner.lastInputValue = currentValue;
// hit backspace when last character is delimiter
if (charCode === 8 && Util.isDelimiter(currentValue.slice(-pps.delimiterLength), pps.delimiter, pps.delimiters)) {
pps.backspace = true;
return;
}
pps.backspace = false;
},
onChange: function () {
this.onInput(this.element.value);
},
onCut: function (e) {
this.copyClipboardData(e);
this.onInput('');
},
onCopy: function (e) {
this.copyClipboardData(e);
},
copyClipboardData: function (e) {
var owner = this,
pps = owner.properties,
Util = Cleave.Util,
inputValue = owner.element.value,
textToCopy = '';
if (!pps.copyDelimiter) {
textToCopy = Util.stripDelimiters(inputValue, pps.delimiter, pps.delimiters);
} else {
textToCopy = inputValue;
}
try {
if (e.clipboardData) {
e.clipboardData.setData('Text', textToCopy);
} else {
window.clipboardData.setData('Text', textToCopy);
}
e.preventDefault();
} catch (ex) {
// empty
}
},
onInput: function (value) {
var owner = this, pps = owner.properties,
prev = value,
Util = Cleave.Util;
// case 1: delete one more character "4"
// 1234*| -> hit backspace -> 123|
// case 2: last character is not delimiter which is:
// 12|34* -> hit backspace -> 1|34*
// note: no need to apply this for numeral mode
if (!pps.numeral && pps.backspace && !Util.isDelimiter(value.slice(-pps.delimiterLength), pps.delimiter, pps.delimiters)) {
value = Util.headStr(value, value.length - pps.delimiterLength);
}
// phone formatter
if (pps.phone) {
pps.result = pps.phoneFormatter.format(value);
owner.updateValueState();
return;
}
// numeral formatter
if (pps.numeral) {
pps.result = pps.prefix + pps.numeralFormatter.format(value);
owner.updateValueState();
return;
}
// date
if (pps.date) {
value = pps.dateFormatter.getValidatedDate(value);
}
// strip delimiters
value = Util.stripDelimiters(value, pps.delimiter, pps.delimiters);
// strip prefix
value = Util.getPrefixStrippedValue(value, pps.prefix, pps.prefixLength);
// strip non-numeric characters
value = pps.numericOnly ? Util.strip(value, /[^\d]/g) : value;
// convert case
value = pps.uppercase ? value.toUpperCase() : value;
value = pps.lowercase ? value.toLowerCase() : value;
// prefix
if (pps.prefix) {
value = pps.prefix + value;
// no blocks specified, no need to do formatting
if (pps.blocksLength === 0) {
pps.result = value;
owner.updateValueState();
return;
}
}
// update credit card props
if (pps.creditCard) {
owner.updateCreditCardPropsByValue(value);
}
// strip over length characters
value = Util.headStr(value, pps.maxLength);
// apply blocks
pps.result = Util.getFormattedValue(value, pps.blocks, pps.blocksLength, pps.delimiter, pps.delimiters);
// nothing changed
// prevent update value to avoid caret position change
if (prev === pps.result && prev !== pps.prefix) {
return;
}
owner.updateValueState();
},
updateCreditCardPropsByValue: function (value) {
var owner = this, pps = owner.properties,
Util = Cleave.Util,
creditCardInfo;
// At least one of the first 4 characters has changed
if (Util.headStr(pps.result, 4) === Util.headStr(value, 4)) {
return;
}
creditCardInfo = Cleave.CreditCardDetector.getInfo(value, pps.creditCardStrictMode);
pps.blocks = creditCardInfo.blocks;
pps.blocksLength = pps.blocks.length;
pps.maxLength = Util.getMaxLength(pps.blocks);
// credit card type changed
if (pps.creditCardType !== creditCardInfo.type) {
pps.creditCardType = creditCardInfo.type;
pps.onCreditCardTypeChanged.call(owner, pps.creditCardType);
}
},
updateValueState: function () {
var owner = this;
// fix Android browser type="text" input field
// cursor not jumping issue
if (owner.isAndroid) {
window.setTimeout(function () {
owner.element.value = owner.properties.result;
}, 1);
return;
}
owner.element.value = owner.properties.result;
},
setPhoneRegionCode: function (phoneRegionCode) {
var owner = this, pps = owner.properties;
pps.phoneRegionCode = phoneRegionCode;
owner.initPhoneFormatter();
owner.onChange();
},
setRawValue: function (value) {
var owner = this, pps = owner.properties;
value = value !== undefined && value !== null ? value.toString() : '';
if (pps.numeral) {
value = value.replace('.', pps.numeralDecimalMark);
}
owner.element.value = value;
owner.onInput(value);
},
getRawValue: function () {
var owner = this,
pps = owner.properties,
Util = Cleave.Util,
rawValue = owner.element.value;
if (pps.rawValueTrimPrefix) {
rawValue = Util.getPrefixStrippedValue(rawValue, pps.prefix, pps.prefixLength);
}
if (pps.numeral) {
rawValue = pps.numeralFormatter.getRawValue(rawValue);
} else {
rawValue = Util.stripDelimiters(rawValue, pps.delimiter, pps.delimiters);
}
return rawValue;
},
getFormattedValue: function () {
return this.element.value;
},
destroy: function () {
var owner = this;
owner.element.removeEventListener('input', owner.onChangeListener);
owner.element.removeEventListener('keydown', owner.onKeyDownListener);
owner.element.removeEventListener('cut', owner.onCutListener);
owner.element.removeEventListener('copy', owner.onCopyListener);
},
toString: function () {
return '[Cleave Object]';
}
};
Cleave.NumeralFormatter = __webpack_require__(1);
Cleave.DateFormatter = __webpack_require__(2);
Cleave.PhoneFormatter = __webpack_require__(3);
Cleave.CreditCardDetector = __webpack_require__(4);
Cleave.Util = __webpack_require__(5);
Cleave.DefaultProperties = __webpack_require__(6);
// for angular directive
((typeof global === 'object' && global) ? global : window)['Cleave'] = Cleave;
// CommonJS
module.exports = Cleave;
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 1 */
/***/ function(module, exports) {
'use strict';
var NumeralFormatter = function (numeralDecimalMark,
numeralIntegerScale,
numeralDecimalScale,
numeralThousandsGroupStyle,
numeralPositiveOnly,
delimiter) {
var owner = this;
owner.numeralDecimalMark = numeralDecimalMark || '.';
owner.numeralIntegerScale = numeralIntegerScale > 0 ? numeralIntegerScale : 0;
owner.numeralDecimalScale = numeralDecimalScale >= 0 ? numeralDecimalScale : 2;
owner.numeralThousandsGroupStyle = numeralThousandsGroupStyle || NumeralFormatter.groupStyle.thousand;
owner.numeralPositiveOnly = !!numeralPositiveOnly;
owner.delimiter = (delimiter || delimiter === '') ? delimiter : ',';
owner.delimiterRE = delimiter ? new RegExp('\\' + delimiter, 'g') : '';
};
NumeralFormatter.groupStyle = {
thousand: 'thousand',
lakh: 'lakh',
wan: 'wan'
};
NumeralFormatter.prototype = {
getRawValue: function (value) {
return value.replace(this.delimiterRE, '').replace(this.numeralDecimalMark, '.');
},
format: function (value) {
var owner = this, parts, partInteger, partDecimal = '';
// strip alphabet letters
value = value.replace(/[A-Za-z]/g, '')
// replace the first decimal mark with reserved placeholder
.replace(owner.numeralDecimalMark, 'M')
// strip non numeric letters except minus and "M"
// this is to ensure prefix has been stripped
.replace(/[^\dM-]/g, '')
// replace the leading minus with reserved placeholder
.replace(/^\-/, 'N')
// strip the other minus sign (if present)
.replace(/\-/g, '')
// replace the minus sign (if present)
.replace('N', owner.numeralPositiveOnly ? '' : '-')
// replace decimal mark
.replace('M', owner.numeralDecimalMark)
// strip any leading zeros
.replace(/^(-)?0+(?=\d)/, '$1');
partInteger = value;
if (value.indexOf(owner.numeralDecimalMark) >= 0) {
parts = value.split(owner.numeralDecimalMark);
partInteger = parts[0];
partDecimal = owner.numeralDecimalMark + parts[1].slice(0, owner.numeralDecimalScale);
}
if (owner.numeralIntegerScale > 0) {
partInteger = partInteger.slice(0, owner.numeralIntegerScale + (value.slice(0, 1) === '-' ? 1 : 0));
}
switch (owner.numeralThousandsGroupStyle) {
case NumeralFormatter.groupStyle.lakh:
partInteger = partInteger.replace(/(\d)(?=(\d\d)+\d$)/g, '$1' + owner.delimiter);
break;
case NumeralFormatter.groupStyle.wan:
partInteger = partInteger.replace(/(\d)(?=(\d{4})+$)/g, '$1' + owner.delimiter);
break;
default:
partInteger = partInteger.replace(/(\d)(?=(\d{3})+$)/g, '$1' + owner.delimiter);
}
return partInteger.toString() + (owner.numeralDecimalScale > 0 ? partDecimal.toString() : '');
}
};
module.exports = NumeralFormatter;
/***/ },
/* 2 */
/***/ function(module, exports) {
'use strict';
var DateFormatter = function (datePattern) {
var owner = this;
owner.blocks = [];
owner.datePattern = datePattern;
owner.initBlocks();
};
DateFormatter.prototype = {
initBlocks: function () {
var owner = this;
owner.datePattern.forEach(function (value) {
if (value === 'Y') {
owner.blocks.push(4);
} else {
owner.blocks.push(2);
}
});
},
getBlocks: function () {
return this.blocks;
},
getValidatedDate: function (value) {
var owner = this, result = '';
value = value.replace(/[^\d]/g, '');
owner.blocks.forEach(function (length, index) {
if (value.length > 0) {
var sub = value.slice(0, length),
sub0 = sub.slice(0, 1),
rest = value.slice(length);
switch (owner.datePattern[index]) {
case 'd':
if (sub === '00') {
sub = '01';
} else if (parseInt(sub0, 10) > 3) {
sub = '0' + sub0;
} else if (parseInt(sub, 10) > 31) {
sub = '31';
}
break;
case 'm':
if (sub === '00') {
sub = '01';
} else if (parseInt(sub0, 10) > 1) {
sub = '0' + sub0;
} else if (parseInt(sub, 10) > 12) {
sub = '12';
}
break;
}
result += sub;
// update remaining string
value = rest;
}
});
return this.getFixedDateString(result);
},
getFixedDateString: function (value) {
var owner = this, datePattern = owner.datePattern, date = [],
dayIndex = 0, monthIndex = 0, yearIndex = 0,
dayStartIndex = 0, monthStartIndex = 0, yearStartIndex = 0,
day, month, year;
// mm-dd || dd-mm
if (value.length === 4 && datePattern[0].toLowerCase() !== 'y' && datePattern[1].toLowerCase() !== 'y') {
dayStartIndex = datePattern[0] === 'd' ? 0 : 2;
monthStartIndex = 2 - dayStartIndex;
day = parseInt(value.slice(dayStartIndex, dayStartIndex + 2), 10);
month = parseInt(value.slice(monthStartIndex, monthStartIndex + 2), 10);
date = this.getFixedDate(day, month, 0);
}
// yyyy-mm-dd || yyyy-dd-mm || mm-dd-yyyy || dd-mm-yyyy || dd-yyyy-mm || mm-yyyy-dd
if (value.length === 8) {
datePattern.forEach(function (type, index) {
switch (type) {
case 'd':
dayIndex = index;
break;
case 'm':
monthIndex = index;
break;
default:
yearIndex = index;
break;
}
});
yearStartIndex = yearIndex * 2;
dayStartIndex = (dayIndex <= yearIndex) ? dayIndex * 2 : (dayIndex * 2 + 2);
monthStartIndex = (monthIndex <= yearIndex) ? monthIndex * 2 : (monthIndex * 2 + 2);
day = parseInt(value.slice(dayStartIndex, dayStartIndex + 2), 10);
month = parseInt(value.slice(monthStartIndex, monthStartIndex + 2), 10);
year = parseInt(value.slice(yearStartIndex, yearStartIndex + 4), 10);
date = this.getFixedDate(day, month, year);
}
return date.length === 0 ? value : datePattern.reduce(function (previous, current) {
switch (current) {
case 'd':
return previous + owner.addLeadingZero(date[0]);
case 'm':
return previous + owner.addLeadingZero(date[1]);
default:
return previous + '' + (date[2] || '');
}
}, '');
},
getFixedDate: function (day, month, year) {
day = Math.min(day, 31);
month = Math.min(month, 12);
year = parseInt((year || 0), 10);
if ((month < 7 && month % 2 === 0) || (month > 8 && month % 2 === 1)) {
day = Math.min(day, month === 2 ? (this.isLeapYear(year) ? 29 : 28) : 30);
}
return [day, month, year];
},
isLeapYear: function (year) {
return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
},
addLeadingZero: function (number) {
return (number < 10 ? '0' : '') + number;
}
};
module.exports = DateFormatter;
/***/ },
/* 3 */
/***/ function(module, exports) {
'use strict';
var PhoneFormatter = function (formatter, delimiter) {
var owner = this;
owner.delimiter = (delimiter || delimiter === '') ? delimiter : ' ';
owner.delimiterRE = delimiter ? new RegExp('\\' + delimiter, 'g') : '';
owner.formatter = formatter;
};
PhoneFormatter.prototype = {
setFormatter: function (formatter) {
this.formatter = formatter;
},
format: function (phoneNumber) {
var owner = this;
owner.formatter.clear();
// only keep number and +
phoneNumber = phoneNumber.replace(/[^\d+]/g, '');
// strip delimiter
phoneNumber = phoneNumber.replace(owner.delimiterRE, '');
var result = '', current, validated = false;
for (var i = 0, iMax = phoneNumber.length; i < iMax; i++) {
current = owner.formatter.inputDigit(phoneNumber.charAt(i));
// has ()- or space inside
if (/[\s()-]/g.test(current)) {
result = current;
validated = true;
} else {
if (!validated) {
result = current;
}
// else: over length input
// it turns to invalid number again
}
}
// strip ()
// e.g. US: 7161234567 returns (716) 123-4567
result = result.replace(/[()]/g, '');
// replace library delimiter with user customized delimiter
result = result.replace(/[\s-]/g, owner.delimiter);
return result;
}
};
module.exports = PhoneFormatter;
/***/ },
/* 4 */
/***/ function(module, exports) {
'use strict';
var CreditCardDetector = {
blocks: {
uatp: [4, 5, 6],
amex: [4, 6, 5],
diners: [4, 6, 4],
discover: [4, 4, 4, 4],
mastercard: [4, 4, 4, 4],
dankort: [4, 4, 4, 4],
instapayment: [4, 4, 4, 4],
jcb: [4, 4, 4, 4],
maestro: [4, 4, 4, 4],
visa: [4, 4, 4, 4],
general: [4, 4, 4, 4],
generalStrict: [4, 4, 4, 7]
},
re: {
// starts with 1; 15 digits, not starts with 1800 (jcb card)
uatp: /^(?!1800)1\d{0,14}/,
// starts with 34/37; 15 digits
amex: /^3[47]\d{0,13}/,
// starts with 6011/65/644-649; 16 digits
discover: /^(?:6011|65\d{0,2}|64[4-9]\d?)\d{0,12}/,
// starts with 300-305/309 or 36/38/39; 14 digits
diners: /^3(?:0([0-5]|9)|[689]\d?)\d{0,11}/,
// starts with 51-55/22-27; 16 digits
mastercard: /^(5[1-5]|2[2-7])\d{0,14}/,
// starts with 5019/4175/4571; 16 digits
dankort: /^(5019|4175|4571)\d{0,12}/,
// starts with 637-639; 16 digits
instapayment: /^63[7-9]\d{0,13}/,
// starts with 2131/1800/35; 16 digits
jcb: /^(?:2131|1800|35\d{0,2})\d{0,12}/,
// starts with 50/56-58/6304/67; 16 digits
maestro: /^(?:5[0678]\d{0,2}|6304|67\d{0,2})\d{0,12}/,
// starts with 4; 16 digits
visa: /^4\d{0,15}/
},
getInfo: function (value, strictMode) {
var blocks = CreditCardDetector.blocks,
re = CreditCardDetector.re;
// In theory, visa credit card can have up to 19 digits number.
// Set strictMode to true will remove the 16 max-length restrain,
// however, I never found any website validate card number like
// this, hence probably you don't need to enable this option.
strictMode = !!strictMode;
if (re.amex.test(value)) {
return {
type: 'amex',
blocks: blocks.amex
};
} else if (re.uatp.test(value)) {
return {
type: 'uatp',
blocks: blocks.uatp
};
} else if (re.diners.test(value)) {
return {
type: 'diners',
blocks: blocks.diners
};
} else if (re.discover.test(value)) {
return {
type: 'discover',
blocks: strictMode ? blocks.generalStrict : blocks.discover
};
} else if (re.mastercard.test(value)) {
return {
type: 'mastercard',
blocks: blocks.mastercard
};
} else if (re.dankort.test(value)) {
return {
type: 'dankort',
blocks: blocks.dankort
};
} else if (re.instapayment.test(value)) {
return {
type: 'instapayment',
blocks: blocks.instapayment
};
} else if (re.jcb.test(value)) {
return {
type: 'jcb',
blocks: blocks.jcb
};
} else if (re.maestro.test(value)) {
return {
type: 'maestro',
blocks: strictMode ? blocks.generalStrict : blocks.maestro
};
} else if (re.visa.test(value)) {
return {
type: 'visa',
blocks: strictMode ? blocks.generalStrict : blocks.visa
};
} else {
return {
type: 'unknown',
blocks: strictMode ? blocks.generalStrict : blocks.general
};
}
}
};
module.exports = CreditCardDetector;
/***/ },
/* 5 */
/***/ function(module, exports) {
'use strict';
var Util = {
noop: function () {
},
strip: function (value, re) {
return value.replace(re, '');
},
isDelimiter: function (letter, delimiter, delimiters) {
// single delimiter
if (delimiters.length === 0) {
return letter === delimiter;
}
// multiple delimiters
return delimiters.some(function (current) {
if (letter === current) {
return true;
}
});
},
getDelimiterREByDelimiter: function (delimiter) {
return new RegExp(delimiter.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'), 'g');
},
stripDelimiters: function (value, delimiter, delimiters) {
var owner = this;
// single delimiter
if (delimiters.length === 0) {
var delimiterRE = delimiter ? owner.getDelimiterREByDelimiter(delimiter) : '';
return value.replace(delimiterRE, '');
}
// multiple delimiters
delimiters.forEach(function (current) {
value = value.replace(owner.getDelimiterREByDelimiter(current), '');
});
return value;
},
headStr: function (str, length) {
return str.slice(0, length);
},
getMaxLength: function (blocks) {
return blocks.reduce(function (previous, current) {
return previous + current;
}, 0);
},
// strip value by prefix length
// for prefix: PRE
// (PRE123, 3) -> 123
// (PR123, 3) -> 23 this happens when user hits backspace in front of "PRE"
getPrefixStrippedValue: function (value, prefix, prefixLength) {
if (value.slice(0, prefixLength) !== prefix) {
var diffIndex = this.getFirstDiffIndex(prefix, value.slice(0, prefixLength));
value = prefix + value.slice(diffIndex, diffIndex + 1) + value.slice(prefixLength + 1);
}
return value.slice(prefixLength);
},
getFirstDiffIndex: function (prev, current) {
var index = 0;
while (prev.charAt(index) === current.charAt(index))
if (prev.charAt(index++) === '')
return -1;
return index;
},
getFormattedValue: function (value, blocks, blocksLength, delimiter, delimiters) {
var result = '',
multipleDelimiters = delimiters.length > 0,
currentDelimiter;
// no options, normal input
if (blocksLength === 0) {
return value;
}
blocks.forEach(function (length, index) {
if (value.length > 0) {
var sub = value.slice(0, length),
rest = value.slice(length);
result += sub;
currentDelimiter = multipleDelimiters ? (delimiters[index] || currentDelimiter) : delimiter;
if (sub.length === length && index < blocksLength - 1) {
result += currentDelimiter;
}
// update remaining string
value = rest;
}
});
return result;
},
isAndroid: function () {
if (navigator && /android/i.test(navigator.userAgent)) {
return true;
}
return false;
},
// On Android chrome, the keyup and keydown events
// always return key code 229 as a composition that
// buffers the user’s keystrokes
// see https://github.com/nosir/cleave.js/issues/147
isAndroidBackspaceKeydown: function (lastInputValue, currentInputValue) {
if (!this.isAndroid()) {
return false;
}
return currentInputValue === lastInputValue.slice(0, -1);
}
};
module.exports = Util;
/***/ },
/* 6 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(function(global) {'use strict';
/**
* Props Assignment
*
* Separate this, so react module can share the usage
*/
var DefaultProperties = {
// Maybe change to object-assign
// for now just keep it as simple
assign: function (target, opts) {
target = target || {};
opts = opts || {};
// credit card
target.creditCard = !!opts.creditCard;
target.creditCardStrictMode = !!opts.creditCardStrictMode;
target.creditCardType = '';
target.onCreditCardTypeChanged = opts.onCreditCardTypeChanged || (function () {});
// phone
target.phone = !!opts.phone;
target.phoneRegionCode = opts.phoneRegionCode || 'AU';
target.phoneFormatter = {};
// date
target.date = !!opts.date;
target.datePattern = opts.datePattern || ['d', 'm', 'Y'];
target.dateFormatter = {};
// numeral
target.numeral = !!opts.numeral;
target.numeralIntegerScale = opts.numeralIntegerScale > 0 ? opts.numeralIntegerScale : 0;
target.numeralDecimalScale = opts.numeralDecimalScale >= 0 ? opts.numeralDecimalScale : 2;
target.numeralDecimalMark = opts.numeralDecimalMark || '.';
target.numeralThousandsGroupStyle = opts.numeralThousandsGroupStyle || 'thousand';
target.numeralPositiveOnly = !!opts.numeralPositiveOnly;
// others
target.numericOnly = target.creditCard || target.date || !!opts.numericOnly;
target.uppercase = !!opts.uppercase;
target.lowercase = !!opts.lowercase;
target.prefix = (target.creditCard || target.phone || target.date) ? '' : (opts.prefix || '');
target.prefixLength = target.prefix.length;
target.rawValueTrimPrefix = !!opts.rawValueTrimPrefix;
target.copyDelimiter = !!opts.copyDelimiter;
target.initValue = (opts.initValue !== undefined && opts.initValue !== null) ? opts.initValue.toString() : '';
target.delimiter =
(opts.delimiter || opts.delimiter === '') ? opts.delimiter :
(opts.date ? '/' :
(opts.numeral ? ',' :
(opts.phone ? ' ' :
' ')));
target.delimiterLength = target.delimiter.length;
target.delimiters = opts.delimiters || [];
target.blocks = opts.blocks || [];
target.blocksLength = target.blocks.length;
target.root = (typeof global === 'object' && global) ? global : window;
target.maxLength = 0;
target.backspace = false;
target.result = '';
return target;
}
};
module.exports = DefaultProperties;
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ }
/******/ ])
});
;
angular.module('cleave.js', [])
.directive('cleave', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
cleave: '&',
onValueChange: '&?'
},
compile: function () {
return {
pre: function ($scope, $element, attrs, ngModelCtrl) {
$scope.cleave = new window.Cleave($element[0], $scope.cleave());
ngModelCtrl.$formatters.push(function (val) {
$scope.cleave.setRawValue(val);
return $scope.cleave.getFormattedValue();
});
ngModelCtrl.$parsers.push(function (newFormattedValue) {
if ($scope.onValueChange) {
$scope.onValueChange()(newFormattedValue);
}
return $scope.cleave.getRawValue();
});
}
};
}
};
});
|
/*!
* Inferno.h v1.5.5
* (c) 2017 Dominic Gannaway'
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('inferno')) :
typeof define === 'function' && define.amd ? define(['inferno'], factory) :
(global.Inferno = global.Inferno || {}, global.Inferno.h = factory(global.Inferno));
}(this, (function (inferno) { 'use strict';
// This should be boolean and not reference to window.document
|
loadIonicon('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M256 76c48.1 0 93.3 18.7 127.3 52.7S436 207.9 436 256s-18.7 93.3-52.7 127.3S304.1 436 256 436c-48.1 0-93.3-18.7-127.3-52.7S76 304.1 76 256s18.7-93.3 52.7-127.3S207.9 76 256 76m0-28C141.1 48 48 141.1 48 256s93.1 208 208 208 208-93.1 208-208S370.9 48 256 48z"/><path d="M363.5 148.5C334.8 119.8 296.6 104 256 104c-40.6 0-78.8 15.8-107.5 44.5C119.8 177.2 104 215.4 104 256s15.8 78.8 44.5 107.5C177.2 392.2 215.4 408 256 408c40.6 0 78.8-15.8 107.5-44.5C392.2 334.8 408 296.6 408 256s-15.8-78.8-44.5-107.5z"/></svg>','ios-radio-button-on'); |
'use strict'
const BB = require('bluebird')
const andAddParentToErrors = require('./and-add-parent-to-errors.js')
const failedDependency = require('./deps.js').failedDependency
const isInstallable = BB.promisify(require('./validate-args.js').isInstallable)
const moduleName = require('../utils/module-name.js')
const npm = require('../npm.js')
const reportOptionalFailure = require('./report-optional-failure.js')
const validate = require('aproba')
const actions = {}
actions.fetch = require('./action/fetch.js')
actions.extract = require('./action/extract.js')
actions.build = require('./action/build.js')
actions.preinstall = require('./action/preinstall.js')
actions.install = require('./action/install.js')
actions.postinstall = require('./action/postinstall.js')
actions.prepare = require('./action/prepare.js')
actions.finalize = require('./action/finalize.js')
actions.remove = require('./action/remove.js')
actions.unbuild = require('./action/unbuild.js')
actions.move = require('./action/move.js')
actions['global-install'] = require('./action/global-install.js')
actions['global-link'] = require('./action/global-link.js')
actions['refresh-package-json'] = require('./action/refresh-package-json.js')
// FIXME: We wrap actions like three ways to sunday here.
// Rewrite this to only work one way.
Object.keys(actions).forEach(function (actionName) {
var action = actions[actionName]
actions[actionName] = (staging, pkg, log) => {
validate('SOO', [staging, pkg, log])
// refuse to run actions for failed packages
if (pkg.failed) return BB.resolve()
if (action.rollback) {
if (!pkg.rollback) pkg.rollback = []
pkg.rollback.unshift(action.rollback)
}
if (action.commit) {
if (!pkg.commit) pkg.commit = []
pkg.commit.push(action.commit)
}
let actionP
if (pkg.knownInstallable) {
actionP = runAction(action, staging, pkg, log)
} else {
actionP = isInstallable(pkg.package).then(() => {
pkg.knownInstallable = true
return runAction(action, staging, pkg, log)
})
}
return actionP.then(() => {
log.finish()
}, (err) => {
return BB.fromNode((cb) => {
andAddParentToErrors(pkg.parent, cb)(err)
}).catch((err) => {
return handleOptionalDepErrors(pkg, err)
})
})
}
actions[actionName].init = action.init || (() => BB.resolve())
actions[actionName].teardown = action.teardown || (() => BB.resolve())
})
exports.actions = actions
function runAction (action, staging, pkg, log) {
return BB.fromNode((cb) => {
const result = action(staging, pkg, log, cb)
if (result && result.then) {
result.then(() => cb(), cb)
}
})
}
function markAsFailed (pkg) {
if (pkg.failed) return
pkg.failed = true
pkg.requires.forEach((req) => {
var requiredBy = req.requiredBy.filter((reqReqBy) => !reqReqBy.failed)
if (requiredBy.length === 0 && !req.userRequired) {
markAsFailed(req)
}
})
}
function handleOptionalDepErrors (pkg, err) {
markAsFailed(pkg)
var anyFatal = failedDependency(pkg)
if (anyFatal) {
throw err
} else {
reportOptionalFailure(pkg, null, err)
}
}
exports.doOne = doOne
function doOne (cmd, staging, pkg, log, next) {
validate('SSOOF', arguments)
const prepped = prepareAction([cmd, pkg], staging, log)
return withInit(actions[cmd], () => {
return execAction(prepped)
}).nodeify(next)
}
exports.doParallel = doParallel
function doParallel (type, staging, actionsToRun, log, next) {
validate('SSAOF', arguments)
const acts = actionsToRun.reduce((acc, todo) => {
if (todo[0] === type) {
acc.push(prepareAction(todo, staging, log))
}
return acc
}, [])
log.silly('doParallel', type + ' ' + acts.length)
time(log)
if (!acts.length) { return next() }
return withInit(actions[type], () => {
return BB.map(acts, execAction, {
concurrency: npm.limit.action
})
}).nodeify((err) => {
log.finish()
timeEnd(log)
next(err)
})
}
exports.doSerial = doSerial
function doSerial (type, staging, actionsToRun, log, next) {
validate('SSAOF', arguments)
log.silly('doSerial', '%s %d', type, actionsToRun.length)
runSerial(type, staging, actionsToRun, log, next)
}
exports.doReverseSerial = doReverseSerial
function doReverseSerial (type, staging, actionsToRun, log, next) {
validate('SSAOF', arguments)
log.silly('doReverseSerial', '%s %d', type, actionsToRun.length)
runSerial(type, staging, [].concat(actionsToRun).reverse(), log, next)
}
function runSerial (type, staging, actionsToRun, log, next) {
const acts = actionsToRun.reduce((acc, todo) => {
if (todo[0] === type) {
acc.push(prepareAction(todo, staging, log))
}
return acc
}, [])
time(log)
if (!acts.length) { return next() }
return withInit(actions[type], () => {
return BB.each(acts, execAction)
}).nodeify((err) => {
log.finish()
timeEnd(log)
next(err)
})
}
function time (log) {
process.emit('time', 'action:' + log.name)
}
function timeEnd (log) {
process.emit('timeEnd', 'action:' + log.name)
}
function withInit (action, body) {
return BB.using(
action.init().disposer(() => action.teardown()),
body
)
}
function prepareAction (action, staging, log) {
validate('ASO', arguments)
validate('SO', action)
var cmd = action[0]
var pkg = action[1]
if (!actions[cmd]) throw new Error('Unknown decomposed command "' + cmd + '" (is it new?)')
return [actions[cmd], staging, pkg, log.newGroup(cmd + ':' + moduleName(pkg))]
}
function execAction (todo) {
return todo[0].apply(null, todo.slice(1))
}
|
/*!
* angular-translate - v2.17.0 - 2017-12-21
*
* Copyright (c) 2017 The angular-translate team, Pascal Precht; Licensed MIT
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define([], function () {
return (factory());
});
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
factory();
}
}(this, function () {
angular.module('pascalprecht.translate')
/**
* @ngdoc object
* @name pascalprecht.translate.$translatePartialLoaderProvider
*
* @description
* By using a $translatePartialLoaderProvider you can configure a list of a needed
* translation parts directly during the configuration phase of your application's
* lifetime. All parts you add by using this provider would be loaded by
* angular-translate at the startup as soon as possible.
*/
.provider('$translatePartialLoader', $translatePartialLoader);
function $translatePartialLoader() {
'use strict';
/**
* @constructor
* @name Part
*
* @description
* Represents Part object to add and set parts at runtime.
*/
function Part(name, priority, urlTemplate) {
this.name = name;
this.isActive = true;
this.tables = {};
this.priority = priority || 0;
this.langPromises = {};
this.urlTemplate = urlTemplate;
}
/**
* @name parseUrl
* @method
*
* @description
* Returns a parsed url template string and replaces given target lang
* and part name it.
*
* @param {string|function} urlTemplate - Either a string containing an url pattern (with
* '{part}' and '{lang}') or a function(part, lang)
* returning a string.
* @param {string} targetLang - Language key for language to be used.
* @return {string} Parsed url template string
*/
Part.prototype.parseUrl = function (urlTemplate, targetLang) {
if (angular.isFunction(urlTemplate)) {
return urlTemplate(this.name, targetLang);
}
return urlTemplate.replace(/\{part\}/g, this.name).replace(/\{lang\}/g, targetLang);
};
Part.prototype.getTable = function (lang, $q, $http, $httpOptions, urlTemplate, errorHandler) {
//locals
var self = this;
var lastLangPromise = this.langPromises[lang];
var deferred = $q.defer();
//private helper helpers
var fetchData = function () {
return $http(
angular.extend({
method : 'GET',
url : self.parseUrl(self.urlTemplate || urlTemplate, lang)
},
$httpOptions)
);
};
//private helper
var handleNewData = function (data) {
self.tables[lang] = data;
deferred.resolve(data);
};
//private helper
var rejectDeferredWithPartName = function () {
deferred.reject(self.name);
};
//private helper
var tryGettingThisTable = function () {
//data fetching logic
fetchData().then(
function (result) {
handleNewData(result.data);
},
function (errorResponse) {
if (errorHandler) {
errorHandler(self.name, lang, errorResponse).then(handleNewData, rejectDeferredWithPartName);
} else {
rejectDeferredWithPartName();
}
});
};
//loading logic
if (!this.tables[lang]) {
//let's try loading the data
if (!lastLangPromise) {
//this is the first request - just go ahead and hit the server
tryGettingThisTable();
} else {
//this is an additional request after one or more unfinished or failed requests
//chain the deferred off the previous request's promise so that this request conditionally executes
//if the previous request succeeds then the result will be passed through, but if it fails then this request will try again and hit the server
lastLangPromise.then(deferred.resolve, tryGettingThisTable);
}
//retain a reference to the last promise so we can continue the chain if another request is made before any succeed
//you can picture the promise chain as a singly-linked list (formed by the .then handler queues) that's traversed by the execution context
this.langPromises[lang] = deferred.promise;
}
else {
//the part has already been loaded - if lastLangPromise is also undefined then the table has been populated using setPart
//this breaks the promise chain because we're not tying langDeferred's outcome to a previous call's promise handler queues, but we don't care because there's no asynchronous execution context to keep track of anymore
deferred.resolve(this.tables[lang]);
}
return deferred.promise;
};
var parts = {};
function hasPart(name) {
return Object.prototype.hasOwnProperty.call(parts, name);
}
function isStringValid(str) {
return angular.isString(str) && str !== '';
}
function isPartAvailable(name) {
if (!isStringValid(name)) {
throw new TypeError('Invalid type of a first argument, a non-empty string expected.');
}
return (hasPart(name) && parts[name].isActive);
}
function deepExtend(dst, src) {
for (var property in src) {
if (src[property] && src[property].constructor &&
src[property].constructor === Object) {
dst[property] = dst[property] || {};
deepExtend(dst[property], src[property]);
} else {
dst[property] = src[property];
}
}
return dst;
}
function getPrioritizedParts() {
var prioritizedParts = [];
for (var part in parts) {
if (parts[part].isActive) {
prioritizedParts.push(parts[part]);
}
}
prioritizedParts.sort(function (a, b) {
return a.priority - b.priority;
});
return prioritizedParts;
}
/**
* @ngdoc function
* @name pascalprecht.translate.$translatePartialLoaderProvider#addPart
* @methodOf pascalprecht.translate.$translatePartialLoaderProvider
*
* @description
* Registers a new part of the translation table to be loaded once the
* `angular-translate` gets into runtime phase. It does not actually load any
* translation data, but only registers a part to be loaded in the future.
*
* @param {string} name A name of the part to add
* @param {int} [priority=0] Sets the load priority of this part.
*
* @returns {object} $translatePartialLoaderProvider, so this method is chainable
* @throws {TypeError} The method could throw a **TypeError** if you pass the param
* of the wrong type. Please, note that the `name` param has to be a
* non-empty **string**.
*/
this.addPart = function (name, priority, urlTemplate) {
if (!isStringValid(name)) {
throw new TypeError('Couldn\'t add part, part name has to be a string!');
}
if (!hasPart(name)) {
parts[name] = new Part(name, priority, urlTemplate);
}
parts[name].isActive = true;
return this;
};
/**
* @ngdocs function
* @name pascalprecht.translate.$translatePartialLoaderProvider#setPart
* @methodOf pascalprecht.translate.$translatePartialLoaderProvider
*
* @description
* Sets a translation table to the specified part. This method does not make the
* specified part available, but only avoids loading this part from the server.
*
* @param {string} lang A language of the given translation table
* @param {string} part A name of the target part
* @param {object} table A translation table to set to the specified part
*
* @return {object} $translatePartialLoaderProvider, so this method is chainable
* @throws {TypeError} The method could throw a **TypeError** if you pass params
* of the wrong type. Please, note that the `lang` and `part` params have to be a
* non-empty **string**s and the `table` param has to be an object.
*/
this.setPart = function (lang, part, table) {
if (!isStringValid(lang)) {
throw new TypeError('Couldn\'t set part.`lang` parameter has to be a string!');
}
if (!isStringValid(part)) {
throw new TypeError('Couldn\'t set part.`part` parameter has to be a string!');
}
if (typeof table !== 'object' || table === null) {
throw new TypeError('Couldn\'t set part. `table` parameter has to be an object!');
}
if (!hasPart(part)) {
parts[part] = new Part(part);
parts[part].isActive = false;
}
parts[part].tables[lang] = table;
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translatePartialLoaderProvider#deletePart
* @methodOf pascalprecht.translate.$translatePartialLoaderProvider
*
* @description
* Removes the previously added part of the translation data. So, `angular-translate` will not
* load it at the startup.
*
* @param {string} name A name of the part to delete
*
* @returns {object} $translatePartialLoaderProvider, so this method is chainable
*
* @throws {TypeError} The method could throw a **TypeError** if you pass the param of the wrong
* type. Please, note that the `name` param has to be a non-empty **string**.
*/
this.deletePart = function (name) {
if (!isStringValid(name)) {
throw new TypeError('Couldn\'t delete part, first arg has to be string.');
}
if (hasPart(name)) {
parts[name].isActive = false;
}
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translatePartialLoaderProvider#isPartAvailable
* @methodOf pascalprecht.translate.$translatePartialLoaderProvider
*
* @description
* Checks if the specific part is available. A part becomes available after it was added by the
* `addPart` method. Available parts would be loaded from the server once the `angular-translate`
* asks the loader to that.
*
* @param {string} name A name of the part to check
*
* @returns {boolean} Returns **true** if the part is available now and **false** if not.
*
* @throws {TypeError} The method could throw a **TypeError** if you pass the param of the wrong
* type. Please, note that the `name` param has to be a non-empty **string**.
*/
this.isPartAvailable = isPartAvailable;
/**
* @ngdoc object
* @name pascalprecht.translate.$translatePartialLoader
*
* @requires $q
* @requires $http
* @requires $injector
* @requires $rootScope
* @requires $translate
*
* @description
*
* @param {object} options Options object
*
* @throws {TypeError}
*/
this.$get = ['$rootScope', '$injector', '$q', '$http', '$log',
function ($rootScope, $injector, $q, $http, $log) {
/**
* @ngdoc event
* @name pascalprecht.translate.$translatePartialLoader#$translatePartialLoaderStructureChanged
* @eventOf pascalprecht.translate.$translatePartialLoader
* @eventType broadcast on root scope
*
* @description
* A $translatePartialLoaderStructureChanged event is called when a state of the loader was
* changed somehow. It could mean either some part is added or some part is deleted. Anyway when
* you get this event the translation table is not longer current and has to be updated.
*
* @param {string} name A name of the part which is a reason why the event was fired
*/
var service = function (options) {
if (!isStringValid(options.key)) {
throw new TypeError('Unable to load data, a key is not a non-empty string.');
}
if (!isStringValid(options.urlTemplate) && !angular.isFunction(options.urlTemplate)) {
throw new TypeError('Unable to load data, a urlTemplate is not a non-empty string or not a function.');
}
var errorHandler = options.loadFailureHandler;
if (errorHandler !== undefined) {
if (!angular.isString(errorHandler)) {
throw new Error('Unable to load data, a loadFailureHandler is not a string.');
} else {
errorHandler = $injector.get(errorHandler);
}
}
var loaders = [],
prioritizedParts = getPrioritizedParts();
angular.forEach(prioritizedParts, function (part) {
loaders.push(
part.getTable(options.key, $q, $http, options.$http, options.urlTemplate, errorHandler)
);
part.urlTemplate = part.urlTemplate || options.urlTemplate;
});
// workaround for #1781
var structureHasBeenChangedWhileLoading = false;
var dirtyCheckEventCloser = $rootScope.$on('$translatePartialLoaderStructureChanged', function () {
structureHasBeenChangedWhileLoading = true;
});
return $q.all(loaders)
.then(function () {
dirtyCheckEventCloser();
if (structureHasBeenChangedWhileLoading) {
if (!options.__retries) {
// the part structure has been changed while loading (the origin ones)
// this can happen if an addPart/removePart has been invoked right after a $translate.use(lang)
// TODO maybe we can optimize this with the actual list of missing parts
options.__retries = (options.__retries || 0) + 1;
return service(options);
} else {
// the part structure has been changed again while loading (retried one)
// because this could an infinite loop, this will not load another one again
$log.warn('The partial loader has detected a multiple structure change (with addPort/removePart) ' +
'while loading translations. You should consider using promises of $translate.use(lang) and ' +
'$translate.refresh(). Also parts should be added/removed right before an explicit refresh ' +
'if possible.');
}
}
var table = {};
prioritizedParts = getPrioritizedParts();
angular.forEach(prioritizedParts, function (part) {
deepExtend(table, part.tables[options.key]);
});
return table;
}, function () {
dirtyCheckEventCloser();
return $q.reject(options.key);
});
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translatePartialLoader#addPart
* @methodOf pascalprecht.translate.$translatePartialLoader
*
* @description
* Registers a new part of the translation table. This method does not actually perform any xhr
* requests to get translation data. The new parts will be loaded in order of priority from the server next time
* `angular-translate` asks the loader to load translations.
*
* @param {string} name A name of the part to add
* @param {int} [priority=0] Sets the load priority of this part.
*
* @returns {object} $translatePartialLoader, so this method is chainable
*
* @fires {$translatePartialLoaderStructureChanged} The $translatePartialLoaderStructureChanged
* event would be fired by this method in case the new part affected somehow on the loaders
* state. This way it means that there are a new translation data available to be loaded from
* the server.
*
* @throws {TypeError} The method could throw a **TypeError** if you pass the param of the wrong
* type. Please, note that the `name` param has to be a non-empty **string**.
*/
service.addPart = function (name, priority, urlTemplate) {
if (!isStringValid(name)) {
throw new TypeError('Couldn\'t add part, first arg has to be a string');
}
if (!hasPart(name)) {
parts[name] = new Part(name, priority, urlTemplate);
$rootScope.$emit('$translatePartialLoaderStructureChanged', name);
} else if (!parts[name].isActive) {
parts[name].isActive = true;
$rootScope.$emit('$translatePartialLoaderStructureChanged', name);
}
return service;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translatePartialLoader#deletePart
* @methodOf pascalprecht.translate.$translatePartialLoader
*
* @description
* Deletes the previously added part of the translation data. The target part could be deleted
* either logically or physically. When the data is deleted logically it is not actually deleted
* from the browser, but the loader marks it as not active and prevents it from affecting on the
* translations. If the deleted in such way part is added again, the loader will use the
* previously loaded data rather than loading it from the server once more time. But if the data
* is deleted physically, the loader will completely remove all information about it. So in case
* of recycling this part will be loaded from the server again.
*
* @param {string} name A name of the part to delete
* @param {boolean=} [removeData=false] An indicator if the loader has to remove a loaded
* translation data physically. If the `removeData` if set to **false** the loaded data will not be
* deleted physically and might be reused in the future to prevent an additional xhr requests.
*
* @returns {object} $translatePartialLoader, so this method is chainable
*
* @fires {$translatePartialLoaderStructureChanged} The $translatePartialLoaderStructureChanged
* event would be fired by this method in case a part deletion process affects somehow on the
* loaders state. This way it means that some part of the translation data is now deprecated and
* the translation table has to be recompiled with the remaining translation parts.
*
* @throws {TypeError} The method could throw a **TypeError** if you pass some param of the
* wrong type. Please, note that the `name` param has to be a non-empty **string** and
* the `removeData` param has to be either **undefined** or **boolean**.
*/
service.deletePart = function (name, removeData) {
if (!isStringValid(name)) {
throw new TypeError('Couldn\'t delete part, first arg has to be string');
}
if (removeData === undefined) {
removeData = false;
} else if (typeof removeData !== 'boolean') {
throw new TypeError('Invalid type of a second argument, a boolean expected.');
}
if (hasPart(name)) {
var wasActive = parts[name].isActive;
if (removeData) {
var $translate = $injector.get('$translate');
var cache = $translate.loaderCache();
if (typeof(cache) === 'string') {
// getting on-demand instance of loader
cache = $injector.get(cache);
}
// Purging items from cache...
if (typeof(cache) === 'object') {
angular.forEach(parts[name].tables, function (value, key) {
cache.remove(parts[name].parseUrl(parts[name].urlTemplate, key));
});
}
delete parts[name];
} else {
parts[name].isActive = false;
}
if (wasActive) {
$rootScope.$emit('$translatePartialLoaderStructureChanged', name);
}
}
return service;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translatePartialLoader#isPartLoaded
* @methodOf pascalprecht.translate.$translatePartialLoader
*
* @description
* Checks if the registered translation part is loaded into the translation table.
*
* @param {string} name A name of the part
* @param {string} lang A key of the language
*
* @returns {boolean} Returns **true** if the translation of the part is loaded to the translation table and **false** if not.
*
* @throws {TypeError} The method could throw a **TypeError** if you pass the param of the wrong
* type. Please, note that the `name` and `lang` params have to be non-empty **string**.
*/
service.isPartLoaded = function (name, lang) {
return angular.isDefined(parts[name]) && angular.isDefined(parts[name].tables[lang]);
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translatePartialLoader#getRegisteredParts
* @methodOf pascalprecht.translate.$translatePartialLoader
*
* @description
* Gets names of the parts that were added with the `addPart`.
*
* @returns {array} Returns array of registered parts, if none were registered then an empty array is returned.
*/
service.getRegisteredParts = function () {
var registeredParts = [];
angular.forEach(parts, function (p) {
if (p.isActive) {
registeredParts.push(p.name);
}
});
return registeredParts;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translatePartialLoader#isPartAvailable
* @methodOf pascalprecht.translate.$translatePartialLoader
*
* @description
* Checks if a target translation part is available. The part becomes available just after it was
* added by the `addPart` method. Part's availability does not mean that it was loaded from the
* server, but only that it was added to the loader. The available part might be loaded next
* time the loader is called.
*
* @param {string} name A name of the part to delete
*
* @returns {boolean} Returns **true** if the part is available now and **false** if not.
*
* @throws {TypeError} The method could throw a **TypeError** if you pass the param of the wrong
* type. Please, note that the `name` param has to be a non-empty **string**.
*/
service.isPartAvailable = isPartAvailable;
return service;
}];
}
$translatePartialLoader.displayName = '$translatePartialLoader';
return 'pascalprecht.translate';
}));
|
/** PURE_IMPORTS_START .._scheduler_async,.._operators_timeoutWith PURE_IMPORTS_END */
import { async } from '../scheduler/async';
import { timeoutWith as higherOrder } from '../operators/timeoutWith';
/* tslint:enable:max-line-length */
/**
*
* Errors if Observable does not emit a value in given time span, in case of which
* subscribes to the second Observable.
*
* <span class="informal">It's a version of `timeout` operator that let's you specify fallback Observable.</span>
*
* <img src="./img/timeoutWith.png" width="100%">
*
* `timeoutWith` is a variation of `timeout` operator. It behaves exactly the same,
* still accepting as a first argument either a number or a Date, which control - respectively -
* when values of source Observable should be emitted or when it should complete.
*
* The only difference is that it accepts a second, required parameter. This parameter
* should be an Observable which will be subscribed when source Observable fails any timeout check.
* So whenever regular `timeout` would emit an error, `timeoutWith` will instead start re-emitting
* values from second Observable. Note that this fallback Observable is not checked for timeouts
* itself, so it can emit values and complete at arbitrary points in time. From the moment of a second
* subscription, Observable returned from `timeoutWith` simply mirrors fallback stream. When that
* stream completes, it completes as well.
*
* Scheduler, which in case of `timeout` is provided as as second argument, can be still provided
* here - as a third, optional parameter. It still is used to schedule timeout checks and -
* as a consequence - when second Observable will be subscribed, since subscription happens
* immediately after failing check.
*
* @example <caption>Add fallback observable</caption>
* const seconds = Rx.Observable.interval(1000);
* const minutes = Rx.Observable.interval(60 * 1000);
*
* seconds.timeoutWith(900, minutes)
* .subscribe(
* value => console.log(value), // After 900ms, will start emitting `minutes`,
* // since first value of `seconds` will not arrive fast enough.
* err => console.log(err) // Would be called after 900ms in case of `timeout`,
* // but here will never be called.
* );
*
* @param {number|Date} due Number specifying period within which Observable must emit values
* or Date specifying before when Observable should complete
* @param {Observable<T>} withObservable Observable which will be subscribed if source fails timeout check.
* @param {Scheduler} [scheduler] Scheduler controlling when timeout checks occur.
* @return {Observable<T>} Observable that mirrors behaviour of source or, when timeout check fails, of an Observable
* passed as a second parameter.
* @method timeoutWith
* @owner Observable
*/
export function timeoutWith(due, withObservable, scheduler) {
if (scheduler === void 0) {
scheduler = async;
}
return higherOrder(due, withObservable, scheduler)(this);
}
//# sourceMappingURL=timeoutWith.js.map
|
/**
* @fileoverview Rule to flag use of an object property of the global object (Math and JSON) as a function
* @author James Allardice
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "disallow calling global object properties as functions",
category: "Possible Errors",
recommended: true
},
schema: []
},
create(context) {
return {
CallExpression(node) {
if (node.callee.type === "Identifier") {
const name = node.callee.name;
if (name === "Math" || name === "JSON" || name === "Reflect") {
context.report({ node, message: "'{{name}}' is not a function.", data: { name } });
}
}
}
};
}
};
|
define(
"dojo/cldr/nls/de/number", //begin v1.x content
{
"group": ".",
"percentSign": "%",
"exponential": "E",
"scientificFormat": "#E0",
"percentFormat": "#,##0 %",
"list": ";",
"infinity": "∞",
"patternDigit": "#",
"minusSign": "-",
"decimal": ",",
"nan": "NaN",
"nativeZeroDigit": "0",
"perMille": "‰",
"decimalFormat": "#,##0.###",
"currencyFormat": "#,##0.00 ¤",
"plusSign": "+"
}
//end v1.x content
); |
var convert = require('./convert'),
func = convert('invertBy', require('../invertBy'));
func.placeholder = require('./placeholder');
module.exports = func;
|
var React = require('react'),
Application = require('./public/application')
window.onload = function() {
React.render(<Application />, document.getElementById('app'))
}
|
'use strict';
exports.__esModule = true;
exports['default'] = shallowEqual;
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB);
for (var i = 0; i < keysA.length; i++) {
if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
}
module.exports = exports['default']; |
(function(c){c.fn.stupidtable=function(b){return this.each(function(){var a=c(this);b=b||{};b=c.extend({},c.fn.stupidtable.default_sort_fns,b);a.data("sortFns",b);a.on("click.stupidtable","thead th",function(){c(this).stupidsort()})})};c.fn.stupidsort=function(b){var a=c(this),g=0,f=c.fn.stupidtable.dir,e=a.closest("table"),k=a.data("sort")||null;if(null!==k){a.parents("tr").find("th").slice(0,c(this).index()).each(function(){var a=c(this).attr("colspan")||1;g+=parseInt(a,10)});var d;1==arguments.length?
d=b:(d=b||a.data("sort-default")||f.ASC,a.data("sort-dir")&&(d=a.data("sort-dir")===f.ASC?f.DESC:f.ASC));if(a.data("sort-dir")!==d)return a.data("sort-dir",d),e.trigger("beforetablesort",{column:g,direction:d}),e.css("display"),setTimeout(function(){var b=[],l=e.data("sortFns")[k],h=e.children("tbody").children("tr");h.each(function(a,d){var e=c(d).children().eq(g),f=e.data("sort-value");"undefined"===typeof f&&(f=e.text(),e.data("sort-value",f));b.push([f,d])});b.sort(function(a,b){return l(a[0],
b[0])});d!=f.ASC&&b.reverse();h=c.map(b,function(a){return a[1]});e.children("tbody").append(h);e.find("th").data("sort-dir",null).removeClass("sorting-desc sorting-asc");a.data("sort-dir",d).addClass("sorting-"+d);e.trigger("aftertablesort",{column:g,direction:d});e.css("display")},10),a}};c.fn.updateSortVal=function(b){var a=c(this);a.is("[data-sort-value]")&&a.attr("data-sort-value",b);a.data("sort-value",b);return a};c.fn.stupidtable.dir={ASC:"asc",DESC:"desc"};c.fn.stupidtable.default_sort_fns=
{"int":function(b,a){return parseInt(b,10)-parseInt(a,10)},"float":function(b,a){return parseFloat(b)-parseFloat(a)},string:function(b,a){return b.localeCompare(a)},"string-ins":function(b,a){b=b.toLocaleLowerCase();a=a.toLocaleLowerCase();return b.localeCompare(a)}}})(jQuery);
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.0.0-master-19c11fd
*/
!function(a,i,t){"use strict";!function(){function a(){return{restrict:"E",require:["^?mdFabSpeedDial","^?mdFabToolbar"],compile:function(a,t){var n=a.children(),e=!1;i.forEach(["","data-","x-"],function(a){e=e||(n.attr(a+"ng-repeat")?!0:!1)}),e?n.addClass("md-fab-action-item"):n.wrap('<div class="md-fab-action-item">')}}}i.module("material.components.fabActions",["material.core"]).directive("mdFabActions",a)}()}(window,window.angular); |
/* eslint-disable no-console */
export default function l(stuffToLog = this) {
console.log(stuffToLog);
return this;
}
// [1, 2, 3].map(x => x + 1)::l().filter(x => x < 3)::l()
// [2, 3, 4]
// [2]
// wow wat
// <Spring endValue={...}>
// {() =>
// <div>
// bla
// </div>
// ::log('hi')::log('keystrokes saver')
// }
// </Spring>
|
/*!
* MediaElement.js
* http://www.mediaelementjs.com/
*
* Wrapper that mimics native HTML5 MediaElement (audio and video)
* using a variety of technologies (pure JavaScript, Flash, iframe)
*
* Copyright 2010-2017, John Dyer (http://j.hn/)
* License: MIT
*
*/(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
},{}],2:[function(_dereq_,module,exports){
(function (global){
var topLevel = typeof global !== 'undefined' ? global :
typeof window !== 'undefined' ? window : {}
var minDoc = _dereq_(1);
if (typeof document !== 'undefined') {
module.exports = document;
} else {
var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
if (!doccy) {
doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
}
module.exports = doccy;
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"1":1}],3:[function(_dereq_,module,exports){
(function (global){
if (typeof window !== "undefined") {
module.exports = window;
} else if (typeof global !== "undefined") {
module.exports = global;
} else if (typeof self !== "undefined"){
module.exports = self;
} else {
module.exports = {};
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],4:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _mejs = _dereq_(6);
var _mejs2 = _interopRequireDefault(_mejs);
var _en = _dereq_(8);
var _general = _dereq_(16);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Locale.
*
* This object manages translations with pluralization. Also deals with WordPress compatibility.
* @type {Object}
*/
var i18n = { lang: 'en', en: _en.EN };
/**
* Language setter/getter
*
* @param {*} args Can pass the language code and/or the translation strings as an Object
* @return {string}
*/
i18n.language = function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args !== null && args !== undefined && args.length) {
if (typeof args[0] !== 'string') {
throw new TypeError('Language code must be a string value');
}
if (!args[0].match(/^[a-z]{2}(\-[a-z]{2})?$/i)) {
throw new TypeError('Language code must have format `xx` or `xx-xx`');
}
i18n.lang = args[0];
// Check if language strings were added; otherwise, check the second argument or set to English as default
if (i18n[args[0]] === undefined) {
args[1] = args[1] !== null && args[1] !== undefined && _typeof(args[1]) === 'object' ? args[1] : {};
i18n[args[0]] = !(0, _general.isObjectEmpty)(args[1]) ? args[1] : _en.EN;
} else if (args[1] !== null && args[1] !== undefined && _typeof(args[1]) === 'object') {
i18n[args[0]] = args[1];
}
}
return i18n.lang;
};
/**
* Translate a string in the language set up (or English by default)
*
* @param {string} message
* @param {number} pluralParam
* @return {string}
*/
i18n.t = function (message) {
var pluralParam = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
if (typeof message === 'string' && message.length) {
var str = void 0,
pluralForm = void 0;
var language = i18n.language();
/**
* Modify string using algorithm to detect plural forms.
*
* @private
* @see http://stackoverflow.com/questions/1353408/messageformat-in-javascript-parameters-in-localized-ui-strings
* @param {String|String[]} input - String or array of strings to pick the plural form
* @param {Number} number - Number to determine the proper plural form
* @param {Number} form - Number of language family to apply plural form
* @return {String}
*/
var _plural = function _plural(input, number, form) {
if ((typeof input === 'undefined' ? 'undefined' : _typeof(input)) !== 'object' || typeof number !== 'number' || typeof form !== 'number') {
return input;
}
/**
*
* @return {Function[]}
* @private
*/
var _pluralForms = function () {
return [
// 0: Chinese, Japanese, Korean, Persian, Turkish, Thai, Lao, Aymará,
// Tibetan, Chiga, Dzongkha, Indonesian, Lojban, Georgian, Kazakh, Khmer, Kyrgyz, Malay,
// Burmese, Yakut, Sundanese, Tatar, Uyghur, Vietnamese, Wolof
function () {
return arguments.length <= 1 ? undefined : arguments[1];
},
// 1: Danish, Dutch, English, Faroese, Frisian, German, Norwegian, Swedish, Estonian, Finnish,
// Hungarian, Basque, Greek, Hebrew, Italian, Portuguese, Spanish, Catalan, Afrikaans,
// Angika, Assamese, Asturian, Azerbaijani, Bulgarian, Bengali, Bodo, Aragonese, Dogri,
// Esperanto, Argentinean Spanish, Fulah, Friulian, Galician, Gujarati, Hausa,
// Hindi, Chhattisgarhi, Armenian, Interlingua, Greenlandic, Kannada, Kurdish, Letzeburgesch,
// Maithili, Malayalam, Mongolian, Manipuri, Marathi, Nahuatl, Neapolitan, Norwegian Bokmal,
// Nepali, Norwegian Nynorsk, Norwegian (old code), Northern Sotho, Oriya, Punjabi, Papiamento,
// Piemontese, Pashto, Romansh, Kinyarwanda, Santali, Scots, Sindhi, Northern Sami, Sinhala,
// Somali, Songhay, Albanian, Swahili, Tamil, Telugu, Turkmen, Urdu, Yoruba
function () {
return (arguments.length <= 0 ? undefined : arguments[0]) === 1 ? arguments.length <= 1 ? undefined : arguments[1] : arguments.length <= 2 ? undefined : arguments[2];
},
// 2: French, Brazilian Portuguese, Acholi, Akan, Amharic, Mapudungun, Breton, Filipino,
// Gun, Lingala, Mauritian Creole, Malagasy, Maori, Occitan, Tajik, Tigrinya, Uzbek, Walloon
function () {
return (arguments.length <= 0 ? undefined : arguments[0]) === 0 || (arguments.length <= 0 ? undefined : arguments[0]) === 1 ? arguments.length <= 1 ? undefined : arguments[1] : arguments.length <= 2 ? undefined : arguments[2];
},
// 3: Latvian
function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) % 10 === 1 && (arguments.length <= 0 ? undefined : arguments[0]) % 100 !== 11) {
return arguments.length <= 1 ? undefined : arguments[1];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) !== 0) {
return arguments.length <= 2 ? undefined : arguments[2];
} else {
return arguments.length <= 3 ? undefined : arguments[3];
}
},
// 4: Scottish Gaelic
function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) === 1 || (arguments.length <= 0 ? undefined : arguments[0]) === 11) {
return arguments.length <= 1 ? undefined : arguments[1];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) === 2 || (arguments.length <= 0 ? undefined : arguments[0]) === 12) {
return arguments.length <= 2 ? undefined : arguments[2];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) > 2 && (arguments.length <= 0 ? undefined : arguments[0]) < 20) {
return arguments.length <= 3 ? undefined : arguments[3];
} else {
return arguments.length <= 4 ? undefined : arguments[4];
}
},
// 5: Romanian
function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) === 1) {
return arguments.length <= 1 ? undefined : arguments[1];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) === 0 || (arguments.length <= 0 ? undefined : arguments[0]) % 100 > 0 && (arguments.length <= 0 ? undefined : arguments[0]) % 100 < 20) {
return arguments.length <= 2 ? undefined : arguments[2];
} else {
return arguments.length <= 3 ? undefined : arguments[3];
}
},
// 6: Lithuanian
function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) % 10 === 1 && (arguments.length <= 0 ? undefined : arguments[0]) % 100 !== 11) {
return arguments.length <= 1 ? undefined : arguments[1];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) % 10 >= 2 && ((arguments.length <= 0 ? undefined : arguments[0]) % 100 < 10 || (arguments.length <= 0 ? undefined : arguments[0]) % 100 >= 20)) {
return arguments.length <= 2 ? undefined : arguments[2];
} else {
return [3];
}
},
// 7: Belarusian, Bosnian, Croatian, Serbian, Russian, Ukrainian
function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) % 10 === 1 && (arguments.length <= 0 ? undefined : arguments[0]) % 100 !== 11) {
return arguments.length <= 1 ? undefined : arguments[1];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) % 10 >= 2 && (arguments.length <= 0 ? undefined : arguments[0]) % 10 <= 4 && ((arguments.length <= 0 ? undefined : arguments[0]) % 100 < 10 || (arguments.length <= 0 ? undefined : arguments[0]) % 100 >= 20)) {
return arguments.length <= 2 ? undefined : arguments[2];
} else {
return arguments.length <= 3 ? undefined : arguments[3];
}
},
// 8: Slovak, Czech
function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) === 1) {
return arguments.length <= 1 ? undefined : arguments[1];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) >= 2 && (arguments.length <= 0 ? undefined : arguments[0]) <= 4) {
return arguments.length <= 2 ? undefined : arguments[2];
} else {
return arguments.length <= 3 ? undefined : arguments[3];
}
},
// 9: Polish
function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) === 1) {
return arguments.length <= 1 ? undefined : arguments[1];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) % 10 >= 2 && (arguments.length <= 0 ? undefined : arguments[0]) % 10 <= 4 && ((arguments.length <= 0 ? undefined : arguments[0]) % 100 < 10 || (arguments.length <= 0 ? undefined : arguments[0]) % 100 >= 20)) {
return arguments.length <= 2 ? undefined : arguments[2];
} else {
return arguments.length <= 3 ? undefined : arguments[3];
}
},
// 10: Slovenian
function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) % 100 === 1) {
return arguments.length <= 2 ? undefined : arguments[2];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) % 100 === 2) {
return arguments.length <= 3 ? undefined : arguments[3];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) % 100 === 3 || (arguments.length <= 0 ? undefined : arguments[0]) % 100 === 4) {
return arguments.length <= 4 ? undefined : arguments[4];
} else {
return arguments.length <= 1 ? undefined : arguments[1];
}
},
// 11: Irish Gaelic
function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) === 1) {
return arguments.length <= 1 ? undefined : arguments[1];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) === 2) {
return arguments.length <= 2 ? undefined : arguments[2];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) > 2 && (arguments.length <= 0 ? undefined : arguments[0]) < 7) {
return arguments.length <= 3 ? undefined : arguments[3];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) > 6 && (arguments.length <= 0 ? undefined : arguments[0]) < 11) {
return arguments.length <= 4 ? undefined : arguments[4];
} else {
return arguments.length <= 5 ? undefined : arguments[5];
}
},
// 12: Arabic
function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) === 0) {
return arguments.length <= 1 ? undefined : arguments[1];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) === 1) {
return arguments.length <= 2 ? undefined : arguments[2];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) === 2) {
return arguments.length <= 3 ? undefined : arguments[3];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) % 100 >= 3 && (arguments.length <= 0 ? undefined : arguments[0]) % 100 <= 10) {
return arguments.length <= 4 ? undefined : arguments[4];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) % 100 >= 11) {
return arguments.length <= 5 ? undefined : arguments[5];
} else {
return arguments.length <= 6 ? undefined : arguments[6];
}
},
// 13: Maltese
function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) === 1) {
return arguments.length <= 1 ? undefined : arguments[1];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) === 0 || (arguments.length <= 0 ? undefined : arguments[0]) % 100 > 1 && (arguments.length <= 0 ? undefined : arguments[0]) % 100 < 11) {
return arguments.length <= 2 ? undefined : arguments[2];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) % 100 > 10 && (arguments.length <= 0 ? undefined : arguments[0]) % 100 < 20) {
return arguments.length <= 3 ? undefined : arguments[3];
} else {
return arguments.length <= 4 ? undefined : arguments[4];
}
},
// 14: Macedonian
function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) % 10 === 1) {
return arguments.length <= 1 ? undefined : arguments[1];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) % 10 === 2) {
return arguments.length <= 2 ? undefined : arguments[2];
} else {
return arguments.length <= 3 ? undefined : arguments[3];
}
},
// 15: Icelandic
function () {
return (arguments.length <= 0 ? undefined : arguments[0]) !== 11 && (arguments.length <= 0 ? undefined : arguments[0]) % 10 === 1 ? arguments.length <= 1 ? undefined : arguments[1] : arguments.length <= 2 ? undefined : arguments[2];
},
// New additions
// 16: Kashubian
// In https://developer.mozilla.org/en-US/docs/Mozilla/Localization/Localization_and_Plurals#List_of__pluralRules
// Breton is listed as #16 but in the Localization Guide it belongs to the group 2
function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) === 1) {
return arguments.length <= 1 ? undefined : arguments[1];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) % 10 >= 2 && (arguments.length <= 0 ? undefined : arguments[0]) % 10 <= 4 && ((arguments.length <= 0 ? undefined : arguments[0]) % 100 < 10 || (arguments.length <= 0 ? undefined : arguments[0]) % 100 >= 20)) {
return arguments.length <= 2 ? undefined : arguments[2];
} else {
return arguments.length <= 3 ? undefined : arguments[3];
}
},
// 17: Welsh
function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) === 1) {
return arguments.length <= 1 ? undefined : arguments[1];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) === 2) {
return arguments.length <= 2 ? undefined : arguments[2];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) !== 8 && (arguments.length <= 0 ? undefined : arguments[0]) !== 11) {
return arguments.length <= 3 ? undefined : arguments[3];
} else {
return arguments.length <= 4 ? undefined : arguments[4];
}
},
// 18: Javanese
function () {
return (arguments.length <= 0 ? undefined : arguments[0]) === 0 ? arguments.length <= 1 ? undefined : arguments[1] : arguments.length <= 2 ? undefined : arguments[2];
},
// 19: Cornish
function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) === 1) {
return arguments.length <= 1 ? undefined : arguments[1];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) === 2) {
return arguments.length <= 2 ? undefined : arguments[2];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) === 3) {
return arguments.length <= 3 ? undefined : arguments[3];
} else {
return arguments.length <= 4 ? undefined : arguments[4];
}
},
// 20: Mandinka
function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) === 0) {
return arguments.length <= 1 ? undefined : arguments[1];
} else if ((arguments.length <= 0 ? undefined : arguments[0]) === 1) {
return arguments.length <= 2 ? undefined : arguments[2];
} else {
return arguments.length <= 3 ? undefined : arguments[3];
}
}];
}();
// Perform plural form or return original text
return _pluralForms[form].apply(null, [number].concat(input));
};
// Fetch the localized version of the string
if (i18n[language] !== undefined) {
str = i18n[language][message];
if (pluralParam !== null && typeof pluralParam === 'number') {
pluralForm = i18n[language]['mejs.plural-form'];
str = _plural.apply(null, [str, pluralParam, pluralForm]);
}
}
// Fallback to default language if requested uid is not translated
if (!str && i18n.en) {
str = i18n.en[message];
if (pluralParam !== null && typeof pluralParam === 'number') {
pluralForm = i18n.en['mejs.plural-form'];
str = _plural.apply(null, [str, pluralParam, pluralForm]);
}
}
// As a last resort, use the requested uid, to mimic original behavior of i18n utils
// (in which uid was the english text)
str = str || message;
// Replace token
if (pluralParam !== null && typeof pluralParam === 'number') {
str = str.replace('%1', pluralParam);
}
return (0, _general.escapeHTML)(str);
}
return message;
};
_mejs2.default.i18n = i18n;
// `i18n` compatibility workflow with WordPress
if (typeof mejsL10n !== 'undefined') {
_mejs2.default.i18n.language(mejsL10n.language, mejsL10n.strings);
}
exports.default = i18n;
},{"16":16,"6":6,"8":8}],5:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _window = _dereq_(3);
var _window2 = _interopRequireDefault(_window);
var _document = _dereq_(2);
var _document2 = _interopRequireDefault(_document);
var _mejs = _dereq_(6);
var _mejs2 = _interopRequireDefault(_mejs);
var _media = _dereq_(17);
var _renderer = _dereq_(7);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Media Core
*
* This class is the foundation to create/render different media formats.
* @class MediaElement
*/
var MediaElement = function MediaElement(idOrNode, options) {
var _this = this;
_classCallCheck(this, MediaElement);
var t = this;
t.defaults = {
/**
* List of the renderers to use
* @type {String[]}
*/
renderers: [],
/**
* Name of MediaElement container
* @type {String}
*/
fakeNodeName: 'mediaelementwrapper',
/**
* The path where shims are located
* @type {String}
*/
pluginPath: 'build/',
/**
* Flag in `<object>` and `<embed>` to determine whether to use local or CDN
* Possible values: 'always' (CDN version) or 'sameDomain' (local files)
*/
shimScriptAccess: 'sameDomain'
};
options = Object.assign(t.defaults, options);
// create our node (note: older versions of iOS don't support Object.defineProperty on DOM nodes)
t.mediaElement = _document2.default.createElement(options.fakeNodeName);
t.mediaElement.options = options;
var id = idOrNode,
i = void 0,
il = void 0;
if (typeof idOrNode === 'string') {
t.mediaElement.originalNode = _document2.default.getElementById(idOrNode);
} else {
t.mediaElement.originalNode = idOrNode;
id = idOrNode.id;
}
id = id || 'mejs_' + Math.random().toString().slice(2);
if (t.mediaElement.originalNode !== undefined && t.mediaElement.originalNode !== null && t.mediaElement.appendChild) {
// change id
t.mediaElement.originalNode.setAttribute('id', id + '_from_mejs');
// add next to this one
t.mediaElement.originalNode.parentNode.insertBefore(t.mediaElement, t.mediaElement.originalNode);
// insert this one inside
t.mediaElement.appendChild(t.mediaElement.originalNode);
} else {
// TODO: where to put the node?
}
t.mediaElement.id = id;
t.mediaElement.renderers = {};
t.mediaElement.renderer = null;
t.mediaElement.rendererName = null;
/**
* Determine whether the renderer was found or not
*
* @public
* @param {String} rendererName
* @param {Object[]} mediaFiles
* @return {Boolean}
*/
t.mediaElement.changeRenderer = function (rendererName, mediaFiles) {
var t = _this;
// check for a match on the current renderer
if (t.mediaElement.renderer !== undefined && t.mediaElement.renderer !== null && t.mediaElement.renderer.name === rendererName) {
t.mediaElement.renderer.pause();
if (t.mediaElement.renderer.stop) {
t.mediaElement.renderer.stop();
}
t.mediaElement.renderer.show();
t.mediaElement.renderer.setSrc(mediaFiles[0].src);
return true;
}
// if existing renderer is not the right one, then hide it
if (t.mediaElement.renderer !== undefined && t.mediaElement.renderer !== null) {
t.mediaElement.renderer.pause();
if (t.mediaElement.renderer.stop) {
t.mediaElement.renderer.stop();
}
t.mediaElement.renderer.hide();
}
// see if we have the renderer already created
var newRenderer = t.mediaElement.renderers[rendererName],
newRendererType = null;
if (newRenderer !== undefined && newRenderer !== null) {
newRenderer.show();
newRenderer.setSrc(mediaFiles[0].src);
t.mediaElement.renderer = newRenderer;
t.mediaElement.rendererName = rendererName;
return true;
}
var rendererArray = t.mediaElement.options.renderers.length ? t.mediaElement.options.renderers : _renderer.renderer.order;
// find the desired renderer in the array of possible ones
for (i = 0, il = rendererArray.length; i < il; i++) {
var index = rendererArray[i];
if (index === rendererName) {
// create the renderer
var rendererList = _renderer.renderer.renderers;
newRendererType = rendererList[index];
var renderOptions = Object.assign(newRendererType.options, t.mediaElement.options);
newRenderer = newRendererType.create(t.mediaElement, renderOptions, mediaFiles);
newRenderer.name = rendererName;
// store for later
t.mediaElement.renderers[newRendererType.name] = newRenderer;
t.mediaElement.renderer = newRenderer;
t.mediaElement.rendererName = rendererName;
newRenderer.show();
return true;
}
}
return false;
};
/**
* Set the element dimensions based on selected renderer's setSize method
*
* @public
* @param {number} width
* @param {number} height
*/
t.mediaElement.setSize = function (width, height) {
if (t.mediaElement.renderer !== undefined && t.mediaElement.renderer !== null) {
t.mediaElement.renderer.setSize(width, height);
}
};
var props = _mejs2.default.html5media.properties,
methods = _mejs2.default.html5media.methods,
addProperty = function addProperty(obj, name, onGet, onSet) {
// wrapper functions
var oldValue = obj[name];
var getFn = function getFn() {
return onGet.apply(obj, [oldValue]);
},
setFn = function setFn(newValue) {
oldValue = onSet.apply(obj, [newValue]);
return oldValue;
};
Object.defineProperty(obj, name, {
get: getFn,
set: setFn
});
},
assignGettersSetters = function assignGettersSetters(propName) {
if (propName !== 'src') {
(function () {
var capName = '' + propName.substring(0, 1).toUpperCase() + propName.substring(1),
getFn = function getFn() {
return t.mediaElement.renderer !== undefined && t.mediaElement.renderer !== null ? t.mediaElement.renderer['get' + capName]() : null;
},
setFn = function setFn(value) {
if (t.mediaElement.renderer !== undefined && t.mediaElement.renderer !== null) {
t.mediaElement.renderer['set' + capName](value);
}
};
addProperty(t.mediaElement, propName, getFn, setFn);
t.mediaElement['get' + capName] = getFn;
t.mediaElement['set' + capName] = setFn;
})();
}
},
// `src` is a property separated from the others since it carries the logic to set the proper renderer
// based on the media files detected
getSrc = function getSrc() {
return t.mediaElement.renderer !== undefined && t.mediaElement.renderer !== null ? t.mediaElement.renderer.getSrc() : null;
},
setSrc = function setSrc(value) {
var mediaFiles = [];
// clean up URLs
if (typeof value === 'string') {
mediaFiles.push({
src: value,
type: value ? (0, _media.getTypeFromFile)(value) : ''
});
} else {
for (i = 0, il = value.length; i < il; i++) {
var src = (0, _media.absolutizeUrl)(value[i].src),
type = value[i].type;
mediaFiles.push({
src: src,
type: (type === '' || type === null || type === undefined) && src ? (0, _media.getTypeFromFile)(src) : type
});
}
}
// find a renderer and URL match
var renderInfo = _renderer.renderer.select(mediaFiles, t.mediaElement.options.renderers.length ? t.mediaElement.options.renderers : []),
event = void 0;
// Ensure that the original gets the first source found
t.mediaElement.originalNode.setAttribute('src', mediaFiles[0].src || '');
// did we find a renderer?
if (renderInfo === null) {
event = _document2.default.createEvent('HTMLEvents');
event.initEvent('error', false, false);
event.message = 'No renderer found';
t.mediaElement.dispatchEvent(event);
return;
}
// turn on the renderer (this checks for the existing renderer already)
t.mediaElement.changeRenderer(renderInfo.rendererName, mediaFiles);
if (t.mediaElement.renderer === undefined || t.mediaElement.renderer === null) {
event = _document2.default.createEvent('HTMLEvents');
event.initEvent('error', false, false);
event.message = 'Error creating renderer';
t.mediaElement.dispatchEvent(event);
}
},
assignMethods = function assignMethods(methodName) {
// run the method on the current renderer
t.mediaElement[methodName] = function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return t.mediaElement.renderer !== undefined && t.mediaElement.renderer !== null && typeof t.mediaElement.renderer[methodName] === 'function' ? t.mediaElement.renderer[methodName](args) : null;
};
};
// Assign all methods/properties/events to fake node if renderer was found
addProperty(t.mediaElement, 'src', getSrc, setSrc);
t.mediaElement.getSrc = getSrc;
t.mediaElement.setSrc = setSrc;
for (i = 0, il = props.length; i < il; i++) {
assignGettersSetters(props[i]);
}
for (i = 0, il = methods.length; i < il; i++) {
assignMethods(methods[i]);
}
// IE && iOS
t.mediaElement.events = {};
// start: fake events
t.mediaElement.addEventListener = function (eventName, callback) {
// create or find the array of callbacks for this eventName
t.mediaElement.events[eventName] = t.mediaElement.events[eventName] || [];
// push the callback into the stack
t.mediaElement.events[eventName].push(callback);
};
t.mediaElement.removeEventListener = function (eventName, callback) {
// no eventName means remove all listeners
if (!eventName) {
t.mediaElement.events = {};
return true;
}
// see if we have any callbacks for this eventName
var callbacks = t.mediaElement.events[eventName];
if (!callbacks) {
return true;
}
// check for a specific callback
if (!callback) {
t.mediaElement.events[eventName] = [];
return true;
}
// remove the specific callback
for (var _i = 0, _il = callbacks.length; _i < _il; _i++) {
if (callbacks[_i] === callback) {
t.mediaElement.events[eventName].splice(_i, 1);
return true;
}
}
return false;
};
/**
*
* @param {Event} event
*/
t.mediaElement.dispatchEvent = function (event) {
var callbacks = t.mediaElement.events[event.type];
if (callbacks) {
for (i = 0, il = callbacks.length; i < il; i++) {
callbacks[i].apply(null, [event]);
}
}
};
if (t.mediaElement.originalNode !== null) {
var mediaFiles = [];
switch (t.mediaElement.originalNode.nodeName.toLowerCase()) {
case 'iframe':
mediaFiles.push({
type: '',
src: t.mediaElement.originalNode.getAttribute('src')
});
break;
case 'audio':
case 'video':
var n = void 0,
src = void 0,
type = void 0,
sources = t.mediaElement.originalNode.childNodes.length,
nodeSource = t.mediaElement.originalNode.getAttribute('src');
// Consider if node contains the `src` and `type` attributes
if (nodeSource) {
var node = t.mediaElement.originalNode;
mediaFiles.push({
type: (0, _media.formatType)(nodeSource, node.getAttribute('type')),
src: nodeSource
});
}
// test <source> types to see if they are usable
for (i = 0; i < sources; i++) {
n = t.mediaElement.originalNode.childNodes[i];
if (n.nodeType === Node.ELEMENT_NODE && n.tagName.toLowerCase() === 'source') {
src = n.getAttribute('src');
type = (0, _media.formatType)(src, n.getAttribute('type'));
mediaFiles.push({ type: type, src: src });
}
}
break;
}
if (mediaFiles.length > 0) {
t.mediaElement.src = mediaFiles;
}
}
if (t.mediaElement.options.success) {
t.mediaElement.options.success(t.mediaElement, t.mediaElement.originalNode);
}
// @todo: Verify if this is needed
// if (t.mediaElement.options.error) {
// t.mediaElement.options.error(this.mediaElement, this.mediaElement.originalNode);
// }
return t.mediaElement;
};
_window2.default.MediaElement = MediaElement;
exports.default = MediaElement;
},{"17":17,"2":2,"3":3,"6":6,"7":7}],6:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _window = _dereq_(3);
var _window2 = _interopRequireDefault(_window);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Namespace
var mejs = {};
// version number
mejs.version = '3.1.3';
// Basic HTML5 settings
mejs.html5media = {
/**
* @type {String[]}
*/
properties: [
// GET/SET
'volume', 'src', 'currentTime', 'muted',
// GET only
'duration', 'paused', 'ended', 'buffered', 'error', 'networkState', 'readyState', 'seeking', 'seekable',
// OTHERS
'currentSrc', 'preload', 'bufferedBytes', 'bufferedTime', 'initialTime', 'startOffsetTime', 'defaultPlaybackRate', 'playbackRate', 'played', 'autoplay', 'loop', 'controls'],
readOnlyProperties: ['duration', 'paused', 'ended', 'buffered', 'error', 'networkState', 'readyState', 'seeking', 'seekable'],
/**
* @type {String[]}
*/
methods: ['load', 'play', 'pause', 'canPlayType'],
/**
* @type {String[]}
*/
events: ['loadstart', 'progress', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'play', 'pause', 'loadedmetadata', 'loadeddata', 'waiting', 'playing', 'canplay', 'canplaythrough', 'seeking', 'seeked', 'timeupdate', 'ended', 'ratechange', 'durationchange', 'volumechange'],
/**
* @type {String[]}
*/
mediaTypes: ['audio/mp3', 'audio/ogg', 'audio/oga', 'audio/wav', 'audio/x-wav', 'audio/wave', 'audio/x-pn-wav', 'audio/mpeg', 'audio/mp4', 'video/mp4', 'video/webm', 'video/ogg']
};
_window2.default.mejs = mejs;
exports.default = mejs;
},{"3":3}],7:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.renderer = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _mejs = _dereq_(6);
var _mejs2 = _interopRequireDefault(_mejs);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
*
* Class to manage renderer selection and addition.
* @class Renderer
*/
var Renderer = function () {
function Renderer() {
_classCallCheck(this, Renderer);
this.renderers = {};
this.order = [];
}
/**
* Register a new renderer.
*
* @param {Object} renderer - An object with all the rendered information (name REQUIRED)
* @method add
*/
_createClass(Renderer, [{
key: 'add',
value: function add(renderer) {
if (renderer.name === undefined) {
throw new TypeError('renderer must contain at least `name` property');
}
this.renderers[renderer.name] = renderer;
this.order.push(renderer.name);
}
/**
* Iterate a list of renderers to determine which one should the player use.
*
* @param {Object[]} mediaFiles - A list of source and type obtained from video/audio/source tags: [{src:'',type:''}]
* @param {?String[]} renderers - Optional list of pre-selected renderers
* @return {?Object} The renderer's name and source selected
* @method select
*/
}, {
key: 'select',
value: function select(mediaFiles) {
var renderers = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
renderers = renderers.length ? renderers : this.order;
for (var i = 0, il = renderers.length; i < il; i++) {
var key = renderers[i],
_renderer = this.renderers[key];
if (_renderer !== null && _renderer !== undefined) {
for (var j = 0, jl = mediaFiles.length; j < jl; j++) {
if (typeof _renderer.canPlayType === 'function' && typeof mediaFiles[j].type === 'string' && _renderer.canPlayType(mediaFiles[j].type)) {
return {
rendererName: _renderer.name,
src: mediaFiles[j].src
};
}
}
}
}
return null;
}
// Setters/getters
}, {
key: 'order',
set: function set(order) {
if (!Array.isArray(order)) {
throw new TypeError('order must be an array of strings.');
}
this._order = order;
},
get: function get() {
return this._order;
}
}, {
key: 'renderers',
set: function set(renderers) {
if (renderers !== null && (typeof renderers === 'undefined' ? 'undefined' : _typeof(renderers)) !== 'object') {
throw new TypeError('renderers must be an array of objects.');
}
this._renderers = renderers;
},
get: function get() {
return this._renderers;
}
}]);
return Renderer;
}();
var renderer = exports.renderer = new Renderer();
_mejs2.default.Renderers = renderer;
},{"6":6}],8:[function(_dereq_,module,exports){
'use strict';
/*!
* This is a `i18n` language object.
*
* English; This can serve as a template for other languages to translate
*
* @author
* TBD
* Sascha Greuel (Twitter: @SoftCreatR)
*
* @see core/i18n.js
*/
Object.defineProperty(exports, "__esModule", {
value: true
});
var EN = exports.EN = {
"mejs.plural-form": 1,
// renderers/flash.js
"mejs.install-flash": "You are using a browser that does not have Flash player enabled or installed. Please turn on your Flash player plugin or download the latest version from https://get.adobe.com/flashplayer/",
// features/fullscreen.js
"mejs.fullscreen": "Fullscreen",
// features/playpause.js
"mejs.play": "Play",
"mejs.pause": "Pause",
// features/progress.js
"mejs.time-slider": "Time Slider",
"mejs.time-help-text": "Use Left/Right Arrow keys to advance one second, Up/Down arrows to advance ten seconds.",
"mejs.live-broadcast": "Live Broadcast",
// features/volume.js
"mejs.volume-help-text": "Use Up/Down Arrow keys to increase or decrease volume.",
"mejs.unmute": "Unmute",
"mejs.mute": "Mute",
"mejs.volume-slider": "Volume Slider",
// core/player.js
"mejs.video-player": "Video Player",
"mejs.audio-player": "Audio Player",
// features/tracks.js
"mejs.captions-subtitles": "Captions/Subtitles",
"mejs.captions-chapters": "Chapters",
"mejs.none": "None",
"mejs.afrikaans": "Afrikaans",
"mejs.albanian": "Albanian",
"mejs.arabic": "Arabic",
"mejs.belarusian": "Belarusian",
"mejs.bulgarian": "Bulgarian",
"mejs.catalan": "Catalan",
"mejs.chinese": "Chinese",
"mejs.chinese-simplified": "Chinese (Simplified)",
"mejs.chinese-traditional": "Chinese (Traditional)",
"mejs.croatian": "Croatian",
"mejs.czech": "Czech",
"mejs.danish": "Danish",
"mejs.dutch": "Dutch",
"mejs.english": "English",
"mejs.estonian": "Estonian",
"mejs.filipino": "Filipino",
"mejs.finnish": "Finnish",
"mejs.french": "French",
"mejs.galician": "Galician",
"mejs.german": "German",
"mejs.greek": "Greek",
"mejs.haitian-creole": "Haitian Creole",
"mejs.hebrew": "Hebrew",
"mejs.hindi": "Hindi",
"mejs.hungarian": "Hungarian",
"mejs.icelandic": "Icelandic",
"mejs.indonesian": "Indonesian",
"mejs.irish": "Irish",
"mejs.italian": "Italian",
"mejs.japanese": "Japanese",
"mejs.korean": "Korean",
"mejs.latvian": "Latvian",
"mejs.lithuanian": "Lithuanian",
"mejs.macedonian": "Macedonian",
"mejs.malay": "Malay",
"mejs.maltese": "Maltese",
"mejs.norwegian": "Norwegian",
"mejs.persian": "Persian",
"mejs.polish": "Polish",
"mejs.portuguese": "Portuguese",
"mejs.romanian": "Romanian",
"mejs.russian": "Russian",
"mejs.serbian": "Serbian",
"mejs.slovak": "Slovak",
"mejs.slovenian": "Slovenian",
"mejs.spanish": "Spanish",
"mejs.swahili": "Swahili",
"mejs.swedish": "Swedish",
"mejs.tagalog": "Tagalog",
"mejs.thai": "Thai",
"mejs.turkish": "Turkish",
"mejs.ukrainian": "Ukrainian",
"mejs.vietnamese": "Vietnamese",
"mejs.welsh": "Welsh",
"mejs.yiddish": "Yiddish"
};
},{}],9:[function(_dereq_,module,exports){
'use strict';
var _window = _dereq_(3);
var _window2 = _interopRequireDefault(_window);
var _document = _dereq_(2);
var _document2 = _interopRequireDefault(_document);
var _mejs = _dereq_(6);
var _mejs2 = _interopRequireDefault(_mejs);
var _renderer = _dereq_(7);
var _general = _dereq_(16);
var _media = _dereq_(17);
var _constants = _dereq_(15);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Native M(PEG)-Dash renderer
*
* Uses dash.js, a reference client implementation for the playback of M(PEG)-DASH via Javascript and compliant browsers.
* It relies on HTML5 video and MediaSource Extensions for playback.
* This renderer integrates new events associated with mpd files.
* @see https://github.com/Dash-Industry-Forum/dash.js
*
*/
var NativeDash = {
/**
* @type {Boolean}
*/
isMediaLoaded: false,
/**
* @type {Array}
*/
creationQueue: [],
/**
* Create a queue to prepare the loading of an DASH source
*
* @param {Object} settings - an object with settings needed to load an DASH player instance
*/
prepareSettings: function prepareSettings(settings) {
if (NativeDash.isLoaded) {
NativeDash.createInstance(settings);
} else {
NativeDash.loadScript(settings);
NativeDash.creationQueue.push(settings);
}
},
/**
* Load dash.mediaplayer.js script on the header of the document
*
* @param {Object} settings - an object with settings needed to load an DASH player instance
*/
loadScript: function loadScript(settings) {
// Skip script loading since it is already loaded
if (typeof dashjs !== 'undefined') {
NativeDash.createInstance(settings);
} else if (!NativeDash.isScriptLoaded) {
(function () {
settings.options.path = typeof settings.options.path === 'string' ? settings.options.path : '//cdn.dashjs.org/latest/dash.mediaplayer.min.js';
var script = _document2.default.createElement('script'),
firstScriptTag = _document2.default.getElementsByTagName('script')[0];
var done = false;
script.src = settings.options.path;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState || this.readyState === undefined || this.readyState === 'loaded' || this.readyState === 'complete')) {
done = true;
NativeDash.mediaReady();
script.onload = script.onreadystatechange = null;
}
};
firstScriptTag.parentNode.insertBefore(script, firstScriptTag);
NativeDash.isScriptLoaded = true;
})();
}
},
/**
* Process queue of DASH player creation
*
*/
mediaReady: function mediaReady() {
NativeDash.isLoaded = true;
NativeDash.isScriptLoaded = true;
while (NativeDash.creationQueue.length > 0) {
var settings = NativeDash.creationQueue.pop();
NativeDash.createInstance(settings);
}
},
/**
* Create a new instance of DASH player and trigger a custom event to initialize it
*
* @param {Object} settings - an object with settings needed to instantiate DASH object
*/
createInstance: function createInstance(settings) {
var player = dashjs.MediaPlayer().create();
_window2.default['__ready__' + settings.id](player);
}
};
var DashNativeRenderer = {
name: 'native_dash',
options: {
prefix: 'native_dash',
dash: {
// Special config: used to set the local path/URL of dash.js mediaplayer library
path: '//cdn.dashjs.org/latest/dash.mediaplayer.min.js',
debug: false
}
},
/**
* Determine if a specific element type can be played with this render
*
* @param {String} type
* @return {Boolean}
*/
canPlayType: function canPlayType(type) {
return _constants.HAS_MSE && ['application/dash+xml'].includes(type);
},
/**
* Create the player instance and add all native events/methods/properties as possible
*
* @param {MediaElement} mediaElement Instance of mejs.MediaElement already created
* @param {Object} options All the player configuration options passed through constructor
* @param {Object[]} mediaFiles List of sources with format: {src: url, type: x/y-z}
* @return {Object}
*/
create: function create(mediaElement, options, mediaFiles) {
var originalNode = mediaElement.originalNode,
id = mediaElement.id + '_' + options.prefix,
stack = {};
var i = void 0,
il = void 0,
node = null,
dashPlayer = void 0;
node = originalNode.cloneNode(true);
options = Object.assign(options, mediaElement.options);
// WRAPPERS for PROPs
var props = _mejs2.default.html5media.properties,
assignGettersSetters = function assignGettersSetters(propName) {
var capName = '' + propName.substring(0, 1).toUpperCase() + propName.substring(1);
node['get' + capName] = function () {
return dashPlayer !== null ? node[propName] : null;
};
node['set' + capName] = function (value) {
if (!_mejs2.default.html5media.readOnlyProperties.includes(propName)) {
if (dashPlayer !== null) {
if (propName === 'src') {
dashPlayer.attachSource(value);
if (node.getAttribute('autoplay')) {
node.play();
}
}
node[propName] = value;
} else {
// store for after "READY" event fires
stack.push({ type: 'set', propName: propName, value: value });
}
}
};
};
for (i = 0, il = props.length; i < il; i++) {
assignGettersSetters(props[i]);
}
// Initial method to register all M-Dash events
_window2.default['__ready__' + id] = function (_dashPlayer) {
mediaElement.dashPlayer = dashPlayer = _dashPlayer;
// By default, console log is off
dashPlayer.getDebug().setLogToBrowserConsole(options.dash.debug);
// do call stack
if (stack.length) {
for (i = 0, il = stack.length; i < il; i++) {
var stackItem = stack[i];
if (stackItem.type === 'set') {
var propName = stackItem.propName,
capName = '' + propName.substring(0, 1).toUpperCase() + propName.substring(1);
node['set' + capName](stackItem.value);
} else if (stackItem.type === 'call') {
node[stackItem.methodName]();
}
}
}
// BUBBLE EVENTS
var events = _mejs2.default.html5media.events.concat(['click', 'mouseover', 'mouseout']),
dashEvents = dashjs.MediaPlayer.events,
assignEvents = function assignEvents(eventName) {
if (eventName === 'loadedmetadata') {
dashPlayer.initialize(node, node.src, false);
}
node.addEventListener(eventName, function (e) {
var event = _document2.default.createEvent('HTMLEvents');
event.initEvent(e.type, e.bubbles, e.cancelable);
mediaElement.dispatchEvent(event);
});
};
for (i = 0, il = events.length; i < il; i++) {
assignEvents(events[i]);
}
/**
* Custom M(PEG)-DASH events
*
* These events can be attached to the original node using addEventListener and the name of the event,
* not using dashjs.MediaPlayer.events object
* @see http://cdn.dashjs.org/latest/jsdoc/MediaPlayerEvents.html
*/
var assignMdashEvents = function assignMdashEvents(e) {
var event = (0, _general.createEvent)(e.type, node);
event.data = e;
mediaElement.dispatchEvent(event);
if (e.type.toLowerCase() === 'error') {
console.error(e);
}
};
for (var eventType in dashEvents) {
if (dashEvents.hasOwnProperty(eventType)) {
dashPlayer.on(dashEvents[eventType], assignMdashEvents);
}
}
};
if (mediaFiles && mediaFiles.length > 0) {
for (i = 0, il = mediaFiles.length; i < il; i++) {
if (_renderer.renderer.renderers[options.prefix].canPlayType(mediaFiles[i].type)) {
node.setAttribute('src', mediaFiles[i].src);
break;
}
}
}
node.setAttribute('id', id);
originalNode.parentNode.insertBefore(node, originalNode);
originalNode.removeAttribute('autoplay');
originalNode.style.display = 'none';
NativeDash.prepareSettings({
options: options.dash,
id: id
});
// HELPER METHODS
node.setSize = function (width, height) {
node.style.width = width + 'px';
node.style.height = height + 'px';
return node;
};
node.hide = function () {
node.pause();
node.style.display = 'none';
return node;
};
node.show = function () {
node.style.display = '';
return node;
};
var event = (0, _general.createEvent)('rendererready', node);
mediaElement.dispatchEvent(event);
return node;
}
};
/**
* Register Native M(PEG)-Dash type based on URL structure
*
*/
_media.typeChecks.push(function (url) {
url = url.toLowerCase();
return url.includes('.mpd') ? 'application/dash+xml' : null;
});
_renderer.renderer.add(DashNativeRenderer);
},{"15":15,"16":16,"17":17,"2":2,"3":3,"6":6,"7":7}],10:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PluginDetector = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _window = _dereq_(3);
var _window2 = _interopRequireDefault(_window);
var _document = _dereq_(2);
var _document2 = _interopRequireDefault(_document);
var _mejs = _dereq_(6);
var _mejs2 = _interopRequireDefault(_mejs);
var _i18n = _dereq_(4);
var _i18n2 = _interopRequireDefault(_i18n);
var _renderer = _dereq_(7);
var _general = _dereq_(16);
var _constants = _dereq_(15);
var _media = _dereq_(17);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Shim that falls back to Flash if a media type is not supported.
*
* Any format not supported natively, including, RTMP, FLV, HLS and M(PEG)-DASH (if browser does not support MSE),
* will play using Flash.
*/
/**
* Core detector, plugins are added below
*
*/
var PluginDetector = exports.PluginDetector = {
/**
* Cached version numbers
* @type {Array}
*/
plugins: [],
/**
* Test a plugin version number
* @param {String} plugin - In this scenario 'flash' will be tested
* @param {Array} v - An array containing the version up to 3 numbers (major, minor, revision)
* @return {Boolean}
*/
hasPluginVersion: function hasPluginVersion(plugin, v) {
var pv = PluginDetector.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 0;
return pv[0] > v[0] || pv[0] === v[0] && pv[1] > v[1] || pv[0] === v[0] && pv[1] === v[1] && pv[2] >= v[2];
},
/**
* Detect plugin and store its version number
*
* @see PluginDetector.detectPlugin
* @param {String} p
* @param {String} pluginName
* @param {String} mimeType
* @param {String} activeX
* @param {Function} axDetect
*/
addPlugin: function addPlugin(p, pluginName, mimeType, activeX, axDetect) {
PluginDetector.plugins[p] = PluginDetector.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
/**
* Obtain version number from the mime-type (all but IE) or ActiveX (IE)
*
* @param {String} pluginName
* @param {String} mimeType
* @param {String} activeX
* @param {Function} axDetect
* @return {int[]}
*/
detectPlugin: function detectPlugin(pluginName, mimeType, activeX, axDetect) {
var version = [0, 0, 0],
description = void 0,
ax = void 0;
// Firefox, Webkit, Opera; avoid MS Edge since `plugins` cannot be accessed
if (!_constants.IS_EDGE && _constants.NAV.plugins !== null && _constants.NAV.plugins !== undefined && _typeof(_constants.NAV.plugins[pluginName]) === 'object') {
description = _constants.NAV.plugins[pluginName].description;
if (description && !(typeof _constants.NAV.mimeTypes !== 'undefined' && _constants.NAV.mimeTypes[mimeType] && !_constants.NAV.mimeTypes[mimeType].enabledPlugin)) {
version = description.replace(pluginName, '').replace(/^\s+/, '').replace(/\sr/gi, '.').split('.');
for (var i = 0; i < version.length; i++) {
version[i] = parseInt(version[i].match(/\d+/), 10);
}
}
// Internet Explorer / ActiveX
} else if (_window2.default.ActiveXObject !== undefined) {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
} catch (e) {
}
}
return version;
}
};
/**
* Add Flash detection
*
*/
PluginDetector.addPlugin('flash', 'Shockwave Flash', 'application/x-shockwave-flash', 'ShockwaveFlash.ShockwaveFlash', function (ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
var FlashMediaElementRenderer = {
/**
* Create the player instance and add all native events/methods/properties as possible
*
* @param {MediaElement} mediaElement Instance of mejs.MediaElement already created
* @param {Object} options All the player configuration options passed through constructor
* @param {Object[]} mediaFiles List of sources with format: {src: url, type: x/y-z}
* @return {Object}
*/
create: function create(mediaElement, options, mediaFiles) {
var flash = {};
var i = void 0,
il = void 0;
// store main variable
flash.options = options;
flash.id = mediaElement.id + '_' + flash.options.prefix;
flash.mediaElement = mediaElement;
// insert data
flash.flashState = {};
flash.flashApi = null;
flash.flashApiStack = [];
// mediaElements for get/set
var props = _mejs2.default.html5media.properties,
assignGettersSetters = function assignGettersSetters(propName) {
// add to flash state that we will store
flash.flashState[propName] = null;
var capName = '' + propName.substring(0, 1).toUpperCase() + propName.substring(1);
flash['get' + capName] = function () {
if (flash.flashApi !== null) {
if (flash.flashApi['get_' + propName] !== undefined) {
var _ret = function () {
var value = flash.flashApi['get_' + propName]();
// special case for buffered to conform to HTML5's newest
if (propName === 'buffered') {
return {
v: {
start: function start() {
return 0;
},
end: function end() {
return value;
},
length: 1
}
};
}
return {
v: value
};
}();
if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
} else {
return null;
}
} else {
return null;
}
};
flash['set' + capName] = function (value) {
if (propName === 'src') {
value = (0, _media.absolutizeUrl)(value);
}
// send value to Flash
if (flash.flashApi !== null && flash.flashApi['set_' + propName] !== undefined) {
flash.flashApi['set_' + propName](value);
} else {
// store for after "READY" event fires
flash.flashApiStack.push({
type: 'set',
propName: propName,
value: value
});
}
};
};
for (i = 0, il = props.length; i < il; i++) {
assignGettersSetters(props[i]);
}
// add mediaElements for native methods
var methods = _mejs2.default.html5media.methods,
assignMethods = function assignMethods(methodName) {
// run the method on the native HTMLMediaElement
flash[methodName] = function () {
if (flash.flashApi !== null) {
// send call up to Flash ExternalInterface API
if (flash.flashApi['fire_' + methodName]) {
try {
flash.flashApi['fire_' + methodName]();
} catch (e) {
}
} else {
}
} else {
// store for after "READY" event fires
flash.flashApiStack.push({
type: 'call',
methodName: methodName
});
}
};
};
methods.push('stop');
for (i = 0, il = methods.length; i < il; i++) {
assignMethods(methods[i]);
}
// give initial events like in others renderers
var initEvents = ['rendererready', 'loadeddata', 'loadedmetadata', 'canplay'];
for (i = 0, il = initEvents.length; i < il; i++) {
var event = (0, _general.createEvent)(initEvents[i], flash);
mediaElement.dispatchEvent(event);
}
// add a ready method that Flash can call to
_window2.default['__ready__' + flash.id] = function () {
flash.flashReady = true;
flash.flashApi = _document2.default.getElementById('__' + flash.id);
// do call stack
if (flash.flashApiStack.length) {
for (i = 0, il = flash.flashApiStack.length; i < il; i++) {
var stackItem = flash.flashApiStack[i];
if (stackItem.type === 'set') {
var propName = stackItem.propName,
capName = '' + propName.substring(0, 1).toUpperCase() + propName.substring(1);
flash['set' + capName](stackItem.value);
} else if (stackItem.type === 'call') {
flash[stackItem.methodName]();
}
}
}
};
_window2.default['__event__' + flash.id] = function (eventName, message) {
var event = (0, _general.createEvent)(eventName, flash);
event.message = message || '';
// send event from Flash up to the mediaElement
flash.mediaElement.dispatchEvent(event);
};
// insert Flash object
flash.flashWrapper = _document2.default.createElement('div');
// If the access script flag does not have any of the valid values, set to `sameDomain` by default
if (!['always', 'sameDomain'].includes(flash.options.shimScriptAccess)) {
flash.options.shimScriptAccess = 'sameDomain';
}
var autoplay = !!mediaElement.getAttribute('autoplay'),
flashVars = ['uid=' + flash.id, 'autoplay=' + autoplay, 'allowScriptAccess=' + flash.options.shimScriptAccess],
isVideo = mediaElement.originalNode !== null && mediaElement.originalNode.tagName.toLowerCase() === 'video',
flashHeight = isVideo ? mediaElement.originalNode.height : 1,
flashWidth = isVideo ? mediaElement.originalNode.width : 1;
if (mediaElement.originalNode.getAttribute('src')) {
flashVars.push('src=' + mediaElement.originalNode.getAttribute('src'));
}
if (flash.options.enablePseudoStreaming === true) {
flashVars.push('pseudostreamstart=' + flash.options.pseudoStreamingStartQueryParam);
flashVars.push('pseudostreamtype=' + flash.options.pseudoStreamingType);
}
mediaElement.appendChild(flash.flashWrapper);
if (mediaElement.originalNode !== null) {
mediaElement.originalNode.style.display = 'none';
}
var settings = [];
if (_constants.IS_IE) {
var specialIEContainer = _document2.default.createElement('div');
flash.flashWrapper.appendChild(specialIEContainer);
settings = ['classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"', 'codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"', 'id="__' + flash.id + '"', 'width="' + flashWidth + '"', 'height="' + flashHeight + '"'];
if (!isVideo) {
settings.push('style="clip: rect(0 0 0 0); position: absolute;"');
}
specialIEContainer.outerHTML = '<object ' + settings.join(' ') + '>' + ('<param name="movie" value="' + flash.options.pluginPath + flash.options.filename + '?x=' + new Date() + '" />') + ('<param name="flashvars" value="' + flashVars.join('&') + '" />') + '<param name="quality" value="high" />' + '<param name="bgcolor" value="#000000" />' + '<param name="wmode" value="transparent" />' + ('<param name="allowScriptAccess" value="' + flash.options.shimScriptAccess + '" />') + '<param name="allowFullScreen" value="true" />' + ('<div>' + _i18n2.default.t('mejs.install-flash') + '</div>') + '</object>';
} else {
settings = ['id="__' + flash.id + '"', 'name="__' + flash.id + '"', 'play="true"', 'loop="false"', 'quality="high"', 'bgcolor="#000000"', 'wmode="transparent"', 'allowScriptAccess="' + flash.options.shimScriptAccess + '"', 'allowFullScreen="true"', 'type="application/x-shockwave-flash"', 'pluginspage="//www.macromedia.com/go/getflashplayer"', 'src="' + flash.options.pluginPath + flash.options.filename + '"', 'flashvars="' + flashVars.join('&') + '"', 'width="' + flashWidth + '"', 'height="' + flashHeight + '"'];
if (!isVideo) {
settings.push('style="clip: rect(0 0 0 0); position: absolute;"');
}
flash.flashWrapper.innerHTML = '<embed ' + settings.join(' ') + '>';
}
flash.flashNode = flash.flashWrapper.lastChild;
flash.hide = function () {
if (isVideo) {
flash.flashNode.style.position = 'absolute';
flash.flashNode.style.width = '1px';
flash.flashNode.style.height = '1px';
try {
flash.flashNode.style.clip = 'rect(0 0 0 0);';
} catch (e) {
}
}
};
flash.show = function () {
if (isVideo) {
flash.flashNode.style.position = '';
flash.flashNode.style.width = '';
flash.flashNode.style.height = '';
try {
flash.flashNode.style.clip = '';
} catch (e) {
}
}
};
flash.setSize = function (width, height) {
flash.flashNode.style.width = width + 'px';
flash.flashNode.style.height = height + 'px';
if (flash.flashApi !== null && typeof flash.flashApi.fire_setSize === 'function') {
flash.flashApi.fire_setSize(width, height);
}
};
flash.destroy = function () {
flash.flashNode.parentNode.removeChild(flash.flashNode);
};
if (mediaFiles && mediaFiles.length > 0) {
for (i = 0, il = mediaFiles.length; i < il; i++) {
if (_renderer.renderer.renderers[options.prefix].canPlayType(mediaFiles[i].type)) {
flash.setSrc(mediaFiles[i].src);
break;
}
}
}
return flash;
}
};
var hasFlash = PluginDetector.hasPluginVersion('flash', [10, 0, 0]);
if (hasFlash) {
/**
* Register media type based on URL structure if Flash is detected
*
*/
_media.typeChecks.push(function (url) {
url = url.toLowerCase();
if (url.startsWith('rtmp')) {
if (url.includes('.mp3')) {
return 'audio/rtmp';
} else {
return 'video/rtmp';
}
} else if (url.includes('.oga') || url.includes('.ogg')) {
return 'audio/ogg';
} else if (!_constants.HAS_MSE && !_constants.SUPPORTS_NATIVE_HLS && url.includes('.m3u8')) {
return 'application/x-mpegURL';
} else if (!_constants.HAS_MSE && url.includes('.mpd')) {
return 'application/dash+xml';
} else if (!_constants.HAS_MSE && url.includes('.flv')) {
return 'video/flv';
} else {
return null;
}
});
// VIDEO
var FlashMediaElementVideoRenderer = {
name: 'flash_video',
options: {
prefix: 'flash_video',
filename: 'mediaelement-flash-video.swf',
enablePseudoStreaming: false,
// start query parameter sent to server for pseudo-streaming
pseudoStreamingStartQueryParam: 'start',
// pseudo streaming type: use `time` for time based seeking (MP4) or `byte` for file byte position (FLV)
pseudoStreamingType: 'byte'
},
/**
* Determine if a specific element type can be played with this render
*
* @param {String} type
* @return {Boolean}
*/
canPlayType: function canPlayType(type) {
return hasFlash && ['video/mp4', 'video/rtmp', 'audio/rtmp', 'rtmp/mp4', 'audio/mp4'].includes(type) || !_constants.HAS_MSE && hasFlash && ['video/flv', 'video/x-flv'].includes(type);
},
create: FlashMediaElementRenderer.create
};
_renderer.renderer.add(FlashMediaElementVideoRenderer);
// HLS
var FlashMediaElementHlsVideoRenderer = {
name: 'flash_hls',
options: {
prefix: 'flash_hls',
filename: 'mediaelement-flash-video-hls.swf'
},
/**
* Determine if a specific element type can be played with this render
*
* @param {String} type
* @return {Boolean}
*/
canPlayType: function canPlayType(type) {
return !_constants.HAS_MSE && hasFlash && ['application/x-mpegurl', 'vnd.apple.mpegurl', 'audio/mpegurl', 'audio/hls', 'video/hls'].includes(type.toLowerCase());
},
create: FlashMediaElementRenderer.create
};
_renderer.renderer.add(FlashMediaElementHlsVideoRenderer);
// M(PEG)-DASH
var FlashMediaElementMdashVideoRenderer = {
name: 'flash_dash',
options: {
prefix: 'flash_dash',
filename: 'mediaelement-flash-video-mdash.swf'
},
/**
* Determine if a specific element type can be played with this render
*
* @param {String} type
* @return {Boolean}
*/
canPlayType: function canPlayType(type) {
return !_constants.HAS_MSE && hasFlash && ['application/dash+xml'].includes(type);
},
create: FlashMediaElementRenderer.create
};
_renderer.renderer.add(FlashMediaElementMdashVideoRenderer);
// AUDIO
var FlashMediaElementAudioRenderer = {
name: 'flash_audio',
options: {
prefix: 'flash_audio',
filename: 'mediaelement-flash-audio.swf'
},
/**
* Determine if a specific element type can be played with this render
*
* @param {String} type
* @return {Boolean}
*/
canPlayType: function canPlayType(type) {
return hasFlash && ['audio/mp3'].includes(type);
},
create: FlashMediaElementRenderer.create
};
_renderer.renderer.add(FlashMediaElementAudioRenderer);
// AUDIO - ogg
var FlashMediaElementAudioOggRenderer = {
name: 'flash_audio_ogg',
options: {
prefix: 'flash_audio_ogg',
filename: 'mediaelement-flash-audio-ogg.swf'
},
/**
* Determine if a specific element type can be played with this render
*
* @param {String} type
* @return {Boolean}
*/
canPlayType: function canPlayType(type) {
return hasFlash && ['audio/ogg', 'audio/oga', 'audio/ogv'].includes(type);
},
create: FlashMediaElementRenderer.create
};
_renderer.renderer.add(FlashMediaElementAudioOggRenderer);
}
},{"15":15,"16":16,"17":17,"2":2,"3":3,"4":4,"6":6,"7":7}],11:[function(_dereq_,module,exports){
'use strict';
var _window = _dereq_(3);
var _window2 = _interopRequireDefault(_window);
var _document = _dereq_(2);
var _document2 = _interopRequireDefault(_document);
var _mejs = _dereq_(6);
var _mejs2 = _interopRequireDefault(_mejs);
var _renderer = _dereq_(7);
var _general = _dereq_(16);
var _constants = _dereq_(15);
var _media = _dereq_(17);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Native FLV renderer
*
* Uses flv.js, which is a JavaScript library which implements mechanisms to play flv files inspired by flv.js.
* It relies on HTML5 video and MediaSource Extensions for playback.
* Currently, it can only play files with the same origin.
*
* @see https://github.com/Bilibili/flv.js
*
*/
var NativeFlv = {
/**
* @type {Boolean}
*/
isMediaStarted: false,
/**
* @type {Boolean}
*/
isMediaLoaded: false,
/**
* @type {Array}
*/
creationQueue: [],
/**
* Create a queue to prepare the loading of an FLV source
* @param {Object} settings - an object with settings needed to load an FLV player instance
*/
prepareSettings: function prepareSettings(settings) {
if (NativeFlv.isLoaded) {
NativeFlv.createInstance(settings);
} else {
NativeFlv.loadScript(settings);
NativeFlv.creationQueue.push(settings);
}
},
/**
* Load flv.js script on the header of the document
*
* @param {Object} settings - an object with settings needed to load an FLV player instance
*/
loadScript: function loadScript(settings) {
// Skip script loading since it is already loaded
if (typeof flvjs !== 'undefined') {
NativeFlv.createInstance(settings);
} else if (!NativeFlv.isMediaStarted) {
(function () {
settings.options.path = typeof settings.options.path === 'string' ? settings.options.path : '//cdnjs.cloudflare.com/ajax/libs/flv.js/1.1.0/flv.min.js';
var script = _document2.default.createElement('script'),
firstScriptTag = _document2.default.getElementsByTagName('script')[0];
var done = false;
script.src = settings.options.path;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState || this.readyState === undefined || this.readyState === 'loaded' || this.readyState === 'complete')) {
done = true;
NativeFlv.mediaReady();
script.onload = script.onreadystatechange = null;
}
};
firstScriptTag.parentNode.insertBefore(script, firstScriptTag);
NativeFlv.isMediaStarted = true;
})();
}
},
/**
* Process queue of FLV player creation
*
*/
mediaReady: function mediaReady() {
NativeFlv.isLoaded = true;
NativeFlv.isMediaLoaded = true;
while (NativeFlv.creationQueue.length > 0) {
var settings = NativeFlv.creationQueue.pop();
NativeFlv.createInstance(settings);
}
},
/**
* Create a new instance of FLV player and trigger a custom event to initialize it
*
* @param {Object} settings - an object with settings needed to instantiate FLV object
*/
createInstance: function createInstance(settings) {
var player = flvjs.createPlayer(settings.options);
_window2.default['__ready__' + settings.id](player);
}
};
var FlvNativeRenderer = {
name: 'native_flv',
options: {
prefix: 'native_flv',
/**
* Custom configuration for FLV player
*
* @see https://github.com/Bilibili/flv.js/blob/master/docs/api.md#config
* @type {Object}
*/
flv: {
// Special config: used to set the local path/URL of flv.js library
path: '//cdnjs.cloudflare.com/ajax/libs/flv.js/1.1.0/flv.min.js',
cors: true,
enableWorker: false,
enableStashBuffer: true,
stashInitialSize: undefined,
isLive: false,
lazyLoad: true,
lazyLoadMaxDuration: 3 * 60,
deferLoadAfterSourceOpen: true,
statisticsInfoReportInterval: 600,
accurateSeek: false,
seekType: 'range', // [range, param, custom]
seekParamStart: 'bstart',
seekParamEnd: 'bend',
rangeLoadZeroStart: false,
customSeekHandler: undefined
}
},
/**
* Determine if a specific element type can be played with this render
*
* @param {String} type
* @return {Boolean}
*/
canPlayType: function canPlayType(type) {
return _constants.HAS_MSE && ['video/x-flv', 'video/flv'].includes(type);
},
/**
* Create the player instance and add all native events/methods/properties as possible
*
* @param {MediaElement} mediaElement Instance of mejs.MediaElement already created
* @param {Object} options All the player configuration options passed through constructor
* @param {Object[]} mediaFiles List of sources with format: {src: url, type: x/y-z}
* @return {Object}
*/
create: function create(mediaElement, options, mediaFiles) {
var originalNode = mediaElement.originalNode,
id = mediaElement.id + '_' + options.prefix,
stack = {};
var i = void 0,
il = void 0,
node = null,
flvPlayer = void 0;
node = originalNode.cloneNode(true);
options = Object.assign(options, mediaElement.options);
// WRAPPERS for PROPs
var props = _mejs2.default.html5media.properties,
assignGettersSetters = function assignGettersSetters(propName) {
var capName = '' + propName.substring(0, 1).toUpperCase() + propName.substring(1);
node['get' + capName] = function () {
return flvPlayer !== null ? node[propName] : null;
};
node['set' + capName] = function (value) {
if (!_mejs2.default.html5media.readOnlyProperties.includes(propName)) {
if (flvPlayer !== null) {
node[propName] = value;
if (propName === 'src') {
flvPlayer.unload();
flvPlayer.detachMediaElement();
flvPlayer.attachMediaElement(node);
flvPlayer.load();
}
} else {
// store for after "READY" event fires
stack.push({ type: 'set', propName: propName, value: value });
}
}
};
};
for (i = 0, il = props.length; i < il; i++) {
assignGettersSetters(props[i]);
}
// Initial method to register all FLV events
_window2.default['__ready__' + id] = function (_flvPlayer) {
mediaElement.flvPlayer = flvPlayer = _flvPlayer;
// do call stack
if (stack.length) {
for (i = 0, il = stack.length; i < il; i++) {
var stackItem = stack[i];
if (stackItem.type === 'set') {
var propName = stackItem.propName,
capName = '' + propName.substring(0, 1).toUpperCase() + propName.substring(1);
node['set' + capName](stackItem.value);
} else if (stackItem.type === 'call') {
node[stackItem.methodName]();
}
}
}
// BUBBLE EVENTS
var events = _mejs2.default.html5media.events.concat(['click', 'mouseover', 'mouseout']),
assignEvents = function assignEvents(eventName) {
if (eventName === 'loadedmetadata') {
flvPlayer.unload();
flvPlayer.detachMediaElement();
flvPlayer.attachMediaElement(node);
flvPlayer.load();
}
node.addEventListener(eventName, function (e) {
var event = _document2.default.createEvent('HTMLEvents');
event.initEvent(e.type, e.bubbles, e.cancelable);
mediaElement.dispatchEvent(event);
});
};
for (i = 0, il = events.length; i < il; i++) {
assignEvents(events[i]);
}
};
if (mediaFiles && mediaFiles.length > 0) {
for (i = 0, il = mediaFiles.length; i < il; i++) {
if (_renderer.renderer.renderers[options.prefix].canPlayType(mediaFiles[i].type)) {
node.setAttribute('src', mediaFiles[i].src);
break;
}
}
}
node.setAttribute('id', id);
originalNode.parentNode.insertBefore(node, originalNode);
originalNode.removeAttribute('autoplay');
originalNode.style.display = 'none';
// Options that cannot be overridden
options.flv.type = 'flv';
options.flv.url = node.getAttribute('src');
NativeFlv.prepareSettings({
options: options.flv,
id: id
});
// HELPER METHODS
node.setSize = function (width, height) {
node.style.width = width + 'px';
node.style.height = height + 'px';
return node;
};
node.hide = function () {
flvPlayer.pause();
node.style.display = 'none';
return node;
};
node.show = function () {
node.style.display = '';
return node;
};
node.destroy = function () {
flvPlayer.destroy();
};
var event = (0, _general.createEvent)('rendererready', node);
mediaElement.dispatchEvent(event);
return node;
}
};
/**
* Register Native FLV type based on URL structure
*
*/
_media.typeChecks.push(function (url) {
url = url.toLowerCase();
return url.includes('.flv') ? 'video/flv' : null;
});
_renderer.renderer.add(FlvNativeRenderer);
},{"15":15,"16":16,"17":17,"2":2,"3":3,"6":6,"7":7}],12:[function(_dereq_,module,exports){
'use strict';
var _window = _dereq_(3);
var _window2 = _interopRequireDefault(_window);
var _document = _dereq_(2);
var _document2 = _interopRequireDefault(_document);
var _mejs = _dereq_(6);
var _mejs2 = _interopRequireDefault(_mejs);
var _renderer = _dereq_(7);
var _general = _dereq_(16);
var _constants = _dereq_(15);
var _media = _dereq_(17);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Native HLS renderer
*
* Uses DailyMotion's hls.js, which is a JavaScript library which implements an HTTP Live Streaming client.
* It relies on HTML5 video and MediaSource Extensions for playback.
* This renderer integrates new events associated with m3u8 files the same way Flash version of Hls does.
* @see https://github.com/dailymotion/hls.js
*
*/
var NativeHls = {
/**
* @type {Boolean}
*/
isMediaStarted: false,
/**
* @type {Boolean}
*/
isMediaLoaded: false,
/**
* @type {Array}
*/
creationQueue: [],
/**
* Create a queue to prepare the loading of an HLS source
*
* @param {Object} settings - an object with settings needed to load an HLS player instance
*/
prepareSettings: function prepareSettings(settings) {
if (NativeHls.isLoaded) {
NativeHls.createInstance(settings);
} else {
NativeHls.loadScript(settings);
NativeHls.creationQueue.push(settings);
}
},
/**
* Load hls.js script on the header of the document
*
* @param {Object} settings - an object with settings needed to load an HLS player instance
*/
loadScript: function loadScript(settings) {
// Skip script loading since it is already loaded
if (typeof Hls !== 'undefined') {
NativeHls.createInstance(settings);
} else if (!NativeHls.isMediaStarted) {
(function () {
settings.options.path = typeof settings.options.path === 'string' ? settings.options.path : '//cdn.jsdelivr.net/hls.js/latest/hls.min.js';
var script = _document2.default.createElement('script'),
firstScriptTag = _document2.default.getElementsByTagName('script')[0];
var done = false;
script.src = settings.options.path;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState || this.readyState === undefined || this.readyState === 'loaded' || this.readyState === 'complete')) {
done = true;
NativeHls.mediaReady();
script.onload = script.onreadystatechange = null;
}
};
firstScriptTag.parentNode.insertBefore(script, firstScriptTag);
NativeHls.isMediaStarted = true;
})();
}
},
/**
* Process queue of HLS player creation
*
*/
mediaReady: function mediaReady() {
NativeHls.isLoaded = true;
NativeHls.isMediaLoaded = true;
while (NativeHls.creationQueue.length > 0) {
var settings = NativeHls.creationQueue.pop();
NativeHls.createInstance(settings);
}
},
/**
* Create a new instance of HLS player and trigger a custom event to initialize it
*
* @param {Object} settings - an object with settings needed to instantiate HLS object
* @return {Hls}
*/
createInstance: function createInstance(settings) {
var player = new Hls(settings.options);
_window2.default['__ready__' + settings.id](player);
return player;
}
};
var HlsNativeRenderer = {
name: 'native_hls',
options: {
prefix: 'native_hls',
/**
* Custom configuration for HLS player
*
* @see https://github.com/dailymotion/hls.js/blob/master/API.md#user-content-fine-tuning
* @type {Object}
*/
hls: {
// Special config: used to set the local path/URL of hls.js library
path: '//cdn.jsdelivr.net/hls.js/latest/hls.min.js',
autoStartLoad: true,
startPosition: -1,
capLevelToPlayerSize: false,
debug: false,
maxBufferLength: 30,
maxMaxBufferLength: 600,
maxBufferSize: 60 * 1000 * 1000,
maxBufferHole: 0.5,
maxSeekHole: 2,
seekHoleNudgeDuration: 0.01,
maxFragLookUpTolerance: 0.2,
liveSyncDurationCount: 3,
liveMaxLatencyDurationCount: 10,
enableWorker: true,
enableSoftwareAES: true,
manifestLoadingTimeOut: 10000,
manifestLoadingMaxRetry: 6,
manifestLoadingRetryDelay: 500,
manifestLoadingMaxRetryTimeout: 64000,
levelLoadingTimeOut: 10000,
levelLoadingMaxRetry: 6,
levelLoadingRetryDelay: 500,
levelLoadingMaxRetryTimeout: 64000,
fragLoadingTimeOut: 20000,
fragLoadingMaxRetry: 6,
fragLoadingRetryDelay: 500,
fragLoadingMaxRetryTimeout: 64000,
startFragPrefech: false,
appendErrorMaxRetry: 3,
enableCEA708Captions: true,
stretchShortVideoTrack: true,
forceKeyFrameOnDiscontinuity: true,
abrEwmaFastLive: 5.0,
abrEwmaSlowLive: 9.0,
abrEwmaFastVoD: 4.0,
abrEwmaSlowVoD: 15.0,
abrEwmaDefaultEstimate: 500000,
abrBandWidthFactor: 0.8,
abrBandWidthUpFactor: 0.7
}
},
/**
* Determine if a specific element type can be played with this render
*
* @param {String} type
* @return {Boolean}
*/
canPlayType: function canPlayType(type) {
return _constants.HAS_MSE && ['application/x-mpegurl', 'vnd.apple.mpegurl', 'audio/mpegurl', 'audio/hls', 'video/hls'].includes(type.toLowerCase());
},
/**
* Create the player instance and add all native events/methods/properties as possible
*
* @param {MediaElement} mediaElement Instance of mejs.MediaElement already created
* @param {Object} options All the player configuration options passed through constructor
* @param {Object[]} mediaFiles List of sources with format: {src: url, type: x/y-z}
* @return {Object}
*/
create: function create(mediaElement, options, mediaFiles) {
var originalNode = mediaElement.originalNode,
id = mediaElement.id + '_' + options.prefix,
stack = {};
var i = void 0,
il = void 0,
hlsPlayer = void 0,
node = null;
node = originalNode.cloneNode(true);
options = Object.assign(options, mediaElement.options);
// WRAPPERS for PROPs
var props = _mejs2.default.html5media.properties,
assignGettersSetters = function assignGettersSetters(propName) {
var capName = '' + propName.substring(0, 1).toUpperCase() + propName.substring(1);
node['get' + capName] = function () {
return hlsPlayer !== null ? node[propName] : null;
};
node['set' + capName] = function (value) {
if (!_mejs2.default.html5media.readOnlyProperties.includes(propName)) {
if (hlsPlayer !== null) {
node[propName] = value;
if (propName === 'src') {
hlsPlayer.destroy();
hlsPlayer = null;
hlsPlayer = NativeHls.createInstance({
options: options.hls,
id: id
});
hlsPlayer.attachMedia(node);
hlsPlayer.on(Hls.Events.MEDIA_ATTACHED, function () {
hlsPlayer.loadSource(value);
});
}
} else {
// store for after "READY" event fires
stack.push({ type: 'set', propName: propName, value: value });
}
}
};
};
for (i = 0, il = props.length; i < il; i++) {
assignGettersSetters(props[i]);
}
// Initial method to register all HLS events
_window2.default['__ready__' + id] = function (_hlsPlayer) {
mediaElement.hlsPlayer = hlsPlayer = _hlsPlayer;
// do call stack
if (stack.length) {
for (i = 0, il = stack.length; i < il; i++) {
var stackItem = stack[i];
if (stackItem.type === 'set') {
var propName = stackItem.propName,
capName = '' + propName.substring(0, 1).toUpperCase() + propName.substring(1);
node['set' + capName](stackItem.value);
} else if (stackItem.type === 'call') {
node[stackItem.methodName]();
}
}
}
// BUBBLE EVENTS
var events = _mejs2.default.html5media.events.concat(['click', 'mouseover', 'mouseout']),
hlsEvents = Hls.Events,
assignEvents = function assignEvents(eventName) {
if (eventName === 'loadedmetadata') {
(function () {
hlsPlayer.detachMedia();
var url = node.src;
hlsPlayer.attachMedia(node);
hlsPlayer.on(hlsEvents.MEDIA_ATTACHED, function () {
hlsPlayer.loadSource(url);
});
})();
}
node.addEventListener(eventName, function (e) {
// copy event
var event = _document2.default.createEvent('HTMLEvents');
event.initEvent(e.type, e.bubbles, e.cancelable);
mediaElement.dispatchEvent(event);
});
};
for (i = 0, il = events.length; i < il; i++) {
assignEvents(events[i]);
}
/**
* Custom HLS events
*
* These events can be attached to the original node using addEventListener and the name of the event,
* not using Hls.Events object
* @see https://github.com/dailymotion/hls.js/blob/master/src/events.js
* @see https://github.com/dailymotion/hls.js/blob/master/src/errors.js
* @see https://github.com/dailymotion/hls.js/blob/master/API.md#runtime-events
* @see https://github.com/dailymotion/hls.js/blob/master/API.md#errors
*/
var assignHlsEvents = function assignHlsEvents(e, data) {
var event = (0, _general.createEvent)(e, node);
event.data = data;
mediaElement.dispatchEvent(event);
if (e === 'hlsError') {
console.error(e, data);
// borrowed from http://dailymotion.github.io/hls.js/demo/
if (data.fatal) {
hlsPlayer.destroy();
} else {
switch (data.type) {
case 'mediaError':
hlsPlayer.recoverMediaError();
break;
case 'networkError':
hlsPlayer.startLoad();
break;
}
}
}
};
for (var eventType in hlsEvents) {
if (hlsEvents.hasOwnProperty(eventType)) {
hlsPlayer.on(hlsEvents[eventType], assignHlsEvents);
}
}
};
if (mediaFiles && mediaFiles.length > 0) {
for (i = 0, il = mediaFiles.length; i < il; i++) {
if (_renderer.renderer.renderers[options.prefix].canPlayType(mediaFiles[i].type)) {
node.setAttribute('src', mediaFiles[i].src);
break;
}
}
}
node.setAttribute('id', id);
originalNode.parentNode.insertBefore(node, originalNode);
originalNode.removeAttribute('autoplay');
originalNode.style.display = 'none';
NativeHls.prepareSettings({
options: options.hls,
id: id
});
// HELPER METHODS
node.setSize = function (width, height) {
node.style.width = width + 'px';
node.style.height = height + 'px';
return node;
};
node.hide = function () {
node.pause();
node.style.display = 'none';
return node;
};
node.show = function () {
node.style.display = '';
return node;
};
node.destroy = function () {
hlsPlayer.destroy();
};
var event = (0, _general.createEvent)('rendererready', node);
mediaElement.dispatchEvent(event);
return node;
}
};
/**
* Register Native HLS type based on URL structure
*
*/
_media.typeChecks.push(function (url) {
url = url.toLowerCase();
return url.includes('.m3u8') ? 'application/x-mpegURL' : null;
});
_renderer.renderer.add(HlsNativeRenderer);
},{"15":15,"16":16,"17":17,"2":2,"3":3,"6":6,"7":7}],13:[function(_dereq_,module,exports){
'use strict';
var _window = _dereq_(3);
var _window2 = _interopRequireDefault(_window);
var _document = _dereq_(2);
var _document2 = _interopRequireDefault(_document);
var _mejs = _dereq_(6);
var _mejs2 = _interopRequireDefault(_mejs);
var _renderer = _dereq_(7);
var _general = _dereq_(16);
var _constants = _dereq_(15);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Native HTML5 Renderer
*
* Wraps the native HTML5 <audio> or <video> tag and bubbles its properties, events, and methods up to the mediaElement.
*/
var HtmlMediaElement = {
name: 'html5',
options: {
prefix: 'html5'
},
/**
* Determine if a specific element type can be played with this render
*
* @param {String} type
* @return {String}
*/
canPlayType: function canPlayType(type) {
var mediaElement = _document2.default.createElement('video');
// Due to an issue on Webkit, force the MP3 and MP4 on Android and consider native support for HLS;
// also consider URLs that might have obfuscated URLs
if (_constants.IS_ANDROID && type.match(/\/mp(3|4)$/gi) !== null || ['application/x-mpegurl', 'vnd.apple.mpegurl', 'audio/mpegurl', 'audio/hls', 'video/hls'].includes(type.toLowerCase()) && _constants.SUPPORTS_NATIVE_HLS) {
return 'yes';
} else if (mediaElement.canPlayType) {
return mediaElement.canPlayType(type).replace(/no/, '');
} else {
return '';
}
},
/**
* Create the player instance and add all native events/methods/properties as possible
*
* @param {MediaElement} mediaElement Instance of mejs.MediaElement already created
* @param {Object} options All the player configuration options passed through constructor
* @param {Object[]} mediaFiles List of sources with format: {src: url, type: x/y-z}
* @return {Object}
*/
create: function create(mediaElement, options, mediaFiles) {
var id = mediaElement.id + '_' + options.prefix;
var node = null,
i = void 0,
il = void 0;
// CREATE NODE
if (mediaElement.originalNode === undefined || mediaElement.originalNode === null) {
node = _document2.default.createElement('audio');
mediaElement.appendChild(node);
} else {
node = mediaElement.originalNode;
}
node.setAttribute('id', id);
// WRAPPERS for PROPs
var props = _mejs2.default.html5media.properties,
assignGettersSetters = function assignGettersSetters(propName) {
var capName = '' + propName.substring(0, 1).toUpperCase() + propName.substring(1);
node['get' + capName] = function () {
return node[propName];
};
node['set' + capName] = function (value) {
if (!_mejs2.default.html5media.readOnlyProperties.includes(propName)) {
node[propName] = value;
}
};
};
for (i = 0, il = props.length; i < il; i++) {
assignGettersSetters(props[i]);
}
var events = _mejs2.default.html5media.events.concat(['click', 'mouseover', 'mouseout']),
assignEvents = function assignEvents(eventName) {
node.addEventListener(eventName, function (e) {
// copy event
var event = _document2.default.createEvent('HTMLEvents');
event.initEvent(e.type, e.bubbles, e.cancelable);
mediaElement.dispatchEvent(event);
});
};
for (i = 0, il = events.length; i < il; i++) {
assignEvents(events[i]);
}
// HELPER METHODS
node.setSize = function (width, height) {
node.style.width = width + 'px';
node.style.height = height + 'px';
return node;
};
node.hide = function () {
node.style.display = 'none';
return node;
};
node.show = function () {
node.style.display = '';
return node;
};
if (mediaFiles && mediaFiles.length > 0) {
for (i = 0, il = mediaFiles.length; i < il; i++) {
if (_renderer.renderer.renderers[options.prefix].canPlayType(mediaFiles[i].type)) {
node.setAttribute('src', mediaFiles[i].src);
break;
}
}
}
var event = (0, _general.createEvent)('rendererready', node);
mediaElement.dispatchEvent(event);
return node;
}
};
_window2.default.HtmlMediaElement = _mejs2.default.HtmlMediaElement = HtmlMediaElement;
_renderer.renderer.add(HtmlMediaElement);
},{"15":15,"16":16,"2":2,"3":3,"6":6,"7":7}],14:[function(_dereq_,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _window = _dereq_(3);
var _window2 = _interopRequireDefault(_window);
var _document = _dereq_(2);
var _document2 = _interopRequireDefault(_document);
var _mejs = _dereq_(6);
var _mejs2 = _interopRequireDefault(_mejs);
var _renderer = _dereq_(7);
var _general = _dereq_(16);
var _media = _dereq_(17);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* YouTube renderer
*
* Uses <iframe> approach and uses YouTube API to manipulate it.
* Note: IE6-7 don't have postMessage so don't support <iframe> API, and IE8 doesn't fire the onReady event,
* so it doesn't work - not sure if Google problem or not.
* @see https://developers.google.com/youtube/iframe_api_reference
*/
var YouTubeApi = {
/**
* @type {Boolean}
*/
isIframeStarted: false,
/**
* @type {Boolean}
*/
isIframeLoaded: false,
/**
* @type {Array}
*/
iframeQueue: [],
/**
* Create a queue to prepare the creation of <iframe>
*
* @param {Object} settings - an object with settings needed to create <iframe>
*/
enqueueIframe: function enqueueIframe(settings) {
// Check whether YouTube API is already loaded.
YouTubeApi.isLoaded = typeof YT !== 'undefined' && YT.loaded;
if (YouTubeApi.isLoaded) {
YouTubeApi.createIframe(settings);
} else {
YouTubeApi.loadIframeApi();
YouTubeApi.iframeQueue.push(settings);
}
},
/**
* Load YouTube API script on the header of the document
*
*/
loadIframeApi: function loadIframeApi() {
if (!YouTubeApi.isIframeStarted) {
var tag = _document2.default.createElement('script');
tag.src = '//www.youtube.com/player_api';
var firstScriptTag = _document2.default.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
YouTubeApi.isIframeStarted = true;
}
},
/**
* Process queue of YouTube <iframe> element creation
*
*/
iFrameReady: function iFrameReady() {
YouTubeApi.isLoaded = true;
YouTubeApi.isIframeLoaded = true;
while (YouTubeApi.iframeQueue.length > 0) {
var settings = YouTubeApi.iframeQueue.pop();
YouTubeApi.createIframe(settings);
}
},
/**
* Create a new instance of YouTube API player and trigger a custom event to initialize it
*
* @param {Object} settings - an object with settings needed to create <iframe>
*/
createIframe: function createIframe(settings) {
return new YT.Player(settings.containerId, settings);
},
/**
* Extract ID from YouTube's URL to be loaded through API
* Valid URL format(s):
* - http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
* - http://www.youtube.com/v/VIDEO_ID?version=3
* - http://youtu.be/Djd6tPrxc08
* - http://www.youtube-nocookie.com/watch?feature=player_embedded&v=yyWWXSwtPP0
*
* @param {String} url
* @return {string}
*/
getYouTubeId: function getYouTubeId(url) {
var youTubeId = '';
if (url.indexOf('?') > 0) {
// assuming: http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
youTubeId = YouTubeApi.getYouTubeIdFromParam(url);
// if it's http://www.youtube.com/v/VIDEO_ID?version=3
if (youTubeId === '') {
youTubeId = YouTubeApi.getYouTubeIdFromUrl(url);
}
} else {
youTubeId = YouTubeApi.getYouTubeIdFromUrl(url);
}
return youTubeId;
},
/**
* Get ID from URL with format: http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
*
* @param {String} url
* @returns {string}
*/
getYouTubeIdFromParam: function getYouTubeIdFromParam(url) {
if (url === undefined || url === null || !url.trim().length) {
return null;
}
var parts = url.split('?'),
parameters = parts[1].split('&');
var youTubeId = '';
for (var i = 0, il = parameters.length; i < il; i++) {
var paramParts = parameters[i].split('=');
if (paramParts[0] === 'v') {
youTubeId = paramParts[1];
break;
}
}
return youTubeId;
},
/**
* Get ID from URL with formats
* - http://www.youtube.com/v/VIDEO_ID?version=3
* - http://youtu.be/Djd6tPrxc08
* @param {String} url
* @return {?String}
*/
getYouTubeIdFromUrl: function getYouTubeIdFromUrl(url) {
if (url === undefined || url === null || !url.trim().length) {
return null;
}
var parts = url.split('?');
url = parts[0];
return url.substring(url.lastIndexOf('/') + 1);
},
/**
* Inject `no-cookie` element to URL. Only works with format: http://www.youtube.com/v/VIDEO_ID?version=3
* @param {String} url
* @return {?String}
*/
getYouTubeNoCookieUrl: function getYouTubeNoCookieUrl(url) {
if (url === undefined || url === null || !url.trim().length || !url.includes('//www.youtube')) {
return url;
}
var parts = url.split('/');
parts[2] = parts[2].replace('.com', '-nocookie.com');
return parts.join('/');
}
};
var YouTubeIframeRenderer = {
name: 'youtube_iframe',
options: {
prefix: 'youtube_iframe',
/**
* Custom configuration for YouTube player
*
* @see https://developers.google.com/youtube/player_parameters#Parameters
* @type {Object}
*/
youtube: {
autoplay: 0,
controls: 0,
disablekb: 1,
end: 0,
loop: 0,
modestbranding: 0,
playsinline: 0,
rel: 0,
showinfo: 0,
start: 0,
iv_load_policy: 3,
// custom to inject `-nocookie` element in URL
nocookie: false
}
},
/**
* Determine if a specific element type can be played with this render
*
* @param {String} type
* @return {Boolean}
*/
canPlayType: function canPlayType(type) {
return ['video/youtube', 'video/x-youtube'].includes(type);
},
/**
* Create the player instance and add all native events/methods/properties as possible
*
* @param {MediaElement} mediaElement Instance of mejs.MediaElement already created
* @param {Object} options All the player configuration options passed through constructor
* @param {Object[]} mediaFiles List of sources with format: {src: url, type: x/y-z}
* @return {Object}
*/
create: function create(mediaElement, options, mediaFiles) {
// API objects
var youtube = {},
apiStack = [],
readyState = 4;
var i = void 0,
il = void 0,
youTubeApi = null,
paused = true,
ended = false,
youTubeIframe = null,
volume = 1;
youtube.options = options;
youtube.id = mediaElement.id + '_' + options.prefix;
youtube.mediaElement = mediaElement;
// wrappers for get/set
var props = _mejs2.default.html5media.properties,
assignGettersSetters = function assignGettersSetters(propName) {
// add to flash state that we will store
var capName = '' + propName.substring(0, 1).toUpperCase() + propName.substring(1);
youtube['get' + capName] = function () {
if (youTubeApi !== null) {
var value = null;
// figure out how to get youtube dta here
var _ret = function () {
switch (propName) {
case 'currentTime':
return {
v: youTubeApi.getCurrentTime()
};
case 'duration':
return {
v: youTubeApi.getDuration()
};
case 'volume':
volume = youTubeApi.getVolume() / 100;
return {
v: volume
};
case 'paused':
return {
v: paused
};
case 'ended':
return {
v: ended
};
case 'muted':
return {
v: youTubeApi.isMuted()
};
case 'buffered':
var percentLoaded = youTubeApi.getVideoLoadedFraction(),
duration = youTubeApi.getDuration();
return {
v: {
start: function start() {
return 0;
},
end: function end() {
return percentLoaded * duration;
},
length: 1
}
};
case 'src':
return {
v: youTubeApi.getVideoUrl()
};
case 'readyState':
return {
v: readyState
};
}
}();
if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
return value;
} else {
return null;
}
};
youtube['set' + capName] = function (value) {
if (youTubeApi !== null) {
// do something
switch (propName) {
case 'src':
var url = typeof value === 'string' ? value : value[0].src,
_videoId = YouTubeApi.getYouTubeId(url);
if (mediaElement.getAttribute('autoplay')) {
youTubeApi.loadVideoById(_videoId);
} else {
youTubeApi.cueVideoById(_videoId);
}
break;
case 'currentTime':
youTubeApi.seekTo(value);
break;
case 'muted':
if (value) {
youTubeApi.mute();
} else {
youTubeApi.unMute();
}
setTimeout(function () {
var event = (0, _general.createEvent)('volumechange', youtube);
mediaElement.dispatchEvent(event);
}, 50);
break;
case 'volume':
volume = value;
youTubeApi.setVolume(value * 100);
setTimeout(function () {
var event = (0, _general.createEvent)('volumechange', youtube);
mediaElement.dispatchEvent(event);
}, 50);
break;
case 'readyState':
var event = (0, _general.createEvent)('canplay', youtube);
mediaElement.dispatchEvent(event);
break;
default:
break;
}
} else {
// store for after "READY" event fires
apiStack.push({ type: 'set', propName: propName, value: value });
}
};
};
for (i = 0, il = props.length; i < il; i++) {
assignGettersSetters(props[i]);
}
// add wrappers for native methods
var methods = _mejs2.default.html5media.methods,
assignMethods = function assignMethods(methodName) {
// run the method on the native HTMLMediaElement
youtube[methodName] = function () {
if (youTubeApi !== null) {
// DO method
switch (methodName) {
case 'play':
paused = false;
return youTubeApi.playVideo();
case 'pause':
paused = true;
return youTubeApi.pauseVideo();
case 'load':
return null;
}
} else {
apiStack.push({ type: 'call', methodName: methodName });
}
};
};
for (i = 0, il = methods.length; i < il; i++) {
assignMethods(methods[i]);
}
// CREATE YouTube
var youtubeContainer = _document2.default.createElement('div');
youtubeContainer.id = youtube.id;
// If `nocookie` feature was enabled, modify original URL
if (youtube.options.youtube.nocookie) {
mediaElement.originalNode.setAttribute('src', YouTubeApi.getYouTubeNoCookieUrl(mediaFiles[0].src));
}
mediaElement.originalNode.parentNode.insertBefore(youtubeContainer, mediaElement.originalNode);
mediaElement.originalNode.style.display = 'none';
var isAudio = mediaElement.originalNode.tagName.toLowerCase() === 'audio',
height = isAudio ? '0' : mediaElement.originalNode.height,
width = isAudio ? '0' : mediaElement.originalNode.width,
videoId = YouTubeApi.getYouTubeId(mediaFiles[0].src),
youtubeSettings = {
id: youtube.id,
containerId: youtubeContainer.id,
videoId: videoId,
height: height,
width: width,
playerVars: Object.assign({
controls: 0,
rel: 0,
disablekb: 1,
showinfo: 0,
modestbranding: 0,
html5: 1,
playsinline: 0,
start: 0,
end: 0,
iv_load_policy: 3
}, youtube.options.youtube),
origin: _window2.default.location.host,
events: {
onReady: function onReady(e) {
mediaElement.youTubeApi = youTubeApi = e.target;
mediaElement.youTubeState = {
paused: true,
ended: false
};
// do call stack
if (apiStack.length) {
for (i = 0, il = apiStack.length; i < il; i++) {
var stackItem = apiStack[i];
if (stackItem.type === 'set') {
var propName = stackItem.propName,
capName = '' + propName.substring(0, 1).toUpperCase() + propName.substring(1);
youtube['set' + capName](stackItem.value);
} else if (stackItem.type === 'call') {
youtube[stackItem.methodName]();
}
}
}
// a few more events
youTubeIframe = youTubeApi.getIframe();
var events = ['mouseover', 'mouseout'],
assignEvents = function assignEvents(e) {
var newEvent = (0, _general.createEvent)(e.type, youtube);
mediaElement.dispatchEvent(newEvent);
};
for (i = 0, il = events.length; i < il; i++) {
youTubeIframe.addEventListener(events[i], assignEvents, false);
}
// send init events
var initEvents = ['rendererready', 'loadeddata', 'loadedmetadata', 'canplay'];
for (i = 0, il = initEvents.length; i < il; i++) {
var event = (0, _general.createEvent)(initEvents[i], youtube);
mediaElement.dispatchEvent(event);
}
},
onStateChange: function onStateChange(e) {
// translate events
var events = [];
switch (e.data) {
case -1:
// not started
events = ['loadedmetadata'];
paused = true;
ended = false;
break;
case 0:
// YT.PlayerState.ENDED
events = ['ended'];
paused = false;
ended = true;
youtube.stopInterval();
break;
case 1:
// YT.PlayerState.PLAYING
events = ['play', 'playing'];
paused = false;
ended = false;
youtube.startInterval();
break;
case 2:
// YT.PlayerState.PAUSED
events = ['pause'];
paused = true;
ended = false;
youtube.stopInterval();
break;
case 3:
// YT.PlayerState.BUFFERING
events = ['progress'];
ended = false;
break;
case 5:
// YT.PlayerState.CUED
events = ['loadeddata', 'loadedmetadata', 'canplay'];
paused = true;
ended = false;
break;
}
// send events up
for (i = 0, il = events.length; i < il; i++) {
var event = (0, _general.createEvent)(events[i], youtube);
mediaElement.dispatchEvent(event);
}
},
onError: function onError(e) {
var event = (0, _general.createEvent)('error', youtube);
event.data = e.data;
mediaElement.dispatchEvent(event);
}
}
};
// The following will prevent that in mobile devices, YouTube is displayed in fullscreen when using audio
if (isAudio) {
youtubeSettings.playerVars.playsinline = 1;
}
// send it off for async loading and creation
YouTubeApi.enqueueIframe(youtubeSettings);
youtube.onEvent = function (eventName, player, _youTubeState) {
if (_youTubeState !== null && _youTubeState !== undefined) {
mediaElement.youTubeState = _youTubeState;
}
};
youtube.setSize = function (width, height) {
if (youTubeApi !== null) {
youTubeApi.setSize(width, height);
}
};
youtube.hide = function () {
youtube.stopInterval();
youtube.pause();
if (youTubeIframe) {
youTubeIframe.style.display = 'none';
}
};
youtube.show = function () {
if (youTubeIframe) {
youTubeIframe.style.display = '';
}
};
youtube.destroy = function () {
youTubeApi.destroy();
};
youtube.interval = null;
youtube.startInterval = function () {
// create timer
youtube.interval = setInterval(function () {
var event = (0, _general.createEvent)('timeupdate', youtube);
mediaElement.dispatchEvent(event);
}, 250);
};
youtube.stopInterval = function () {
if (youtube.interval) {
clearInterval(youtube.interval);
}
};
return youtube;
}
};
if (_window2.default.postMessage && _typeof(_window2.default.addEventListener)) {
_window2.default.onYouTubePlayerAPIReady = function () {
YouTubeApi.iFrameReady();
};
_media.typeChecks.push(function (url) {
url = url.toLowerCase();
return url.includes('//www.youtube') || url.includes('//youtu.be') ? 'video/x-youtube' : null;
});
_renderer.renderer.add(YouTubeIframeRenderer);
}
},{"16":16,"17":17,"2":2,"3":3,"6":6,"7":7}],15:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.cancelFullScreen = exports.requestFullScreen = exports.isFullScreen = exports.FULLSCREEN_EVENT_NAME = exports.HAS_NATIVE_FULLSCREEN_ENABLED = exports.HAS_TRUE_NATIVE_FULLSCREEN = exports.HAS_IOS_FULLSCREEN = exports.HAS_MS_NATIVE_FULLSCREEN = exports.HAS_MOZ_NATIVE_FULLSCREEN = exports.HAS_WEBKIT_NATIVE_FULLSCREEN = exports.HAS_NATIVE_FULLSCREEN = exports.SUPPORTS_NATIVE_HLS = exports.SUPPORT_POINTER_EVENTS = exports.HAS_MSE = exports.IS_STOCK_ANDROID = exports.IS_SAFARI = exports.IS_FIREFOX = exports.IS_CHROME = exports.IS_EDGE = exports.IS_IE = exports.IS_ANDROID = exports.IS_IOS = exports.IS_IPHONE = exports.IS_IPAD = exports.UA = exports.NAV = undefined;
var _window = _dereq_(3);
var _window2 = _interopRequireDefault(_window);
var _document = _dereq_(2);
var _document2 = _interopRequireDefault(_document);
var _mejs = _dereq_(6);
var _mejs2 = _interopRequireDefault(_mejs);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var NAV = exports.NAV = _window2.default.navigator;
var UA = exports.UA = NAV.userAgent.toLowerCase();
var IS_IPAD = exports.IS_IPAD = UA.match(/ipad/i) !== null;
var IS_IPHONE = exports.IS_IPHONE = UA.match(/iphone/i) !== null;
var IS_IOS = exports.IS_IOS = IS_IPHONE || IS_IPAD;
var IS_ANDROID = exports.IS_ANDROID = UA.match(/android/i) !== null;
var IS_IE = exports.IS_IE = NAV.appName.toLowerCase().includes('microsoft') || NAV.appName.toLowerCase().match(/trident/gi) !== null;
var IS_EDGE = exports.IS_EDGE = 'msLaunchUri' in NAV && !('documentMode' in _document2.default);
var IS_CHROME = exports.IS_CHROME = UA.match(/chrome/gi) !== null;
var IS_FIREFOX = exports.IS_FIREFOX = UA.match(/firefox/gi) !== null;
var IS_SAFARI = exports.IS_SAFARI = UA.match(/safari/gi) !== null && !IS_CHROME;
var IS_STOCK_ANDROID = exports.IS_STOCK_ANDROID = UA.match(/^mozilla\/\d+\.\d+\s\(linux;\su;/gi) !== null;
var HAS_MSE = exports.HAS_MSE = 'MediaSource' in _window2.default;
var SUPPORT_POINTER_EVENTS = exports.SUPPORT_POINTER_EVENTS = function () {
var element = _document2.default.createElement('x'),
documentElement = _document2.default.documentElement,
getComputedStyle = _window2.default.getComputedStyle;
if (!('pointerEvents' in element.style)) {
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
var supports = getComputedStyle && getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
}();
// for IE
var html5Elements = ['source', 'track', 'audio', 'video'];
var video = void 0;
for (var i = 0, il = html5Elements.length; i < il; i++) {
video = _document2.default.createElement(html5Elements[i]);
}
// Test if browsers support HLS natively (right now Safari, Android's Chrome and Stock browsers, and MS Edge)
var SUPPORTS_NATIVE_HLS = exports.SUPPORTS_NATIVE_HLS = IS_SAFARI || IS_ANDROID && (IS_CHROME || IS_STOCK_ANDROID) || IS_IE && UA.match(/edge/gi) !== null;
// Detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)
// iOS
var hasiOSFullScreen = video.webkitEnterFullscreen !== undefined;
// W3C
var hasNativeFullscreen = video.requestFullscreen !== undefined;
// OS X 10.5 can't do this even if it says it can :(
if (hasiOSFullScreen && UA.match(/mac os x 10_5/i)) {
hasNativeFullscreen = false;
hasiOSFullScreen = false;
}
// webkit/firefox/IE11+
var hasWebkitNativeFullScreen = video.webkitRequestFullScreen !== undefined;
var hasMozNativeFullScreen = video.mozRequestFullScreen !== undefined;
var hasMsNativeFullScreen = video.msRequestFullscreen !== undefined;
var hasTrueNativeFullScreen = hasWebkitNativeFullScreen || hasMozNativeFullScreen || hasMsNativeFullScreen;
var nativeFullScreenEnabled = hasTrueNativeFullScreen;
var fullScreenEventName = '';
var isFullScreen = void 0,
requestFullScreen = void 0,
cancelFullScreen = void 0;
// Enabled?
if (hasMozNativeFullScreen) {
nativeFullScreenEnabled = _document2.default.mozFullScreenEnabled;
} else if (hasMsNativeFullScreen) {
nativeFullScreenEnabled = _document2.default.msFullscreenEnabled;
}
if (IS_CHROME) {
hasiOSFullScreen = false;
}
if (hasTrueNativeFullScreen) {
if (hasWebkitNativeFullScreen) {
fullScreenEventName = 'webkitfullscreenchange';
} else if (hasMozNativeFullScreen) {
fullScreenEventName = 'mozfullscreenchange';
} else if (hasMsNativeFullScreen) {
fullScreenEventName = 'MSFullscreenChange';
}
exports.isFullScreen = isFullScreen = function isFullScreen() {
if (hasMozNativeFullScreen) {
return _document2.default.mozFullScreen;
} else if (hasWebkitNativeFullScreen) {
return _document2.default.webkitIsFullScreen;
} else if (hasMsNativeFullScreen) {
return _document2.default.msFullscreenElement !== null;
}
};
exports.requestFullScreen = requestFullScreen = function requestFullScreen(el) {
if (hasWebkitNativeFullScreen) {
el.webkitRequestFullScreen();
} else if (hasMozNativeFullScreen) {
el.mozRequestFullScreen();
} else if (hasMsNativeFullScreen) {
el.msRequestFullscreen();
}
};
exports.cancelFullScreen = cancelFullScreen = function cancelFullScreen() {
if (hasWebkitNativeFullScreen) {
_document2.default.webkitCancelFullScreen();
} else if (hasMozNativeFullScreen) {
_document2.default.mozCancelFullScreen();
} else if (hasMsNativeFullScreen) {
_document2.default.msExitFullscreen();
}
};
}
var HAS_NATIVE_FULLSCREEN = exports.HAS_NATIVE_FULLSCREEN = hasNativeFullscreen;
var HAS_WEBKIT_NATIVE_FULLSCREEN = exports.HAS_WEBKIT_NATIVE_FULLSCREEN = hasWebkitNativeFullScreen;
var HAS_MOZ_NATIVE_FULLSCREEN = exports.HAS_MOZ_NATIVE_FULLSCREEN = hasMozNativeFullScreen;
var HAS_MS_NATIVE_FULLSCREEN = exports.HAS_MS_NATIVE_FULLSCREEN = hasMsNativeFullScreen;
var HAS_IOS_FULLSCREEN = exports.HAS_IOS_FULLSCREEN = hasiOSFullScreen;
var HAS_TRUE_NATIVE_FULLSCREEN = exports.HAS_TRUE_NATIVE_FULLSCREEN = hasTrueNativeFullScreen;
var HAS_NATIVE_FULLSCREEN_ENABLED = exports.HAS_NATIVE_FULLSCREEN_ENABLED = nativeFullScreenEnabled;
var FULLSCREEN_EVENT_NAME = exports.FULLSCREEN_EVENT_NAME = fullScreenEventName;
exports.isFullScreen = isFullScreen;
exports.requestFullScreen = requestFullScreen;
exports.cancelFullScreen = cancelFullScreen;
_mejs2.default.Features = _mejs2.default.Features || {};
_mejs2.default.Features.isiPad = IS_IPAD;
_mejs2.default.Features.isiPhone = IS_IPHONE;
_mejs2.default.Features.isiOS = _mejs2.default.Features.isiPhone || _mejs2.default.Features.isiPad;
_mejs2.default.Features.isAndroid = IS_ANDROID;
_mejs2.default.Features.isIE = IS_IE;
_mejs2.default.Features.isEdge = IS_EDGE;
_mejs2.default.Features.isChrome = IS_CHROME;
_mejs2.default.Features.isFirefox = IS_FIREFOX;
_mejs2.default.Features.isSafari = IS_SAFARI;
_mejs2.default.Features.isStockAndroid = IS_STOCK_ANDROID;
_mejs2.default.Features.hasMSE = HAS_MSE;
_mejs2.default.Features.supportsNativeHLS = SUPPORTS_NATIVE_HLS;
_mejs2.default.Features.supportsPointerEvents = SUPPORT_POINTER_EVENTS;
_mejs2.default.Features.hasiOSFullScreen = HAS_IOS_FULLSCREEN;
_mejs2.default.Features.hasNativeFullscreen = HAS_NATIVE_FULLSCREEN;
_mejs2.default.Features.hasWebkitNativeFullScreen = HAS_WEBKIT_NATIVE_FULLSCREEN;
_mejs2.default.Features.hasMozNativeFullScreen = HAS_MOZ_NATIVE_FULLSCREEN;
_mejs2.default.Features.hasMsNativeFullScreen = HAS_MS_NATIVE_FULLSCREEN;
_mejs2.default.Features.hasTrueNativeFullScreen = HAS_TRUE_NATIVE_FULLSCREEN;
_mejs2.default.Features.nativeFullScreenEnabled = HAS_NATIVE_FULLSCREEN_ENABLED;
_mejs2.default.Features.fullScreenEventName = FULLSCREEN_EVENT_NAME;
_mejs2.default.Features.isFullScreen = isFullScreen;
_mejs2.default.Features.requestFullScreen = requestFullScreen;
_mejs2.default.Features.cancelFullScreen = cancelFullScreen;
},{"2":2,"3":3,"6":6}],16:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.escapeHTML = escapeHTML;
exports.debounce = debounce;
exports.isObjectEmpty = isObjectEmpty;
exports.splitEvents = splitEvents;
exports.createEvent = createEvent;
exports.isNodeAfter = isNodeAfter;
exports.isString = isString;
var _mejs = _dereq_(6);
var _mejs2 = _interopRequireDefault(_mejs);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
*
* @param {String} input
* @return {string}
*/
function escapeHTML(input) {
if (typeof input !== 'string') {
throw new Error('Argument passed must be a string');
}
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"'
};
return input.replace(/[&<>"]/g, function (c) {
return map[c];
});
}
// taken from underscore
function debounce(func, wait) {
var _this = this,
_arguments = arguments;
var immediate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (typeof func !== 'function') {
throw new Error('First argument must be a function');
}
if (typeof wait !== 'number') {
throw new Error('Second argument must be a numeric value');
}
var timeout = void 0;
return function () {
var context = _this,
args = _arguments;
var later = function later() {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
}
/**
* Determine if an object contains any elements
*
* @see http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object
* @param {Object} instance
* @return {Boolean}
*/
function isObjectEmpty(instance) {
return Object.getOwnPropertyNames(instance).length <= 0;
}
/**
* Group a string of events into `document` (d) and `window` (w) events
*
* @param {String} events List of space separated events
* @param {String} id Namespace appended to events
* @return {{d: Array, w: Array}}
*/
function splitEvents(events, id) {
// Global events
var rwindow = /^((after|before)print|(before)?unload|hashchange|message|o(ff|n)line|page(hide|show)|popstate|resize|storage)\b/;
// add player ID as an event namespace so it's easier to unbind them all later
var ret = { d: [], w: [] };
(events || '').split(' ').forEach(function (v) {
var eventName = v + '.' + id;
if (eventName.startsWith('.')) {
ret.d.push(eventName);
ret.w.push(eventName);
} else {
ret[rwindow.test(v) ? 'w' : 'd'].push(eventName);
}
});
ret.d = ret.d.join(' ');
ret.w = ret.w.join(' ');
return ret;
}
/**
*
* @param {string} eventName
* @param {*} target
* @return {Event|Object}
*/
function createEvent(eventName, target) {
if (typeof eventName !== 'string') {
throw new Error('Event name must be a string');
}
var event = void 0;
if (document.createEvent) {
event = document.createEvent('Event');
event.initEvent(eventName, true, false);
} else {
event = {};
event.type = eventName;
event.target = target;
event.canceleable = true;
event.bubbable = false;
}
return event;
}
/**
* Returns true if targetNode appears after sourceNode in the dom.
* @param {HTMLElement} sourceNode - the source node for comparison
* @param {HTMLElement} targetNode - the node to compare against sourceNode
*/
function isNodeAfter(sourceNode, targetNode) {
return !!(sourceNode && targetNode && sourceNode.compareDocumentPosition(targetNode) && Node.DOCUMENT_POSITION_PRECEDING);
}
/**
* Determines if a value is a string
*
* @param {*} value to check
* @returns {Boolean} True if a value is a string
*/
function isString(value) {
return typeof value === 'string';
}
_mejs2.default.Utils = _mejs2.default.Utils || {};
_mejs2.default.Utils.escapeHTML = escapeHTML;
_mejs2.default.Utils.debounce = debounce;
_mejs2.default.Utils.isObjectEmpty = isObjectEmpty;
_mejs2.default.Utils.splitEvents = splitEvents;
_mejs2.default.Utils.createEvent = createEvent;
_mejs2.default.Utils.isNodeAfter = isNodeAfter;
_mejs2.default.Utils.isString = isString;
},{"6":6}],17:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.typeChecks = undefined;
exports.absolutizeUrl = absolutizeUrl;
exports.formatType = formatType;
exports.getMimeFromType = getMimeFromType;
exports.getTypeFromFile = getTypeFromFile;
exports.getExtension = getExtension;
exports.normalizeExtension = normalizeExtension;
var _mejs = _dereq_(6);
var _mejs2 = _interopRequireDefault(_mejs);
var _general = _dereq_(16);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var typeChecks = exports.typeChecks = [];
/**
*
* @param {String} url
* @return {String}
*/
function absolutizeUrl(url) {
if (typeof url !== 'string') {
throw new Error('`url` argument must be a string');
}
var el = document.createElement('div');
el.innerHTML = '<a href="' + (0, _general.escapeHTML)(url) + '">x</a>';
return el.firstChild.href;
}
/**
* Get the format of a specific media, based on URL and additionally its mime type
*
* @param {String} url
* @param {String} type
* @return {String}
*/
function formatType(url) {
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
return url && !type ? getTypeFromFile(url) : getMimeFromType(type);
}
/**
* Return the mime part of the type in case the attribute contains the codec
* (`video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`)
*
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
* @param {String} type
* @return {String}
*/
function getMimeFromType(type) {
if (typeof type !== 'string') {
throw new Error('`type` argument must be a string');
}
return type && ~type.indexOf(';') ? type.substr(0, type.indexOf(';')) : type;
}
/**
* Get the type of media based on URL structure
*
* @param {String} url
* @return {String}
*/
function getTypeFromFile(url) {
if (typeof url !== 'string') {
throw new Error('`url` argument must be a string');
}
var i = void 0,
il = void 0,
type = void 0;
// Validate `typeChecks` array
if (!Array.isArray(typeChecks)) {
throw new Error('`typeChecks` must be an array');
}
if (typeChecks.length) {
for (i = 0, il = typeChecks.length; i < il; i++) {
var _type = typeChecks[i];
if (typeof _type !== 'function') {
throw new Error('Element in array must be a function');
}
}
}
// do type checks first
for (i = 0, il = typeChecks.length; i < il; i++) {
type = typeChecks[i](url);
if (type !== undefined && type !== null) {
return type;
}
}
// the do standard extension check
var ext = getExtension(url),
normalizedExt = normalizeExtension(ext);
var mime = 'video/mp4';
// Obtain correct MIME types
if (normalizedExt) {
if (['mp4', 'm4v', 'ogg', 'ogv', 'webm', 'flv', 'mpeg', 'mov'].includes(normalizedExt)) {
mime = 'video/' + normalizedExt;
} else if (['mp3', 'oga', 'wav', 'mid', 'midi'].includes(normalizedExt)) {
mime = 'audio/' + normalizedExt;
}
}
return mime;
}
/**
* Get media file extension from URL
*
* @param {String} url
* @return {String}
*/
function getExtension(url) {
if (typeof url !== 'string') {
throw new Error('`url` argument must be a string');
}
var baseUrl = url.split('?')[0],
baseName = baseUrl.split('\\').pop().split('/').pop();
return baseName.indexOf('.') > -1 ? baseName.substring(baseName.lastIndexOf('.') + 1) : '';
}
/**
* Get standard extension of a media file
*
* @param {String} extension
* @return {String}
*/
function normalizeExtension(extension) {
if (typeof extension !== 'string') {
throw new Error('`extension` argument must be a string');
}
switch (extension) {
case 'mp4':
case 'm4v':
return 'mp4';
case 'webm':
case 'webma':
case 'webmv':
return 'webm';
case 'ogg':
case 'oga':
case 'ogv':
return 'ogg';
default:
return extension;
}
}
_mejs2.default.Utils = _mejs2.default.Utils || {};
_mejs2.default.Utils.typeChecks = typeChecks;
_mejs2.default.Utils.absolutizeUrl = absolutizeUrl;
_mejs2.default.Utils.formatType = formatType;
_mejs2.default.Utils.getMimeFromType = getMimeFromType;
_mejs2.default.Utils.getTypeFromFile = getTypeFromFile;
_mejs2.default.Utils.getExtension = getExtension;
_mejs2.default.Utils.normalizeExtension = normalizeExtension;
},{"16":16,"6":6}],18:[function(_dereq_,module,exports){
'use strict';
var _document = _dereq_(2);
var _document2 = _interopRequireDefault(_document);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Polyfill
*
* Mimics the missing methods like Object.assign, Array.includes, etc., as a way to avoid including the whole list
* of polyfills provided by Babel.
*/
// IE6,7,8
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement, fromIndex) {
var k = void 0;
// 1. const O be the result of calling ToObject passing
// the this value as the argument.
if (undefined === undefined || undefined === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(undefined);
// 2. const lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. const len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed const n be
// ToInteger(fromIndex); else const n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then const k be n.
// 8. Else, n<0, const k be len - abs(n).
// If k is less than 0, then const k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. const Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. const kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. const elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. const same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
// document.createEvent for IE8 or other old browsers that do not implement it
// Reference: https://github.com/WebReflection/ie8/blob/master/build/ie8.max.js
if (_document2.default.createEvent === undefined) {
_document2.default.createEvent = function () {
var e = _document2.default.createEventObject();
e.timeStamp = new Date().getTime();
e.enumerable = true;
e.writable = true;
e.configurable = true;
e.initEvent = function (type, bubbles, cancelable) {
undefined.type = type;
undefined.bubbles = !!bubbles;
undefined.cancelable = !!cancelable;
if (!undefined.bubbles) {
undefined.stopPropagation = function () {
undefined.stoppedPropagation = true;
undefined.cancelBubble = true;
};
}
};
return e;
};
}
// Object.assign polyfill
// Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill
if (typeof Object.assign !== 'function') {
Object.assign = function (target) {
// .length of function is 2
if (target === null || target === undefined) {
// TypeError if undefined or null
throw new TypeError('Cannot convert undefined or null to object');
}
var to = Object(target);
for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index];
if (nextSource !== null) {
// Skip over if undefined or null
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
};
}
// Array.includes polyfill
// Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Polyfill
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
value: function value(searchElement, fromIndex) {
// 1. const O be ? ToObject(this value).
if (this === null || this === undefined) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. const len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If len is 0, return false.
if (len === 0) {
return false;
}
// 4. const n be ? ToInteger(fromIndex).
// (If fromIndex is undefined, this step produces the value 0.)
var n = fromIndex | 0;
// 5. If n ≥ 0, then
// a. const k be n.
// 6. Else n < 0,
// a. const k be len + n.
// b. If k < 0, const k be 0.
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 7. Repeat, while k < len
while (k < len) {
// a. const elementK be the result of ? Get(O, ! ToString(k)).
// b. If SameValueZero(searchElement, elementK) is true, return true.
// c. Increase k by 1.
// NOTE: === provides the correct "SameValueZero" comparison needed here.
if (o[k] === searchElement) {
return true;
}
k++;
}
// 8. Return false
return false;
}
});
}
if (!String.prototype.includes) {
String.prototype.includes = function () {
return String.prototype.indexOf.apply(this, arguments) !== -1;
};
}
// String.startsWith polyfill
// Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith#Polyfill
if (!String.prototype.startsWith) {
String.prototype.startsWith = function (searchString, position) {
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
}
},{"2":2}]},{},[18,5,4,8,13,10,9,11,12,14]);
|
module.exports = require("npm:https-browserify@0.0.0/index"); |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'sourcearea', 'fo', {
toolbar: 'Kelda'
} );
|
(function ($) {
$.Redactor.opts.langs['zh-CN'] = {
html: 'HTML代码',
video: '视频',
image: '图片',
table: '表格',
link: '链接',
link_insert: '插入链接',
link_edit: 'Edit link',
unlink: '取消链接',
formatting: '样式',
paragraph: '段落',
quote: '引用',
code: '代码',
header1: '一级标题',
header2: '二级标题',
header3: '三级标题',
header4: '四级标题',
header5: 'Header 5',
bold: '粗体',
italic: '斜体',
fontcolor: '字体颜色',
backcolor: '背景颜色',
unorderedlist: '项目编号',
orderedlist: '数字编号',
outdent: '减少缩进',
indent: '增加缩进',
cancel: '取消',
insert: '插入',
save: '保存',
_delete: '删除',
insert_table: '插入表格',
insert_row_above: '在上方插入',
insert_row_below: '在下方插入',
insert_column_left: '在左侧插入',
insert_column_right: '在右侧插入',
delete_column: '删除整列',
delete_row: '删除整行',
delete_table: '删除表格',
rows: '行',
columns: '列',
add_head: '添加标题',
delete_head: '删除标题',
title: '标题',
image_position: '位置',
none: '无',
left: '左',
right: '右',
image_web_link: '图片网页链接',
text: '文本',
mailto: '邮箱',
web: '网址',
video_html_code: '视频嵌入代码',
file: '文件',
upload: '上传',
download: '下载',
choose: '选择',
or_choose: '或选择',
drop_file_here: '将文件拖拽至此区域',
align_left: '左对齐',
align_center: '居中',
align_right: '右对齐',
align_justify: '两端对齐',
horizontalrule: '水平线',
fullscreen: '全屏',
deleted: '删除',
anchor: '锚点',
link_new_tab: 'Open link in new tab',
underline: 'Underline',
alignment: 'Alignment',
filename: 'Name (optional)',
edit: 'Edit',
center: 'Center'
};
})( jQuery );
|
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'flash', 'da', {
access: 'Scriptadgang',
accessAlways: 'Altid',
accessNever: 'Aldrig',
accessSameDomain: 'Samme domæne',
alignAbsBottom: 'Absolut nederst',
alignAbsMiddle: 'Absolut centreret',
alignBaseline: 'Grundlinje',
alignTextTop: 'Toppen af teksten',
bgcolor: 'Baggrundsfarve',
chkFull: 'Tillad fuldskærm',
chkLoop: 'Gentagelse',
chkMenu: 'Vis Flash-menu',
chkPlay: 'Automatisk afspilning',
flashvars: 'Variabler for Flash',
hSpace: 'Vandret margen',
properties: 'Egenskaber for Flash',
propertiesTab: 'Egenskaber',
quality: 'Kvalitet',
qualityAutoHigh: 'Auto høj',
qualityAutoLow: 'Auto lav',
qualityBest: 'Bedste',
qualityHigh: 'Høj',
qualityLow: 'Lav',
qualityMedium: 'Medium',
scale: 'Skalér',
scaleAll: 'Vis alt',
scaleFit: 'Tilpas størrelse',
scaleNoBorder: 'Ingen ramme',
title: 'Egenskaber for Flash',
vSpace: 'Lodret margen',
validateHSpace: 'Vandret margen skal være et tal.',
validateSrc: 'Indtast hyperlink URL!',
validateVSpace: 'Lodret margen skal være et tal.',
windowMode: 'Vinduestilstand',
windowModeOpaque: 'Gennemsigtig (opaque)',
windowModeTransparent: 'Transparent',
windowModeWindow: 'Vindue'
} );
|
//This is dummy file. To commit unnittest-files folder git needs a file.
|
module.exports = function(hljs) {
var RUBY_METHOD_RE = '[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?';
var RUBY_KEYWORDS = {
keyword:
'and then defined module in return redo if BEGIN retry end for self when ' +
'next until do begin unless END rescue else break undef not super class case ' +
'require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor',
literal:
'true false nil'
};
var YARDOCTAG = {
className: 'doctag',
begin: '@[A-Za-z]+'
};
var IRB_OBJECT = {
begin: '#<', end: '>'
};
var COMMENT_MODES = [
hljs.COMMENT(
'#',
'$',
{
contains: [YARDOCTAG]
}
),
hljs.COMMENT(
'^\\=begin',
'^\\=end',
{
contains: [YARDOCTAG],
relevance: 10
}
),
hljs.COMMENT('^__END__', '\\n$')
];
var SUBST = {
className: 'subst',
begin: '#\\{', end: '}',
keywords: RUBY_KEYWORDS
};
var STRING = {
className: 'string',
contains: [hljs.BACKSLASH_ESCAPE, SUBST],
variants: [
{begin: /'/, end: /'/},
{begin: /"/, end: /"/},
{begin: /`/, end: /`/},
{begin: '%[qQwWx]?\\(', end: '\\)'},
{begin: '%[qQwWx]?\\[', end: '\\]'},
{begin: '%[qQwWx]?{', end: '}'},
{begin: '%[qQwWx]?<', end: '>'},
{begin: '%[qQwWx]?/', end: '/'},
{begin: '%[qQwWx]?%', end: '%'},
{begin: '%[qQwWx]?-', end: '-'},
{begin: '%[qQwWx]?\\|', end: '\\|'},
{
// \B in the beginning suppresses recognition of ?-sequences where ?
// is the last character of a preceding identifier, as in: `func?4`
begin: /\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/
}
]
};
var PARAMS = {
className: 'params',
begin: '\\(', end: '\\)', endsParent: true,
keywords: RUBY_KEYWORDS
};
var RUBY_DEFAULT_CONTAINS = [
STRING,
IRB_OBJECT,
{
className: 'class',
beginKeywords: 'class module', end: '$|;',
illegal: /=/,
contains: [
hljs.inherit(hljs.TITLE_MODE, {begin: '[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?'}),
{
begin: '<\\s*',
contains: [{
begin: '(' + hljs.IDENT_RE + '::)?' + hljs.IDENT_RE
}]
}
].concat(COMMENT_MODES)
},
{
className: 'function',
beginKeywords: 'def', end: '$|;',
contains: [
hljs.inherit(hljs.TITLE_MODE, {begin: RUBY_METHOD_RE}),
PARAMS
].concat(COMMENT_MODES)
},
{
// swallow namespace qualifiers before symbols
begin: hljs.IDENT_RE + '::'
},
{
className: 'symbol',
begin: hljs.UNDERSCORE_IDENT_RE + '(\\!|\\?)?:',
relevance: 0
},
{
className: 'symbol',
begin: ':(?!\\s)',
contains: [STRING, {begin: RUBY_METHOD_RE}],
relevance: 0
},
{
className: 'number',
begin: '(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b',
relevance: 0
},
{
begin: '(\\$\\W)|((\\$|\\@\\@?)(\\w+))' // variables
},
{
className: 'params',
begin: /\|/, end: /\|/,
keywords: RUBY_KEYWORDS
},
{ // regexp container
begin: '(' + hljs.RE_STARTERS_RE + ')\\s*',
contains: [
IRB_OBJECT,
{
className: 'regexp',
contains: [hljs.BACKSLASH_ESCAPE, SUBST],
illegal: /\n/,
variants: [
{begin: '/', end: '/[a-z]*'},
{begin: '%r{', end: '}[a-z]*'},
{begin: '%r\\(', end: '\\)[a-z]*'},
{begin: '%r!', end: '![a-z]*'},
{begin: '%r\\[', end: '\\][a-z]*'}
]
}
].concat(COMMENT_MODES),
relevance: 0
}
].concat(COMMENT_MODES);
SUBST.contains = RUBY_DEFAULT_CONTAINS;
PARAMS.contains = RUBY_DEFAULT_CONTAINS;
var SIMPLE_PROMPT = "[>?]>";
var DEFAULT_PROMPT = "[\\w#]+\\(\\w+\\):\\d+:\\d+>";
var RVM_PROMPT = "(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>";
var IRB_DEFAULT = [
{
begin: /^\s*=>/,
starts: {
end: '$', contains: RUBY_DEFAULT_CONTAINS
}
},
{
className: 'meta',
begin: '^('+SIMPLE_PROMPT+"|"+DEFAULT_PROMPT+'|'+RVM_PROMPT+')',
starts: {
end: '$', contains: RUBY_DEFAULT_CONTAINS
}
}
];
return {
aliases: ['rb', 'gemspec', 'podspec', 'thor', 'irb'],
keywords: RUBY_KEYWORDS,
illegal: /\/\*/,
contains: COMMENT_MODES.concat(IRB_DEFAULT).concat(RUBY_DEFAULT_CONTAINS)
};
}; |
jQuery.extend(jQuery.validator.messages,{required:"Ovo polje je obavezno.",remote:"Ovo polje treba popraviti.",email:"Unesite ispravnu e-mail adresu.",url:"Unesite ispravan URL.",date:"Unesite ispravan datum.",dateISO:"Unesite ispravan datum (ISO).",number:"Unesite ispravan broj.",digits:"Unesite samo brojeve.",creditcard:"Unesite ispravan broj kreditne kartice.",equalTo:"Unesite ponovo istu vrijednost.",accept:"Unesite vrijednost sa ispravnom ekstenzijom.",maxlength:$.validator.format("Maksimalni broj znakova je {0} ."),minlength:$.validator.format("Minimalni broj znakova je {0} ."),rangelength:$.validator.format("Unesite vrijednost između {0} i {1} znakova."),range:$.validator.format("Unesite vrijednost između {0} i {1}."),max:$.validator.format("Unesite vrijednost manju ili jednaku {0}."),min:$.validator.format("Unesite vrijednost veću ili jednaku {0}.")});
//# sourceMappingURL=messages_hr.min.js.map |
define(function () {
return function () {
describe('PubSub', function () {
it('listen() without context', function (done) {
$.listen('foo', function (arg) {
expect(arg).to.be('bar');
done();
});
$.emit('foo', 'bar');
});
it('listen() with context', function (done) {
var obj = { foo: function (bar) { return 'foo' + bar; } };
$.listen('foo', obj, function (arg) {
expect(this.foo(arg)).to.be('foobar');
done();
});
$.emit('foo', 'bar');
});
it('listenTo() ParsleyField', function (done) {
$('body').append('<input type="text" id="element" />');
$('body').append('<input type="text" id="element2" />');
var instance = $('#element').psly();
$.listenTo(instance, 'foo', function (parsleyInstance) {
expect(parsleyInstance.__id__).to.be(instance.__id__);
done();
});
$.emit('foo', 'bar');
$.emit('foo', $('#element2').psly());
$.emit('foo', instance);
});
it('listenTo() ParsleyForm will listen to Form', function (done) {
$('body').append(
'<form id="element" data-parsley-trigger="change">' +
'<input id="field1" type="text" data-parsley-required="true" />' +
'<div id="field2"></div>' +
'<textarea id="field3" data-parsley-notblank="true"></textarea>' +
'</form>');
$.listenTo($('#element').psly(), 'foo', function (parsleyInstance) {
expect($('#element').psly().__id__ === parsleyInstance.__id__);
done();
});
$.emit('foo', $('#element').psly());
});
it('listenTo() Form will listen to its fields too', function (done) {
$('body').append(
'<form id="element" data-parsley-trigger="change">' +
'<input id="field1" type="text" data-parsley-required="true" />' +
'<div id="field2"></div>' +
'<textarea id="field3" data-parsley-notblank="true"></textarea>' +
'</form>');
$.listenTo($('#element').psly(), 'foo', function (instance) {
done();
});
$.emit('foo', $('#field1').psly());
});
it('unsubscribeTo()', function () {
$('body').append('<input type="text" id="element" />');
$.listen('foo', $.noop);
$.listenTo($('#element').psly(), 'foo', $.noop);
expect($.subscribed()).to.have.key('foo');
expect($.subscribed().foo.length).to.be(2);
$.unsubscribeTo($('#element').psly(), 'foo');
expect($.subscribed().foo.length).to.be(1);
});
it('unsubscribe()', function () {
$.listen('foo', $.noop);
expect($.subscribed()).to.have.key('foo');
expect($.subscribed().foo.length).to.be(1);
$.unsubscribe('foo', $.noop);
expect($.subscribed().foo.length).to.be(0);
});
afterEach(function () {
if ($('#element').length)
$('#element').remove();
if ($('#element2').length)
$('#element2').remove();
$.unsubscribeAll('foo');
});
});
};
});
|
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'pagebreak', 'da', {
alt: 'Sideskift',
toolbar: 'Indsæt sideskift'
} );
|
;/*! showdown 17-12-2016 */
(function(){
/**
* Created by Tivie on 13-07-2015.
*/
function getDefaultOpts(simple) {
'use strict';
var defaultOptions = {
omitExtraWLInCodeBlocks: {
defaultValue: false,
describe: 'Omit the default extra whiteline added to code blocks',
type: 'boolean'
},
noHeaderId: {
defaultValue: false,
describe: 'Turn on/off generated header id',
type: 'boolean'
},
prefixHeaderId: {
defaultValue: false,
describe: 'Specify a prefix to generated header ids',
type: 'string'
},
headerLevelStart: {
defaultValue: false,
describe: 'The header blocks level start',
type: 'integer'
},
parseImgDimensions: {
defaultValue: false,
describe: 'Turn on/off image dimension parsing',
type: 'boolean'
},
simplifiedAutoLink: {
defaultValue: false,
describe: 'Turn on/off GFM autolink style',
type: 'boolean'
},
excludeTrailingPunctuationFromURLs: {
defaultValue: false,
describe: 'Excludes trailing punctuation from links generated with autoLinking',
type: 'boolean'
},
literalMidWordUnderscores: {
defaultValue: false,
describe: 'Parse midword underscores as literal underscores',
type: 'boolean'
},
strikethrough: {
defaultValue: false,
describe: 'Turn on/off strikethrough support',
type: 'boolean'
},
tables: {
defaultValue: false,
describe: 'Turn on/off tables support',
type: 'boolean'
},
tablesHeaderId: {
defaultValue: false,
describe: 'Add an id to table headers',
type: 'boolean'
},
ghCodeBlocks: {
defaultValue: true,
describe: 'Turn on/off GFM fenced code blocks support',
type: 'boolean'
},
tasklists: {
defaultValue: false,
describe: 'Turn on/off GFM tasklist support',
type: 'boolean'
},
smoothLivePreview: {
defaultValue: false,
describe: 'Prevents weird effects in live previews due to incomplete input',
type: 'boolean'
},
smartIndentationFix: {
defaultValue: false,
description: 'Tries to smartly fix indentation in es6 strings',
type: 'boolean'
},
disableForced4SpacesIndentedSublists: {
defaultValue: false,
description: 'Disables the requirement of indenting nested sublists by 4 spaces',
type: 'boolean'
},
simpleLineBreaks: {
defaultValue: false,
description: 'Parses simple line breaks as <br> (GFM Style)',
type: 'boolean'
}
};
if (simple === false) {
return JSON.parse(JSON.stringify(defaultOptions));
}
var ret = {};
for (var opt in defaultOptions) {
if (defaultOptions.hasOwnProperty(opt)) {
ret[opt] = defaultOptions[opt].defaultValue;
}
}
return ret;
}
/**
* Created by Tivie on 06-01-2015.
*/
// Private properties
var showdown = {},
parsers = {},
extensions = {},
globalOptions = getDefaultOpts(true),
flavor = {
github: {
omitExtraWLInCodeBlocks: true,
prefixHeaderId: 'user-content-',
simplifiedAutoLink: true,
excludeTrailingPunctuationFromURLs: true,
literalMidWordUnderscores: true,
strikethrough: true,
tables: true,
tablesHeaderId: true,
ghCodeBlocks: true,
tasklists: true,
disableForced4SpacesIndentedSublists: true,
simpleLineBreaks: true
},
vanilla: getDefaultOpts(true)
};
/**
* helper namespace
* @type {{}}
*/
showdown.helper = {};
/**
* TODO LEGACY SUPPORT CODE
* @type {{}}
*/
showdown.extensions = {};
/**
* Set a global option
* @static
* @param {string} key
* @param {*} value
* @returns {showdown}
*/
showdown.setOption = function (key, value) {
'use strict';
globalOptions[key] = value;
return this;
};
/**
* Get a global option
* @static
* @param {string} key
* @returns {*}
*/
showdown.getOption = function (key) {
'use strict';
return globalOptions[key];
};
/**
* Get the global options
* @static
* @returns {{}}
*/
showdown.getOptions = function () {
'use strict';
return globalOptions;
};
/**
* Reset global options to the default values
* @static
*/
showdown.resetOptions = function () {
'use strict';
globalOptions = getDefaultOpts(true);
};
/**
* Set the flavor showdown should use as default
* @param {string} name
*/
showdown.setFlavor = function (name) {
'use strict';
if (flavor.hasOwnProperty(name)) {
var preset = flavor[name];
for (var option in preset) {
if (preset.hasOwnProperty(option)) {
globalOptions[option] = preset[option];
}
}
}
};
/**
* Get the default options
* @static
* @param {boolean} [simple=true]
* @returns {{}}
*/
showdown.getDefaultOptions = function (simple) {
'use strict';
return getDefaultOpts(simple);
};
/**
* Get or set a subParser
*
* subParser(name) - Get a registered subParser
* subParser(name, func) - Register a subParser
* @static
* @param {string} name
* @param {function} [func]
* @returns {*}
*/
showdown.subParser = function (name, func) {
'use strict';
if (showdown.helper.isString(name)) {
if (typeof func !== 'undefined') {
parsers[name] = func;
} else {
if (parsers.hasOwnProperty(name)) {
return parsers[name];
} else {
throw Error('SubParser named ' + name + ' not registered!');
}
}
}
};
/**
* Gets or registers an extension
* @static
* @param {string} name
* @param {object|function=} ext
* @returns {*}
*/
showdown.extension = function (name, ext) {
'use strict';
if (!showdown.helper.isString(name)) {
throw Error('Extension \'name\' must be a string');
}
name = showdown.helper.stdExtName(name);
// Getter
if (showdown.helper.isUndefined(ext)) {
if (!extensions.hasOwnProperty(name)) {
throw Error('Extension named ' + name + ' is not registered!');
}
return extensions[name];
// Setter
} else {
// Expand extension if it's wrapped in a function
if (typeof ext === 'function') {
ext = ext();
}
// Ensure extension is an array
if (!showdown.helper.isArray(ext)) {
ext = [ext];
}
var validExtension = validate(ext, name);
if (validExtension.valid) {
extensions[name] = ext;
} else {
throw Error(validExtension.error);
}
}
};
/**
* Gets all extensions registered
* @returns {{}}
*/
showdown.getAllExtensions = function () {
'use strict';
return extensions;
};
/**
* Remove an extension
* @param {string} name
*/
showdown.removeExtension = function (name) {
'use strict';
delete extensions[name];
};
/**
* Removes all extensions
*/
showdown.resetExtensions = function () {
'use strict';
extensions = {};
};
/**
* Validate extension
* @param {array} extension
* @param {string} name
* @returns {{valid: boolean, error: string}}
*/
function validate(extension, name) {
'use strict';
var errMsg = (name) ? 'Error in ' + name + ' extension->' : 'Error in unnamed extension',
ret = {
valid: true,
error: ''
};
if (!showdown.helper.isArray(extension)) {
extension = [extension];
}
for (var i = 0; i < extension.length; ++i) {
var baseMsg = errMsg + ' sub-extension ' + i + ': ',
ext = extension[i];
if (typeof ext !== 'object') {
ret.valid = false;
ret.error = baseMsg + 'must be an object, but ' + typeof ext + ' given';
return ret;
}
if (!showdown.helper.isString(ext.type)) {
ret.valid = false;
ret.error = baseMsg + 'property "type" must be a string, but ' + typeof ext.type + ' given';
return ret;
}
var type = ext.type = ext.type.toLowerCase();
// normalize extension type
if (type === 'language') {
type = ext.type = 'lang';
}
if (type === 'html') {
type = ext.type = 'output';
}
if (type !== 'lang' && type !== 'output' && type !== 'listener') {
ret.valid = false;
ret.error = baseMsg + 'type ' + type + ' is not recognized. Valid values: "lang/language", "output/html" or "listener"';
return ret;
}
if (type === 'listener') {
if (showdown.helper.isUndefined(ext.listeners)) {
ret.valid = false;
ret.error = baseMsg + '. Extensions of type "listener" must have a property called "listeners"';
return ret;
}
} else {
if (showdown.helper.isUndefined(ext.filter) && showdown.helper.isUndefined(ext.regex)) {
ret.valid = false;
ret.error = baseMsg + type + ' extensions must define either a "regex" property or a "filter" method';
return ret;
}
}
if (ext.listeners) {
if (typeof ext.listeners !== 'object') {
ret.valid = false;
ret.error = baseMsg + '"listeners" property must be an object but ' + typeof ext.listeners + ' given';
return ret;
}
for (var ln in ext.listeners) {
if (ext.listeners.hasOwnProperty(ln)) {
if (typeof ext.listeners[ln] !== 'function') {
ret.valid = false;
ret.error = baseMsg + '"listeners" property must be an hash of [event name]: [callback]. listeners.' + ln +
' must be a function but ' + typeof ext.listeners[ln] + ' given';
return ret;
}
}
}
}
if (ext.filter) {
if (typeof ext.filter !== 'function') {
ret.valid = false;
ret.error = baseMsg + '"filter" must be a function, but ' + typeof ext.filter + ' given';
return ret;
}
} else if (ext.regex) {
if (showdown.helper.isString(ext.regex)) {
ext.regex = new RegExp(ext.regex, 'g');
}
if (!ext.regex instanceof RegExp) {
ret.valid = false;
ret.error = baseMsg + '"regex" property must either be a string or a RegExp object, but ' + typeof ext.regex + ' given';
return ret;
}
if (showdown.helper.isUndefined(ext.replace)) {
ret.valid = false;
ret.error = baseMsg + '"regex" extensions must implement a replace string or function';
return ret;
}
}
}
return ret;
}
/**
* Validate extension
* @param {object} ext
* @returns {boolean}
*/
showdown.validateExtension = function (ext) {
'use strict';
var validateExtension = validate(ext, null);
if (!validateExtension.valid) {
console.warn(validateExtension.error);
return false;
}
return true;
};
/**
* showdownjs helper functions
*/
if (!showdown.hasOwnProperty('helper')) {
showdown.helper = {};
}
/**
* Check if var is string
* @static
* @param {string} a
* @returns {boolean}
*/
showdown.helper.isString = function isString(a) {
'use strict';
return (typeof a === 'string' || a instanceof String);
};
/**
* Check if var is a function
* @static
* @param {string} a
* @returns {boolean}
*/
showdown.helper.isFunction = function isFunction(a) {
'use strict';
var getType = {};
return a && getType.toString.call(a) === '[object Function]';
};
/**
* ForEach helper function
* @static
* @param {*} obj
* @param {function} callback
*/
showdown.helper.forEach = function forEach(obj, callback) {
'use strict';
if (typeof obj.forEach === 'function') {
obj.forEach(callback);
} else {
for (var i = 0; i < obj.length; i++) {
callback(obj[i], i, obj);
}
}
};
/**
* isArray helper function
* @static
* @param {*} a
* @returns {boolean}
*/
showdown.helper.isArray = function isArray(a) {
'use strict';
return a.constructor === Array;
};
/**
* Check if value is undefined
* @static
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
*/
showdown.helper.isUndefined = function isUndefined(value) {
'use strict';
return typeof value === 'undefined';
};
/**
* Standardidize extension name
* @static
* @param {string} s extension name
* @returns {string}
*/
showdown.helper.stdExtName = function (s) {
'use strict';
return s.replace(/[_-]||\s/g, '').toLowerCase();
};
function escapeCharactersCallback(wholeMatch, m1) {
'use strict';
var charCodeToEscape = m1.charCodeAt(0);
return '~E' + charCodeToEscape + 'E';
}
/**
* Callback used to escape characters when passing through String.replace
* @static
* @param {string} wholeMatch
* @param {string} m1
* @returns {string}
*/
showdown.helper.escapeCharactersCallback = escapeCharactersCallback;
/**
* Escape characters in a string
* @static
* @param {string} text
* @param {string} charsToEscape
* @param {boolean} afterBackslash
* @returns {XML|string|void|*}
*/
showdown.helper.escapeCharacters = function escapeCharacters(text, charsToEscape, afterBackslash) {
'use strict';
// First we have to escape the escape characters so that
// we can build a character class out of them
var regexString = '([' + charsToEscape.replace(/([\[\]\\])/g, '\\$1') + '])';
if (afterBackslash) {
regexString = '\\\\' + regexString;
}
var regex = new RegExp(regexString, 'g');
text = text.replace(regex, escapeCharactersCallback);
return text;
};
var rgxFindMatchPos = function (str, left, right, flags) {
'use strict';
var f = flags || '',
g = f.indexOf('g') > -1,
x = new RegExp(left + '|' + right, 'g' + f.replace(/g/g, '')),
l = new RegExp(left, f.replace(/g/g, '')),
pos = [],
t, s, m, start, end;
do {
t = 0;
while ((m = x.exec(str))) {
if (l.test(m[0])) {
if (!(t++)) {
s = x.lastIndex;
start = s - m[0].length;
}
} else if (t) {
if (!--t) {
end = m.index + m[0].length;
var obj = {
left: {start: start, end: s},
match: {start: s, end: m.index},
right: {start: m.index, end: end},
wholeMatch: {start: start, end: end}
};
pos.push(obj);
if (!g) {
return pos;
}
}
}
}
} while (t && (x.lastIndex = s));
return pos;
};
/**
* matchRecursiveRegExp
*
* (c) 2007 Steven Levithan <stevenlevithan.com>
* MIT License
*
* Accepts a string to search, a left and right format delimiter
* as regex patterns, and optional regex flags. Returns an array
* of matches, allowing nested instances of left/right delimiters.
* Use the "g" flag to return all matches, otherwise only the
* first is returned. Be careful to ensure that the left and
* right format delimiters produce mutually exclusive matches.
* Backreferences are not supported within the right delimiter
* due to how it is internally combined with the left delimiter.
* When matching strings whose format delimiters are unbalanced
* to the left or right, the output is intentionally as a
* conventional regex library with recursion support would
* produce, e.g. "<<x>" and "<x>>" both produce ["x"] when using
* "<" and ">" as the delimiters (both strings contain a single,
* balanced instance of "<x>").
*
* examples:
* matchRecursiveRegExp("test", "\\(", "\\)")
* returns: []
* matchRecursiveRegExp("<t<<e>><s>>t<>", "<", ">", "g")
* returns: ["t<<e>><s>", ""]
* matchRecursiveRegExp("<div id=\"x\">test</div>", "<div\\b[^>]*>", "</div>", "gi")
* returns: ["test"]
*/
showdown.helper.matchRecursiveRegExp = function (str, left, right, flags) {
'use strict';
var matchPos = rgxFindMatchPos (str, left, right, flags),
results = [];
for (var i = 0; i < matchPos.length; ++i) {
results.push([
str.slice(matchPos[i].wholeMatch.start, matchPos[i].wholeMatch.end),
str.slice(matchPos[i].match.start, matchPos[i].match.end),
str.slice(matchPos[i].left.start, matchPos[i].left.end),
str.slice(matchPos[i].right.start, matchPos[i].right.end)
]);
}
return results;
};
/**
*
* @param {string} str
* @param {string|function} replacement
* @param {string} left
* @param {string} right
* @param {string} flags
* @returns {string}
*/
showdown.helper.replaceRecursiveRegExp = function (str, replacement, left, right, flags) {
'use strict';
if (!showdown.helper.isFunction(replacement)) {
var repStr = replacement;
replacement = function () {
return repStr;
};
}
var matchPos = rgxFindMatchPos(str, left, right, flags),
finalStr = str,
lng = matchPos.length;
if (lng > 0) {
var bits = [];
if (matchPos[0].wholeMatch.start !== 0) {
bits.push(str.slice(0, matchPos[0].wholeMatch.start));
}
for (var i = 0; i < lng; ++i) {
bits.push(
replacement(
str.slice(matchPos[i].wholeMatch.start, matchPos[i].wholeMatch.end),
str.slice(matchPos[i].match.start, matchPos[i].match.end),
str.slice(matchPos[i].left.start, matchPos[i].left.end),
str.slice(matchPos[i].right.start, matchPos[i].right.end)
)
);
if (i < lng - 1) {
bits.push(str.slice(matchPos[i].wholeMatch.end, matchPos[i + 1].wholeMatch.start));
}
}
if (matchPos[lng - 1].wholeMatch.end < str.length) {
bits.push(str.slice(matchPos[lng - 1].wholeMatch.end));
}
finalStr = bits.join('');
}
return finalStr;
};
/**
* POLYFILLS
*/
if (showdown.helper.isUndefined(console)) {
console = {
warn: function (msg) {
'use strict';
alert(msg);
},
log: function (msg) {
'use strict';
alert(msg);
},
error: function (msg) {
'use strict';
throw msg;
}
};
}
/**
* Created by Estevao on 31-05-2015.
*/
/**
* Showdown Converter class
* @class
* @param {object} [converterOptions]
* @returns {Converter}
*/
showdown.Converter = function (converterOptions) {
'use strict';
var
/**
* Options used by this converter
* @private
* @type {{}}
*/
options = {},
/**
* Language extensions used by this converter
* @private
* @type {Array}
*/
langExtensions = [],
/**
* Output modifiers extensions used by this converter
* @private
* @type {Array}
*/
outputModifiers = [],
/**
* Event listeners
* @private
* @type {{}}
*/
listeners = {};
_constructor();
/**
* Converter constructor
* @private
*/
function _constructor() {
converterOptions = converterOptions || {};
for (var gOpt in globalOptions) {
if (globalOptions.hasOwnProperty(gOpt)) {
options[gOpt] = globalOptions[gOpt];
}
}
// Merge options
if (typeof converterOptions === 'object') {
for (var opt in converterOptions) {
if (converterOptions.hasOwnProperty(opt)) {
options[opt] = converterOptions[opt];
}
}
} else {
throw Error('Converter expects the passed parameter to be an object, but ' + typeof converterOptions +
' was passed instead.');
}
if (options.extensions) {
showdown.helper.forEach(options.extensions, _parseExtension);
}
}
/**
* Parse extension
* @param {*} ext
* @param {string} [name='']
* @private
*/
function _parseExtension(ext, name) {
name = name || null;
// If it's a string, the extension was previously loaded
if (showdown.helper.isString(ext)) {
ext = showdown.helper.stdExtName(ext);
name = ext;
// LEGACY_SUPPORT CODE
if (showdown.extensions[ext]) {
console.warn('DEPRECATION WARNING: ' + ext + ' is an old extension that uses a deprecated loading method.' +
'Please inform the developer that the extension should be updated!');
legacyExtensionLoading(showdown.extensions[ext], ext);
return;
// END LEGACY SUPPORT CODE
} else if (!showdown.helper.isUndefined(extensions[ext])) {
ext = extensions[ext];
} else {
throw Error('Extension "' + ext + '" could not be loaded. It was either not found or is not a valid extension.');
}
}
if (typeof ext === 'function') {
ext = ext();
}
if (!showdown.helper.isArray(ext)) {
ext = [ext];
}
var validExt = validate(ext, name);
if (!validExt.valid) {
throw Error(validExt.error);
}
for (var i = 0; i < ext.length; ++i) {
switch (ext[i].type) {
case 'lang':
langExtensions.push(ext[i]);
break;
case 'output':
outputModifiers.push(ext[i]);
break;
}
if (ext[i].hasOwnProperty('listeners')) {
for (var ln in ext[i].listeners) {
if (ext[i].listeners.hasOwnProperty(ln)) {
listen(ln, ext[i].listeners[ln]);
}
}
}
}
}
/**
* LEGACY_SUPPORT
* @param {*} ext
* @param {string} name
*/
function legacyExtensionLoading(ext, name) {
if (typeof ext === 'function') {
ext = ext(new showdown.Converter());
}
if (!showdown.helper.isArray(ext)) {
ext = [ext];
}
var valid = validate(ext, name);
if (!valid.valid) {
throw Error(valid.error);
}
for (var i = 0; i < ext.length; ++i) {
switch (ext[i].type) {
case 'lang':
langExtensions.push(ext[i]);
break;
case 'output':
outputModifiers.push(ext[i]);
break;
default:// should never reach here
throw Error('Extension loader error: Type unrecognized!!!');
}
}
}
/**
* Listen to an event
* @param {string} name
* @param {function} callback
*/
function listen(name, callback) {
if (!showdown.helper.isString(name)) {
throw Error('Invalid argument in converter.listen() method: name must be a string, but ' + typeof name + ' given');
}
if (typeof callback !== 'function') {
throw Error('Invalid argument in converter.listen() method: callback must be a function, but ' + typeof callback + ' given');
}
if (!listeners.hasOwnProperty(name)) {
listeners[name] = [];
}
listeners[name].push(callback);
}
function rTrimInputText(text) {
var rsp = text.match(/^\s*/)[0].length,
rgx = new RegExp('^\\s{0,' + rsp + '}', 'gm');
return text.replace(rgx, '');
}
/**
* Dispatch an event
* @private
* @param {string} evtName Event name
* @param {string} text Text
* @param {{}} options Converter Options
* @param {{}} globals
* @returns {string}
*/
this._dispatch = function dispatch (evtName, text, options, globals) {
if (listeners.hasOwnProperty(evtName)) {
for (var ei = 0; ei < listeners[evtName].length; ++ei) {
var nText = listeners[evtName][ei](evtName, text, this, options, globals);
if (nText && typeof nText !== 'undefined') {
text = nText;
}
}
}
return text;
};
/**
* Listen to an event
* @param {string} name
* @param {function} callback
* @returns {showdown.Converter}
*/
this.listen = function (name, callback) {
listen(name, callback);
return this;
};
/**
* Converts a markdown string into HTML
* @param {string} text
* @returns {*}
*/
this.makeHtml = function (text) {
//check if text is not falsy
if (!text) {
return text;
}
var globals = {
gHtmlBlocks: [],
gHtmlMdBlocks: [],
gHtmlSpans: [],
gUrls: {},
gTitles: {},
gDimensions: {},
gListLevel: 0,
hashLinkCounts: {},
langExtensions: langExtensions,
outputModifiers: outputModifiers,
converter: this,
ghCodeBlocks: []
};
// attacklab: Replace ~ with ~T
// This lets us use tilde as an escape char to avoid md5 hashes
// The choice of character is arbitrary; anything that isn't
// magic in Markdown will work.
text = text.replace(/~/g, '~T');
// attacklab: Replace $ with ~D
// RegExp interprets $ as a special character
// when it's in a replacement string
text = text.replace(/\$/g, '~D');
// Standardize line endings
text = text.replace(/\r\n/g, '\n'); // DOS to Unix
text = text.replace(/\r/g, '\n'); // Mac to Unix
// Stardardize line spaces (nbsp causes trouble in older browsers and some regex flavors)
text = text.replace(/\u00A0/g, ' ');
if (options.smartIndentationFix) {
text = rTrimInputText(text);
}
// Make sure text begins and ends with a couple of newlines:
text = '\n\n' + text + '\n\n';
// detab
text = showdown.subParser('detab')(text, options, globals);
// stripBlankLines
text = showdown.subParser('stripBlankLines')(text, options, globals);
//run languageExtensions
showdown.helper.forEach(langExtensions, function (ext) {
text = showdown.subParser('runExtension')(ext, text, options, globals);
});
// run the sub parsers
text = showdown.subParser('hashPreCodeTags')(text, options, globals);
text = showdown.subParser('githubCodeBlocks')(text, options, globals);
text = showdown.subParser('hashHTMLBlocks')(text, options, globals);
text = showdown.subParser('hashHTMLSpans')(text, options, globals);
text = showdown.subParser('stripLinkDefinitions')(text, options, globals);
text = showdown.subParser('blockGamut')(text, options, globals);
text = showdown.subParser('unhashHTMLSpans')(text, options, globals);
text = showdown.subParser('unescapeSpecialChars')(text, options, globals);
// attacklab: Restore dollar signs
text = text.replace(/~D/g, '$$');
// attacklab: Restore tildes
text = text.replace(/~T/g, '~');
// Run output modifiers
showdown.helper.forEach(outputModifiers, function (ext) {
text = showdown.subParser('runExtension')(ext, text, options, globals);
});
return text;
};
/**
* Set an option of this Converter instance
* @param {string} key
* @param {*} value
*/
this.setOption = function (key, value) {
options[key] = value;
};
/**
* Get the option of this Converter instance
* @param {string} key
* @returns {*}
*/
this.getOption = function (key) {
return options[key];
};
/**
* Get the options of this Converter instance
* @returns {{}}
*/
this.getOptions = function () {
return options;
};
/**
* Add extension to THIS converter
* @param {{}} extension
* @param {string} [name=null]
*/
this.addExtension = function (extension, name) {
name = name || null;
_parseExtension(extension, name);
};
/**
* Use a global registered extension with THIS converter
* @param {string} extensionName Name of the previously registered extension
*/
this.useExtension = function (extensionName) {
_parseExtension(extensionName);
};
/**
* Set the flavor THIS converter should use
* @param {string} name
*/
this.setFlavor = function (name) {
if (flavor.hasOwnProperty(name)) {
var preset = flavor[name];
for (var option in preset) {
if (preset.hasOwnProperty(option)) {
options[option] = preset[option];
}
}
}
};
/**
* Remove an extension from THIS converter.
* Note: This is a costly operation. It's better to initialize a new converter
* and specify the extensions you wish to use
* @param {Array} extension
*/
this.removeExtension = function (extension) {
if (!showdown.helper.isArray(extension)) {
extension = [extension];
}
for (var a = 0; a < extension.length; ++a) {
var ext = extension[a];
for (var i = 0; i < langExtensions.length; ++i) {
if (langExtensions[i] === ext) {
langExtensions[i].splice(i, 1);
}
}
for (var ii = 0; ii < outputModifiers.length; ++i) {
if (outputModifiers[ii] === ext) {
outputModifiers[ii].splice(i, 1);
}
}
}
};
/**
* Get all extension of THIS converter
* @returns {{language: Array, output: Array}}
*/
this.getAllExtensions = function () {
return {
language: langExtensions,
output: outputModifiers
};
};
};
/**
* Turn Markdown link shortcuts into XHTML <a> tags.
*/
showdown.subParser('anchors', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('anchors.before', text, options, globals);
var writeAnchorTag = function (wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
if (showdown.helper.isUndefined(m7)) {
m7 = '';
}
wholeMatch = m1;
var linkText = m2,
linkId = m3.toLowerCase(),
url = m4,
title = m7;
if (!url) {
if (!linkId) {
// lower-case and turn embedded newlines into spaces
linkId = linkText.toLowerCase().replace(/ ?\n/g, ' ');
}
url = '#' + linkId;
if (!showdown.helper.isUndefined(globals.gUrls[linkId])) {
url = globals.gUrls[linkId];
if (!showdown.helper.isUndefined(globals.gTitles[linkId])) {
title = globals.gTitles[linkId];
}
} else {
if (wholeMatch.search(/\(\s*\)$/m) > -1) {
// Special case for explicit empty url
url = '';
} else {
return wholeMatch;
}
}
}
url = showdown.helper.escapeCharacters(url, '*_', false);
var result = '<a href="' + url + '"';
if (title !== '' && title !== null) {
title = title.replace(/"/g, '"');
title = showdown.helper.escapeCharacters(title, '*_', false);
result += ' title="' + title + '"';
}
result += '>' + linkText + '</a>';
return result;
};
// First, handle reference-style links: [link text] [id]
text = text.replace(/(\[((?:\[[^\]]*]|[^\[\]])*)][ ]?(?:\n[ ]*)?\[(.*?)])()()()()/g, writeAnchorTag);
// Next, inline-style links: [link text](url "optional title")
text = text.replace(/(\[((?:\[[^\]]*]|[^\[\]])*)]\([ \t]*()<?(.*?(?:\(.*?\).*?)?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,
writeAnchorTag);
// Last, handle reference-style shortcuts: [link text]
// These must come last in case you've also got [link test][1]
// or [link test](/foo)
text = text.replace(/(\[([^\[\]]+)])()()()()()/g, writeAnchorTag);
text = globals.converter._dispatch('anchors.after', text, options, globals);
return text;
});
showdown.subParser('autoLinks', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('autoLinks.before', text, options, globals);
var simpleURLRegex = /\b(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+)()(?=\s|$)(?!["<>])/gi,
simpleURLRegex2 = /\b(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+?)([.!?()]?)(?=\s|$)(?!["<>])/gi,
delimUrlRegex = /<(((https?|ftp|dict):\/\/|www\.)[^'">\s]+)>/gi,
simpleMailRegex = /(?:^|\s)([A-Za-z0-9!#$%&'*+-/=?^_`{|}~.]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)(?:$|\s)/gi,
delimMailRegex = /<(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi;
text = text.replace(delimUrlRegex, replaceLink);
text = text.replace(delimMailRegex, replaceMail);
// simpleURLRegex = /\b(((https?|ftp|dict):\/\/|www\.)[-.+~:?#@!$&'()*,;=[\]\w]+)\b/gi,
// Email addresses: <address@domain.foo>
if (options.simplifiedAutoLink) {
if (options.excludeTrailingPunctuationFromURLs) {
text = text.replace(simpleURLRegex2, replaceLink);
} else {
text = text.replace(simpleURLRegex, replaceLink);
}
text = text.replace(simpleMailRegex, replaceMail);
}
function replaceLink(wm, link, m2, m3, trailingPunctuation) {
var lnkTxt = link,
append = '';
if (/^www\./i.test(link)) {
link = link.replace(/^www\./i, 'http://www.');
}
if (options.excludeTrailingPunctuationFromURLs && trailingPunctuation) {
append = trailingPunctuation;
}
return '<a href="' + link + '">' + lnkTxt + '</a>' + append;
}
function replaceMail(wholeMatch, mail) {
var unescapedStr = showdown.subParser('unescapeSpecialChars')(mail);
return showdown.subParser('encodeEmailAddress')(unescapedStr);
}
text = globals.converter._dispatch('autoLinks.after', text, options, globals);
return text;
});
/**
* These are all the transformations that form block-level
* tags like paragraphs, headers, and list items.
*/
showdown.subParser('blockGamut', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('blockGamut.before', text, options, globals);
// we parse blockquotes first so that we can have headings and hrs
// inside blockquotes
text = showdown.subParser('blockQuotes')(text, options, globals);
text = showdown.subParser('headers')(text, options, globals);
// Do Horizontal Rules:
var key = showdown.subParser('hashBlock')('<hr />', options, globals);
text = text.replace(/^ {0,2}( ?\* ?){3,}[ \t]*$/gm, key);
text = text.replace(/^ {0,2}( ?- ?){3,}[ \t]*$/gm, key);
text = text.replace(/^ {0,2}( ?_ ?){3,}[ \t]*$/gm, key);
text = showdown.subParser('lists')(text, options, globals);
text = showdown.subParser('codeBlocks')(text, options, globals);
text = showdown.subParser('tables')(text, options, globals);
// We already ran _HashHTMLBlocks() before, in Markdown(), but that
// was to escape raw HTML in the original Markdown source. This time,
// we're escaping the markup we've just created, so that we don't wrap
// <p> tags around block-level tags.
text = showdown.subParser('hashHTMLBlocks')(text, options, globals);
text = showdown.subParser('paragraphs')(text, options, globals);
text = globals.converter._dispatch('blockGamut.after', text, options, globals);
return text;
});
showdown.subParser('blockQuotes', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('blockQuotes.before', text, options, globals);
text = text.replace(/((^ {0,3}>[ \t]?.+\n(.+\n)*\n*)+)/gm, function (wholeMatch, m1) {
var bq = m1;
// attacklab: hack around Konqueror 3.5.4 bug:
// "----------bug".replace(/^-/g,"") == "bug"
bq = bq.replace(/^[ \t]*>[ \t]?/gm, '~0'); // trim one level of quoting
// attacklab: clean up hack
bq = bq.replace(/~0/g, '');
bq = bq.replace(/^[ \t]+$/gm, ''); // trim whitespace-only lines
bq = showdown.subParser('githubCodeBlocks')(bq, options, globals);
bq = showdown.subParser('blockGamut')(bq, options, globals); // recurse
bq = bq.replace(/(^|\n)/g, '$1 ');
// These leading spaces screw with <pre> content, so we need to fix that:
bq = bq.replace(/(\s*<pre>[^\r]+?<\/pre>)/gm, function (wholeMatch, m1) {
var pre = m1;
// attacklab: hack around Konqueror 3.5.4 bug:
pre = pre.replace(/^ /mg, '~0');
pre = pre.replace(/~0/g, '');
return pre;
});
return showdown.subParser('hashBlock')('<blockquote>\n' + bq + '\n</blockquote>', options, globals);
});
text = globals.converter._dispatch('blockQuotes.after', text, options, globals);
return text;
});
/**
* Process Markdown `<pre><code>` blocks.
*/
showdown.subParser('codeBlocks', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('codeBlocks.before', text, options, globals);
// sentinel workarounds for lack of \A and \Z, safari\khtml bug
text += '~0';
var pattern = /(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g;
text = text.replace(pattern, function (wholeMatch, m1, m2) {
var codeblock = m1,
nextChar = m2,
end = '\n';
codeblock = showdown.subParser('outdent')(codeblock);
codeblock = showdown.subParser('encodeCode')(codeblock);
codeblock = showdown.subParser('detab')(codeblock);
codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing newlines
if (options.omitExtraWLInCodeBlocks) {
end = '';
}
codeblock = '<pre><code>' + codeblock + end + '</code></pre>';
return showdown.subParser('hashBlock')(codeblock, options, globals) + nextChar;
});
// strip sentinel
text = text.replace(/~0/, '');
text = globals.converter._dispatch('codeBlocks.after', text, options, globals);
return text;
});
/**
*
* * Backtick quotes are used for <code></code> spans.
*
* * You can use multiple backticks as the delimiters if you want to
* include literal backticks in the code span. So, this input:
*
* Just type ``foo `bar` baz`` at the prompt.
*
* Will translate to:
*
* <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
*
* There's no arbitrary limit to the number of backticks you
* can use as delimters. If you need three consecutive backticks
* in your code, use four for delimiters, etc.
*
* * You can use spaces to get literal backticks at the edges:
*
* ... type `` `bar` `` ...
*
* Turns to:
*
* ... type <code>`bar`</code> ...
*/
showdown.subParser('codeSpans', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('codeSpans.before', text, options, globals);
/*
text = text.replace(/
(^|[^\\]) // Character before opening ` can't be a backslash
(`+) // $2 = Opening run of `
( // $3 = The code block
[^\r]*?
[^`] // attacklab: work around lack of lookbehind
)
\2 // Matching closer
(?!`)
/gm, function(){...});
*/
if (typeof(text) === 'undefined') {
text = '';
}
text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
function (wholeMatch, m1, m2, m3) {
var c = m3;
c = c.replace(/^([ \t]*)/g, ''); // leading whitespace
c = c.replace(/[ \t]*$/g, ''); // trailing whitespace
c = showdown.subParser('encodeCode')(c);
return m1 + '<code>' + c + '</code>';
}
);
text = globals.converter._dispatch('codeSpans.after', text, options, globals);
return text;
});
/**
* Convert all tabs to spaces
*/
showdown.subParser('detab', function (text) {
'use strict';
// expand first n-1 tabs
text = text.replace(/\t(?=\t)/g, ' '); // g_tab_width
// replace the nth with two sentinels
text = text.replace(/\t/g, '~A~B');
// use the sentinel to anchor our regex so it doesn't explode
text = text.replace(/~B(.+?)~A/g, function (wholeMatch, m1) {
var leadingText = m1,
numSpaces = 4 - leadingText.length % 4; // g_tab_width
// there *must* be a better way to do this:
for (var i = 0; i < numSpaces; i++) {
leadingText += ' ';
}
return leadingText;
});
// clean up sentinels
text = text.replace(/~A/g, ' '); // g_tab_width
text = text.replace(/~B/g, '');
return text;
});
/**
* Smart processing for ampersands and angle brackets that need to be encoded.
*/
showdown.subParser('encodeAmpsAndAngles', function (text) {
'use strict';
// Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
// http://bumppo.net/projects/amputator/
text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, '&');
// Encode naked <'s
text = text.replace(/<(?![a-z\/?\$!])/gi, '<');
return text;
});
/**
* Returns the string, with after processing the following backslash escape sequences.
*
* attacklab: The polite way to do this is with the new escapeCharacters() function:
*
* text = escapeCharacters(text,"\\",true);
* text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
*
* ...but we're sidestepping its use of the (slow) RegExp constructor
* as an optimization for Firefox. This function gets called a LOT.
*/
showdown.subParser('encodeBackslashEscapes', function (text) {
'use strict';
text = text.replace(/\\(\\)/g, showdown.helper.escapeCharactersCallback);
text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g, showdown.helper.escapeCharactersCallback);
return text;
});
/**
* Encode/escape certain characters inside Markdown code runs.
* The point is that in code, these characters are literals,
* and lose their special Markdown meanings.
*/
showdown.subParser('encodeCode', function (text) {
'use strict';
// Encode all ampersands; HTML entities are not
// entities within a Markdown code span.
text = text.replace(/&/g, '&');
// Do the angle bracket song and dance:
text = text.replace(/</g, '<');
text = text.replace(/>/g, '>');
// Now, escape characters that are magic in Markdown:
text = showdown.helper.escapeCharacters(text, '*_{}[]\\', false);
// jj the line above breaks this:
//---
//* Item
// 1. Subitem
// special char: *
// ---
return text;
});
/**
* Input: an email address, e.g. "foo@example.com"
*
* Output: the email address as a mailto link, with each character
* of the address encoded as either a decimal or hex entity, in
* the hopes of foiling most address harvesting spam bots. E.g.:
*
* <a href="mailto:foo@e
* xample.com">foo
* @example.com</a>
*
* Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
* mailing list: <http://tinyurl.com/yu7ue>
*
*/
showdown.subParser('encodeEmailAddress', function (addr) {
'use strict';
var encode = [
function (ch) {
return '&#' + ch.charCodeAt(0) + ';';
},
function (ch) {
return '&#x' + ch.charCodeAt(0).toString(16) + ';';
},
function (ch) {
return ch;
}
];
addr = 'mailto:' + addr;
addr = addr.replace(/./g, function (ch) {
if (ch === '@') {
// this *must* be encoded. I insist.
ch = encode[Math.floor(Math.random() * 2)](ch);
} else if (ch !== ':') {
// leave ':' alone (to spot mailto: later)
var r = Math.random();
// roughly 10% raw, 45% hex, 45% dec
ch = (
r > 0.9 ? encode[2](ch) : r > 0.45 ? encode[1](ch) : encode[0](ch)
);
}
return ch;
});
addr = '<a href="' + addr + '">' + addr + '</a>';
addr = addr.replace(/">.+:/g, '">'); // strip the mailto: from the visible part
return addr;
});
/**
* Within tags -- meaning between < and > -- encode [\ ` * _] so they
* don't conflict with their use in Markdown for code, italics and strong.
*/
showdown.subParser('escapeSpecialCharsWithinTagAttributes', function (text) {
'use strict';
// Build a regex to find HTML tags and comments. See Friedl's
// "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--.*?--\s*)+>)/gi;
text = text.replace(regex, function (wholeMatch) {
var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g, '$1`');
tag = showdown.helper.escapeCharacters(tag, '\\`*_', false);
return tag;
});
return text;
});
/**
* Handle github codeblocks prior to running HashHTML so that
* HTML contained within the codeblock gets escaped properly
* Example:
* ```ruby
* def hello_world(x)
* puts "Hello, #{x}"
* end
* ```
*/
showdown.subParser('githubCodeBlocks', function (text, options, globals) {
'use strict';
// early exit if option is not enabled
if (!options.ghCodeBlocks) {
return text;
}
text = globals.converter._dispatch('githubCodeBlocks.before', text, options, globals);
text += '~0';
text = text.replace(/(?:^|\n)```(.*)\n([\s\S]*?)\n```/g, function (wholeMatch, language, codeblock) {
var end = (options.omitExtraWLInCodeBlocks) ? '' : '\n';
// First parse the github code block
codeblock = showdown.subParser('encodeCode')(codeblock);
codeblock = showdown.subParser('detab')(codeblock);
codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing whitespace
codeblock = '<pre><code' + (language ? ' class="' + language + ' language-' + language + '"' : '') + '>' + codeblock + end + '</code></pre>';
codeblock = showdown.subParser('hashBlock')(codeblock, options, globals);
// Since GHCodeblocks can be false positives, we need to
// store the primitive text and the parsed text in a global var,
// and then return a token
return '\n\n~G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\n\n';
});
// attacklab: strip sentinel
text = text.replace(/~0/, '');
return globals.converter._dispatch('githubCodeBlocks.after', text, options, globals);
});
showdown.subParser('hashBlock', function (text, options, globals) {
'use strict';
text = text.replace(/(^\n+|\n+$)/g, '');
return '\n\n~K' + (globals.gHtmlBlocks.push(text) - 1) + 'K\n\n';
});
showdown.subParser('hashElement', function (text, options, globals) {
'use strict';
return function (wholeMatch, m1) {
var blockText = m1;
// Undo double lines
blockText = blockText.replace(/\n\n/g, '\n');
blockText = blockText.replace(/^\n/, '');
// strip trailing blank lines
blockText = blockText.replace(/\n+$/g, '');
// Replace the element text with a marker ("~KxK" where x is its key)
blockText = '\n\n~K' + (globals.gHtmlBlocks.push(blockText) - 1) + 'K\n\n';
return blockText;
};
});
showdown.subParser('hashHTMLBlocks', function (text, options, globals) {
'use strict';
var blockTags = [
'pre',
'div',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'blockquote',
'table',
'dl',
'ol',
'ul',
'script',
'noscript',
'form',
'fieldset',
'iframe',
'math',
'style',
'section',
'header',
'footer',
'nav',
'article',
'aside',
'address',
'audio',
'canvas',
'figure',
'hgroup',
'output',
'video',
'p'
],
repFunc = function (wholeMatch, match, left, right) {
var txt = wholeMatch;
// check if this html element is marked as markdown
// if so, it's contents should be parsed as markdown
if (left.search(/\bmarkdown\b/) !== -1) {
txt = left + globals.converter.makeHtml(match) + right;
}
return '\n\n~K' + (globals.gHtmlBlocks.push(txt) - 1) + 'K\n\n';
};
for (var i = 0; i < blockTags.length; ++i) {
text = showdown.helper.replaceRecursiveRegExp(text, repFunc, '^ {0,3}<' + blockTags[i] + '\\b[^>]*>', '</' + blockTags[i] + '>', 'gim');
}
// HR SPECIAL CASE
text = text.replace(/(\n {0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,
showdown.subParser('hashElement')(text, options, globals));
// Special case for standalone HTML comments
text = showdown.helper.replaceRecursiveRegExp(text, function (txt) {
return '\n\n~K' + (globals.gHtmlBlocks.push(txt) - 1) + 'K\n\n';
}, '^ {0,3}<!--', '-->', 'gm');
// PHP and ASP-style processor instructions (<?...?> and <%...%>)
text = text.replace(/(?:\n\n)( {0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,
showdown.subParser('hashElement')(text, options, globals));
return text;
});
/**
* Hash span elements that should not be parsed as markdown
*/
showdown.subParser('hashHTMLSpans', function (text, config, globals) {
'use strict';
var matches = showdown.helper.matchRecursiveRegExp(text, '<code\\b[^>]*>', '</code>', 'gi');
for (var i = 0; i < matches.length; ++i) {
text = text.replace(matches[i][0], '~L' + (globals.gHtmlSpans.push(matches[i][0]) - 1) + 'L');
}
return text;
});
/**
* Unhash HTML spans
*/
showdown.subParser('unhashHTMLSpans', function (text, config, globals) {
'use strict';
for (var i = 0; i < globals.gHtmlSpans.length; ++i) {
text = text.replace('~L' + i + 'L', globals.gHtmlSpans[i]);
}
return text;
});
/**
* Hash span elements that should not be parsed as markdown
*/
showdown.subParser('hashPreCodeTags', function (text, config, globals) {
'use strict';
var repFunc = function (wholeMatch, match, left, right) {
// encode html entities
var codeblock = left + showdown.subParser('encodeCode')(match) + right;
return '\n\n~G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\n\n';
};
text = showdown.helper.replaceRecursiveRegExp(text, repFunc, '^ {0,3}<pre\\b[^>]*>\\s*<code\\b[^>]*>', '^ {0,3}</code>\\s*</pre>', 'gim');
return text;
});
showdown.subParser('headers', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('headers.before', text, options, globals);
var prefixHeader = options.prefixHeaderId,
headerLevelStart = (isNaN(parseInt(options.headerLevelStart))) ? 1 : parseInt(options.headerLevelStart),
// Set text-style headers:
// Header 1
// ========
//
// Header 2
// --------
//
setextRegexH1 = (options.smoothLivePreview) ? /^(.+)[ \t]*\n={2,}[ \t]*\n+/gm : /^(.+)[ \t]*\n=+[ \t]*\n+/gm,
setextRegexH2 = (options.smoothLivePreview) ? /^(.+)[ \t]*\n-{2,}[ \t]*\n+/gm : /^(.+)[ \t]*\n-+[ \t]*\n+/gm;
text = text.replace(setextRegexH1, function (wholeMatch, m1) {
var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
hID = (options.noHeaderId) ? '' : ' id="' + headerId(m1) + '"',
hLevel = headerLevelStart,
hashBlock = '<h' + hLevel + hID + '>' + spanGamut + '</h' + hLevel + '>';
return showdown.subParser('hashBlock')(hashBlock, options, globals);
});
text = text.replace(setextRegexH2, function (matchFound, m1) {
var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
hID = (options.noHeaderId) ? '' : ' id="' + headerId(m1) + '"',
hLevel = headerLevelStart + 1,
hashBlock = '<h' + hLevel + hID + '>' + spanGamut + '</h' + hLevel + '>';
return showdown.subParser('hashBlock')(hashBlock, options, globals);
});
// atx-style headers:
// # Header 1
// ## Header 2
// ## Header 2 with closing hashes ##
// ...
// ###### Header 6
//
text = text.replace(/^(#{1,6})[ \t]*(.+?)[ \t]*#*\n+/gm, function (wholeMatch, m1, m2) {
var span = showdown.subParser('spanGamut')(m2, options, globals),
hID = (options.noHeaderId) ? '' : ' id="' + headerId(m2) + '"',
hLevel = headerLevelStart - 1 + m1.length,
header = '<h' + hLevel + hID + '>' + span + '</h' + hLevel + '>';
return showdown.subParser('hashBlock')(header, options, globals);
});
function headerId(m) {
var title, escapedId = m.replace(/[^\w]/g, '').toLowerCase();
if (globals.hashLinkCounts[escapedId]) {
title = escapedId + '-' + (globals.hashLinkCounts[escapedId]++);
} else {
title = escapedId;
globals.hashLinkCounts[escapedId] = 1;
}
// Prefix id to prevent causing inadvertent pre-existing style matches.
if (prefixHeader === true) {
prefixHeader = 'section';
}
if (showdown.helper.isString(prefixHeader)) {
return prefixHeader + title;
}
return title;
}
text = globals.converter._dispatch('headers.after', text, options, globals);
return text;
});
/**
* Turn Markdown image shortcuts into <img> tags.
*/
showdown.subParser('images', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('images.before', text, options, globals);
var inlineRegExp = /!\[(.*?)]\s?\([ \t]*()<?(\S+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(['"])(.*?)\6[ \t]*)?\)/g,
referenceRegExp = /!\[([^\]]*?)] ?(?:\n *)?\[(.*?)]()()()()()/g;
function writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title) {
var gUrls = globals.gUrls,
gTitles = globals.gTitles,
gDims = globals.gDimensions;
linkId = linkId.toLowerCase();
if (!title) {
title = '';
}
if (url === '' || url === null) {
if (linkId === '' || linkId === null) {
// lower-case and turn embedded newlines into spaces
linkId = altText.toLowerCase().replace(/ ?\n/g, ' ');
}
url = '#' + linkId;
if (!showdown.helper.isUndefined(gUrls[linkId])) {
url = gUrls[linkId];
if (!showdown.helper.isUndefined(gTitles[linkId])) {
title = gTitles[linkId];
}
if (!showdown.helper.isUndefined(gDims[linkId])) {
width = gDims[linkId].width;
height = gDims[linkId].height;
}
} else {
return wholeMatch;
}
}
altText = altText.replace(/"/g, '"');
altText = showdown.helper.escapeCharacters(altText, '*_', false);
url = showdown.helper.escapeCharacters(url, '*_', false);
var result = '<img src="' + url + '" alt="' + altText + '"';
if (title) {
title = title.replace(/"/g, '"');
title = showdown.helper.escapeCharacters(title, '*_', false);
result += ' title="' + title + '"';
}
if (width && height) {
width = (width === '*') ? 'auto' : width;
height = (height === '*') ? 'auto' : height;
result += ' width="' + width + '"';
result += ' height="' + height + '"';
}
result += ' />';
return result;
}
// First, handle reference-style labeled images: ![alt text][id]
text = text.replace(referenceRegExp, writeImageTag);
// Next, handle inline images: 
text = text.replace(inlineRegExp, writeImageTag);
text = globals.converter._dispatch('images.after', text, options, globals);
return text;
});
showdown.subParser('italicsAndBold', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('italicsAndBold.before', text, options, globals);
if (options.literalMidWordUnderscores) {
//underscores
// Since we are consuming a \s character, we need to add it
text = text.replace(/(^|\s|>|\b)__(?=\S)([\s\S]+?)__(?=\b|<|\s|$)/gm, '$1<strong>$2</strong>');
text = text.replace(/(^|\s|>|\b)_(?=\S)([\s\S]+?)_(?=\b|<|\s|$)/gm, '$1<em>$2</em>');
//asterisks
text = text.replace(/(\*\*)(?=\S)([^\r]*?\S[*]*)\1/g, '<strong>$2</strong>');
text = text.replace(/(\*)(?=\S)([^\r]*?\S)\1/g, '<em>$2</em>');
} else {
// <strong> must go first:
text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g, '<strong>$2</strong>');
text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g, '<em>$2</em>');
}
text = globals.converter._dispatch('italicsAndBold.after', text, options, globals);
return text;
});
/**
* Form HTML ordered (numbered) and unordered (bulleted) lists.
*/
showdown.subParser('lists', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('lists.before', text, options, globals);
/**
* Process the contents of a single ordered or unordered list, splitting it
* into individual list items.
* @param {string} listStr
* @param {boolean} trimTrailing
* @returns {string}
*/
function processListItems (listStr, trimTrailing) {
// The $g_list_level global keeps track of when we're inside a list.
// Each time we enter a list, we increment it; when we leave a list,
// we decrement. If it's zero, we're not in a list anymore.
//
// We do this because when we're not inside a list, we want to treat
// something like this:
//
// I recommend upgrading to version
// 8. Oops, now this line is treated
// as a sub-list.
//
// As a single paragraph, despite the fact that the second line starts
// with a digit-period-space sequence.
//
// Whereas when we're inside a list (or sub-list), that line will be
// treated as the start of a sub-list. What a kludge, huh? This is
// an aspect of Markdown's syntax that's hard to parse perfectly
// without resorting to mind-reading. Perhaps the solution is to
// change the syntax rules such that sub-lists must start with a
// starting cardinal number; e.g. "1." or "a.".
globals.gListLevel++;
// trim trailing blank lines:
listStr = listStr.replace(/\n{2,}$/, '\n');
// attacklab: add sentinel to emulate \z
listStr += '~0';
var rgx = /(\n)?(^ {0,3})([*+-]|\d+[.])[ \t]+((\[(x|X| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(~0| {0,3}([*+-]|\d+[.])[ \t]+))/gm,
isParagraphed = (/\n[ \t]*\n(?!~0)/.test(listStr));
// Since version 1.5, nesting sublists requires 4 spaces (or 1 tab) indentation,
// which is a syntax breaking change
// activating this option reverts to old behavior
if (options.disableForced4SpacesIndentedSublists) {
rgx = /(\n)?(^ {0,3})([*+-]|\d+[.])[ \t]+((\[(x|X| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm;
}
listStr = listStr.replace(rgx, function (wholeMatch, m1, m2, m3, m4, taskbtn, checked) {
checked = (checked && checked.trim() !== '');
var item = showdown.subParser('outdent')(m4, options, globals),
bulletStyle = '';
// Support for github tasklists
if (taskbtn && options.tasklists) {
bulletStyle = ' class="task-list-item" style="list-style-type: none;"';
item = item.replace(/^[ \t]*\[(x|X| )?]/m, function () {
var otp = '<input type="checkbox" disabled style="margin: 0px 0.35em 0.25em -1.6em; vertical-align: middle;"';
if (checked) {
otp += ' checked';
}
otp += '>';
return otp;
});
}
// ISSUE #312
// This input: - - - a
// causes trouble to the parser, since it interprets it as:
// <ul><li><li><li>a</li></li></li></ul>
// instead of:
// <ul><li>- - a</li></ul>
// So, to prevent it, we will put a marker (~A)in the beginning of the line
// Kind of hackish/monkey patching, but seems more effective than overcomplicating the list parser
item = item.replace(/^([-*+]|\d\.)[ \t]+[\s\n]*/g, function (wm2) {
return '~A' + wm2;
});
// m1 - Leading line or
// Has a double return (multi paragraph) or
// Has sublist
if (m1 || (item.search(/\n{2,}/) > -1)) {
item = showdown.subParser('githubCodeBlocks')(item, options, globals);
item = showdown.subParser('blockGamut')(item, options, globals);
} else {
// Recursion for sub-lists:
item = showdown.subParser('lists')(item, options, globals);
item = item.replace(/\n$/, ''); // chomp(item)
if (isParagraphed) {
item = showdown.subParser('paragraphs')(item, options, globals);
} else {
item = showdown.subParser('spanGamut')(item, options, globals);
}
}
// now we need to remove the marker (~A)
item = item.replace('~A', '');
// we can finally wrap the line in list item tags
item = '<li' + bulletStyle + '>' + item + '</li>\n';
return item;
});
// attacklab: strip sentinel
listStr = listStr.replace(/~0/g, '');
globals.gListLevel--;
if (trimTrailing) {
listStr = listStr.replace(/\s+$/, '');
}
return listStr;
}
/**
* Check and parse consecutive lists (better fix for issue #142)
* @param {string} list
* @param {string} listType
* @param {boolean} trimTrailing
* @returns {string}
*/
function parseConsecutiveLists(list, listType, trimTrailing) {
// check if we caught 2 or more consecutive lists by mistake
// we use the counterRgx, meaning if listType is UL we look for OL and vice versa
var olRgx = (options.disableForced4SpacesIndentedSublists) ? /^ ?\d+\.[ \t]/gm : /^ {0,3}\d+\.[ \t]/gm,
ulRgx = (options.disableForced4SpacesIndentedSublists) ? /^ ?[*+-][ \t]/gm : /^ {0,3}[*+-][ \t]/gm,
counterRxg = (listType === 'ul') ? olRgx : ulRgx,
result = '';
if (list.search(counterRxg) !== -1) {
(function parseCL(txt) {
var pos = txt.search(counterRxg);
if (pos !== -1) {
// slice
result += '\n<' + listType + '>\n' + processListItems(txt.slice(0, pos), !!trimTrailing) + '</' + listType + '>\n';
// invert counterType and listType
listType = (listType === 'ul') ? 'ol' : 'ul';
counterRxg = (listType === 'ul') ? olRgx : ulRgx;
//recurse
parseCL(txt.slice(pos));
} else {
result += '\n<' + listType + '>\n' + processListItems(txt, !!trimTrailing) + '</' + listType + '>\n';
}
})(list);
} else {
result = '\n<' + listType + '>\n' + processListItems(list, !!trimTrailing) + '</' + listType + '>\n';
}
return result;
}
// add sentinel to hack around khtml/safari bug:
// http://bugs.webkit.org/show_bug.cgi?id=11231
text += '~0';
if (globals.gListLevel) {
text = text.replace(/^(( {0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm,
function (wholeMatch, list, m2) {
var listType = (m2.search(/[*+-]/g) > -1) ? 'ul' : 'ol';
return parseConsecutiveLists(list, listType, true);
}
);
} else {
text = text.replace(/(\n\n|^\n?)(( {0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm,
function (wholeMatch, m1, list, m3) {
var listType = (m3.search(/[*+-]/g) > -1) ? 'ul' : 'ol';
return parseConsecutiveLists(list, listType, false);
}
);
}
// strip sentinel
text = text.replace(/~0/, '');
text = globals.converter._dispatch('lists.after', text, options, globals);
return text;
});
/**
* Remove one level of line-leading tabs or spaces
*/
showdown.subParser('outdent', function (text) {
'use strict';
// attacklab: hack around Konqueror 3.5.4 bug:
// "----------bug".replace(/^-/g,"") == "bug"
text = text.replace(/^(\t|[ ]{1,4})/gm, '~0'); // attacklab: g_tab_width
// attacklab: clean up hack
text = text.replace(/~0/g, '');
return text;
});
/**
*
*/
showdown.subParser('paragraphs', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('paragraphs.before', text, options, globals);
// Strip leading and trailing lines:
text = text.replace(/^\n+/g, '');
text = text.replace(/\n+$/g, '');
var grafs = text.split(/\n{2,}/g),
grafsOut = [],
end = grafs.length; // Wrap <p> tags
for (var i = 0; i < end; i++) {
var str = grafs[i];
// if this is an HTML marker, copy it
if (str.search(/~(K|G)(\d+)\1/g) >= 0) {
grafsOut.push(str);
} else {
str = showdown.subParser('spanGamut')(str, options, globals);
str = str.replace(/^([ \t]*)/g, '<p>');
str += '</p>';
grafsOut.push(str);
}
}
/** Unhashify HTML blocks */
end = grafsOut.length;
for (i = 0; i < end; i++) {
var blockText = '',
grafsOutIt = grafsOut[i],
codeFlag = false;
// if this is a marker for an html block...
while (grafsOutIt.search(/~(K|G)(\d+)\1/) >= 0) {
var delim = RegExp.$1,
num = RegExp.$2;
if (delim === 'K') {
blockText = globals.gHtmlBlocks[num];
} else {
// we need to check if ghBlock is a false positive
if (codeFlag) {
// use encoded version of all text
blockText = showdown.subParser('encodeCode')(globals.ghCodeBlocks[num].text);
} else {
blockText = globals.ghCodeBlocks[num].codeblock;
}
}
blockText = blockText.replace(/\$/g, '$$$$'); // Escape any dollar signs
grafsOutIt = grafsOutIt.replace(/(\n\n)?~(K|G)\d+\2(\n\n)?/, blockText);
// Check if grafsOutIt is a pre->code
if (/^<pre\b[^>]*>\s*<code\b[^>]*>/.test(grafsOutIt)) {
codeFlag = true;
}
}
grafsOut[i] = grafsOutIt;
}
text = grafsOut.join('\n');
// Strip leading and trailing lines:
text = text.replace(/^\n+/g, '');
text = text.replace(/\n+$/g, '');
return globals.converter._dispatch('paragraphs.after', text, options, globals);
});
/**
* Run extension
*/
showdown.subParser('runExtension', function (ext, text, options, globals) {
'use strict';
if (ext.filter) {
text = ext.filter(text, globals.converter, options);
} else if (ext.regex) {
// TODO remove this when old extension loading mechanism is deprecated
var re = ext.regex;
if (!re instanceof RegExp) {
re = new RegExp(re, 'g');
}
text = text.replace(re, ext.replace);
}
return text;
});
/**
* These are all the transformations that occur *within* block-level
* tags like paragraphs, headers, and list items.
*/
showdown.subParser('spanGamut', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('spanGamut.before', text, options, globals);
text = showdown.subParser('codeSpans')(text, options, globals);
text = showdown.subParser('escapeSpecialCharsWithinTagAttributes')(text, options, globals);
text = showdown.subParser('encodeBackslashEscapes')(text, options, globals);
// Process anchor and image tags. Images must come first,
// because ![foo][f] looks like an anchor.
text = showdown.subParser('images')(text, options, globals);
text = showdown.subParser('anchors')(text, options, globals);
// Make links out of things like `<http://example.com/>`
// Must come after _DoAnchors(), because you can use < and >
// delimiters in inline links like [this](<url>).
text = showdown.subParser('autoLinks')(text, options, globals);
text = showdown.subParser('encodeAmpsAndAngles')(text, options, globals);
text = showdown.subParser('italicsAndBold')(text, options, globals);
text = showdown.subParser('strikethrough')(text, options, globals);
// Do hard breaks
// GFM style hard breaks
if (options.simpleLineBreaks) {
text = text.replace(/\n/g, '<br />\n');
} else {
text = text.replace(/ +\n/g, '<br />\n');
}
text = globals.converter._dispatch('spanGamut.after', text, options, globals);
return text;
});
showdown.subParser('strikethrough', function (text, options, globals) {
'use strict';
if (options.strikethrough) {
text = globals.converter._dispatch('strikethrough.before', text, options, globals);
text = text.replace(/(?:~T){2}([\s\S]+?)(?:~T){2}/g, '<del>$1</del>');
text = globals.converter._dispatch('strikethrough.after', text, options, globals);
}
return text;
});
/**
* Strip any lines consisting only of spaces and tabs.
* This makes subsequent regexs easier to write, because we can
* match consecutive blank lines with /\n+/ instead of something
* contorted like /[ \t]*\n+/
*/
showdown.subParser('stripBlankLines', function (text) {
'use strict';
return text.replace(/^[ \t]+$/mg, '');
});
/**
* Strips link definitions from text, stores the URLs and titles in
* hash references.
* Link defs are in the form: ^[id]: url "optional title"
*/
showdown.subParser('stripLinkDefinitions', function (text, options, globals) {
'use strict';
var regex = /^ {0,3}\[(.+)]:[ \t]*\n?[ \t]*<?(\S+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*\n?[ \t]*(?:(\n*)["|'(](.+?)["|')][ \t]*)?(?:\n+|(?=~0))/gm;
// attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
text += '~0';
text = text.replace(regex, function (wholeMatch, linkId, url, width, height, blankLines, title) {
linkId = linkId.toLowerCase();
globals.gUrls[linkId] = showdown.subParser('encodeAmpsAndAngles')(url); // Link IDs are case-insensitive
if (blankLines) {
// Oops, found blank lines, so it's not a title.
// Put back the parenthetical statement we stole.
return blankLines + title;
} else {
if (title) {
globals.gTitles[linkId] = title.replace(/"|'/g, '"');
}
if (options.parseImgDimensions && width && height) {
globals.gDimensions[linkId] = {
width: width,
height: height
};
}
}
// Completely remove the definition from the text
return '';
});
// attacklab: strip sentinel
text = text.replace(/~0/, '');
return text;
});
showdown.subParser('tables', function (text, options, globals) {
'use strict';
if (!options.tables) {
return text;
}
var tableRgx = /^ {0,3}\|?.+\|.+\n[ \t]{0,3}\|?[ \t]*:?[ \t]*(?:-|=){2,}[ \t]*:?[ \t]*\|[ \t]*:?[ \t]*(?:-|=){2,}[\s\S]+?(?:\n\n|~0)/gm;
function parseStyles(sLine) {
if (/^:[ \t]*--*$/.test(sLine)) {
return ' style="text-align:left;"';
} else if (/^--*[ \t]*:[ \t]*$/.test(sLine)) {
return ' style="text-align:right;"';
} else if (/^:[ \t]*--*[ \t]*:$/.test(sLine)) {
return ' style="text-align:center;"';
} else {
return '';
}
}
function parseHeaders(header, style) {
var id = '';
header = header.trim();
if (options.tableHeaderId) {
id = ' id="' + header.replace(/ /g, '_').toLowerCase() + '"';
}
header = showdown.subParser('spanGamut')(header, options, globals);
return '<th' + id + style + '>' + header + '</th>\n';
}
function parseCells(cell, style) {
var subText = showdown.subParser('spanGamut')(cell, options, globals);
return '<td' + style + '>' + subText + '</td>\n';
}
function buildTable(headers, cells) {
var tb = '<table>\n<thead>\n<tr>\n',
tblLgn = headers.length;
for (var i = 0; i < tblLgn; ++i) {
tb += headers[i];
}
tb += '</tr>\n</thead>\n<tbody>\n';
for (i = 0; i < cells.length; ++i) {
tb += '<tr>\n';
for (var ii = 0; ii < tblLgn; ++ii) {
tb += cells[i][ii];
}
tb += '</tr>\n';
}
tb += '</tbody>\n</table>\n';
return tb;
}
text = globals.converter._dispatch('tables.before', text, options, globals);
text = text.replace(tableRgx, function (rawTable) {
var i, tableLines = rawTable.split('\n');
// strip wrong first and last column if wrapped tables are used
for (i = 0; i < tableLines.length; ++i) {
if (/^ {0,3}\|/.test(tableLines[i])) {
tableLines[i] = tableLines[i].replace(/^ {0,3}\|/, '');
}
if (/\|[ \t]*$/.test(tableLines[i])) {
tableLines[i] = tableLines[i].replace(/\|[ \t]*$/, '');
}
}
var rawHeaders = tableLines[0].split('|').map(function (s) { return s.trim();}),
rawStyles = tableLines[1].split('|').map(function (s) { return s.trim();}),
rawCells = [],
headers = [],
styles = [],
cells = [];
tableLines.shift();
tableLines.shift();
for (i = 0; i < tableLines.length; ++i) {
if (tableLines[i].trim() === '') {
continue;
}
rawCells.push(
tableLines[i]
.split('|')
.map(function (s) {
return s.trim();
})
);
}
if (rawHeaders.length < rawStyles.length) {
return rawTable;
}
for (i = 0; i < rawStyles.length; ++i) {
styles.push(parseStyles(rawStyles[i]));
}
for (i = 0; i < rawHeaders.length; ++i) {
if (showdown.helper.isUndefined(styles[i])) {
styles[i] = '';
}
headers.push(parseHeaders(rawHeaders[i], styles[i]));
}
for (i = 0; i < rawCells.length; ++i) {
var row = [];
for (var ii = 0; ii < headers.length; ++ii) {
if (showdown.helper.isUndefined(rawCells[i][ii])) {
}
row.push(parseCells(rawCells[i][ii], styles[ii]));
}
cells.push(row);
}
return buildTable(headers, cells);
});
text = globals.converter._dispatch('tables.after', text, options, globals);
return text;
});
/**
* Swap back in all the special characters we've hidden.
*/
showdown.subParser('unescapeSpecialChars', function (text) {
'use strict';
text = text.replace(/~E(\d+)E/g, function (wholeMatch, m1) {
var charCodeToReplace = parseInt(m1);
return String.fromCharCode(charCodeToReplace);
});
return text;
});
var root = this;
// CommonJS/nodeJS Loader
if (typeof module !== 'undefined' && module.exports) {
module.exports = showdown;
// AMD Loader
} else if (typeof define === 'function' && define.amd) {
define(function () {
'use strict';
return showdown;
});
// Regular Browser loader
} else {
root.showdown = showdown;
}
}).call(this);
//# sourceMappingURL=showdown.js.map
|
/* */
"format cjs";
/* eslint no-unused-vars: 0 */
"use strict";
exports.__esModule = true;
// istanbul ignore next
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
var _types = require("../../../types");
var t = _interopRequireWildcard(_types);
var metadata = {
group: "builtin-pre"
};
/**
* [Please add a description.]
*/
exports.metadata = metadata;
function isString(node) {
return t.isLiteral(node) && typeof node.value === "string";
}
/**
* [Please add a description.]
*/
function buildBinaryExpression(left, right) {
var node = t.binaryExpression("+", left, right);
node._templateLiteralProduced = true;
return node;
}
/**
* [Please add a description.]
*/
function crawl(path) {
if (path.is("_templateLiteralProduced")) {
crawl(path.get("left"));
crawl(path.get("right"));
} else if (!path.isBaseType("string") && !path.isBaseType("number")) {
path.replaceWith(t.callExpression(t.identifier("String"), [path.node]));
}
}
/**
* [Please add a description.]
*/
var visitor = {
/**
* [Please add a description.]
*/
TaggedTemplateExpression: function TaggedTemplateExpression(node, parent, scope, file) {
var quasi = node.quasi;
var args = [];
var strings = [];
var raw = [];
var _arr = quasi.quasis;
for (var _i = 0; _i < _arr.length; _i++) {
var elem = _arr[_i];
strings.push(t.literal(elem.value.cooked));
raw.push(t.literal(elem.value.raw));
}
strings = t.arrayExpression(strings);
raw = t.arrayExpression(raw);
var templateName = "tagged-template-literal";
if (file.isLoose("es6.templateLiterals")) templateName += "-loose";
var templateObject = file.addTemplateObject(templateName, strings, raw);
args.push(templateObject);
args = args.concat(quasi.expressions);
return t.callExpression(node.tag, args);
},
/**
* [Please add a description.]
*/
TemplateLiteral: function TemplateLiteral(node, parent, scope, file) {
var nodes = [];
var _arr2 = node.quasis;
// filter out empty string literals
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var elem = _arr2[_i2];
nodes.push(t.literal(elem.value.cooked));
var expr = node.expressions.shift();
if (expr) nodes.push(expr);
}nodes = nodes.filter(function (n) {
return !t.isLiteral(n, { value: "" });
});
// since `+` is left-to-right associative
// ensure the first node is a string if first/second isn't
if (!isString(nodes[0]) && !isString(nodes[1])) {
nodes.unshift(t.literal(""));
}
if (nodes.length > 1) {
var root = buildBinaryExpression(nodes.shift(), nodes.shift());
var _arr3 = nodes;
for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
var _node = _arr3[_i3];
root = buildBinaryExpression(root, _node);
}
this.replaceWith(root);
//crawl(this);
} else {
return nodes[0];
}
}
};
exports.visitor = visitor; |
YUI.add('loader-yui3', function(Y) {
/* This file is auto-generated by src/loader/meta_join.py */
/**
* YUI 3 module metadata
* @module loader
* @submodule yui3
*/
YUI.Env[Y.version].modules = YUI.Env[Y.version].modules || {
"anim": {
"submodules": {
"anim-base": {
"requires": [
"base-base",
"node-style"
]
},
"anim-color": {
"requires": [
"anim-base"
]
},
"anim-curve": {
"requires": [
"anim-xy"
]
},
"anim-easing": {
"requires": [
"anim-base"
]
},
"anim-node-plugin": {
"requires": [
"node-pluginhost",
"anim-base"
]
},
"anim-scroll": {
"requires": [
"anim-base"
]
},
"anim-xy": {
"requires": [
"anim-base",
"node-screen"
]
}
}
},
"arraysort": {
"requires": [
"yui-base"
]
},
"async-queue": {
"requires": [
"event-custom"
]
},
"attribute": {
"submodules": {
"attribute-base": {
"requires": [
"event-custom"
]
},
"attribute-complex": {
"requires": [
"attribute-base"
]
}
}
},
"autocomplete": {
"submodules": {
"autocomplete-base": {
"optional": [
"autocomplete-sources"
],
"plugins": {
"autocomplete-filters": {
"path": "autocomplete/autocomplete-filters-min.js",
"requires": [
"array-extras",
"text-wordbreak"
]
},
"autocomplete-filters-accentfold": {
"path": "autocomplete/autocomplete-filters-accentfold-min.js",
"requires": [
"array-extras",
"text-accentfold",
"text-wordbreak"
]
},
"autocomplete-highlighters": {
"path": "autocomplete/autocomplete-highlighters-min.js",
"requires": [
"array-extras",
"highlight-base"
]
},
"autocomplete-highlighters-accentfold": {
"path": "autocomplete/autocomplete-highlighters-accentfold-min.js",
"requires": [
"array-extras",
"highlight-accentfold"
]
}
},
"requires": [
"array-extras",
"base-build",
"escape",
"event-valuechange",
"node-base"
]
},
"autocomplete-list": {
"after": "autocomplete-sources",
"lang": [
"en"
],
"plugins": {
"autocomplete-list-keys": {
"condition": {
"test": function (Y) {
// Only add keyboard support to autocomplete-list if this doesn't appear to
// be an iOS or Android-based mobile device.
//
// There's currently no feasible way to actually detect whether a device has
// a hardware keyboard, so this sniff will have to do. It can easily be
// overridden by manually loading the autocomplete-list-keys module.
//
// Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari
// doesn't fire the keyboard events used by AutoCompleteList, so there's
// no point loading the -keys module even when a bluetooth keyboard may be
// available.
return !(Y.UA.ios || Y.UA.android);
},
"trigger": "autocomplete-list"
},
"path": "autocomplete/autocomplete-list-keys-min.js",
"requires": [
"autocomplete-list",
"base-build"
]
},
"autocomplete-plugin": {
"path": "autocomplete/autocomplete-plugin-min.js",
"requires": [
"autocomplete-list",
"node-pluginhost"
]
}
},
"requires": [
"autocomplete-base",
"selector-css3",
"widget",
"widget-position",
"widget-position-align",
"widget-stack"
],
"skinnable": true
},
"autocomplete-sources": {
"optional": [
"io-base",
"json-parse",
"jsonp",
"yql"
],
"requires": [
"autocomplete-base"
]
}
}
},
"base": {
"submodules": {
"base-base": {
"after": [
"attribute-complex"
],
"requires": [
"attribute-base"
]
},
"base-build": {
"requires": [
"base-base"
]
},
"base-pluginhost": {
"requires": [
"base-base",
"pluginhost"
]
}
}
},
"cache": {
"submodules": {
"cache-base": {
"requires": [
"base"
]
},
"cache-offline": {
"requires": [
"cache-base",
"json"
]
},
"cache-plugin": {
"requires": [
"plugin",
"cache-base"
]
}
}
},
"charts": {
"requires": [
"dom",
"datatype",
"event-custom",
"event-mouseenter",
"widget",
"widget-position",
"widget-stack"
]
},
"classnamemanager": {
"requires": [
"yui-base"
]
},
"collection": {
"submodules": {
"array-extras": {},
"array-invoke": {},
"arraylist": {},
"arraylist-add": {
"requires": [
"arraylist"
]
},
"arraylist-filter": {
"requires": [
"arraylist"
]
}
}
},
"compat": {
"requires": [
"event-base",
"dom",
"dump",
"substitute"
]
},
"console": {
"lang": [
"en",
"es"
],
"plugins": {
"console-filters": {
"requires": [
"plugin",
"console"
],
"skinnable": true
}
},
"requires": [
"yui-log",
"widget",
"substitute"
],
"skinnable": true
},
"cookie": {
"requires": [
"yui-base"
]
},
"cssbase": {
"after": [
"cssreset",
"cssfonts",
"cssgrids",
"cssreset-context",
"cssfonts-context",
"cssgrids-context"
],
"path": "cssbase/base-min.css",
"type": "css"
},
"cssbase-context": {
"after": [
"cssreset",
"cssfonts",
"cssgrids",
"cssreset-context",
"cssfonts-context",
"cssgrids-context"
],
"path": "cssbase/base-context-min.css",
"type": "css"
},
"cssfonts": {
"path": "cssfonts/fonts-min.css",
"type": "css"
},
"cssfonts-context": {
"path": "cssfonts/fonts-context-min.css",
"type": "css"
},
"cssgrids": {
"optional": [
"cssreset",
"cssfonts"
],
"path": "cssgrids/grids-min.css",
"type": "css"
},
"cssgrids-context-deprecated": {
"optional": [
"cssreset-context"
],
"path": "cssgrids-deprecated/grids-context-min.css",
"requires": [
"cssfonts-context"
],
"type": "css"
},
"cssgrids-deprecated": {
"optional": [
"cssreset"
],
"path": "cssgrids-deprecated/grids-min.css",
"requires": [
"cssfonts"
],
"type": "css"
},
"cssreset": {
"path": "cssreset/reset-min.css",
"type": "css"
},
"cssreset-context": {
"path": "cssreset/reset-context-min.css",
"type": "css"
},
"dataschema": {
"submodules": {
"dataschema-array": {
"requires": [
"dataschema-base"
]
},
"dataschema-base": {
"requires": [
"base"
]
},
"dataschema-json": {
"requires": [
"dataschema-base",
"json"
]
},
"dataschema-text": {
"requires": [
"dataschema-base"
]
},
"dataschema-xml": {
"requires": [
"dataschema-base"
]
}
}
},
"datasource": {
"submodules": {
"datasource-arrayschema": {
"requires": [
"datasource-local",
"plugin",
"dataschema-array"
]
},
"datasource-cache": {
"requires": [
"datasource-local",
"cache-base"
]
},
"datasource-function": {
"requires": [
"datasource-local"
]
},
"datasource-get": {
"requires": [
"datasource-local",
"get"
]
},
"datasource-io": {
"requires": [
"datasource-local",
"io-base"
]
},
"datasource-jsonschema": {
"requires": [
"datasource-local",
"plugin",
"dataschema-json"
]
},
"datasource-local": {
"requires": [
"base"
]
},
"datasource-polling": {
"requires": [
"datasource-local"
]
},
"datasource-textschema": {
"requires": [
"datasource-local",
"plugin",
"dataschema-text"
]
},
"datasource-xmlschema": {
"requires": [
"datasource-local",
"plugin",
"dataschema-xml"
]
}
}
},
"datatable": {
"submodules": {
"datatable-base": {
"requires": [
"recordset-base",
"widget",
"substitute",
"event-mouseenter"
],
"skinnable": true
},
"datatable-datasource": {
"requires": [
"datatable-base",
"plugin",
"datasource-local"
]
},
"datatable-scroll": {
"requires": [
"datatable-base",
"plugin",
"stylesheet"
]
},
"datatable-sort": {
"lang": [
"en"
],
"requires": [
"datatable-base",
"plugin",
"recordset-sort"
]
}
}
},
"datatype": {
"submodules": {
"datatype-date": {
"lang": [
"ar",
"ar-JO",
"ca",
"ca-ES",
"da",
"da-DK",
"de",
"de-AT",
"de-DE",
"el",
"el-GR",
"en",
"en-AU",
"en-CA",
"en-GB",
"en-IE",
"en-IN",
"en-JO",
"en-MY",
"en-NZ",
"en-PH",
"en-SG",
"en-US",
"es",
"es-AR",
"es-BO",
"es-CL",
"es-CO",
"es-EC",
"es-ES",
"es-MX",
"es-PE",
"es-PY",
"es-US",
"es-UY",
"es-VE",
"fi",
"fi-FI",
"fr",
"fr-BE",
"fr-CA",
"fr-FR",
"hi",
"hi-IN",
"id",
"id-ID",
"it",
"it-IT",
"ja",
"ja-JP",
"ko",
"ko-KR",
"ms",
"ms-MY",
"nb",
"nb-NO",
"nl",
"nl-BE",
"nl-NL",
"pl",
"pl-PL",
"pt",
"pt-BR",
"ro",
"ro-RO",
"ru",
"ru-RU",
"sv",
"sv-SE",
"th",
"th-TH",
"tr",
"tr-TR",
"vi",
"vi-VN",
"zh-Hans",
"zh-Hans-CN",
"zh-Hant",
"zh-Hant-HK",
"zh-Hant-TW"
],
"requires": [
"yui-base"
],
"supersedes": [
"datatype-date-format"
]
},
"datatype-number": {
"requires": [
"yui-base"
]
},
"datatype-xml": {
"requires": [
"yui-base"
]
}
}
},
"datatype-date-format": {
"path": "datatype/datatype-date-format-min.js"
},
"dd": {
"plugins": {
"dd-drop-plugin": {
"requires": [
"dd-drop"
]
},
"dd-gestures": {
"condition": {
"test": function(Y) {
return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome));
},
"trigger": "dd-drag"
},
"requires": [
"dd-drag",
"event-move"
]
},
"dd-plugin": {
"optional": [
"dd-constrain",
"dd-proxy"
],
"requires": [
"dd-drag"
]
}
},
"submodules": {
"dd-constrain": {
"requires": [
"dd-drag"
]
},
"dd-ddm": {
"requires": [
"dd-ddm-base",
"event-resize"
]
},
"dd-ddm-base": {
"requires": [
"node",
"base",
"yui-throttle",
"classnamemanager"
]
},
"dd-ddm-drop": {
"requires": [
"dd-ddm"
]
},
"dd-delegate": {
"requires": [
"dd-drag",
"dd-drop-plugin",
"event-mouseenter"
]
},
"dd-drag": {
"requires": [
"dd-ddm-base"
]
},
"dd-drop": {
"requires": [
"dd-ddm-drop"
]
},
"dd-proxy": {
"requires": [
"dd-drag"
]
},
"dd-scroll": {
"requires": [
"dd-drag"
]
}
}
},
"dial": {
"lang": [
"en",
"es"
],
"requires": [
"widget",
"dd-drag",
"substitute",
"event-mouseenter",
"transition",
"intl"
],
"skinnable": true
},
"dom": {
"plugins": {
"dom-deprecated": {
"requires": [
"dom-base"
]
},
"dom-style-ie": {
"condition": {
"test": function (Y) {
var testFeature = Y.Features.test,
addFeature = Y.Features.add,
WINDOW = Y.config.win,
DOCUMENT = Y.config.doc,
DOCUMENT_ELEMENT = 'documentElement',
ret = false;
addFeature('style', 'computedStyle', {
test: function() {
return WINDOW && 'getComputedStyle' in WINDOW;
}
});
addFeature('style', 'opacity', {
test: function() {
return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style;
}
});
ret = (!testFeature('style', 'opacity') &&
!testFeature('style', 'computedStyle'));
return ret;
},
"trigger": "dom-style"
},
"requires": [
"dom-style"
]
},
"selector-css3": {
"requires": [
"selector-css2"
]
}
},
"requires": [
"oop"
],
"submodules": {
"dom-base": {
"requires": [
"oop"
]
},
"dom-screen": {
"requires": [
"dom-base",
"dom-style"
]
},
"dom-style": {
"requires": [
"dom-base"
]
},
"selector": {
"requires": [
"dom-base"
]
},
"selector-css2": {
"requires": [
"selector-native"
]
},
"selector-native": {
"requires": [
"dom-base"
]
}
}
},
"dump": {
"requires": [
"yui-base"
]
},
"editor": {
"submodules": {
"createlink-base": {
"requires": [
"editor-base"
]
},
"editor-base": {
"requires": [
"base",
"frame",
"node",
"exec-command",
"selection"
]
},
"editor-bidi": {
"requires": [
"editor-base"
]
},
"editor-br": {
"requires": [
"node"
]
},
"editor-lists": {
"requires": [
"editor-base"
]
},
"editor-para": {
"requires": [
"node"
]
},
"exec-command": {
"requires": [
"frame"
]
},
"frame": {
"requires": [
"base",
"node",
"selector-css3",
"substitute"
]
},
"selection": {
"requires": [
"node"
]
}
}
},
"escape": {},
"event": {
"after": "node-base",
"plugins": {
"event-base-ie": {
"after": [
"event-base"
],
"condition": {
"test": function(Y) {
var imp = Y.config.doc && Y.config.doc.implementation;
return (imp && (!imp.hasFeature('Events', '2.0')));
},
"trigger": "node-base"
},
"requires": [
"node-base"
]
},
"event-touch": {
"requires": [
"node-base"
]
}
},
"submodules": {
"event-base": {
"after": "node-base",
"requires": [
"event-custom-base"
]
},
"event-delegate": {
"requires": [
"node-base"
]
},
"event-focus": {
"requires": [
"event-synthetic"
]
},
"event-hover": {
"requires": [
"event-synthetic"
]
},
"event-key": {
"requires": [
"event-synthetic"
]
},
"event-mouseenter": {
"requires": [
"event-synthetic"
]
},
"event-mousewheel": {
"requires": [
"event-synthetic"
]
},
"event-resize": {
"requires": [
"event-synthetic"
]
},
"event-synthetic": {
"requires": [
"node-base",
"event-custom-complex"
]
}
}
},
"event-custom": {
"submodules": {
"event-custom-base": {
"requires": [
"oop"
]
},
"event-custom-complex": {
"requires": [
"event-custom-base"
]
}
}
},
"event-gestures": {
"submodules": {
"event-flick": {
"requires": [
"node-base",
"event-touch",
"event-synthetic"
]
},
"event-move": {
"requires": [
"node-base",
"event-touch",
"event-synthetic"
]
}
}
},
"event-simulate": {
"requires": [
"event-base"
]
},
"event-valuechange": {
"requires": [
"event-focus",
"event-synthetic"
]
},
"highlight": {
"submodules": {
"highlight-accentfold": {
"requires": [
"highlight-base",
"text-accentfold"
]
},
"highlight-base": {
"requires": [
"array-extras",
"escape",
"text-wordbreak"
]
}
}
},
"history": {
"plugins": {
"history-hash-ie": {
"condition": {
"test": function (Y) {
var docMode = Y.config.doc.documentMode;
return Y.UA.ie && (!('onhashchange' in Y.config.win) ||
!docMode || docMode < 8);
},
"trigger": "history-hash"
},
"requires": [
"history-hash",
"node-base"
]
}
},
"submodules": {
"history-base": {
"after": [
"history-deprecated"
],
"requires": [
"event-custom-complex"
]
},
"history-hash": {
"after": [
"history-html5"
],
"requires": [
"event-synthetic",
"history-base",
"yui-later"
]
},
"history-html5": {
"optional": [
"json"
],
"requires": [
"event-base",
"history-base",
"node-base"
]
}
}
},
"history-deprecated": {
"requires": [
"node"
]
},
"imageloader": {
"requires": [
"base-base",
"node-style",
"node-screen"
]
},
"intl": {
"requires": [
"intl-base",
"event-custom"
]
},
"io": {
"submodules": {
"io-base": {
"optional": [
"querystring-stringify-simple"
],
"requires": [
"event-custom-base"
]
},
"io-form": {
"requires": [
"io-base",
"node-base",
"node-style"
]
},
"io-queue": {
"requires": [
"io-base",
"queue-promote"
]
},
"io-upload-iframe": {
"requires": [
"io-base",
"node-base"
]
},
"io-xdr": {
"requires": [
"io-base",
"datatype-xml"
]
}
}
},
"json": {
"submodules": {
"json-parse": {
"requires": [
"yui-base"
]
},
"json-stringify": {
"requires": [
"yui-base"
]
}
}
},
"jsonp": {
"plugins": {
"jsonp-url": {
"requires": [
"jsonp"
]
}
},
"requires": [
"get",
"oop"
]
},
"loader": {
"submodules": {
"loader-base": {
"requires": [
"get"
]
},
"loader-rollup": {
"requires": [
"loader-base"
]
},
"loader-yui3": {
"requires": [
"loader-base"
]
}
}
},
"node": {
"plugins": {
"align-plugin": {
"requires": [
"node-screen",
"node-pluginhost"
]
},
"node-deprecated": {
"requires": [
"node-base"
]
},
"node-event-simulate": {
"requires": [
"node-base",
"event-simulate"
]
},
"node-load": {
"requires": [
"node-base",
"io-base"
]
},
"shim-plugin": {
"requires": [
"node-style",
"node-pluginhost"
]
},
"transition": {
"requires": [
"transition-native",
"node-style"
]
},
"transition-native": {
"requires": [
"node-base"
]
}
},
"submodules": {
"node-base": {
"requires": [
"dom-base",
"selector-css2",
"event-base"
]
},
"node-event-delegate": {
"requires": [
"node-base",
"event-delegate"
]
},
"node-pluginhost": {
"requires": [
"node-base",
"pluginhost"
]
},
"node-screen": {
"requires": [
"dom-screen",
"node-base"
]
},
"node-style": {
"requires": [
"dom-style",
"node-base"
]
}
}
},
"node-flick": {
"requires": [
"classnamemanager",
"transition",
"event-flick",
"plugin"
],
"skinnable": true
},
"node-focusmanager": {
"requires": [
"attribute",
"node",
"plugin",
"node-event-simulate",
"event-key",
"event-focus"
]
},
"node-menunav": {
"requires": [
"node",
"classnamemanager",
"plugin",
"node-focusmanager"
],
"skinnable": true
},
"oop": {
"requires": [
"yui-base"
]
},
"overlay": {
"requires": [
"widget",
"widget-stdmod",
"widget-position",
"widget-position-align",
"widget-stack",
"widget-position-constrain"
],
"skinnable": true
},
"plugin": {
"requires": [
"base-base"
]
},
"pluginhost": {
"submodules": {
"pluginhost-base": {
"requires": [
"yui-base"
]
},
"pluginhost-config": {
"requires": [
"pluginhost-base"
]
}
}
},
"profiler": {
"requires": [
"yui-base"
]
},
"querystring": {
"submodules": {
"querystring-parse": {
"requires": [
"yui-base",
"array-extras"
]
},
"querystring-stringify": {
"requires": [
"yui-base"
]
}
}
},
"querystring-parse-simple": {
"path": "querystring/querystring-parse-simple-min.js",
"requires": [
"yui-base"
]
},
"querystring-stringify-simple": {
"path": "querystring/querystring-stringify-simple-min.js",
"requires": [
"yui-base"
]
},
"queue-promote": {
"requires": [
"yui-base"
]
},
"queue-run": {
"path": "async-queue/async-queue-min.js",
"requires": [
"event-custom"
]
},
"recordset": {
"submodules": {
"recordset-base": {
"requires": [
"base",
"arraylist"
]
},
"recordset-filter": {
"requires": [
"recordset-base",
"array-extras",
"plugin"
]
},
"recordset-indexer": {
"requires": [
"recordset-base",
"plugin"
]
},
"recordset-sort": {
"requires": [
"arraysort",
"recordset-base",
"plugin"
]
}
}
},
"resize": {
"submodules": {
"resize-base": {
"requires": [
"widget",
"substitute",
"event",
"oop",
"dd-drag",
"dd-delegate",
"dd-drop"
],
"skinnable": true
},
"resize-constrain": {
"requires": [
"plugin",
"resize-base"
]
},
"resize-proxy": {
"requires": [
"plugin",
"resize-base"
]
}
}
},
"scrollview": {
"plugins": {
"scrollview-base": {
"path": "scrollview/scrollview-base-min.js",
"requires": [
"widget",
"event-gestures",
"transition"
],
"skinnable": true
},
"scrollview-base-ie": {
"condition": {
"trigger": "scrollview-base",
"ua": "ie"
},
"requires": [
"scrollview-base"
]
},
"scrollview-paginator": {
"path": "scrollview/scrollview-paginator-min.js",
"requires": [
"plugin"
]
},
"scrollview-scrollbars": {
"path": "scrollview/scrollview-scrollbars-min.js",
"requires": [
"plugin"
],
"skinnable": true
}
},
"requires": [
"scrollview-base",
"scrollview-scrollbars"
]
},
"slider": {
"submodules": {
"clickable-rail": {
"requires": [
"slider-base"
]
},
"range-slider": {
"requires": [
"slider-base",
"slider-value-range",
"clickable-rail"
]
},
"slider-base": {
"requires": [
"widget",
"dd-constrain",
"substitute"
],
"skinnable": true
},
"slider-value-range": {
"requires": [
"slider-base"
]
}
}
},
"sortable": {
"plugins": {
"sortable-scroll": {
"requires": [
"dd-scroll"
]
}
},
"requires": [
"dd-delegate",
"dd-drop-plugin",
"dd-proxy"
]
},
"stylesheet": {
"requires": [
"yui-base"
]
},
"substitute": {
"optional": [
"dump"
]
},
"swf": {
"requires": [
"event-custom",
"node",
"swfdetect"
]
},
"swfdetect": {},
"tabview": {
"plugins": {
"tabview-base": {
"requires": [
"node-event-delegate",
"classnamemanager",
"skin-sam-tabview"
]
},
"tabview-plugin": {
"requires": [
"tabview-base"
]
}
},
"requires": [
"widget",
"widget-parent",
"widget-child",
"tabview-base",
"node-pluginhost",
"node-focusmanager"
],
"skinnable": true
},
"test": {
"requires": [
"substitute",
"node",
"json",
"event-simulate"
],
"skinnable": true
},
"text": {
"submodules": {
"text-accentfold": {
"requires": [
"array-extras",
"text-data-accentfold"
]
},
"text-data-accentfold": {},
"text-data-wordbreak": {},
"text-wordbreak": {
"requires": [
"array-extras",
"text-data-wordbreak"
]
}
}
},
"transition": {
"submodules": {
"transition-native": {
"requires": [
"node-base"
]
},
"transition-timer": {
"requires": [
"transition-native",
"node-style"
]
}
}
},
"uploader": {
"requires": [
"event-custom",
"node",
"base",
"swf"
]
},
"widget": {
"plugins": {
"widget-base-ie": {
"condition": {
"trigger": "widget-base",
"ua": "ie"
},
"requires": [
"widget-base"
]
},
"widget-child": {
"requires": [
"base-build",
"widget"
]
},
"widget-parent": {
"requires": [
"base-build",
"arraylist",
"widget"
]
},
"widget-position": {
"requires": [
"base-build",
"node-screen",
"widget"
]
},
"widget-position-align": {
"requires": [
"widget-position"
]
},
"widget-position-constrain": {
"requires": [
"widget-position"
]
},
"widget-stack": {
"requires": [
"base-build",
"widget"
],
"skinnable": true
},
"widget-stdmod": {
"requires": [
"base-build",
"widget"
]
}
},
"skinnable": true,
"submodules": {
"widget-base": {
"requires": [
"attribute",
"event-focus",
"base-base",
"base-pluginhost",
"node-base",
"node-style",
"classnamemanager"
]
},
"widget-htmlparser": {
"requires": [
"widget-base"
]
},
"widget-skin": {
"requires": [
"widget-base"
]
},
"widget-uievents": {
"requires": [
"widget-base",
"node-event-delegate"
]
}
}
},
"widget-anim": {
"requires": [
"plugin",
"anim-base",
"widget"
]
},
"widget-locale": {
"path": "widget/widget-locale-min.js",
"requires": [
"widget-base"
]
},
"yql": {
"requires": [
"jsonp",
"jsonp-url"
]
},
"yui": {
"submodules": {
"features": {
"requires": [
"yui-base"
]
},
"get": {
"requires": [
"yui-base"
]
},
"intl-base": {
"requires": [
"yui-base"
]
},
"rls": {
"requires": [
"get",
"features"
]
},
"yui-base": {},
"yui-later": {
"requires": [
"yui-base"
]
},
"yui-log": {
"requires": [
"yui-base"
]
},
"yui-throttle": {
"requires": [
"yui-base"
]
}
}
}
};
YUI.Env[Y.version].md5 = 'faf08d27c01d7ab5575789a63b1e36fc';
}, '@VERSION@' ,{requires:['loader-base']});
|
'use strict';
exports.type = 'perItem';
exports.active = true;
exports.description = 'converts colors: rgb() to #rrggbb and #rrggbb to #rgb';
exports.params = {
currentColor: false,
names2hex: true,
rgb2hex: true,
shorthex: true,
shortname: true
};
var collections = require('./_collections'),
rNumber = '([+-]?(?:\\d*\\.\\d+|\\d+\\.?)%?)',
rComma = '\\s*,\\s*',
regRGB = new RegExp('^rgb\\(\\s*' + rNumber + rComma + rNumber + rComma + rNumber + '\\s*\\)$'),
regHEX = /^\#(([a-fA-F0-9])\2){3}$/,
none = /\bnone\b/i;
/**
* Convert different colors formats in element attributes to hex.
*
* @see http://www.w3.org/TR/SVG/types.html#DataTypeColor
* @see http://www.w3.org/TR/SVG/single-page.html#types-ColorKeywords
*
* @example
* Convert color name keyword to long hex:
* fuchsia ➡ #ff00ff
*
* Convert rgb() to long hex:
* rgb(255, 0, 255) ➡ #ff00ff
* rgb(50%, 100, 100%) ➡ #7f64ff
*
* Convert long hex to short hex:
* #aabbcc ➡ #abc
*
* Convert hex to short name
* #000080 ➡ navy
*
* @param {Object} item current iteration item
* @param {Object} params plugin params
* @return {Boolean} if false, item will be filtered out
*
* @author Kir Belevich
*/
exports.fn = function(item, params) {
if (item.elem) {
item.eachAttr(function(attr) {
if (collections.colorsProps.indexOf(attr.name) > -1) {
var val = attr.value,
match;
// Convert colors to currentColor
if (params.currentColor) {
if (typeof params.currentColor === 'string') {
match = val === params.currentColor;
} else if (params.currentColor.exec) {
match = params.currentColor.exec(val);
} else {
match = !val.match(none);
}
if (match) {
val = 'currentColor';
}
}
// Convert color name keyword to long hex
if (params.names2hex && val.toLowerCase() in collections.colorsNames) {
val = collections.colorsNames[val.toLowerCase()];
}
// Convert rgb() to long hex
if (params.rgb2hex && (match = val.match(regRGB))) {
match = match.slice(1, 4).map(function(m) {
if (m.indexOf('%') > -1)
m = Math.round(parseFloat(m) * 2.55);
return Math.max(0, Math.min(m, 255));
});
val = rgb2hex(match);
}
// Convert long hex to short hex
if (params.shorthex && (match = val.match(regHEX))) {
val = '#' + match[0][1] + match[0][3] + match[0][5];
}
// Convert hex to short name
if (params.shortname) {
var lowerVal = val.toLowerCase();
if (lowerVal in collections.colorsShortNames) {
val = collections.colorsShortNames[lowerVal];
}
}
attr.value = val;
}
});
}
};
/**
* Convert [r, g, b] to #rrggbb.
*
* @see https://gist.github.com/983535
*
* @example
* rgb2hex([255, 255, 255]) // '#ffffff'
*
* @param {Array} rgb [r, g, b]
* @return {String} #rrggbb
*
* @author Jed Schmidt
*/
function rgb2hex(rgb) {
return '#' + ('00000' + (rgb[0] << 16 | rgb[1] << 8 | rgb[2]).toString(16)).slice(-6).toUpperCase();
}
|
IntlMessageFormat.__addLocaleData({locale:"jmc", messageformat:{pluralFunction:function (n) { n=Math.floor(n);if(n===1)return"one";return"other"; }}}); |
/*!
* Kraken v7.3.0: A lightweight front-end boilerplate
* (c) 2016 Chris Ferdinandi
* MIT License
* http://github.com/cferdinandi/kraken
*/
;(function (window, document, undefined) {
'use strict';
// SVG feature detection
var supports = !!document.createElementNS && !!document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect;
if ( !supports ) return;
// Add `.svg` class to <html> element
document.documentElement.className += (document.documentElement.className ? ' ' : '') + 'svg';
})(window, document); |
(function($) {
if (typeof _wpcf7 == 'undefined' || _wpcf7 === null)
_wpcf7 = {};
_wpcf7 = $.extend({ cached: 0 }, _wpcf7);
$(function() {
_wpcf7.supportHtml5 = $.wpcf7SupportHtml5();
$('div.wpcf7 > form').wpcf7InitForm();
});
$.fn.wpcf7InitForm = function() {
this.ajaxForm({
beforeSubmit: function(arr, $form, options) {
$form.wpcf7ClearResponseOutput();
$form.find('[aria-invalid]').attr('aria-invalid', 'false');
$form.find('img.ajax-loader').css({ visibility: 'visible' });
return true;
},
beforeSerialize: function($form, options) {
$form.find('[placeholder].placeheld').each(function(i, n) {
$(n).val('');
});
return true;
},
data: { '_wpcf7_is_ajax_call': 1 },
dataType: 'json',
success: $.wpcf7AjaxSuccess,
error: function(xhr, status, error, $form) {
var e = $('<div class="ajax-error"></div>').text(error.message);
$form.after(e);
}
});
if (_wpcf7.cached)
this.wpcf7OnloadRefill();
this.wpcf7ToggleSubmit();
this.find('.wpcf7-submit').wpcf7AjaxLoader();
this.find('.wpcf7-acceptance').click(function() {
$(this).closest('form').wpcf7ToggleSubmit();
});
this.find('.wpcf7-exclusive-checkbox').wpcf7ExclusiveCheckbox();
this.find('.wpcf7-list-item.has-free-text').wpcf7ToggleCheckboxFreetext();
this.find('[placeholder]').wpcf7Placeholder();
if (_wpcf7.jqueryUi && ! _wpcf7.supportHtml5.date) {
this.find('input.wpcf7-date[type="date"]').each(function() {
$(this).datepicker({
dateFormat: 'yy-mm-dd',
minDate: new Date($(this).attr('min')),
maxDate: new Date($(this).attr('max'))
});
});
}
if (_wpcf7.jqueryUi && ! _wpcf7.supportHtml5.number) {
this.find('input.wpcf7-number[type="number"]').each(function() {
$(this).spinner({
min: $(this).attr('min'),
max: $(this).attr('max'),
step: $(this).attr('step')
});
});
}
this.find('.wpcf7-character-count').wpcf7CharacterCount();
this.find('.wpcf7-validates-as-url').change(function() {
$(this).wpcf7NormalizeUrl();
});
};
$.wpcf7AjaxSuccess = function(data, status, xhr, $form) {
if (! $.isPlainObject(data) || $.isEmptyObject(data))
return;
var $responseOutput = $form.find('div.wpcf7-response-output');
$form.wpcf7ClearResponseOutput();
$form.find('.wpcf7-form-control').removeClass('wpcf7-not-valid');
$form.removeClass('invalid spam sent failed');
if (data.captcha)
$form.wpcf7RefillCaptcha(data.captcha);
if (data.quiz)
$form.wpcf7RefillQuiz(data.quiz);
if (data.invalids) {
$.each(data.invalids, function(i, n) {
$form.find(n.into).wpcf7NotValidTip(n.message);
$form.find(n.into).find('.wpcf7-form-control').addClass('wpcf7-not-valid');
$form.find(n.into).find('[aria-invalid]').attr('aria-invalid', 'true');
});
$responseOutput.addClass('wpcf7-validation-errors');
$form.addClass('invalid');
$(data.into).trigger('invalid.wpcf7');
} else if (1 == data.spam) {
$responseOutput.addClass('wpcf7-spam-blocked');
$form.addClass('spam');
$(data.into).trigger('spam.wpcf7');
} else if (1 == data.mailSent) {
$responseOutput.addClass('wpcf7-mail-sent-ok');
$form.addClass('sent');
if (data.onSentOk)
$.each(data.onSentOk, function(i, n) { eval(n) });
$(data.into).trigger('mailsent.wpcf7');
} else {
$responseOutput.addClass('wpcf7-mail-sent-ng');
$form.addClass('failed');
$(data.into).trigger('mailfailed.wpcf7');
}
if (data.onSubmit)
$.each(data.onSubmit, function(i, n) { eval(n) });
$(data.into).trigger('submit.wpcf7');
if (1 == data.mailSent)
$form.resetForm();
$form.find('[placeholder].placeheld').each(function(i, n) {
$(n).val($(n).attr('placeholder'));
});
$responseOutput.append(data.message).slideDown('fast');
$responseOutput.attr('role', 'alert');
$.wpcf7UpdateScreenReaderResponse($form, data);
};
$.fn.wpcf7ExclusiveCheckbox = function() {
return this.find('input:checkbox').click(function() {
$(this).closest('.wpcf7-checkbox').find('input:checkbox').not(this).removeAttr('checked');
});
};
$.fn.wpcf7Placeholder = function() {
if (_wpcf7.supportHtml5.placeholder)
return this;
return this.each(function() {
$(this).val($(this).attr('placeholder'));
$(this).addClass('placeheld');
$(this).focus(function() {
if ($(this).hasClass('placeheld'))
$(this).val('').removeClass('placeheld');
});
$(this).blur(function() {
if ('' == $(this).val()) {
$(this).val($(this).attr('placeholder'));
$(this).addClass('placeheld');
}
});
});
};
$.fn.wpcf7AjaxLoader = function() {
return this.each(function() {
var loader = $('<img class="ajax-loader" />')
.attr({ src: _wpcf7.loaderUrl, alt: _wpcf7.sending })
.css('visibility', 'hidden');
$(this).after(loader);
});
};
$.fn.wpcf7ToggleSubmit = function() {
return this.each(function() {
var form = $(this);
if (this.tagName.toLowerCase() != 'form')
form = $(this).find('form').first();
if (form.hasClass('wpcf7-acceptance-as-validation'))
return;
var submit = form.find('input:submit');
if (! submit.length) return;
var acceptances = form.find('input:checkbox.wpcf7-acceptance');
if (! acceptances.length) return;
submit.removeAttr('disabled');
acceptances.each(function(i, n) {
n = $(n);
if (n.hasClass('wpcf7-invert') && n.is(':checked')
|| ! n.hasClass('wpcf7-invert') && ! n.is(':checked'))
submit.attr('disabled', 'disabled');
});
});
};
$.fn.wpcf7ToggleCheckboxFreetext = function() {
return this.each(function() {
var $wrap = $(this).closest('.wpcf7-form-control');
if ($(this).find(':checkbox, :radio').is(':checked')) {
$(this).find(':input.wpcf7-free-text').prop('disabled', false);
} else {
$(this).find(':input.wpcf7-free-text').prop('disabled', true);
}
$wrap.find(':checkbox, :radio').change(function() {
var $cb = $('.has-free-text', $wrap).find(':checkbox, :radio');
var $freetext = $(':input.wpcf7-free-text', $wrap);
if ($cb.is(':checked')) {
$freetext.prop('disabled', false).focus();
} else {
$freetext.prop('disabled', true);
}
});
});
};
$.fn.wpcf7CharacterCount = function() {
return this.each(function() {
var $count = $(this);
var name = $count.attr('data-target-name');
var down = $count.hasClass('down');
var starting = parseInt($count.attr('data-starting-value'), 10);
var maximum = parseInt($count.attr('data-maximum-value'), 10);
var minimum = parseInt($count.attr('data-minimum-value'), 10);
var updateCount = function($target) {
var length = $target.val().length;
var count = down ? starting - length : length;
$count.attr('data-current-value', count);
$count.text(count);
if (maximum && maximum < length) {
$count.addClass('too-long');
} else {
$count.removeClass('too-long');
}
if (minimum && length < minimum) {
$count.addClass('too-short');
} else {
$count.removeClass('too-short');
}
};
$count.closest('form').find(':input[name="' + name + '"]').each(function() {
updateCount($(this));
$(this).keyup(function() {
updateCount($(this));
});
});
});
};
$.fn.wpcf7NormalizeUrl = function() {
return this.each(function() {
var val = $.trim($(this).val());
if (! val.match(/^[a-z][a-z0-9.+-]*:/i)) { // check the scheme part
val = val.replace(/^\/+/, '');
val = 'http://' + val;
}
$(this).val(val);
});
};
$.fn.wpcf7NotValidTip = function(message) {
return this.each(function() {
var $into = $(this);
$into.find('span.wpcf7-not-valid-tip').remove();
$into.append('<span role="alert" class="wpcf7-not-valid-tip">' + message + '</span>');
if ($into.is('.use-floating-validation-tip *')) {
$('.wpcf7-not-valid-tip', $into).mouseover(function() {
$(this).wpcf7FadeOut();
});
$(':input', $into).focus(function() {
$('.wpcf7-not-valid-tip', $into).not(':hidden').wpcf7FadeOut();
});
}
});
};
$.fn.wpcf7FadeOut = function() {
return this.each(function() {
$(this).animate({
opacity: 0
}, 'fast', function() {
$(this).css({'z-index': -100});
});
});
};
$.fn.wpcf7OnloadRefill = function() {
return this.each(function() {
var url = $(this).attr('action');
if (0 < url.indexOf('#'))
url = url.substr(0, url.indexOf('#'));
var id = $(this).find('input[name="_wpcf7"]').val();
var unitTag = $(this).find('input[name="_wpcf7_unit_tag"]').val();
$.getJSON(url,
{ _wpcf7_is_ajax_call: 1, _wpcf7: id, _wpcf7_request_ver: $.now() },
function(data) {
if (data && data.captcha)
$('#' + unitTag).wpcf7RefillCaptcha(data.captcha);
if (data && data.quiz)
$('#' + unitTag).wpcf7RefillQuiz(data.quiz);
}
);
});
};
$.fn.wpcf7RefillCaptcha = function(captcha) {
return this.each(function() {
var form = $(this);
$.each(captcha, function(i, n) {
form.find(':input[name="' + i + '"]').clearFields();
form.find('img.wpcf7-captcha-' + i).attr('src', n);
var match = /([0-9]+)\.(png|gif|jpeg)$/.exec(n);
form.find('input:hidden[name="_wpcf7_captcha_challenge_' + i + '"]').attr('value', match[1]);
});
});
};
$.fn.wpcf7RefillQuiz = function(quiz) {
return this.each(function() {
var form = $(this);
$.each(quiz, function(i, n) {
form.find(':input[name="' + i + '"]').clearFields();
form.find(':input[name="' + i + '"]').siblings('span.wpcf7-quiz-label').text(n[0]);
form.find('input:hidden[name="_wpcf7_quiz_answer_' + i + '"]').attr('value', n[1]);
});
});
};
$.fn.wpcf7ClearResponseOutput = function() {
return this.each(function() {
$(this).find('div.wpcf7-response-output').hide().empty().removeClass('wpcf7-mail-sent-ok wpcf7-mail-sent-ng wpcf7-validation-errors wpcf7-spam-blocked').removeAttr('role');
$(this).find('span.wpcf7-not-valid-tip').remove();
$(this).find('img.ajax-loader').css({ visibility: 'hidden' });
});
};
$.wpcf7UpdateScreenReaderResponse = function($form, data) {
$('.wpcf7 .screen-reader-response').html('').attr('role', '');
if (data.message) {
var $response = $form.siblings('.screen-reader-response').first();
$response.append(data.message);
if (data.invalids) {
var $invalids = $('<ul></ul>');
$.each(data.invalids, function(i, n) {
if (n.idref) {
var $li = $('<li></li>').append($('<a></a>').attr('href', '#' + n.idref).append(n.message));
} else {
var $li = $('<li></li>').append(n.message);
}
$invalids.append($li);
});
$response.append($invalids);
}
$response.attr('role', 'alert').focus();
}
};
$.wpcf7SupportHtml5 = function() {
var features = {};
var input = document.createElement('input');
features.placeholder = 'placeholder' in input;
var inputTypes = ['email', 'url', 'tel', 'number', 'range', 'date'];
$.each(inputTypes, function(index, value) {
input.setAttribute('type', value);
features[value] = input.type !== 'text';
});
return features;
};
})(jQuery); |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
},{}],2:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
// Shimming starts here.
(function() {
// Utils.
var utils = require('./utils');
var logging = utils.log;
var browserDetails = utils.browserDetails;
// Export to the adapter global object visible in the browser.
module.exports.browserDetails = browserDetails;
module.exports.extractVersion = utils.extractVersion;
module.exports.disableLog = utils.disableLog;
// Uncomment the line below if you want logging to occur, including logging
// for the switch statement below. Can also be turned on in the browser via
// adapter.disableLog(false), but then logging from the switch statement below
// will not appear.
// require('./utils').disableLog(false);
// Browser shims.
var chromeShim = require('./chrome/chrome_shim') || null;
var edgeShim = require('./edge/edge_shim') || null;
var firefoxShim = require('./firefox/firefox_shim') || null;
var safariShim = require('./safari/safari_shim') || null;
// Shim browser if found.
switch (browserDetails.browser) {
case 'chrome':
if (!chromeShim || !chromeShim.shimPeerConnection) {
logging('Chrome shim is not included in this adapter release.');
return;
}
logging('adapter.js shimming chrome.');
// Export to the adapter global object visible in the browser.
module.exports.browserShim = chromeShim;
chromeShim.shimGetUserMedia();
chromeShim.shimMediaStream();
utils.shimCreateObjectURL();
chromeShim.shimSourceObject();
chromeShim.shimPeerConnection();
chromeShim.shimOnTrack();
chromeShim.shimGetSendersWithDtmf();
break;
case 'firefox':
if (!firefoxShim || !firefoxShim.shimPeerConnection) {
logging('Firefox shim is not included in this adapter release.');
return;
}
logging('adapter.js shimming firefox.');
// Export to the adapter global object visible in the browser.
module.exports.browserShim = firefoxShim;
firefoxShim.shimGetUserMedia();
utils.shimCreateObjectURL();
firefoxShim.shimSourceObject();
firefoxShim.shimPeerConnection();
firefoxShim.shimOnTrack();
break;
case 'edge':
if (!edgeShim || !edgeShim.shimPeerConnection) {
logging('MS edge shim is not included in this adapter release.');
return;
}
logging('adapter.js shimming edge.');
// Export to the adapter global object visible in the browser.
module.exports.browserShim = edgeShim;
edgeShim.shimGetUserMedia();
utils.shimCreateObjectURL();
edgeShim.shimPeerConnection();
edgeShim.shimReplaceTrack();
break;
case 'safari':
if (!safariShim) {
logging('Safari shim is not included in this adapter release.');
return;
}
logging('adapter.js shimming safari.');
// Export to the adapter global object visible in the browser.
module.exports.browserShim = safariShim;
safariShim.shimOnAddStream();
safariShim.shimGetUserMedia();
break;
default:
logging('Unsupported browser!');
}
})();
},{"./chrome/chrome_shim":3,"./edge/edge_shim":1,"./firefox/firefox_shim":5,"./safari/safari_shim":7,"./utils":8}],3:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var logging = require('../utils.js').log;
var browserDetails = require('../utils.js').browserDetails;
var chromeShim = {
shimMediaStream: function() {
window.MediaStream = window.MediaStream || window.webkitMediaStream;
},
shimOnTrack: function() {
if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
window.RTCPeerConnection.prototype)) {
Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
get: function() {
return this._ontrack;
},
set: function(f) {
var self = this;
if (this._ontrack) {
this.removeEventListener('track', this._ontrack);
this.removeEventListener('addstream', this._ontrackpoly);
}
this.addEventListener('track', this._ontrack = f);
this.addEventListener('addstream', this._ontrackpoly = function(e) {
// onaddstream does not fire when a track is added to an existing
// stream. But stream.onaddtrack is implemented so we use that.
e.stream.addEventListener('addtrack', function(te) {
var event = new Event('track');
event.track = te.track;
event.receiver = {track: te.track};
event.streams = [e.stream];
self.dispatchEvent(event);
});
e.stream.getTracks().forEach(function(track) {
var event = new Event('track');
event.track = track;
event.receiver = {track: track};
event.streams = [e.stream];
this.dispatchEvent(event);
}.bind(this));
}.bind(this));
}
});
}
},
shimGetSendersWithDtmf: function() {
if (typeof window === 'object' && window.RTCPeerConnection &&
!('getSenders' in RTCPeerConnection.prototype) &&
'createDTMFSender' in RTCPeerConnection.prototype) {
RTCPeerConnection.prototype.getSenders = function() {
return this._senders;
};
var origAddStream = RTCPeerConnection.prototype.addStream;
var origRemoveStream = RTCPeerConnection.prototype.removeStream;
RTCPeerConnection.prototype.addStream = function(stream) {
var pc = this;
pc._senders = pc._senders || [];
origAddStream.apply(pc, [stream]);
stream.getTracks().forEach(function(track) {
pc._senders.push({
track: track,
get dtmf() {
if (this._dtmf === undefined) {
if (track.kind === 'audio') {
this._dtmf = pc.createDTMFSender(track);
} else {
this._dtmf = null;
}
}
return this._dtmf;
}
});
});
};
RTCPeerConnection.prototype.removeStream = function(stream) {
var pc = this;
pc._senders = pc._senders || [];
origRemoveStream.apply(pc, [stream]);
stream.getTracks().forEach(function(track) {
var sender = pc._senders.find(function(s) {
return s.track === track;
});
if (sender) {
pc._senders.splice(pc._senders.indexOf(sender), 1); // remove sender
}
});
};
}
},
shimSourceObject: function() {
if (typeof window === 'object') {
if (window.HTMLMediaElement &&
!('srcObject' in window.HTMLMediaElement.prototype)) {
// Shim the srcObject property, once, when HTMLMediaElement is found.
Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
get: function() {
return this._srcObject;
},
set: function(stream) {
var self = this;
// Use _srcObject as a private property for this shim
this._srcObject = stream;
if (this.src) {
URL.revokeObjectURL(this.src);
}
if (!stream) {
this.src = '';
return undefined;
}
this.src = URL.createObjectURL(stream);
// We need to recreate the blob url when a track is added or
// removed. Doing it manually since we want to avoid a recursion.
stream.addEventListener('addtrack', function() {
if (self.src) {
URL.revokeObjectURL(self.src);
}
self.src = URL.createObjectURL(stream);
});
stream.addEventListener('removetrack', function() {
if (self.src) {
URL.revokeObjectURL(self.src);
}
self.src = URL.createObjectURL(stream);
});
}
});
}
}
},
shimPeerConnection: function() {
// The RTCPeerConnection object.
if (!window.RTCPeerConnection) {
window.RTCPeerConnection = function(pcConfig, pcConstraints) {
// Translate iceTransportPolicy to iceTransports,
// see https://code.google.com/p/webrtc/issues/detail?id=4869
// this was fixed in M56 along with unprefixing RTCPeerConnection.
logging('PeerConnection');
if (pcConfig && pcConfig.iceTransportPolicy) {
pcConfig.iceTransports = pcConfig.iceTransportPolicy;
}
return new webkitRTCPeerConnection(pcConfig, pcConstraints);
};
window.RTCPeerConnection.prototype = webkitRTCPeerConnection.prototype;
// wrap static methods. Currently just generateCertificate.
if (webkitRTCPeerConnection.generateCertificate) {
Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
get: function() {
return webkitRTCPeerConnection.generateCertificate;
}
});
}
} else {
// migrate from non-spec RTCIceServer.url to RTCIceServer.urls
var OrigPeerConnection = RTCPeerConnection;
window.RTCPeerConnection = function(pcConfig, pcConstraints) {
if (pcConfig && pcConfig.iceServers) {
var newIceServers = [];
for (var i = 0; i < pcConfig.iceServers.length; i++) {
var server = pcConfig.iceServers[i];
if (!server.hasOwnProperty('urls') &&
server.hasOwnProperty('url')) {
console.warn('RTCIceServer.url is deprecated! Use urls instead.');
server = JSON.parse(JSON.stringify(server));
server.urls = server.url;
newIceServers.push(server);
} else {
newIceServers.push(pcConfig.iceServers[i]);
}
}
pcConfig.iceServers = newIceServers;
}
return new OrigPeerConnection(pcConfig, pcConstraints);
};
window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
// wrap static methods. Currently just generateCertificate.
Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
get: function() {
return OrigPeerConnection.generateCertificate;
}
});
}
var origGetStats = RTCPeerConnection.prototype.getStats;
RTCPeerConnection.prototype.getStats = function(selector,
successCallback, errorCallback) {
var self = this;
var args = arguments;
// If selector is a function then we are in the old style stats so just
// pass back the original getStats format to avoid breaking old users.
if (arguments.length > 0 && typeof selector === 'function') {
return origGetStats.apply(this, arguments);
}
// When spec-style getStats is supported, return those when called with
// either no arguments or the selector argument is null.
if (origGetStats.length === 0 && (arguments.length === 0 ||
typeof arguments[0] !== 'function')) {
return origGetStats.apply(this, []);
}
var fixChromeStats_ = function(response) {
var standardReport = {};
var reports = response.result();
reports.forEach(function(report) {
var standardStats = {
id: report.id,
timestamp: report.timestamp,
type: {
localcandidate: 'local-candidate',
remotecandidate: 'remote-candidate'
}[report.type] || report.type
};
report.names().forEach(function(name) {
standardStats[name] = report.stat(name);
});
standardReport[standardStats.id] = standardStats;
});
return standardReport;
};
// shim getStats with maplike support
var makeMapStats = function(stats) {
return new Map(Object.keys(stats).map(function(key) {
return[key, stats[key]];
}));
};
if (arguments.length >= 2) {
var successCallbackWrapper_ = function(response) {
args[1](makeMapStats(fixChromeStats_(response)));
};
return origGetStats.apply(this, [successCallbackWrapper_,
arguments[0]]);
}
// promise-support
return new Promise(function(resolve, reject) {
origGetStats.apply(self, [
function(response) {
resolve(makeMapStats(fixChromeStats_(response)));
}, reject]);
}).then(successCallback, errorCallback);
};
// add promise support -- natively available in Chrome 51
if (browserDetails.version < 51) {
['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
.forEach(function(method) {
var nativeMethod = RTCPeerConnection.prototype[method];
RTCPeerConnection.prototype[method] = function() {
var args = arguments;
var self = this;
var promise = new Promise(function(resolve, reject) {
nativeMethod.apply(self, [args[0], resolve, reject]);
});
if (args.length < 2) {
return promise;
}
return promise.then(function() {
args[1].apply(null, []);
},
function(err) {
if (args.length >= 3) {
args[2].apply(null, [err]);
}
});
};
});
}
// promise support for createOffer and createAnswer. Available (without
// bugs) since M52: crbug/619289
if (browserDetails.version < 52) {
['createOffer', 'createAnswer'].forEach(function(method) {
var nativeMethod = RTCPeerConnection.prototype[method];
RTCPeerConnection.prototype[method] = function() {
var self = this;
if (arguments.length < 1 || (arguments.length === 1 &&
typeof arguments[0] === 'object')) {
var opts = arguments.length === 1 ? arguments[0] : undefined;
return new Promise(function(resolve, reject) {
nativeMethod.apply(self, [resolve, reject, opts]);
});
}
return nativeMethod.apply(this, arguments);
};
});
}
// shim implicit creation of RTCSessionDescription/RTCIceCandidate
['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
.forEach(function(method) {
var nativeMethod = RTCPeerConnection.prototype[method];
RTCPeerConnection.prototype[method] = function() {
arguments[0] = new ((method === 'addIceCandidate') ?
RTCIceCandidate : RTCSessionDescription)(arguments[0]);
return nativeMethod.apply(this, arguments);
};
});
// support for addIceCandidate(null or undefined)
var nativeAddIceCandidate =
RTCPeerConnection.prototype.addIceCandidate;
RTCPeerConnection.prototype.addIceCandidate = function() {
if (!arguments[0]) {
if (arguments[1]) {
arguments[1].apply(null);
}
return Promise.resolve();
}
return nativeAddIceCandidate.apply(this, arguments);
};
}
};
// Expose public methods.
module.exports = {
shimMediaStream: chromeShim.shimMediaStream,
shimOnTrack: chromeShim.shimOnTrack,
shimGetSendersWithDtmf: chromeShim.shimGetSendersWithDtmf,
shimSourceObject: chromeShim.shimSourceObject,
shimPeerConnection: chromeShim.shimPeerConnection,
shimGetUserMedia: require('./getusermedia')
};
},{"../utils.js":8,"./getusermedia":4}],4:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var logging = require('../utils.js').log;
var browserDetails = require('../utils.js').browserDetails;
// Expose public methods.
module.exports = function() {
var constraintsToChrome_ = function(c) {
if (typeof c !== 'object' || c.mandatory || c.optional) {
return c;
}
var cc = {};
Object.keys(c).forEach(function(key) {
if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
return;
}
var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};
if (r.exact !== undefined && typeof r.exact === 'number') {
r.min = r.max = r.exact;
}
var oldname_ = function(prefix, name) {
if (prefix) {
return prefix + name.charAt(0).toUpperCase() + name.slice(1);
}
return (name === 'deviceId') ? 'sourceId' : name;
};
if (r.ideal !== undefined) {
cc.optional = cc.optional || [];
var oc = {};
if (typeof r.ideal === 'number') {
oc[oldname_('min', key)] = r.ideal;
cc.optional.push(oc);
oc = {};
oc[oldname_('max', key)] = r.ideal;
cc.optional.push(oc);
} else {
oc[oldname_('', key)] = r.ideal;
cc.optional.push(oc);
}
}
if (r.exact !== undefined && typeof r.exact !== 'number') {
cc.mandatory = cc.mandatory || {};
cc.mandatory[oldname_('', key)] = r.exact;
} else {
['min', 'max'].forEach(function(mix) {
if (r[mix] !== undefined) {
cc.mandatory = cc.mandatory || {};
cc.mandatory[oldname_(mix, key)] = r[mix];
}
});
}
});
if (c.advanced) {
cc.optional = (cc.optional || []).concat(c.advanced);
}
return cc;
};
var shimConstraints_ = function(constraints, func) {
constraints = JSON.parse(JSON.stringify(constraints));
if (constraints && constraints.audio) {
constraints.audio = constraintsToChrome_(constraints.audio);
}
if (constraints && typeof constraints.video === 'object') {
// Shim facingMode for mobile & surface pro.
var face = constraints.video.facingMode;
face = face && ((typeof face === 'object') ? face : {ideal: face});
var getSupportedFacingModeLies = browserDetails.version < 61;
if ((face && (face.exact === 'user' || face.exact === 'environment' ||
face.ideal === 'user' || face.ideal === 'environment')) &&
!(navigator.mediaDevices.getSupportedConstraints &&
navigator.mediaDevices.getSupportedConstraints().facingMode &&
!getSupportedFacingModeLies)) {
delete constraints.video.facingMode;
var match;
if (face.exact === 'environment' || face.ideal === 'environment') {
match = 'back';
} else if (face.exact === 'user' || face.ideal === 'user') {
match = 'front';
}
if (match) {
// Look for match in label.
return navigator.mediaDevices.enumerateDevices()
.then(function(devices) {
devices = devices.filter(function(d) {
return d.kind === 'videoinput';
});
var dev = devices.find(function(d) {
return d.label.toLowerCase().indexOf(match) !== -1;
});
if (dev) {
constraints.video.deviceId = face.exact ? {exact: dev.deviceId} :
{ideal: dev.deviceId};
}
constraints.video = constraintsToChrome_(constraints.video);
logging('chrome: ' + JSON.stringify(constraints));
return func(constraints);
});
}
}
constraints.video = constraintsToChrome_(constraints.video);
}
logging('chrome: ' + JSON.stringify(constraints));
return func(constraints);
};
var shimError_ = function(e) {
return {
name: {
PermissionDeniedError: 'NotAllowedError',
ConstraintNotSatisfiedError: 'OverconstrainedError'
}[e.name] || e.name,
message: e.message,
constraint: e.constraintName,
toString: function() {
return this.name + (this.message && ': ') + this.message;
}
};
};
var getUserMedia_ = function(constraints, onSuccess, onError) {
shimConstraints_(constraints, function(c) {
navigator.webkitGetUserMedia(c, onSuccess, function(e) {
onError(shimError_(e));
});
});
};
navigator.getUserMedia = getUserMedia_;
// Returns the result of getUserMedia as a Promise.
var getUserMediaPromise_ = function(constraints) {
return new Promise(function(resolve, reject) {
navigator.getUserMedia(constraints, resolve, reject);
});
};
if (!navigator.mediaDevices) {
navigator.mediaDevices = {
getUserMedia: getUserMediaPromise_,
enumerateDevices: function() {
return new Promise(function(resolve) {
var kinds = {audio: 'audioinput', video: 'videoinput'};
return MediaStreamTrack.getSources(function(devices) {
resolve(devices.map(function(device) {
return {label: device.label,
kind: kinds[device.kind],
deviceId: device.id,
groupId: ''};
}));
});
});
},
getSupportedConstraints: function() {
return {
deviceId: true, echoCancellation: true, facingMode: true,
frameRate: true, height: true, width: true
};
}
};
}
// A shim for getUserMedia method on the mediaDevices object.
// TODO(KaptenJansson) remove once implemented in Chrome stable.
if (!navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia = function(constraints) {
return getUserMediaPromise_(constraints);
};
} else {
// Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
// function which returns a Promise, it does not accept spec-style
// constraints.
var origGetUserMedia = navigator.mediaDevices.getUserMedia.
bind(navigator.mediaDevices);
navigator.mediaDevices.getUserMedia = function(cs) {
return shimConstraints_(cs, function(c) {
return origGetUserMedia(c).then(function(stream) {
if (c.audio && !stream.getAudioTracks().length ||
c.video && !stream.getVideoTracks().length) {
stream.getTracks().forEach(function(track) {
track.stop();
});
throw new DOMException('', 'NotFoundError');
}
return stream;
}, function(e) {
return Promise.reject(shimError_(e));
});
});
};
}
// Dummy devicechange event methods.
// TODO(KaptenJansson) remove once implemented in Chrome stable.
if (typeof navigator.mediaDevices.addEventListener === 'undefined') {
navigator.mediaDevices.addEventListener = function() {
logging('Dummy mediaDevices.addEventListener called.');
};
}
if (typeof navigator.mediaDevices.removeEventListener === 'undefined') {
navigator.mediaDevices.removeEventListener = function() {
logging('Dummy mediaDevices.removeEventListener called.');
};
}
};
},{"../utils.js":8}],5:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var browserDetails = require('../utils').browserDetails;
var firefoxShim = {
shimOnTrack: function() {
if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
window.RTCPeerConnection.prototype)) {
Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
get: function() {
return this._ontrack;
},
set: function(f) {
if (this._ontrack) {
this.removeEventListener('track', this._ontrack);
this.removeEventListener('addstream', this._ontrackpoly);
}
this.addEventListener('track', this._ontrack = f);
this.addEventListener('addstream', this._ontrackpoly = function(e) {
e.stream.getTracks().forEach(function(track) {
var event = new Event('track');
event.track = track;
event.receiver = {track: track};
event.streams = [e.stream];
this.dispatchEvent(event);
}.bind(this));
}.bind(this));
}
});
}
},
shimSourceObject: function() {
// Firefox has supported mozSrcObject since FF22, unprefixed in 42.
if (typeof window === 'object') {
if (window.HTMLMediaElement &&
!('srcObject' in window.HTMLMediaElement.prototype)) {
// Shim the srcObject property, once, when HTMLMediaElement is found.
Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
get: function() {
return this.mozSrcObject;
},
set: function(stream) {
this.mozSrcObject = stream;
}
});
}
}
},
shimPeerConnection: function() {
if (typeof window !== 'object' || !(window.RTCPeerConnection ||
window.mozRTCPeerConnection)) {
return; // probably media.peerconnection.enabled=false in about:config
}
// The RTCPeerConnection object.
if (!window.RTCPeerConnection) {
window.RTCPeerConnection = function(pcConfig, pcConstraints) {
if (browserDetails.version < 38) {
// .urls is not supported in FF < 38.
// create RTCIceServers with a single url.
if (pcConfig && pcConfig.iceServers) {
var newIceServers = [];
for (var i = 0; i < pcConfig.iceServers.length; i++) {
var server = pcConfig.iceServers[i];
if (server.hasOwnProperty('urls')) {
for (var j = 0; j < server.urls.length; j++) {
var newServer = {
url: server.urls[j]
};
if (server.urls[j].indexOf('turn') === 0) {
newServer.username = server.username;
newServer.credential = server.credential;
}
newIceServers.push(newServer);
}
} else {
newIceServers.push(pcConfig.iceServers[i]);
}
}
pcConfig.iceServers = newIceServers;
}
}
return new mozRTCPeerConnection(pcConfig, pcConstraints);
};
window.RTCPeerConnection.prototype = mozRTCPeerConnection.prototype;
// wrap static methods. Currently just generateCertificate.
if (mozRTCPeerConnection.generateCertificate) {
Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
get: function() {
return mozRTCPeerConnection.generateCertificate;
}
});
}
window.RTCSessionDescription = mozRTCSessionDescription;
window.RTCIceCandidate = mozRTCIceCandidate;
}
// shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
.forEach(function(method) {
var nativeMethod = RTCPeerConnection.prototype[method];
RTCPeerConnection.prototype[method] = function() {
arguments[0] = new ((method === 'addIceCandidate') ?
RTCIceCandidate : RTCSessionDescription)(arguments[0]);
return nativeMethod.apply(this, arguments);
};
});
// support for addIceCandidate(null or undefined)
var nativeAddIceCandidate =
RTCPeerConnection.prototype.addIceCandidate;
RTCPeerConnection.prototype.addIceCandidate = function() {
if (!arguments[0]) {
if (arguments[1]) {
arguments[1].apply(null);
}
return Promise.resolve();
}
return nativeAddIceCandidate.apply(this, arguments);
};
// shim getStats with maplike support
var makeMapStats = function(stats) {
var map = new Map();
Object.keys(stats).forEach(function(key) {
map.set(key, stats[key]);
map[key] = stats[key];
});
return map;
};
var modernStatsTypes = {
inboundrtp: 'inbound-rtp',
outboundrtp: 'outbound-rtp',
candidatepair: 'candidate-pair',
localcandidate: 'local-candidate',
remotecandidate: 'remote-candidate'
};
var nativeGetStats = RTCPeerConnection.prototype.getStats;
RTCPeerConnection.prototype.getStats = function(selector, onSucc, onErr) {
return nativeGetStats.apply(this, [selector || null])
.then(function(stats) {
if (browserDetails.version < 48) {
stats = makeMapStats(stats);
}
if (browserDetails.version < 53 && !onSucc) {
// Shim only promise getStats with spec-hyphens in type names
// Leave callback version alone; misc old uses of forEach before Map
try {
stats.forEach(function(stat) {
stat.type = modernStatsTypes[stat.type] || stat.type;
});
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
// Avoid TypeError: "type" is read-only, in old versions. 34-43ish
stats.forEach(function(stat, i) {
stats.set(i, Object.assign({}, stat, {
type: modernStatsTypes[stat.type] || stat.type
}));
});
}
}
return stats;
})
.then(onSucc, onErr);
};
}
};
// Expose public methods.
module.exports = {
shimOnTrack: firefoxShim.shimOnTrack,
shimSourceObject: firefoxShim.shimSourceObject,
shimPeerConnection: firefoxShim.shimPeerConnection,
shimGetUserMedia: require('./getusermedia')
};
},{"../utils":8,"./getusermedia":6}],6:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var logging = require('../utils').log;
var browserDetails = require('../utils').browserDetails;
// Expose public methods.
module.exports = function() {
var shimError_ = function(e) {
return {
name: {
NotSupportedError: 'TypeError',
SecurityError: 'NotAllowedError',
PermissionDeniedError: 'NotAllowedError'
}[e.name] || e.name,
message: {
'The operation is insecure.': 'The request is not allowed by the ' +
'user agent or the platform in the current context.'
}[e.message] || e.message,
constraint: e.constraint,
toString: function() {
return this.name + (this.message && ': ') + this.message;
}
};
};
// getUserMedia constraints shim.
var getUserMedia_ = function(constraints, onSuccess, onError) {
var constraintsToFF37_ = function(c) {
if (typeof c !== 'object' || c.require) {
return c;
}
var require = [];
Object.keys(c).forEach(function(key) {
if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
return;
}
var r = c[key] = (typeof c[key] === 'object') ?
c[key] : {ideal: c[key]};
if (r.min !== undefined ||
r.max !== undefined || r.exact !== undefined) {
require.push(key);
}
if (r.exact !== undefined) {
if (typeof r.exact === 'number') {
r. min = r.max = r.exact;
} else {
c[key] = r.exact;
}
delete r.exact;
}
if (r.ideal !== undefined) {
c.advanced = c.advanced || [];
var oc = {};
if (typeof r.ideal === 'number') {
oc[key] = {min: r.ideal, max: r.ideal};
} else {
oc[key] = r.ideal;
}
c.advanced.push(oc);
delete r.ideal;
if (!Object.keys(r).length) {
delete c[key];
}
}
});
if (require.length) {
c.require = require;
}
return c;
};
constraints = JSON.parse(JSON.stringify(constraints));
if (browserDetails.version < 38) {
logging('spec: ' + JSON.stringify(constraints));
if (constraints.audio) {
constraints.audio = constraintsToFF37_(constraints.audio);
}
if (constraints.video) {
constraints.video = constraintsToFF37_(constraints.video);
}
logging('ff37: ' + JSON.stringify(constraints));
}
return navigator.mozGetUserMedia(constraints, onSuccess, function(e) {
onError(shimError_(e));
});
};
// Returns the result of getUserMedia as a Promise.
var getUserMediaPromise_ = function(constraints) {
return new Promise(function(resolve, reject) {
getUserMedia_(constraints, resolve, reject);
});
};
// Shim for mediaDevices on older versions.
if (!navigator.mediaDevices) {
navigator.mediaDevices = {getUserMedia: getUserMediaPromise_,
addEventListener: function() { },
removeEventListener: function() { }
};
}
navigator.mediaDevices.enumerateDevices =
navigator.mediaDevices.enumerateDevices || function() {
return new Promise(function(resolve) {
var infos = [
{kind: 'audioinput', deviceId: 'default', label: '', groupId: ''},
{kind: 'videoinput', deviceId: 'default', label: '', groupId: ''}
];
resolve(infos);
});
};
if (browserDetails.version < 41) {
// Work around http://bugzil.la/1169665
var orgEnumerateDevices =
navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
navigator.mediaDevices.enumerateDevices = function() {
return orgEnumerateDevices().then(undefined, function(e) {
if (e.name === 'NotFoundError') {
return [];
}
throw e;
});
};
}
if (browserDetails.version < 49) {
var origGetUserMedia = navigator.mediaDevices.getUserMedia.
bind(navigator.mediaDevices);
navigator.mediaDevices.getUserMedia = function(c) {
return origGetUserMedia(c).then(function(stream) {
// Work around https://bugzil.la/802326
if (c.audio && !stream.getAudioTracks().length ||
c.video && !stream.getVideoTracks().length) {
stream.getTracks().forEach(function(track) {
track.stop();
});
throw new DOMException('The object can not be found here.',
'NotFoundError');
}
return stream;
}, function(e) {
return Promise.reject(shimError_(e));
});
};
}
navigator.getUserMedia = function(constraints, onSuccess, onError) {
if (browserDetails.version < 44) {
return getUserMedia_(constraints, onSuccess, onError);
}
// Replace Firefox 44+'s deprecation warning with unprefixed version.
console.warn('navigator.getUserMedia has been replaced by ' +
'navigator.mediaDevices.getUserMedia');
navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
};
};
},{"../utils":8}],7:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
'use strict';
var safariShim = {
// TODO: DrAlex, should be here, double check against LayoutTests
// TODO: once the back-end for the mac port is done, add.
// TODO: check for webkitGTK+
// shimPeerConnection: function() { },
shimOnAddStream: function() {
if (typeof window === 'object' && window.RTCPeerConnection &&
!('onaddstream' in window.RTCPeerConnection.prototype)) {
Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', {
get: function() {
return this._onaddstream;
},
set: function(f) {
if (this._onaddstream) {
this.removeEventListener('addstream', this._onaddstream);
this.removeEventListener('track', this._onaddstreampoly);
}
this.addEventListener('addstream', this._onaddstream = f);
this.addEventListener('track', this._onaddstreampoly = function(e) {
var stream = e.streams[0];
if (!this._streams) {
this._streams = [];
}
if (this._streams.indexOf(stream) >= 0) {
return;
}
this._streams.push(stream);
var event = new Event('addstream');
event.stream = e.streams[0];
this.dispatchEvent(event);
}.bind(this));
}
});
}
},
shimGetUserMedia: function() {
if (!navigator.getUserMedia) {
if (navigator.webkitGetUserMedia) {
navigator.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
} else if (navigator.mediaDevices &&
navigator.mediaDevices.getUserMedia) {
navigator.getUserMedia = function(constraints, cb, errcb) {
navigator.mediaDevices.getUserMedia(constraints)
.then(cb, errcb);
}.bind(navigator);
}
}
}
};
// Expose public methods.
module.exports = {
shimOnAddStream: safariShim.shimOnAddStream,
shimGetUserMedia: safariShim.shimGetUserMedia
// TODO
// shimPeerConnection: safariShim.shimPeerConnection
};
},{}],8:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var logDisabled_ = true;
// Utility methods.
var utils = {
disableLog: function(bool) {
if (typeof bool !== 'boolean') {
return new Error('Argument type: ' + typeof bool +
'. Please use a boolean.');
}
logDisabled_ = bool;
return (bool) ? 'adapter.js logging disabled' :
'adapter.js logging enabled';
},
log: function() {
if (typeof window === 'object') {
if (logDisabled_) {
return;
}
if (typeof console !== 'undefined' && typeof console.log === 'function') {
console.log.apply(console, arguments);
}
}
},
/**
* Extract browser version out of the provided user agent string.
*
* @param {!string} uastring userAgent string.
* @param {!string} expr Regular expression used as match criteria.
* @param {!number} pos position in the version string to be returned.
* @return {!number} browser version.
*/
extractVersion: function(uastring, expr, pos) {
var match = uastring.match(expr);
return match && match.length >= pos && parseInt(match[pos], 10);
},
/**
* Browser detector.
*
* @return {object} result containing browser and version
* properties.
*/
detectBrowser: function() {
// Returned result object.
var result = {};
result.browser = null;
result.version = null;
// Fail early if it's not a browser
if (typeof window === 'undefined' || !window.navigator) {
result.browser = 'Not a browser.';
return result;
}
// Firefox.
if (navigator.mozGetUserMedia) {
result.browser = 'firefox';
result.version = this.extractVersion(navigator.userAgent,
/Firefox\/(\d+)\./, 1);
} else if (navigator.webkitGetUserMedia) {
// Chrome, Chromium, Webview, Opera, all use the chrome shim for now
if (window.webkitRTCPeerConnection) {
result.browser = 'chrome';
result.version = this.extractVersion(navigator.userAgent,
/Chrom(e|ium)\/(\d+)\./, 2);
} else { // Safari (in an unpublished version) or unknown webkit-based.
if (navigator.userAgent.match(/Version\/(\d+).(\d+)/)) {
result.browser = 'safari';
result.version = this.extractVersion(navigator.userAgent,
/AppleWebKit\/(\d+)\./, 1);
} else { // unknown webkit-based browser.
result.browser = 'Unsupported webkit-based browser ' +
'with GUM support but no WebRTC support.';
return result;
}
}
} else if (navigator.mediaDevices &&
navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) { // Edge.
result.browser = 'edge';
result.version = this.extractVersion(navigator.userAgent,
/Edge\/(\d+).(\d+)$/, 2);
} else if (navigator.mediaDevices &&
navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) {
// Safari, with webkitGetUserMedia removed.
result.browser = 'safari';
result.version = this.extractVersion(navigator.userAgent,
/AppleWebKit\/(\d+)\./, 1);
} else { // Default fallthrough: not supported.
result.browser = 'Not a supported browser.';
return result;
}
return result;
},
// shimCreateObjectURL must be called before shimSourceObject to avoid loop.
shimCreateObjectURL: function() {
if (!(typeof window === 'object' && window.HTMLMediaElement &&
'srcObject' in window.HTMLMediaElement.prototype)) {
// Only shim CreateObjectURL using srcObject if srcObject exists.
return undefined;
}
var nativeCreateObjectURL = URL.createObjectURL.bind(URL);
var nativeRevokeObjectURL = URL.revokeObjectURL.bind(URL);
var streams = new Map(), newId = 0;
URL.createObjectURL = function(stream) {
if ('getTracks' in stream) {
var url = 'polyblob:' + (++newId);
streams.set(url, stream);
console.log('URL.createObjectURL(stream) is deprecated! ' +
'Use elem.srcObject = stream instead!');
return url;
}
return nativeCreateObjectURL(stream);
};
URL.revokeObjectURL = function(url) {
nativeRevokeObjectURL(url);
streams.delete(url);
};
var dsc = Object.getOwnPropertyDescriptor(window.HTMLMediaElement.prototype,
'src');
Object.defineProperty(window.HTMLMediaElement.prototype, 'src', {
get: function() {
return dsc.get.apply(this);
},
set: function(url) {
this.srcObject = streams.get(url) || null;
return dsc.set.apply(this, [url]);
}
});
var nativeSetAttribute = HTMLMediaElement.prototype.setAttribute;
HTMLMediaElement.prototype.setAttribute = function() {
if (arguments.length === 2 &&
('' + arguments[0]).toLowerCase() === 'src') {
this.srcObject = streams.get(arguments[1]) || null;
}
return nativeSetAttribute.apply(this, arguments);
};
}
};
// Export.
module.exports = {
log: utils.log,
disableLog: utils.disableLog,
browserDetails: utils.detectBrowser(),
extractVersion: utils.extractVersion,
shimCreateObjectURL: utils.shimCreateObjectURL,
detectBrowser: utils.detectBrowser.bind(utils)
};
},{}]},{},[2]);
|
// http://dev.w3.org/csswg/css-color/
function Color(value) {
this.r = 0;
this.g = 0;
this.b = 0;
this.a = null;
var result = this.fromArray(value) ||
this.namedColor(value) ||
this.rgb(value) ||
this.rgba(value) ||
this.hex6(value) ||
this.hex3(value);
}
Color.prototype.darken = function(amount) {
var a = 1 - amount;
return new Color([
Math.round(this.r * a),
Math.round(this.g * a),
Math.round(this.b * a),
this.a
]);
};
Color.prototype.isTransparent = function() {
return this.a === 0;
};
Color.prototype.isBlack = function() {
return this.r === 0 && this.g === 0 && this.b === 0;
};
Color.prototype.fromArray = function(array) {
if (Array.isArray(array)) {
this.r = Math.min(array[0], 255);
this.g = Math.min(array[1], 255);
this.b = Math.min(array[2], 255);
if (array.length > 3) {
this.a = array[3];
}
}
return (Array.isArray(array));
};
var _hex3 = /^#([a-f0-9]{3})$/i;
Color.prototype.hex3 = function(value) {
var match = null;
if ((match = value.match(_hex3)) !== null) {
this.r = parseInt(match[1][0] + match[1][0], 16);
this.g = parseInt(match[1][1] + match[1][1], 16);
this.b = parseInt(match[1][2] + match[1][2], 16);
}
return match !== null;
};
var _hex6 = /^#([a-f0-9]{6})$/i;
Color.prototype.hex6 = function(value) {
var match = null;
if ((match = value.match(_hex6)) !== null) {
this.r = parseInt(match[1].substring(0, 2), 16);
this.g = parseInt(match[1].substring(2, 4), 16);
this.b = parseInt(match[1].substring(4, 6), 16);
}
return match !== null;
};
var _rgb = /^rgb\((\d{1,3}) *, *(\d{1,3}) *, *(\d{1,3})\)$/;
Color.prototype.rgb = function(value) {
var match = null;
if ((match = value.match(_rgb)) !== null) {
this.r = Number(match[1]);
this.g = Number(match[2]);
this.b = Number(match[3]);
}
return match !== null;
};
var _rgba = /^rgba\((\d{1,3}) *, *(\d{1,3}) *, *(\d{1,3}) *, *(\d+\.?\d*)\)$/;
Color.prototype.rgba = function(value) {
var match = null;
if ((match = value.match(_rgba)) !== null) {
this.r = Number(match[1]);
this.g = Number(match[2]);
this.b = Number(match[3]);
this.a = Number(match[4]);
}
return match !== null;
};
Color.prototype.toString = function() {
return this.a !== null && this.a !== 1 ?
"rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" :
"rgb(" + [this.r, this.g, this.b].join(",") + ")";
};
Color.prototype.namedColor = function(value) {
var color = colors[value.toLowerCase()];
if (color) {
this.r = color[0];
this.g = color[1];
this.b = color[2];
} else if (value.toLowerCase() === "transparent") {
this.r = this.g = this.b = this.a = 0;
return true;
}
return !!color;
};
Color.prototype.isColor = true;
// JSON.stringify([].slice.call($$('.named-color-table tr'), 1).map(function(row) { return [row.childNodes[3].textContent, row.childNodes[5].textContent.trim().split(",").map(Number)] }).reduce(function(data, row) {data[row[0]] = row[1]; return data}, {}))
var colors = {
"aliceblue": [240, 248, 255],
"antiquewhite": [250, 235, 215],
"aqua": [0, 255, 255],
"aquamarine": [127, 255, 212],
"azure": [240, 255, 255],
"beige": [245, 245, 220],
"bisque": [255, 228, 196],
"black": [0, 0, 0],
"blanchedalmond": [255, 235, 205],
"blue": [0, 0, 255],
"blueviolet": [138, 43, 226],
"brown": [165, 42, 42],
"burlywood": [222, 184, 135],
"cadetblue": [95, 158, 160],
"chartreuse": [127, 255, 0],
"chocolate": [210, 105, 30],
"coral": [255, 127, 80],
"cornflowerblue": [100, 149, 237],
"cornsilk": [255, 248, 220],
"crimson": [220, 20, 60],
"cyan": [0, 255, 255],
"darkblue": [0, 0, 139],
"darkcyan": [0, 139, 139],
"darkgoldenrod": [184, 134, 11],
"darkgray": [169, 169, 169],
"darkgreen": [0, 100, 0],
"darkgrey": [169, 169, 169],
"darkkhaki": [189, 183, 107],
"darkmagenta": [139, 0, 139],
"darkolivegreen": [85, 107, 47],
"darkorange": [255, 140, 0],
"darkorchid": [153, 50, 204],
"darkred": [139, 0, 0],
"darksalmon": [233, 150, 122],
"darkseagreen": [143, 188, 143],
"darkslateblue": [72, 61, 139],
"darkslategray": [47, 79, 79],
"darkslategrey": [47, 79, 79],
"darkturquoise": [0, 206, 209],
"darkviolet": [148, 0, 211],
"deeppink": [255, 20, 147],
"deepskyblue": [0, 191, 255],
"dimgray": [105, 105, 105],
"dimgrey": [105, 105, 105],
"dodgerblue": [30, 144, 255],
"firebrick": [178, 34, 34],
"floralwhite": [255, 250, 240],
"forestgreen": [34, 139, 34],
"fuchsia": [255, 0, 255],
"gainsboro": [220, 220, 220],
"ghostwhite": [248, 248, 255],
"gold": [255, 215, 0],
"goldenrod": [218, 165, 32],
"gray": [128, 128, 128],
"green": [0, 128, 0],
"greenyellow": [173, 255, 47],
"grey": [128, 128, 128],
"honeydew": [240, 255, 240],
"hotpink": [255, 105, 180],
"indianred": [205, 92, 92],
"indigo": [75, 0, 130],
"ivory": [255, 255, 240],
"khaki": [240, 230, 140],
"lavender": [230, 230, 250],
"lavenderblush": [255, 240, 245],
"lawngreen": [124, 252, 0],
"lemonchiffon": [255, 250, 205],
"lightblue": [173, 216, 230],
"lightcoral": [240, 128, 128],
"lightcyan": [224, 255, 255],
"lightgoldenrodyellow": [250, 250, 210],
"lightgray": [211, 211, 211],
"lightgreen": [144, 238, 144],
"lightgrey": [211, 211, 211],
"lightpink": [255, 182, 193],
"lightsalmon": [255, 160, 122],
"lightseagreen": [32, 178, 170],
"lightskyblue": [135, 206, 250],
"lightslategray": [119, 136, 153],
"lightslategrey": [119, 136, 153],
"lightsteelblue": [176, 196, 222],
"lightyellow": [255, 255, 224],
"lime": [0, 255, 0],
"limegreen": [50, 205, 50],
"linen": [250, 240, 230],
"magenta": [255, 0, 255],
"maroon": [128, 0, 0],
"mediumaquamarine": [102, 205, 170],
"mediumblue": [0, 0, 205],
"mediumorchid": [186, 85, 211],
"mediumpurple": [147, 112, 219],
"mediumseagreen": [60, 179, 113],
"mediumslateblue": [123, 104, 238],
"mediumspringgreen": [0, 250, 154],
"mediumturquoise": [72, 209, 204],
"mediumvioletred": [199, 21, 133],
"midnightblue": [25, 25, 112],
"mintcream": [245, 255, 250],
"mistyrose": [255, 228, 225],
"moccasin": [255, 228, 181],
"navajowhite": [255, 222, 173],
"navy": [0, 0, 128],
"oldlace": [253, 245, 230],
"olive": [128, 128, 0],
"olivedrab": [107, 142, 35],
"orange": [255, 165, 0],
"orangered": [255, 69, 0],
"orchid": [218, 112, 214],
"palegoldenrod": [238, 232, 170],
"palegreen": [152, 251, 152],
"paleturquoise": [175, 238, 238],
"palevioletred": [219, 112, 147],
"papayawhip": [255, 239, 213],
"peachpuff": [255, 218, 185],
"peru": [205, 133, 63],
"pink": [255, 192, 203],
"plum": [221, 160, 221],
"powderblue": [176, 224, 230],
"purple": [128, 0, 128],
"rebeccapurple": [102, 51, 153],
"red": [255, 0, 0],
"rosybrown": [188, 143, 143],
"royalblue": [65, 105, 225],
"saddlebrown": [139, 69, 19],
"salmon": [250, 128, 114],
"sandybrown": [244, 164, 96],
"seagreen": [46, 139, 87],
"seashell": [255, 245, 238],
"sienna": [160, 82, 45],
"silver": [192, 192, 192],
"skyblue": [135, 206, 235],
"slateblue": [106, 90, 205],
"slategray": [112, 128, 144],
"slategrey": [112, 128, 144],
"snow": [255, 250, 250],
"springgreen": [0, 255, 127],
"steelblue": [70, 130, 180],
"tan": [210, 180, 140],
"teal": [0, 128, 128],
"thistle": [216, 191, 216],
"tomato": [255, 99, 71],
"turquoise": [64, 224, 208],
"violet": [238, 130, 238],
"wheat": [245, 222, 179],
"white": [255, 255, 255],
"whitesmoke": [245, 245, 245],
"yellow": [255, 255, 0],
"yellowgreen": [154, 205, 50]
};
module.exports = Color;
|
/**
* Klass.js - copyright @ded & @fat
* https://github.com/polvero/klass
* Follow our software http://twitter.com/dedfat
* MIT License
*/
!function(a){function g(a){var f=this,g,h=e(a)?(g={},a):(g=a,this),i=function i(){f.apply(this,arguments),h.apply(this,arguments)},j=new c;i.methods=function(a){for(var c in a)j[c]=e(a[c])&&e(f[d][c])&&b.test(a[c])?function(a,b){return function(){this.supr=f[d][a];return b.apply(this,arguments)}}(c,a[c]):a[c];i[d]=j;return this},i.methods.call(i,g).constructor=this,i.extend=arguments.callee,i[d].implement=i.statics=function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);return this};return i}function f(a){var b,d=e(a)?(b={},a):(b=a,c);return g.call(d,a)}var b=/xyz/.test(function(){xyz})?/\bsupr\b/:/.*/,c=function(){},d="prototype",e=function(a){return typeof a=="function"};typeof module!="undefined"&&module.exports?module.exports=f:a.klass=f}(this) |
/*!
* angular-translate - v2.5.1 - 2014-12-10
* http://github.com/angular-translate/angular-translate
* Copyright (c) 2014 ; Licensed MIT
*/
angular.module('pascalprecht.translate')
/**
* @ngdoc object
* @name pascalprecht.translate.$translatePartialLoaderProvider
*
* @description
* By using a $translatePartialLoaderProvider you can configure a list of a needed
* translation parts directly during the configuration phase of your application's
* lifetime. All parts you add by using this provider would be loaded by
* angular-translate at the startup as soon as possible.
*/
.provider('$translatePartialLoader', function() {
/**
* @constructor
* @name Part
*
* @description
* Represents Part object to add and set parts at runtime.
*/
function Part(name) {
this.name = name;
this.isActive = true;
this.tables = {};
}
/**
* @name parseUrl
* @method
*
* @description
* Returns a parsed url template string and replaces given target lang
* and part name it.
*
* @param {string} urlTemplate Url pattern to use.
* @param {string} targetLang Language key for language to be used.
* @return {string} Parsed url template string
*/
Part.prototype.parseUrl = function(urlTemplate, targetLang) {
return urlTemplate.replace(/\{part\}/g, this.name).replace(/\{lang\}/g, targetLang);
};
Part.prototype.getTable = function(lang, $q, $http, $httpOptions, urlTemplate, errorHandler) {
var deferred = $q.defer();
if (!this.tables[lang]) {
var self = this;
$http(angular.extend({
method : 'GET',
url: this.parseUrl(urlTemplate, lang)
}, $httpOptions)).success(function(data){
self.tables[lang] = data;
deferred.resolve(data);
}).error(function() {
if (errorHandler) {
errorHandler(self.name, lang).then(function(data) {
self.tables[lang] = data;
deferred.resolve(data);
}, function() {
deferred.reject(self.name);
});
} else {
deferred.reject(self.name);
}
});
} else {
deferred.resolve(this.tables[lang]);
}
return deferred.promise;
};
var parts = {};
function hasPart(name) {
return Object.prototype.hasOwnProperty.call(parts, name);
}
function isStringValid(str) {
return angular.isString(str) && str !== '';
}
function isPartAvailable(name) {
if (!isStringValid(name)) {
throw new TypeError('Invalid type of a first argument, a non-empty string expected.');
}
return (hasPart(name) && parts[name].isActive);
}
function deepExtend(dst, src) {
for (var property in src) {
if (src[property] && src[property].constructor &&
src[property].constructor === Object) {
dst[property] = dst[property] || {};
deepExtend(dst[property], src[property]);
} else {
dst[property] = src[property];
}
}
return dst;
}
/**
* @ngdoc function
* @name pascalprecht.translate.$translatePartialLoaderProvider#addPart
* @methodOf pascalprecht.translate.$translatePartialLoaderProvider
*
* @description
* Registers a new part of the translation table to be loaded once the
* `angular-translate` gets into runtime phase. It does not actually load any
* translation data, but only registers a part to be loaded in the future.
*
* @param {string} name A name of the part to add
* @returns {object} $translatePartialLoaderProvider, so this method is chainable
* @throws {TypeError} The method could throw a **TypeError** if you pass the param
* of the wrong type. Please, note that the `name` param has to be a
* non-empty **string**.
*/
this.addPart = function(name) {
if (!isStringValid(name)) {
throw new TypeError('Couldn\'t add part, part name has to be a string!');
}
if (!hasPart(name)) {
parts[name] = new Part(name);
}
parts[name].isActive = true;
return this;
};
/**
* @ngdocs function
* @name pascalprecht.translate.$translatePartialLoaderProvider#setPart
* @methodOf pascalprecht.translate.$translatePartialLoaderProvider
*
* @description
* Sets a translation table to the specified part. This method does not make the
* specified part available, but only avoids loading this part from the server.
*
* @param {string} lang A language of the given translation table
* @param {string} part A name of the target part
* @param {object} table A translation table to set to the specified part
*
* @return {object} $translatePartialLoaderProvider, so this method is chainable
* @throws {TypeError} The method could throw a **TypeError** if you pass params
* of the wrong type. Please, note that the `lang` and `part` params have to be a
* non-empty **string**s and the `table` param has to be an object.
*/
this.setPart = function(lang, part, table) {
if (!isStringValid(lang)) {
throw new TypeError('Couldn\'t set part.`lang` parameter has to be a string!');
}
if (!isStringValid(part)) {
throw new TypeError('Couldn\'t set part.`part` parameter has to be a string!');
}
if (typeof table !== 'object' || table === null) {
throw new TypeError('Couldn\'t set part. `table` parameter has to be an object!');
}
if (!hasPart(part)) {
parts[part] = new Part(part);
parts[part].isActive = false;
}
parts[part].tables[lang] = table;
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translatePartialLoaderProvider#deletePart
* @methodOf pascalprecht.translate.$translatePartialLoaderProvider
*
* @description
* Removes the previously added part of the translation data. So, `angular-translate` will not
* load it at the startup.
*
* @param {string} name A name of the part to delete
*
* @returns {object} $translatePartialLoaderProvider, so this method is chainable
*
* @throws {TypeError} The method could throw a **TypeError** if you pass the param of the wrong
* type. Please, note that the `name` param has to be a non-empty **string**.
*/
this.deletePart = function(name) {
if (!isStringValid(name)) {
throw new TypeError('Couldn\'t delete part, first arg has to be string.');
}
if (hasPart(name)) {
parts[name].isActive = false;
}
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translatePartialLoaderProvider#isPartAvailable
* @methodOf pascalprecht.translate.$translatePartialLoaderProvider
*
* @description
* Checks if the specific part is available. A part becomes available after it was added by the
* `addPart` method. Available parts would be loaded from the server once the `angular-translate`
* asks the loader to that.
*
* @param {string} name A name of the part to check
*
* @returns {boolean} Returns **true** if the part is available now and **false** if not.
*
* @throws {TypeError} The method could throw a **TypeError** if you pass the param of the wrong
* type. Please, note that the `name` param has to be a non-empty **string**.
*/
this.isPartAvailable = isPartAvailable;
/**
* @ngdoc object
* @name pascalprecht.translate.$translatePartialLoader
*
* @requires $q
* @requires $http
* @requires $injector
* @requires $rootScope
* @requires $translate
*
* @description
*
* @param {object} options Options object
*
* @throws {TypeError}
*/
this.$get = ['$rootScope', '$injector', '$q', '$http',
function($rootScope, $injector, $q, $http) {
/**
* @ngdoc event
* @name pascalprecht.translate.$translatePartialLoader#$translatePartialLoaderStructureChanged
* @eventOf pascalprecht.translate.$translatePartialLoader
* @eventType broadcast on root scope
*
* @description
* A $translatePartialLoaderStructureChanged event is called when a state of the loader was
* changed somehow. It could mean either some part is added or some part is deleted. Anyway when
* you get this event the translation table is not longer current and has to be updated.
*
* @param {string} name A name of the part which is a reason why the event was fired
*/
var service = function(options) {
if (!isStringValid(options.key)) {
throw new TypeError('Unable to load data, a key is not a non-empty string.');
}
if (!isStringValid(options.urlTemplate)) {
throw new TypeError('Unable to load data, a urlTemplate is not a non-empty string.');
}
var errorHandler = options.loadFailureHandler;
if (errorHandler !== undefined) {
if (!angular.isString(errorHandler)) {
throw new Error('Unable to load data, a loadFailureHandler is not a string.');
} else errorHandler = $injector.get(errorHandler);
}
var loaders = [],
tables = [],
deferred = $q.defer();
function addTablePart(table) {
tables.push(table);
}
for (var part in parts) {
if (hasPart(part) && parts[part].isActive) {
loaders.push(
parts[part]
.getTable(options.key, $q, $http, options.$http, options.urlTemplate, errorHandler)
.then(addTablePart)
);
parts[part].urlTemplate = options.urlTemplate;
}
}
if (loaders.length) {
$q.all(loaders).then(
function() {
var table = {};
for (var i = 0; i < tables.length; i++) {
deepExtend(table, tables[i]);
}
deferred.resolve(table);
},
function() {
deferred.reject(options.key);
}
);
} else {
deferred.resolve({});
}
return deferred.promise;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translatePartialLoader#addPart
* @methodOf pascalprecht.translate.$translatePartialLoader
*
* @description
* Registers a new part of the translation table. This method does actually not perform any xhr
* requests to get a translation data. The new parts would be loaded from the server next time
* `angular-translate` asks to loader to loaded translations.
*
* @param {string} name A name of the part to add
*
* @returns {object} $translatePartialLoader, so this method is chainable
*
* @fires {$translatePartialLoaderStructureChanged} The $translatePartialLoaderStructureChanged
* event would be fired by this method in case the new part affected somehow on the loaders
* state. This way it means that there are a new translation data available to be loaded from
* the server.
*
* @throws {TypeError} The method could throw a **TypeError** if you pass the param of the wrong
* type. Please, note that the `name` param has to be a non-empty **string**.
*/
service.addPart = function(name) {
if (!isStringValid(name)) {
throw new TypeError('Couldn\'t add part, first arg has to be a string');
}
if (!hasPart(name)) {
parts[name] = new Part(name);
$rootScope.$emit('$translatePartialLoaderStructureChanged', name);
} else if (!parts[name].isActive) {
parts[name].isActive = true;
$rootScope.$emit('$translatePartialLoaderStructureChanged', name);
}
return service;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translatePartialLoader#deletePart
* @methodOf pascalprecht.translate.$translatePartialLoader
*
* @description
* Deletes the previously added part of the translation data. The target part could be deleted
* either logically or physically. When the data is deleted logically it is not actually deleted
* from the browser, but the loader marks it as not active and prevents it from affecting on the
* translations. If the deleted in such way part is added again, the loader will use the
* previously loaded data rather than loading it from the server once more time. But if the data
* is deleted physically, the loader will completely remove all information about it. So in case
* of recycling this part will be loaded from the server again.
*
* @param {string} name A name of the part to delete
* @param {boolean=} [removeData=false] An indicator if the loader has to remove a loaded
* translation data physically. If the `removeData` if set to **false** the loaded data will not be
* deleted physically and might be reused in the future to prevent an additional xhr requests.
*
* @returns {object} $translatePartialLoader, so this method is chainable
*
* @fires {$translatePartialLoaderStructureChanged} The $translatePartialLoaderStructureChanged
* event would be fired by this method in case a part deletion process affects somehow on the
* loaders state. This way it means that some part of the translation data is now deprecated and
* the translation table has to be recompiled with the remaining translation parts.
*
* @throws {TypeError} The method could throw a **TypeError** if you pass some param of the
* wrong type. Please, note that the `name` param has to be a non-empty **string** and
* the `removeData` param has to be either **undefined** or **boolean**.
*/
service.deletePart = function(name, removeData) {
if (!isStringValid(name)) {
throw new TypeError('Couldn\'t delete part, first arg has to be string');
}
if (removeData === undefined) {
removeData = false;
} else if (typeof removeData !== 'boolean') {
throw new TypeError('Invalid type of a second argument, a boolean expected.');
}
if (hasPart(name)) {
var wasActive = parts[name].isActive;
if (removeData) {
var $translate = $injector.get('$translate');
var cache = $translate.loaderCache();
if (typeof(cache) === 'string') {
// getting on-demand instance of loader
cache = $injector.get(cache);
}
// Purging items from cache...
if (typeof(cache) === 'object') {
angular.forEach(parts[name].tables, function(value, key) {
cache.remove(parts[name].parseUrl(parts[name].urlTemplate, key));
});
}
delete parts[name];
} else {
parts[name].isActive = false;
}
if (wasActive) {
$rootScope.$emit('$translatePartialLoaderStructureChanged', name);
}
}
return service;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translatePartialLoader#isPartAvailable
* @methodOf pascalprecht.translate.$translatePartialLoader
*
* @description
* Checks if a target translation part is available. The part becomes available just after it was
* added by the `addPart` method. Part's availability does not mean that it was loaded from the
* server, but only that it was added to the loader. The available part might be loaded next
* time the loader is called.
*
* @param {string} name A name of the part to delete
*
* @returns {boolean} Returns **true** if the part is available now and **false** if not.
*
* @throws {TypeError} The method could throw a **TypeError** if you pass the param of the wrong
* type. Please, note that the `name` param has to be a non-empty **string**.
*/
service.isPartAvailable = isPartAvailable;
return service;
}];
});
|
/*!
* jQuery UI Progressbar 1.11.1
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/progressbar/
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([
"jquery",
"./core",
"./widget"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
return $.widget( "ui.progressbar", {
version: "1.11.1",
options: {
max: 100,
value: 0,
change: null,
complete: null
},
min: 0,
_create: function() {
// Constrain initial value
this.oldValue = this.options.value = this._constrainedValue();
this.element
.addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
.attr({
// Only set static values, aria-valuenow and aria-valuemax are
// set inside _refreshValue()
role: "progressbar",
"aria-valuemin": this.min
});
this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" )
.appendTo( this.element );
this._refreshValue();
},
_destroy: function() {
this.element
.removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
.removeAttr( "role" )
.removeAttr( "aria-valuemin" )
.removeAttr( "aria-valuemax" )
.removeAttr( "aria-valuenow" );
this.valueDiv.remove();
},
value: function( newValue ) {
if ( newValue === undefined ) {
return this.options.value;
}
this.options.value = this._constrainedValue( newValue );
this._refreshValue();
},
_constrainedValue: function( newValue ) {
if ( newValue === undefined ) {
newValue = this.options.value;
}
this.indeterminate = newValue === false;
// sanitize value
if ( typeof newValue !== "number" ) {
newValue = 0;
}
return this.indeterminate ? false :
Math.min( this.options.max, Math.max( this.min, newValue ) );
},
_setOptions: function( options ) {
// Ensure "value" option is set after other values (like max)
var value = options.value;
delete options.value;
this._super( options );
this.options.value = this._constrainedValue( value );
this._refreshValue();
},
_setOption: function( key, value ) {
if ( key === "max" ) {
// Don't allow a max less than min
value = Math.max( this.min, value );
}
if ( key === "disabled" ) {
this.element
.toggleClass( "ui-state-disabled", !!value )
.attr( "aria-disabled", value );
}
this._super( key, value );
},
_percentage: function() {
return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min );
},
_refreshValue: function() {
var value = this.options.value,
percentage = this._percentage();
this.valueDiv
.toggle( this.indeterminate || value > this.min )
.toggleClass( "ui-corner-right", value === this.options.max )
.width( percentage.toFixed(0) + "%" );
this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate );
if ( this.indeterminate ) {
this.element.removeAttr( "aria-valuenow" );
if ( !this.overlayDiv ) {
this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv );
}
} else {
this.element.attr({
"aria-valuemax": this.options.max,
"aria-valuenow": value
});
if ( this.overlayDiv ) {
this.overlayDiv.remove();
this.overlayDiv = null;
}
}
if ( this.oldValue !== value ) {
this.oldValue = value;
this._trigger( "change" );
}
if ( value === this.options.max ) {
this._trigger( "complete" );
}
}
});
}));
|
/*
By André Knieriem, www.andreknieriem.de
Available for use under the MIT License
*/
;( function( $, window, document, undefined )
{
'use strict';
$.fn.simpleLightbox = function( options )
{
var options = $.extend({
overlay: true,
spinner: true,
nav: true,
navText: ['←','→'],
captions: true,
close: true,
closeText: 'X',
showCounter: true,
fileExt: 'png|jpg|jpeg|gif',
animationSpeed: 250,
preloading: true,
enableKeyboard: true,
loop: true,
docClose: true,
swipeTolerance: 50,
className: 'simple-lightbox',
widthRatio: 0.8,
heightRatio: 0.9
}, options );
// global variables
var touchDevice = ( 'ontouchstart' in window ),
pointerEnabled = window.navigator.pointerEnabled || window.navigator.msPointerEnabled,
touched = function( event ){
if( touchDevice ) return true;
if( !pointerEnabled || typeof event === 'undefined' || typeof event.pointerType === 'undefined' )
return false;
if( typeof event.MSPOINTER_TYPE_MOUSE !== 'undefined' )
{
if( event.MSPOINTER_TYPE_MOUSE != event.pointerType )
return true;
}
else
if( event.pointerType != 'mouse' )
return true;
return false;
},
swipeDiff = 0,
curImg = $(),
transPrefix = function(){
var s = document.body || document.documentElement, s = s.style;
if( s.WebkitTransition == '' ) return '-webkit-';
if( s.MozTransition == '' ) return '-moz-';
if( s.OTransition == '' ) return '-o-';
if( s.transition == '' ) return '';
return false;
},
opened = false,
selector = this.selector,
transPrefix = transPrefix(),
canTransisions = (transPrefix !== false) ? true : false,
prefix = 'simplelb',
overlay = $('<div>').addClass('sl-overlay'),
closeBtn = $('<button>').addClass('sl-close').html(options.closeText),
spinner = $('<div>').addClass('sl-spinner').html('<div></div>'),
nav = $('<div>').addClass('sl-navigation').html('<button class="sl-prev">'+options.navText[0]+'</button><button class="sl-next">'+options.navText[1]+'</button>'),
counter = $('<div>').addClass('sl-counter').html('<span class="sl-current"></span>/<span class="sl-total"></span>'),
animating = false,
index = 0,
image = $(),
caption = $('<div>').addClass('sl-caption'),
isValidLink = function( element ){
return $( element ).prop( 'tagName' ).toLowerCase() == 'a' && ( new RegExp( '\.(' + options.fileExt + ')$', 'i' ) ).test( $( element ).attr( 'href' ) );
},
setup = function(){
if(options.overlay) overlay.appendTo($('body'));
$('<div>')
.addClass('sl-wrapper').addClass(options.className)
.html('<div class="sl-image"></div>')
.appendTo('body');
image = $('.sl-image');
if(options.close) closeBtn.appendTo($('.sl-wrapper'));
if(options.showCounter){
if($(selector).length > 1){
counter.appendTo($('.sl-wrapper'));
$('.sl-wrapper .sl-counter .sl-total').text($(selector).length);
}
}
if(options.nav) nav.appendTo($('.sl-wrapper'));
if(options.spinner) spinner.appendTo($('.sl-wrapper'));
},
openImage = function(elem){
elem.trigger($.Event('show.simplelightbox'));
animating = true;
index = $(selector).index(elem);
curImg = $( '<img/>' )
.hide()
.attr('src', elem.attr('href'));
$('.sl-image').html('');
curImg.appendTo($('.sl-image'));
overlay.fadeIn('fast');
$('.sl-close').fadeIn('fast');
spinner.show();
nav.fadeIn('fast');
$('.sl-wrapper .sl-counter .sl-current').text(index +1);
counter.fadeIn('fast');
adjustImage();
if(options.preloading){
preload();
}
setTimeout( function(){ elem.trigger($.Event('shown.simplelightbox'));} ,options.animationSpeed);
},
adjustImage = function(dir){
if(!curImg.length) return;
var tmpImage = new Image(),
windowWidth = $( window ).width() * options.widthRatio,
windowHeight = $( window ).height() * options.heightRatio;
tmpImage.src = curImg.attr( 'src' );
tmpImage.onload = function() {
var imageWidth = tmpImage.width,
imageHeight = tmpImage.height;
if( imageWidth > windowWidth || imageHeight > windowHeight ){
var ratio = imageWidth / imageHeight > windowWidth / windowHeight ? imageWidth / windowWidth : imageHeight / windowHeight;
imageWidth /= ratio;
imageHeight /= ratio;
}
$('.sl-image').css({
'top': ( $( window ).height() - imageHeight ) / 2 + 'px',
'left': ( $( window ).width() - imageWidth ) / 2 + 'px'
});
spinner.hide();
curImg
.css({
'width': imageWidth + 'px',
'height': imageHeight + 'px'
})
.fadeIn('fast');
opened = true;
var captionText = $(selector).eq(index).find('img').prop('title');
if(dir == 1 || dir == -1){
var css = { 'opacity': 1.0 };
if( canTransisions ) {
slide(0, 100 * dir + 'px');
setTimeout( function(){ slide( options.animationSpeed / 1000, 0 + 'px'), 50 });
}
else {
css.left = parseInt( $('.sl-image').css( 'left' ) ) + 100 * dir + 'px';
}
$('.sl-image').animate( css, options.animationSpeed, function(){
animating = false;
setCaption(captionText);
});
} else {
animating = false;
setCaption(captionText);
}
}
},
setCaption = function(captiontext){
if(captiontext != '' && options.captions){
caption.text(captiontext).hide().appendTo($('.sl-image')).fadeIn('fast');
}
},
slide = function(speed, pos){
var styles = {};
styles[transPrefix + 'transform'] = 'translateX(' + pos + ')';
styles[transPrefix + 'transition'] = transPrefix + 'transform ' + speed + 's linear';
$('.sl-image').css(styles);
},
preload = function(){
var next = (index+1 < 0) ? $(selector).length -1: (index+1 >= $(selector).length -1) ? 0 : index+1,
prev = (index-1 < 0) ? $(selector).length -1: (index-1 >= $(selector).length -1) ? 0 : index-1;
$( '<img />' ).attr( 'src', $(selector).eq(next).attr( 'href' ) ).load();
$( '<img />' ).attr( 'src', $(selector).eq(prev).attr( 'href' ) ).load();
},
loadImage = function(dir){
spinner.show();
var newIndex = index + dir;
if(animating || (newIndex < 0 || newIndex >= $(selector).length) && options.loop == false ) return;
animating = true;
index = (newIndex < 0) ? $(selector).length -1: (newIndex > $(selector).length -1) ? 0 : newIndex;
$('.sl-wrapper .sl-counter .sl-current').text(index +1);
var css = { 'opacity': 0 };
if( canTransisions ) slide(options.animationSpeed / 1000, ( -100 * dir ) - swipeDiff + 'px');
else css.left = parseInt( $('.sl-image').css( 'left' ) ) + -100 * dir + 'px';
$('.sl-image').animate( css, options.animationSpeed, function(){
setTimeout( function(){
// fadeout old image
var elem = $(selector).eq(index);
curImg
.attr('src', elem.attr('href'));
$('.sl-caption').remove();
adjustImage(dir);
if(options.preloading) preload();
}, 100);
});
},
close = function(){
var elem = $(selector).eq(index),
triggered = false;
elem.trigger($.Event('close.simplelightbox'));
$('.sl-image img, .sl-overlay, .sl-close, .sl-navigation, .sl-image .sl-caption, .sl-counter').fadeOut('fast', function(){
if(!triggered) elem.trigger($.Event('closed.simplelightbox'));
triggered = true;
});
curImg = $();
opened = false;
}
// events
setup();
// resize/responsive
$( window ).on( 'resize', adjustImage );
// open lightbox
$( document ).on( 'click.'+prefix, this.selector, function( e ){
if(isValidLink(this)){
e.preventDefault();
if(animating) return false;
openImage($(this));
}
});
// close lightbox on close btn
$(document).on('click', '.sl-close', function(e){
e.preventDefault();
if(opened){ close();}
});
// close on click on doc
$(document).click(function(e){
if(opened){
if((options.docClose && $(e.target).closest('.sl-image').length == 0 && $(e.target).closest('.sl-navigation').length == 0)
){
close();
}
}
});
// nav-buttons
$(document).on('click', '.sl-navigation button', function(e){
e.preventDefault();
swipeDiff = 0;
loadImage( $(this).hasClass('sl-next') ? 1 : -1 );
});
// keyboard-control
if( options.enableKeyboard ){
$( document ).on( 'keyup.'+prefix, function( e ){
e.preventDefault();
swipeDiff = 0;
// keyboard control only if lightbox is open
if(opened){
var key = e.keyCode;
if( key == 27 ) {
close();
}
if( key == 37 || e.keyCode == 39 ) {
loadImage( e.keyCode == 39 ? 1 : -1 );
}
}
});
}
// touchcontrols
var swipeStart = 0,
swipeEnd = 0,
mousedown = false,
imageLeft = 0;
$(document)
.on( 'touchstart mousedown pointerdown MSPointerDown', '.sl-image', function(e)
{
if(mousedown) return true;
if( canTransisions ) imageLeft = parseInt( image.css( 'left' ) );
mousedown = true;
swipeStart = e.originalEvent.pageX || e.originalEvent.touches[ 0 ].pageX;
})
.on( 'touchmove mousemove pointermove MSPointerMove', '.sl-image', function(e)
{
if(!mousedown) return true;
e.preventDefault();
swipeEnd = e.originalEvent.pageX || e.originalEvent.touches[ 0 ].pageX;
swipeDiff = swipeStart - swipeEnd;
if( canTransisions ) slide( 0, -swipeDiff + 'px' );
else image.css( 'left', imageLeft - swipeDiff + 'px' );
})
.on( 'touchend mouseup touchcancel pointerup pointercancel MSPointerUp MSPointerCancel', '.sl-image' ,function(e)
{
mousedown = false;
if( Math.abs( swipeDiff ) > options.swipeTolerance ) {
loadImage( swipeDiff > 0 ? 1 : -1 );
}
else
{
if( canTransisions ) slide( options.animationSpeed / 1000, 0 + 'px' );
else image.animate({ 'left': imageLeft + 'px' }, options.animationSpeed / 2 );
}
});
// Public methods
this.open = function(elem){
openImage(elem);
}
this.next = function(){
loadImage( 1 );
}
this.prev = function(){
loadImage( -1 );
}
this.close = function(){
close();
}
this.destroy = function(){
$(document).unbind('click.'+prefix).unbind('keyup.'+prefix);
close();
$('.sl-overlay, .sl-wrapper').remove();
}
return this;
};
})( jQuery, window, document ); |
// Generated by CoffeeScript 1.7.1
(function() {
var $, cardFromNumber, cardFromType, cards, defaultFormat, formatBackCardNumber, formatBackExpiry, formatCardNumber, formatExpiry, formatForwardExpiry, formatForwardSlash, hasTextSelected, luhnCheck, reFormatCardNumber, restrictCVC, restrictCardNumber, restrictExpiry, restrictNumeric, setCardType,
__slice = [].slice,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
$ = jQuery;
$.payment = {};
$.payment.fn = {};
$.fn.payment = function() {
var args, method;
method = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return $.payment.fn[method].apply(this, args);
};
defaultFormat = /(\d{1,4})/g;
cards = [
{
type: 'maestro',
pattern: /^(5018|5020|5038|6304|6759|676[1-3])/,
format: defaultFormat,
length: [12, 13, 14, 15, 16, 17, 18, 19],
cvcLength: [3],
luhn: true
}, {
type: 'dinersclub',
pattern: /^(36|38|30[0-5])/,
format: defaultFormat,
length: [14],
cvcLength: [3],
luhn: true
}, {
type: 'laser',
pattern: /^(6706|6771|6709)/,
format: defaultFormat,
length: [16, 17, 18, 19],
cvcLength: [3],
luhn: true
}, {
type: 'jcb',
pattern: /^35/,
format: defaultFormat,
length: [16],
cvcLength: [3],
luhn: true
}, {
type: 'unionpay',
pattern: /^62/,
format: defaultFormat,
length: [16, 17, 18, 19],
cvcLength: [3],
luhn: false
}, {
type: 'discover',
pattern: /^(6011|65|64[4-9]|622)/,
format: defaultFormat,
length: [16],
cvcLength: [3],
luhn: true
}, {
type: 'mastercard',
pattern: /^5[1-5]/,
format: defaultFormat,
length: [16],
cvcLength: [3],
luhn: true
}, {
type: 'amex',
pattern: /^3[47]/,
format: /(\d{1,4})(\d{1,6})?(\d{1,5})?/,
length: [15],
cvcLength: [3, 4],
luhn: true
}, {
type: 'visa',
pattern: /^4/,
format: defaultFormat,
length: [13, 16],
cvcLength: [3],
luhn: true
}
];
cardFromNumber = function(num) {
var card, _i, _len;
num = (num + '').replace(/\D/g, '');
for (_i = 0, _len = cards.length; _i < _len; _i++) {
card = cards[_i];
if (card.pattern.test(num)) {
return card;
}
}
};
cardFromType = function(type) {
var card, _i, _len;
for (_i = 0, _len = cards.length; _i < _len; _i++) {
card = cards[_i];
if (card.type === type) {
return card;
}
}
};
luhnCheck = function(num) {
var digit, digits, odd, sum, _i, _len;
odd = true;
sum = 0;
digits = (num + '').split('').reverse();
for (_i = 0, _len = digits.length; _i < _len; _i++) {
digit = digits[_i];
digit = parseInt(digit, 10);
if ((odd = !odd)) {
digit *= 2;
}
if (digit > 9) {
digit -= 9;
}
sum += digit;
}
return sum % 10 === 0;
};
hasTextSelected = function($target) {
var _ref;
if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== $target.prop('selectionEnd')) {
return true;
}
if (typeof document !== "undefined" && document !== null ? (_ref = document.selection) != null ? typeof _ref.createRange === "function" ? _ref.createRange().text : void 0 : void 0 : void 0) {
return true;
}
return false;
};
reFormatCardNumber = function(e) {
return setTimeout((function(_this) {
return function() {
var $target, value;
$target = $(e.currentTarget);
value = $target.val();
value = $.payment.formatCardNumber(value);
return $target.val(value);
};
})(this));
};
formatCardNumber = function(e) {
var $target, card, digit, length, re, upperLength, value;
digit = String.fromCharCode(e.which);
if (!/^\d+$/.test(digit)) {
return;
}
$target = $(e.currentTarget);
value = $target.val();
card = cardFromNumber(value + digit);
length = (value.replace(/\D/g, '') + digit).length;
upperLength = 16;
if (card) {
upperLength = card.length[card.length.length - 1];
}
if (length >= upperLength) {
return;
}
if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== value.length) {
return;
}
if (card && card.type === 'amex') {
re = /^(\d{4}|\d{4}\s\d{6})$/;
} else {
re = /(?:^|\s)(\d{4})$/;
}
if (re.test(value)) {
e.preventDefault();
return $target.val(value + ' ' + digit);
} else if (re.test(value + digit)) {
e.preventDefault();
return $target.val(value + digit + ' ');
}
};
formatBackCardNumber = function(e) {
var $target, value;
$target = $(e.currentTarget);
value = $target.val();
if (e.meta) {
return;
}
if (e.which !== 8) {
return;
}
if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== value.length) {
return;
}
if (/\d\s$/.test(value)) {
e.preventDefault();
return $target.val(value.replace(/\d\s$/, ''));
} else if (/\s\d?$/.test(value)) {
e.preventDefault();
return $target.val(value.replace(/\s\d?$/, ''));
}
};
formatExpiry = function(e) {
var $target, digit, val;
digit = String.fromCharCode(e.which);
if (!/^\d+$/.test(digit)) {
return;
}
$target = $(e.currentTarget);
val = $target.val() + digit;
if (/^\d$/.test(val) && (val !== '0' && val !== '1')) {
e.preventDefault();
return $target.val("0" + val + " / ");
} else if (/^\d\d$/.test(val)) {
e.preventDefault();
return $target.val("" + val + " / ");
}
};
formatForwardExpiry = function(e) {
var $target, digit, val;
digit = String.fromCharCode(e.which);
if (!/^\d+$/.test(digit)) {
return;
}
$target = $(e.currentTarget);
val = $target.val();
if (/^\d\d$/.test(val)) {
return $target.val("" + val + " / ");
}
};
formatForwardSlash = function(e) {
var $target, slash, val;
slash = String.fromCharCode(e.which);
if (slash !== '/') {
return;
}
$target = $(e.currentTarget);
val = $target.val();
if (/^\d$/.test(val) && val !== '0') {
return $target.val("0" + val + " / ");
}
};
formatBackExpiry = function(e) {
var $target, value;
if (e.meta) {
return;
}
$target = $(e.currentTarget);
value = $target.val();
if (e.which !== 8) {
return;
}
if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== value.length) {
return;
}
if (/\d(\s|\/)+$/.test(value)) {
e.preventDefault();
return $target.val(value.replace(/\d(\s|\/)*$/, ''));
} else if (/\s\/\s?\d?$/.test(value)) {
e.preventDefault();
return $target.val(value.replace(/\s\/\s?\d?$/, ''));
}
};
restrictNumeric = function(e) {
var input;
if (e.metaKey || e.ctrlKey) {
return true;
}
if (e.which === 32) {
return false;
}
if (e.which === 0) {
return true;
}
if (e.which < 33) {
return true;
}
input = String.fromCharCode(e.which);
return !!/[\d\s]/.test(input);
};
restrictCardNumber = function(e) {
var $target, card, digit, value;
$target = $(e.currentTarget);
digit = String.fromCharCode(e.which);
if (!/^\d+$/.test(digit)) {
return;
}
if (hasTextSelected($target)) {
return;
}
value = ($target.val() + digit).replace(/\D/g, '');
card = cardFromNumber(value);
if (card) {
return value.length <= card.length[card.length.length - 1];
} else {
return value.length <= 16;
}
};
restrictExpiry = function(e) {
var $target, digit, value;
$target = $(e.currentTarget);
digit = String.fromCharCode(e.which);
if (!/^\d+$/.test(digit)) {
return;
}
if (hasTextSelected($target)) {
return;
}
value = $target.val() + digit;
value = value.replace(/\D/g, '');
if (value.length > 6) {
return false;
}
};
restrictCVC = function(e) {
var $target, digit, val;
$target = $(e.currentTarget);
digit = String.fromCharCode(e.which);
if (!/^\d+$/.test(digit)) {
return;
}
if (hasTextSelected($target)) {
return;
}
val = $target.val() + digit;
return val.length <= 4;
};
setCardType = function(e) {
var $target, allTypes, card, cardType, val;
$target = $(e.currentTarget);
val = $target.val();
cardType = $.payment.cardType(val) || 'unknown';
if (!$target.hasClass(cardType)) {
allTypes = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = cards.length; _i < _len; _i++) {
card = cards[_i];
_results.push(card.type);
}
return _results;
})();
$target.removeClass('unknown');
$target.removeClass(allTypes.join(' '));
$target.addClass(cardType);
$target.toggleClass('identified', cardType !== 'unknown');
return $target.trigger('payment.cardType', cardType);
}
};
$.payment.fn.formatCardCVC = function() {
this.payment('restrictNumeric');
this.on('keypress', restrictCVC);
return this;
};
$.payment.fn.formatCardExpiry = function() {
this.payment('restrictNumeric');
this.on('keypress', restrictExpiry);
this.on('keypress', formatExpiry);
this.on('keypress', formatForwardSlash);
this.on('keypress', formatForwardExpiry);
this.on('keydown', formatBackExpiry);
return this;
};
$.payment.fn.formatCardNumber = function() {
this.payment('restrictNumeric');
this.on('keypress', restrictCardNumber);
this.on('keypress', formatCardNumber);
this.on('keydown', formatBackCardNumber);
this.on('keyup', setCardType);
this.on('paste', reFormatCardNumber);
return this;
};
$.payment.fn.restrictNumeric = function() {
this.on('keypress', restrictNumeric);
return this;
};
$.payment.fn.cardExpiryVal = function() {
return $.payment.cardExpiryVal($(this).val());
};
$.payment.cardExpiryVal = function(value) {
var month, prefix, year, _ref;
value = value.replace(/\s/g, '');
_ref = value.split('/', 2), month = _ref[0], year = _ref[1];
if ((year != null ? year.length : void 0) === 2 && /^\d+$/.test(year)) {
prefix = (new Date).getFullYear();
prefix = prefix.toString().slice(0, 2);
year = prefix + year;
}
month = parseInt(month, 10);
year = parseInt(year, 10);
return {
month: month,
year: year
};
};
$.payment.validateCardNumber = function(num) {
var card, _ref;
num = (num + '').replace(/\s+|-/g, '');
if (!/^\d+$/.test(num)) {
return false;
}
card = cardFromNumber(num);
if (!card) {
return false;
}
return (_ref = num.length, __indexOf.call(card.length, _ref) >= 0) && (card.luhn === false || luhnCheck(num));
};
$.payment.validateCardExpiry = (function(_this) {
return function(month, year) {
var currentTime, expiry, prefix, _ref;
if (typeof month === 'object' && 'month' in month) {
_ref = month, month = _ref.month, year = _ref.year;
}
if (!(month && year)) {
return false;
}
month = $.trim(month);
year = $.trim(year);
if (!/^\d+$/.test(month)) {
return false;
}
if (!/^\d+$/.test(year)) {
return false;
}
if (!(parseInt(month, 10) <= 12)) {
return false;
}
if (year.length === 2) {
prefix = (new Date).getFullYear();
prefix = prefix.toString().slice(0, 2);
year = prefix + year;
}
expiry = new Date(year, month);
currentTime = new Date;
expiry.setMonth(expiry.getMonth() - 1);
expiry.setMonth(expiry.getMonth() + 1, 1);
return expiry > currentTime;
};
})(this);
$.payment.validateCardCVC = function(cvc, type) {
var _ref, _ref1;
cvc = $.trim(cvc);
if (!/^\d+$/.test(cvc)) {
return false;
}
if (type) {
return _ref = cvc.length, __indexOf.call((_ref1 = cardFromType(type)) != null ? _ref1.cvcLength : void 0, _ref) >= 0;
} else {
return cvc.length >= 3 && cvc.length <= 4;
}
};
$.payment.cardType = function(num) {
var _ref;
if (!num) {
return null;
}
return ((_ref = cardFromNumber(num)) != null ? _ref.type : void 0) || null;
};
$.payment.formatCardNumber = function(num) {
var card, groups, upperLength, _ref;
card = cardFromNumber(num);
if (!card) {
return num;
}
upperLength = card.length[card.length.length - 1];
num = num.replace(/\D/g, '');
num = num.slice(0, +upperLength + 1 || 9e9);
if (card.format.global) {
return (_ref = num.match(card.format)) != null ? _ref.join(' ') : void 0;
} else {
groups = card.format.exec(num);
if (groups != null) {
groups.shift();
}
return groups != null ? groups.join(' ') : void 0;
}
};
}).call(this); |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _filter;
var _arrayMap = require('lodash/_arrayMap');
var _arrayMap2 = _interopRequireDefault(_arrayMap);
var _baseProperty = require('lodash/_baseProperty');
var _baseProperty2 = _interopRequireDefault(_baseProperty);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _filter(eachfn, arr, iteratee, callback) {
var results = [];
eachfn(arr, function (x, index, callback) {
iteratee(x, function (err, v) {
if (err) {
callback(err);
} else {
if (v) {
results.push({ index: index, value: x });
}
callback();
}
});
}, function (err) {
if (err) {
callback(err);
} else {
callback(null, (0, _arrayMap2.default)(results.sort(function (a, b) {
return a.index - b.index;
}), (0, _baseProperty2.default)('value')));
}
});
}
module.exports = exports['default']; |
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides the built-in number matchers like lessThan,
* greaterThan, etc.
*/
goog.provide('goog.labs.testing.CloseToMatcher');
goog.provide('goog.labs.testing.EqualToMatcher');
goog.provide('goog.labs.testing.GreaterThanEqualToMatcher');
goog.provide('goog.labs.testing.GreaterThanMatcher');
goog.provide('goog.labs.testing.LessThanEqualToMatcher');
goog.provide('goog.labs.testing.LessThanMatcher');
goog.require('goog.asserts');
goog.require('goog.labs.testing.Matcher');
/**
* The GreaterThan matcher.
*
* @param {number} value The value to compare.
*
* @constructor
* @struct
* @implements {goog.labs.testing.Matcher}
* @final
*/
goog.labs.testing.GreaterThanMatcher = function(value) {
/**
* @type {number}
* @private
*/
this.value_ = value;
};
/**
* Determines if input value is greater than the expected value.
*
* @override
*/
goog.labs.testing.GreaterThanMatcher.prototype.matches = function(actualValue) {
goog.asserts.assertNumber(actualValue);
return actualValue > this.value_;
};
/**
* @override
*/
goog.labs.testing.GreaterThanMatcher.prototype.describe = function(
actualValue) {
goog.asserts.assertNumber(actualValue);
return actualValue + ' is not greater than ' + this.value_;
};
/**
* The lessThan matcher.
*
* @param {number} value The value to compare.
*
* @constructor
* @struct
* @implements {goog.labs.testing.Matcher}
* @final
*/
goog.labs.testing.LessThanMatcher = function(value) {
/**
* @type {number}
* @private
*/
this.value_ = value;
};
/**
* Determines if the input value is less than the expected value.
*
* @override
*/
goog.labs.testing.LessThanMatcher.prototype.matches = function(actualValue) {
goog.asserts.assertNumber(actualValue);
return actualValue < this.value_;
};
/**
* @override
*/
goog.labs.testing.LessThanMatcher.prototype.describe = function(actualValue) {
goog.asserts.assertNumber(actualValue);
return actualValue + ' is not less than ' + this.value_;
};
/**
* The GreaterThanEqualTo matcher.
*
* @param {number} value The value to compare.
*
* @constructor
* @struct
* @implements {goog.labs.testing.Matcher}
* @final
*/
goog.labs.testing.GreaterThanEqualToMatcher = function(value) {
/**
* @type {number}
* @private
*/
this.value_ = value;
};
/**
* Determines if the input value is greater than equal to the expected value.
*
* @override
*/
goog.labs.testing.GreaterThanEqualToMatcher.prototype.matches = function(
actualValue) {
goog.asserts.assertNumber(actualValue);
return actualValue >= this.value_;
};
/**
* @override
*/
goog.labs.testing.GreaterThanEqualToMatcher.prototype.describe = function(
actualValue) {
goog.asserts.assertNumber(actualValue);
return actualValue + ' is not greater than equal to ' + this.value_;
};
/**
* The LessThanEqualTo matcher.
*
* @param {number} value The value to compare.
*
* @constructor
* @struct
* @implements {goog.labs.testing.Matcher}
* @final
*/
goog.labs.testing.LessThanEqualToMatcher = function(value) {
/**
* @type {number}
* @private
*/
this.value_ = value;
};
/**
* Determines if the input value is less than or equal to the expected value.
*
* @override
*/
goog.labs.testing.LessThanEqualToMatcher.prototype.matches = function(
actualValue) {
goog.asserts.assertNumber(actualValue);
return actualValue <= this.value_;
};
/**
* @override
*/
goog.labs.testing.LessThanEqualToMatcher.prototype.describe = function(
actualValue) {
goog.asserts.assertNumber(actualValue);
return actualValue + ' is not less than equal to ' + this.value_;
};
/**
* The EqualTo matcher.
*
* @param {number} value The value to compare.
*
* @constructor
* @struct
* @implements {goog.labs.testing.Matcher}
* @final
*/
goog.labs.testing.EqualToMatcher = function(value) {
/**
* @type {number}
* @private
*/
this.value_ = value;
};
/**
* Determines if the input value is equal to the expected value.
*
* @override
*/
goog.labs.testing.EqualToMatcher.prototype.matches = function(actualValue) {
goog.asserts.assertNumber(actualValue);
return actualValue === this.value_;
};
/**
* @override
*/
goog.labs.testing.EqualToMatcher.prototype.describe = function(actualValue) {
goog.asserts.assertNumber(actualValue);
return actualValue + ' is not equal to ' + this.value_;
};
/**
* The CloseTo matcher.
*
* @param {number} value The value to compare.
* @param {number} range The range to check within.
*
* @constructor
* @struct
* @implements {goog.labs.testing.Matcher}
* @final
*/
goog.labs.testing.CloseToMatcher = function(value, range) {
/**
* @type {number}
* @private
*/
this.value_ = value;
/**
* @type {number}
* @private
*/
this.range_ = range;
};
/**
* Determines if input value is within a certain range of the expected value.
*
* @override
*/
goog.labs.testing.CloseToMatcher.prototype.matches = function(actualValue) {
goog.asserts.assertNumber(actualValue);
return Math.abs(this.value_ - actualValue) < this.range_;
};
/**
* @override
*/
goog.labs.testing.CloseToMatcher.prototype.describe = function(actualValue) {
goog.asserts.assertNumber(actualValue);
return actualValue + ' is not close to(' + this.range_ + ') ' + this.value_;
};
/**
* @param {number} value The expected value.
*
* @return {!goog.labs.testing.GreaterThanMatcher} A GreaterThanMatcher.
*/
function greaterThan(value) {
return new goog.labs.testing.GreaterThanMatcher(value);
}
/**
* @param {number} value The expected value.
*
* @return {!goog.labs.testing.GreaterThanEqualToMatcher} A
* GreaterThanEqualToMatcher.
*/
function greaterThanEqualTo(value) {
return new goog.labs.testing.GreaterThanEqualToMatcher(value);
}
/**
* @param {number} value The expected value.
*
* @return {!goog.labs.testing.LessThanMatcher} A LessThanMatcher.
*/
function lessThan(value) {
return new goog.labs.testing.LessThanMatcher(value);
}
/**
* @param {number} value The expected value.
*
* @return {!goog.labs.testing.LessThanEqualToMatcher} A LessThanEqualToMatcher.
*/
function lessThanEqualTo(value) {
return new goog.labs.testing.LessThanEqualToMatcher(value);
}
/**
* @param {number} value The expected value.
*
* @return {!goog.labs.testing.EqualToMatcher} An EqualToMatcher.
*/
function equalTo(value) {
return new goog.labs.testing.EqualToMatcher(value);
}
/**
* @param {number} value The expected value.
* @param {number} range The maximum allowed difference from the expected value.
*
* @return {!goog.labs.testing.CloseToMatcher} A CloseToMatcher.
*/
function closeTo(value, range) {
return new goog.labs.testing.CloseToMatcher(value, range);
}
|
/*!
* jQuery Lazy - v0.6.2
* http://jquery.eisbehr.de/lazy/
*
* Copyright 2012 - 2015, Daniel 'Eisbehr' Kern
*
* Dual licensed under the MIT and GPL-2.0 licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
*
* $("img.lazy").lazy();
*/
;(function($, window, document, undefined)
{
"use strict";
// make lazy a bit more case-insensitive :)
$.fn.Lazy = $.fn.lazy = function(settings)
{
return new LazyPlugin(this, settings);
};
/**
* contains all logic and the whole element handling
* is packed in a private function outside class to reduce memory usage, because it will not be created on every plugin instance
* @access private
* @type {function}
* @param {LazyPlugin} instance
* @param {function} configuration
* @param {object} items
* @param {object} events
* @return void
*/
function _executeLazy(instance, configuration, items, events)
{
/**
* a helper to trigger the 'onFinishedAll' callback after all other events
* @access private
* @type {number}
*/
var _awaitingAfterLoad = 0,
/**
* visible content width
* @access private
* @type {number}
*/
_actualWidth = -1,
/**
* visible content height
* @access private
* @type {number}
*/
_actualHeight = -1,
/**
* determine possible detected high pixel density
* @access private
* @type {boolean}
*/
_isRetinaDisplay = false;
/**
* initialize plugin
* bind loading to events or set delay time to load all items at once
* @access private
* @return void
*/
function _initialize()
{
// detect actual device pixel ratio
// noinspection JSUnresolvedVariable
_isRetinaDisplay = window.devicePixelRatio > 1;
// prepare all initial items
_prepareItems(items);
// if delay time is set load all items at once after delay time
if( configuration("delay") >= 0 ) setTimeout(function() { _lazyLoadItems(true); }, configuration("delay"));
// if no delay is set or combine usage is active bind events
if( configuration("delay") < 0 || configuration("combined") )
{
// create unique event function
events.e = _throttle(configuration("throttle"), function(event)
{
// reset detected window size on resize event
if( event.type === "resize" )
_actualWidth = _actualHeight = -1;
// execute 'lazy magic'
_lazyLoadItems(event.all);
});
// create function to add new items to instance
events.a = function(additionalItems)
{
_prepareItems(additionalItems);
items.push.apply(items, additionalItems);
};
// create function to get all instance items left
events.g = function()
{
return items;
};
// load initial items
_lazyLoadItems();
// bind lazy load functions to scroll and resize event
$(configuration("appendScroll")).on("scroll." + instance.name + " resize." + instance.name, events.e);
}
}
/**
* prepare items before handle them
* @access private
* @param {Array|object|jQuery} items
* @return void
*/
function _prepareItems(items)
{
// filter items and only add those who not handled yet and got needed attributes available
items = $(items).filter(function()
{
return !$(this).data(configuration("handledName")) && ($(this).attr(configuration("attribute")) || $(this).attr(configuration("loaderAttribute")));
})
// append plugin instance to all elements
.data("plugin_" + instance.name, instance);
// bind error callback to items if set
if( configuration("onError") )
items.on("error." + instance.name, function()
{
_triggerCallback("onError", $(this));
});
// set default image and/or placeholder to elements if configured
if( configuration("defaultImage") || configuration("placeholder") )
for( var i = 0; i < items.length; i++ )
{
var element = $(items[i]),
tag = items[i].tagName.toLowerCase(),
propertyName = "background-image";
// set default image on every element without source
if( tag == "img" && configuration("defaultImage") && !element.attr("src") )
element.attr("src", configuration("defaultImage"));
// set placeholder on every element without background image
else if( tag != "img" && configuration("placeholder") && (!element.css(propertyName) || element.css(propertyName) == "none") )
element.css(propertyName, "url(" + configuration("placeholder") + ")");
}
}
/**
* the 'lazy magic' - check all items
* @access private
* @param {boolean} [allItems]
* @return void
*/
function _lazyLoadItems(allItems)
{
// skip if no items where left
if( !items.length )
{
// destroy instance if option is enabled
if( configuration("autoDestroy") )
// noinspection JSUnresolvedFunction
instance.destroy();
return;
}
// helper to see if something was changed
var loadTriggered = false,
// get image base once, not on every image loop
imageBase = configuration("imageBase") ? configuration("imageBase") : "";
// loop all available items
for( var i = 0; i < items.length; i++ )
(function(item)
{
// item is at least in loadable area
if( _isInLoadableArea(item) || allItems )
{
var element = $(item),
tag = item.tagName.toLowerCase(),
attribute = imageBase + element.attr(configuration("attribute")),
customLoader;
// is not already handled
if( !element.data(configuration("handledName")) &&
// and is visible or visibility doesn't matter
(!configuration("visibleOnly") || element.is(":visible")) && (
// and image source attribute is available
attribute && (
// and is image tag where attribute is not equal source
(tag == "img" && attribute != element.attr("src")) ||
// or is non image tag where attribute is not equal background
(tag != "img" && attribute != element.css("background-image")) ) ||
// or custom loader is available
(customLoader = element.attr(configuration("loaderAttribute"))) ))
{
// mark element always as handled as this point to prevent double loading
loadTriggered = true;
element.data(configuration("handledName"), true);
// load item
_handleItem(element, tag, imageBase, customLoader);
}
}
})(items[i]);
// when something was loaded remove them from remaining items
if( loadTriggered )
items = $(items).filter(function()
{
return !$(this).data(configuration("handledName"));
});
}
/**
* load the given element the lazy way
* @access private
* @param {object} element
* @param {string} tag
* @param {string} imageBase
* @param {function} [customLoader]
* @return void
*/
function _handleItem(element, tag, imageBase, customLoader)
{
// increment count of items waiting for after load
++_awaitingAfterLoad;
// extended error callback for correct 'onFinishedAll' handling
var errorCallback = function()
{
_triggerCallback("onError", element);
_reduceAwaiting();
};
// trigger function before loading image
_triggerCallback("beforeLoad", element);
// handle custom loader
if( customLoader )
{
// bind error event to trigger callback and reduce waiting amount
element.off("error").one("error", errorCallback);
// bind after load callback to image
element.one("load", function()
{
// remove attribute from element
if( configuration("removeAttribute") )
element.removeAttr(configuration("loaderAttribute"));
// call after load event
_triggerCallback("afterLoad", element);
// remove item from waiting queue and possible trigger finished event
_reduceAwaiting();
});
// trigger custom loader
if( !_triggerCallback(customLoader, element, function(response)
{
if( response ) element.load();
else element.error();
})) element.error();
}
// handle images
else
{
// create image object
var imageObj = $(new Image());
// bind error event to trigger callback and reduce waiting amount
imageObj.one("error", errorCallback);
// bind after load callback to image
imageObj.one("load", function()
{
// remove element from view
element.hide();
// set image back to element
if( tag == "img" ) element.attr("src", imageObj.attr("src"));
else element.css("background-image", "url(" + imageObj.attr("src") + ")");
// bring it back with some effect!
element[configuration("effect")](configuration("effectTime"));
// remove attribute from element
if( configuration("removeAttribute") )
element.removeAttr(configuration("attribute") + " " + configuration("retinaAttribute"));
// call after load event
_triggerCallback("afterLoad", element);
// cleanup image object
imageObj.remove();
// remove item from waiting queue and possible trigger finished event
_reduceAwaiting();
});
// set source
imageObj.attr("src", imageBase + element.attr(configuration(_isRetinaDisplay && element.attr(configuration("retinaAttribute")) ? "retinaAttribute" : "attribute")));
// call after load even on cached image
if( imageObj.complete ) imageObj.load();
}
}
/**
* check if the given element is inside the current viewport or threshold
* @access private
* @param {object} element
* @return {boolean}
*/
function _isInLoadableArea(element)
{
var elementBound = element.getBoundingClientRect(),
direction = configuration("scrollDirection"),
threshold = configuration("threshold"),
vertical = // check if element is in loadable area from top
((_getActualHeight() + threshold) > elementBound.top) &&
// check if element is even in loadable are from bottom
(-threshold < elementBound.bottom),
horizontal = // check if element is in loadable area from left
((_getActualWidth() + threshold) > elementBound.left) &&
// check if element is even in loadable area from right
(-threshold < elementBound.right);
if( direction == "vertical" ) return vertical;
else if( direction == "horizontal" ) return horizontal;
return vertical && horizontal;
}
/**
* receive the current viewed width of the browser
* @access private
* @return {number}
*/
function _getActualWidth()
{
return _actualWidth >= 0 ? _actualWidth : (_actualWidth = $(window).width());
}
/**
* receive the current viewed height of the browser
* @access private
* @return {number}
*/
function _getActualHeight()
{
return _actualHeight >= 0 ? _actualHeight : (_actualHeight = $(window).height());
}
/**
* helper function to throttle down event triggering
* @access private
* @param {number} delay
* @param {function} callback
* @return {function}
*/
function _throttle(delay, callback)
{
var timeout, lastExecute = 0;
return function(event, ignoreThrottle)
{
var elapsed = +new Date() - lastExecute;
function run()
{
lastExecute = +new Date();
callback.call(instance, event);
}
timeout && clearTimeout(timeout);
if( elapsed > delay || !configuration("enableThrottle") || ignoreThrottle ) run();
else timeout = setTimeout(run, delay - elapsed);
};
}
/**
* reduce count of awaiting elements to 'afterLoad' event and fire 'onFinishedAll' if reached zero
* @access private
* @return void
*/
function _reduceAwaiting()
{
--_awaitingAfterLoad;
// if no items were left trigger finished event
if( !items.size() && !_awaitingAfterLoad ) _triggerCallback("onFinishedAll");
}
/**
* single implementation to handle callbacks, pass element and set 'this' to current instance
* @access private
* @param {string|function} callback
* @param {object} [element]
* @param {*} [args]
* @return {boolean}
*/
function _triggerCallback(callback, element, args)
{
if( (callback = configuration(callback)) )
{
callback.apply(instance, $(arguments).slice(1));
return true;
}
return false;
}
// set up lazy
(function()
{
// if event driven don't wait for page loading
if( configuration("bind") == "event" ) _initialize();
// otherwise load initial items and start lazy after page load
else $(window).load(_initialize);
})();
}
/**
* lazy plugin class constructor
* @constructor
* @access private
* @param {object} elements
* @param {object} settings
* @return {object|LazyPlugin}
*/
function LazyPlugin(elements, settings)
{
/**
* this lazy plugin instance
* @access private
* @type {object|LazyPlugin}
*/
var _instance = this,
/**
* this lazy plugin instance configuration
* @access private
* @type {object}
*/
_config = $.extend({}, _instance.configuration, settings),
/**
* instance generated event executed on container scroll or resize
* packed in an object to be referenceable and short named because properties will not be minified
* @access private
* @type {object}
*/
_events = {};
// noinspection JSUndefinedPropertyAssignment
/**
* wrapper to get or set an entry from plugin instance configuration
* much smaller on minify as direct access
* @access private
* @type {function}
* @param {string} entryName
* @param {*} [value]
* @return {LazyPlugin|*}
*/
_instance.config = function(entryName, value)
{
if( value === undefined )
return _config[entryName];
else
_config[entryName] = value;
return _instance;
};
// noinspection JSUndefinedPropertyAssignment
/**
* add additional items to current instance
* @access public
* @param {Array|object|string} items
* @return {LazyPlugin}
*/
_instance.addItems = function(items)
{
if( _events.a )
_events.a($.type(items) === "string" ? $(items) : items);
return _instance;
};
// noinspection JSUndefinedPropertyAssignment
/**
* get all left items of this instance
* @access public
* @returns {object}
*/
_instance.getItems = function()
{
return _events.g ? _events.g() : {};
};
// noinspection JSUndefinedPropertyAssignment
/**
* force lazy to load all items in loadable area right now
* by default without throttle
* @access public
* @type {function}
* @param {boolean} [useThrottle]
* @return {LazyPlugin}
*/
_instance.update = function(useThrottle)
{
if( _events.e )
_events.e({}, !useThrottle);
return _instance;
};
// noinspection JSUndefinedPropertyAssignment
/**
* force lazy to load all available items right now
* this call ignores throttling
* @access public
* @type {function}
* @return {LazyPlugin}
*/
_instance.loadAll = function()
{
if( _events.e )
_events.e({all: true}, true);
return _instance;
};
// noinspection JSUndefinedPropertyAssignment
/**
* destroy this plugin instance
* @access public
* @type {function}
* @return void
*/
_instance.destroy = function ()
{
// unbind instance generated events
// noinspection JSUnresolvedFunction
$(_instance.config("appendScroll")).off("." + _instance.name, _events.e);
// clear events
_events = {};
};
// start using lazy and return all elements to be chainable or instance for further use
// noinspection JSUnresolvedVariable
_executeLazy(_instance, _instance.config, elements, _events);
// noinspection JSUnresolvedFunction
return _instance.config("chainable") ? elements : _instance;
}
// use jquery to extend class prototype without conflicts
$.extend(LazyPlugin.prototype,
{
/**
* internal name used for bindings and namespaces
* @access public
* @var {string}
*/
name: "lazy",
/**
* settings and configuration data
* @access public
* @type {object}
*/
configuration:
{
// general
chainable : true,
autoDestroy : true,
bind : "load",
threshold : 500,
visibleOnly : false,
appendScroll : window,
scrollDirection : "both",
imageBase : null,
defaultImage : "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==",
placeholder : null,
delay : -1,
combined : false,
// attributes
attribute : "data-src",
retinaAttribute : "data-retina",
loaderAttribute : "data-loader",
removeAttribute : true,
handledName : "handled",
// effect
effect : "show",
effectTime : 0,
// throttle
enableThrottle : true,
throttle : 250,
// callbacks
beforeLoad : null,
afterLoad : null,
onError : null,
onFinishedAll : null
}
});
})(jQuery, window, document); |
/**
* API Bound Models for AngularJS
* @version v0.4.0 - 2013-10-25
* @link https://github.com/angular-platanus/angular-restmod
* @author Ignacio Baixas <iobaixas@gmai.com>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
!function(a,b){"use strict";a.module("plRestmod").factory("DirtyModel",["$restmod",function(a){return a.abstract(function(){this.afterFeed(function(a){this.$original=a}).attrIgnored("$original",!0).define("$dirty",function(a){var c=this.$original;if(a)return c&&c[a]!==b?c[a]!==this[a]:!1;var d,e=[];if(c)for(d in c)c.hasOwnProperty(d)&&c[d]!==this[d]&&e.push(d);return e})})}])}(angular); |
/*!
* jquery.inputmask.phone.extensions.js
* http://github.com/RobinHerbots/jquery.inputmask
* Copyright (c) 2010 - 2014 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 3.1.45
*/
;!function(a){"function"==typeof define&&define.amd?define(["jquery","./jquery.inputmask"],a):a(jQuery)}(function(a){return a.extend(a.inputmask.defaults.aliases,{phone:{url:"phone-codes/phone-codes.js",maskInit:"+pp(pp)pppppppp",countrycode:"",mask:function(b){b.definitions={p:{validator:function(){return !1},cardinality:1},"#":{validator:"[0-9]",cardinality:1}};var c=[];return a.ajax({url:b.url,async:!1,dataType:"json",success:function(d){c=d},error:function(f,d,e){alert(e+" - "+b.url)}}),c=c.sort(function(e,d){return(e.mask||e)<(d.mask||d)?-1:1}),""!=b.countrycode&&(b.maskInit="+"+b.countrycode+b.maskInit.substring(3)),c.splice(0,0,b.maskInit),c},nojumps:!0,nojumpsThreshold:1,onBeforeMask:function(d,c){var b=d.replace(/^0/g,"");return(b.indexOf(c.countrycode)>1||-1==b.indexOf(c.countrycode))&&(b="+"+c.countrycode+b),b}},phonebe:{alias:"phone",url:"phone-codes/phone-be.js",countrycode:"32",nojumpsThreshold:4}}),a.fn.inputmask}); |
(function($){
var id = 0;
var isNumber = function(string){
return (typeof string == 'number' || (string && string == string * 1));
};
var retDefault = function(val, def){
if(!(typeof val == 'number' || (val && val == val * 1))){
return def;
}
return val * 1;
};
var createOpts = ['step', 'min', 'max', 'readonly', 'title', 'disabled', 'tabindex'];
var rangeProto = {
_create: function(){
var i;
this.element.addClass('ws-range').attr({role: 'slider'}).append('<span class="ws-range-min ws-range-progress" /><span class="ws-range-rail ws-range-track"><span class="ws-range-thumb" /></span>');
this.trail = $('.ws-range-track', this.element);
this.range = $('.ws-range-progress', this.element);
this.thumb = $('.ws-range-thumb', this.trail);
this.updateMetrics();
this.orig = this.options.orig;
for(i = 0; i < createOpts.length; i++){
this[createOpts[i]](this.options[createOpts[i]]);
}
this.value = this._value;
this.value(this.options.value);
this.initDataList();
this.element.data('rangeUi', this);
this.addBindings();
this._init = true;
},
value: $.noop,
_value: function(val, _noNormalize, animate){
var left, posDif, textValue;
var o = this.options;
var oVal = val;
var thumbStyle = {};
var rangeStyle = {};
if(!_noNormalize && parseFloat(val, 10) != val){
val = o.min + ((o.max - o.min) / 2);
}
if(!_noNormalize){
val = this.normalizeVal(val);
}
left = 100 * ((val - o.min) / (o.max - o.min));
if(this._init && val == o.value && oVal == val){return;}
this.options.value = val;
if($.fn.stop){
this.thumb.stop();
this.range.stop();
}
rangeStyle[this.dirs.width] = left+'%';
if(this.vertical){
left = Math.abs(left - 100);
}
thumbStyle[this.dirs.left] = left+'%';
if(!animate || !$.fn.animate){
this.thumb.css(thumbStyle);
this.range.css(rangeStyle);
} else {
if(typeof animate != 'object'){
animate = {};
} else {
animate = $.extend({}, animate);
}
if(!animate.duration){
posDif = Math.abs(left - parseInt(this.thumb[0].style[this.dirs.left] || 50, 10));
animate.duration = Math.max(Math.min(999, posDif * 5), 99);
}
this.thumb.animate(thumbStyle, animate);
this.range.animate(rangeStyle, animate);
}
if(this.orig && (oVal != val || (!this._init && this.orig.value != val)) ){
this.options._change(val);
}
textValue = this.options.textValue ? this.options.textValue(this.options.value) : this.options.options[this.options.value] || this.options.value;
this.element.attr({
'aria-valuenow': this.options.value,
'aria-valuetext': textValue
});
this.thumb.attr({
'data-value': this.options.value,
'data-valuetext': textValue
});
},
initDataList: function(){
if(this.orig){
var listTimer;
var that = this;
var updateList = function(){
$(that.orig)
.jProp('list')
.off('updateDatalist', updateList)
.on('updateDatalist', updateList)
;
clearTimeout(listTimer);
listTimer = setTimeout(function(){
if(that.list){
that.list();
}
}, 9);
};
$(this.orig).on('listdatalistchange', updateList);
this.list();
}
},
list: function(opts){
var o = this.options;
var min = o.min;
var max = o.max;
var trail = this.trail;
var that = this;
this.element.attr({'aria-valuetext': o.options[o.value] || o.value});
$('.ws-range-ticks', trail).remove();
$(this.orig).jProp('list').find('option:not([disabled])').each(function(){
o.options[$.prop(this, 'value')] = $.prop(this, 'label') || '';
});
$.each(o.options, function(val, label){
if(!isNumber(val) || val < min || val > max){return;}
var left = 100 * ((val - min) / (max - min));
var attr = '';
if(label){
attr += 'data-label="'+label+'"';
if(o.showLabels){
attr += ' title="'+label+'"';
}
}
if(that.vertical){
left = Math.abs(left - 100);
}
that.posCenter(
$('<span class="ws-range-ticks"'+ attr +' style="'+(that.dirs.left)+': '+left+'%;" />').appendTo(trail)
);
});
},
readonly: function(val){
val = !!val;
this.options.readonly = val;
this.element.attr('aria-readonly', ''+val);
if(this._init){
this.updateMetrics();
}
},
disabled: function(val){
val = !!val;
this.options.disabled = val;
if(val){
this.element.attr({tabindex: -1, 'aria-disabled': 'true'});
} else {
this.element.attr({tabindex: this.options.tabindex, 'aria-disabled': 'false'});
}
if(this._init){
this.updateMetrics();
}
},
tabindex: function(val){
this.options.tabindex = val;
if(!this.options.disabled){
this.element.attr({tabindex: val});
}
},
title: function(val){
this.element.prop('title', val);
},
min: function(val){
this.options.min = retDefault(val, 0);
this.value(this.options.value, true);
},
max: function(val){
this.options.max = retDefault(val, 100);
this.value(this.options.value, true);
},
step: function(val){
var o = this.options;
var step = val == 'any' ? 'any' : retDefault(val, 1);
if(o.stepping){
if(step != 'any' && o.stepping % step){
webshims.error('wrong stepping value for type range:'+ (o.stepping % step));
} else {
step = o.stepping;
}
}
o.step = step;
this.value(this.options.value);
},
normalizeVal: function(val){
var valModStep, alignValue, step;
var o = this.options;
if(val <= o.min){
val = o.min;
} else if(val >= o.max) {
val = o.max;
} else if(o.step != 'any'){
step = o.step;
valModStep = (val - o.min) % step;
alignValue = val - valModStep;
if ( Math.abs(valModStep) * 2 >= step ) {
alignValue += ( valModStep > 0 ) ? step : ( -step );
}
val = alignValue.toFixed(5) * 1;
}
return val;
},
doStep: function(factor, animate){
var step = retDefault(this.options.step, 1);
if(this.options.step == 'any'){
step = Math.min(step, (this.options.max - this.options.min) / 10);
}
this.value( this.options.value + (step * factor), false, animate );
},
getStepedValueFromPos: function(pos){
var val, valModStep, alignValue, step;
if(pos <= 0){
val = this.options[this.dirs.min];
} else if(pos > 100) {
val = this.options[this.dirs.max];
} else {
if(this.vertical){
pos = Math.abs(pos - 100);
}
val = ((this.options.max - this.options.min) * (pos / 100)) + this.options.min;
step = this.options.step;
if(step != 'any'){
valModStep = (val - this.options.min) % step;
alignValue = val - valModStep;
if ( Math.abs(valModStep) * 2 >= step ) {
alignValue += ( valModStep > 0 ) ? step : ( -step );
}
val = ((alignValue).toFixed(5)) * 1;
}
}
return val;
},
addRemoveClass: function(cName, add){
var isIn = this.element.prop('className').indexOf(cName) != -1;
var action;
if(!add && isIn){
action = 'removeClass';
this.element.removeClass(cName);
this.updateMetrics();
} else if(add && !isIn){
action = 'addClass';
}
if(action){
this.element[action](cName);
if(this._init){
this.updateMetrics();
}
}
},
addBindings: function(){
var leftOffset, widgetUnits, hasFocus, isActive;
var that = this;
var o = this.options;
var eventTimer = (function(){
var events = {};
return {
init: function(name, curVal, fn){
if(!events[name]){
events[name] = {fn: fn};
if(that.orig){
$(that.orig).on(name, function(){
events[name].val = $.prop(that.orig, 'value');
});
}
}
events[name].val = curVal;
},
call: function(name, val){
if(events[name].val != val){
clearTimeout(events[name].timer);
events[name].val = val;
events[name].timer = setTimeout(function(){
events[name].fn(val, that);
}, 0);
}
}
};
})();
var normalizeTouch = (function(){
var types = {
touchstart: 1,
touchend: 1,
touchmove: 1
};
var normalize = ['pageX', 'pageY'];
return function(e){
if(types[e.type] && e.originalEvent && e.originalEvent.touches && e.originalEvent.touches.length){
for(var i = 0; i < normalize.length; i++){
e[normalize[i]] = e.originalEvent.touches[0][normalize[i]];
}
}
return e;
};
})();
var setValueFromPos = function(e, animate){
if(e.type == 'touchmove'){
e.preventDefault();
normalizeTouch(e);
}
var val = that.getStepedValueFromPos((e[that.dirs.mouse] - leftOffset) * widgetUnits);
if(val != o.value){
that.value(val, false, animate);
eventTimer.call('input', val);
}
if(e && e.type == 'mousemove'){
e.preventDefault();
}
};
var remove = function(e){
if(e && e.type == 'mouseup'){
eventTimer.call('input', o.value);
eventTimer.call('change', o.value);
}
that.addRemoveClass('ws-active');
$(document).off('mousemove touchmove', setValueFromPos).off('mouseup touchend', remove);
$(window).off('blur', removeWin);
isActive = false;
};
var removeWin = function(e){
if(e.target == window){remove();}
};
var add = function(e){
var outerWidth;
if(isActive || (e.type == 'touchstart' && (!e.originalEvent || !e.originalEvent.touches || e.originalEvent.touches.length != 1))){
return;
}
e.preventDefault();
$(document).off('mousemove touchmove', setValueFromPos).off('mouseup touchend', remove);
$(window).off('blur', removeWin);
if(!o.readonly && !o.disabled){
normalizeTouch(e);
that.element.trigger('focus');
that.addRemoveClass('ws-active', true);
leftOffset = that.element.offset();
widgetUnits = that.element[that.dirs.innerWidth]();
if(!widgetUnits || !leftOffset){return;}
outerWidth = that.thumb[that.dirs.outerWidth]();
leftOffset = leftOffset[that.dirs.pos];
widgetUnits = 100 / widgetUnits;
setValueFromPos(e, o.animate);
isActive = true;
$(document)
.on(e.type == 'touchstart' ?
{
touchend: remove,
touchmove: setValueFromPos
} :
{
mouseup: remove,
mousemove: setValueFromPos
}
)
;
$(window).on('blur', removeWin);
e.stopPropagation();
}
};
var elementEvts = {
'touchstart mousedown': add,
focus: function(e){
if(!o.disabled && !hasFocus){
eventTimer.init('input', o.value);
eventTimer.init('change', o.value);
that.addRemoveClass('ws-focus', true);
that.updateMetrics();
}
hasFocus = true;
},
blur: function(e){
that.element.removeClass('ws-focus ws-active');
that.updateMetrics();
hasFocus = false;
eventTimer.init('input', o.value);
eventTimer.call('change', o.value);
},
keyup: function(){
that.addRemoveClass('ws-active');
eventTimer.call('input', o.value);
eventTimer.call('change', o.value);
},
keydown: function(e){
var step = true;
var code = e.keyCode;
if(!o.readonly && !o.disabled){
if (code == 39 || code == 38) {
that.doStep(1);
} else if (code == 37 || code == 40) {
that.doStep(-1);
} else if (code == 33) {
that.doStep(10, o.animate);
} else if (code == 34) {
that.doStep(-10, o.animate);
} else if (code == 36) {
that.value(that.options.max, false, o.animate);
} else if (code == 35) {
that.value(that.options.min, false, o.animate);
} else {
step = false;
}
if (step) {
that.addRemoveClass('ws-active', true);
eventTimer.call('input', o.value);
e.preventDefault();
}
}
}
};
eventTimer.init('input', o.value, this.options.input);
eventTimer.init('change', o.value, this.options.change);
elementEvts[$.fn.mwheelIntent ? 'mwheelIntent' : 'mousewheel'] = function(e, delta){
if(delta && hasFocus && !o.readonly && !o.disabled){
that.doStep(delta);
e.preventDefault();
eventTimer.call('input', o.value);
}
};
this.element.on(elementEvts);
this.thumb.on({
mousedown: add
});
if(this.orig){
$(this.orig).jProp('form').on('reset', function(){
var val = $.prop(that.orig, 'value');
that.value(val);
setTimeout(function(){
var val2 = $.prop(that.orig, 'value');
if(val != val2){
that.value(val2);
}
}, 4);
});
}
if (window.webshims) {
webshims.ready('WINDOWLOAD', function(){
webshims.ready('dom-support', function(){
if ($.fn.onWSOff) {
that.element.onWSOff('updateshadowdom', function(){
that.updateMetrics();
});
}
});
if (!$.fn.onWSOff && webshims._polyfill) {
webshims._polyfill(['dom-support']);
}
});
}
},
posCenter: function(elem, outerWidth){
var temp;
if(this.options.calcCenter && (!this._init || this.element[0].offsetWidth)){
if(!elem){
elem = this.thumb;
}
if(!outerWidth){
outerWidth = elem[this.dirs.outerWidth]();
}
outerWidth = outerWidth / -2;
elem.css(this.dirs.marginLeft, outerWidth);
if(this.options.calcTrail && elem[0] == this.thumb[0]){
temp = this.element[this.dirs.innerHeight]();
elem.css(this.dirs.marginTop, (elem[this.dirs.outerHeight]() - temp) / -2);
this.range.css(this.dirs.marginTop, (this.range[this.dirs.outerHeight]() - temp) / -2 );
outerWidth *= -1;
this.trail
.css(this.dirs.left, outerWidth)
.css(this.dirs.right, outerWidth)
;
}
}
},
updateMetrics: function(){
var width = this.element.innerWidth();
this.vertical = (width && this.element.innerHeight() - width > 10);
this.dirs = this.vertical ?
{mouse: 'pageY', pos: 'top', min: 'max', max: 'min', left: 'top', right: 'bottom', width: 'height', innerWidth: 'innerHeight', innerHeight: 'innerWidth', outerWidth: 'outerHeight', outerHeight: 'outerWidth', marginTop: 'marginLeft', marginLeft: 'marginTop'} :
{mouse: 'pageX', pos: 'left', min: 'min', max: 'max', left: 'left', right: 'right', width: 'width', innerWidth: 'innerWidth', innerHeight: 'innerHeight', outerWidth: 'outerWidth', outerHeight: 'outerHeight', marginTop: 'marginTop', marginLeft: 'marginLeft'}
;
this.element
[this.vertical ? 'addClass' : 'removeClass']('vertical-range')
[this.vertical ? 'addClass' : 'removeClass']('horizontal-range')
;
this.posCenter();
}
};
var oCreate = function (o) {
function F() {}
F.prototype = o;
return new F();
};
$.fn.rangeUI = function(opts){
opts = $.extend({
readonly: false,
disabled: false,
tabindex: 0,
min: 0,
step: 1,
max: 100,
value: 50,
input: $.noop,
change: $.noop,
_change: $.noop,
showLabels: true,
options: {},
calcCenter: true,
calcTrail: true
}, opts);
return this.each(function(){
var obj = $.extend(oCreate(rangeProto), {element: $(this)});
obj.options = opts;
obj._create.call(obj);
});
};
if(window.webshims && webshims.isReady){
webshims.isReady('range-ui', true);
}
})(window.webshims ? webshims.$ : jQuery);;webshims.register('form-number-date-ui', function($, webshims, window, document, undefined, options){
"use strict";
var curCfg;
var formcfg = webshims.formcfg;
var hasFormValidation = Modernizr.formvalidation && !webshims.bugs.bustedValidity;
var monthDigits = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
var stopPropagation = function(e){
e.stopImmediatePropagation();
};
var getMonthOptions = function(opts){
var selectName = 'monthSelect'+opts.formatMonthNames;
if(!curCfg[selectName]){
var labels = curCfg.date[opts.formatMonthNames] || monthDigits;
curCfg[selectName] = ('<option value=""></option>')+$.map(monthDigits, function(val, i){
return '<option value="'+val+'"]>'+labels[i]+'</option>';
}).join('');
}
return curCfg[selectName];
};
var daySelect = '<select class="dd"><option value=""></option>'+ (function(){
var i = 1;
var opts = [];
while(i < 32){
opts.push('<option>'+ ((i < 10) ? '0'+ i : i) +'</option>' );
i++;
}
return opts.join('');
})() +'</select>';
var createFormat = function(name){
if(!curCfg.patterns[name+'Obj']){
var obj = {};
$.each(curCfg.patterns[name].split(curCfg[name+'Format']), function(i, name){
obj[name] = i;
});
curCfg.patterns[name+'Obj'] = obj;
}
};
var splitInputs = {
date: {
_create: function(opts){
var obj = {
splits: [$('<input type="text" class="yy" size="4" inputmode="numeric" maxlength="4" />')[0]]
};
if(opts.monthSelect){
obj.splits.push($('<select class="mm">'+getMonthOptions(opts)+'</select>')[0]);
} else {
obj.splits.push($('<input type="text" class="mm" inputmode="numeric" maxlength="2" size="2" />')[0]);
}
if(opts.daySelect){
obj.splits.push($(daySelect)[0]);
} else {
obj.splits.push($('<input type="text" class="dd ws-spin" inputmode="numeric" maxlength="2" size="2" />')[0]);
}
obj.elements = [obj.splits[0], $('<span class="ws-input-seperator" />')[0], obj.splits[1], $('<span class="ws-input-seperator" />')[0], obj.splits[2]];
return obj;
},
sort: function(element){
createFormat('d');
var i = 0;
var seperators = $('.ws-input-seperator', element).html(curCfg.dFormat);
var inputs = $('input, select', element);
$.each(curCfg.patterns.dObj, function(name, value){
var input = inputs.filter('.'+ name);
if(input[0]){
input.appendTo(element);
if(i < seperators.length){
seperators.eq(i).insertAfter(input);
}
i++;
}
});
}
},
month: {
_create: function(opts){
var obj = {
splits: [$('<input type="text" class="yy" inputmode="numeric" size="4" />')[0]]
};
if(opts.monthSelect){
obj.splits.push($('<select class="mm">'+getMonthOptions(opts)+'</select>')[0]);
} else {
obj.splits.push($('<input type="text" class="mm ws-spin" />')[0]);
if(opts.onlyMonthDigits){
$(obj.splits[1]).attr({inputmode: 'numeric', size: 2, maxlength: 2});
}
}
obj.elements = [obj.splits[0], $('<span class="ws-input-seperator" />')[0], obj.splits[1]];
return obj;
},
sort: function(element){
var seperator = $('.ws-input-seperator', element).html(curCfg.dFormat);
var mm = $('input.mm, select.mm', element);
var action;
if(curCfg.date.showMonthAfterYear){
mm.appendTo(element);
action = 'insertBefore';
} else {
mm.prependTo(element);
action = 'insertAfter';
}
seperator[action](mm);
}
}
};
var nowDate = new Date(new Date().getTime() - (new Date().getTimezoneOffset() * 60 * 1000 ));
nowDate = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), nowDate.getHours()).getTime()
var steps = {
number: {
step: 1
},
// week: {
// step: 1,
// start: new Date(nowDate)
// },
'datetime-local': {
step: 60,
start: new Date(nowDate).getTime()
},
time: {
step: 60
},
month: {
step: 1,
start: new Date(nowDate)
},
date: {
step: 1,
start: new Date(nowDate)
}
};
var labelWidth = (function(){
var getId = function(){
return webshims.getID(this);
};
return function(element, labels, noFocus){
$(element).attr({'aria-labelledby': labels.map(getId).get().join(' ')});
if(!noFocus){
labels.on('click', function(e){
element.getShadowFocusElement().focus();
e.preventDefault();
return false;
});
}
};
})();
var addZero = function(val){
if(!val){return "";}
val = val+'';
return val.length == 1 ? '0'+val : val;
};
var loadPicker = function(type, name){
type = (type == 'color' ? 'color' : 'forms')+'-picker';
if(!loadPicker[name+'Loaded'+type]){
loadPicker[name+'Loaded'+type] = true;
webshims.ready(name, function(){
webshims.loader.loadList([type]);
});
}
return type;
};
options.addZero = addZero;
webshims.loader.addModule('forms-picker', {
noAutoCallback: true,
options: options
});
webshims.loader.addModule('color-picker', {
noAutoCallback: true,
css: 'jpicker/jpicker.css',
options: options,
d: ['forms-picker']
});
options.steps = steps;
(function(){
formcfg.de = $.extend(true, {
numberFormat: {
",": ".",
".": ","
},
timeSigns: ":. ",
numberSigns: ',',
dateSigns: '.',
dFormat: ".",
patterns: {
d: "dd.mm.yy"
},
month: {
currentText: 'Aktueller Monat'
},
time: {
currentText: 'Jetzt'
},
date: {
close: 'schließen',
clear: 'Löschen',
prevText: 'Zurück',
nextText: 'Vor',
currentText: 'Heute',
monthNames: ['Januar','Februar','März','April','Mai','Juni',
'Juli','August','September','Oktober','November','Dezember'],
monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
'Jul','Aug','Sep','Okt','Nov','Dez'],
dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
weekHeader: 'KW',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''
}
}, formcfg.de || {});
formcfg.en = $.extend(true, {
numberFormat: {
".": ".",
",": ","
},
numberSigns: '.',
dateSigns: '/',
timeSigns: ":. ",
dFormat: "/",
patterns: {
d: "mm/dd/yy"
},
meridian: ['AM', 'PM'],
month: {
currentText: 'This month'
},
time: {
"currentText": "Now"
},
date: {
"closeText": "Done",
clear: 'Clear',
"prevText": "Prev",
"nextText": "Next",
"currentText": "Today",
"monthNames": ["January","February","March","April","May","June","July","August","September","October","November","December"],
"monthNamesShort": ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],
"dayNames": ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
"dayNamesShort": ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],
"dayNamesMin": ["Su","Mo","Tu","We","Th","Fr","Sa"],
"weekHeader": "Wk",
"firstDay": 0,
"isRTL": false,
"showMonthAfterYear": false,
"yearSuffix": ""
}
}, formcfg.en || {});
if(!formcfg['en-US']){
formcfg['en-US'] = $.extend(true, {}, formcfg['en']);
}
if(!formcfg['en-GB']){
formcfg['en-GB'] = $.extend(true, {}, formcfg.en, {
date: {firstDay: 1},
patterns: {d: "dd/mm/yy"}
});
}
if(!formcfg['en-AU']){
formcfg['en-AU'] = $.extend(true, {}, formcfg['en-GB']);
}
if(!formcfg['']){
formcfg[''] = formcfg['en-US'];
}
curCfg = formcfg[''];
var processLangCFG = function(langCfg){
if(!langCfg.date.monthkeys){
var create = function(i, name){
var strNum;
var num = i + 1;
strNum = (num < 10) ? '0'+num : ''+num;
langCfg.date.monthkeys[num] = strNum;
langCfg.date.monthkeys[name] = strNum;
langCfg.date.monthkeys[name.toLowerCase()] = strNum;
};
langCfg.date.monthkeys = {};
langCfg.date.monthDigits = monthDigits;
langCfg.numberSigns += '-';
if(langCfg.meridian){
langCfg.timeSigns += langCfg.meridian[0] + langCfg.meridian[1] + langCfg.meridian[0].toLowerCase() + langCfg.meridian[1].toLowerCase();
}
$.each(langCfg.date.monthNames, create);
$.each(langCfg.date.monthNamesShort, create);
}
if(!langCfg.colorSigns){
langCfg.colorSigns = '#abcdefABCDEF';
}
if(!langCfg['datetime-localSigns']){
langCfg['datetime-localSigns'] = langCfg.dateSigns+langCfg.timeSigns;
}
if(!langCfg['datetime-local']){
langCfg['datetime-local'] = {};
}
if(!langCfg.time){
langCfg.time = {};
}
if(!langCfg['datetime-local'].currentText && langCfg.time.currentText){
langCfg['datetime-local'].currentText = langCfg.time.currentText;
}
};
var triggerLocaleChange = function(){
processLangCFG(curCfg);
$(document).triggerHandler('wslocalechange');
};
curCfg = webshims.activeLang(formcfg);
triggerLocaleChange();
$(formcfg).on('change', function(){
curCfg = formcfg.__active;
triggerLocaleChange();
});
})();
(function(){
var retDefault = function(val, def){
if(!(typeof val == 'number' || (val && val == val * 1))){
return def;
}
return val * 1;
};
var formatVal = {
number: function(val){
return (val+'').replace(/\,/g, '').replace(/\./, curCfg.numberFormat['.']);
},
time: function(val){
var fVal;
if(val && curCfg.meridian){
val = val.split(':');
fVal = (val[0] * 1);
if(fVal && fVal >= 12){
val[0] = addZero(fVal - 12+'');
fVal = 1;
} else {
fVal = 0;
}
if(val[0] === '00'){
val[0] = '12';
}
val = $.trim(val.join(':')) + ' '+ curCfg.meridian[fVal];
}
return val;
},
'datetime-local': function(val, o){
var fVal = $.trim(val || '').split('T');
if(fVal.length == 2){
val = this.date(fVal[0], o) +' '+this.time(fVal[1], o);
}
return val;
},
// week: function(val){
// return val;
// },
//todo empty val for month/split
month: function(val, options){
var names;
var p = val.split('-');
if(p[0] && p[1]){
names = curCfg.date[options.formatMonthNames] || curCfg.date[options.monthNames] || curCfg.date.monthNames;
p[1] = names[(p[1] * 1) - 1];
if(options && options.splitInput){
val = [p[0] || '', p[1] || ''];
} else if(p[1]){
val = curCfg.date.showMonthAfterYear ? p.join(' ') : p[1]+' '+p[0];
}
} else if(options && options.splitInput){
val = [p[0] || '', p[1] || ''];
}
return val;
},
date: function(val, opts){
var p = (val+'').split('-');
if(p[2] && p[1] && p[0]){
if(opts && opts.splitInput){
val = p;
} else {
val = curCfg.patterns.d.replace('yy', p[0] || '');
val = val.replace('mm', p[1] || '');
val = val.replace('dd', p[2] || '');
}
} else if(opts && opts.splitInput){
val = [p[0] || '', p[1] || '', p[2] || ''];
}
return val;
},
color: function(val, opts){
var ret = '#000000';
if(val){
val = val.toLowerCase();
if(val.length == 7 && createHelper('color').isValid(val)) {
ret = val;
}
}
return ret;
}
};
var parseVal = {
number: function(val){
return (val+'').replace(curCfg.numberFormat[','], '').replace(curCfg.numberFormat['.'], '.');
},
// week: function(val){
// return val;
// },
'datetime-local': function(val, o){
var tmp;
var fVal = $.trim(val || '').split(/\s+/);
if(fVal.length == 2){
if(fVal[0].indexOf(':') != -1 && fVal[1].indexOf(':') == -1){
tmp = fVal[1];
fVal[1] = fVal[0];
fVal[0] = tmp;
}
val = this.date(fVal[0], o) +'T'+ this.time(fVal[1], o);
} else if (fVal.length == 3) {
val = this.date(fVal[0], o) +'T'+ this.time(fVal[1]+fVal[2], o);
}
return val;
},
time: function(val){
var fVal;
if(val && curCfg.meridian){
val = val.toUpperCase();
if(val.substr(0,2) === "12"){
val = "00" + val.substr(2);
}
if(val.indexOf(curCfg.meridian[1]) != -1){
val = val.split(':');
fVal = (val[0] * 1);
if(!isNaN(fVal)){
val[0] = fVal + 12;
}
val = val.join(':');
}
val = $.trim(val.replace(curCfg.meridian[0], '').replace(curCfg.meridian[1], ''));
}
return val;
},
month: function(val, opts, noCorrect){
var p = (!opts.splitInput) ? val.trim().split(/[\.\s-\/\\]+/) : val;
if(p.length == 2 && p[0] && p[1]){
p[0] = !noCorrect && curCfg.date.monthkeys[p[0]] || p[0];
p[1] = !noCorrect && curCfg.date.monthkeys[p[1]] || p[1];
if(p[1].length == 2 && p[0].length > 3){
val = p[0]+'-'+p[1];
} else if(p[0].length == 2 && p[1].length > 3){
val = p[1]+'-'+p[0];
} else {
val = '';
}
} else if(opts.splitInput) {
val = '';
}
return val;
},
date: function(val, opts, noCorrect){
createFormat('d');
var tmp, obj;
var ret = '';
if(opts.splitInput){
obj = {yy: 0, mm: 1, dd: 2};
} else {
obj = curCfg.patterns.dObj;
val = val.split(curCfg.dFormat);
}
if(val.length == 3 && val[0] && val[1] && val[2] && (!noCorrect || (val[obj.yy].length > 3 && val[obj.mm].length == 2 && val[obj.dd].length == 2))){
if(val[obj.mm] > 12 && val[obj.dd] < 13){
tmp = val[obj.dd];
val[obj.dd] = val[obj.mm];
val[obj.mm] = tmp;
}
if(val[obj.yy].length < 4){
tmp = ((new Date()).getFullYear() +'').substr(0, 4 - val[obj.yy].length);
if(val[obj.yy] > 50){
tmp--;
}
val[obj.yy] = tmp + val[obj.yy];
}
ret = ([addZero(val[obj.yy]), addZero(val[obj.mm]), addZero(val[obj.dd])]).join('-');
}
return ret
;
},
color: function(val, opts){
var ret = '#000000';
if(val){
val = val.toLowerCase();
if (val.indexOf('#') !== 0) {
val = '#' + val;
}
if(val.length == 4){
val = '#' + val.charAt(1) + val.charAt(1) + val.charAt(2) + val.charAt(2) + val.charAt(3) + val.charAt(3);
}
if(val.length == 7 && createHelper('color').isValid(val)) {
ret = val;
}
}
return ret;
}
};
var placeholderFormat = {
date: function(val, opts){
var hintValue = (val || '').split('-');
if(hintValue.length == 3){
hintValue = opts.splitInput ?
hintValue :
curCfg.patterns.d.replace('yy', hintValue[0]).replace('mm', hintValue[1]).replace('dd', hintValue[2]);
} else {
hintValue = opts.splitInput ?
[val, val, val] :
val;
}
return hintValue;
},
month: function(val, opts){
var hintValue = (val || '').split('-');
if(hintValue.length == 2){
hintValue = opts.splitInput ?
hintValue :
curCfg.date.showMonthAfterYear ?
hintValue[0] +' '+hintValue[1] :
hintValue[1] +' '+ hintValue[0];
} else {
hintValue = opts.splitInput ?
[val, val] :
val;
}
return hintValue;
}
};
var createHelper = (function(){
var types = {};
return function(type){
var input;
if(!types[type]){
input = $('<input type="'+type+'" step="any" />');
types[type] = {
asNumber: function(val){
var type = (typeof val == 'object') ? 'valueAsDate' : 'value';
return input.prop(type, val).prop('valueAsNumber');
},
asValue: function(val){
var type = (typeof val == 'object') ? 'valueAsDate' : 'valueAsNumber';
return input.prop(type, val).prop('value');
},
isValid: function(val, attrs){
if(attrs && (attrs.nodeName || attrs.jquery)){
attrs = {
min: $(attrs).prop('min') || '',
max: $(attrs).prop('max') || '',
step: $(attrs).prop('step') || 'any'
};
}
attrs = $.extend({step: 'any', min: '', max: ''}, attrs || {});
return input.attr(attrs).prop('value', val).is(':valid') && input.prop('value') == val;
}
};
}
return types[type];
};
})();
steps.range = steps.number;
var wsWidgetProto = {
_create: function(){
var i, that, timedMirror;
var o = this.options;
var createOpts = this.createOpts;
this.type = o.type;
this.orig = o.orig;
this.buttonWrapper = $('<span class="input-buttons '+this.type+'-input-buttons"></span>').insertAfter(this.element);
this.options.containerElements.push(this.buttonWrapper[0]);
o.mirrorValidity = o.mirrorValidity && this.orig && hasFormValidation;
if(o.splitInput && this._addSplitInputs){
if(o.monthSelect){
this.element.addClass('ws-month-select');
}
this._addSplitInputs();
} else {
this.inputElements = this.element;
}
if( steps[this.type] && typeof steps[this.type].start == 'object'){
steps[this.type].start = this.asNumber(steps[this.type].start);
}
if(!webshims.picker[this.type]){
o.buttonOnly = false;
}
for(i = 0; i < createOpts.length; i++){
if(o[createOpts[i]] != null){
this[createOpts[i]](o[createOpts[i]], o[createOpts[i]]);
}
}
if(this.type == 'color'){
this.inputElements.prop('maxLength', 7);
}
this.addBindings();
$(this.element).data('wsWidget'+o.type, this);
if(o.buttonOnly){
this.inputElements.prop({readOnly: true});
}
this._init = true;
if(o.mirrorValidity){
that = this;
timedMirror = function(){
clearTimeout(timedMirror._timerDealy);
timedMirror._timerDealy = setTimeout(timedMirror._wsexec, 9);
};
timedMirror._wsexec = function(){
clearTimeout(timedMirror._timerDealy);
that.mirrorValidity(true);
};
timedMirror();
$(this.orig).on('change input', function(e){
if(e.type == 'input'){
timedMirror();
} else {
timedMirror._wsexec();
}
});
}
},
mirrorValidity: function(_noTest){
//
if(this._init && this.options.mirrorValidity){
if(!_noTest){
$.prop(this.orig, 'validity');
}
var message = $(this.orig).getErrorMessage();
if(message !== this.lastErrorMessage){
this.inputElements.prop('setCustomValidity', function(i, val){
if(val._supvalue){
val._supvalue.call(this, message);
}
});
this.lastErrorMessage = message;
}
}
},
addBindings: function(){
var that = this;
var o = this.options;
var run = function(){
that._addBindings();
};
if(this._addBindings){
run();
} else {
webshims.ready('forms-picker', run);
loadPicker(this.type, 'WINDOWLOAD');
}
this.inputElements
.add(this.buttonWrapper)
.add(this.element)
.one('mousedown focusin', function(e){
loadPicker(that.type, 'DOM');
})
.on({
'change input focus focusin blur focusout': function(e){
$(e.target).trigger('ws__'+e.type);
}
})
;
if(this.type != 'color'){
(function(){
var localeChange, select, selectVal;
if(!o.splitInput){
localeChange = function(){
if(o.value){
that.value(o.value, true);
}
if(placeholderFormat[that.type] && o.placeholder){
that.placeholder(o.placeholder);
}
};
} else {
localeChange = function(){
that.reorderInputs();
if(o.monthSelect){
select = that.inputElements.filter('select.mm');
selectVal = select.prop('value');
select.html(getMonthOptions(o));
select.prop('value', selectVal);
}
};
that.reorderInputs();
}
$(that.orig).onWSOff('wslocalechange', localeChange);
})();
}
},
required: function(val, boolVal){
this.inputElements.attr({'aria-required': ''+boolVal});
this.mirrorValidity();
},
parseValue: function(noCorrect){
var value = this.inputElements.map(function(){
return $.prop(this, 'value');
}).get();
if(!this.options.splitInput){
value = value[0];
}
return parseVal[this.type](value, this.options, noCorrect);
},
formatValue: function(val, noSplit){
return formatVal[this.type](val, noSplit === false ? false : this.options);
},
createOpts: ['readonly', 'title', 'disabled', 'tabindex', 'placeholder', 'defaultValue', 'value', 'required'],
placeholder: function(val){
var options = this.options;
options.placeholder = val;
var placeholder = val;
if(placeholderFormat[this.type]){
placeholder = placeholderFormat[this.type](val, this.options);
}
if(options.splitInput && typeof placeholder == 'object'){
$.each(this.splits, function(i, elem){
if($.nodeName(elem, 'select')){
$(elem).children('option:first-child').text(placeholder[i]);
} else {
$.prop(elem, 'placeholder', placeholder[i]);
}
});
} else {
this.element.prop('placeholder', placeholder);
}
},
list: function(val){
if(this.type == 'number'){
this.element.attr('list', $.attr(this.orig, 'list'));
}
this.options.list = val;
this._propertyChange('list');
},
_propertyChange: $.noop,
tabindex: function(val){
this.options.tabindex = val;
this.inputElements.prop('tabindex', this.options.tabindex);
$('button', this.buttonWrapper).prop('tabindex', this.options.tabindex);
},
title: function(val){
if(!val && this.orig && $.attr(this.orig, 'title') == null){
val = null;
}
this.options.title = val;
if(val == null){
this.inputElements.removeAttr('title');
} else {
this.inputElements.prop('title', this.options.title);
}
}
};
['defaultValue', 'value'].forEach(function(name){
wsWidgetProto[name] = function(val, force){
if(!this._init || force || val !== this.options[name]){
this.element.prop(name, this.formatValue(val));
this.options[name] = val;
this._propertyChange(name);
this.mirrorValidity();
}
};
});
['readonly', 'disabled'].forEach(function(name){
var isDisabled = name == 'disabled';
wsWidgetProto[name] = function(val, boolVal){
var options = this.options;
if(options[name] != boolVal || !this._init){
options[name] = !!boolVal;
if(!isDisabled && options.buttonOnly){
this.inputElements.attr({'aria-readonly': options[name]});
} else {
this.inputElements.prop(name, options[name]);
}
this.buttonWrapper[options[name] ? 'addClass' : 'removeClass']('ws-'+name);
if(isDisabled){
$('button', this.buttonWrapper).prop('disabled', options[name]);
}
}
};
});
var spinBtnProto = $.extend({}, wsWidgetProto, {
_create: function(){
var o = this.options;
var helper = createHelper(o.type);
this.elemHelper = $('<input type="'+ o.type+'" />');
this.asNumber = helper.asNumber;
this.asValue = helper.asValue;
this.isValid = helper.isValid;
wsWidgetProto._create.apply(this, arguments);
this._init = false;
this.buttonWrapper.html('<span unselectable="on" class="step-controls"><span class="step-up"></span><span class="step-down"></span></span>');
if(this.type == 'number'){
this.inputElements.attr('inputmode', 'numeric');
}
if((!o.max && typeof o.relMax == 'number') || (!o.min && typeof o.relMin == 'number')){
webshims.error('relMax/relMin are not supported anymore')
}
this._init = true;
},
createOpts: ['step', 'min', 'max', 'readonly', 'title', 'disabled', 'tabindex', 'placeholder', 'defaultValue', 'value', 'required'],
_addSplitInputs: function(){
if(!this.inputElements){
var create = splitInputs[this.type]._create(this.options);
this.splits = create.splits;
this.inputElements = $(create.elements).prependTo(this.element).filter('input, select');
}
},
getRelNumber: function(rel){
var start = steps[this.type].start || 0;
if(rel){
start += rel;
}
return start;
},
addZero: addZero,
_setStartInRange: function(){
var start = this.getRelNumber(this.options.relDefaultValue);
if(!isNaN(this.minAsNumber) && start < this.minAsNumber){
start = this.minAsNumber;
} else if(!isNaN(this.maxAsNumber) && start > this.maxAsNumber){
start = this.maxAsNumber;
}
this.elemHelper.prop('valueAsNumber', start);
this.options.defValue = this.elemHelper.prop('value');
},
reorderInputs: function(){
if(splitInputs[this.type]){
var element = this.element;
splitInputs[this.type].sort(element, this.options);
setTimeout(function(){
var data = webshims.data(element);
if(data && data.shadowData){
data.shadowData.shadowFocusElement = element.find('input, select')[0] || element[0];
}
}, 9);
}
},
step: function(val){
var defStep = steps[this.type];
this.options.step = val;
this.elemHelper.prop('step', retDefault(val, defStep.step));
this.mirrorValidity();
},
_beforeValue: function(val){
this.valueAsNumber = this.asNumber(val);
this.options.value = val;
if(isNaN(this.valueAsNumber) || (!isNaN(this.minAsNumber) && this.valueAsNumber < this.minAsNumber) || (!isNaN(this.maxAsNumber) && this.valueAsNumber > this.maxAsNumber)){
this._setStartInRange();
} else {
this.elemHelper.prop('value', val);
this.options.defValue = "";
}
}
});
['defaultValue', 'value'].forEach(function(name){
var isValue = name == 'value';
spinBtnProto[name] = function(val, force){
if(!this._init || force || this.options[name] !== val){
if(isValue){
this._beforeValue(val);
} else {
this.elemHelper.prop(name, val);
}
val = formatVal[this.type](val, this.options);
if(this.options.splitInput){
$.each(this.splits, function(i, elem){
var setOption;
if(!(name in elem) && !isValue && $.nodeName(elem, 'select')){
$('option[value="'+ val[i] +'"]', elem).prop('defaultSelected', true);
} else {
$.prop(elem, name, val[i]);
}
});
} else {
this.element.prop(name, val);
}
this._propertyChange(name);
this.mirrorValidity();
}
};
});
$.each({min: 1, max: -1}, function(name, factor){
var numName = name +'AsNumber';
spinBtnProto[name] = function(val){
this.elemHelper.prop(name, val);
this[numName] = this.asNumber(val);
if(this.valueAsNumber != null && (isNaN(this.valueAsNumber) || (!isNaN(this[numName]) && (this.valueAsNumber * factor) < (this[numName] * factor)))){
this._setStartInRange();
}
this.options[name] = val;
this._propertyChange(name);
this.mirrorValidity();
};
});
$.fn.wsBaseWidget = function(opts){
opts = $.extend({}, opts);
return this.each(function(){
$.webshims.objectCreate(wsWidgetProto, {
element: {
value: $(this)
}
}, opts);
});
};
$.fn.wsBaseWidget.wsProto = wsWidgetProto;
$.fn.spinbtnUI = function(opts){
opts = $.extend({
monthNames: 'monthNames'
}, opts);
return this.each(function(){
$.webshims.objectCreate(spinBtnProto, {
element: {
value: $(this)
}
}, opts);
});
};
$.fn.spinbtnUI.wsProto = spinBtnProto;
})();
(function(){
var picker = {};
webshims.inlinePopover = {
_create: function(){
this.element = $('<div class="ws-inline-picker"><div class="ws-po-box" /></div>').data('wspopover', this);
this.contentElement = $('.ws-po-box', this.element);
this.element.insertAfter(this.options.prepareFor);
},
show: $.noop,
hide: $.noop,
preventBlur: $.noop,
isVisible: true
};
picker._genericSetFocus = function(element, _noFocus){
element = $(element || this.activeButton);
if(!this.popover.openedByFocus && !_noFocus){
var that = this;
var setFocus = function(noTrigger){
clearTimeout(that.timer);
that.timer = setTimeout(function(){
if(element[0]){
element[0].focus();
if(noTrigger !== true && !element.is(':focus')){
setFocus(true);
}
}
}, that.popover.isVisible ? 99 : 360);
};
this.popover.activateElement(element);
setFocus();
}
};
picker._actions = {
changeInput: function(val, popover, data){
if(!data.options.noChangeDismiss){
picker._actions.cancel(val, popover, data);
}
data.setChange(val);
},
cancel: function(val, popover, data){
if(!data.options.inlinePicker){
popover.stopOpen = true;
data.element.getShadowFocusElement().trigger('focus');
setTimeout(function(){
popover.stopOpen = false;
}, 9);
popover.hide();
}
}
};
picker.commonInit = function(data, popover){
if(data._commonInit){return;}
data._commonInit = true;
var tabbable;
popover.isDirty = true;
popover.element.on('updatepickercontent pickerchange', function(){
tabbable = false;
});
if(!data.options.inlinePicker){
popover.contentElement.on({
keydown: function(e){
if(e.keyCode == 9){
if(!tabbable){
tabbable = $('input:not(:disabled), [tabindex="0"]:not(:disabled)', this).filter(':visible');
}
var index = tabbable.index(e.target);
if(e.shiftKey && index <= 0){
tabbable.last().focus();
return false;
}
if(!e.shiftKey && index >= tabbable.length - 1){
tabbable.first().focus();
return false;
}
} else if(e.keyCode == 27){
data.element.getShadowFocusElement().focus();
popover.hide();
return false;
}
}
});
}
data._propertyChange = (function(){
var timer;
var update = function(){
if(popover.isVisible){
popover.element.triggerHandler('updatepickercontent');
}
};
return function(prop){
if(prop == 'value' && !data.options.inlinePicker){return;}
popover.isDirty = true;
if(popover.isVisible){
clearTimeout(timer);
timer = setTimeout(update, 9);
}
};
})();
popover.activeElement = $([]);
popover.activateElement = function(element){
element = $(element);
if(element[0] != popover.activeElement[0]){
popover.activeElement.removeClass('ws-focus');
element.addClass('ws-focus');
}
popover.activeElement = element;
};
popover.element.on({
wspopoverbeforeshow: function(){
data.element.triggerHandler('wsupdatevalue');
popover.element.triggerHandler('updatepickercontent');
}
});
$(data.orig).on('remove', function(e){
if(!e.originalEvent){
$(document).off('wslocalechange', data._propertyChange);
}
});
};
picker._common = function(data){
var options = data.options;
var popover = webshims.objectCreate(options.inlinePicker ? webshims.inlinePopover : webshims.wsPopover, {}, $.extend(options.popover || {}, {prepareFor: options.inlinePicker ? data.buttonWrapper : data.element}));
var opener = $('<button type="button" class="ws-popover-opener"><span /></button>').appendTo(data.buttonWrapper);
if(options.widgetPosition){
webshims.error('options.widgetPosition was removed use options.popover.position instead');
}
if(options.openOnFocus && popover.options && (popover.options.appendTo == 'auto' || popover.options.appendTo == 'element')){
webshims.error('openOnFocus and popover.appendTo "auto/element" can prduce a11y problems try to change appendTo to body or similiar or use openOnMouseFocus instead');
}
var showPickerContent = function(){
(picker[data.type].showPickerContent || picker.showPickerContent)(data, popover);
};
var show = function(){
var type = loadPicker(data.type, 'DOM');
if(!options.disabled && !options.readonly && (options.inlinePicker || !popover.isVisible)){
webshims.ready(type, showPickerContent);
popover.show(data.element);
}
};
var open = function(){
if((options.inlinePicker || popover.isVisible) && popover.activeElement){
popover.openedByFocus = false;
popover.activeElement.focus();
}
show();
};
options.containerElements.push(popover.element[0]);
popover.element
.addClass(data.type+'-popover input-picker')
.attr({role: 'application'})
.on({
wspopoverhide: function(){
popover.openedByFocus = false;
},
focusin: function(e){
if(popover.activateElement){
popover.openedByFocus = false;
popover.activateElement(e.target);
}
},
focusout: function(){
if(popover.activeElement){
popover.activeElement.removeClass('ws-focus');
}
if(options.inlinePicker){
popover.openedByFocus = true;
}
}
})
;
labelWidth(popover.element.children('div.ws-po-outerbox').attr({role: 'group'}), options.labels, true);
labelWidth(opener, options.labels, true);
if(options.tabindex != null){
opener.attr({tabindex: options.tabindex});
}
if(options.disabled){
opener.prop({disabled: true});
}
opener.on({click: open});
if(options.inlinePicker){
popover.openedByFocus = true;
} else {
opener
.on({
mousedown: function(){
stopPropagation.apply(this, arguments);
popover.preventBlur();
},
focus: function(){
popover.preventBlur();
}
})
;
(function(){
var mouseFocus = false;
var resetMouseFocus = function(){
mouseFocus = false;
};
data.inputElements.on({
keydown: function(e){
if(e.keyCode == 40 && e.altKey && !$.nodeName(e.target, 'select')){
open();
}
},
focus: function(e){
if(!popover.stopOpen && (options.buttonOnly || options.openOnFocus || (mouseFocus && options.openOnMouseFocus)) && !$.nodeName(e.target, 'select')){
popover.openedByFocus = options.buttonOnly ? false : !options.noInput;
show();
} else {
popover.preventBlur();
}
},
mousedown: function(){
mouseFocus = true;
setTimeout(resetMouseFocus, 9);
if(options.buttonOnly && popover.isVisible && popover.activeElement){
popover.openedByFocus = false;
setTimeout(function(){
popover.openedByFocus = false;
popover.activeElement.focus();
}, 4);
}
if(data.element.is(':focus') && !$.nodeName(e.target, 'select')){
popover.openedByFocus = options.buttonOnly ? false : !options.noInput;
show();
}
popover.preventBlur();
}
});
})();
}
data.popover = popover;
data.opener = opener;
$(data.orig).on('remove', function(e){
if(!e.originalEvent){
setTimeout(function(){
opener.remove();
popover.element.remove();
}, 4);
}
});
if(options.inlinePicker){
show();
}
};
picker.month = picker._common;
picker.date = picker._common;
picker.time = picker._common;
picker['datetime-local'] = picker._common;
// picker.week = picker._common;
picker.color = function(data){
var ret = picker._common.apply(this, arguments);
var alpha = $(data.orig).data('alphacontrol');
var colorIndicator = data.opener
.prepend('<span class="ws-color-indicator-bg"><span class="ws-color-indicator" /></span>')
.find('.ws-color-indicator')
;
var showColor = function(){
colorIndicator.css({backgroundColor: $.prop(this, 'value') || '#000000'});
};
var showOpacity = (function(){
var timer;
var show = function(){
try {
var value = data.alpha.prop('valueAsNumber') / (data.alpha.prop('max') || 1);
if(!isNaN(value)){
colorIndicator.css({opacity: value});
}
} catch(er){}
};
return function(e){
clearTimeout(timer);
timer = setTimeout(show, !e || e.type == 'change' ? 4: 40);
};
})();
data.alpha = (alpha) ? $('#'+alpha) : $([]);
$(data.orig).on('wsupdatevalue change', showColor).each(showColor);
data.alpha.on('wsupdatevalue change input', showOpacity).each(showOpacity);
return ret;
};
webshims.picker = picker;
})();
(function(){
var stopCircular, isCheckValidity;
var modernizrInputTypes = Modernizr.inputtypes;
var inputTypes = {
};
var boolAttrs = {disabled: 1, required: 1, readonly: 1};
var copyProps = [
'disabled',
'readonly',
'value',
'defaultValue',
'min',
'max',
'step',
'title',
'required',
'placeholder'
];
//
var copyAttrs = ['data-placeholder', 'tabindex'];
$.each(copyProps.concat(copyAttrs), function(i, name){
var fnName = name.replace(/^data\-/, '');
webshims.onNodeNamesPropertyModify('input', name, function(val, boolVal){
if(!stopCircular){
var shadowData = webshims.data(this, 'shadowData');
if(shadowData && shadowData.data && shadowData.nativeElement === this && shadowData.data[fnName]){
if(boolAttrs[fnName]){
shadowData.data[fnName](val, boolVal);
} else {
shadowData.data[fnName](val);
}
}
}
});
});
if(options.replaceUI && 'valueAsNumber' in document.createElement('input')){
var reflectFn = function(){
if(webshims.data(this, 'hasShadow')){
$.prop(this, 'value', $.prop(this, 'value'));
}
};
webshims.onNodeNamesPropertyModify('input', 'valueAsNumber', reflectFn);
webshims.onNodeNamesPropertyModify('input', 'valueAsDate', reflectFn);
$.each({stepUp: 1, stepDown: -1}, function(name, stepFactor){
var stepDescriptor = webshims.defineNodeNameProperty('input', name, {
prop: {
value: function(){
var ret;
if(stepDescriptor.prop && stepDescriptor.prop._supvalue){
ret = stepDescriptor.prop._supvalue.apply(this, arguments);
reflectFn.apply(this, arguments);
}
return ret;
}
}
});
});
}
var extendType = (function(){
return function(name, data){
inputTypes[name] = data;
data.attrs = $.merge([], copyAttrs, data.attrs);
data.props = $.merge([], copyProps, data.props);
};
})();
var isVisible = function(){
return $.css(this, 'display') != 'none';
};
var sizeInput = function(data){
var init;
var updateStyles = function(){
$(data.orig).removeClass('ws-important-hide');
$.style( data.orig, 'display', '' );
var hasButtons, marginR, marginL;
var correctWidth = 0.8;
if(!init || data.orig.offsetWidth){
hasButtons = data.buttonWrapper && data.buttonWrapper.filter(isVisible).length;
marginR = $.css( data.orig, 'marginRight');
data.element.css({
marginLeft: $.css( data.orig, 'marginLeft'),
marginRight: hasButtons ? 0 : marginR
});
if(hasButtons){
marginL = (parseInt(data.buttonWrapper.css('marginLeft'), 10) || 0);
data.element.css({paddingRight: ''});
if(marginL < 0){
marginR = (parseInt(marginR, 10) || 0) + ((data.buttonWrapper.outerWidth() + marginL) * -1);
data.buttonWrapper.css('marginRight', marginR);
data.element
.css({paddingRight: ''})
.css({
paddingRight: (parseInt( data.element.css('paddingRight'), 10) || 0) + data.buttonWrapper.outerWidth()
})
;
} else {
data.buttonWrapper.css('marginRight', marginR);
correctWidth = data.buttonWrapper.outerWidth(true) + correctWidth;
}
}
data.element.outerWidth( $(data.orig).outerWidth() - correctWidth );
}
init = true;
$(data.orig).addClass('ws-important-hide');
};
data.element.onWSOff('updateshadowdom', updateStyles, true);
};
var implementType = function(){
var type = $.prop(this, 'type');
var i, opts, data, optsName, labels;
if(inputTypes[type] && webshims.implement(this, 'inputwidgets')){
data = {};
optsName = type;
labels = $(this).jProp('labels');
opts = $.extend(webshims.getOptions(this, type, [options.widgets, options[type], $($.prop(this, 'form')).data(type)]), {
orig: this,
type: type,
labels: labels,
options: {},
input: function(val){
opts._change(val, 'input');
},
change: function(val){
opts._change(val, 'change');
},
_change: function(val, trigger){
stopCircular = true;
$.prop(opts.orig, 'value', val);
stopCircular = false;
if(trigger){
$(opts.orig).trigger(trigger);
}
},
containerElements: []
});
for(i = 0; i < copyProps.length; i++){
opts[copyProps[i]] = $.prop(this, copyProps[i]);
}
for(i = 0; i < copyAttrs.length; i++){
optsName = copyAttrs[i].replace(/^data\-/, '');
if(optsName == 'placeholder' || !opts[optsName]){
opts[optsName] = $.attr(this, copyAttrs[i]) || opts[optsName];
}
}
if(opts.onlyMonthDigits || (!opts.formatMonthNames && opts.monthSelect)){
opts.formatMonthNames = 'monthDigits';
}
data.shim = inputTypes[type]._create(opts);
webshims.addShadowDom(this, data.shim.element, {
data: data.shim || {}
});
data.shim.options.containerElements.push(data.shim.element[0]);
labelWidth($(this).getShadowFocusElement(), labels);
$(this).on('change', function(e){
if(!stopCircular){
data.shim.value($.prop(this, 'value'));
}
});
(function(){
var has = {
focusin: true,
focus: true
};
var timer;
var hasFocusTriggered = false;
var hasFocus = false;
$(data.shim.options.containerElements)
.on({
'focusin focus focusout blur': function(e){
e.stopImmediatePropagation();
hasFocus = has[e.type];
clearTimeout(timer);
timer = setTimeout(function(){
if(hasFocus != hasFocusTriggered){
hasFocusTriggered = hasFocus;
$(opts.orig).triggerHandler(hasFocus ? 'focus' : 'blur');
$(opts.orig).trigger(hasFocus ? 'focusin' : 'focusout');
}
hasFocusTriggered = hasFocus;
}, 0);
}
})
;
})();
data.shim.element.on('change input', stopPropagation);
if(hasFormValidation){
$(opts.orig).on('firstinvalid', function(e){
if(!webshims.fromSubmit && isCheckValidity){return;}
$(opts.orig).off('invalid.replacedwidgetbubble').on('invalid.replacedwidgetbubble', function(evt){
if(!evt.isDefaultPrevented()){
webshims.validityAlert.showFor( e.target );
e.preventDefault();
evt.preventDefault();
}
$(opts.orig).off('invalid.replacedwidgetbubble');
});
});
}
if(data.shim.buttonWrapper && data.shim.buttonWrapper.filter(isVisible).length){
data.shim.element.addClass('has-input-buttons');
}
data.shim.element.addClass($.prop(this, 'className'));
if(opts.calculateWidth){
sizeInput(data.shim);
} else {
$(this).addClass('ws-important-hide');
}
}
};
if(hasFormValidation){
['input', 'form'].forEach(function(name){
var desc = webshims.defineNodeNameProperty(name, 'checkValidity', {
prop: {
value: function(){
isCheckValidity = true;
var ret = desc.prop._supvalue.apply(this, arguments);
isCheckValidity = false;
return ret;
}
}
});
});
}
var replace = {};
if(options.replaceUI){
if( $.isPlainObject(options.replaceUI) ){
$.extend(replace, options.replaceUI);
} else {
$.extend(replace, {
'range': 1,
'number': 1,
'time': 1,
'month': 1,
'date': 1,
'color': 1,
'datetime-local': 1
});
}
}
if(modernizrInputTypes.number && navigator.userAgent.indexOf('Touch') == -1 && ((/MSIE 1[0|1]\.\d/.test(navigator.userAgent)) || (/Trident\/7\.0/.test(navigator.userAgent)))){
replace.number = 1;
}
if(!modernizrInputTypes.range || replace.range){
extendType('range', {
_create: function(opts, set){
var data = $('<span />').insertAfter(opts.orig).rangeUI(opts).data('rangeUi');
return data;
}
});
}
['number', 'time', 'month', 'date', 'color', 'datetime-local'].forEach(function(name){
if(!modernizrInputTypes[name] || replace[name]){
extendType(name, {
_create: function(opts, set){
if(opts.monthSelect || opts.daySelect){
opts.splitInput = true;
}
if(opts.splitInput && !splitInputs[name]){
webshims.warn('splitInput not supported for '+ name);
opts.splitInput = false;
}
var markup = opts.splitInput ?
'<span class="ws-'+name+' ws-input ws-inputreplace" role="group"></span>' :
'<input class="ws-'+name+' ws-inputreplace" type="text" />';
var data = $(markup).insertAfter(opts.orig);
if(steps[name]){
data = data.spinbtnUI(opts).data('wsWidget'+name);
} else {
data = data.wsBaseWidget(opts).data('wsWidget'+name);
}
if(webshims.picker && webshims.picker[name]){
webshims.picker[name](data);
}
data.buttonWrapper.addClass('input-button-size-'+(data.buttonWrapper.children().filter(isVisible).length));
return data;
}
});
}
});
var init = function(){
webshims.addReady(function(context, contextElem){
$('input', context)
.add(contextElem.filter('input'))
.each(implementType)
;
});
};
if(formcfg._isLoading){
$(formcfg).one('change', init);
} else {
init();
}
})();
});
|
// Backbone.Marionette, v0.10.2
// Copyright (c)2012 Derick Bailey, Muted Solutions, LLC.
// Distributed under MIT license
// http://github.com/derickbailey/backbone.marionette
Backbone.Marionette = (function(Backbone, _, $){
var Marionette = {};
// EventBinder
// -----------
// The event binder facilitates the binding and unbinding of events
// from objects that extend `Backbone.Events`. It makes
// unbinding events, even with anonymous callback functions,
// easy.
//
// Inspired by [Johnny Oshika](http://stackoverflow.com/questions/7567404/backbone-js-repopulate-or-recreate-the-view/7607853#7607853)
Marionette.EventBinder = function(){
this._eventBindings = [];
};
_.extend(Marionette.EventBinder.prototype, {
// Store the event binding in array so it can be unbound
// easily, at a later point in time.
bindTo: function (obj, eventName, callback, context) {
context = context || this;
obj.on(eventName, callback, context);
var binding = {
obj: obj,
eventName: eventName,
callback: callback,
context: context
};
this._eventBindings.push(binding);
return binding;
},
// Unbind from a single binding object. Binding objects are
// returned from the `bindTo` method call.
unbindFrom: function(binding){
binding.obj.off(binding.eventName, binding.callback, binding.context);
this._eventBindings = _.reject(this._eventBindings, function(bind){return bind === binding;});
},
// Unbind all of the events that we have stored.
unbindAll: function () {
var that = this;
// The `unbindFrom` call removes elements from the array
// while it is being iterated, so clone it first.
var bindings = _.map(this._eventBindings, _.identity);
_.each(bindings, function (binding, index) {
that.unbindFrom(binding);
});
}
});
// Copy the `extend` function used by Backbone's classes
Marionette.EventBinder.extend = Backbone.View.extend;
// Marionette.View
// ---------------
// The core view type that other Marionette views extend from.
Marionette.View = Backbone.View.extend({
constructor: function(){
var eventBinder = new Marionette.EventBinder();
_.extend(this, eventBinder);
Backbone.View.prototype.constructor.apply(this, arguments);
this.bindBackboneEntityTo(this.model, this.modelEvents);
this.bindBackboneEntityTo(this.collection, this.collectionEvents);
this.bindTo(this, "show", this.onShowCalled, this);
},
// Get the template for this view
// instance. You can set a `template` attribute in the view
// definition or pass a `template: "whatever"` parameter in
// to the constructor options.
getTemplate: function(){
var template;
// Get the template from `this.options.template` or
// `this.template`. The `options` takes precedence.
if (this.options && this.options.template){
template = this.options.template;
} else {
template = this.template;
}
return template;
},
// Serialize the model or collection for the view. If a model is
// found, `.toJSON()` is called. If a collection is found, `.toJSON()`
// is also called, but is used to populate an `items` array in the
// resulting data. If both are found, defaults to the model.
// You can override the `serializeData` method in your own view
// definition, to provide custom serialization for your view's data.
serializeData: function(){
var data;
if (this.model) {
data = this.model.toJSON();
}
else if (this.collection) {
data = { items: this.collection.toJSON() };
}
data = this.mixinTemplateHelpers(data);
return data;
},
// Mix in template helper methods. Looks for a
// `templateHelpers` attribute, which can either be an
// object literal, or a function that returns an object
// literal. All methods and attributes from this object
// are copies to the object passed in.
mixinTemplateHelpers: function(target){
target = target || {};
var templateHelpers = this.templateHelpers;
if (_.isFunction(templateHelpers)){
templateHelpers = templateHelpers.call(this);
}
return _.extend(target, templateHelpers);
},
// Configure `triggers` to forward DOM events to view
// events. `triggers: {"click .foo": "do:foo"}`
configureTriggers: function(){
if (!this.triggers) { return; }
var triggers = this.triggers;
var that = this;
var triggerEvents = {};
// Allow `triggers` to be configured as a function
if (_.isFunction(triggers)){ triggers = triggers.call(this); }
// Configure the triggers, prevent default
// action and stop propagation of DOM events
_.each(triggers, function(value, key){
triggerEvents[key] = function(e){
if (e && e.preventDefault){ e.preventDefault(); }
if (e && e.stopPropagation){ e.stopPropagation(); }
that.trigger(value);
};
});
return triggerEvents;
},
// Overriding Backbone.View's delegateEvents specifically
// to handle the `triggers` configuration
delegateEvents: function(events){
events = events || this.events;
if (_.isFunction(events)){ events = events.call(this); }
var combinedEvents = {};
var triggers = this.configureTriggers();
_.extend(combinedEvents, events, triggers);
Backbone.View.prototype.delegateEvents.call(this, combinedEvents);
},
// Internal method, handles the `show` event.
onShowCalled: function(){},
// Default `close` implementation, for removing a view from the
// DOM and unbinding it. Regions will call this method
// for you. You can specify an `onClose` method in your view to
// add custom code that is called after the view is closed.
close: function(){
if (this.beforeClose) { this.beforeClose(); }
this.remove();
if (this.onClose) { this.onClose(); }
this.trigger('close');
this.unbindAll();
this.unbind();
},
// This method binds the elements specified in the "ui" hash inside the view's code with
// the associated jQuery selectors.
bindUIElements: function(){
if (!this.ui) { return; }
var that = this;
if (!this.uiBindings) {
// We want to store the ui hash in uiBindings, since afterwards the values in the ui hash
// will be overridden with jQuery selectors.
this.uiBindings = this.ui;
}
// refreshing the associated selectors since they should point to the newly rendered elements.
this.ui = {};
_.each(_.keys(this.uiBindings), function(key) {
var selector = that.uiBindings[key];
that.ui[key] = that.$(selector);
});
},
// This method is used to bind a backbone "entity" (collection/model) to methods on the view.
bindBackboneEntityTo: function(entity, bindings){
if (!entity || !bindings) { return; }
var view = this;
_.each(bindings, function(methodName, evt){
var method = view[methodName];
if(!method) {
throw new Error("View method '"+ methodName +"' was configured as an event handler, but does not exist.");
}
view.bindTo(entity, evt, method, view);
});
}
});
// Item View
// ---------
// A single item view implementation that contains code for rendering
// with underscore.js templates, serializing the view's model or collection,
// and calling several methods on extended views, such as `onRender`.
Marionette.ItemView = Marionette.View.extend({
constructor: function(){
Marionette.View.prototype.constructor.apply(this, arguments);
if (this.initialEvents){
this.initialEvents();
}
},
// Render the view, defaulting to underscore.js templates.
// You can override this in your view definition to provide
// a very specific rendering for your view. In general, though,
// you should override the `Marionette.Renderer` object to
// change how Marionette renders views.
render: function(){
if (this.beforeRender){ this.beforeRender(); }
this.trigger("before:render", this);
this.trigger("item:before:render", this);
var data = this.serializeData();
var template = this.getTemplate();
var html = Marionette.Renderer.render(template, data);
this.$el.html(html);
this.bindUIElements();
if (this.onRender){ this.onRender(); }
this.trigger("render", this);
this.trigger("item:rendered", this);
return this;
},
// Override the default close event to add a few
// more events that are triggered.
close: function(){
this.trigger('item:before:close');
Marionette.View.prototype.close.apply(this, arguments);
this.trigger('item:closed');
}
});
// Collection View
// ---------------
// A view that iterates over a Backbone.Collection
// and renders an individual ItemView for each model.
Marionette.CollectionView = Marionette.View.extend({
constructor: function(){
Marionette.View.prototype.constructor.apply(this, arguments);
this.initChildViewStorage();
this.initialEvents();
this.onShowCallbacks = new Marionette.Callbacks();
},
// Configured the initial events that the collection view
// binds to. Override this method to prevent the initial
// events, or to add your own initial events.
initialEvents: function(){
if (this.collection){
this.bindTo(this.collection, "add", this.addChildView, this);
this.bindTo(this.collection, "remove", this.removeItemView, this);
this.bindTo(this.collection, "reset", this.render, this);
}
},
// Handle a child item added to the collection
addChildView: function(item, collection, options){
this.closeEmptyView();
var ItemView = this.getItemView(item);
return this.addItemView(item, ItemView, options.index);
},
// Override from `Marionette.View` to guarantee the `onShow` method
// of child views is called.
onShowCalled: function(){
this.onShowCallbacks.run();
},
// Internal method to trigger the before render callbacks
// and events
triggerBeforeRender: function(){
if (this.beforeRender) { this.beforeRender(); }
this.trigger("before:render", this);
this.trigger("collection:before:render", this);
},
// Internal method to trigger the rendered callbacks and
// events
triggerRendered: function(){
if (this.onRender) { this.onRender(); }
this.trigger("render", this);
this.trigger("collection:rendered", this);
},
// Render the collection of items. Override this method to
// provide your own implementation of a render function for
// the collection view.
render: function(){
this.triggerBeforeRender();
this.closeEmptyView();
this.closeChildren();
if (this.collection && this.collection.length > 0) {
this.showCollection();
} else {
this.showEmptyView();
}
this.triggerRendered();
return this;
},
// Internal method to loop through each item in the
// collection view and show it
showCollection: function(){
var that = this;
var ItemView;
this.collection.each(function(item, index){
ItemView = that.getItemView(item);
that.addItemView(item, ItemView, index);
});
},
// Internal method to show an empty view in place of
// a collection of item views, when the collection is
// empty
showEmptyView: function(){
var EmptyView = this.options.emptyView || this.emptyView;
if (EmptyView && !this._showingEmptyView){
this._showingEmptyView = true;
var model = new Backbone.Model();
this.addItemView(model, EmptyView, 0);
}
},
// Internal method to close an existing emptyView instance
// if one exists. Called when a collection view has been
// rendered empty, and then an item is added to the collection.
closeEmptyView: function(){
if (this._showingEmptyView){
this.closeChildren();
delete this._showingEmptyView;
}
},
// Retrieve the itemView type, either from `this.options.itemView`
// or from the `itemView` in the object definition. The "options"
// takes precedence.
getItemView: function(item){
var itemView = this.options.itemView || this.itemView;
if (!itemView){
var err = new Error("An `itemView` must be specified");
err.name = "NoItemViewError";
throw err;
}
return itemView;
},
// Render the child item's view and add it to the
// HTML for the collection view.
addItemView: function(item, ItemView, index){
var that = this;
var view = this.buildItemView(item, ItemView);
// Store the child view itself so we can properly
// remove and/or close it later
this.storeChild(view);
if (this.onItemAdded){ this.onItemAdded(view); }
this.trigger("item:added", view);
// Render it and show it
var renderResult = this.renderItemView(view, index);
// call onShow for child item views
if (view.onShow){
this.onShowCallbacks.add(view.onShow, view);
}
// Forward all child item view events through the parent,
// prepending "itemview:" to the event name
var childBinding = this.bindTo(view, "all", function(){
var args = slice.call(arguments);
args[0] = "itemview:" + args[0];
args.splice(1, 0, view);
that.trigger.apply(that, args);
});
// Store all child event bindings so we can unbind
// them when removing / closing the child view
this.childBindings = this.childBindings || {};
this.childBindings[view.cid] = childBinding;
return renderResult;
},
// render the item view
renderItemView: function(view, index) {
view.render();
this.appendHtml(this, view, index);
},
// Build an `itemView` for every model in the collection.
buildItemView: function(item, ItemView){
var itemViewOptions;
if (_.isFunction(this.itemViewOptions)){
itemViewOptions = this.itemViewOptions(item);
} else {
itemViewOptions = this.itemViewOptions;
}
var options = _.extend({model: item}, itemViewOptions);
var view = new ItemView(options);
return view;
},
// Remove the child view and close it
removeItemView: function(item){
var view = this.children[item.cid];
if (view){
var childBinding = this.childBindings[view.cid];
if (childBinding) {
this.unbindFrom(childBinding);
delete this.childBindings[view.cid];
}
view.close();
delete this.children[item.cid];
}
if (!this.collection || this.collection.length === 0){
this.showEmptyView();
}
this.trigger("item:removed", view);
},
// Append the HTML to the collection's `el`.
// Override this method to do something other
// then `.append`.
appendHtml: function(collectionView, itemView, index){
collectionView.$el.append(itemView.el);
},
// Store references to all of the child `itemView`
// instances so they can be managed and cleaned up, later.
storeChild: function(view){
this.children[view.model.cid] = view;
},
// Internal method to set up the `children` object for
// storing all of the child views
initChildViewStorage: function(){
this.children = {};
},
// Handle cleanup and other closing needs for
// the collection of views.
close: function(){
this.trigger("collection:before:close");
this.closeChildren();
this.trigger("collection:closed");
Marionette.View.prototype.close.apply(this, arguments);
},
// Close the child views that this collection view
// is holding on to, if any
closeChildren: function(){
var that = this;
if (this.children){
_.each(_.clone(this.children), function(childView){
that.removeItemView(childView.model);
});
}
}
});
// Composite View
// --------------
// Used for rendering a branch-leaf, hierarchical structure.
// Extends directly from CollectionView and also renders an
// an item view as `modelView`, for the top leaf
Marionette.CompositeView = Marionette.CollectionView.extend({
constructor: function(options){
Marionette.CollectionView.apply(this, arguments);
this.itemView = this.getItemView();
},
// Configured the initial events that the composite view
// binds to. Override this method to prevent the initial
// events, or to add your own initial events.
initialEvents: function(){
if (this.collection){
this.bindTo(this.collection, "add", this.addChildView, this);
this.bindTo(this.collection, "remove", this.removeItemView, this);
this.bindTo(this.collection, "reset", this.renderCollection, this);
}
},
// Retrieve the `itemView` to be used when rendering each of
// the items in the collection. The default is to return
// `this.itemView` or Marionette.CompositeView if no `itemView`
// has been defined
getItemView: function(item){
var itemView = this.options.itemView || this.itemView || this.constructor;
if (!itemView){
var err = new Error("An `itemView` must be specified");
err.name = "NoItemViewError";
throw err;
}
return itemView;
},
// Renders the model once, and the collection once. Calling
// this again will tell the model's view to re-render itself
// but the collection will not re-render.
render: function(){
var that = this;
this.resetItemViewContainer();
var html = this.renderModel();
this.$el.html(html);
// the ui bindings is done here and not at the end of render since they should be
// available before the collection is rendered.
this.bindUIElements();
this.trigger("composite:model:rendered");
this.trigger("render");
this.renderCollection();
this.trigger("composite:rendered");
return this;
},
// Render the collection for the composite view
renderCollection: function(){
Marionette.CollectionView.prototype.render.apply(this, arguments);
this.trigger("composite:collection:rendered");
},
// Render an individual model, if we have one, as
// part of a composite view (branch / leaf). For example:
// a treeview.
renderModel: function(){
var data = {};
data = this.serializeData();
var template = this.getTemplate();
return Marionette.Renderer.render(template, data);
},
// Appends the `el` of itemView instances to the specified
// `itemViewContainer` (a jQuery selector). Override this method to
// provide custom logic of how the child item view instances have their
// HTML appended to the composite view instance.
appendHtml: function(cv, iv){
var $container = this.getItemViewContainer(cv);
$container.append(iv.el);
},
// Internal method to ensure an `$itemViewContainer` exists, for the
// `appendHtml` method to use.
getItemViewContainer: function(containerView){
var container;
if ("$itemViewContainer" in containerView){
container = containerView.$itemViewContainer;
} else {
if (containerView.itemViewContainer){
container = containerView.$(_.result(containerView, "itemViewContainer"));
if (container.length <= 0) {
var err = new Error("Missing `itemViewContainer`");
err.name = "ItemViewContainerMissingError";
throw err;
}
} else {
container = containerView.$el;
}
containerView.$itemViewContainer = container;
}
return container;
},
// Internal method to reset the `$itemViewContainer` on render
resetItemViewContainer: function(){
if (this.$itemViewContainer){
delete this.$itemViewContainer;
}
}
});
// Region
// ------
// Manage the visual regions of your composite application. See
// http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/
Marionette.Region = function(options){
this.options = options || {};
var eventBinder = new Marionette.EventBinder();
_.extend(this, eventBinder, options);
if (!this.el){
var err = new Error("An 'el' must be specified");
err.name = "NoElError";
throw err;
}
if (this.initialize){
this.initialize.apply(this, arguments);
}
};
_.extend(Marionette.Region.prototype, Backbone.Events, {
// Displays a backbone view instance inside of the region.
// Handles calling the `render` method for you. Reads content
// directly from the `el` attribute. Also calls an optional
// `onShow` and `close` method on your view, just after showing
// or just before closing the view, respectively.
show: function(view){
this.ensureEl();
this.close();
view.render();
this.open(view);
if (view.onShow) { view.onShow(); }
view.trigger("show");
if (this.onShow) { this.onShow(view); }
this.trigger("view:show", view);
this.currentView = view;
},
ensureEl: function(){
if (!this.$el || this.$el.length === 0){
this.$el = this.getEl(this.el);
}
},
// Override this method to change how the region finds the
// DOM element that it manages. Return a jQuery selector object.
getEl: function(selector){
return $(selector);
},
// Override this method to change how the new view is
// appended to the `$el` that the region is managing
open: function(view){
this.$el.html(view.el);
},
// Close the current view, if there is one. If there is no
// current view, it does nothing and returns immediately.
close: function(){
var view = this.currentView;
if (!view){ return; }
if (view.close) { view.close(); }
this.trigger("view:closed", view);
delete this.currentView;
},
// Attach an existing view to the region. This
// will not call `render` or `onShow` for the new view,
// and will not replace the current HTML for the `el`
// of the region.
attachView: function(view){
this.currentView = view;
},
// Reset the region by closing any existing view and
// clearing out the cached `$el`. The next time a view
// is shown via this region, the region will re-query the
// DOM for the region's `el`.
reset: function(){
this.close();
delete this.$el;
}
});
// Copy the `extend` function used by Backbone's classes
Marionette.Region.extend = Backbone.View.extend;
// Layout
// ------
// Used for managing application layouts, nested layouts and
// multiple regions within an application or sub-application.
//
// A specialized view type that renders an area of HTML and then
// attaches `Region` instances to the specified `regions`.
// Used for composite view management and sub-application areas.
Marionette.Layout = Marionette.ItemView.extend({
regionType: Marionette.Region,
// Ensure the regions are avialable when the `initialize` method
// is called.
constructor: function () {
this.initializeRegions();
Backbone.Marionette.ItemView.apply(this, arguments);
},
// Layout's render will use the existing region objects the
// first time it is called. Subsequent calls will close the
// views that the regions are showing and then reset the `el`
// for the regions to the newly rendered DOM elements.
render: function(){
// If this is not the first render call, then we need to
// re-initializing the `el` for each region
if (!this._firstRender){
this.closeRegions();
this.reInitializeRegions();
} else {
this._firstRender = false;
}
var result = Marionette.ItemView.prototype.render.apply(this, arguments);
return result;
},
// Handle closing regions, and then close the view itself.
close: function () {
this.closeRegions();
this.destroyRegions();
Backbone.Marionette.ItemView.prototype.close.call(this, arguments);
},
// Initialize the regions that have been defined in a
// `regions` attribute on this layout. The key of the
// hash becomes an attribute on the layout object directly.
// For example: `regions: { menu: ".menu-container" }`
// will product a `layout.menu` object which is a region
// that controls the `.menu-container` DOM element.
initializeRegions: function () {
if (!this.regionManagers){
this.regionManagers = {};
}
var that = this;
_.each(this.regions, function (region, name) {
var regionIsString = (typeof region === "string");
var regionSelectorIsString = (typeof region.selector === "string");
var regionTypeIsUndefined = (typeof region.regionType === "undefined");
if (!regionIsString && !regionSelectorIsString) {
throw new Error("Region must be specified as a selector string or an object with selector property");
}
var selector, RegionType;
if (regionIsString) {
selector = region;
} else {
selector = region.selector;
}
if (regionTypeIsUndefined){
RegionType = that.regionType;
} else {
RegionType = region.regionType;
}
var regionManager = new RegionType({
el: selector,
getEl: function(selector){
return that.$(selector);
}
});
that.regionManagers[name] = regionManager;
that[name] = regionManager;
});
},
// Re-initialize all of the regions by updating the `el` that
// they point to
reInitializeRegions: function(){
if (this.regionManagers && _.size(this.regionManagers)===0){
this.initializeRegions();
} else {
_.each(this.regionManagers, function(region){
region.reset();
});
}
},
// Close all of the regions that have been opened by
// this layout. This method is called when the layout
// itself is closed.
closeRegions: function () {
var that = this;
_.each(this.regionManagers, function (manager, name) {
manager.close();
});
},
// Destroys all of the regions by removing references
// from the Layout
destroyRegions: function(){
var that = this;
_.each(this.regionManagers, function (manager, name) {
delete that[name];
});
this.regionManagers = {};
}
});
// Application
// -----------
// Contain and manage the composite application as a whole.
// Stores and starts up `Region` objects, includes an
// event aggregator as `app.vent`
Marionette.Application = function(options){
this.initCallbacks = new Marionette.Callbacks();
this.vent = new Marionette.EventAggregator();
this.submodules = {};
var eventBinder = new Marionette.EventBinder();
_.extend(this, eventBinder, options);
};
_.extend(Marionette.Application.prototype, Backbone.Events, {
// Add an initializer that is either run at when the `start`
// method is called, or run immediately if added after `start`
// has already been called.
addInitializer: function(initializer){
this.initCallbacks.add(initializer);
},
// kick off all of the application's processes.
// initializes all of the regions that have been added
// to the app, and runs all of the initializer functions
start: function(options){
this.trigger("initialize:before", options);
this.initCallbacks.run(options, this);
this.trigger("initialize:after", options);
this.trigger("start", options);
},
// Add regions to your app.
// Accepts a hash of named strings or Region objects
// addRegions({something: "#someRegion"})
// addRegions{{something: Region.extend({el: "#someRegion"}) });
addRegions: function(regions){
var RegionValue, regionObj, region;
for(region in regions){
if (regions.hasOwnProperty(region)){
RegionValue = regions[region];
if (typeof RegionValue === "string"){
regionObj = new Marionette.Region({
el: RegionValue
});
} else {
regionObj = new RegionValue();
}
this[region] = regionObj;
}
}
},
// Removes a region from your app.
// Accepts the regions name
// removeRegion('myRegion')
removeRegion: function(region) {
this[region].close();
delete this[region];
},
// Create a module, attached to the application
module: function(moduleNames, moduleDefinition){
// slice the args, and add this application object as the
// first argument of the array
var args = slice.call(arguments);
args.unshift(this);
// see the Marionette.Module object for more information
return Marionette.Module.create.apply(Marionette.Module, args);
}
});
// Copy the `extend` function used by Backbone's classes
Marionette.Application.extend = Backbone.View.extend;
// AppRouter
// ---------
// Reduce the boilerplate code of handling route events
// and then calling a single method on another object.
// Have your routers configured to call the method on
// your object, directly.
//
// Configure an AppRouter with `appRoutes`.
//
// App routers can only take one `controller` object.
// It is recommended that you divide your controller
// objects in to smaller peices of related functionality
// and have multiple routers / controllers, instead of
// just one giant router and controller.
//
// You can also add standard routes to an AppRouter.
Marionette.AppRouter = Backbone.Router.extend({
constructor: function(options){
Backbone.Router.prototype.constructor.call(this, options);
if (this.appRoutes){
var controller = this.controller;
if (options && options.controller) {
controller = options.controller;
}
this.processAppRoutes(controller, this.appRoutes);
}
},
// Internal method to process the `appRoutes` for the
// router, and turn them in to routes that trigger the
// specified method on the specified `controller`.
processAppRoutes: function(controller, appRoutes){
var method, methodName;
var route, routesLength, i;
var routes = [];
var router = this;
for(route in appRoutes){
if (appRoutes.hasOwnProperty(route)){
routes.unshift([route, appRoutes[route]]);
}
}
routesLength = routes.length;
for (i = 0; i < routesLength; i++){
route = routes[i][0];
methodName = routes[i][1];
method = controller[methodName];
if (!method){
var msg = "Method '" + methodName + "' was not found on the controller";
var err = new Error(msg);
err.name = "NoMethodError";
throw err;
}
method = _.bind(method, controller);
router.route(route, methodName, method);
}
}
});
// Module
// ------
// A simple module system, used to create privacy and encapsulation in
// Marionette applications
Marionette.Module = function(moduleName, app, customArgs){
this.moduleName = moduleName;
// store sub-modules
this.submodules = {};
this._setupInitializersAndFinalizers();
// store the configuration for this module
this.config = {};
this.config.app = app;
this.config.customArgs = customArgs;
this.config.definitions = [];
// extend this module with an event binder
var eventBinder = new Marionette.EventBinder();
_.extend(this, eventBinder);
};
// Extend the Module prototype with events / bindTo, so that the module
// can be used as an event aggregator or pub/sub.
_.extend(Marionette.Module.prototype, Backbone.Events, {
// Initializer for a specific module. Initializers are run when the
// module's `start` method is called.
addInitializer: function(callback){
this._initializerCallbacks.add(callback);
},
// Finalizers are run when a module is stopped. They are used to teardown
// and finalize any variables, references, events and other code that the
// module had set up.
addFinalizer: function(callback){
this._finalizerCallbacks.add(callback);
},
// Start the module, and run all of it's initializers
start: function(options){
// Prevent re-start the module
if (this._isInitialized){ return; }
// start the sub-modules (depth-first hierarchy)
_.each(this.submodules, function(mod){
if (mod.config.options.startWithParent){
mod.start(options);
}
});
// run the callbacks to "start" the current module
this._initializerCallbacks.run(options, this);
this._isInitialized = true;
},
// Stop this module by running its finalizers and then stop all of
// the sub-modules for this module
stop: function(){
// if we are not initialized, don't bother finalizing
if (!this._isInitialized){ return; }
this._isInitialized = false;
// stop the sub-modules; depth-first, to make sure the
// sub-modules are stopped / finalized before parents
_.each(this.submodules, function(mod){ mod.stop(); });
// run the finalizers
this._finalizerCallbacks.run();
// reset the initializers and finalizers
this._initializerCallbacks.reset();
this._finalizerCallbacks.reset();
},
// Configure the module with a definition function and any custom args
// that are to be passed in to the definition function
addDefinition: function(moduleDefinition){
this._runModuleDefinition(moduleDefinition);
},
// Internal method: run the module definition function with the correct
// arguments
_runModuleDefinition: function(definition){
if (!definition){ return; }
// build the correct list of arguments for the module definition
var args = _.flatten([
this,
this.config.app,
Backbone,
Marionette,
$, _,
this.config.customArgs
]);
definition.apply(this, args);
},
// Internal method: set up new copies of initializers and finalizers.
// Calling this method will wipe out all existing initializers and
// finalizers.
_setupInitializersAndFinalizers: function(){
this._initializerCallbacks = new Marionette.Callbacks();
this._finalizerCallbacks = new Marionette.Callbacks();
}
});
// Function level methods to create modules
_.extend(Marionette.Module, {
// Create a module, hanging off the app parameter as the parent object.
create: function(app, moduleNames, moduleDefinition){
var that = this;
var parentModule = app;
moduleNames = moduleNames.split(".");
// get the custom args passed in after the module definition and
// get rid of the module name and definition function
var customArgs = slice.apply(arguments);
customArgs.splice(0, 3);
// Loop through all the parts of the module definition
var length = moduleNames.length;
_.each(moduleNames, function(moduleName, i){
var isLastModuleInChain = (i === length-1);
var module = that._getModuleDefinition(parentModule, moduleName, app, customArgs);
module.config.options = that._getModuleOptions(parentModule, moduleDefinition);
// if it's the first module in the chain, configure it
// for auto-start, as specified by the options
if (isLastModuleInChain){
that._configureAutoStart(app, module);
}
// Only add a module definition and initializer when this is
// the last module in a "parent.child.grandchild" hierarchy of
// module names
if (isLastModuleInChain && module.config.options.hasDefinition){
module.addDefinition(module.config.options.definition);
}
// Reset the parent module so that the next child
// in the list will be added to the correct parent
parentModule = module;
});
// Return the last module in the definition chain
return parentModule;
},
_configureAutoStart: function(app, module){
// Only add the initializer if it's the first module, and
// if it is set to auto-start, and if it has not yet been added
if (module.config.options.startWithParent && !module.config.autoStartConfigured){
// start the module when the app starts
app.addInitializer(function(options){
module.start(options);
});
}
// prevent this module from being configured for
// auto start again. the first time the module
// is defined, determines it's auto-start
module.config.autoStartConfigured = true;
},
_getModuleDefinition: function(parentModule, moduleName, app, customArgs){
// Get an existing module of this name if we have one
var module = parentModule[moduleName];
if (!module){
// Create a new module if we don't have one
module = new Marionette.Module(moduleName, app, customArgs);
parentModule[moduleName] = module;
// store the module on the parent
parentModule.submodules[moduleName] = module;
}
return module;
},
_getModuleOptions: function(parentModule, moduleDefinition){
// default to starting the module with the app
var options = {
startWithParent: true,
hasDefinition: !!moduleDefinition
};
// short circuit if we don't have a module definition
if (!options.hasDefinition){ return options; }
if (_.isFunction(moduleDefinition)){
// if the definition is a function, assign it directly
// and use the defaults
options.definition = moduleDefinition;
} else {
// the definition is an object.
// grab the "define" attribute
options.hasDefinition = !!moduleDefinition.define;
options.definition = moduleDefinition.define;
// grab the "startWithParent" attribute if one exists
if (moduleDefinition.hasOwnProperty("startWithParent")){
options.startWithParent = moduleDefinition.startWithParent;
}
}
return options;
}
});
// Template Cache
// --------------
// Manage templates stored in `<script>` blocks,
// caching them for faster access.
Marionette.TemplateCache = function(templateId){
this.templateId = templateId;
};
// TemplateCache object-level methods. Manage the template
// caches from these method calls instead of creating
// your own TemplateCache instances
_.extend(Marionette.TemplateCache, {
templateCaches: {},
// Get the specified template by id. Either
// retrieves the cached version, or loads it
// from the DOM.
get: function(templateId){
var that = this;
var cachedTemplate = this.templateCaches[templateId];
if (!cachedTemplate){
cachedTemplate = new Marionette.TemplateCache(templateId);
this.templateCaches[templateId] = cachedTemplate;
}
return cachedTemplate.load();
},
// Clear templates from the cache. If no arguments
// are specified, clears all templates:
// `clear()`
//
// If arguments are specified, clears each of the
// specified templates from the cache:
// `clear("#t1", "#t2", "...")`
clear: function(){
var i;
var length = arguments.length;
if (length > 0){
for(i=0; i<length; i++){
delete this.templateCaches[arguments[i]];
}
} else {
this.templateCaches = {};
}
}
});
// TemplateCache instance methods, allowing each
// template cache object to manage it's own state
// and know whether or not it has been loaded
_.extend(Marionette.TemplateCache.prototype, {
// Internal method to load the template asynchronously.
load: function(){
var that = this;
// Guard clause to prevent loading this template more than once
if (this.compiledTemplate){
return this.compiledTemplate;
}
// Load the template and compile it
var template = this.loadTemplate(this.templateId);
this.compiledTemplate = this.compileTemplate(template);
return this.compiledTemplate;
},
// Load a template from the DOM, by default. Override
// this method to provide your own template retrieval,
// such as asynchronous loading from a server.
loadTemplate: function(templateId){
var template = $(templateId).html();
if (!template || template.length === 0){
var msg = "Could not find template: '" + templateId + "'";
var err = new Error(msg);
err.name = "NoTemplateError";
throw err;
}
return template;
},
// Pre-compile the template before caching it. Override
// this method if you do not need to pre-compile a template
// (JST / RequireJS for example) or if you want to change
// the template engine used (Handebars, etc).
compileTemplate: function(rawTemplate){
return _.template(rawTemplate);
}
});
// Renderer
// --------
// Render a template with data by passing in the template
// selector and the data to render.
Marionette.Renderer = {
// Render a template with data. The `template` parameter is
// passed to the `TemplateCache` object to retrieve the
// template function. Override this method to provide your own
// custom rendering and template handling for all of Marionette.
render: function(template, data){
var templateFunc = typeof template === 'function' ? template : Marionette.TemplateCache.get(template);
var html = templateFunc(data);
return html;
}
};
// Callbacks
// ---------
// A simple way of managing a collection of callbacks
// and executing them at a later point in time, using jQuery's
// `Deferred` object.
Marionette.Callbacks = function(){
this._deferred = $.Deferred();
this._callbacks = [];
};
_.extend(Marionette.Callbacks.prototype, {
// Add a callback to be executed. Callbacks added here are
// guaranteed to execute, even if they are added after the
// `run` method is called.
add: function(callback, contextOverride){
this._callbacks.push({cb: callback, ctx: contextOverride});
this._deferred.done(function(context, options){
if (contextOverride){ context = contextOverride; }
callback.call(context, options);
});
},
// Run all registered callbacks with the context specified.
// Additional callbacks can be added after this has been run
// and they will still be executed.
run: function(options, context){
this._deferred.resolve(context, options);
},
// Resets the list of callbacks to be run, allowing the same list
// to be run multiple times - whenever the `run` method is called.
reset: function(){
var that = this;
var callbacks = this._callbacks;
this._deferred = $.Deferred();
this._callbacks = [];
_.each(callbacks, function(cb){
that.add(cb.cb, cb.ctx);
});
}
});
// Event Aggregator
// ----------------
// A pub-sub object that can be used to decouple various parts
// of an application through event-driven architecture.
Marionette.EventAggregator = Marionette.EventBinder.extend({
// Extend any provided options directly on to the event binder
constructor: function(options){
Marionette.EventBinder.apply(this, arguments);
_.extend(this, options);
},
// Override the `bindTo` method to ensure that the event aggregator
// is used as the event binding storage
bindTo: function(eventName, callback, context){
return Marionette.EventBinder.prototype.bindTo.call(this, this, eventName, callback, context);
}
});
// Copy the basic Backbone.Events on to the event aggregator
_.extend(Marionette.EventAggregator.prototype, Backbone.Events);
// Copy the `extend` function used by Backbone's classes
Marionette.EventAggregator.extend = Backbone.View.extend;
// Helpers
// -------
// For slicing `arguments` in functions
var slice = Array.prototype.slice;
return Marionette;
})(Backbone, _, window.jQuery || window.Zepto || window.ender); |
/*!
* jBone v0.0.8 - 2013-11-13 - Library for DOM manipulation
*
* https://github.com/kupriyanenko/jbone
*
* Copyright 2013 Alexey Kupriyanenko
* Released under the MIT license.
*/
(function(exports, global) {
global["true"] = exports;
var rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
var rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;
function jBone(element, data) {
if (this instanceof jBone) {
return init.call(this, element, data);
} else {
return new jBone(element, data);
}
}
function init(element, data) {
var elements;
if (element instanceof jBone) {
return element;
} else if (Array.isArray(element)) {
elements = element.map(function(el) {
return getElement(el, data);
});
} else if (element) {
elements = getElement(element, data);
}
elements = Array.isArray(elements) ? elements : [ elements ];
jBone.merge(this, elements);
if (data) {
this.attr(data);
}
return this;
}
function getElement(element) {
var tag, wraper;
if (typeof element === "string" && (tag = rsingleTag.exec(element))) {
return document.createElement(tag[1]);
} else if (typeof element === "string" && (tag = rquickExpr.exec(element)) && tag[1]) {
wraper = document.createElement("div");
wraper.innerHTML = element;
return [].slice.call(wraper.childNodes);
} else if (typeof element === "string") {
return [].slice.call(document.querySelectorAll(element));
}
return element;
}
jBone.setId = function(el) {
var jid = el.jid || undefined;
if (el === window) {
jid = "window";
} else if (!el.jid) {
jid = ++jBone._cache.jid;
el.jid = jid;
}
if (!jBone._cache.events[jid]) {
jBone._cache.events[jid] = {};
}
};
jBone.getData = function(el) {
el = el instanceof jBone ? el[0] : el;
var jid = el === window ? "window" : el.jid;
return {
jid: jid,
events: jBone._cache.events[jid]
};
};
jBone.merge = function(first, second) {
var l = second.length, i = first.length, j = 0;
if (typeof l === "number") {
while (j < l) {
first[i++] = second[j];
j++;
}
} else {
while (second[j] !== undefined) {
first[i++] = second[j++];
}
}
first.length = i;
return first;
};
jBone._cache = {
events: {},
jid: 0
};
jBone.fn = jBone.prototype = [];
window.jBone = window.$ = jBone;
jBone.fn.on = function() {
var event = arguments[0], callback, target, namespace, fn, events;
if (arguments.length === 2) {
callback = arguments[1];
} else {
target = arguments[1], callback = arguments[2];
}
this.forEach(function(el) {
jBone.setId(el);
events = jBone.getData(el).events;
event.split(" ").forEach(function(event) {
namespace = event.split(".")[1];
event = event.split(".")[0];
events[event] = events[event] ? events[event] : [];
fn = function(e) {
if (e.namespace && e.namespace !== namespace) {
return;
}
if (!target) {
callback.call(el, e);
} else {
if (~jBone(el).find(target).indexOf(e.target)) {
callback.call(el, e);
}
}
};
events[event].push({
namespace: namespace,
fn: fn,
originfn: callback
});
if (el.addEventListener) {
el.addEventListener(event, fn, false);
}
});
});
return this;
};
jBone.fn.one = function() {
var event = arguments[0], callback, target;
if (arguments.length === 2) {
callback = arguments[1];
} else {
target = arguments[1], callback = arguments[2];
}
this.forEach(function(el) {
event.split(" ").forEach(function(event) {
var fn = function(e) {
callback.call(el, e);
jBone(el).off(event, fn);
};
if (arguments.length === 2) {
jBone(el).on(event, fn);
} else {
jBone(el).on(event, target, fn);
}
});
});
return this;
};
jBone.fn.trigger = function(eventName) {
if (!eventName || !eventName.split(".")[0]) {
return this;
}
var namespace, event;
this.forEach(function(el) {
eventName.split(" ").forEach(function(eventName) {
namespace = eventName.split(".")[1];
eventName = eventName.split(".")[0];
if ("CustomEvent" in window) {
event = document.createEvent("CustomEvent");
event.initCustomEvent(eventName, true, true, null);
} else {
event = document.createEvent("Event");
event.initEvent(eventName, true, true);
}
event.namespace = namespace;
if (el.dispatchEvent) {
el.dispatchEvent(event);
}
});
});
return this;
};
jBone.fn.off = function(event, fn) {
var events, callback, namespace, getCallback = function(e) {
if (fn && e.originfn === fn) {
return e.fn;
} else if (!fn) {
return e.fn;
}
};
this.forEach(function(el) {
events = jBone.getData(el).events;
event.split(" ").forEach(function(event) {
namespace = event.split(".")[1];
event = event.split(".")[0];
if (events && events[event]) {
events[event].forEach(function(e) {
callback = getCallback(e);
if (namespace) {
if (e.namespace === namespace) {
el.removeEventListener(event, callback);
}
} else if (!namespace) {
el.removeEventListener(event, callback);
}
});
} else if (namespace) {
Object.keys(events).forEach(function(key) {
events[key].forEach(function(e) {
callback = getCallback(e);
if (e.namespace === namespace) {
el.removeEventListener(key, callback);
}
});
});
}
});
});
return this;
};
jBone.fn.is = function() {
var args = arguments;
return this.some(function(el) {
return el.tagName.toLowerCase() === args[0];
});
};
jBone.fn.has = function() {
var args = arguments;
return this.some(function(el) {
return el.querySelectorAll(args[0]).length;
});
};
jBone.fn.attr = function() {
var args = arguments;
if (typeof args[0] === "string" && args.length === 1) {
return this[0].getAttribute(args[0]);
} else if (typeof args[0] === "string" && args.length > 1) {
this.forEach(function(el) {
el.setAttribute(args[0], args[1]);
});
} else if (args[0] instanceof Object) {
this.forEach(function(el) {
Object.keys(args[0]).forEach(function(key) {
el.setAttribute(key, args[0][key]);
});
});
}
return this;
};
jBone.fn.val = function(value) {
if (typeof value === "string") {
this.forEach(function(el) {
el.value = value;
});
} else {
return this[0].value;
}
return this;
};
jBone.fn.css = function() {
var args = arguments;
if (typeof args[0] === "string" && args.length === 2) {
this.forEach(function(el) {
el.style[args[0]] = args[1];
});
} else if (args[0] instanceof Object) {
this.forEach(function(el) {
Object.keys(args[0]).forEach(function(key) {
el.style[key] = args[0][key];
});
});
}
return this;
};
jBone.fn.find = function(selector) {
var results = [];
this.forEach(function(el) {
[].forEach.call(el.querySelectorAll(selector), function(finded) {
results.push(finded);
});
});
return jBone(results);
};
jBone.fn.get = function(index) {
return this[index];
};
jBone.fn.eq = function(index) {
return jBone(this[index]);
};
jBone.fn.html = function() {
var value = arguments[0], result;
if (value !== undefined) {
this.empty.call(this);
this.append.call(this, value);
return this;
} else {
result = [];
this.forEach(function(el) {
if (el instanceof HTMLElement) {
result.push(el.innerHTML);
}
});
return result.length ? result.join("") : null;
}
};
jBone.fn.append = function(appended) {
if (typeof appended === "string") {
appended = jBone(appended);
}
if (appended instanceof jBone) {
this.forEach(function(el, i) {
appended.forEach(function(jel) {
if (!i) {
el.appendChild(jel);
} else {
el.appendChild(jel.cloneNode());
}
});
});
} else if (appended instanceof HTMLElement || appended instanceof DocumentFragment) {
this.forEach(function(el) {
el.appendChild(appended);
});
}
return this;
};
jBone.fn.appendTo = function(to) {
jBone(to).append(this);
return this;
};
jBone.fn.empty = function() {
this.forEach(function(el) {
while (el.hasChildNodes()) {
el.removeChild(el.lastChild);
}
});
return this;
};
jBone.fn.remove = function() {
this.forEach(function(el) {
if (el.parentNode) {
el.parentNode.removeChild(el);
}
});
return this;
};
})({}, function() {
return this;
}()); |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'wsc', 'th', {
btnIgnore: 'ยกเว้น',
btnIgnoreAll: 'ยกเว้นทั้งหมด',
btnReplace: 'แทนที่',
btnReplaceAll: 'แทนที่ทั้งหมด',
btnUndo: 'ยกเลิก',
changeTo: 'แก้ไขเป็น',
errorLoading: 'Error loading application service host: %s.',
ieSpellDownload: 'ไม่ได้ติดตั้งระบบตรวจสอบคำสะกด. ต้องการติดตั้งไหมครับ?',
manyChanges: 'ตรวจสอบคำสะกดเสร็จสิ้น:: แก้ไข %1 คำ',
noChanges: 'ตรวจสอบคำสะกดเสร็จสิ้น: ไม่มีการแก้คำใดๆ',
noMispell: 'ตรวจสอบคำสะกดเสร็จสิ้น: ไม่พบคำสะกดผิด',
noSuggestions: '- ไม่มีคำแนะนำใดๆ -',
notAvailable: 'Sorry, but service is unavailable now.',
notInDic: 'ไม่พบในดิกชันนารี',
oneChange: 'ตรวจสอบคำสะกดเสร็จสิ้น: แก้ไข1คำ',
progress: 'กำลังตรวจสอบคำสะกด...',
title: 'Spell Checker',
toolbar: 'ตรวจการสะกดคำ'
});
|
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Strana';
$.fn.pagination.defaults.afterPageText = 'z {pages}';
$.fn.pagination.defaults.displayMsg = 'Zobrazuji {from} do {to} z {total} položky';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'Zpracování, čekejte prosím ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Ok';
$.messager.defaults.cancel = 'Zrušit';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'Toto pole je vyžadováno.';
$.fn.validatebox.defaults.rules.email.message = 'Zadejte prosím platnou e-mailovou adresu.';
$.fn.validatebox.defaults.rules.url.message = 'Zadejte prosím platnou adresu URL.';
$.fn.validatebox.defaults.rules.length.message = 'Prosím, zadejte hodnotu mezi {0} a {1}.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'Toto pole je vyžadováno.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'Toto pole je vyžadováno.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'Toto pole je vyžadováno.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'Toto pole je vyžadováno.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['S','M','T','W','T','F','S'];
$.fn.calendar.defaults.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'Dnes';
$.fn.datebox.defaults.closeText = 'Zavřít';
$.fn.datebox.defaults.okText = 'Ok';
$.fn.datebox.defaults.missingMessage = 'Toto pole je vyžadováno.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
|
/*
* Globalize Culture sr-Latn-ME
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need to be fixed in the generator
*/
(function( window, undefined ) {
var Globalize;
if ( typeof require !== "undefined" &&
typeof exports !== "undefined" &&
typeof module !== "undefined" ) {
// Assume CommonJS
Globalize = require( "globalize" );
} else {
// Global variable
Globalize = window.Globalize;
}
Globalize.addCultureInfo( "sr-Latn-ME", "default", {
name: "sr-Latn-ME",
englishName: "Serbian (Latin, Montenegro)",
nativeName: "srpski (Crna Gora)",
language: "sr-Latn",
numberFormat: {
",": ".",
".": ",",
negativeInfinity: "-beskonačnost",
positiveInfinity: "+beskonačnost",
percent: {
pattern: ["-n%","n%"],
",": ".",
".": ","
},
currency: {
pattern: ["-n $","n $"],
",": ".",
".": ",",
symbol: "€"
}
},
calendars: {
standard: {
"/": ".",
firstDay: 1,
days: {
names: ["nedelja","ponedeljak","utorak","sreda","četvrtak","petak","subota"],
namesAbbr: ["ned","pon","uto","sre","čet","pet","sub"],
namesShort: ["ne","po","ut","sr","če","pe","su"]
},
months: {
names: ["januar","februar","mart","april","maj","jun","jul","avgust","septembar","oktobar","novembar","decembar",""],
namesAbbr: ["jan","feb","mar","apr","maj","jun","jul","avg","sep","okt","nov","dec",""]
},
AM: null,
PM: null,
eras: [{"name":"n.e.","start":null,"offset":0}],
patterns: {
d: "d.M.yyyy",
D: "d. MMMM yyyy",
t: "H:mm",
T: "H:mm:ss",
f: "d. MMMM yyyy H:mm",
F: "d. MMMM yyyy H:mm:ss",
M: "d. MMMM",
Y: "MMMM yyyy"
}
}
}
});
}( this ));
|
/*
* /MathJax/jax/output/HTML-CSS/fonts/STIX/IntegralsD/Bold/All.js
*
* Copyright (c) 2009-2016 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS["STIXIntegralsD-bold"],{32:[0,0,250,0,0],160:[0,0,250,0,0],8747:[2000,269,686,56,1136],8748:[2000,269,1084,56,1534],8749:[2000,269,1482,56,1932],8750:[2000,269,736,56,1136],8751:[2000,269,1134,56,1534],8752:[2000,269,1532,56,1932],8753:[2000,269,736,56,1136],8754:[2000,269,736,56,1136],8755:[2000,269,736,56,1136],10764:[2000,269,1880,56,2330],10765:[2000,269,736,56,1136],10766:[2000,269,736,56,1136],10767:[2000,269,736,56,1136],10768:[2000,269,736,56,1136],10769:[2000,269,736,56,1136],10770:[2000,269,836,56,1136],10771:[2000,269,736,56,1136],10772:[2000,269,926,56,1136],10773:[2000,269,736,56,1136],10774:[2000,269,836,56,1136],10775:[2000,269,911,24,1131],10776:[2000,269,736,56,1136],10777:[2000,269,836,56,1136],10778:[2000,269,836,56,1136],10779:[2182,269,746,56,1146],10780:[2000,451,696,56,1146]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/IntegralsD/Bold/All.js");
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'table', 'en-au', {
border: 'Border size',
caption: 'Caption',
cell: {
menu: 'Cell',
insertBefore: 'Insert Cell Before',
insertAfter: 'Insert Cell After',
deleteCell: 'Delete Cells',
merge: 'Merge Cells',
mergeRight: 'Merge Right',
mergeDown: 'Merge Down',
splitHorizontal: 'Split Cell Horizontally',
splitVertical: 'Split Cell Vertically',
title: 'Cell Properties',
cellType: 'Cell Type',
rowSpan: 'Rows Span',
colSpan: 'Columns Span',
wordWrap: 'Word Wrap',
hAlign: 'Horizontal Alignment',
vAlign: 'Vertical Alignment',
alignBaseline: 'Baseline',
bgColor: 'Background Color',
borderColor: 'Border Color',
data: 'Data',
header: 'Header',
yes: 'Yes',
no: 'No',
invalidWidth: 'Cell width must be a number.',
invalidHeight: 'Cell height must be a number.',
invalidRowSpan: 'Rows span must be a whole number.',
invalidColSpan: 'Columns span must be a whole number.',
chooseColor: 'Choose'
},
cellPad: 'Cell padding',
cellSpace: 'Cell spacing',
column: {
menu: 'Column',
insertBefore: 'Insert Column Before',
insertAfter: 'Insert Column After',
deleteColumn: 'Delete Columns'
},
columns: 'Columns',
deleteTable: 'Delete Table',
headers: 'Headers',
headersBoth: 'Both',
headersColumn: 'First column',
headersNone: 'None',
headersRow: 'First Row',
invalidBorder: 'Border size must be a number.',
invalidCellPadding: 'Cell padding must be a number.',
invalidCellSpacing: 'Cell spacing must be a number.',
invalidCols: 'Number of columns must be a number greater than 0.',
invalidHeight: 'Table height must be a number.',
invalidRows: 'Number of rows must be a number greater than 0.',
invalidWidth: 'Table width must be a number.',
menu: 'Table Properties',
row: {
menu: 'Row',
insertBefore: 'Insert Row Before',
insertAfter: 'Insert Row After',
deleteRow: 'Delete Rows'
},
rows: 'Rows',
summary: 'Summary',
title: 'Table Properties',
toolbar: 'Table',
widthPc: 'percent',
widthPx: 'pixels',
widthUnit: 'width unit' // MISSING
});
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v5.0.7
* @link http://www.ag-grid.com/
* @license MIT
*/
|
/*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, describe, beforeEach, afterEach, it, runs, expect, waitsForDone, beforeFirst, afterLast */
define(function (require, exports, module) {
'use strict';
// Load dependent modules
var CommandManager, // loaded from brackets.test
Commands, // loaded from brackets.test
DocumentManager, // loaded from brackets.test
EditorManager, // loaded from brackets.test
SpecRunnerUtils = require("spec/SpecRunnerUtils");
describe("DocumentManager", function () {
this.category = "integration";
var testPath = SpecRunnerUtils.getTestPath("/spec/DocumentCommandHandlers-test-files"),
testFile = testPath + "/test.js",
testWindow,
_$,
promise;
beforeFirst(function () {
SpecRunnerUtils.createTestWindowAndRun(this, function (w) {
testWindow = w;
_$ = testWindow.$;
// Load module instances from brackets.test
CommandManager = testWindow.brackets.test.CommandManager;
Commands = testWindow.brackets.test.Commands;
DocumentManager = testWindow.brackets.test.DocumentManager;
EditorManager = testWindow.brackets.test.EditorManager;
});
});
afterLast(function () {
testWindow = null;
CommandManager = null;
Commands = null;
DocumentManager = null;
EditorManager = null;
SpecRunnerUtils.closeTestWindow();
});
beforeEach(function () {
// Working set behavior is sensitive to whether file lives in the project or outside it, so make
// the project root a known quantity.
SpecRunnerUtils.loadProjectInTestWindow(testPath);
});
afterEach(function () {
promise = null;
runs(function () {
// Call closeAll() directly. Some tests set a spy on the save as
// dialog preventing SpecRunnerUtils.closeAllFiles() from
// working properly.
testWindow.brackets.test.MainViewManager._closeAll(testWindow.brackets.test.MainViewManager.ALL_PANES);
});
});
describe("openDocument ", function () {
it("Should report document in open documents list", function () {
runs(function () {
promise = CommandManager.execute(Commands.FILE_OPEN, { fullPath: testFile });
waitsForDone(promise, Commands.FILE_OPEN);
});
runs(function () {
expect(DocumentManager.getOpenDocumentForPath(testFile)).toBeTruthy();
expect(DocumentManager.getAllOpenDocuments().length).toEqual(1);
expect(DocumentManager.getCurrentDocument().file.fullPath).toEqual(testFile);
});
runs(function () {
promise = DocumentManager.getDocumentText({ fullPath: testFile });
waitsForDone(promise, "DocumentManager.getDocumentText");
});
runs(function () {
promise = CommandManager.execute(Commands.FILE_CLOSE_ALL);
waitsForDone(promise, Commands.FILE_CLOSE_ALL);
});
runs(function () {
expect(DocumentManager.getAllOpenDocuments().length).toEqual(0);
expect(DocumentManager.getCurrentDocument()).toBeFalsy();
});
});
it("Should create a new untitled document", function () {
runs(function () {
var doc = DocumentManager.createUntitledDocument(1, ".txt");
expect(doc).toBeTruthy();
});
});
});
});
});
|
/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the 2-clause BSD license.
* See license.txt in the OpenLayers distribution or repository for the
* full text of the license. */
/**
* @requires OpenLayers/Format/XML/VersionedOGC.js
* @requires OpenLayers/Filter/FeatureId.js
* @requires OpenLayers/Filter/Logical.js
* @requires OpenLayers/Filter/Comparison.js
*/
/**
* Class: OpenLayers.Format.Filter
* Read/Wite ogc:Filter. Create a new instance with the <OpenLayers.Format.Filter>
* constructor.
*
* Inherits from:
* - <OpenLayers.Format.XML.VersionedOGC>
*/
OpenLayers.Format.Filter = OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC, {
/**
* APIProperty: defaultVersion
* {String} Version number to assume if none found. Default is "1.0.0".
*/
defaultVersion: "1.0.0",
/**
* APIMethod: write
* Write an ogc:Filter given a filter object.
*
* Parameters:
* filter - {<OpenLayers.Filter>} An filter.
* options - {Object} Optional configuration object.
*
* Returns:
* {Elment} An ogc:Filter element node.
*/
/**
* APIMethod: read
* Read and Filter doc and return an object representing the Filter.
*
* Parameters:
* data - {String | DOMElement} Data to read.
*
* Returns:
* {<OpenLayers.Filter>} A filter object.
*/
CLASS_NAME: "OpenLayers.Format.Filter"
});
|
/*! Amaze UI v2.2.0 ~ Old IE Fucker | by Amaze UI Team | (c) 2015 AllMobilize, Inc. | Licensed under MIT | 2015-01-28T06:01:01 UTC */
(function e(t, n, r) {
function s(o, u) {
if (!n[o]) {
if (!t[o]) {
var a = typeof require == "function" && require;
if (!u && a) return a(o, !0);
if (i) return i(o, !0);
var f = new Error("Cannot find module '" + o + "'");
throw f.code = "MODULE_NOT_FOUND", f
}
var l = n[o] = {
exports: {}
};
t[o][0].call(l.exports, function(e) {
var n = t[o][1][e];
return s(n ? n : e)
}, l, l.exports, e, t, n, r)
}
return n[o].exports
}
var i = typeof require == "function" && require;
for (var o = 0; o < r.length; o++) s(r[o]);
return s
})({
1: [
function(require, module, exports) {
(function(global) {
// Amaze UI JavaScript for IE8
'use strict';
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
require('./core');
require('./ui.alert');
require('./ui.button');
require('./ui.collapse');
require('./ui.dimmer');
require('./ui.dropdown');
require('./ui.flexslider');
require('./ui.modal');
require('./ui.offcanvas');
require('./ui.popover');
require('./ui.progress');
require('./ui.scrollspynav');
require('./ui.sticky');
require('./util.cookie');
module.exports = $.AMUI;
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {
"./core": 2,
"./ui.alert": 3,
"./ui.button": 4,
"./ui.collapse": 5,
"./ui.dimmer": 6,
"./ui.dropdown": 7,
"./ui.flexslider": 8,
"./ui.modal": 9,
"./ui.offcanvas": 10,
"./ui.popover": 11,
"./ui.progress": 12,
"./ui.scrollspynav": 13,
"./ui.sticky": 15,
"./util.cookie": 16
}
],
2: [
function(require, module, exports) {
(function(global) {
'use strict';
/* jshint -W040 */
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
if (typeof $ === 'undefined') {
throw new Error('Amaze UI 2.x requires jQuery :-(\n' +
'\u7231\u4e0a\u4e00\u5339\u91ce\u9a6c\uff0c\u53ef\u4f60' +
'\u7684\u5bb6\u91cc\u6ca1\u6709\u8349\u539f\u2026');
}
var UI = $.AMUI || {};
var $win = $(window);
var doc = window.document;
var $html = $('html');
UI.VERSION = '2.0.0';
UI.support = {};
UI.support.transition = (function() {
var transitionEnd = (function() {
// https://developer.mozilla.org/en-US/docs/Web/Events/transitionend#Browser_compatibility
var element = doc.body || doc.documentElement;
var transEndEventNames = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
};
for (var name in transEndEventNames) {
if (element.style[name] !== undefined) {
return transEndEventNames[name];
}
}
})();
return transitionEnd && {
end: transitionEnd
};
})();
UI.support.animation = (function() {
var animationEnd = (function() {
var element = doc.body || doc.documentElement;
var animEndEventNames = {
WebkitAnimation: 'webkitAnimationEnd',
MozAnimation: 'animationend',
OAnimation: 'oAnimationEnd oanimationend',
animation: 'animationend'
};
for (var name in animEndEventNames) {
if (element.style[name] !== undefined) {
return animEndEventNames[name];
}
}
})();
return animationEnd && {
end: animationEnd
};
})();
/* jshint -W069 */
UI.support.touch = (
('ontouchstart' in window &&
navigator.userAgent.toLowerCase().match(/mobile|tablet/)) ||
(window.DocumentTouch && document instanceof window.DocumentTouch) ||
(window.navigator['msPointerEnabled'] &&
window.navigator['msMaxTouchPoints'] > 0) || //IE 10
(window.navigator['pointerEnabled'] &&
window.navigator['maxTouchPoints'] > 0) || //IE >=11
false);
// https://developer.mozilla.org/zh-CN/docs/DOM/MutationObserver
UI.support.mutationobserver = (window.MutationObserver ||
window.WebKitMutationObserver || null);
// https://github.com/Modernizr/Modernizr/blob/924c7611c170ef2dc502582e5079507aff61e388/feature-detects/forms/validation.js#L20
UI.support.formValidation = (typeof document.createElement('form').checkValidity ===
'function');
UI.utils = {};
/**
* Debounce function
* @param {function} func Function to be debounced
* @param {number} wait Function execution threshold in milliseconds
* @param {bool} immediate Whether the function should be called at
* the beginning of the delay instead of the
* end. Default is false.
* @desc Executes a function when it stops being invoked for n seconds
* @via _.debounce() http://underscorejs.org
*/
UI.utils.debounce = function(func, wait, immediate) {
var timeout;
return function() {
var context = this;
var args = arguments;
var later = function() {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
};
UI.utils.isInView = function(element, options) {
var $element = $(element);
var visible = !!($element.width() || $element.height()) &&
$element.css('display') !== 'none';
if (!visible) {
return false;
}
var windowLeft = $win.scrollLeft();
var windowTop = $win.scrollTop();
var offset = $element.offset();
var left = offset.left;
var top = offset.top;
options = $.extend({
topOffset: 0,
leftOffset: 0
}, options);
return (top + $element.height() >= windowTop &&
top - options.topOffset <= windowTop + $win.height() &&
left + $element.width() >= windowLeft &&
left - options.leftOffset <= windowLeft + $win.width());
};
/* jshint -W054 */
UI.utils.parseOptions = UI.utils.options = function(string) {
if ($.isPlainObject(string)) {
return string;
}
var start = (string ? string.indexOf('{') : -1);
var options = {};
if (start != -1) {
try {
options = (new Function('',
'var json = ' + string.substr(start) +
'; return JSON.parse(JSON.stringify(json));'))();
} catch (e) {}
}
return options;
};
/* jshint +W054 */
UI.utils.generateGUID = function(namespace) {
var uid = namespace + '-' || 'am-';
do {
uid += Math.random().toString(36).substring(2, 7);
} while (document.getElementById(uid));
return uid;
};
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function(duration) {
var called = false;
var $el = this;
$(this).one(UI.support.transition.end, function() {
called = true;
});
var callback = function() {
if (!called) {
$($el).trigger(UI.support.transition.end);
}
$el.transitionEndTimmer = undefined;
};
this.transitionEndTimmer = setTimeout(callback, duration);
return this;
};
$.fn.redraw = function() {
$(this).each(function() {
/* jshint unused:false */
var redraw = this.offsetHeight;
});
return this;
};
/* jshint unused:true */
$.fn.transitionEnd = function(callback) {
var endEvent = UI.support.transition.end;
var dom = this;
function fireCallBack(e) {
callback.call(this, e);
endEvent && dom.off(endEvent, fireCallBack);
}
if (callback && endEvent) {
dom.on(endEvent, fireCallBack);
}
return this;
};
$.fn.removeClassRegEx = function() {
return this.each(function(regex) {
var classes = $(this).attr('class');
if (!classes || !regex) {
return false;
}
var classArray = [];
classes = classes.split(' ');
for (var i = 0, len = classes.length; i < len; i++) {
if (!classes[i].match(regex)) {
classArray.push(classes[i]);
}
}
$(this).attr('class', classArray.join(' '));
});
};
//
$.fn.alterClass = function(removals, additions) {
var self = this;
if (removals.indexOf('*') === -1) {
// Use native jQuery methods if there is no wildcard matching
self.removeClass(removals);
return !additions ? self : self.addClass(additions);
}
var classPattern = new RegExp('\\s' +
removals.replace(/\*/g, '[A-Za-z0-9-_]+').split(' ').join(
'\\s|\\s') +
'\\s', 'g');
self.each(function(i, it) {
var cn = ' ' + it.className + ' ';
while (classPattern.test(cn)) {
cn = cn.replace(classPattern, ' ');
}
it.className = $.trim(cn);
});
return !additions ? self : self.addClass(additions);
};
// handle multiple browsers for requestAnimationFrame()
// http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
// https://github.com/gnarf/jquery-requestAnimationFrame
UI.utils.rAF = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
// if all else fails, use setTimeout
function(callback) {
return window.setTimeout(callback, 1000 / 60); // shoot for 60 fps
};
})();
// handle multiple browsers for cancelAnimationFrame()
UI.utils.cancelAF = (function() {
return window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
window.oCancelAnimationFrame ||
function(id) {
window.clearTimeout(id);
};
})();
// via http://davidwalsh.name/detect-scrollbar-width
UI.utils.measureScrollbar = function() {
if (document.body.clientWidth >= window.innerWidth) {
return 0;
}
// if ($html.width() >= window.innerWidth) return;
// var scrollbarWidth = window.innerWidth - $html.width();
var $measure = $('<div ' +
'style="width: 100px;height: 100px;overflow: scroll;' +
'position: absolute;top: -9999px;"></div>');
$(document.body).append($measure);
var scrollbarWidth = $measure[0].offsetWidth - $measure[0].clientWidth;
$measure.remove();
return scrollbarWidth;
};
UI.utils.imageLoader = function($image, callback) {
function loaded() {
callback($image[0]);
}
function bindLoad() {
this.one('load', loaded);
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
var src = this.attr('src');
var param = src.match(/\?/) ? '&' : '?';
param += 'random=' + (new Date()).getTime();
this.attr('src', src + param);
}
}
if (!$image.attr('src')) {
loaded();
return;
}
if ($image[0].complete || $image[0].readyState === 4) {
loaded();
} else {
bindLoad.call($image);
}
};
/**
* https://github.com/cho45/micro-template.js
* (c) cho45 http://cho45.github.com/mit-license
*/
/* jshint -W109 */
UI.template = function(id, data) {
var me = UI.template;
if (!me.cache[id]) {
me.cache[id] = (function() {
var name = id;
var string = /^[\w\-]+$/.test(id) ?
me.get(id) : (name = 'template(string)', id); // no warnings
var line = 1;
var body = ('try { ' + (me.variable ?
'var ' + me.variable + ' = this.stash;' :
'with (this.stash) { ') +
"this.ret += '" +
string.replace(/<%/g, '\x11').replace(/%>/g, '\x13'). // if you want other tag, just edit this line
replace(/'(?![^\x11\x13]+?\x13)/g, '\\x27').replace(
/^\s*|\s*$/g, '').replace(/\n/g, function() {
return "';\nthis.line = " + (++line) +
"; this.ret += '\\n";
}).replace(/\x11-(.+?)\x13/g, "' + ($1) + '").replace(
/\x11=(.+?)\x13/g, "' + this.escapeHTML($1) + '").replace(
/\x11(.+?)\x13/g, "'; $1; this.ret += '") +
"'; " + (me.variable ? "" : "}") + "return this.ret;" +
"} catch (e) { throw 'TemplateError: ' + e + ' (on " +
name +
"' + ' line ' + this.line + ')'; } " +
"//@ sourceURL=" + name + "\n" // source map
).replace(/this\.ret \+= '';/g, '');
/* jshint -W054 */
var func = new Function(body);
var map = {
'&': '&',
'<': '<',
'>': '>',
'\x22': '"',
'\x27': '''
};
var escapeHTML = function(string) {
return ('' + string).replace(/[&<>\'\"]/g, function(_) {
return map[_];
});
};
return function(stash) {
return func.call(me.context = {
escapeHTML: escapeHTML,
line: 1,
ret: '',
stash: stash
});
};
})();
}
return data ? me.cache[id](data) : me.cache[id];
};
/* jshint +W109 */
/* jshint +W054 */
UI.template.cache = {};
UI.template.get = function(id) {
if (id) {
var element = document.getElementById(id);
return element && element.innerHTML || '';
}
};
// Dom mutation watchers
UI.DOMWatchers = [];
UI.DOMReady = false;
UI.ready = function(callback) {
UI.DOMWatchers.push(callback);
if (UI.DOMReady) {
console.log('ready call');
callback(document);
}
};
UI.DOMObserve = function(elements, options, callback) {
var Observer = UI.support.mutationobserver;
if (!Observer) {
return;
}
options = $.isPlainObject(options) ?
options : {
childList: true,
subtree: true
};
callback = typeof callback === 'function' && callback || function() {};
$(elements).each(function() {
var element = this;
var $element = $(element);
if ($element.data('am.observer')) {
return;
}
try {
var observer = new Observer(UI.utils.debounce(
function(mutations, instance) {
callback.call(element, mutations, instance);
// trigger this event manually if MutationObserver not supported
$element.trigger('changed.dom.amui');
}, 50));
observer.observe(element, options);
$element.data('am.observer', observer);
} catch (e) {}
});
};
$.fn.DOMObserve = function(options, callback) {
return this.each(function() {
UI.DOMObserve(this, options, callback);
});
};
// Attach FastClick on touch devices
if (UI.support.touch) {
$html.addClass('am-touch');
$(function() {
var FastClick = $.AMUI.FastClick;
FastClick && FastClick.attach(document.body);
});
}
$(document).on('changed.dom.amui', function(e) {
var element = e.target;
// TODO: just call changed element's watcher
// every watcher callback should have a key
// use like this: <div data-am-observe='key1, key2'>
// get keys via $(element).data('amObserve')
// call functions store with these keys
$.each(UI.DOMWatchers, function(i, watcher) {
watcher(element);
});
});
$(function() {
var $body = $('body');
UI.DOMReady = true;
// Run default init
$.each(UI.DOMWatchers, function(i, watcher) {
watcher(document);
});
// watches DOM
UI.DOMObserve('[data-am-observe]');
$html.removeClass('no-js').addClass('js');
UI.support.animation && $html.addClass('cssanimations');
// iOS standalone mode
if (window.navigator.standalone) {
$html.addClass('am-standalone');
}
$('.am-topbar-fixed-top').length &&
$body.addClass('am-with-topbar-fixed-top');
$('.am-topbar-fixed-bottom').length &&
$body.addClass('am-with-topbar-fixed-bottom');
// Remove responsive classes in .am-layout
var $layout = $('.am-layout');
$layout.find('[class*="md-block-grid"]').alterClass(
'md-block-grid-*');
$layout.find('[class*="lg-block-grid"]').alterClass(
'lg-block-grid');
// widgets not in .am-layout
$('[data-am-widget]').each(function() {
var $widget = $(this);
// console.log($widget.parents('.am-layout').length)
if ($widget.parents('.am-layout').length === 0) {
$widget.addClass('am-no-layout');
}
});
});
$.AMUI = UI;
module.exports = UI;
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {}
],
3: [
function(require, module, exports) {
(function(global) {
'use strict';
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
var UI = require('./core');
/**
* @via https://github.com/Minwe/bootstrap/blob/master/js/alert.js
* @copyright Copyright 2013 Twitter, Inc.
* @license Apache 2.0
*/
// Alert Class
// NOTE: removeElement option is unavailable now
var Alert = function(element, options) {
var _this = this;
this.options = $.extend({}, Alert.DEFAULTS, options);
this.$element = $(element);
this.$element.
addClass('am-fade am-in').
on('click.alert.amui', '.am-close', function() {
_this.close.call(this);
});
};
Alert.DEFAULTS = {
removeElement: true
};
Alert.prototype.close = function() {
var $this = $(this);
var $target = $this.hasClass('am-alert') ?
$this :
$this.parent('.am-alert');
$target.trigger('close.alert.amui');
$target.removeClass('am-in');
function processAlert() {
$target.trigger('closed.alert.amui').remove();
}
UI.support.transition && $target.hasClass('am-fade') ?
$target.
one(UI.support.transition.end, processAlert).
emulateTransitionEnd(200) : processAlert();
};
// Alert Plugin
$.fn.alert = function(option) {
return this.each(function() {
var $this = $(this);
var data = $this.data('amui.alert');
var options = typeof option == 'object' && option;
if (!data) {
$this.data('amui.alert', (data = new Alert(this, options || {})));
}
if (typeof option == 'string') {
data[option].call($this);
}
});
};
// Init code
$(document).on('click.alert.amui.data-api', '[data-am-alert]',
function(e) {
var $target = $(e.target);
$(this).addClass('am-fade am-in');
$target.is('.am-close') && $(this).alert('close');
});
$.AMUI.alert = Alert;
module.exports = Alert;
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {
"./core": 2
}
],
4: [
function(require, module, exports) {
(function(global) {
'use strict';
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
var UI = require('./core');
/**
* @via https://github.com/twbs/bootstrap/blob/master/js/button.js
* @copyright (c) 2011-2014 Twitter, Inc
* @license The MIT License
*/
var Button = function(element, options) {
this.$element = $(element);
this.options = $.extend({}, Button.DEFAULTS, options);
this.isLoading = false;
this.hasSpinner = false;
};
Button.DEFAULTS = {
loadingText: 'loading...',
className: {
loading: 'am-btn-loading',
disabled: 'am-disabled'
},
spinner: undefined
};
Button.prototype.setState = function(state) {
var disabled = 'disabled';
var $element = this.$element;
var options = this.options;
var val = $element.is('input') ? 'val' : 'html';
var loadingClassName = options.className.disabled + ' ' +
options.className.loading;
state = state + 'Text';
if (!options.resetText) {
options.resetText = $element[val]();
}
// add spinner for element with html()
if (UI.support.animation && options.spinner &&
val === 'html' && !this.hasSpinner) {
options.loadingText = '<span class="am-icon-' +
options.spinner +
' am-icon-spin"></span>' + options.loadingText;
this.hasSpinner = true;
}
$element[val](options[state]);
// push to event loop to allow forms to submit
setTimeout($.proxy(function() {
if (state == 'loadingText') {
$element.addClass(loadingClassName).attr(disabled,
disabled);
this.isLoading = true;
} else if (this.isLoading) {
$element.removeClass(loadingClassName).removeAttr(
disabled);
this.isLoading = false;
}
}, this), 0);
};
Button.prototype.toggle = function() {
var changed = true;
var $element = this.$element;
var $parent = this.$element.parent('.am-btn-group');
if ($parent.length) {
var $input = this.$element.find('input');
if ($input.prop('type') == 'radio') {
if ($input.prop('checked') && $element.hasClass('am-active')) {
changed = false;
} else {
$parent.find('.am-active').removeClass('am-active');
}
}
if (changed) {
$input.prop('checked', !$element.hasClass('am-active')).trigger(
'change');
}
}
if (changed) {
$element.toggleClass('am-active');
if (!$element.hasClass('am-active')) {
$element.blur();
}
}
};
// Button plugin
function Plugin(option) {
return this.each(function() {
var $this = $(this);
var data = $this.data('amui.button');
var options = typeof option == 'object' && option || {};
if (!data) {
$this.data('amui.button', (data = new Button(this,
options)));
}
if (option == 'toggle') {
data.toggle();
} else if (typeof option == 'string') {
data.setState(option);
}
});
}
$.fn.button = Plugin;
// Init code
$(document).on('click.button.amui.data-api', '[data-am-button]',
function(e) {
var $btn = $(e.target);
if (!$btn.hasClass('am-btn')) {
$btn = $btn.closest('.am-btn');
}
Plugin.call($btn, 'toggle');
e.preventDefault();
});
UI.ready(function(context) {
$('[data-am-loading]', context).each(function() {
$(this).button(UI.utils.parseOptions($(this).data(
'amLoading')));
});
});
$.AMUI.button = Button;
module.exports = Button;
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {
"./core": 2
}
],
5: [
function(require, module, exports) {
(function(global) {
'use strict';
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
var UI = require('./core');
/**
* @via https://github.com/twbs/bootstrap/blob/master/js/collapse.js
* @copyright (c) 2011-2014 Twitter, Inc
* @license The MIT License
*/
var Collapse = function(element, options) {
this.$element = $(element);
this.options = $.extend({}, Collapse.DEFAULTS, options);
this.transitioning = null;
if (this.options.parent) {
this.$parent = $(this.options.parent);
}
if (this.options.toggle) {
this.toggle();
}
};
Collapse.DEFAULTS = {
toggle: true
};
Collapse.prototype.open = function() {
if (this.transitioning || this.$element.hasClass('am-in')) {
return;
}
var startEvent = $.Event('open.collapse.amui');
this.$element.trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return;
}
var actives = this.$parent && this.$parent.find(
'> .am-panel > .am-in');
if (actives && actives.length) {
var hasData = actives.data('amui.collapse');
if (hasData && hasData.transitioning) {
return;
}
Plugin.call(actives, 'close');
hasData || actives.data('amui.collapse', null);
}
this.$element
.removeClass('am-collapse')
.addClass('am-collapsing').height(0);
this.transitioning = 1;
var complete = function() {
this.$element.
removeClass('am-collapsing').
addClass('am-collapse am-in').
height('');
this.transitioning = 0;
this.$element.trigger('opened.collapse.amui');
};
if (!UI.support.transition) {
return complete.call(this);
}
var scrollHeight = this.$element[0].scrollHeight;
this.$element
.one(UI.support.transition.end, $.proxy(complete, this))
.emulateTransitionEnd(300).
css({
height: scrollHeight
}); // 当折叠的容器有 padding 时,如果用 height() 只能设置内容的宽度
};
Collapse.prototype.close = function() {
if (this.transitioning || !this.$element.hasClass('am-in')) {
return;
}
var startEvent = $.Event('close.collapse.amui');
this.$element.trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return;
}
this.$element.height(this.$element.height()).redraw();
this.$element.addClass('am-collapsing').
removeClass('am-collapse am-in');
this.transitioning = 1;
var complete = function() {
this.transitioning = 0;
this.$element.trigger('closed.collapse.amui').
removeClass('am-collapsing').
addClass('am-collapse');
// css({height: '0'});
};
if (!UI.support.transition) {
return complete.call(this);
}
this.$element.height(0)
.one(UI.support.transition.end, $.proxy(complete, this))
.emulateTransitionEnd(300);
};
Collapse.prototype.toggle = function() {
this[this.$element.hasClass('am-in') ? 'close' : 'open']();
};
// Collapse Plugin
function Plugin(option) {
return this.each(function() {
var $this = $(this);
var data = $this.data('amui.collapse');
var options = $.extend({}, Collapse.DEFAULTS,
UI.utils.options($this.attr('data-am-collapse')),
typeof option == 'object' && option);
if (!data && options.toggle && option == 'open') {
option = !option;
}
if (!data) {
$this.data('amui.collapse', (data = new Collapse(this,
options)));
}
if (typeof option == 'string') {
data[option]();
}
});
}
$.fn.collapse = Plugin;
// Init code
$(document).on('click.collapse.amui.data-api', '[data-am-collapse]',
function(e) {
var href;
var $this = $(this);
var options = UI.utils.options($this.attr('data-am-collapse'));
var target = options.target ||
e.preventDefault() ||
(href = $this.attr('href')) &&
href.replace(/.*(?=#[^\s]+$)/, '');
var $target = $(target);
var data = $target.data('amui.collapse');
var option = data ? 'toggle' : options;
var parent = options.parent;
var $parent = parent && $(parent);
if (!data || !data.transitioning) {
if ($parent) {
// '[data-am-collapse*="{parent: \'' + parent + '"]
$parent.find('[data-am-collapse]').not($this).addClass(
'am-collapsed');
}
$this[$target.hasClass('am-in') ? 'addClass' :
'removeClass']('am-collapsed');
}
Plugin.call($target, option);
});
$.AMUI.collapse = Collapse;
module.exports = Collapse;
// TODO: 更好的 target 选择方式
// 折叠的容器必须没有 border/padding 才能正常处理,否则动画会有一些小问题
// 寻找更好的未知高度 transition 动画解决方案,max-height 之类的就算了
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {
"./core": 2
}
],
6: [
function(require, module, exports) {
(function(global) {
'use strict';
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
var UI = require('./core');
var $doc = $(document);
var transition = UI.support.transition;
var Dimmer = function() {
this.id = UI.utils.generateGUID('am-dimmer');
this.$element = $(Dimmer.DEFAULTS.tpl, {
id: this.id
});
this.inited = false;
this.scrollbarWidth = 0;
this.$used = $([]);
};
Dimmer.DEFAULTS = {
tpl: '<div class="am-dimmer" data-am-dimmer></div>'
};
Dimmer.prototype.init = function() {
if (!this.inited) {
$(document.body).append(this.$element);
this.inited = true;
$doc.trigger('init.dimmer.amui');
}
return this;
};
Dimmer.prototype.open = function(relatedElement) {
if (!this.inited) {
this.init();
}
var $element = this.$element;
// 用于多重调用
if (relatedElement) {
this.$used = this.$used.add($(relatedElement));
}
this.checkScrollbar().setScrollbar();
$element.off(transition.end).show().trigger('open.dimmer.amui');
setTimeout(function() {
$element.addClass('am-active');
}, 0);
return this;
};
Dimmer.prototype.close = function(relatedElement, force) {
this.$used = this.$used.not($(relatedElement));
if (!force && this.$used.length) {
return this;
}
var $element = this.$element;
$element.removeClass('am-active').trigger('close.dimmer.amui');
function complete() {
$element.hide();
this.resetScrollbar();
}
// transition ? $element.one(transition.end, $.proxy(complete, this)) :
complete.call(this);
return this;
};
Dimmer.prototype.checkScrollbar = function() {
this.scrollbarWidth = UI.utils.measureScrollbar();
return this;
};
Dimmer.prototype.setScrollbar = function() {
var $body = $(document.body);
var bodyPaddingRight = parseInt(($body.css('padding-right') || 0),
10);
if (this.scrollbarWidth) {
$body.css('padding-right', bodyPaddingRight + this.scrollbarWidth);
}
$body.addClass('am-dimmer-active');
return this;
};
Dimmer.prototype.resetScrollbar = function() {
$(document.body).css('padding-right', '').removeClass(
'am-dimmer-active');
return this;
};
var dimmer = new Dimmer();
$.AMUI.dimmer = dimmer;
module.exports = dimmer;
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {
"./core": 2
}
],
7: [
function(require, module, exports) {
(function(global) {
'use strict';
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
var UI = require('./core');
var animation = UI.support.animation;
/**
* @via https://github.com/Minwe/bootstrap/blob/master/js/dropdown.js
* @copyright (c) 2011-2014 Twitter, Inc
* @license The MIT License
*/
// var toggle = '[data-am-dropdown] > .am-dropdown-toggle';
var Dropdown = function(element, options) {
this.options = $.extend({}, Dropdown.DEFAULTS, options);
options = this.options;
this.$element = $(element);
this.$toggle = this.$element.find(options.selector.toggle);
this.$dropdown = this.$element.find(options.selector.dropdown);
this.$boundary = (options.boundary === window) ? $(window) :
this.$element.closest(options.boundary);
this.$justify = (options.justify && $(options.justify).length &&
$(options.justify)) || undefined;
!this.$boundary.length && (this.$boundary = $(window));
this.active = this.$element.hasClass('am-active') ? true :
false;
this.animating = null;
this.events();
};
Dropdown.DEFAULTS = {
animation: 'am-animation-slide-top-fixed',
boundary: window,
justify: undefined,
selector: {
dropdown: '.am-dropdown-content',
toggle: '.am-dropdown-toggle'
},
trigger: 'click'
};
Dropdown.prototype.toggle = function() {
this.clear();
if (this.animating) {
return;
}
this[this.active ? 'close' : 'open']();
};
Dropdown.prototype.open = function(e) {
var $toggle = this.$toggle;
var $element = this.$element;
var $dropdown = this.$dropdown;
if ($toggle.is('.am-disabled, :disabled')) {
return;
}
if (this.active) {
return;
}
$element.trigger('open.dropdown.amui').addClass('am-active');
$toggle.trigger('focus');
this.checkDimensions();
var complete = $.proxy(function() {
$element.trigger('opened.dropdown.amui');
this.active = true;
this.animating = 0;
}, this);
if (animation) {
this.animating = 1;
$dropdown.addClass(this.options.animation).
on(animation.end + '.open.dropdown.amui', $.proxy(function() {
complete();
$dropdown.removeClass(this.options.animation);
}, this));
} else {
complete();
}
};
Dropdown.prototype.close = function() {
if (!this.active) {
return;
}
// fix #165
// var animationName = this.options.animation + ' am-animation-reverse';
var animationName = 'am-dropdown-animation';
var $element = this.$element;
var $dropdown = this.$dropdown;
$element.trigger('close.dropdown.amui');
var complete = $.proxy(function complete() {
$element.
removeClass('am-active').
trigger('closed.dropdown.amui');
this.active = false;
this.animating = 0;
this.$toggle.blur();
}, this);
if (animation) {
$dropdown.removeClass(this.options.animation);
$dropdown.addClass(animationName);
this.animating = 1;
// animation
$dropdown.one(animation.end + '.close.dropdown.amui', function() {
$dropdown.removeClass(animationName);
complete();
});
} else {
complete();
}
};
Dropdown.prototype.checkDimensions = function() {
if (!this.$dropdown.length) {
return;
}
var $dropdown = this.$dropdown;
var offset = $dropdown.offset();
var width = $dropdown.outerWidth();
var boundaryWidth = this.$boundary.width();
var boundaryOffset = $.isWindow(this.boundary) && this.$boundary.offset() ?
this.$boundary.offset().left : 0;
if (this.$justify) {
// jQuery.fn.width() is really...
$dropdown.css({
'min-width': this.$justify.css('width')
});
}
if ((width + (offset.left - boundaryOffset)) > boundaryWidth) {
this.$element.addClass('am-dropdown-flip');
}
};
Dropdown.prototype.clear = function() {
$('[data-am-dropdown]').not(this.$element).each(function() {
var data = $(this).data('amui.dropdown');
data && data.close();
});
};
Dropdown.prototype.events = function() {
var eventNS = 'dropdown.amui';
// triggers = this.options.trigger.split(' '),
var $toggle = this.$toggle;
$toggle.on('click.' + eventNS, $.proxy(function(e) {
e.preventDefault();
this.toggle();
}, this));
/*for (var i = triggers.length; i--;) {
var trigger = triggers[i];
if (trigger === 'click') {
$toggle.on('click.' + eventNS, $.proxy(this.toggle, this))
}
if (trigger === 'focus' || trigger === 'hover') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin';
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout';
this.$element.on(eventIn + '.' + eventNS, $.proxy(this.open, this))
.on(eventOut + '.' + eventNS, $.proxy(this.close, this));
}
}*/
$(document).on('keydown.dropdown.amui', $.proxy(function(e) {
e.keyCode === 27 && this.active && this.close();
}, this)).on('click.outer.dropdown.amui', $.proxy(function(e) {
// var $target = $(e.target);
if (this.active &&
(this.$element[0] === e.target || !this.$element.find(e.target)
.length)) {
this.close();
}
}, this));
};
// Dropdown Plugin
function Plugin(option) {
return this.each(function() {
var $this = $(this);
var data = $this.data('amui.dropdown');
var options = $.extend({},
UI.utils.parseOptions($this.attr('data-am-dropdown')),
typeof option == 'object' && option);
if (!data) {
$this.data('amui.dropdown', (data = new Dropdown(this,
options)));
}
if (typeof option == 'string') {
data[option]();
}
});
}
$.fn.dropdown = Plugin;
// Init code
UI.ready(function(context) {
$('[data-am-dropdown]', context).dropdown();
});
$(document).on('click.dropdown.amui.data-api', '.am-dropdown form',
function(e) {
e.stopPropagation();
});
$.AMUI.dropdown = Dropdown;
module.exports = Dropdown;
// TODO: 1. 处理链接 focus
// 2. 增加 mouseenter / mouseleave 选项
// 3. 宽度适应
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {
"./core": 2
}
],
8: [
function(require, module, exports) {
(function(global) {
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
var UI = require('./core');
// MODIFIED:
// - LINE 226: add `<i></i>`
// - namespace
// - Init code
// TODO: start after x ms when pause on actions
/*
* jQuery FlexSlider v2.2.2
* Copyright 2012 WooThemes
* Contributing Author: Tyler Smith
*/
// FlexSlider: Object Instance
$.flexslider = function(el, options) {
var slider = $(el);
// making variables public
slider.vars = $.extend({}, $.flexslider.defaults, options);
var namespace = slider.vars.namespace,
msGesture = window.navigator && window.navigator.msPointerEnabled &&
window.MSGesture,
touch = (("ontouchstart" in window) || msGesture || window.DocumentTouch &&
document instanceof DocumentTouch) && slider.vars.touch,
// depricating this idea, as devices are being released with both of these events
//eventType = (touch) ? "touchend" : "click",
eventType = "click touchend MSPointerUp keyup",
watchedEvent = "",
watchedEventClearTimer,
vertical = slider.vars.direction === "vertical",
reverse = slider.vars.reverse,
carousel = (slider.vars.itemWidth > 0),
fade = slider.vars.animation === "fade",
asNav = slider.vars.asNavFor !== "",
methods = {},
focused = true;
// Store a reference to the slider object
$.data(el, 'flexslider', slider);
// Private slider methods
methods = {
init: function() {
slider.animating = false;
// Get current slide and make sure it is a number
slider.currentSlide = parseInt((slider.vars.startAt ? slider.vars
.startAt : 0), 10);
if (isNaN(slider.currentSlide)) {
slider.currentSlide = 0;
}
slider.animatingTo = slider.currentSlide;
slider.atEnd = (slider.currentSlide === 0 || slider.currentSlide ===
slider.last);
slider.containerSelector = slider.vars.selector.substr(0,
slider.vars.selector.search(' '));
slider.slides = $(slider.vars.selector, slider);
slider.container = $(slider.containerSelector, slider);
slider.count = slider.slides.length;
// SYNC:
slider.syncExists = $(slider.vars.sync).length > 0;
// SLIDE:
if (slider.vars.animation === "slide") slider.vars.animation =
"swing";
slider.prop = (vertical) ? "top" : "marginLeft";
slider.args = {};
// SLIDESHOW:
slider.manualPause = false;
slider.stopped = false;
//PAUSE WHEN INVISIBLE
slider.started = false;
slider.startTimeout = null;
// TOUCH/USECSS:
slider.transitions = !slider.vars.video && !fade && slider.vars
.useCSS && (function() {
var obj = document.createElement('div'),
props = ['perspectiveProperty', 'WebkitPerspective',
'MozPerspective', 'OPerspective', 'msPerspective'
];
for (var i in props) {
if (obj.style[props[i]] !== undefined) {
slider.pfx = props[i].replace('Perspective', '').toLowerCase();
slider.prop = "-" + slider.pfx + "-transform";
return true;
}
}
return false;
}());
slider.ensureAnimationEnd = '';
// CONTROLSCONTAINER:
if (slider.vars.controlsContainer !== "") slider.controlsContainer =
$(slider.vars.controlsContainer).length > 0 && $(slider.vars
.controlsContainer);
// MANUAL:
if (slider.vars.manualControls !== "") slider.manualControls =
$(slider.vars.manualControls).length > 0 && $(slider.vars.manualControls);
// RANDOMIZE:
if (slider.vars.randomize) {
slider.slides.sort(function() {
return (Math.round(Math.random()) - 0.5);
});
slider.container.empty().append(slider.slides);
}
slider.doMath();
// INIT
slider.setup("init");
// CONTROLNAV:
if (slider.vars.controlNav) methods.controlNav.setup();
// DIRECTIONNAV:
if (slider.vars.directionNav) methods.directionNav.setup();
// KEYBOARD:
if (slider.vars.keyboard && ($(slider.containerSelector).length ===
1 || slider.vars.multipleKeyboard)) {
$(document).bind('keyup', function(event) {
var keycode = event.keyCode;
if (!slider.animating && (keycode === 39 || keycode ===
37)) {
var target = (keycode === 39) ? slider.getTarget(
'next') :
(keycode === 37) ? slider.getTarget('prev') : false;
slider.flexAnimate(target, slider.vars.pauseOnAction);
}
});
}
// MOUSEWHEEL:
if (slider.vars.mousewheel) {
slider.bind('mousewheel', function(event, delta, deltaX,
deltaY) {
event.preventDefault();
var target = (delta < 0) ? slider.getTarget('next') :
slider.getTarget('prev');
slider.flexAnimate(target, slider.vars.pauseOnAction);
});
}
// PAUSEPLAY
if (slider.vars.pausePlay) methods.pausePlay.setup();
//PAUSE WHEN INVISIBLE
if (slider.vars.slideshow && slider.vars.pauseInvisible)
methods.pauseInvisible.init();
// SLIDSESHOW
if (slider.vars.slideshow) {
if (slider.vars.pauseOnHover) {
slider.hover(function() {
if (!slider.manualPlay && !slider.manualPause) slider
.pause();
}, function() {
if (!slider.manualPause && !slider.manualPlay && !
slider.stopped) slider.play();
});
}
// initialize animation
//If we're visible, or we don't use PageVisibility API
if (!slider.vars.pauseInvisible || !methods.pauseInvisible.isHidden()) {
(slider.vars.initDelay > 0) ? slider.startTimeout =
setTimeout(slider.play, slider.vars.initDelay) : slider
.play();
}
}
// ASNAV:
if (asNav) methods.asNav.setup();
// TOUCH
if (touch && slider.vars.touch) methods.touch();
// FADE&&SMOOTHHEIGHT || SLIDE:
if (!fade || (fade && slider.vars.smoothHeight)) $(window).bind(
"resize orientationchange focus", methods.resize);
slider.find("img").attr("draggable", "false");
// API: start() Callback
setTimeout(function() {
slider.vars.start(slider);
}, 200);
},
asNav: {
setup: function() {
slider.asNav = true;
slider.animatingTo = Math.floor(slider.currentSlide /
slider.move);
slider.currentItem = slider.currentSlide;
slider.slides.removeClass(namespace + "active-slide").eq(
slider.currentItem).addClass(namespace + "active-slide");
if (!msGesture) {
slider.slides.on(eventType, function(e) {
e.preventDefault();
var $slide = $(this),
target = $slide.index();
var posFromLeft = $slide.offset().left - $(slider).scrollLeft(); // Find position of slide relative to left of slider container
if (posFromLeft <= 0 && $slide.hasClass(namespace +
'active-slide')) {
slider.flexAnimate(slider.getTarget("prev"), true);
} else if (!$(slider.vars.asNavFor).data('flexslider')
.animating && !$slide.hasClass(namespace +
"active-slide")) {
slider.direction = (slider.currentItem < target) ?
"next" : "prev";
slider.flexAnimate(target, slider.vars.pauseOnAction,
false, true, true);
}
});
} else {
el._slider = slider;
slider.slides.each(function() {
var that = this;
that._gesture = new MSGesture();
that._gesture.target = that;
that.addEventListener("MSPointerDown", function(e) {
e.preventDefault();
if (e.currentTarget._gesture)
e.currentTarget._gesture.addPointer(e.pointerId);
}, false);
that.addEventListener("MSGestureTap", function(e) {
e.preventDefault();
var $slide = $(this),
target = $slide.index();
if (!$(slider.vars.asNavFor).data('flexslider').animating &&
!$slide.hasClass('active')) {
slider.direction = (slider.currentItem < target) ?
"next" : "prev";
slider.flexAnimate(target, slider.vars.pauseOnAction,
false, true, true);
}
});
});
}
}
},
controlNav: {
setup: function() {
if (!slider.manualControls) {
methods.controlNav.setupPaging();
} else { // MANUALCONTROLS:
methods.controlNav.setupManual();
}
},
setupPaging: function() {
var type = (slider.vars.controlNav === "thumbnails") ?
'control-thumbs' : 'control-paging',
j = 1,
item,
slide;
slider.controlNavScaffold = $('<ol class="' + namespace +
'control-nav ' + namespace + type + '"></ol>');
if (slider.pagingCount > 1) {
for (var i = 0; i < slider.pagingCount; i++) {
slide = slider.slides.eq(i);
item = (slider.vars.controlNav === "thumbnails") ?
'<img src="' + slide.attr('data-thumb') + '"/>' :
'<a>' + j + '</a>';
if ('thumbnails' === slider.vars.controlNav && true ===
slider.vars.thumbCaptions) {
var captn = slide.attr('data-thumbcaption');
if ('' != captn && undefined != captn) item +=
'<span class="' + namespace + 'caption">' + captn +
'</span>';
}
// slider.controlNavScaffold.append('<li>' + item + '</li>');
slider.controlNavScaffold.append('<li>' + item +
'<i></i></li>');
j++;
}
}
// CONTROLSCONTAINER:
(slider.controlsContainer) ? $(slider.controlsContainer).append(
slider.controlNavScaffold) : slider.append(slider.controlNavScaffold);
methods.controlNav.set();
methods.controlNav.active();
slider.controlNavScaffold.delegate('a, img', eventType,
function(event) {
event.preventDefault();
if (watchedEvent === "" || watchedEvent === event.type) {
var $this = $(this),
target = slider.controlNav.index($this);
if (!$this.hasClass(namespace + 'active')) {
slider.direction = (target > slider.currentSlide) ?
"next" : "prev";
slider.flexAnimate(target, slider.vars.pauseOnAction);
}
}
// setup flags to prevent event duplication
if (watchedEvent === "") {
watchedEvent = event.type;
}
methods.setToClearWatchedEvent();
});
},
setupManual: function() {
slider.controlNav = slider.manualControls;
methods.controlNav.active();
slider.controlNav.bind(eventType, function(event) {
event.preventDefault();
if (watchedEvent === "" || watchedEvent === event.type) {
var $this = $(this),
target = slider.controlNav.index($this);
if (!$this.hasClass(namespace + 'active')) {
(target > slider.currentSlide) ? slider.direction =
"next" : slider.direction = "prev";
slider.flexAnimate(target, slider.vars.pauseOnAction);
}
}
// setup flags to prevent event duplication
if (watchedEvent === "") {
watchedEvent = event.type;
}
methods.setToClearWatchedEvent();
});
},
set: function() {
var selector = (slider.vars.controlNav === "thumbnails") ?
'img' : 'a';
slider.controlNav = $('.' + namespace + 'control-nav li ' +
selector, (slider.controlsContainer) ? slider.controlsContainer :
slider);
},
active: function() {
slider.controlNav.removeClass(namespace + "active").eq(
slider.animatingTo).addClass(namespace + "active");
},
update: function(action, pos) {
if (slider.pagingCount > 1 && action === "add") {
slider.controlNavScaffold.append($('<li><a>' + slider.count +
'</a></li>'));
} else if (slider.pagingCount === 1) {
slider.controlNavScaffold.find('li').remove();
} else {
slider.controlNav.eq(pos).closest('li').remove();
}
methods.controlNav.set();
(slider.pagingCount > 1 && slider.pagingCount !== slider.controlNav
.length) ? slider.update(pos, action) : methods.controlNav
.active();
}
},
directionNav: {
setup: function() {
var directionNavScaffold = $('<ul class="' + namespace +
'direction-nav"><li><a class="' + namespace +
'prev" href="#">' + slider.vars.prevText +
'</a></li><li><a class="' + namespace +
'next" href="#">' + slider.vars.nextText +
'</a></li></ul>');
// CONTROLSCONTAINER:
if (slider.controlsContainer) {
$(slider.controlsContainer).append(directionNavScaffold);
slider.directionNav = $('.' + namespace +
'direction-nav li a', slider.controlsContainer);
} else {
slider.append(directionNavScaffold);
slider.directionNav = $('.' + namespace +
'direction-nav li a', slider);
}
methods.directionNav.update();
slider.directionNav.bind(eventType, function(event) {
event.preventDefault();
var target;
if (watchedEvent === "" || watchedEvent === event.type) {
target = ($(this).hasClass(namespace + 'next')) ?
slider.getTarget('next') : slider.getTarget('prev');
slider.flexAnimate(target, slider.vars.pauseOnAction);
}
// setup flags to prevent event duplication
if (watchedEvent === "") {
watchedEvent = event.type;
}
methods.setToClearWatchedEvent();
});
},
update: function() {
var disabledClass = namespace + 'disabled';
if (slider.pagingCount === 1) {
slider.directionNav.addClass(disabledClass).attr(
'tabindex', '-1');
} else if (!slider.vars.animationLoop) {
if (slider.animatingTo === 0) {
slider.directionNav.removeClass(disabledClass).filter(
'.' + namespace + "prev").addClass(disabledClass).attr(
'tabindex', '-1');
} else if (slider.animatingTo === slider.last) {
slider.directionNav.removeClass(disabledClass).filter(
'.' + namespace + "next").addClass(disabledClass).attr(
'tabindex', '-1');
} else {
slider.directionNav.removeClass(disabledClass).removeAttr(
'tabindex');
}
} else {
slider.directionNav.removeClass(disabledClass).removeAttr(
'tabindex');
}
}
},
pausePlay: {
setup: function() {
var pausePlayScaffold = $('<div class="' + namespace +
'pauseplay"><a></a></div>');
// CONTROLSCONTAINER:
if (slider.controlsContainer) {
slider.controlsContainer.append(pausePlayScaffold);
slider.pausePlay = $('.' + namespace + 'pauseplay a',
slider.controlsContainer);
} else {
slider.append(pausePlayScaffold);
slider.pausePlay = $('.' + namespace + 'pauseplay a',
slider);
}
methods.pausePlay.update((slider.vars.slideshow) ?
namespace + 'pause' : namespace + 'play');
slider.pausePlay.bind(eventType, function(event) {
event.preventDefault();
if (watchedEvent === "" || watchedEvent === event.type) {
if ($(this).hasClass(namespace + 'pause')) {
slider.manualPause = true;
slider.manualPlay = false;
slider.pause();
} else {
slider.manualPause = false;
slider.manualPlay = true;
slider.play();
}
}
// setup flags to prevent event duplication
if (watchedEvent === "") {
watchedEvent = event.type;
}
methods.setToClearWatchedEvent();
});
},
update: function(state) {
(state === "play") ? slider.pausePlay.removeClass(namespace +
'pause').addClass(namespace + 'play').html(slider.vars.playText) :
slider.pausePlay.removeClass(namespace + 'play').addClass(
namespace + 'pause').html(slider.vars.pauseText);
}
},
touch: function() {
var startX,
startY,
offset,
cwidth,
dx,
startT,
scrolling = false,
localX = 0,
localY = 0,
accDx = 0;
if (!msGesture) {
el.addEventListener('touchstart', onTouchStart, false);
function onTouchStart(e) {
if (slider.animating) {
e.preventDefault();
} else if ((window.navigator.msPointerEnabled) || e.touches
.length === 1) {
slider.pause();
// CAROUSEL:
cwidth = (vertical) ? slider.h : slider.w;
startT = Number(new Date());
// CAROUSEL:
// Local vars for X and Y points.
localX = e.touches[0].pageX;
localY = e.touches[0].pageY;
offset = (carousel && reverse && slider.animatingTo ===
slider.last) ? 0 :
(carousel && reverse) ? slider.limit - (((slider.itemW +
slider.vars.itemMargin) * slider.move) * slider.animatingTo) :
(carousel && slider.currentSlide === slider.last) ?
slider.limit :
(carousel) ? ((slider.itemW + slider.vars.itemMargin) *
slider.move) * slider.currentSlide :
(reverse) ? (slider.last - slider.currentSlide +
slider.cloneOffset) * cwidth : (slider.currentSlide +
slider.cloneOffset) * cwidth;
startX = (vertical) ? localY : localX;
startY = (vertical) ? localX : localY;
el.addEventListener('touchmove', onTouchMove, false);
el.addEventListener('touchend', onTouchEnd, false);
}
}
function onTouchMove(e) {
// Local vars for X and Y points.
localX = e.touches[0].pageX;
localY = e.touches[0].pageY;
dx = (vertical) ? startX - localY : startX - localX;
scrolling = (vertical) ? (Math.abs(dx) < Math.abs(localX -
startY)) : (Math.abs(dx) < Math.abs(localY - startY));
var fxms = 500;
if (!scrolling || Number(new Date()) - startT > fxms) {
e.preventDefault();
if (!fade && slider.transitions) {
if (!slider.vars.animationLoop) {
dx = dx / ((slider.currentSlide === 0 && dx < 0 ||
slider.currentSlide === slider.last && dx > 0) ?
(Math.abs(dx) / cwidth + 2) : 1);
}
slider.setProps(offset + dx, "setTouch");
}
}
}
function onTouchEnd(e) {
// finish the touch by undoing the touch session
el.removeEventListener('touchmove', onTouchMove, false);
if (slider.animatingTo === slider.currentSlide && !
scrolling && !(dx === null)) {
var updateDx = (reverse) ? -dx : dx,
target = (updateDx > 0) ? slider.getTarget('next') :
slider.getTarget('prev');
if (slider.canAdvance(target) && (Number(new Date()) -
startT < 550 && Math.abs(updateDx) > 50 || Math.abs(
updateDx) > cwidth / 2)) {
slider.flexAnimate(target, slider.vars.pauseOnAction);
} else {
if (!fade) slider.flexAnimate(slider.currentSlide,
slider.vars.pauseOnAction, true);
}
}
el.removeEventListener('touchend', onTouchEnd, false);
startX = null;
startY = null;
dx = null;
offset = null;
}
} else {
el.style.msTouchAction = "none";
el._gesture = new MSGesture();
el._gesture.target = el;
el.addEventListener("MSPointerDown", onMSPointerDown, false);
el._slider = slider;
el.addEventListener("MSGestureChange", onMSGestureChange,
false);
el.addEventListener("MSGestureEnd", onMSGestureEnd, false);
function onMSPointerDown(e) {
e.stopPropagation();
if (slider.animating) {
e.preventDefault();
} else {
slider.pause();
el._gesture.addPointer(e.pointerId);
accDx = 0;
cwidth = (vertical) ? slider.h : slider.w;
startT = Number(new Date());
// CAROUSEL:
offset = (carousel && reverse && slider.animatingTo ===
slider.last) ? 0 :
(carousel && reverse) ? slider.limit - (((slider.itemW +
slider.vars.itemMargin) * slider.move) * slider.animatingTo) :
(carousel && slider.currentSlide === slider.last) ?
slider.limit :
(carousel) ? ((slider.itemW + slider.vars.itemMargin) *
slider.move) * slider.currentSlide :
(reverse) ? (slider.last - slider.currentSlide +
slider.cloneOffset) * cwidth : (slider.currentSlide +
slider.cloneOffset) * cwidth;
}
}
function onMSGestureChange(e) {
e.stopPropagation();
var slider = e.target._slider;
if (!slider) {
return;
}
var transX = -e.translationX,
transY = -e.translationY;
//Accumulate translations.
accDx = accDx + ((vertical) ? transY : transX);
dx = accDx;
scrolling = (vertical) ? (Math.abs(accDx) < Math.abs(-
transX)) : (Math.abs(accDx) < Math.abs(-transY));
if (e.detail === e.MSGESTURE_FLAG_INERTIA) {
setImmediate(function() {
el._gesture.stop();
});
return;
}
if (!scrolling || Number(new Date()) - startT > 500) {
e.preventDefault();
if (!fade && slider.transitions) {
if (!slider.vars.animationLoop) {
dx = accDx / ((slider.currentSlide === 0 && accDx <
0 || slider.currentSlide === slider.last &&
accDx > 0) ? (Math.abs(accDx) / cwidth + 2) : 1);
}
slider.setProps(offset + dx, "setTouch");
}
}
}
function onMSGestureEnd(e) {
e.stopPropagation();
var slider = e.target._slider;
if (!slider) {
return;
}
if (slider.animatingTo === slider.currentSlide && !
scrolling && !(dx === null)) {
var updateDx = (reverse) ? -dx : dx,
target = (updateDx > 0) ? slider.getTarget('next') :
slider.getTarget('prev');
if (slider.canAdvance(target) && (Number(new Date()) -
startT < 550 && Math.abs(updateDx) > 50 || Math.abs(
updateDx) > cwidth / 2)) {
slider.flexAnimate(target, slider.vars.pauseOnAction);
} else {
if (!fade) slider.flexAnimate(slider.currentSlide,
slider.vars.pauseOnAction, true);
}
}
startX = null;
startY = null;
dx = null;
offset = null;
accDx = 0;
}
}
},
resize: function() {
if (!slider.animating && slider.is(':visible')) {
if (!carousel) slider.doMath();
if (fade) {
// SMOOTH HEIGHT:
methods.smoothHeight();
} else if (carousel) { //CAROUSEL:
slider.slides.width(slider.computedW);
slider.update(slider.pagingCount);
slider.setProps();
} else if (vertical) { //VERTICAL:
slider.viewport.height(slider.h);
slider.setProps(slider.h, "setTotal");
} else {
// SMOOTH HEIGHT:
if (slider.vars.smoothHeight) methods.smoothHeight();
slider.newSlides.width(slider.computedW);
slider.setProps(slider.computedW, "setTotal");
}
}
},
smoothHeight: function(dur) {
if (!vertical || fade) {
var $obj = (fade) ? slider : slider.viewport;
(dur) ? $obj.animate({
"height": slider.slides.eq(slider.animatingTo).height()
}, dur) : $obj.height(slider.slides.eq(slider.animatingTo).height());
}
},
sync: function(action) {
var $obj = $(slider.vars.sync).data("flexslider"),
target = slider.animatingTo;
switch (action) {
case "animate":
$obj.flexAnimate(target, slider.vars.pauseOnAction, false,
true);
break;
case "play":
if (!$obj.playing && !$obj.asNav) {
$obj.play();
}
break;
case "pause":
$obj.pause();
break;
}
},
uniqueID: function($clone) {
// Append _clone to current level and children elements with id attributes
$clone.filter('[id]').add($clone.find('[id]')).each(function() {
var $this = $(this);
$this.attr('id', $this.attr('id') + '_clone');
});
return $clone;
},
pauseInvisible: {
visProp: null,
init: function() {
var prefixes = ['webkit', 'moz', 'ms', 'o'];
if ('hidden' in document) return 'hidden';
for (var i = 0; i < prefixes.length; i++) {
if ((prefixes[i] + 'Hidden') in document)
methods.pauseInvisible.visProp = prefixes[i] + 'Hidden';
}
if (methods.pauseInvisible.visProp) {
var evtname = methods.pauseInvisible.visProp.replace(
/[H|h]idden/, '') + 'visibilitychange';
document.addEventListener(evtname, function() {
if (methods.pauseInvisible.isHidden()) {
if (slider.startTimeout) clearTimeout(slider.startTimeout); //If clock is ticking, stop timer and prevent from starting while invisible
else slider.pause(); //Or just pause
} else {
if (slider.started) slider.play(); //Initiated before, just play
else(slider.vars.initDelay > 0) ? setTimeout(slider
.play, slider.vars.initDelay) : slider.play(); //Didn't init before: simply init or wait for it
}
});
}
},
isHidden: function() {
return document[methods.pauseInvisible.visProp] || false;
}
},
setToClearWatchedEvent: function() {
clearTimeout(watchedEventClearTimer);
watchedEventClearTimer = setTimeout(function() {
watchedEvent = "";
}, 3000);
}
};
// public methods
slider.flexAnimate = function(target, pause, override, withSync,
fromNav) {
if (!slider.vars.animationLoop && target !== slider.currentSlide) {
slider.direction = (target > slider.currentSlide) ? "next" :
"prev";
}
if (asNav && slider.pagingCount === 1) slider.direction = (
slider.currentItem < target) ? "next" : "prev";
if (!slider.animating && (slider.canAdvance(target, fromNav) ||
override) && slider.is(":visible")) {
if (asNav && withSync) {
var master = $(slider.vars.asNavFor).data('flexslider');
slider.atEnd = target === 0 || target === slider.count - 1;
master.flexAnimate(target, true, false, true, fromNav);
slider.direction = (slider.currentItem < target) ? "next" :
"prev";
master.direction = slider.direction;
if (Math.ceil((target + 1) / slider.visible) - 1 !== slider
.currentSlide && target !== 0) {
slider.currentItem = target;
slider.slides.removeClass(namespace + "active-slide").eq(
target).addClass(namespace + "active-slide");
target = Math.floor(target / slider.visible);
} else {
slider.currentItem = target;
slider.slides.removeClass(namespace + "active-slide").eq(
target).addClass(namespace + "active-slide");
return false;
}
}
slider.animating = true;
slider.animatingTo = target;
// SLIDESHOW:
if (pause) slider.pause();
// API: before() animation Callback
slider.vars.before(slider);
// SYNC:
if (slider.syncExists && !fromNav) methods.sync("animate");
// CONTROLNAV
if (slider.vars.controlNav) methods.controlNav.active();
// !CAROUSEL:
// CANDIDATE: slide active class (for add/remove slide)
if (!carousel) slider.slides.removeClass(namespace +
'active-slide').eq(target).addClass(namespace +
'active-slide');
// INFINITE LOOP:
// CANDIDATE: atEnd
slider.atEnd = target === 0 || target === slider.last;
// DIRECTIONNAV:
if (slider.vars.directionNav) methods.directionNav.update();
if (target === slider.last) {
// API: end() of cycle Callback
slider.vars.end(slider);
// SLIDESHOW && !INFINITE LOOP:
if (!slider.vars.animationLoop) slider.pause();
}
// SLIDE:
if (!fade) {
var dimension = (vertical) ? slider.slides.filter(':first')
.height() : slider.computedW,
margin, slideString, calcNext;
// INFINITE LOOP / REVERSE:
if (carousel) {
//margin = (slider.vars.itemWidth > slider.w) ? slider.vars.itemMargin * 2 : slider.vars.itemMargin;
margin = slider.vars.itemMargin;
calcNext = ((slider.itemW + margin) * slider.move) *
slider.animatingTo;
slideString = (calcNext > slider.limit && slider.visible !==
1) ? slider.limit : calcNext;
} else if (slider.currentSlide === 0 && target === slider.count -
1 && slider.vars.animationLoop && slider.direction !==
"next") {
slideString = (reverse) ? (slider.count + slider.cloneOffset) *
dimension : 0;
} else if (slider.currentSlide === slider.last && target ===
0 && slider.vars.animationLoop && slider.direction !==
"prev") {
slideString = (reverse) ? 0 : (slider.count + 1) *
dimension;
} else {
slideString = (reverse) ? ((slider.count - 1) - target +
slider.cloneOffset) * dimension : (target + slider.cloneOffset) *
dimension;
}
slider.setProps(slideString, "", slider.vars.animationSpeed);
if (slider.transitions) {
if (!slider.vars.animationLoop || !slider.atEnd) {
slider.animating = false;
slider.currentSlide = slider.animatingTo;
}
// Unbind previous transitionEnd events and re-bind new transitionEnd event
slider.container.unbind(
"webkitTransitionEnd transitionend");
slider.container.bind("webkitTransitionEnd transitionend",
function() {
clearTimeout(slider.ensureAnimationEnd);
slider.wrapup(dimension);
});
// Insurance for the ever-so-fickle transitionEnd event
clearTimeout(slider.ensureAnimationEnd);
slider.ensureAnimationEnd = setTimeout(function() {
slider.wrapup(dimension);
}, slider.vars.animationSpeed + 100);
} else {
slider.container.animate(slider.args, slider.vars.animationSpeed,
slider.vars.easing, function() {
slider.wrapup(dimension);
});
}
} else { // FADE:
if (!touch) {
//slider.slides.eq(slider.currentSlide).fadeOut(slider.vars.animationSpeed, slider.vars.easing);
//slider.slides.eq(target).fadeIn(slider.vars.animationSpeed, slider.vars.easing, slider.wrapup);
slider.slides.eq(slider.currentSlide).css({
"zIndex": 1
}).animate({
"opacity": 0
}, slider.vars.animationSpeed, slider.vars.easing);
slider.slides.eq(target).css({
"zIndex": 2
}).animate({
"opacity": 1
}, slider.vars.animationSpeed, slider.vars.easing,
slider.wrapup);
} else {
slider.slides.eq(slider.currentSlide).css({
"opacity": 0,
"zIndex": 1
});
slider.slides.eq(target).css({
"opacity": 1,
"zIndex": 2
});
slider.wrapup(dimension);
}
}
// SMOOTH HEIGHT:
if (slider.vars.smoothHeight) methods.smoothHeight(slider.vars
.animationSpeed);
}
};
slider.wrapup = function(dimension) {
// SLIDE:
if (!fade && !carousel) {
if (slider.currentSlide === 0 && slider.animatingTo ===
slider.last && slider.vars.animationLoop) {
slider.setProps(dimension, "jumpEnd");
} else if (slider.currentSlide === slider.last && slider.animatingTo ===
0 && slider.vars.animationLoop) {
slider.setProps(dimension, "jumpStart");
}
}
slider.animating = false;
slider.currentSlide = slider.animatingTo;
// API: after() animation Callback
slider.vars.after(slider);
};
// SLIDESHOW:
slider.animateSlides = function() {
if (!slider.animating && focused) slider.flexAnimate(slider.getTarget(
"next"));
};
// SLIDESHOW:
slider.pause = function() {
clearInterval(slider.animatedSlides);
slider.animatedSlides = null;
slider.playing = false;
// PAUSEPLAY:
if (slider.vars.pausePlay) methods.pausePlay.update("play");
// SYNC:
if (slider.syncExists) methods.sync("pause");
};
// SLIDESHOW:
slider.play = function() {
if (slider.playing) clearInterval(slider.animatedSlides);
slider.animatedSlides = slider.animatedSlides || setInterval(
slider.animateSlides, slider.vars.slideshowSpeed);
slider.started = slider.playing = true;
// PAUSEPLAY:
if (slider.vars.pausePlay) methods.pausePlay.update("pause");
// SYNC:
if (slider.syncExists) methods.sync("play");
};
// STOP:
slider.stop = function() {
slider.pause();
slider.stopped = true;
};
slider.canAdvance = function(target, fromNav) {
// ASNAV:
var last = (asNav) ? slider.pagingCount - 1 : slider.last;
return (fromNav) ? true :
(asNav && slider.currentItem === slider.count - 1 && target ===
0 && slider.direction === "prev") ? true :
(asNav && slider.currentItem === 0 && target === slider.pagingCount -
1 && slider.direction !== "next") ? false :
(target === slider.currentSlide && !asNav) ? false :
(slider.vars.animationLoop) ? true :
(slider.atEnd && slider.currentSlide === 0 && target === last &&
slider.direction !== "next") ? false :
(slider.atEnd && slider.currentSlide === last && target === 0 &&
slider.direction === "next") ? false :
true;
};
slider.getTarget = function(dir) {
slider.direction = dir;
if (dir === "next") {
return (slider.currentSlide === slider.last) ? 0 : slider.currentSlide +
1;
} else {
return (slider.currentSlide === 0) ? slider.last : slider.currentSlide -
1;
}
};
// SLIDE:
slider.setProps = function(pos, special, dur) {
var target = (function() {
var posCheck = (pos) ? pos : ((slider.itemW + slider.vars
.itemMargin) * slider.move) * slider.animatingTo,
posCalc = (function() {
if (carousel) {
return (special === "setTouch") ? pos :
(reverse && slider.animatingTo === slider.last) ?
0 :
(reverse) ? slider.limit - (((slider.itemW +
slider.vars.itemMargin) * slider.move) *
slider.animatingTo) :
(slider.animatingTo === slider.last) ? slider.limit :
posCheck;
} else {
switch (special) {
case "setTotal":
return (reverse) ? ((slider.count - 1) -
slider.currentSlide + slider.cloneOffset) *
pos : (slider.currentSlide + slider.cloneOffset) *
pos;
case "setTouch":
return (reverse) ? pos : pos;
case "jumpEnd":
return (reverse) ? pos : slider.count * pos;
case "jumpStart":
return (reverse) ? slider.count * pos : pos;
default:
return pos;
}
}
}());
return (posCalc * -1) + "px";
}());
if (slider.transitions) {
target = (vertical) ? "translate3d(0," + target + ",0)" :
"translate3d(" + target + ",0,0)";
dur = (dur !== undefined) ? (dur / 1000) + "s" : "0s";
slider.container.css("-" + slider.pfx +
"-transition-duration", dur);
slider.container.css("transition-duration", dur);
}
slider.args[slider.prop] = target;
if (slider.transitions || dur === undefined) slider.container.css(
slider.args);
slider.container.css('transform', target);
};
slider.setup = function(type) {
// SLIDE:
if (!fade) {
var sliderOffset, arr;
if (type === "init") {
slider.viewport = $('<div class="' + namespace +
'viewport"></div>').css({
"overflow": "hidden",
"position": "relative"
}).appendTo(slider).append(slider.container);
// INFINITE LOOP:
slider.cloneCount = 0;
slider.cloneOffset = 0;
// REVERSE:
if (reverse) {
arr = $.makeArray(slider.slides).reverse();
slider.slides = $(arr);
slider.container.empty().append(slider.slides);
}
}
// INFINITE LOOP && !CAROUSEL:
if (slider.vars.animationLoop && !carousel) {
slider.cloneCount = 2;
slider.cloneOffset = 1;
// clear out old clones
if (type !== "init") slider.container.find('.clone').remove();
slider.container.append(methods.uniqueID(slider.slides.first()
.clone().addClass('clone')).attr('aria-hidden', 'true'))
.prepend(methods.uniqueID(slider.slides.last().clone().addClass(
'clone')).attr('aria-hidden', 'true'));
}
slider.newSlides = $(slider.vars.selector, slider);
sliderOffset = (reverse) ? slider.count - 1 - slider.currentSlide +
slider.cloneOffset : slider.currentSlide + slider.cloneOffset;
// VERTICAL:
if (vertical && !carousel) {
slider.container.height((slider.count + slider.cloneCount) *
200 + "%").css("position", "absolute").width("100%");
setTimeout(function() {
slider.newSlides.css({
"display": "block"
});
slider.doMath();
slider.viewport.height(slider.h);
slider.setProps(sliderOffset * slider.h, "init");
}, (type === "init") ? 100 : 0);
} else {
slider.container.width((slider.count + slider.cloneCount) *
200 + "%");
slider.setProps(sliderOffset * slider.computedW, "init");
setTimeout(function() {
slider.doMath();
slider.newSlides.css({
"width": slider.computedW,
"float": "left",
"display": "block"
});
// SMOOTH HEIGHT:
if (slider.vars.smoothHeight) methods.smoothHeight();
}, (type === "init") ? 100 : 0);
}
} else { // FADE:
slider.slides.css({
"width": "100%",
"float": "left",
"marginRight": "-100%",
"position": "relative"
});
if (type === "init") {
if (!touch) {
//slider.slides.eq(slider.currentSlide).fadeIn(slider.vars.animationSpeed, slider.vars.easing);
if (slider.vars.fadeFirstSlide == false) {
slider.slides.css({
"opacity": 0,
"display": "block",
"zIndex": 1
}).eq(slider.currentSlide).css({
"zIndex": 2
}).css({
"opacity": 1
});
} else {
slider.slides.css({
"opacity": 0,
"display": "block",
"zIndex": 1
}).eq(slider.currentSlide).css({
"zIndex": 2
}).animate({
"opacity": 1
}, slider.vars.animationSpeed, slider.vars.easing);
}
} else {
slider.slides.css({
"opacity": 0,
"display": "block",
"webkitTransition": "opacity " + slider.vars.animationSpeed /
1000 + "s ease",
"zIndex": 1
}).eq(slider.currentSlide).css({
"opacity": 1,
"zIndex": 2
});
}
}
// SMOOTH HEIGHT:
if (slider.vars.smoothHeight) methods.smoothHeight();
}
// !CAROUSEL:
// CANDIDATE: active slide
if (!carousel) slider.slides.removeClass(namespace +
"active-slide").eq(slider.currentSlide).addClass(namespace +
"active-slide");
//FlexSlider: init() Callback
slider.vars.init(slider);
};
slider.doMath = function() {
var slide = slider.slides.first(),
slideMargin = slider.vars.itemMargin,
minItems = slider.vars.minItems,
maxItems = slider.vars.maxItems;
slider.w = (slider.viewport === undefined) ? slider.width() :
slider.viewport.width();
slider.h = slide.height();
slider.boxPadding = slide.outerWidth() - slide.width();
// CAROUSEL:
if (carousel) {
slider.itemT = slider.vars.itemWidth + slideMargin;
slider.minW = (minItems) ? minItems * slider.itemT : slider.w;
slider.maxW = (maxItems) ? (maxItems * slider.itemT) -
slideMargin : slider.w;
slider.itemW = (slider.minW > slider.w) ? (slider.w - (
slideMargin * (minItems - 1))) / minItems :
(slider.maxW < slider.w) ? (slider.w - (slideMargin * (
maxItems - 1))) / maxItems :
(slider.vars.itemWidth > slider.w) ? slider.w : slider.vars
.itemWidth;
slider.visible = Math.floor(slider.w / (slider.itemW));
slider.move = (slider.vars.move > 0 && slider.vars.move <
slider.visible) ? slider.vars.move : slider.visible;
slider.pagingCount = Math.ceil(((slider.count - slider.visible) /
slider.move) + 1);
slider.last = slider.pagingCount - 1;
slider.limit = (slider.pagingCount === 1) ? 0 :
(slider.vars.itemWidth > slider.w) ? (slider.itemW * (
slider.count - 1)) + (slideMargin * (slider.count - 1)) : (
(slider.itemW + slideMargin) * slider.count) - slider.w -
slideMargin;
} else {
slider.itemW = slider.w;
slider.pagingCount = slider.count;
slider.last = slider.count - 1;
}
slider.computedW = slider.itemW - slider.boxPadding;
};
slider.update = function(pos, action) {
slider.doMath();
// update currentSlide and slider.animatingTo if necessary
if (!carousel) {
if (pos < slider.currentSlide) {
slider.currentSlide += 1;
} else if (pos <= slider.currentSlide && pos !== 0) {
slider.currentSlide -= 1;
}
slider.animatingTo = slider.currentSlide;
}
// update controlNav
if (slider.vars.controlNav && !slider.manualControls) {
if ((action === "add" && !carousel) || slider.pagingCount >
slider.controlNav.length) {
methods.controlNav.update("add");
} else if ((action === "remove" && !carousel) || slider.pagingCount <
slider.controlNav.length) {
if (carousel && slider.currentSlide > slider.last) {
slider.currentSlide -= 1;
slider.animatingTo -= 1;
}
methods.controlNav.update("remove", slider.last);
}
}
// update directionNav
if (slider.vars.directionNav) methods.directionNav.update();
};
slider.addSlide = function(obj, pos) {
var $obj = $(obj);
slider.count += 1;
slider.last = slider.count - 1;
// append new slide
if (vertical && reverse) {
(pos !== undefined) ? slider.slides.eq(slider.count - pos).after(
$obj) : slider.container.prepend($obj);
} else {
(pos !== undefined) ? slider.slides.eq(pos).before($obj) :
slider.container.append($obj);
}
// update currentSlide, animatingTo, controlNav, and directionNav
slider.update(pos, "add");
// update slider.slides
slider.slides = $(slider.vars.selector + ':not(.clone)', slider);
// re-setup the slider to accomdate new slide
slider.setup();
//FlexSlider: added() Callback
slider.vars.added(slider);
};
slider.removeSlide = function(obj) {
var pos = (isNaN(obj)) ? slider.slides.index($(obj)) : obj;
// update count
slider.count -= 1;
slider.last = slider.count - 1;
// remove slide
if (isNaN(obj)) {
$(obj, slider.slides).remove();
} else {
(vertical && reverse) ? slider.slides.eq(slider.last).remove() :
slider.slides.eq(obj).remove();
}
// update currentSlide, animatingTo, controlNav, and directionNav
slider.doMath();
slider.update(pos, "remove");
// update slider.slides
slider.slides = $(slider.vars.selector + ':not(.clone)', slider);
// re-setup the slider to accomdate new slide
slider.setup();
// FlexSlider: removed() Callback
slider.vars.removed(slider);
};
//FlexSlider: Initialize
methods.init();
};
// Ensure the slider isn't focussed if the window loses focus.
$(window).blur(function(e) {
focused = false;
}).focus(function(e) {
focused = true;
});
// FlexSlider: Default Settings
$.flexslider.defaults = {
namespace: "am-", //{NEW} String: Prefix string attached to the class of every element generated by the plugin
selector: ".am-slides > li", //{NEW} Selector: Must match a simple pattern. '{container} > {slide}' -- Ignore pattern at your own peril
animation: "slide", //String: Select your animation type, "fade" or "slide"
easing: "swing", //{NEW} String: Determines the easing method used in jQuery transitions. jQuery easing plugin is supported!
direction: "horizontal", //String: Select the sliding direction, "horizontal" or "vertical"
reverse: false, //{NEW} Boolean: Reverse the animation direction
animationLoop: true, //Boolean: Should the animation loop? If false, directionNav will received "disable" classes at either end
smoothHeight: false, //{NEW} Boolean: Allow height of the slider to animate smoothly in horizontal mode
startAt: 0, //Integer: The slide that the slider should start on. Array notation (0 = first slide)
slideshow: true, //Boolean: Animate slider automatically
slideshowSpeed: 5000, //Integer: Set the speed of the slideshow cycling, in milliseconds
animationSpeed: 600, //Integer: Set the speed of animations, in milliseconds
initDelay: 0, //{NEW} Integer: Set an initialization delay, in milliseconds
randomize: false, //Boolean: Randomize slide order
fadeFirstSlide: true, //Boolean: Fade in the first slide when animation type is "fade"
thumbCaptions: false, //Boolean: Whether or not to put captions on thumbnails when using the "thumbnails" controlNav.
// Usability features
pauseOnAction: true, //Boolean: Pause the slideshow when interacting with control elements, highly recommended.
pauseOnHover: false, //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering
pauseInvisible: true, //{NEW} Boolean: Pause the slideshow when tab is invisible, resume when visible. Provides better UX, lower CPU usage.
useCSS: true, //{NEW} Boolean: Slider will use CSS3 transitions if available
touch: true, //{NEW} Boolean: Allow touch swipe navigation of the slider on touch-enabled devices
video: false, //{NEW} Boolean: If using video in the slider, will prevent CSS3 3D Transforms to avoid graphical glitches
// Primary Controls
controlNav: true, //Boolean: Create navigation for paging control of each slide? Note: Leave true for manualControls usage
directionNav: true, //Boolean: Create navigation for previous/next navigation? (true/false)
prevText: "Previous", //String: Set the text for the "previous" directionNav item
nextText: "Next", //String: Set the text for the "next" directionNav item
// Secondary Navigation
keyboard: true, //Boolean: Allow slider navigating via keyboard left/right keys
multipleKeyboard: false, //{NEW} Boolean: Allow keyboard navigation to affect multiple sliders. Default behavior cuts out keyboard navigation with more than one slider present.
mousewheel: false, //{UPDATED} Boolean: Requires jquery.mousewheel.js (https://github.com/brandonaaron/jquery-mousewheel) - Allows slider navigating via mousewheel
pausePlay: false, //Boolean: Create pause/play dynamic element
pauseText: "Pause", //String: Set the text for the "pause" pausePlay item
playText: "Play", //String: Set the text for the "play" pausePlay item
// Special properties
controlsContainer: "", //{UPDATED} jQuery Object/Selector: Declare which container the navigation elements should be appended too. Default container is the FlexSlider element. Example use would be $(".flexslider-container"). Property is ignored if given element is not found.
manualControls: "", //{UPDATED} jQuery Object/Selector: Declare custom control navigation. Examples would be $(".flex-control-nav li") or "#tabs-nav li img", etc. The number of elements in your controlNav should match the number of slides/tabs.
sync: "", //{NEW} Selector: Mirror the actions performed on this slider with another slider. Use with care.
asNavFor: "", //{NEW} Selector: Internal property exposed for turning the slider into a thumbnail navigation for another slider
// Carousel Options
itemWidth: 0, //{NEW} Integer: Box-model width of individual carousel items, including horizontal borders and padding.
itemMargin: 0, //{NEW} Integer: Margin between carousel items.
minItems: 1, //{NEW} Integer: Minimum number of carousel items that should be visible. Items will resize fluidly when below this.
maxItems: 0, //{NEW} Integer: Maxmimum number of carousel items that should be visible. Items will resize fluidly when above this limit.
move: 0, //{NEW} Integer: Number of carousel items that should move on animation. If 0, slider will move all visible items.
allowOneSlide: true, //{NEW} Boolean: Whether or not to allow a slider comprised of a single slide
// Callback API
start: function() {}, //Callback: function(slider) - Fires when the slider loads the first slide
before: function() {}, //Callback: function(slider) - Fires asynchronously with each slider animation
after: function() {}, //Callback: function(slider) - Fires after each slider animation completes
end: function() {}, //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous)
added: function() {}, //{NEW} Callback: function(slider) - Fires after a slide is added
removed: function() {}, //{NEW} Callback: function(slider) - Fires after a slide is removed
init: function() {} //{NEW} Callback: function(slider) - Fires after the slider is initially setup
};
// FlexSlider: Plugin Function
$.fn.flexslider = function(options) {
if (options === undefined) options = {};
if (typeof options === "object") {
return this.each(function() {
var $this = $(this),
selector = (options.selector) ? options.selector :
".am-slides > li",
$slides = $this.find(selector);
if (($slides.length === 1 && options.allowOneSlide ===
true) || $slides.length === 0) {
$slides.fadeIn(400);
if (options.start) options.start($this);
} else if ($this.data('flexslider') === undefined) {
new $.flexslider(this, options);
}
});
} else {
// Helper strings to quickly pecdrform functions on the slider
var $slider = $(this).data('flexslider');
switch (options) {
case 'play':
$slider.play();
break;
case 'pause':
$slider.pause();
break;
case 'stop':
$slider.stop();
break;
case 'next':
$slider.flexAnimate($slider.getTarget('next'), true);
break;
case 'prev':
case 'previous':
$slider.flexAnimate($slider.getTarget('prev'), true);
break;
default:
if (typeof options === 'number') {
$slider.flexAnimate(options, true);
}
}
}
};
// Init code
UI.ready(function(context) {
$('[data-am-flexslider]', context).each(function(i, item) {
var $slider = $(item);
var options = UI.utils.parseOptions($slider.data(
'amFlexslider'));
options.before = function(slider) {
if (slider._pausedTimer) {
window.clearTimeout(slider._pausedTimer);
slider._pausedTimer = null;
}
};
options.after = function(slider) {
var pauseTime = slider.vars.playAfterPaused;
if (pauseTime && !isNaN(pauseTime) && !slider.playing) {
if (!slider.manualPause && !slider.manualPlay && !
slider.stopped) {
slider._pausedTimer = window.setTimeout(function() {
slider.play();
}, pauseTime);
}
}
};
$slider.flexslider(options);
});
});
// if (!slider.manualPause && !slider.manualPlay && !slider.stopped) slider.play();
module.exports = $.flexslider;
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {
"./core": 2
}
],
9: [
function(require, module, exports) {
(function(global) {
'use strict';
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
var UI = require('./core');
var dimmer = require('./ui.dimmer');
var $doc = $(document);
var supportTransition = UI.support.transition;
/**
* @reference https://github.com/nolimits4web/Framework7/blob/master/src/js/modals.js
* @license https://github.com/nolimits4web/Framework7/blob/master/LICENSE
*/
var Modal = function(element, options) {
this.options = $.extend({}, Modal.DEFAULTS, options || {});
this.$element = $(element);
this.$dialog = this.$element.find('.am-modal-dialog');
if (!this.$element.attr('id')) {
this.$element.attr('id', UI.utils.generateGUID('am-modal'));
}
this.isPopup = this.$element.hasClass('am-popup');
this.isActions = this.$element.hasClass('am-modal-actions');
this.active = this.transitioning = this.relatedTarget = null;
this.events();
};
Modal.DEFAULTS = {
className: {
active: 'am-modal-active',
out: 'am-modal-out'
},
selector: {
modal: '.am-modal',
active: '.am-modal-active'
},
closeViaDimmer: true,
cancelable: true,
onConfirm: function() {},
onCancel: function() {},
height: undefined,
width: undefined,
duration: 300, // must equal the CSS transition duration
transitionEnd: supportTransition && supportTransition.end +
'.modal.amui'
};
Modal.prototype.toggle = function(relatedTarget) {
return this.active ? this.close() : this.open(relatedTarget);
};
Modal.prototype.open = function(relatedTarget) {
var $element = this.$element;
var options = this.options;
var isPopup = this.isPopup;
var width = options.width;
var height = options.height;
var style = {};
if (this.active) {
return;
}
if (!this.$element.length) {
return;
}
// callback hook
relatedTarget && (this.relatedTarget = relatedTarget);
// 判断如果还在动画,就先触发之前的closed事件
if (this.transitioning) {
clearTimeout($element.transitionEndTimmer);
$element.transitionEndTimmer = null;
$element.trigger(options.transitionEnd).off(options.transitionEnd);
}
isPopup && this.$element.show();
this.active = true;
$element.trigger($.Event('open.modal.amui', {
relatedTarget: relatedTarget
}));
dimmer.open($element);
$element.show().redraw();
// apply Modal width/height if set
if (!isPopup && !this.isActions) {
if (width) {
width = parseInt(width, 10);
style.width = width + 'px';
style.marginLeft = -parseInt(width / 2) + 'px';
}
if (height) {
height = parseInt(height, 10);
// style.height = height + 'px';
style.marginTop = -parseInt(height / 2) + 'px';
// the background color is styled to $dialog
// so the height should set to $dialog
this.$dialog.css({
height: height + 'px'
});
} else {
style.marginTop = -parseInt($element.height() / 2, 10) + 'px';
}
$element.css(style);
}
$element.
removeClass(options.className.out).
addClass(options.className.active);
this.transitioning = 1;
var complete = function() {
$element.trigger($.Event('opened.modal.amui', {
relatedTarget: relatedTarget
}));
this.transitioning = 0;
};
if (!supportTransition) {
return complete.call(this);
}
$element.
one(options.transitionEnd, $.proxy(complete, this)).
emulateTransitionEnd(options.duration);
};
Modal.prototype.close = function(relatedTarget) {
if (!this.active) {
return;
}
var $element = this.$element;
var options = this.options;
var isPopup = this.isPopup;
// 判断如果还在动画,就先触发之前的opened事件
if (this.transitioning) {
clearTimeout($element.transitionEndTimmer);
$element.transitionEndTimmer = null;
$element.trigger(options.transitionEnd).off(options.transitionEnd);
dimmer.close($element, true);
}
this.$element.trigger($.Event('close.modal.amui', {
relatedTarget: relatedTarget
}));
this.transitioning = 1;
var complete = function() {
$element.trigger('closed.modal.amui');
isPopup && $element.removeClass(options.className.out);
$element.hide();
this.transitioning = 0;
// 不强制关闭 Dimmer,以便多个 Modal 可以共享 Dimmer
dimmer.close($element, false);
this.active = false;
};
$element.removeClass(options.className.active).
addClass(options.className.out);
if (!supportTransition) {
return complete.call(this);
}
$element.one(options.transitionEnd, $.proxy(complete, this)).
emulateTransitionEnd(options.duration);
};
Modal.prototype.events = function() {
var that = this;
var $element = this.$element;
var $ipt = $element.find('.am-modal-prompt-input');
var getData = function() {
var data = [];
$ipt.each(function() {
data.push($(this).val());
});
return (data.length === 0) ? undefined :
((data.length === 1) ? data[0] : data);
};
// close via Esc key
if (this.options.cancelable) {
$element.on('keyup.modal.amui', function(e) {
if (that.active && e.which === 27) {
$element.trigger('cancel.modal.amui');
that.close();
}
});
}
// Close Modal when dimmer clicked
if (this.options.closeViaDimmer) {
dimmer.$element.on('click.dimmer.modal.amui', function(e) {
that.close();
});
}
// Close Modal when button clicked
$element.find('[data-am-modal-close], .am-modal-btn').
on('click.close.modal.amui', function(e) {
e.preventDefault();
that.close();
});
$element.find('[data-am-modal-confirm]').on(
'click.confirm.modal.amui',
function() {
$element.trigger($.Event('confirm.modal.amui', {
trigger: this
}));
});
$element.find('[data-am-modal-cancel]').
on('click.cancel.modal.amui', function() {
$element.trigger($.Event('cancel.modal.amui', {
trigger: this
}));
});
$element.on('confirm.modal.amui', function(e) {
e.data = getData();
that.options.onConfirm.call(that, e);
}).on('cancel.modal.amui', function(e) {
e.data = getData();
that.options.onCancel.call(that, e);
});
};
function Plugin(option, relatedTarget) {
return this.each(function() {
var $this = $(this);
var data = $this.data('amui.modal');
var options = $.extend({},
Modal.DEFAULTS, typeof option == 'object' && option);
if (!data) {
$this.data('amui.modal', (data = new Modal(this, options)));
}
if (typeof option == 'string') {
data[option] && data[option](relatedTarget);
} else {
data.toggle(option && option.relatedTarget || undefined);
}
});
}
$.fn.modal = Plugin;
// Init
$doc.on('click.modal.amui.data-api', '[data-am-modal]', function() {
var $this = $(this);
var options = UI.utils.parseOptions($this.attr('data-am-modal'));
var $target = $(options.target ||
(this.href && this.href.replace(/.*(?=#[^\s]+$)/, '')));
var option = $target.data('amui.modal') ? 'toggle' : options;
Plugin.call($target, option, this);
});
$.AMUI.modal = Modal;
module.exports = Modal;
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {
"./core": 2,
"./ui.dimmer": 6
}
],
10: [
function(require, module, exports) {
(function(global) {
'use strict';
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
var UI = require('./core');
var Hammer = require('./util.hammer');
var $win = $(window);
var $doc = $(document);
var scrollPos;
/**
* @via https://github.com/uikit/uikit/blob/master/src/js/offcanvas.js
* @license https://github.com/uikit/uikit/blob/master/LICENSE.md
*/
var OffCanvas = function(element, options) {
this.$element = $(element);
this.options = $.extend({}, OffCanvas.DEFAULTS, options);
this.active = null;
this.bindEvents();
};
OffCanvas.DEFAULTS = {
duration: 300,
effect: 'overlay' // {push|overlay}, push is too expensive
};
OffCanvas.prototype.open = function(relatedElement) {
var _this = this;
var $element = this.$element;
if (!$element.length || $element.hasClass('am-active')) {
return;
}
var effect = this.options.effect;
var $html = $('html');
var $body = $('body');
var $bar = $element.find('.am-offcanvas-bar').first();
var dir = $bar.hasClass('am-offcanvas-bar-flip') ? -1 : 1;
$bar.addClass('am-offcanvas-bar-' + effect);
scrollPos = {
x: window.scrollX,
y: window.scrollY
};
$element.addClass('am-active');
$body.css({
width: window.innerWidth,
height: $win.height()
}).addClass('am-offcanvas-page');
if (effect !== 'overlay') {
$body.css({
'margin-left': $bar.outerWidth() * dir
}).width(); // force redraw
}
$html.css('margin-top', scrollPos.y * -1);
setTimeout(function() {
$bar.addClass('am-offcanvas-bar-active').width();
}, 0);
$element.trigger('open.offcanvas.amui');
this.active = 1;
// Close OffCanvas when none content area clicked
$element.on('click.offcanvas.amui', function(e) {
var $target = $(e.target);
if ($target.hasClass('am-offcanvas-bar')) {
return;
}
if ($target.parents('.am-offcanvas-bar').first().length) {
return;
}
// https://developer.mozilla.org/zh-CN/docs/DOM/event.stopImmediatePropagation
e.stopImmediatePropagation();
_this.close();
});
$html.on('keydown.offcanvas.amui', function(e) {
(e.keyCode === 27) && _this.close();
});
};
OffCanvas.prototype.close = function(relatedElement) {
var _this = this;
var $html = $('html');
var $body = $('body');
var $element = this.$element;
var $bar = $element.find('.am-offcanvas-bar').first();
if (!$element.length || !this.active || !$element.hasClass(
'am-active')) {
return;
}
$element.trigger('close.offcanvas.amui');
function complete() {
$body.removeClass('am-offcanvas-page').
css({
width: '',
height: '',
'margin-left': '',
'margin-right': ''
});
$element.removeClass('am-active');
$bar.removeClass('am-offcanvas-bar-active');
$html.css('margin-top', '');
window.scrollTo(scrollPos.x, scrollPos.y);
$element.trigger('closed.offcanvas.amui');
_this.active = 0;
}
if (UI.support.transition) {
setTimeout(function() {
$bar.removeClass('am-offcanvas-bar-active');
}, 0);
$body.css('margin-left', '').one(UI.support.transition.end,
function() {
complete();
}).emulateTransitionEnd(this.options.duration);
} else {
complete();
}
$element.off('click.offcanvas.amui');
$html.off('.offcanvas.amui');
};
OffCanvas.prototype.bindEvents = function() {
var _this = this;
$doc.on('click.offcanvas.amui', '[data-am-dismiss="offcanvas"]',
function(e) {
e.preventDefault();
_this.close();
});
$win.on('resize.offcanvas.amui orientationchange.offcanvas.amui',
function() {
_this.active && _this.close();
});
this.$element.hammer().on('swipeleft swipeleft', function(e) {
e.preventDefault();
_this.close();
});
return this;
};
function Plugin(option, relatedElement) {
return this.each(function() {
var $this = $(this);
var data = $this.data('amui.offcanvas');
var options = $.extend({}, typeof option == 'object' &&
option);
if (!data) {
$this.data('amui.offcanvas', (data = new OffCanvas(this,
options)));
(!option || typeof option == 'object') && data.open(
relatedElement);
}
if (typeof option == 'string') {
data[option] && data[option](relatedElement);
}
});
}
$.fn.offCanvas = Plugin;
// Init code
$doc.on('click.offcanvas.amui', '[data-am-offcanvas]', function(e) {
e.preventDefault();
var $this = $(this);
var options = UI.utils.parseOptions($this.data('amOffcanvas'));
var $target = $(options.target ||
(this.href && this.href.replace(/.*(?=#[^\s]+$)/, '')));
var option = $target.data('amui.offcanvas') ? 'open' : options;
Plugin.call($target, option, this);
});
$.AMUI.offcanvas = OffCanvas;
module.exports = OffCanvas;
// TODO: 优化动画效果
// http://dbushell.github.io/Responsive-Off-Canvas-Menu/step4.html
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {
"./core": 2,
"./util.hammer": 17
}
],
11: [
function(require, module, exports) {
(function(global) {
'use strict';
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
var UI = require('./core');
var $w = $(window);
/**
* @reference https://github.com/nolimits4web/Framework7/blob/master/src/js/modals.js
* @license https://github.com/nolimits4web/Framework7/blob/master/LICENSE
*/
var Popover = function(element, options) {
this.options = $.extend({}, Popover.DEFAULTS, options || {});
this.$element = $(element);
this.active = null;
this.$popover = (this.options.target && $(this.options.target)) ||
null;
this.init();
this.events();
};
Popover.DEFAULTS = {
theme: undefined,
trigger: 'click',
content: '',
open: false,
target: undefined,
tpl: '<div class="am-popover">' +
'<div class="am-popover-inner"></div>' +
'<div class="am-popover-caret"></div></div>'
};
Popover.prototype.init = function() {
var me = this;
var $element = this.$element;
var $popover;
if (!this.options.target) {
this.$popover = this.getPopover();
this.setContent();
}
$popover = this.$popover;
$popover.appendTo($('body'));
this.sizePopover();
function sizePopover() {
me.sizePopover();
}
// TODO: 监听页面内容变化,重新调整位置
$element.on('open.popover.amui', function() {
$(window).on('resize.popover.amui', UI.utils.debounce(
sizePopover, 50));
});
$element.on('close.popover.amui', function() {
$(window).off('resize.popover.amui', sizePopover);
});
this.options.open && this.open();
};
Popover.prototype.sizePopover = function sizePopover() {
var $element = this.$element;
var $popover = this.$popover;
if (!$popover || !$popover.length) {
return;
}
var popWidth = $popover.outerWidth();
var popHeight = $popover.outerHeight();
var $popCaret = $popover.find('.am-popover-caret');
var popCaretSize = ($popCaret.outerWidth() / 2) || 8;
// 取不到 $popCaret.outerHeight() 的值,所以直接加 8
var popTotalHeight = popHeight + 8; // $popCaret.outerHeight();
var triggerWidth = $element.outerWidth();
var triggerHeight = $element.outerHeight();
var triggerOffset = $element.offset();
var triggerRect = $element[0].getBoundingClientRect();
var winHeight = $w.height();
var winWidth = $w.width();
var popTop = 0;
var popLeft = 0;
var diff = 0;
var spacing = 2;
var popPosition = 'top';
$popover.css({
left: '',
top: ''
}).removeClass('am-popover-left ' +
'am-popover-right am-popover-top am-popover-bottom');
$popCaret.css({
left: '',
top: ''
});
if (popTotalHeight - spacing < triggerRect.top + spacing) {
// Popover on the top of trigger
popTop = triggerOffset.top - popTotalHeight - spacing;
} else if (popTotalHeight <
winHeight - triggerRect.top - triggerRect.height) {
// On bottom
popPosition = 'bottom';
popTop = triggerOffset.top + triggerHeight + popCaretSize +
spacing;
} else { // On middle
popPosition = 'middle';
popTop = triggerHeight / 2 + triggerOffset.top - popHeight / 2;
}
// Horizontal Position
if (popPosition === 'top' || popPosition === 'bottom') {
popLeft = triggerWidth / 2 + triggerOffset.left - popWidth / 2;
diff = popLeft;
if (popLeft < 5) {
popLeft = 5;
}
if (popLeft + popWidth > winWidth) {
popLeft = (winWidth - popWidth - 20);
// console.log('left %d, win %d, popw %d', popLeft, winWidth, popWidth);
}
if (popPosition === 'top') {
// This is the Popover position, NOT caret position
// Popover on the Top of trigger, caret on the bottom of Popover
$popover.addClass('am-popover-top');
}
if (popPosition === 'bottom') {
$popover.addClass('am-popover-bottom');
}
diff = diff - popLeft;
$popCaret.css({
left: (popWidth / 2 - popCaretSize + diff) + 'px'
});
} else if (popPosition === 'middle') {
popLeft = triggerOffset.left - popWidth - popCaretSize;
$popover.addClass('am-popover-left');
if (popLeft < 5) {
popLeft = triggerOffset.left + triggerWidth + popCaretSize;
$popover.removeClass('am-popover-left').addClass(
'am-popover-right');
}
if (popLeft + popWidth > winWidth) {
popLeft = winWidth - popWidth - 5;
$popover.removeClass('am-popover-left').addClass(
'am-popover-right');
}
$popCaret.css({
top: (popHeight / 2 - popCaretSize / 2) + 'px'
});
}
// Apply position style
$popover.css({
top: popTop + 'px',
left: popLeft + 'px'
});
};
Popover.prototype.toggle = function() {
return this[this.active ? 'close' : 'open']();
};
Popover.prototype.open = function() {
var $popover = this.$popover;
this.$element.trigger('open.popover.amui');
this.sizePopover();
$popover.show().addClass('am-active');
this.active = true;
};
Popover.prototype.close = function() {
var $popover = this.$popover;
this.$element.trigger('close.popover.amui');
$popover.
removeClass('am-active').
trigger('closed.popover.amui').
hide();
this.active = false;
};
Popover.prototype.getPopover = function() {
var uid = UI.utils.generateGUID('am-popover');
var theme = [];
if (this.options.theme) {
$.each(this.options.theme.split(','), function(i, item) {
theme.push('am-popover-' + $.trim(item));
});
}
return $(this.options.tpl).attr('id', uid).addClass(theme.join(
' '));
};
Popover.prototype.setContent = function(content) {
content = content || this.options.content;
this.$popover && this.$popover.find('.am-popover-inner').empty().
html(content);
};
Popover.prototype.events = function() {
var eventNS = 'popover.amui';
var triggers = this.options.trigger.split(' ');
for (var i = triggers.length; i--;) {
var trigger = triggers[i];
if (trigger === 'click') {
this.$element.on('click.' + eventNS, $.proxy(this.toggle,
this));
} else { // hover or focus
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin';
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout';
this.$element.on(eventIn + '.' + eventNS, $.proxy(this.open,
this));
this.$element.on(eventOut + '.' + eventNS, $.proxy(this.close,
this));
}
}
};
function Plugin(option) {
return this.each(function() {
var $this = $(this);
var data = $this.data('amui.popover');
var options = $.extend({},
UI.utils.parseOptions($this.attr('data-am-popover')),
typeof option == 'object' && option);
if (!data) {
$this.data('amui.popover', (data = new Popover(this,
options)));
}
if (typeof option == 'string') {
data[option] && data[option]();
}
});
}
$.fn.popover = Plugin;
// Init code
UI.ready(function(context) {
$('[data-am-popover]', context).popover();
});
$.AMUI.popover = Popover;
module.exports = Popover;
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {
"./core": 2
}
],
12: [
function(require, module, exports) {
(function(global) {
'use strict';
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
var UI = require('./core');
var Progress = (function() {
/**
* NProgress (c) 2013, Rico Sta. Cruz
* @via http://ricostacruz.com/nprogress
*/
var NProgress = {};
var $html = $('html');
NProgress.version = '0.1.6';
var Settings = NProgress.settings = {
minimum: 0.08,
easing: 'ease',
positionUsing: '',
speed: 200,
trickle: true,
trickleRate: 0.02,
trickleSpeed: 800,
showSpinner: true,
parent: 'body',
barSelector: '[role="nprogress-bar"]',
spinnerSelector: '[role="nprogress-spinner"]',
template: '<div class="nprogress-bar" role="nprogress-bar">' +
'<div class="nprogress-peg"></div></div>' +
'<div class="nprogress-spinner" role="nprogress-spinner">' +
'<div class="nprogress-spinner-icon"></div></div>'
};
/**
* Updates configuration.
*
* NProgress.configure({
* minimum: 0.1
* });
*/
NProgress.configure = function(options) {
var key, value;
for (key in options) {
value = options[key];
if (value !== undefined && options.hasOwnProperty(key))
Settings[key] = value;
}
return this;
};
/**
* Last number.
*/
NProgress.status = null;
/**
* Sets the progress bar status, where `n` is a number from `0.0` to `1.0`.
*
* NProgress.set(0.4);
* NProgress.set(1.0);
*/
NProgress.set = function(n) {
var started = NProgress.isStarted();
n = clamp(n, Settings.minimum, 1);
NProgress.status = (n === 1 ? null : n);
var progress = NProgress.render(!started),
bar = progress.querySelector(Settings.barSelector),
speed = Settings.speed,
ease = Settings.easing;
progress.offsetWidth;
/* Repaint */
queue(function(next) {
// Set positionUsing if it hasn't already been set
if (Settings.positionUsing === '') Settings.positionUsing =
NProgress.getPositioningCSS();
// Add transition
css(bar, barPositionCSS(n, speed, ease));
if (n === 1) {
// Fade out
css(progress, {
transition: 'none',
opacity: 1
});
progress.offsetWidth;
/* Repaint */
setTimeout(function() {
css(progress, {
transition: 'all ' + speed + 'ms linear',
opacity: 0
});
setTimeout(function() {
NProgress.remove();
next();
}, speed);
}, speed);
} else {
setTimeout(next, speed);
}
});
return this;
};
NProgress.isStarted = function() {
return typeof NProgress.status === 'number';
};
/**
* Shows the progress bar.
* This is the same as setting the status to 0%, except that it doesn't go backwards.
*
* NProgress.start();
*
*/
NProgress.start = function() {
if (!NProgress.status) NProgress.set(0);
var work = function() {
setTimeout(function() {
if (!NProgress.status) return;
NProgress.trickle();
work();
}, Settings.trickleSpeed);
};
if (Settings.trickle) work();
return this;
};
/**
* Hides the progress bar.
* This is the *sort of* the same as setting the status to 100%, with the
* difference being `done()` makes some placebo effect of some realistic motion.
*
* NProgress.done();
*
* If `true` is passed, it will show the progress bar even if its hidden.
*
* NProgress.done(true);
*/
NProgress.done = function(force) {
if (!force && !NProgress.status) return this;
return NProgress.inc(0.3 + 0.5 * Math.random()).set(1);
};
/**
* Increments by a random amount.
*/
NProgress.inc = function(amount) {
var n = NProgress.status;
if (!n) {
return NProgress.start();
} else {
if (typeof amount !== 'number') {
amount = (1 - n) * clamp(Math.random() * n, 0.1, 0.95);
}
n = clamp(n + amount, 0, 0.994);
return NProgress.set(n);
}
};
NProgress.trickle = function() {
return NProgress.inc(Math.random() * Settings.trickleRate);
};
/**
* (Internal) renders the progress bar markup based on the `template`
* setting.
*/
NProgress.render = function(fromStart) {
if (NProgress.isRendered()) return document.getElementById(
'nprogress');
$html.addClass('nprogress-busy');
var progress = document.createElement('div');
progress.id = 'nprogress';
progress.innerHTML = Settings.template;
var bar = progress.querySelector(Settings.barSelector),
perc = fromStart ? '-100' : toBarPerc(NProgress.status ||
0),
parent = document.querySelector(Settings.parent),
spinner;
css(bar, {
transition: 'all 0 linear',
transform: 'translate3d(' + perc + '%,0,0)'
});
if (!Settings.showSpinner) {
spinner = progress.querySelector(Settings.spinnerSelector);
spinner && $(spinner).remove();
}
if (parent != document.body) {
$(parent).addClass('nprogress-custom-parent');
}
parent.appendChild(progress);
return progress;
};
/**
* Removes the element. Opposite of render().
*/
NProgress.remove = function() {
$html.removeClass('nprogress-busy');
$(Settings.parent).removeClass('nprogress-custom-parent');
var progress = document.getElementById('nprogress');
progress && $(progress).remove();
};
/**
* Checks if the progress bar is rendered.
*/
NProgress.isRendered = function() {
return !!document.getElementById('nprogress');
};
/**
* Determine which positioning CSS rule to use.
*/
NProgress.getPositioningCSS = function() {
// Sniff on document.body.style
var bodyStyle = document.body.style;
// Sniff prefixes
var vendorPrefix = ('WebkitTransform' in bodyStyle) ?
'Webkit' :
('MozTransform' in bodyStyle) ? 'Moz' :
('msTransform' in bodyStyle) ? 'ms' :
('OTransform' in bodyStyle) ? 'O' : '';
if (vendorPrefix + 'Perspective' in bodyStyle) {
// Modern browsers with 3D support, e.g. Webkit, IE10
return 'translate3d';
} else if (vendorPrefix + 'Transform' in bodyStyle) {
// Browsers without 3D support, e.g. IE9
return 'translate';
} else {
// Browsers without translate() support, e.g. IE7-8
return 'margin';
}
};
/**
* Helpers
*/
function clamp(n, min, max) {
if (n < min) return min;
if (n > max) return max;
return n;
}
/**
* (Internal) converts a percentage (`0..1`) to a bar translateX
* percentage (`-100%..0%`).
*/
function toBarPerc(n) {
return (-1 + n) * 100;
}
/**
* (Internal) returns the correct CSS for changing the bar's
* position given an n percentage, and speed and ease from Settings
*/
function barPositionCSS(n, speed, ease) {
var barCSS;
if (Settings.positionUsing === 'translate3d') {
barCSS = {
transform: 'translate3d(' + toBarPerc(n) + '%,0,0)'
};
} else if (Settings.positionUsing === 'translate') {
barCSS = {
transform: 'translate(' + toBarPerc(n) + '%,0)'
};
} else {
barCSS = {
'margin-left': toBarPerc(n) + '%'
};
}
barCSS.transition = 'all ' + speed + 'ms ' + ease;
return barCSS;
}
/**
* (Internal) Queues a function to be executed.
*/
var queue = (function() {
var pending = [];
function next() {
var fn = pending.shift();
if (fn) {
fn(next);
}
}
return function(fn) {
pending.push(fn);
if (pending.length == 1) next();
};
})();
/**
* (Internal) Applies css properties to an element, similar to the jQuery
* css method.
*
* While this helper does assist with vendor prefixed property names, it
* does not perform any manipulation of values prior to setting styles.
*/
var css = (function() {
var cssPrefixes = ['Webkit', 'O', 'Moz', 'ms'],
cssProps = {};
function camelCase(string) {
return string.replace(/^-ms-/, 'ms-').replace(
/-([\da-z])/gi, function(match, letter) {
return letter.toUpperCase();
});
}
function getVendorProp(name) {
var style = document.body.style;
if (name in style) return name;
var i = cssPrefixes.length,
capName = name.charAt(0).toUpperCase() + name.slice(
1),
vendorName;
while (i--) {
vendorName = cssPrefixes[i] + capName;
if (vendorName in style) return vendorName;
}
return name;
}
function getStyleProp(name) {
name = camelCase(name);
return cssProps[name] || (cssProps[name] =
getVendorProp(name));
}
function applyCss(element, prop, value) {
prop = getStyleProp(prop);
element.style[prop] = value;
}
return function(element, properties) {
var args = arguments,
prop,
value;
if (args.length == 2) {
for (prop in properties) {
value = properties[prop];
if (value !== undefined && properties.hasOwnProperty(
prop)) applyCss(element, prop, value);
}
} else {
applyCss(element, args[1], args[2]);
}
}
})();
return NProgress;
})();
$.AMUI.progress = Progress;
module.exports = Progress;
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {
"./core": 2
}
],
13: [
function(require, module, exports) {
(function(global) {
'use strict';
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
var UI = require('./core');
require('./ui.smooth-scroll');
/**
* @via https://github.com/uikit/uikit/
* @license https://github.com/uikit/uikit/blob/master/LICENSE.md
*/
// ScrollSpyNav Class
var ScrollSpyNav = function(element, options) {
this.options = $.extend({}, ScrollSpyNav.DEFAULTS, options);
this.$element = $(element);
this.anchors = [];
this.$links = this.$element.find('a[href^="#"]').each(function(
i, link) {
this.anchors.push($(link).attr('href'));
}.bind(this));
this.$targets = $(this.anchors.join(', '));
var processRAF = function() {
UI.utils.rAF.call(window, $.proxy(this.process, this));
}.bind(this);
this.$window = $(window).on('scroll.scrollspynav.amui',
processRAF)
.on(
'resize.scrollspynav.amui orientationchange.scrollspynav.amui',
UI.utils.debounce(processRAF, 50));
processRAF();
this.scrollProcess();
};
ScrollSpyNav.DEFAULTS = {
className: {
active: 'am-active'
},
closest: false,
smooth: true,
offsetTop: 0
};
ScrollSpyNav.prototype.process = function() {
var scrollTop = this.$window.scrollTop();
var options = this.options;
var inViews = [];
var $links = this.$links;
var $targets = this.$targets;
$targets.each(function(i, target) {
if (UI.utils.isInView(target, options)) {
inViews.push(target);
}
});
// console.log(inViews.length);
if (inViews.length) {
var $target;
$.each(inViews, function(i, item) {
if ($(item).offset().top >= scrollTop) {
$target = $(item);
return false; // break
}
});
if (!$target) {
return;
}
if (options.closest) {
$links.closest(options.closest).removeClass(options.className
.active);
$links.filter('a[href="#' + $target.attr('id') + '"]').
closest(options.closest).addClass(options.className.active);
} else {
$links.removeClass(options.className.active).
filter('a[href="#' + $target.attr('id') + '"]').
addClass(options.className.active);
}
}
};
ScrollSpyNav.prototype.scrollProcess = function() {
var $links = this.$links;
var options = this.options;
// smoothScroll
if (options.smooth) {
$links.on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $target = $($this.attr('href'));
if (!$target) {
return;
}
var offsetTop = options.offsetTop &&
!isNaN(parseInt(options.offsetTop)) && parseInt(options.offsetTop) ||
0;
$(window).smoothScroll({
position: $target.offset().top - offsetTop
});
});
}
};
// ScrollSpyNav Plugin
function Plugin(option) {
return this.each(function() {
var $this = $(this);
var data = $this.data('amui.scrollspynav');
var options = typeof option == 'object' && option;
if (!data) {
$this.data('amui.scrollspynav', (data = new ScrollSpyNav(
this, options)));
}
if (typeof option == 'string') {
data[option]();
}
});
}
$.fn.scrollspynav = Plugin;
// Init code
UI.ready(function(context) {
$('[data-am-scrollspy-nav]', context).each(function() {
var $this = $(this);
var options = UI.utils.options($this.data('amScrollspyNav'));
Plugin.call($this, options);
});
});
$.AMUI.scrollspynav = ScrollSpyNav;
module.exports = ScrollSpyNav;
// TODO: 1. 算法改进
// 2. 多级菜单支持
// 3. smooth scroll pushState
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {
"./core": 2,
"./ui.smooth-scroll": 14
}
],
14: [
function(require, module, exports) {
(function(global) {
'use strict';
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
var UI = require('./core');
var rAF = UI.utils.rAF;
var cAF = UI.utils.cancelAF;
/**
* Smooth Scroll
* @param position
* @via http://mir.aculo.us/2014/01/19/scrolling-dom-elements-to-the-top-a-zepto-plugin/
*/
// Usage: $(window).smoothScroll([options])
// only allow one scroll to top operation to be in progress at a time,
// which is probably what you want
var smoothScrollInProgress = false;
var SmoothScroll = function(element, options) {
options = options || {};
var $this = $(element);
var targetY = parseInt(options.position) || SmoothScroll.DEFAULTS
.position;
var initialY = $this.scrollTop();
var lastY = initialY;
var delta = targetY - initialY;
// duration in ms, make it a bit shorter for short distances
// this is not scientific and you might want to adjust this for
// your preferences
var speed = options.speed ||
Math.min(750, Math.min(1500, Math.abs(initialY - targetY)));
// temp variables (t will be a position between 0 and 1, y is the calculated scrollTop)
var start;
var t;
var y;
var cancelScroll = function() {
abort();
};
// abort if already in progress or nothing to scroll
if (smoothScrollInProgress) {
return;
}
if (delta === 0) {
return;
}
// quint ease-in-out smoothing, from
// https://github.com/madrobby/scripty2/blob/master/src/effects/transitions/penner.js#L127-L136
function smooth(pos) {
if ((pos /= 0.5) < 1) {
return 0.5 * Math.pow(pos, 5);
}
return 0.5 * (Math.pow((pos - 2), 5) + 2);
}
function abort() {
$this.off('touchstart.smoothscroll.amui', cancelScroll);
smoothScrollInProgress = false;
}
// when there's a touch detected while scrolling is in progress, abort
// the scrolling (emulates native scrolling behavior)
$this.on('touchstart.smoothscroll.amui', cancelScroll);
smoothScrollInProgress = true;
// start rendering away! note the function given to frame
// is named "render" so we can reference it again further down
function render(now) {
if (!smoothScrollInProgress) {
return;
}
if (!start) {
start = now;
}
// calculate t, position of animation in [0..1]
t = Math.min(1, Math.max((now - start) / speed, 0));
// calculate the new scrollTop position (don't forget to smooth)
y = Math.round(initialY + delta * smooth(t));
// bracket scrollTop so we're never over-scrolling
if (delta > 0 && y > targetY) {
y = targetY;
}
if (delta < 0 && y < targetY) {
y = targetY;
}
// only actually set scrollTop if there was a change fromt he last frame
if (lastY != y) {
$this.scrollTop(y);
}
lastY = y;
// if we're not done yet, queue up an other frame to render,
// or clean up
if (y !== targetY) {
cAF(scrollRAF);
scrollRAF = rAF(render);
} else {
cAF(scrollRAF);
abort();
}
}
var scrollRAF = rAF(render);
};
SmoothScroll.DEFAULTS = {
position: 0
};
$.fn.smoothScroll = function(option) {
return this.each(function() {
new SmoothScroll(this, option);
});
};
// Init code
$(document).on('click.smoothScroll.amui.data-api',
'[data-am-smooth-scroll]',
function(e) {
e.preventDefault();
var options = UI.utils.parseOptions($(this).data(
'amSmoothScroll'));
$(window).smoothScroll(options);
});
module.exports = SmoothScroll;
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {
"./core": 2
}
],
15: [
function(require, module, exports) {
(function(global) {
'use strict';
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
var UI = require('./core');
/**
* @via https://github.com/uikit/uikit/blob/master/src/js/addons/sticky.js
* @license https://github.com/uikit/uikit/blob/master/LICENSE.md
*/
// Sticky Class
var Sticky = function(element, options) {
var me = this;
this.options = $.extend({}, Sticky.DEFAULTS, options);
this.$element = $(element);
this.sticked = null;
this.inited = null;
this.$holder = undefined;
this.$window = $(window).
on('scroll.sticky.amui',
UI.utils.debounce($.proxy(this.checkPosition, this), 10)).
on('resize.sticky.amui orientationchange.sticky.amui',
UI.utils.debounce(function() {
me.reset(true, function() {
me.checkPosition();
});
}, 50)).
on('load.sticky.amui', $.proxy(this.checkPosition, this));
// the `.offset()` is diff between jQuery & Zepto.js
// jQuery: return `top` and `left`
// Zepto.js: return `top`, `left`, `width`, `height`
this.offset = this.$element.offset();
this.init();
};
Sticky.DEFAULTS = {
top: 0,
bottom: 0,
animation: '',
className: {
sticky: 'am-sticky',
resetting: 'am-sticky-resetting',
stickyBtm: 'am-sticky-bottom',
animationRev: 'am-animation-reverse'
}
};
Sticky.prototype.init = function() {
var result = this.check();
if (!result) {
return false;
}
var $element = this.$element;
var $holder = $('<div class="am-sticky-placeholder"></div>').css({
height: $element.css('position') != 'absolute' ?
$element.outerHeight() : '',
float: $element.css('float') != 'none' ? $element.css(
'float') : '',
margin: $element.css('margin')
});
this.$holder = $element.css('margin', 0).wrap($holder).parent();
this.inited = 1;
return true;
};
Sticky.prototype.reset = function(force, cb) {
var options = this.options;
var $element = this.$element;
var animation = (options.animation) ?
' am-animation-' + options.animation : '';
var complete = function() {
$element.css({
position: '',
top: '',
width: '',
left: '',
margin: 0
});
$element.removeClass([
animation,
options.className.animationRev,
options.className.sticky,
options.className.resetting
].join(' '));
this.animating = false;
this.sticked = false;
this.offset = $element.offset();
cb && cb();
}.bind(this);
$element.addClass(options.className.resetting);
if (!force && options.animation && UI.support.animation) {
this.animating = true;
$element.removeClass(animation).one(UI.support.animation.end,
function() {
complete();
}).width(); // force redraw
$element.addClass(animation + ' ' + options.className.animationRev);
} else {
complete();
}
};
Sticky.prototype.check = function() {
if (!this.$element.is(':visible')) {
return false;
}
var media = this.options.media;
if (media) {
switch (typeof(media)) {
case 'number':
if (window.innerWidth < media) {
return false;
}
break;
case 'string':
if (window.matchMedia && !window.matchMedia(media).matches) {
return false;
}
break;
}
}
return true;
};
Sticky.prototype.checkPosition = function() {
if (!this.inited) {
var initialized = this.init();
if (!initialized) {
return;
}
}
var options = this.options;
var scrollTop = this.$window.scrollTop();
var offsetTop = options.top;
var offsetBottom = options.bottom;
var $element = this.$element;
var animation = (options.animation) ?
' am-animation-' + options.animation : '';
var className = [options.className.sticky, animation].join(' ');
if (typeof offsetBottom == 'function') {
offsetBottom = offsetBottom(this.$element);
}
var checkResult = (scrollTop > this.$holder.offset().top);
if (!this.sticked && checkResult) {
$element.addClass(className);
} else if (this.sticked && !checkResult) {
this.reset();
}
this.$holder.height($element.is(':visible') ? $element.height() :
0);
if (checkResult) {
$element.css({
top: offsetTop,
left: this.$holder.offset().left,
width: this.$holder.width()
});
/*
if (offsetBottom) {
// (底部边距 + 元素高度 > 窗口高度) 时定位到底部
if ((offsetBottom + this.offset.height > $(window).height()) &&
(scrollTop + $(window).height() >= scrollHeight - offsetBottom)) {
$element.addClass(options.className.stickyBtm).
css({top: $(window).height() - offsetBottom - this.offset.height});
} else {
$element.removeClass(options.className.stickyBtm).css({top: offsetTop});
}
}
*/
}
this.sticked = checkResult;
};
// Sticky Plugin
function Plugin(option) {
return this.each(function() {
var $this = $(this);
var data = $this.data('amui.sticky');
var options = typeof option == 'object' && option;
if (!data) {
$this.data('amui.sticky', (data = new Sticky(this,
options)));
}
if (typeof option == 'string') {
data[option]();
}
});
}
$.fn.sticky = Plugin;
// Init code
$(window).on('load', function() {
$('[data-am-sticky]').each(function() {
var $this = $(this);
var options = UI.utils.options($this.attr('data-am-sticky'));
Plugin.call($this, options);
});
});
$.AMUI.sticky = Sticky;
module.exports = Sticky;
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {
"./core": 2
}
],
16: [
function(require, module, exports) {
(function(global) {
'use strict';
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
require('./core');
var cookie = {
get: function(name) {
var cookieName = encodeURIComponent(name) + '=';
var cookieStart = document.cookie.indexOf(cookieName);
var cookieValue = null;
var cookieEnd;
if (cookieStart > -1) {
cookieEnd = document.cookie.indexOf(';', cookieStart);
if (cookieEnd == -1) {
cookieEnd = document.cookie.length;
}
cookieValue = decodeURIComponent(document.cookie.substring(
cookieStart +
cookieName.length, cookieEnd));
}
return cookieValue;
},
set: function(name, value, expires, path, domain, secure) {
var cookieText = encodeURIComponent(name) + '=' +
encodeURIComponent(value);
if (expires instanceof Date) {
cookieText += '; expires=' + expires.toGMTString();
}
if (path) {
cookieText += '; path=' + path;
}
if (domain) {
cookieText += '; domain=' + domain;
}
if (secure) {
cookieText += '; secure';
}
document.cookie = cookieText;
},
unset: function(name, path, domain, secure) {
this.set(name, '', new Date(0), path, domain, secure);
}
};
$.AMUI.utils.cookie = cookie;
module.exports = cookie;
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {
"./core": 2
}
],
17: [
function(require, module, exports) {
(function(global) {
/*! Hammer.JS - v2.0.4 - 2014-09-28
* http://hammerjs.github.io/
*
* Copyright (c) 2014 Jorik Tangelder;
* Licensed under the MIT license */
'use strict';
var $ = (typeof window !== "undefined" ? window.jQuery : typeof global !==
"undefined" ? global.jQuery : null);
var UI = require('./core');
var VENDOR_PREFIXES = ['', 'webkit', 'moz', 'MS', 'ms', 'o'];
var TEST_ELEMENT = document.createElement('div');
var TYPE_FUNCTION = 'function';
var round = Math.round;
var abs = Math.abs;
var now = Date.now;
/**
* set a timeout with a given scope
* @param {Function} fn
* @param {Number} timeout
* @param {Object} context
* @returns {number}
*/
function setTimeoutContext(fn, timeout, context) {
return setTimeout(bindFn(fn, context), timeout);
}
/**
* if the argument is an array, we want to execute the fn on each entry
* if it aint an array we don't want to do a thing.
* this is used by all the methods that accept a single and array argument.
* @param {*|Array} arg
* @param {String} fn
* @param {Object} [context]
* @returns {Boolean}
*/
function invokeArrayArg(arg, fn, context) {
if (Array.isArray(arg)) {
each(arg, context[fn], context);
return true;
}
return false;
}
/**
* walk objects and arrays
* @param {Object} obj
* @param {Function} iterator
* @param {Object} context
*/
function each(obj, iterator, context) {
var i;
if (!obj) {
return;
}
if (obj.forEach) {
obj.forEach(iterator, context);
} else if (obj.length !== undefined) {
i = 0;
while (i < obj.length) {
iterator.call(context, obj[i], i, obj);
i++;
}
} else {
for (i in obj) {
obj.hasOwnProperty(i) && iterator.call(context, obj[i], i,
obj);
}
}
}
/**
* extend object.
* means that properties in dest will be overwritten by the ones in src.
* @param {Object} dest
* @param {Object} src
* @param {Boolean} [merge]
* @returns {Object} dest
*/
function extend(dest, src, merge) {
var keys = Object.keys(src);
var i = 0;
while (i < keys.length) {
if (!merge || (merge && dest[keys[i]] === undefined)) {
dest[keys[i]] = src[keys[i]];
}
i++;
}
return dest;
}
/**
* merge the values from src in the dest.
* means that properties that exist in dest will not be overwritten by src
* @param {Object} dest
* @param {Object} src
* @returns {Object} dest
*/
function merge(dest, src) {
return extend(dest, src, true);
}
/**
* simple class inheritance
* @param {Function} child
* @param {Function} base
* @param {Object} [properties]
*/
function inherit(child, base, properties) {
var baseP = base.prototype,
childP;
childP = child.prototype = Object.create(baseP);
childP.constructor = child;
childP._super = baseP;
if (properties) {
extend(childP, properties);
}
}
/**
* simple function bind
* @param {Function} fn
* @param {Object} context
* @returns {Function}
*/
function bindFn(fn, context) {
return function boundFn() {
return fn.apply(context, arguments);
};
}
/**
* let a boolean value also be a function that must return a boolean
* this first item in args will be used as the context
* @param {Boolean|Function} val
* @param {Array} [args]
* @returns {Boolean}
*/
function boolOrFn(val, args) {
if (typeof val == TYPE_FUNCTION) {
return val.apply(args ? args[0] || undefined : undefined, args);
}
return val;
}
/**
* use the val2 when val1 is undefined
* @param {*} val1
* @param {*} val2
* @returns {*}
*/
function ifUndefined(val1, val2) {
return (val1 === undefined) ? val2 : val1;
}
/**
* addEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function addEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
target.addEventListener(type, handler, false);
});
}
/**
* removeEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function removeEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
target.removeEventListener(type, handler, false);
});
}
/**
* find if a node is in the given parent
* @method hasParent
* @param {HTMLElement} node
* @param {HTMLElement} parent
* @return {Boolean} found
*/
function hasParent(node, parent) {
while (node) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
/**
* small indexOf wrapper
* @param {String} str
* @param {String} find
* @returns {Boolean} found
*/
function inStr(str, find) {
return str.indexOf(find) > -1;
}
/**
* split string on whitespace
* @param {String} str
* @returns {Array} words
*/
function splitStr(str) {
return str.trim().split(/\s+/g);
}
/**
* find if a array contains the object using indexOf or a simple polyFill
* @param {Array} src
* @param {String} find
* @param {String} [findByKey]
* @return {Boolean|Number} false when not found, or the index
*/
function inArray(src, find, findByKey) {
if (src.indexOf && !findByKey) {
return src.indexOf(find);
} else {
var i = 0;
while (i < src.length) {
if ((findByKey && src[i][findByKey] == find) || (!findByKey &&
src[i] === find)) {
return i;
}
i++;
}
return -1;
}
}
/**
* convert array-like objects to real arrays
* @param {Object} obj
* @returns {Array}
*/
function toArray(obj) {
return Array.prototype.slice.call(obj, 0);
}
/**
* unique array with objects based on a key (like 'id') or just by the array's value
* @param {Array} src [{id:1},{id:2},{id:1}]
* @param {String} [key]
* @param {Boolean} [sort=False]
* @returns {Array} [{id:1},{id:2}]
*/
function uniqueArray(src, key, sort) {
var results = [];
var values = [];
var i = 0;
while (i < src.length) {
var val = key ? src[i][key] : src[i];
if (inArray(values, val) < 0) {
results.push(src[i]);
}
values[i] = val;
i++;
}
if (sort) {
if (!key) {
results = results.sort();
} else {
results = results.sort(function sortUniqueArray(a, b) {
return a[key] > b[key];
});
}
}
return results;
}
/**
* get the prefixed property
* @param {Object} obj
* @param {String} property
* @returns {String|Undefined} prefixed
*/
function prefixed(obj, property) {
var prefix, prop;
var camelProp = property[0].toUpperCase() + property.slice(1);
var i = 0;
while (i < VENDOR_PREFIXES.length) {
prefix = VENDOR_PREFIXES[i];
prop = (prefix) ? prefix + camelProp : property;
if (prop in obj) {
return prop;
}
i++;
}
return undefined;
}
/**
* get a unique id
* @returns {number} uniqueId
*/
var _uniqueId = 1;
function uniqueId() {
return _uniqueId++;
}
/**
* get the window object of an element
* @param {HTMLElement} element
* @returns {DocumentView|Window}
*/
function getWindowForElement(element) {
var doc = element.ownerDocument;
return (doc.defaultView || doc.parentWindow);
}
var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
var SUPPORT_TOUCH = ('ontouchstart' in window);
var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !==
undefined;
var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(
navigator.userAgent);
var INPUT_TYPE_TOUCH = 'touch';
var INPUT_TYPE_PEN = 'pen';
var INPUT_TYPE_MOUSE = 'mouse';
var INPUT_TYPE_KINECT = 'kinect';
var COMPUTE_INTERVAL = 25;
var INPUT_START = 1;
var INPUT_MOVE = 2;
var INPUT_END = 4;
var INPUT_CANCEL = 8;
var DIRECTION_NONE = 1;
var DIRECTION_LEFT = 2;
var DIRECTION_RIGHT = 4;
var DIRECTION_UP = 8;
var DIRECTION_DOWN = 16;
var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
var PROPS_XY = ['x', 'y'];
var PROPS_CLIENT_XY = ['clientX', 'clientY'];
/**
* create new input type manager
* @param {Manager} manager
* @param {Function} callback
* @returns {Input}
* @constructor
*/
function Input(manager, callback) {
var self = this;
this.manager = manager;
this.callback = callback;
this.element = manager.element;
this.target = manager.options.inputTarget;
// smaller wrapper around the handler, for the scope and the enabled state of the manager,
// so when disabled the input events are completely bypassed.
this.domHandler = function(ev) {
if (boolOrFn(manager.options.enable, [manager])) {
self.handler(ev);
}
};
this.init();
}
Input.prototype = {
/**
* should handle the inputEvent data and trigger the callback
* @virtual
*/
handler: function() {},
/**
* bind the events
*/
init: function() {
this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
this.evTarget && addEventListeners(this.target, this.evTarget,
this.domHandler);
this.evWin && addEventListeners(getWindowForElement(this.element),
this.evWin, this.domHandler);
},
/**
* unbind the events
*/
destroy: function() {
this.evEl && removeEventListeners(this.element, this.evEl, this
.domHandler);
this.evTarget && removeEventListeners(this.target, this.evTarget,
this.domHandler);
this.evWin && removeEventListeners(getWindowForElement(this.element),
this.evWin, this.domHandler);
}
};
/**
* create new input type manager
* called by the Manager constructor
* @param {Hammer} manager
* @returns {Input}
*/
function createInputInstance(manager) {
var Type;
var inputClass = manager.options.inputClass;
if (inputClass) {
Type = inputClass;
} else if (SUPPORT_POINTER_EVENTS) {
Type = PointerEventInput;
} else if (SUPPORT_ONLY_TOUCH) {
Type = TouchInput;
} else if (!SUPPORT_TOUCH) {
Type = MouseInput;
} else {
Type = TouchMouseInput;
}
return new(Type)(manager, inputHandler);
}
/**
* handle input events
* @param {Manager} manager
* @param {String} eventType
* @param {Object} input
*/
function inputHandler(manager, eventType, input) {
var pointersLen = input.pointers.length;
var changedPointersLen = input.changedPointers.length;
var isFirst = (eventType & INPUT_START && (pointersLen -
changedPointersLen === 0));
var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (
pointersLen - changedPointersLen === 0));
input.isFirst = !!isFirst;
input.isFinal = !!isFinal;
if (isFirst) {
manager.session = {};
}
// source event is the normalized value of the domEvents
// like 'touchstart, mouseup, pointerdown'
input.eventType = eventType;
// compute scale, rotation etc
computeInputData(manager, input);
// emit secret event
manager.emit('hammer.input', input);
manager.recognize(input);
manager.session.prevInput = input;
}
/**
* extend the data with some usable properties like scale, rotate, velocity etc
* @param {Object} manager
* @param {Object} input
*/
function computeInputData(manager, input) {
var session = manager.session;
var pointers = input.pointers;
var pointersLength = pointers.length;
// store the first input to calculate the distance and direction
if (!session.firstInput) {
session.firstInput = simpleCloneInputData(input);
}
// to compute scale and rotation we need to store the multiple touches
if (pointersLength > 1 && !session.firstMultiple) {
session.firstMultiple = simpleCloneInputData(input);
} else if (pointersLength === 1) {
session.firstMultiple = false;
}
var firstInput = session.firstInput;
var firstMultiple = session.firstMultiple;
var offsetCenter = firstMultiple ? firstMultiple.center :
firstInput.center;
var center = input.center = getCenter(pointers);
input.timeStamp = now();
input.deltaTime = input.timeStamp - firstInput.timeStamp;
input.angle = getAngle(offsetCenter, center);
input.distance = getDistance(offsetCenter, center);
computeDeltaXY(session, input);
input.offsetDirection = getDirection(input.deltaX, input.deltaY);
input.scale = firstMultiple ? getScale(firstMultiple.pointers,
pointers) : 1;
input.rotation = firstMultiple ? getRotation(firstMultiple.pointers,
pointers) : 0;
computeIntervalInputData(session, input);
// find the correct target
var target = manager.element;
if (hasParent(input.srcEvent.target, target)) {
target = input.srcEvent.target;
}
input.target = target;
}
function computeDeltaXY(session, input) {
var center = input.center;
var offset = session.offsetDelta || {};
var prevDelta = session.prevDelta || {};
var prevInput = session.prevInput || {};
if (input.eventType === INPUT_START || prevInput.eventType ===
INPUT_END) {
prevDelta = session.prevDelta = {
x: prevInput.deltaX || 0,
y: prevInput.deltaY || 0
};
offset = session.offsetDelta = {
x: center.x,
y: center.y
};
}
input.deltaX = prevDelta.x + (center.x - offset.x);
input.deltaY = prevDelta.y + (center.y - offset.y);
}
/**
* velocity is calculated every x ms
* @param {Object} session
* @param {Object} input
*/
function computeIntervalInputData(session, input) {
var last = session.lastInterval || input,
deltaTime = input.timeStamp - last.timeStamp,
velocity, velocityX, velocityY, direction;
if (input.eventType != INPUT_CANCEL && (deltaTime >
COMPUTE_INTERVAL || last.velocity === undefined)) {
var deltaX = last.deltaX - input.deltaX;
var deltaY = last.deltaY - input.deltaY;
var v = getVelocity(deltaTime, deltaX, deltaY);
velocityX = v.x;
velocityY = v.y;
velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;
direction = getDirection(deltaX, deltaY);
session.lastInterval = input;
} else {
// use latest velocity info if it doesn't overtake a minimum period
velocity = last.velocity;
velocityX = last.velocityX;
velocityY = last.velocityY;
direction = last.direction;
}
input.velocity = velocity;
input.velocityX = velocityX;
input.velocityY = velocityY;
input.direction = direction;
}
/**
* create a simple clone from the input used for storage of firstInput and firstMultiple
* @param {Object} input
* @returns {Object} clonedInputData
*/
function simpleCloneInputData(input) {
// make a simple copy of the pointers because we will get a reference if we don't
// we only need clientXY for the calculations
var pointers = [];
var i = 0;
while (i < input.pointers.length) {
pointers[i] = {
clientX: round(input.pointers[i].clientX),
clientY: round(input.pointers[i].clientY)
};
i++;
}
return {
timeStamp: now(),
pointers: pointers,
center: getCenter(pointers),
deltaX: input.deltaX,
deltaY: input.deltaY
};
}
/**
* get the center of all the pointers
* @param {Array} pointers
* @return {Object} center contains `x` and `y` properties
*/
function getCenter(pointers) {
var pointersLength = pointers.length;
// no need to loop when only one touch
if (pointersLength === 1) {
return {
x: round(pointers[0].clientX),
y: round(pointers[0].clientY)
};
}
var x = 0,
y = 0,
i = 0;
while (i < pointersLength) {
x += pointers[i].clientX;
y += pointers[i].clientY;
i++;
}
return {
x: round(x / pointersLength),
y: round(y / pointersLength)
};
}
/**
* calculate the velocity between two points. unit is in px per ms.
* @param {Number} deltaTime
* @param {Number} x
* @param {Number} y
* @return {Object} velocity `x` and `y`
*/
function getVelocity(deltaTime, x, y) {
return {
x: x / deltaTime || 0,
y: y / deltaTime || 0
};
}
/**
* get the direction between two points
* @param {Number} x
* @param {Number} y
* @return {Number} direction
*/
function getDirection(x, y) {
if (x === y) {
return DIRECTION_NONE;
}
if (abs(x) >= abs(y)) {
return x > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
}
return y > 0 ? DIRECTION_UP : DIRECTION_DOWN;
}
/**
* calculate the absolute distance between two points
* @param {Object} p1 {x, y}
* @param {Object} p2 {x, y}
* @param {Array} [props] containing x and y keys
* @return {Number} distance
*/
function getDistance(p1, p2, props) {
if (!props) {
props = PROPS_XY;
}
var x = p2[props[0]] - p1[props[0]],
y = p2[props[1]] - p1[props[1]];
return Math.sqrt((x * x) + (y * y));
}
/**
* calculate the angle between two coordinates
* @param {Object} p1
* @param {Object} p2
* @param {Array} [props] containing x and y keys
* @return {Number} angle
*/
function getAngle(p1, p2, props) {
if (!props) {
props = PROPS_XY;
}
var x = p2[props[0]] - p1[props[0]],
y = p2[props[1]] - p1[props[1]];
return Math.atan2(y, x) * 180 / Math.PI;
}
/**
* calculate the rotation degrees between two pointersets
* @param {Array} start array of pointers
* @param {Array} end array of pointers
* @return {Number} rotation
*/
function getRotation(start, end) {
return getAngle(end[1], end[0], PROPS_CLIENT_XY) - getAngle(start[
1], start[0], PROPS_CLIENT_XY);
}
/**
* calculate the scale factor between two pointersets
* no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
* @param {Array} start array of pointers
* @param {Array} end array of pointers
* @return {Number} scale
*/
function getScale(start, end) {
return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(
start[0], start[1], PROPS_CLIENT_XY);
}
var MOUSE_INPUT_MAP = {
mousedown: INPUT_START,
mousemove: INPUT_MOVE,
mouseup: INPUT_END
};
var MOUSE_ELEMENT_EVENTS = 'mousedown';
var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';
/**
* Mouse events input
* @constructor
* @extends Input
*/
function MouseInput() {
this.evEl = MOUSE_ELEMENT_EVENTS;
this.evWin = MOUSE_WINDOW_EVENTS;
this.allow = true; // used by Input.TouchMouse to disable mouse events
this.pressed = false; // mousedown state
Input.apply(this, arguments);
}
inherit(MouseInput, Input, {
/**
* handle mouse events
* @param {Object} ev
*/
handler: function MEhandler(ev) {
var eventType = MOUSE_INPUT_MAP[ev.type];
// on start we want to have the left mouse button down
if (eventType & INPUT_START && ev.button === 0) {
this.pressed = true;
}
if (eventType & INPUT_MOVE && ev.which !== 1) {
eventType = INPUT_END;
}
// mouse must be down, and mouse events are allowed (see the TouchMouse input)
if (!this.pressed || !this.allow) {
return;
}
if (eventType & INPUT_END) {
this.pressed = false;
}
this.callback(this.manager, eventType, {
pointers: [ev],
changedPointers: [ev],
pointerType: INPUT_TYPE_MOUSE,
srcEvent: ev
});
}
});
var POINTER_INPUT_MAP = {
pointerdown: INPUT_START,
pointermove: INPUT_MOVE,
pointerup: INPUT_END,
pointercancel: INPUT_CANCEL,
pointerout: INPUT_CANCEL
};
// in IE10 the pointer types is defined as an enum
var IE10_POINTER_TYPE_ENUM = {
2: INPUT_TYPE_TOUCH,
3: INPUT_TYPE_PEN,
4: INPUT_TYPE_MOUSE,
5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816
};
var POINTER_ELEMENT_EVENTS = 'pointerdown';
var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel';
// IE10 has prefixed support, and case-sensitive
if (window.MSPointerEvent) {
POINTER_ELEMENT_EVENTS = 'MSPointerDown';
POINTER_WINDOW_EVENTS =
'MSPointerMove MSPointerUp MSPointerCancel';
}
/**
* Pointer events input
* @constructor
* @extends Input
*/
function PointerEventInput() {
this.evEl = POINTER_ELEMENT_EVENTS;
this.evWin = POINTER_WINDOW_EVENTS;
Input.apply(this, arguments);
this.store = (this.manager.session.pointerEvents = []);
}
inherit(PointerEventInput, Input, {
/**
* handle mouse events
* @param {Object} ev
*/
handler: function PEhandler(ev) {
var store = this.store;
var removePointer = false;
var eventTypeNormalized = ev.type.toLowerCase().replace('ms',
'');
var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] ||
ev.pointerType;
var isTouch = (pointerType == INPUT_TYPE_TOUCH);
// get index of the event in the store
var storeIndex = inArray(store, ev.pointerId, 'pointerId');
// start and mouse must be down
if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
if (storeIndex < 0) {
store.push(ev);
storeIndex = store.length - 1;
}
} else if (eventType & (INPUT_END | INPUT_CANCEL)) {
removePointer = true;
}
// it not found, so the pointer hasn't been down (so it's probably a hover)
if (storeIndex < 0) {
return;
}
// update the event in the store
store[storeIndex] = ev;
this.callback(this.manager, eventType, {
pointers: store,
changedPointers: [ev],
pointerType: pointerType,
srcEvent: ev
});
if (removePointer) {
// remove from the store
store.splice(storeIndex, 1);
}
}
});
var SINGLE_TOUCH_INPUT_MAP = {
touchstart: INPUT_START,
touchmove: INPUT_MOVE,
touchend: INPUT_END,
touchcancel: INPUT_CANCEL
};
var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';
var SINGLE_TOUCH_WINDOW_EVENTS =
'touchstart touchmove touchend touchcancel';
/**
* Touch events input
* @constructor
* @extends Input
*/
function SingleTouchInput() {
this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
this.started = false;
Input.apply(this, arguments);
}
inherit(SingleTouchInput, Input, {
handler: function TEhandler(ev) {
var type = SINGLE_TOUCH_INPUT_MAP[ev.type];
// should we handle the touch events?
if (type === INPUT_START) {
this.started = true;
}
if (!this.started) {
return;
}
var touches = normalizeSingleTouches.call(this, ev, type);
// when done, reset the started state
if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length -
touches[1].length === 0) {
this.started = false;
}
this.callback(this.manager, type, {
pointers: touches[0],
changedPointers: touches[1],
pointerType: INPUT_TYPE_TOUCH,
srcEvent: ev
});
}
});
/**
* @this {TouchInput}
* @param {Object} ev
* @param {Number} type flag
* @returns {undefined|Array} [all, changed]
*/
function normalizeSingleTouches(ev, type) {
var all = toArray(ev.touches);
var changed = toArray(ev.changedTouches);
if (type & (INPUT_END | INPUT_CANCEL)) {
all = uniqueArray(all.concat(changed), 'identifier', true);
}
return [all, changed];
}
var TOUCH_INPUT_MAP = {
touchstart: INPUT_START,
touchmove: INPUT_MOVE,
touchend: INPUT_END,
touchcancel: INPUT_CANCEL
};
var TOUCH_TARGET_EVENTS =
'touchstart touchmove touchend touchcancel';
/**
* Multi-user touch events input
* @constructor
* @extends Input
*/
function TouchInput() {
this.evTarget = TOUCH_TARGET_EVENTS;
this.targetIds = {};
Input.apply(this, arguments);
}
inherit(TouchInput, Input, {
handler: function MTEhandler(ev) {
var type = TOUCH_INPUT_MAP[ev.type];
var touches = getTouches.call(this, ev, type);
if (!touches) {
return;
}
this.callback(this.manager, type, {
pointers: touches[0],
changedPointers: touches[1],
pointerType: INPUT_TYPE_TOUCH,
srcEvent: ev
});
}
});
/**
* @this {TouchInput}
* @param {Object} ev
* @param {Number} type flag
* @returns {undefined|Array} [all, changed]
*/
function getTouches(ev, type) {
var allTouches = toArray(ev.touches);
var targetIds = this.targetIds;
// when there is only one touch, the process can be simplified
if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
targetIds[allTouches[0].identifier] = true;
return [allTouches, allTouches];
}
var i,
targetTouches,
changedTouches = toArray(ev.changedTouches),
changedTargetTouches = [],
target = this.target;
// get target touches from touches
targetTouches = allTouches.filter(function(touch) {
return hasParent(touch.target, target);
});
// collect touches
if (type === INPUT_START) {
i = 0;
while (i < targetTouches.length) {
targetIds[targetTouches[i].identifier] = true;
i++;
}
}
// filter changed touches to only contain touches that exist in the collected target ids
i = 0;
while (i < changedTouches.length) {
if (targetIds[changedTouches[i].identifier]) {
changedTargetTouches.push(changedTouches[i]);
}
// cleanup removed touches
if (type & (INPUT_END | INPUT_CANCEL)) {
delete targetIds[changedTouches[i].identifier];
}
i++;
}
if (!changedTargetTouches.length) {
return;
}
return [
// merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
uniqueArray(targetTouches.concat(changedTargetTouches),
'identifier', true),
changedTargetTouches
];
}
/**
* Combined touch and mouse input
*
* Touch has a higher priority then mouse, and while touching no mouse events are allowed.
* This because touch devices also emit mouse events while doing a touch.
*
* @constructor
* @extends Input
*/
function TouchMouseInput() {
Input.apply(this, arguments);
var handler = bindFn(this.handler, this);
this.touch = new TouchInput(this.manager, handler);
this.mouse = new MouseInput(this.manager, handler);
}
inherit(TouchMouseInput, Input, {
/**
* handle mouse and touch events
* @param {Hammer} manager
* @param {String} inputEvent
* @param {Object} inputData
*/
handler: function TMEhandler(manager, inputEvent, inputData) {
var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH),
isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE);
// when we're in a touch event, so block all upcoming mouse events
// most mobile browser also emit mouseevents, right after touchstart
if (isTouch) {
this.mouse.allow = false;
} else if (isMouse && !this.mouse.allow) {
return;
}
// reset the allowMouse when we're done
if (inputEvent & (INPUT_END | INPUT_CANCEL)) {
this.mouse.allow = true;
}
this.callback(manager, inputEvent, inputData);
},
/**
* remove the event listeners
*/
destroy: function destroy() {
this.touch.destroy();
this.mouse.destroy();
}
});
var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style,
'touchAction');
var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;
// magical touchAction value
var TOUCH_ACTION_COMPUTE = 'compute';
var TOUCH_ACTION_AUTO = 'auto';
var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented
var TOUCH_ACTION_NONE = 'none';
var TOUCH_ACTION_PAN_X = 'pan-x';
var TOUCH_ACTION_PAN_Y = 'pan-y';
/**
* Touch Action
* sets the touchAction property or uses the js alternative
* @param {Manager} manager
* @param {String} value
* @constructor
*/
function TouchAction(manager, value) {
this.manager = manager;
this.set(value);
}
TouchAction.prototype = {
/**
* set the touchAction value on the element or enable the polyfill
* @param {String} value
*/
set: function(value) {
// find out the touch-action by the event handlers
if (value == TOUCH_ACTION_COMPUTE) {
value = this.compute();
}
if (NATIVE_TOUCH_ACTION) {
this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
}
this.actions = value.toLowerCase().trim();
},
/**
* just re-set the touchAction value
*/
update: function() {
this.set(this.manager.options.touchAction);
},
/**
* compute the value for the touchAction property based on the recognizer's settings
* @returns {String} value
*/
compute: function() {
var actions = [];
each(this.manager.recognizers, function(recognizer) {
if (boolOrFn(recognizer.options.enable, [recognizer])) {
actions = actions.concat(recognizer.getTouchAction());
}
});
return cleanTouchActions(actions.join(' '));
},
/**
* this method is called on each input cycle and provides the preventing of the browser behavior
* @param {Object} input
*/
preventDefaults: function(input) {
// not needed with native support for the touchAction property
if (NATIVE_TOUCH_ACTION) {
return;
}
var srcEvent = input.srcEvent;
var direction = input.offsetDirection;
// if the touch action did prevented once this session
if (this.manager.session.prevented) {
srcEvent.preventDefault();
return;
}
var actions = this.actions;
var hasNone = inStr(actions, TOUCH_ACTION_NONE);
var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
if (hasNone ||
(hasPanY && direction & DIRECTION_HORIZONTAL) ||
(hasPanX && direction & DIRECTION_VERTICAL)) {
return this.preventSrc(srcEvent);
}
},
/**
* call preventDefault to prevent the browser's default behavior (scrolling in most cases)
* @param {Object} srcEvent
*/
preventSrc: function(srcEvent) {
this.manager.session.prevented = true;
srcEvent.preventDefault();
}
};
/**
* when the touchActions are collected they are not a valid value, so we need to clean things up. *
* @param {String} actions
* @returns {*}
*/
function cleanTouchActions(actions) {
// none
if (inStr(actions, TOUCH_ACTION_NONE)) {
return TOUCH_ACTION_NONE;
}
var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
// pan-x and pan-y can be combined
if (hasPanX && hasPanY) {
return TOUCH_ACTION_PAN_X + ' ' + TOUCH_ACTION_PAN_Y;
}
// pan-x OR pan-y
if (hasPanX || hasPanY) {
return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
}
// manipulation
if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
return TOUCH_ACTION_MANIPULATION;
}
return TOUCH_ACTION_AUTO;
}
/**
* Recognizer flow explained; *
* All recognizers have the initial state of POSSIBLE when a input session starts.
* The definition of a input session is from the first input until the last input, with all it's movement in it. *
* Example session for mouse-input: mousedown -> mousemove -> mouseup
*
* On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
* which determines with state it should be.
*
* If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
* POSSIBLE to give it another change on the next cycle.
*
* Possible
* |
* +-----+---------------+
* | |
* +-----+-----+ |
* | | |
* Failed Cancelled |
* +-------+------+
* | |
* Recognized Began
* |
* Changed
* |
* Ended/Recognized
*/
var STATE_POSSIBLE = 1;
var STATE_BEGAN = 2;
var STATE_CHANGED = 4;
var STATE_ENDED = 8;
var STATE_RECOGNIZED = STATE_ENDED;
var STATE_CANCELLED = 16;
var STATE_FAILED = 32;
/**
* Recognizer
* Every recognizer needs to extend from this class.
* @constructor
* @param {Object} options
*/
function Recognizer(options) {
this.id = uniqueId();
this.manager = null;
this.options = merge(options || {}, this.defaults);
// default is enable true
this.options.enable = ifUndefined(this.options.enable, true);
this.state = STATE_POSSIBLE;
this.simultaneous = {};
this.requireFail = [];
}
Recognizer.prototype = {
/**
* @virtual
* @type {Object}
*/
defaults: {},
/**
* set options
* @param {Object} options
* @return {Recognizer}
*/
set: function(options) {
extend(this.options, options);
// also update the touchAction, in case something changed about the directions/enabled state
this.manager && this.manager.touchAction.update();
return this;
},
/**
* recognize simultaneous with an other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
recognizeWith: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
return this;
}
var simultaneous = this.simultaneous;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer,
this);
if (!simultaneous[otherRecognizer.id]) {
simultaneous[otherRecognizer.id] = otherRecognizer;
otherRecognizer.recognizeWith(this);
}
return this;
},
/**
* drop the simultaneous link. it doesnt remove the link on the other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
dropRecognizeWith: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
return this;
}
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer,
this);
delete this.simultaneous[otherRecognizer.id];
return this;
},
/**
* recognizer can only run when an other is failing
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
requireFailure: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
return this;
}
var requireFail = this.requireFail;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer,
this);
if (inArray(requireFail, otherRecognizer) === -1) {
requireFail.push(otherRecognizer);
otherRecognizer.requireFailure(this);
}
return this;
},
/**
* drop the requireFailure link. it does not remove the link on the other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
dropRequireFailure: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
return this;
}
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer,
this);
var index = inArray(this.requireFail, otherRecognizer);
if (index > -1) {
this.requireFail.splice(index, 1);
}
return this;
},
/**
* has require failures boolean
* @returns {boolean}
*/
hasRequireFailures: function() {
return this.requireFail.length > 0;
},
/**
* if the recognizer can recognize simultaneous with an other recognizer
* @param {Recognizer} otherRecognizer
* @returns {Boolean}
*/
canRecognizeWith: function(otherRecognizer) {
return !!this.simultaneous[otherRecognizer.id];
},
/**
* You should use `tryEmit` instead of `emit` directly to check
* that all the needed recognizers has failed before emitting.
* @param {Object} input
*/
emit: function(input) {
var self = this;
var state = this.state;
function emit(withState) {
self.manager.emit(self.options.event + (withState ? stateStr(
state) : ''), input);
}
// 'panstart' and 'panmove'
if (state < STATE_ENDED) {
emit(true);
}
emit(); // simple 'eventName' events
// panend and pancancel
if (state >= STATE_ENDED) {
emit(true);
}
},
/**
* Check that all the require failure recognizers has failed,
* if true, it emits a gesture event,
* otherwise, setup the state to FAILED.
* @param {Object} input
*/
tryEmit: function(input) {
if (this.canEmit()) {
return this.emit(input);
}
// it's failing anyway
this.state = STATE_FAILED;
},
/**
* can we emit?
* @returns {boolean}
*/
canEmit: function() {
var i = 0;
while (i < this.requireFail.length) {
if (!(this.requireFail[i].state & (STATE_FAILED |
STATE_POSSIBLE))) {
return false;
}
i++;
}
return true;
},
/**
* update the recognizer
* @param {Object} inputData
*/
recognize: function(inputData) {
// make a new copy of the inputData
// so we can change the inputData without messing up the other recognizers
var inputDataClone = extend({}, inputData);
// is is enabled and allow recognizing?
if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
this.reset();
this.state = STATE_FAILED;
return;
}
// reset when we've reached the end
if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED |
STATE_FAILED)) {
this.state = STATE_POSSIBLE;
}
this.state = this.process(inputDataClone);
// the recognizer has recognized a gesture
// so trigger an event
if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED |
STATE_CANCELLED)) {
this.tryEmit(inputDataClone);
}
},
/**
* return the state of the recognizer
* the actual recognizing happens in this method
* @virtual
* @param {Object} inputData
* @returns {Const} STATE
*/
process: function(inputData) {}, // jshint ignore:line
/**
* return the preferred touch-action
* @virtual
* @returns {Array}
*/
getTouchAction: function() {},
/**
* called when the gesture isn't allowed to recognize
* like when another is being recognized or it is disabled
* @virtual
*/
reset: function() {}
};
/**
* get a usable string, used as event postfix
* @param {Const} state
* @returns {String} state
*/
function stateStr(state) {
if (state & STATE_CANCELLED) {
return 'cancel';
} else if (state & STATE_ENDED) {
return 'end';
} else if (state & STATE_CHANGED) {
return 'move';
} else if (state & STATE_BEGAN) {
return 'start';
}
return '';
}
/**
* direction cons to string
* @param {Const} direction
* @returns {String}
*/
function directionStr(direction) {
if (direction == DIRECTION_DOWN) {
return 'down';
} else if (direction == DIRECTION_UP) {
return 'up';
} else if (direction == DIRECTION_LEFT) {
return 'left';
} else if (direction == DIRECTION_RIGHT) {
return 'right';
}
return '';
}
/**
* get a recognizer by name if it is bound to a manager
* @param {Recognizer|String} otherRecognizer
* @param {Recognizer} recognizer
* @returns {Recognizer}
*/
function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
var manager = recognizer.manager;
if (manager) {
return manager.get(otherRecognizer);
}
return otherRecognizer;
}
/**
* This recognizer is just used as a base for the simple attribute recognizers.
* @constructor
* @extends Recognizer
*/
function AttrRecognizer() {
Recognizer.apply(this, arguments);
}
inherit(AttrRecognizer, Recognizer, {
/**
* @namespace
* @memberof AttrRecognizer
*/
defaults: {
/**
* @type {Number}
* @default 1
*/
pointers: 1
},
/**
* Used to check if it the recognizer receives valid input, like input.distance > 10.
* @memberof AttrRecognizer
* @param {Object} input
* @returns {Boolean} recognized
*/
attrTest: function(input) {
var optionPointers = this.options.pointers;
return optionPointers === 0 || input.pointers.length ===
optionPointers;
},
/**
* Process the input and return the state for the recognizer
* @memberof AttrRecognizer
* @param {Object} input
* @returns {*} State
*/
process: function(input) {
var state = this.state;
var eventType = input.eventType;
var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
var isValid = this.attrTest(input);
// on cancel input and we've recognized before, return STATE_CANCELLED
if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
return state | STATE_CANCELLED;
} else if (isRecognized || isValid) {
if (eventType & INPUT_END) {
return state | STATE_ENDED;
} else if (!(state & STATE_BEGAN)) {
return STATE_BEGAN;
}
return state | STATE_CHANGED;
}
return STATE_FAILED;
}
});
/**
* Pan
* Recognized when the pointer is down and moved in the allowed direction.
* @constructor
* @extends AttrRecognizer
*/
function PanRecognizer() {
AttrRecognizer.apply(this, arguments);
this.pX = null;
this.pY = null;
}
inherit(PanRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof PanRecognizer
*/
defaults: {
event: 'pan',
threshold: 10,
pointers: 1,
direction: DIRECTION_ALL
},
getTouchAction: function() {
var direction = this.options.direction;
var actions = [];
if (direction & DIRECTION_HORIZONTAL) {
actions.push(TOUCH_ACTION_PAN_Y);
}
if (direction & DIRECTION_VERTICAL) {
actions.push(TOUCH_ACTION_PAN_X);
}
return actions;
},
directionTest: function(input) {
var options = this.options;
var hasMoved = true;
var distance = input.distance;
var direction = input.direction;
var x = input.deltaX;
var y = input.deltaY;
// lock to axis?
if (!(direction & options.direction)) {
if (options.direction & DIRECTION_HORIZONTAL) {
direction = (x === 0) ? DIRECTION_NONE : (x < 0) ?
DIRECTION_LEFT : DIRECTION_RIGHT;
hasMoved = x != this.pX;
distance = Math.abs(input.deltaX);
} else {
direction = (y === 0) ? DIRECTION_NONE : (y < 0) ?
DIRECTION_UP : DIRECTION_DOWN;
hasMoved = y != this.pY;
distance = Math.abs(input.deltaY);
}
}
input.direction = direction;
return hasMoved && distance > options.threshold && direction &
options.direction;
},
attrTest: function(input) {
return AttrRecognizer.prototype.attrTest.call(this, input) &&
(this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) &&
this.directionTest(input)));
},
emit: function(input) {
this.pX = input.deltaX;
this.pY = input.deltaY;
var direction = directionStr(input.direction);
if (direction) {
this.manager.emit(this.options.event + direction, input);
}
this._super.emit.call(this, input);
}
});
/**
* Pinch
* Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
* @constructor
* @extends AttrRecognizer
*/
function PinchRecognizer() {
AttrRecognizer.apply(this, arguments);
}
inherit(PinchRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof PinchRecognizer
*/
defaults: {
event: 'pinch',
threshold: 0,
pointers: 2
},
getTouchAction: function() {
return [TOUCH_ACTION_NONE];
},
attrTest: function(input) {
return this._super.attrTest.call(this, input) &&
(Math.abs(input.scale - 1) > this.options.threshold || this
.state & STATE_BEGAN);
},
emit: function(input) {
this._super.emit.call(this, input);
if (input.scale !== 1) {
var inOut = input.scale < 1 ? 'in' : 'out';
this.manager.emit(this.options.event + inOut, input);
}
}
});
/**
* Press
* Recognized when the pointer is down for x ms without any movement.
* @constructor
* @extends Recognizer
*/
function PressRecognizer() {
Recognizer.apply(this, arguments);
this._timer = null;
this._input = null;
}
inherit(PressRecognizer, Recognizer, {
/**
* @namespace
* @memberof PressRecognizer
*/
defaults: {
event: 'press',
pointers: 1,
time: 500, // minimal time of the pointer to be pressed
threshold: 5 // a minimal movement is ok, but keep it low
},
getTouchAction: function() {
return [TOUCH_ACTION_AUTO];
},
process: function(input) {
var options = this.options;
var validPointers = input.pointers.length === options.pointers;
var validMovement = input.distance < options.threshold;
var validTime = input.deltaTime > options.time;
this._input = input;
// we only allow little movement
// and we've reached an end event, so a tap is possible
if (!validMovement || !validPointers || (input.eventType & (
INPUT_END | INPUT_CANCEL) && !validTime)) {
this.reset();
} else if (input.eventType & INPUT_START) {
this.reset();
this._timer = setTimeoutContext(function() {
this.state = STATE_RECOGNIZED;
this.tryEmit();
}, options.time, this);
} else if (input.eventType & INPUT_END) {
return STATE_RECOGNIZED;
}
return STATE_FAILED;
},
reset: function() {
clearTimeout(this._timer);
},
emit: function(input) {
if (this.state !== STATE_RECOGNIZED) {
return;
}
if (input && (input.eventType & INPUT_END)) {
this.manager.emit(this.options.event + 'up', input);
} else {
this._input.timeStamp = now();
this.manager.emit(this.options.event, this._input);
}
}
});
/**
* Rotate
* Recognized when two or more pointer are moving in a circular motion.
* @constructor
* @extends AttrRecognizer
*/
function RotateRecognizer() {
AttrRecognizer.apply(this, arguments);
}
inherit(RotateRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof RotateRecognizer
*/
defaults: {
event: 'rotate',
threshold: 0,
pointers: 2
},
getTouchAction: function() {
return [TOUCH_ACTION_NONE];
},
attrTest: function(input) {
return this._super.attrTest.call(this, input) &&
(Math.abs(input.rotation) > this.options.threshold || this.state &
STATE_BEGAN);
}
});
/**
* Swipe
* Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
* @constructor
* @extends AttrRecognizer
*/
function SwipeRecognizer() {
AttrRecognizer.apply(this, arguments);
}
inherit(SwipeRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof SwipeRecognizer
*/
defaults: {
event: 'swipe',
threshold: 10,
velocity: 0.65,
direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
pointers: 1
},
getTouchAction: function() {
return PanRecognizer.prototype.getTouchAction.call(this);
},
attrTest: function(input) {
var direction = this.options.direction;
var velocity;
if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
velocity = input.velocity;
} else if (direction & DIRECTION_HORIZONTAL) {
velocity = input.velocityX;
} else if (direction & DIRECTION_VERTICAL) {
velocity = input.velocityY;
}
return this._super.attrTest.call(this, input) &&
direction & input.direction &&
input.distance > this.options.threshold &&
abs(velocity) > this.options.velocity && input.eventType &
INPUT_END;
},
emit: function(input) {
var direction = directionStr(input.direction);
if (direction) {
this.manager.emit(this.options.event + direction, input);
}
this.manager.emit(this.options.event, input);
}
});
/**
* A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
* between the given interval and position. The delay option can be used to recognize multi-taps without firing
* a single tap.
*
* The eventData from the emitted event contains the property `tapCount`, which contains the amount of
* multi-taps being recognized.
* @constructor
* @extends Recognizer
*/
function TapRecognizer() {
Recognizer.apply(this, arguments);
// previous time and center,
// used for tap counting
this.pTime = false;
this.pCenter = false;
this._timer = null;
this._input = null;
this.count = 0;
}
inherit(TapRecognizer, Recognizer, {
/**
* @namespace
* @memberof PinchRecognizer
*/
defaults: {
event: 'tap',
pointers: 1,
taps: 1,
interval: 300, // max time between the multi-tap taps
time: 250, // max time of the pointer to be down (like finger on the screen)
threshold: 2, // a minimal movement is ok, but keep it low
posThreshold: 10 // a multi-tap can be a bit off the initial position
},
getTouchAction: function() {
return [TOUCH_ACTION_MANIPULATION];
},
process: function(input) {
var options = this.options;
var validPointers = input.pointers.length === options.pointers;
var validMovement = input.distance < options.threshold;
var validTouchTime = input.deltaTime < options.time;
this.reset();
if ((input.eventType & INPUT_START) && (this.count === 0)) {
return this.failTimeout();
}
// we only allow little movement
// and we've reached an end event, so a tap is possible
if (validMovement && validTouchTime && validPointers) {
if (input.eventType != INPUT_END) {
return this.failTimeout();
}
var validInterval = this.pTime ? (input.timeStamp - this.pTime <
options.interval) : true;
var validMultiTap = !this.pCenter || getDistance(this.pCenter,
input.center) < options.posThreshold;
this.pTime = input.timeStamp;
this.pCenter = input.center;
if (!validMultiTap || !validInterval) {
this.count = 1;
} else {
this.count += 1;
}
this._input = input;
// if tap count matches we have recognized it,
// else it has began recognizing...
var tapCount = this.count % options.taps;
if (tapCount === 0) {
// no failing requirements, immediately trigger the tap event
// or wait as long as the multitap interval to trigger
if (!this.hasRequireFailures()) {
return STATE_RECOGNIZED;
} else {
this._timer = setTimeoutContext(function() {
this.state = STATE_RECOGNIZED;
this.tryEmit();
}, options.interval, this);
return STATE_BEGAN;
}
}
}
return STATE_FAILED;
},
failTimeout: function() {
this._timer = setTimeoutContext(function() {
this.state = STATE_FAILED;
}, this.options.interval, this);
return STATE_FAILED;
},
reset: function() {
clearTimeout(this._timer);
},
emit: function() {
if (this.state == STATE_RECOGNIZED) {
this._input.tapCount = this.count;
this.manager.emit(this.options.event, this._input);
}
}
});
/**
* Simple way to create an manager with a default set of recognizers.
* @param {HTMLElement} element
* @param {Object} [options]
* @constructor
*/
function Hammer(element, options) {
options = options || {};
options.recognizers = ifUndefined(options.recognizers, Hammer.defaults
.preset);
return new Manager(element, options);
}
/**
* @const {string}
*/
Hammer.VERSION = '2.0.4';
/**
* default settings
* @namespace
*/
Hammer.defaults = {
/**
* set if DOM events are being triggered.
* But this is slower and unused by simple implementations, so disabled by default.
* @type {Boolean}
* @default false
*/
domEvents: false,
/**
* The value for the touchAction property/fallback.
* When set to `compute` it will magically set the correct value based on the added recognizers.
* @type {String}
* @default compute
*/
touchAction: TOUCH_ACTION_COMPUTE,
/**
* @type {Boolean}
* @default true
*/
enable: true,
/**
* EXPERIMENTAL FEATURE -- can be removed/changed
* Change the parent input target element.
* If Null, then it is being set the to main element.
* @type {Null|EventTarget}
* @default null
*/
inputTarget: null,
/**
* force an input class
* @type {Null|Function}
* @default null
*/
inputClass: null,
/**
* Default recognizer setup when calling `Hammer()`
* When creating a new Manager these will be skipped.
* @type {Array}
*/
preset: [
// RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
[RotateRecognizer, {
enable: false
}],
[PinchRecognizer, {
enable: false
},
['rotate']
],
[SwipeRecognizer, {
direction: DIRECTION_HORIZONTAL
}],
[PanRecognizer, {
direction: DIRECTION_HORIZONTAL
},
['swipe']
],
[TapRecognizer],
[TapRecognizer, {
event: 'doubletap',
taps: 2
},
['tap']
],
[PressRecognizer]
],
/**
* Some CSS properties can be used to improve the working of Hammer.
* Add them to this method and they will be set when creating a new Manager.
* @namespace
*/
cssProps: {
/**
* Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
* @type {String}
* @default 'none'
*/
userSelect: 'none',
/**
* Disable the Windows Phone grippers when pressing an element.
* @type {String}
* @default 'none'
*/
touchSelect: 'none',
/**
* Disables the default callout shown when you touch and hold a touch target.
* On iOS, when you touch and hold a touch target such as a link, Safari displays
* a callout containing information about the link. This property allows you to disable that callout.
* @type {String}
* @default 'none'
*/
touchCallout: 'none',
/**
* Specifies whether zooming is enabled. Used by IE10>
* @type {String}
* @default 'none'
*/
contentZooming: 'none',
/**
* Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
* @type {String}
* @default 'none'
*/
userDrag: 'none',
/**
* Overrides the highlight color shown when the user taps a link or a JavaScript
* clickable element in iOS. This property obeys the alpha value, if specified.
* @type {String}
* @default 'rgba(0,0,0,0)'
*/
tapHighlightColor: 'rgba(0,0,0,0)'
}
};
var STOP = 1;
var FORCED_STOP = 2;
/**
* Manager
* @param {HTMLElement} element
* @param {Object} [options]
* @constructor
*/
function Manager(element, options) {
options = options || {};
this.options = merge(options, Hammer.defaults);
this.options.inputTarget = this.options.inputTarget || element;
this.handlers = {};
this.session = {};
this.recognizers = [];
this.element = element;
this.input = createInputInstance(this);
this.touchAction = new TouchAction(this, this.options.touchAction);
toggleCssProps(this, true);
each(options.recognizers, function(item) {
var recognizer = this.add(new(item[0])(item[1]));
item[2] && recognizer.recognizeWith(item[2]);
item[3] && recognizer.requireFailure(item[3]);
}, this);
}
Manager.prototype = {
/**
* set options
* @param {Object} options
* @returns {Manager}
*/
set: function(options) {
extend(this.options, options);
// Options that need a little more setup
if (options.touchAction) {
this.touchAction.update();
}
if (options.inputTarget) {
// Clean up existing event listeners and reinitialize
this.input.destroy();
this.input.target = options.inputTarget;
this.input.init();
}
return this;
},
/**
* stop recognizing for this session.
* This session will be discarded, when a new [input]start event is fired.
* When forced, the recognizer cycle is stopped immediately.
* @param {Boolean} [force]
*/
stop: function(force) {
this.session.stopped = force ? FORCED_STOP : STOP;
},
/**
* run the recognizers!
* called by the inputHandler function on every movement of the pointers (touches)
* it walks through all the recognizers and tries to detect the gesture that is being made
* @param {Object} inputData
*/
recognize: function(inputData) {
var session = this.session;
if (session.stopped) {
return;
}
// run the touch-action polyfill
this.touchAction.preventDefaults(inputData);
var recognizer;
var recognizers = this.recognizers;
// this holds the recognizer that is being recognized.
// so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
// if no recognizer is detecting a thing, it is set to `null`
var curRecognizer = session.curRecognizer;
// reset when the last recognizer is recognized
// or when we're in a new session
if (!curRecognizer || (curRecognizer && curRecognizer.state &
STATE_RECOGNIZED)) {
curRecognizer = session.curRecognizer = null;
}
var i = 0;
while (i < recognizers.length) {
recognizer = recognizers[i];
// find out if we are allowed try to recognize the input for this one.
// 1. allow if the session is NOT forced stopped (see the .stop() method)
// 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
// that is being recognized.
// 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
// this can be setup with the `recognizeWith()` method on the recognizer.
if (session.stopped !== FORCED_STOP && ( // 1
!curRecognizer || recognizer == curRecognizer || // 2
recognizer.canRecognizeWith(curRecognizer))) { // 3
recognizer.recognize(inputData);
} else {
recognizer.reset();
}
// if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
// current active recognizer. but only if we don't already have an active recognizer
if (!curRecognizer && recognizer.state & (STATE_BEGAN |
STATE_CHANGED | STATE_ENDED)) {
curRecognizer = session.curRecognizer = recognizer;
}
i++;
}
},
/**
* get a recognizer by its event name.
* @param {Recognizer|String} recognizer
* @returns {Recognizer|Null}
*/
get: function(recognizer) {
if (recognizer instanceof Recognizer) {
return recognizer;
}
var recognizers = this.recognizers;
for (var i = 0; i < recognizers.length; i++) {
if (recognizers[i].options.event == recognizer) {
return recognizers[i];
}
}
return null;
},
/**
* add a recognizer to the manager
* existing recognizers with the same event name will be removed
* @param {Recognizer} recognizer
* @returns {Recognizer|Manager}
*/
add: function(recognizer) {
if (invokeArrayArg(recognizer, 'add', this)) {
return this;
}
// remove existing
var existing = this.get(recognizer.options.event);
if (existing) {
this.remove(existing);
}
this.recognizers.push(recognizer);
recognizer.manager = this;
this.touchAction.update();
return recognizer;
},
/**
* remove a recognizer by name or instance
* @param {Recognizer|String} recognizer
* @returns {Manager}
*/
remove: function(recognizer) {
if (invokeArrayArg(recognizer, 'remove', this)) {
return this;
}
var recognizers = this.recognizers;
recognizer = this.get(recognizer);
recognizers.splice(inArray(recognizers, recognizer), 1);
this.touchAction.update();
return this;
},
/**
* bind event
* @param {String} events
* @param {Function} handler
* @returns {EventEmitter} this
*/
on: function(events, handler) {
var handlers = this.handlers;
each(splitStr(events), function(event) {
handlers[event] = handlers[event] || [];
handlers[event].push(handler);
});
return this;
},
/**
* unbind event, leave emit blank to remove all handlers
* @param {String} events
* @param {Function} [handler]
* @returns {EventEmitter} this
*/
off: function(events, handler) {
var handlers = this.handlers;
each(splitStr(events), function(event) {
if (!handler) {
delete handlers[event];
} else {
handlers[event].splice(inArray(handlers[event], handler),
1);
}
});
return this;
},
/**
* emit event to the listeners
* @param {String} event
* @param {Object} data
*/
emit: function(event, data) {
// we also want to trigger dom events
if (this.options.domEvents) {
triggerDomEvent(event, data);
}
// no handlers, so skip it all
var handlers = this.handlers[event] && this.handlers[event].slice();
if (!handlers || !handlers.length) {
return;
}
data.type = event;
data.preventDefault = function() {
data.srcEvent.preventDefault();
};
var i = 0;
while (i < handlers.length) {
handlers[i](data);
i++;
}
},
/**
* destroy the manager and unbinds all events
* it doesn't unbind dom events, that is the user own responsibility
*/
destroy: function() {
this.element && toggleCssProps(this, false);
this.handlers = {};
this.session = {};
this.input.destroy();
this.element = null;
}
};
/**
* add/remove the css properties as defined in manager.options.cssProps
* @param {Manager} manager
* @param {Boolean} add
*/
function toggleCssProps(manager, add) {
var element = manager.element;
each(manager.options.cssProps, function(value, name) {
element.style[prefixed(element.style, name)] = add ? value :
'';
});
}
/**
* trigger dom event
* @param {String} event
* @param {Object} data
*/
function triggerDomEvent(event, data) {
var gestureEvent = document.createEvent('Event');
gestureEvent.initEvent(event, true, true);
gestureEvent.gesture = data;
data.target.dispatchEvent(gestureEvent);
}
extend(Hammer, {
INPUT_START: INPUT_START,
INPUT_MOVE: INPUT_MOVE,
INPUT_END: INPUT_END,
INPUT_CANCEL: INPUT_CANCEL,
STATE_POSSIBLE: STATE_POSSIBLE,
STATE_BEGAN: STATE_BEGAN,
STATE_CHANGED: STATE_CHANGED,
STATE_ENDED: STATE_ENDED,
STATE_RECOGNIZED: STATE_RECOGNIZED,
STATE_CANCELLED: STATE_CANCELLED,
STATE_FAILED: STATE_FAILED,
DIRECTION_NONE: DIRECTION_NONE,
DIRECTION_LEFT: DIRECTION_LEFT,
DIRECTION_RIGHT: DIRECTION_RIGHT,
DIRECTION_UP: DIRECTION_UP,
DIRECTION_DOWN: DIRECTION_DOWN,
DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
DIRECTION_VERTICAL: DIRECTION_VERTICAL,
DIRECTION_ALL: DIRECTION_ALL,
Manager: Manager,
Input: Input,
TouchAction: TouchAction,
TouchInput: TouchInput,
MouseInput: MouseInput,
PointerEventInput: PointerEventInput,
TouchMouseInput: TouchMouseInput,
SingleTouchInput: SingleTouchInput,
Recognizer: Recognizer,
AttrRecognizer: AttrRecognizer,
Tap: TapRecognizer,
Pan: PanRecognizer,
Swipe: SwipeRecognizer,
Pinch: PinchRecognizer,
Rotate: RotateRecognizer,
Press: PressRecognizer,
on: addEventListeners,
off: removeEventListeners,
each: each,
merge: merge,
extend: extend,
inherit: inherit,
bindFn: bindFn,
prefixed: prefixed
});
// jquery.hammer.js
// This jQuery plugin is just a small wrapper around the Hammer() class.
// It also extends the Manager.emit method by triggering jQuery events.
// $(element).hammer(options).bind("pan", myPanHandler);
// The Hammer instance is stored at $element.data("hammer").
// https://github.com/hammerjs/jquery.hammer.js
(function($, Hammer) {
function hammerify(el, options) {
var $el = $(el);
if (!$el.data('hammer')) {
$el.data('hammer', new Hammer($el[0], options));
}
}
$.fn.hammer = function(options) {
return this.each(function() {
hammerify(this, options);
});
};
// extend the emit method to also trigger jQuery events
Hammer.Manager.prototype.emit = (function(originalEmit) {
return function(type, data) {
originalEmit.call(this, type, data);
$(this.element).trigger({
type: type,
gesture: data
});
};
})(Hammer.Manager.prototype.emit);
})($, Hammer);
$.AMUI.Hammer = Hammer;
module.exports = Hammer;
}).call(this, typeof global !== "undefined" ? global : typeof self !==
"undefined" ? self : typeof window !== "undefined" ? window : {})
}, {
"./core": 2
}
]
}, {}, [1]);
|
"use strict";
exports.__esModule = true;
var _map = require("babel-runtime/core-js/map");
var _map2 = _interopRequireDefault(_map);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn");
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require("babel-runtime/helpers/inherits");
var _inherits3 = _interopRequireDefault(_inherits2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Store = function (_Map) {
(0, _inherits3.default)(Store, _Map);
function Store() {
(0, _classCallCheck3.default)(this, Store);
var _this = (0, _possibleConstructorReturn3.default)(this, _Map.call(this));
_this.dynamicData = {};
return _this;
}
Store.prototype.setDynamic = function setDynamic(key, fn) {
this.dynamicData[key] = fn;
};
Store.prototype.get = function get(key) {
if (this.has(key)) {
return _Map.prototype.get.call(this, key);
} else {
if (Object.prototype.hasOwnProperty.call(this.dynamicData, key)) {
var val = this.dynamicData[key]();
this.set(key, val);
return val;
}
}
};
return Store;
}(_map2.default);
exports.default = Store;
module.exports = exports["default"]; |
var count = (function abs(BigNumber) {
var start = +new Date(),
log,
error,
passed = 0,
total = 0;
if (typeof window === 'undefined') {
log = console.log;
error = console.error;
} else {
log = function (str) { document.body.innerHTML += str.replace('\n', '<br>') };
error = function (str) { document.body.innerHTML += '<div style="color: red">' +
str.replace('\n', '<br>') + '</div>' };
}
if (!BigNumber && typeof require === 'function') BigNumber = require('../bignumber');
function assert(expected, actual) {
total++;
if (expected !== actual) {
error('\n Test number: ' + total + ' failed');
error(' Expected: ' + expected);
error(' Actual: ' + actual);
//process.exit();
}
else {
passed++;
//log('\n Expected and actual: ' + actual);
}
}
function T(expected, value){
assert(String(expected), new BigNumber(String(value)).abs().toString());
}
log('\n Testing abs...');
BigNumber.config({
DECIMAL_PLACES : 20,
ROUNDING_MODE : 4,
ERRORS : true,
RANGE : 1E9,
EXPONENTIAL_AT : [-7, 21]
});
T(1, 1);
T(1, -1);
T(0.5, '0.5');
T(0.5, '-0.5');
T(0.1, 0.1);
T(0.1, -0.1);
T(1.1, 1.1);
T(1.1, -1.1);
T(1.5, '1.5');
T(1.5, '-1.5');
T(0.00001, '-1e-5');
T(9000000000, '-9e9');
T(123456.7891011, -123456.7891011);
T(999.999, '-999.999');
T(99, 99);
T(1, new BigNumber(-1));
T(0.001, new BigNumber(0.001));
T(0.001, new BigNumber('-0.001'));
T('Infinity', Infinity);
T('Infinity', -Infinity);
T(NaN, NaN);
T(NaN, -NaN);
T(0, 0);
T(0, -0);
var minusZero = 1 / (-1 / 0);
function isMinusZero(n) {
return n.toString() === '0' && n.s == -1;
}
T(0, 0);
T(0, -0);
T(0, minusZero);
assert(true, isMinusZero(new BigNumber('-0')));
assert(true, isMinusZero(new BigNumber(minusZero)));
assert(false, isMinusZero(new BigNumber(-0).abs()));
assert(false, isMinusZero(new BigNumber(minusZero).abs()));
assert(true, !isMinusZero(new BigNumber('-0').abs()));
assert(true, !isMinusZero(new BigNumber(minusZero).abs()));
BigNumber.config({EXPONENTIAL_AT : 100});
T(Number.MIN_VALUE, Number.MIN_VALUE);
T(Number.MIN_VALUE, -Number.MIN_VALUE);
T(Number.MAX_VALUE, Number.MAX_VALUE);
T(Number.MAX_VALUE, -Number.MAX_VALUE);
var two_30 = 1 << 30;
T(two_30, two_30);
T(two_30, -two_30);
T(two_30 + 1, two_30 + 1);
T(two_30 + 1, -two_30 - 1);
T(two_30 - 1, two_30 - 1);
T(two_30 - 1, -two_30 + 1);
var two_31 = 2 * two_30;
T(two_31, two_31);
T(two_31, -two_31);
T(two_31 + 1, two_31 + 1);
T(two_31 + 1, -two_31 - 1);
T(two_31 - 1, two_31 - 1);
T(two_31 - 1, -two_31 + 1);
BigNumber.config({ EXPONENTIAL_AT : [-7, 21] });
T(NaN, 'NaN');
T('0', '0');
T('1', '-1');
T('11.121', '11.121');
T('0.023842', '-0.023842');
T('1.19', '-1.19');
T('9.622e-11', '-0.00000000009622');
T('5.09e-10', '-0.000000000509');
T('3838.2', '3838.2');
T('127', '127.0');
T('4.23073', '4.23073');
T('2.5469', '-2.5469');
T('29949', '-29949');
T('277.1', '-277.10');
T('4.97898e-15', '-0.00000000000000497898');
T('53.456', '53.456');
T('100564', '-100564');
T('12431.9', '-12431.9');
T('97633.7', '-97633.7');
T('220', '220');
T('188.67', '-188.67');
T('35', '-35');
T('2.6', '-2.6');
T('2.2e-19', '-0.000000000000000000220');
T('1.469', '-1.469');
T('150.7', '-150.7');
T('74', '-74');
T('3.52e-9', '-0.00000000352');
T('2221.7', '-2221.7');
T('0.000004211', '-0.000004211');
T('1', '-1');
T('5.886', '-5.886');
T('16', '16');
T('4.4493e-9', '0.0000000044493');
T('47.6', '47.6');
T('1.6', '-1.60');
T('1', '-1');
T('1.5', '-1.5');
T('5', '-5');
T('1', '-1');
T('8027', '8027');
T('6.36e-16', '-0.000000000000000636');
T('3.87766', '3.87766');
T('7.4', '-7.4');
T('4.449', '-4.449');
T('5.2218e-19', '-0.000000000000000000522180');
T('1.3769e-11', '-0.000000000013769');
T('7.898e-13', '-0.0000000000007898');
T('522.9', '-522.9');
T('16.1', '-16.1');
T('2.15', '2.15');
T('4.3', '4.3');
T('3', '-3');
T('2.8', '-2.8');
T('1', '-1');
T('0.0000128696', '-0.0000128696');
T('13.33', '-13.33');
T('0.00000132177', '-0.00000132177');
T('1.41516', '-1.41516');
T('180.4', '-180.4');
T('115079', '-115079');
T('959', '959');
T('714.4', '714.4');
T('1.4544', '1.4544');
T('53.691', '53.691');
T('2.03832e-12', '-0.00000000000203832');
T('1', '-1');
T('10.8', '10.8');
T('6189.2', '-6189.2');
T('6.30866', '6.30866');
T('62306', '62306');
T('4', '-4.0');
T('997.1', '-997.1');
T('27.4', '-27.40');
T('9242', '9242');
T('31.1', '-31.1');
T('23.4', '23.4');
T('451818', '-451818');
T('7', '-7');
T('1.9', '-1.9');
T('2', '-2');
T('112.983', '-112.983');
T('9.36e-8', '-0.0000000936');
T('12.8515', '12.8515');
T('73.1', '-73.1');
T('18.15', '18.150');
T('11997.8', '11997.8');
T('23.1', '-23.1');
T('82.022', '-82.022');
T('3.916e-20', '-0.00000000000000000003916');
T('3.3', '-3.3');
T('892.1', '-892.1');
T('24.4', '24.4');
T('72', '72.0');
T('0.0013346', '0.0013346');
T('10.4', '-10.4');
T('367.5', '367.5');
T('7', '-7');
T('127.195', '127.195');
T('7.89e-13', '-0.000000000000789');
T('63', '-63');
T('85821.2', '-85821.2');
T('95.6', '95.6');
T('8.9e-14', '-0.000000000000089');
T('112.1', '-112.1');
T('3.68', '-3.68');
T('9', '-9');
T('0.0000975', '-0.0000975');
T('393.6', '-393.6');
T('7.4', '-7.4');
T('69.62', '-69.62');
T('5201.3', '5201.3');
T('163', '163');
T('4.30732', '4.30732');
T('224.49', '-224.49');
T('319.8', '-319.8');
T('88.1', '-88.1');
T('2.7762e-8', '0.000000027762');
T('2.043e-7', '-0.0000002043');
T('75459.3', '-75459.3');
T('0.178', '0.178');
T('0.00001633', '0.00001633');
T('955', '955');
T('373898', '-373898');
T('9780.1', '9780.1');
T('503.47', '503.47');
T('3.44562', '-3.44562');
T('1.6', '-1.6');
T('1.22442', '-1.22442');
T('1.4', '1.4');
T('1219.1', '-1219.1');
T('2.7', '-2.7');
T('1057', '-1057');
T('1938', '1938');
T('1.1983', '1.1983');
T('0.0012', '-0.0012');
T('95.713', '-95.713');
T('2', '-2');
T('17.24', '-17.24');
T('10.3', '-10.3');
T('1', '-1');
T('65.8', '-65.8');
T('2.9', '2.9');
T('54149', '54149');
T('8', '-8');
T('1', '1.0');
T('4', '-4');
T('6.3', '-6.3');
T('5.25e-9', '0.00000000525');
T('52.3', '-52.3');
T('75290', '-75290');
T('5.9', '-5.9');
T('13.7', '13.7');
T('2.3982e-9', '0.0000000023982');
T('91.5', '-91.50');
T('2072.39', '2072.39');
T('385.6', '385.6');
T('4.77', '4.77');
T('18.72', '18.720');
T('2817', '-2817');
T('44535', '-44535');
T('655', '655');
T('2e-15', '-0.0000000000000020');
T('0.625', '0.6250');
T('2', '-2');
T('5.315', '5.315');
T('70.9', '70.90');
T('6.4', '6.4');
T('1824', '1824');
T('52.595', '52.595');
T('3662', '3662.0');
T('3.1', '3.1');
T('1.05032e-7', '0.000000105032');
T('997.063', '-997.063');
T('41746', '-41746');
T('24.0402', '24.0402');
T('0.009135', '0.009135');
T('2.34e-9', '-0.00000000234');
T('13.1', '13.1');
T('228.8', '228.8');
T('565.85', '565.85');
T('4e-20', '0.000000000000000000040');
T('1.73', '1.73');
T('38.9', '38.9');
T('1.02e-14', '-0.0000000000000102');
T('302.8', '-302.8');
T('7', '-7');
T('1', '-1');
T('0.00247', '0.00247');
T('2', '-2');
T('3.26', '-3.26');
T('8.8', '8.8');
T('90.6', '90.6');
T('8.3053e-17', '-0.000000000000000083053');
T('2.5', '-2.5');
T('376.2', '-376.2');
T('1.29', '1.29');
T('1.379', '-1.379');
T('40921.5', '-40921.5');
T('1', '-1');
T('12.5', '12.5');
T('10.1', '10.1');
T('1', '-1');
T('226636', '226636');
T('1', '-1');
T('1.7', '-1.7');
T('31.31', '31.31');
T('79.9', '-79.9');
T('4.027e-13', '0.0000000000004027');
T('43.838', '43.838');
T('6.47', '-6.47');
T('5.292e-19', '0.0000000000000000005292');
T('4.6', '-4.6');
T('15918', '-15918.0');
T('239.45', '239.45');
T('1.02', '-1.02');
T('14101', '-14101');
T('7', '-7');
T('367.34', '367.34');
T('5', '-5');
T('19.9', '-19.9');
T('269.45', '-269.45');
T('10.34', '-10.34');
T('3.32882e-12', '-0.00000000000332882');
T('5.9', '5.9');
T('9', '-9.0');
T('1.3597', '-1.3597');
T('8', '8.0');
T('1', '1.0');
T('312.5', '312.5');
T('1.554', '-1.554');
T('210.985', '-210.985');
T('1', '-1');
T('1.24', '-1.24');
T('513865', '-513865');
T('6748', '-6748');
T('591.51', '-591.51');
T('2.2', '-2.2');
T('19.5495', '19.5495');
T('3.3', '3.3');
T('30', '-30');
T('94', '-94');
T('217.55', '217.55');
T('2', '-2');
T('99', '99');
T('4.067', '-4.067');
T('702.57', '702.57');
T('3.7', '-3.70');
T('4', '4.0');
T('192944', '192944');
T('0.000022', '0.000022');
T('47.6', '47.60');
T('0.391', '0.3910');
T('35', '-35');
T('100', '-100');
T('3.3', '-3.3');
T('32.432', '32.432');
T('1.07849e-18', '0.00000000000000000107849');
T('2', '-2.0');
T('23.27', '23.27');
T('4.054e-15', '-0.000000000000004054');
T('7.6', '-7.6');
T('1305', '1305');
T('1.501', '-1.501');
T('3.4', '3.4');
T('22.5', '-22.5');
T('1.0916', '1.0916');
T('2', '-2');
T('58.271', '58.271');
T('1.73e-12', '0.00000000000173');
T('1.3458e-15', '0.0000000000000013458');
T('309.87', '-309.87');
T('5.318', '-5.318');
T('1.5302e-8', '0.000000015302');
T('596765', '596765');
T('54.42', '-54.42');
T('6.549e-20', '0.00000000000000000006549');
T('29', '29');
T('46.025', '46.025');
T('2556.78', '-2556.78');
T('0.00287721', '0.00287721');
T('1.63', '-1.63');
T('0.00041', '0.00041');
T('698', '698');
T('134.4', '134.4');
T('2.1', '2.1');
T('2.07', '-2.07');
T('122.869', '122.869');
T('0.00017', '-0.00017');
T('18.6', '18.6');
T('7', '-7');
T('0.0180557', '0.0180557');
T('5', '-5');
T('6.2', '-6.2');
T('8', '-8');
T('450.96', '-450.96');
T('20.2', '-20.2');
T('176.52', '176.52');
T('0.00017', '-0.000170');
T('5', '-5');
T('1', '-1');
T('1.37856e-14', '0.0000000000000137856');
T('76.3048', '76.3048');
T('1803.7', '-1803.7');
T('74', '74');
T('1.7e-12', '0.0000000000017');
T('48.7', '-48.7');
T('4.48', '-4.48');
T('1.4', '-1.4');
T('7.69', '-7.69');
T('23.5987', '23.5987');
T('3074', '3074.0');
T('8.06e-15', '-0.00000000000000806');
T('21.3757', '-21.3757');
T('35', '35');
T('11.056', '11.0560');
T('3.36e-14', '-0.0000000000000336');
T('49139.4', '-49139.4');
T('32.654', '-32.654');
T('34035.4', '34035.4');
T('15.22', '15.22');
T('62', '62.0');
T('8.89156', '-8.89156');
T('14', '14');
T('0.006', '-0.0060');
T('1.5', '1.5');
T('7', '-7');
T('1.6e-11', '0.000000000016');
T('26.6427', '26.6427');
T('1.5e-18', '-0.0000000000000000015');
T('1.52838e-15', '0.00000000000000152838');
T('119.1', '119.1');
T('0.004283', '0.004283');
T('818', '-818');
T('194', '194');
T('104.788', '-104.788');
T('3.74e-11', '0.0000000000374');
T('6.162', '-6.162');
T('5.19214e-18', '-0.00000000000000000519214');
T('1.4', '-1.4');
T('1.27', '-1.27');
T('7.83822e-12', '-0.00000000000783822');
T('1', '-1');
T('4.4', '4.4');
T('7.37382e-12', '0.00000000000737382');
T('13.618', '13.618');
T('1.03', '-1.03');
T('3.7457e-13', '0.00000000000037457');
T('5.2', '-5.2');
T('3.5', '3.5');
T('364', '-364');
T('7.336', '7.336');
T('1.1447e-16', '-0.00000000000000011447');
T('510.63', '-510.63');
T('5.8', '5.8');
T('7.8', '7.8');
T('2.96', '-2.96');
T('15.64', '-15.64');
T('187863', '-187863');
T('2.73', '-2.73');
T('2.671', '-2.671');
T('18.179', '-18.179');
T('855885', '855885');
T('4.16', '4.16');
T('5.722e-18', '0.000000000000000005722');
T('67.62', '67.62');
T('813.31', '813.31');
T('40.2', '40.20');
T('0.00002515', '0.00002515');
T('0.0196', '0.01960');
T('13.165', '13.165');
T('6.743', '-6.743');
T('1', '-1');
T('200.56', '-200.56');
T('1.932', '1.932');
T('92.9', '92.90');
T('16.74', '16.74');
T('4.5554e-7', '-0.00000045554');
T('2.1296e-15', '-0.0000000000000021296');
T('2.088', '2.088');
T('2577', '2577');
T('45.4', '-45.4');
T('41.3', '-41.3');
T('3.63', '-3.63');
T('1.09', '-1.09');
T('1', '-1');
T('3.7', '-3.7');
T('204.54', '204.54');
T('235.6', '235.6');
T('384', '-384');
T('0.0207', '0.02070');
T('680', '680');
T('1.09', '1.09');
T('109.2', '109.2');
T('0.00010117', '0.00010117');
T('13.81', '13.81');
T('192.3', '192.3');
T('1', '-1');
T('1.2', '1.2');
T('4.1', '-4.1');
T('2.5', '2.5');
T('8.4076', '-8.4076');
T('0.0517', '0.0517');
T('6.3923', '-6.3923');
T('506.179', '-506.179');
T('375886', '375886');
T('618858', '-618858');
T('8.5e-11', '0.000000000085');
T('6', '-6.0');
T('2.4', '2.40');
T('0.0000013', '-0.0000013');
T('1.064', '-1.064');
T('1', '-1');
T('4', '-4');
T('4.5', '-4.5');
T('93.6206', '93.6206');
T('3.07e-18', '0.00000000000000000307');
BigNumber.config({EXPONENTIAL_AT : 0});
T('5.2452468128e+1', '-5.2452468128e+1');
T('1.41525905257189365008396e+16', '1.41525905257189365008396e+16');
T('2.743068083928e+11', '2.743068083928e+11');
T('1.52993064722314247378724599e+26', '-1.52993064722314247378724599e+26');
T('3.7205576746e+10', '3.7205576746e+10');
T('8.680996444609343472665e+17', '8.680996444609343472665e+17');
T('1.254549e+3', '1.254549e+3');
T('6.23417196172381875892300762819e-18', '6.23417196172381875892300762819e-18');
T('1.31179940821919284431e+19', '1.31179940821919284431e+19');
T('9.7697726168e+7', '9.7697726168e+7');
T('2.663e-10', '-2.663e-10');
T('1.26574209965030360615518e+17', '-1.26574209965030360615518e+17');
T('1.052e+3', '1.052e+3');
T('4.452945872502e+6', '-4.452945872502e+6');
T('2.95732460816619226e+13', '2.95732460816619226e+13');
T('1.1923100194288654481424e+18', '-1.1923100194288654481424e+18');
T('8.99315449050893705e+6', '8.99315449050893705e+6');
T('5.200726538434486963e+8', '5.200726538434486963e+8');
T('1.182618278949368566264898065e+18', '1.182618278949368566264898065e+18');
T('3.815873266712e-20', '-3.815873266712e-20');
T('1.316675370382742615e+6', '-1.316675370382742615e+6');
T('2.1032502e+6', '-2.1032502e+6');
T('1.8e+1', '1.8e+1');
T('1.033525906631680944018544811261e-13', '1.033525906631680944018544811261e-13');
T('1.102361746443461856816e+14', '-1.102361746443461856816e+14');
T('8.595358491143959e+1', '8.595358491143959e+1');
T('3.6908859412618413e+9', '-3.6908859412618413e+9');
T('2.25907048615912944e+5', '-2.25907048615912944e+5');
T('1.7441871813329475518e+19', '-1.7441871813329475518e+19');
T('3.805493087068952925e-11', '-3.805493087068952925e-11');
T('3.58049465451e+9', '-3.58049465451e+9');
T('8.0688614291e+10', '-8.0688614291e+10');
T('3.337855e+4', '-3.337855e+4');
T('2.59977855e+8', '2.59977855e+8');
T('4.96353e+4', '-4.96353e+4');
T('7.47233581107861762e-13', '7.47233581107861762e-13');
T('1.73948e-2', '1.73948e-2');
T('5.784e-15', '5.784e-15');
T('4.448338479762497e-8', '4.448338479762497e-8');
T('3.9008023052e+8', '3.9008023052e+8');
T('3e+0', '3e+0');
T('8.61435e-9', '8.61435e-9');
T('4.37e+1', '-4.37e+1');
T('8.4034159379836e-18', '-8.4034159379836e-18');
T('2.002857355721079885824481e+7', '2.002857355721079885824481e+7');
T('7.000871862e+6', '-7.000871862e+6');
T('2.2902057767e+9', '2.2902057767e+9');
T('5.9896443375617e+8', '5.9896443375617e+8');
T('1.53503650707e-11', '-1.53503650707e-11');
T('2.0508347e+6', '2.0508347e+6');
T('4.789433e+2', '-4.789433e+2');
T('8.28161975302168665599e+11', '8.28161975302168665599e+11');
T('1.2518396296278445e-5', '1.2518396296278445e-5');
T('1.44290332e+8', '-1.44290332e+8');
T('4.6570237501625609051773e-12', '4.6570237501625609051773e-12');
T('7.8514960198282212436e+19', '7.8514960198282212436e+19');
T('1.6197e-20', '1.6197e-20');
T('6.51635176e+0', '-6.51635176e+0');
T('4.49618e+3', '-4.49618e+3');
T('1.32052259561417e-1', '-1.32052259561417e-1');
T('2.09089580968e-18', '2.09089580968e-18');
T('1.4064735615678257623873854709e-1', '1.4064735615678257623873854709e-1');
T('3.14172e+0', '-3.14172e+0');
T('1.7458792e+1', '1.7458792e+1');
T('9.97831655282e+11', '9.97831655282e+11');
T('1.94594e+1', '-1.94594e+1');
T('1.2174602334491e+5', '-1.2174602334491e+5');
T('1.12135222651239e+6', '-1.12135222651239e+6');
T('6.3160490484343918e-20', '6.3160490484343918e-20');
T('1.9238315686509393329629520842e+24', '1.9238315686509393329629520842e+24');
T('9.915274405618026e+11', '-9.915274405618026e+11');
T('2.3564687894712721487205001557e+28', '2.3564687894712721487205001557e+28');
T('8.127315365677288172165e+2', '8.127315365677288172165e+2');
T('4.93e+0', '-4.93e+0');
T('1.41530382e+0', '-1.41530382e+0');
T('4.86451432707435321820779e+19', '-4.86451432707435321820779e+19');
T('1.4162540859e+0', '-1.4162540859e+0');
T('4.646e+2', '-4.646e+2');
T('2.1172e-14', '-2.1172e-14');
T('8.69000536011392432707132752e-11', '8.69000536011392432707132752e-11');
T('2.52776394053478133209e+20', '2.52776394053478133209e+20');
T('8.500211152e+9', '8.500211152e+9');
T('1.36178922026634255436879e+23', '1.36178922026634255436879e+23');
T('4.6398705910903109e+3', '-4.6398705910903109e+3');
T('2.15872185740218265392874524e+18', '2.15872185740218265392874524e+18');
T('2.4663508855569609277266393e-3', '-2.4663508855569609277266393e-3');
T('5.247072789229625795e+11', '-5.247072789229625795e+11');
T('1.142743622516581e-15', '-1.142743622516581e-15');
T('3.70055552960951165e-4', '-3.70055552960951165e-4');
T('1.01218e+3', '1.01218e+3');
T('3.622286100282e+2', '3.622286100282e+2');
T('9.5526239814e+3', '9.5526239814e+3');
T('2.7619598176203983624994361644e+28', '2.7619598176203983624994361644e+28');
T('6.8696488497688008067537526e-6', '6.8696488497688008067537526e-6');
T('2.48936e+1', '2.48936e+1');
T('3.27658301230616e+14', '3.27658301230616e+14');
T('2.1887387e+0', '-2.1887387e+0');
T('1.4779696309033248e+16', '1.4779696309033248e+16');
T('1.471782313713309789663e+4', '1.471782313713309789663e+4');
T('2.0674554e+2', '-2.0674554e+2');
T('1.763392540310312024e+9', '1.763392540310312024e+9');
T('2.66209467493293140387227569744e+26', '-2.66209467493293140387227569744e+26');
T('1.4522423854706487171671160683e-16', '1.4522423854706487171671160683e-16');
T('5.5534571375626084341933639e-18', '-5.5534571375626084341933639e-18');
T('3.670610508911e-18', '-3.670610508911e-18');
T('1.8e+1', '1.8e+1');
T('4.21466540619392e+14', '-4.21466540619392e+14');
T('4.57881788773078611890575215e-13', '-4.57881788773078611890575215e-13');
T('1.14912007700989046355e+20', '1.14912007700989046355e+20');
T('1.10572e+0', '1.10572e+0');
T('5.45027073427600086838788178e+8', '5.45027073427600086838788178e+8');
T('5.3607527344097728e-14', '-5.3607527344097728e-14');
T('1.20985e+0', '1.20985e+0');
T('2.173758396975e+4', '-2.173758396975e+4');
T('1.443459545123362e+10', '1.443459545123362e+10');
T('8.26154936079048787963e-19', '8.26154936079048787963e-19');
T('1.24e+0', '-1.24e+0');
T('6.61e+1', '6.61e+1');
T('8.37241281e-15', '-8.37241281e-15');
T('1.4673863119972e+5', '1.4673863119972e+5');
T('1.052445707646628e+15', '1.052445707646628e+15');
T('2.770216401480935105227985046e+0', '2.770216401480935105227985046e+0');
T('1e-2', '-1e-2');
T('2.0530189404000503380382112e+7', '-2.0530189404000503380382112e+7');
T('7.73428930734513129e+5', '7.73428930734513129e+5');
T('2.969e-2', '2.969e-2');
T('3.355869237729311e-19', '3.355869237729311e-19');
T('7.585426017526e+3', '7.585426017526e+3');
T('1.6544419963706446557685646278e+23', '-1.6544419963706446557685646278e+23');
T('2.92136474375552641396809118574e-18', '2.92136474375552641396809118574e-18');
T('3.38424409165604660854e+4', '-3.38424409165604660854e+4');
T('1.173591570196350093112e+11', '-1.173591570196350093112e+11');
T('7.8375092064291352e+1', '-7.8375092064291352e+1');
T('1.88191e+3', '1.88191e+3');
T('4.6761e-2', '-4.6761e-2');
T('5.988129995539574e+10', '5.988129995539574e+10');
T('2.5390529009345115e+2', '2.5390529009345115e+2');
T('2.132229656150917182e+5', '-2.132229656150917182e+5');
T('1.0719725506854825717e-19', '-1.0719725506854825717e-19');
T('4.3681500769125575941008112847e+28', '-4.3681500769125575941008112847e+28');
T('1.35927075893264893848008382e-13', '-1.35927075893264893848008382e-13');
T('1.9240692976139e-18', '-1.9240692976139e-18');
T('4.49668506275546883445e+20', '4.49668506275546883445e+20');
T('5.19198662387790072e+9', '5.19198662387790072e+9');
T('1.51188431866457089e+16', '-1.51188431866457089e+16');
T('1.4463331863500941e+12', '1.4463331863500941e+12');
T('1e+0', '-1e+0');
T('2.50029927958615945e+1', '-2.50029927958615945e+1');
T('1.001415164502846757e+3', '-1.001415164502846757e+3');
T('1.45526428e+8', '-1.45526428e+8');
T('5.813181844e-3', '-5.813181844e-3');
T('2.4481022856740302965057941113e+10', '2.4481022856740302965057941113e+10');
T('5.55e+1', '-5.55e+1');
T('3.36356932710712e+11', '-3.36356932710712e+11');
T('5.28080163e+8', '5.28080163e+8');
T('5.3879740593083469994135e+13', '-5.3879740593083469994135e+13');
T('6.6759148438881472902e+19', '-6.6759148438881472902e+19');
T('1.26e-20', '1.26e-20');
T('1.005680289388988e+10', '-1.005680289388988e+10');
T('1.4855958598e+0', '-1.4855958598e+0');
T('2.94014963598446075495453768e+24', '-2.94014963598446075495453768e+24');
T('5.219896118644e+12', '-5.219896118644e+12');
T('6.8e+0', '-6.8e+0');
T('5.492e-9', '-5.492e-9');
T('1.0038e+4', '-1.0038e+4');
T('2.781382585e+5', '2.781382585e+5');
T('3.30150670653876784e+17', '-3.30150670653876784e+17');
T('1.87927e+5', '-1.87927e+5');
T('1.4774557974305197453804758396e+16', '-1.4774557974305197453804758396e+16');
T('6.05644990832733182152086098e+18', '-6.05644990832733182152086098e+18');
T('2.78459055955765755e-14', '-2.78459055955765755e-14');
T('2.66385931106395122e+6', '2.66385931106395122e+6');
T('3.3683073647556597682246e-9', '-3.3683073647556597682246e-9');
T('7.081e+2', '7.081e+2');
T('2.73122035866217320954404e+6', '2.73122035866217320954404e+6');
T('1.2434001e-7', '1.2434001e-7');
T('1.135877627944001e+14', '1.135877627944001e+14');
T('5.59534951548380080886141393126e+21', '5.59534951548380080886141393126e+21');
T('5.7723782191795798882571e+9', '-5.7723782191795798882571e+9');
T('1.5162957113185485632499369443e-12', '-1.5162957113185485632499369443e-12');
T('4.29309951955288963780116e+6', '4.29309951955288963780116e+6');
T('3.9722643229317825409e+13', '3.9722643229317825409e+13');
T('1.011489199242414759e-17', '1.011489199242414759e-17');
T('1.253643670639200989056241e-19', '-1.253643670639200989056241e-19');
T('4.4836025129185e+8', '4.4836025129185e+8');
T('6.3777231879677253018091496e-20', '6.3777231879677253018091496e-20');
T('4.76278478201471177044e+11', '4.76278478201471177044e+11');
T('1.05e+2', '-1.05e+2');
T('8.2407974521826916377252018422e+18', '8.2407974521826916377252018422e+18');
T('2.00932156087e+4', '2.00932156087e+4');
T('1.965992456941204354956867603e-17', '-1.965992456941204354956867603e-17');
T('5.333218599567659131313e+2', '-5.333218599567659131313e+2');
T('1.286162439284e+10', '-1.286162439284e+10');
T('8.1336617205815143346477183e+16', '-8.1336617205815143346477183e+16');
T('1.762845949430042e+13', '-1.762845949430042e+13');
T('7.837280986421e+12', '7.837280986421e+12');
T('2.84048190010833793e+13', '2.84048190010833793e+13');
T('3.25755301782427035301e+20', '-3.25755301782427035301e+20');
T('2.58959421885729898387238225e+13', '2.58959421885729898387238225e+13');
T('1.8851093513683294449e+10', '-1.8851093513683294449e+10');
T('1.21916240456196024666e+20', '-1.21916240456196024666e+20');
T('5.840503333749926899855535241e-6', '5.840503333749926899855535241e-6');
T('2.998914116e+4', '2.998914116e+4');
T('5.97277308650934e+10', '5.97277308650934e+10');
T('6.56e+2', '6.56e+2');
T('1.56235984592541e+12', '-1.56235984592541e+12');
T('3.71e+1', '3.71e+1');
T('5.41937441824138694e+16', '-5.41937441824138694e+16');
T('6.116633e-5', '-6.116633e-5');
T('5.45e+2', '-5.45e+2');
T('2.9449785444e+3', '-2.9449785444e+3');
T('6.6706550091070638245894e+7', '-6.6706550091070638245894e+7');
T('1.39231027e-9', '1.39231027e-9');
T('7.45311483e+8', '7.45311483e+8');
T('7.6856950378651228179663e+18', '7.6856950378651228179663e+18');
T('3.094636736003620629e+8', '-3.094636736003620629e+8');
T('5.876896131624540495694931644e+7', '-5.876896131624540495694931644e+7');
T('1.10975974e+8', '-1.10975974e+8');
T('1.741e+0', '1.741e+0');
T('2.351595813466272408066e-4', '-2.351595813466272408066e-4');
T('1.519156959043394168562e+20', '1.519156959043394168562e+20');
T('1.620081571051799e+7', '1.620081571051799e+7');
T('7.316815038867932520586761e+23', '7.316815038867932520586761e+23');
T('3.094134522833396822e+0', '3.094134522833396822e+0');
T('1.168234556e+2', '-1.168234556e+2');
T('1.503324779432e+4', '1.503324779432e+4');
T('5.6710777e-9', '5.6710777e-9');
T('2.1463873346182e-6', '2.1463873346182e-6');
T('1.2934324795526700185311026007e+28', '-1.2934324795526700185311026007e+28');
T('1.237009087265757433674283664e+11', '1.237009087265757433674283664e+11');
T('1.226806049797304683867e-18', '1.226806049797304683867e-18');
T('5e+0', '-5e+0');
T('1.091168788407093537887970016e+15', '-1.091168788407093537887970016e+15');
T('3.87166413612272027e+12', '3.87166413612272027e+12');
T('1.411514e+5', '1.411514e+5');
T('1.0053454672509859631996e+22', '1.0053454672509859631996e+22');
T('6.9265714e+0', '6.9265714e+0');
T('1.04627709e+4', '1.04627709e+4');
T('1.74378341199e+9', '1.74378341199e+9');
T('8.427721739784805398864e+21', '-8.427721739784805398864e+21');
T('3.0433401636913618083715e-20', '3.0433401636913618083715e-20');
T('8.596751182989204e-17', '8.596751182989204e-17');
T('2.83012114501087201358049280895e-3', '2.83012114501087201358049280895e-3');
T('6.0621417107465763e-13', '6.0621417107465763e-13');
T('7.927e+0', '7.927e+0');
T('1.95309091153617e+6', '-1.95309091153617e+6');
T('3.479245772e-4', '3.479245772e-4');
T('9.1256366370332e-20', '-9.1256366370332e-20');
T('6.357737394e-19', '-6.357737394e-19');
T('4.016038725869e-1', '4.016038725869e-1');
T('2.3600611340992838105408e-2', '-2.3600611340992838105408e-2');
T('1.1982e+3', '1.1982e+3');
T('1.895744317788222501065084139e+17', '1.895744317788222501065084139e+17');
T('3.2450271098259184465439822499e+5', '3.2450271098259184465439822499e+5');
T('1.1699868235212007000965506e+25', '-1.1699868235212007000965506e+25');
T('7.988985662262809183538221216e+27', '-7.988985662262809183538221216e+27');
T('1.476540158366695285164548325e+7', '-1.476540158366695285164548325e+7');
T('8.8357361253e+1', '-8.8357361253e+1');
T('2.6019583787920961e+15', '-2.6019583787920961e+15');
T('2.617913486220978003463345e+24', '2.617913486220978003463345e+24');
T('8.22380392476331112656616e+14', '-8.22380392476331112656616e+14');
T('5.738943e+2', '-5.738943e+2');
T('1.04315155601043625824403526143e+24', '-1.04315155601043625824403526143e+24');
T('5.1800101324564241e-1', '-5.1800101324564241e-1');
T('3.5101750876959537987e-8', '3.5101750876959537987e-8');
T('2.1857385393e+3', '-2.1857385393e+3');
T('2.29674272702302434336e+13', '2.29674272702302434336e+13');
T('2.64606405319747e+14', '2.64606405319747e+14');
T('2.1888980498865372455451e+1', '-2.1888980498865372455451e+1');
T('1.51602e+0', '-1.51602e+0');
T('5.8047548e+7', '5.8047548e+7');
T('1.17525103769842428108679e+6', '-1.17525103769842428108679e+6');
T('8.47642371517851e-1', '-8.47642371517851e-1');
T('6.0574e+0', '-6.0574e+0');
T('2.59202859815854485362744156646e-3', '2.59202859815854485362744156646e-3');
T('1.040746238422014004691755e+15', '1.040746238422014004691755e+15');
T('1.7064734811115159257936e+22', '-1.7064734811115159257936e+22');
T('7.26051238227573319908663048e+26', '7.26051238227573319908663048e+26');
T('7.4795685183599759424050861e+6', '-7.4795685183599759424050861e+6');
T('2.9817e-16', '-2.9817e-16');
T('2.298907884272330951e+6', '2.298907884272330951e+6');
T('4.0531847e-8', '4.0531847e-8');
T('2.6189e+4', '-2.6189e+4');
T('3.911906e+3', '-3.911906e+3');
T('9.408498865993245868145865993e+2', '-9.408498865993245868145865993e+2');
T('4.05451047373376774e-7', '4.05451047373376774e-7');
T('2.08836709959016517e+6', '-2.08836709959016517e+6');
T('6.3417891663e+10', '6.3417891663e+10');
T('8.08596745e+9', '8.08596745e+9');
T('2.5865615419545921e+13', '2.5865615419545921e+13');
T('1.5731674925482283378868e+22', '-1.5731674925482283378868e+22');
T('1.19068602e+1', '-1.19068602e+1');
T('5.3687670881355020502668e-3', '-5.3687670881355020502668e-3');
T('1.2488884456407e+10', '-1.2488884456407e+10');
T('2.51800212e+3', '-2.51800212e+3');
T('3.738131519976930832896022e+24', '-3.738131519976930832896022e+24');
T('6e+0', '6e+0');
T('1.24131e+5', '-1.24131e+5');
T('9.22635e+3', '-9.22635e+3');
T('4e+0', '4e+0');
T('1.83e+1', '1.83e+1');
T('1.846025e+6', '-1.846025e+6');
T('1.27e+1', '1.27e+1');
T('2.24e+1', '2.24e+1');
T('2.476323257183413822109348e-18', '-2.476323257183413822109348e-18');
T('1.926752842e-7', '1.926752842e-7');
T('8.80612762892681839383e-19', '8.80612762892681839383e-19');
T('1.101085e+3', '-1.101085e+3');
T('3.4906077350467600648759e+22', '3.4906077350467600648759e+22');
T('1.04494855994965735236868e+23', '1.04494855994965735236868e+23');
T('1.58387879923230822739579e+19', '1.58387879923230822739579e+19');
T('4.213902971419525700930675e+19', '-4.213902971419525700930675e+19');
T('9.13804011600009749427632034e+0', '9.13804011600009749427632034e+0');
T('1.84491548817806624708211e+23', '-1.84491548817806624708211e+23');
T('1.948625124086563483825890385e+22', '1.948625124086563483825890385e+22');
T('1.3e+0', '1.3e+0');
T('1.32939216745e+12', '1.32939216745e+12');
T('7.078251628e+6', '7.078251628e+6');
T('1.7313022e+2', '1.7313022e+2');
T('3.415584872774897359156e+0', '3.415584872774897359156e+0');
T('5.51297107980065895009041695e+23', '5.51297107980065895009041695e+23');
T('2.5113503918614988744859e-15', '2.5113503918614988744859e-15');
T('1.630239450859331215249576367e+27', '1.630239450859331215249576367e+27');
T('5.4721390329589760404415744136e+18', '-5.4721390329589760404415744136e+18');
T('2.945751278429364126367812e-17', '2.945751278429364126367812e-17');
T('4.2782880893227686126997e+4', '4.2782880893227686126997e+4');
T('1.9847055931e+1', '-1.9847055931e+1');
T('2.261026e+3', '-2.261026e+3');
T('1.52615708575e+9', '1.52615708575e+9');
T('4.55553743697189921932e+5', '-4.55553743697189921932e+5');
T('4.222829719336993778496867e+12', '4.222829719336993778496867e+12');
T('4.485e+3', '4.485e+3');
T('5.2e+0', '-5.2e+0');
T('1.845091473820299081635836e+6', '1.845091473820299081635836e+6');
T('5.46863948617381450255744e-14', '-5.46863948617381450255744e-14');
T('3.0245e+4', '3.0245e+4');
T('1.53486267119215101935302e-6', '-1.53486267119215101935302e-6');
T('6.4843132478784299210571e+16', '6.4843132478784299210571e+16');
T('4.386363241636966071e+13', '-4.386363241636966071e+13');
T('7.581683508504e+6', '7.581683508504e+6');
T('1.09730944345409824e+16', '1.09730944345409824e+16');
T('3.594503e+6', '-3.594503e+6');
T('4.443273220375505949638436659e+1', '4.443273220375505949638436659e+1');
T('1.70867026016477719112e+20', '-1.70867026016477719112e+20');
T('1.29553439888e+11', '-1.29553439888e+11');
T('1.1130502308247230952431e-11', '1.1130502308247230952431e-11');
T('6.058565749e+10', '-6.058565749e+10');
T('3.87180284987679e-10', '-3.87180284987679e-10');
T('3.49184930268913133535e+19', '3.49184930268913133535e+19');
T('9e+0', '9e+0');
T('1.28461567447442016927071963077e-8', '-1.28461567447442016927071963077e-8');
T('2.72815445800161137e-19', '2.72815445800161137e-19');
T('5.849268583211e-4', '5.849268583211e-4');
T('3.19417089569942412006e+3', '-3.19417089569942412006e+3');
T('1.9e+1', '-1.9e+1');
T('3.3872886317814608310483125577e+6', '3.3872886317814608310483125577e+6');
T('3.99977971703789643632671956e+9', '-3.99977971703789643632671956e+9');
T('1.998549e-5', '1.998549e-5');
T('7.18512424913e-15', '7.18512424913e-15');
T('9.365052273317995234261e+21', '9.365052273317995234261e+21');
T('2.569e+3', '-2.569e+3');
T('9.460553674215355e+3', '-9.460553674215355e+3');
T('1.22541e+2', '-1.22541e+2');
T('2.180882957e-2', '-2.180882957e-2');
T('3.963983308804e-5', '3.963983308804e-5');
T('4.9059909584804e+11', '4.9059909584804e+11');
T('3.89345544e+8', '-3.89345544e+8');
T('3.13811755993550161609599737307e+9', '3.13811755993550161609599737307e+9');
T('2.1684124657298e+7', '2.1684124657298e+7');
T('4e+0', '4e+0');
T('1.89e+1', '-1.89e+1');
T('1.0500428125617165569673e+6', '1.0500428125617165569673e+6');
T('3.45971690973815432646e+9', '-3.45971690973815432646e+9');
T('4e+0', '-4e+0');
T('1.2826728638181755448600624e+4', '-1.2826728638181755448600624e+4');
T('5.2490288314345e+5', '5.2490288314345e+5');
T('8.46401e+0', '8.46401e+0');
T('2.15070506987596858e-9', '2.15070506987596858e-9');
T('1.4569180505e+5', '-1.4569180505e+5');
T('1.75535288191468954993283e+8', '-1.75535288191468954993283e+8');
T('1.83e-19', '1.83e-19');
T('3.77847393193912874449578e+6', '3.77847393193912874449578e+6');
T('2.823610210086368e+0', '2.823610210086368e+0');
T('3.2326e+4', '-3.2326e+4');
T('7.21208310236919171558e+7', '-7.21208310236919171558e+7');
T('2.537182162994085967e+11', '2.537182162994085967e+11');
T('2.4881474405e-15', '2.4881474405e-15');
T('6.8484737e+6', '6.8484737e+6');
T('8.09636762896763e+1', '8.09636762896763e+1');
T('1.387805e+1', '-1.387805e+1');
T('1.949086825141843503e-3', '-1.949086825141843503e-3');
T('8.22006002683570972726913386e+26', '-8.22006002683570972726913386e+26');
T('8.82e+1', '-8.82e+1');
T('9.8e+0', '-9.8e+0');
T('5.73018e+5', '-5.73018e+5');
T('2.039854296e-18', '2.039854296e-18');
T('3.85806698884e+2', '3.85806698884e+2');
T('7.761351239715879e-15', '-7.761351239715879e-15');
T('2.37976961448611739e-13', '2.37976961448611739e-13');
T('1.625694436559179391897024e-12', '-1.625694436559179391897024e-12');
T('2.612e+1', '-2.612e+1');
T('8.317023570754122191146041e+24', '8.317023570754122191146041e+24');
T('8.128823e-9', '8.128823e-9');
T('3.316888938212137e-7', '3.316888938212137e-7');
T('4.590734e+2', '4.590734e+2');
T('9.95284154681380079083087718e-7', '9.95284154681380079083087718e-7');
T('1.379051e-15', '1.379051e-15');
T('2.543347781939297185736e+21', '-2.543347781939297185736e+21');
T('1.41496183748704601485699e-10', '-1.41496183748704601485699e-10');
T('3.11665e+5', '-3.11665e+5');
T('6.4377728353162694052697e+1', '6.4377728353162694052697e+1');
T('1.36920115218557491e+17', '1.36920115218557491e+17');
T('1.27e+1', '-1.27e+1');
T('5.1e-4', '5.1e-4');
T('4.124e+3', '4.124e+3');
T('7.96e+0', '7.96e+0');
T('1.0109019145999979839008159507e-20', '1.0109019145999979839008159507e-20');
T('1.507784067070212e+12', '1.507784067070212e+12');
T('5.03530585620864526983697e+10', '5.03530585620864526983697e+10');
T('5.87771648701709094e-3', '-5.87771648701709094e-3');
T('2.6641175511284360931e+19', '2.6641175511284360931e+19');
T('3.5430949752e+3', '-3.5430949752e+3');
T('1.434481e+6', '1.434481e+6');
T('6.95e+0', '6.95e+0');
T('2.7922814988487634078255e+17', '2.7922814988487634078255e+17');
T('1e+0', '-1e+0');
T('1.34094272275111823704509269719e+9', '-1.34094272275111823704509269719e+9');
T('5.2e+0', '5.2e+0');
T('5.961731008805248930549e+0', '5.961731008805248930549e+0');
T('1.95863217313239788358925850999e+27', '1.95863217313239788358925850999e+27');
T('1.115927378282807678794111117e+18', '-1.115927378282807678794111117e+18');
T('6.6448e-6', '-6.6448e-6');
T('1.210298078691983e-7', '1.210298078691983e-7');
T('1.55022703113469956595e+8', '-1.55022703113469956595e+8');
T('2.519409262126392490249e+9', '-2.519409262126392490249e+9');
T('8.3744112435155841906e+19', '8.3744112435155841906e+19');
T('5.56052914013431e-4', '5.56052914013431e-4');
T('1.847716075495989e+13', '-1.847716075495989e+13');
T('5.78580529835020695846e+19', '-5.78580529835020695846e+19');
T('7.3177e-15', '-7.3177e-15');
T('5.8018949e+6', '-5.8018949e+6');
T('1.234850494854913982840923624126e+30', '1.234850494854913982840923624126e+30');
T('3.1e+0', '3.1e+0');
T('3.085340434810406103e+4', '3.085340434810406103e+4');
T('1.461332e+6', '1.461332e+6');
T('2.042933164181166e-9', '2.042933164181166e-9');
T('1.14852656434391849784404293276e-6', '1.14852656434391849784404293276e-6');
T('8.56930722573e-11', '8.56930722573e-11');
T('7.753629727831898e+11', '7.753629727831898e+11');
T('2.5807119689e+5', '-2.5807119689e+5');
T('6.5889872564e+7', '6.5889872564e+7');
T('6.2e+0', '6.2e+0');
T('7.16926024589772e+14', '-7.16926024589772e+14');
T('2.444762609546357e-12', '2.444762609546357e-12');
T('1.58017211706879e+2', '-1.58017211706879e+2');
T('2.74612804105217564273009e+23', '-2.74612804105217564273009e+23');
T('8.2105e+3', '-8.2105e+3');
T('6.2289747e+7', '-6.2289747e+7');
T('4.47847136680063365276e+21', '-4.47847136680063365276e+21');
T('7.599263848474204e+15', '-7.599263848474204e+15');
T('9.534064037670226206e-11', '-9.534064037670226206e-11');
T('5.3511395608925655035624181e+7', '-5.3511395608925655035624181e+7');
T('2.536656469414e+8', '2.536656469414e+8');
T('4.454301005499233196018257e+16', '-4.454301005499233196018257e+16');
T('2.3289800995961777747097e+10', '-2.3289800995961777747097e+10');
T('2.7363696755334e+6', '-2.7363696755334e+6');
T('2.56e+2', '2.56e+2');
T('7.3430201092837e+2', '7.3430201092837e+2');
T('1.114804e+5', '1.114804e+5');
T('3.1845809556698336607622e+4', '-3.1845809556698336607622e+4');
T('1.7780378655260403138e+19', '-1.7780378655260403138e+19');
T('3.608970926e-15', '3.608970926e-15');
T('1.949e+3', '-1.949e+3');
T('1.9021837e+4', '-1.9021837e+4');
T('1.5e+0', '1.5e+0');
T('3.1155266673e+10', '-3.1155266673e+10');
T('4e+0', '-4e+0');
T('9.09316542545977506e+14', '9.09316542545977506e+14');
T('2.15531740334146749845e+8', '2.15531740334146749845e+8');
T('1.5605317646e+8', '1.5605317646e+8');
T('3.8806066633613066e+13', '-3.8806066633613066e+13');
T('1.653298e+6', '1.653298e+6');
T('7.920024310736e-20', '7.920024310736e-20');
T('2.27611872e+8', '2.27611872e+8');
T('2.76569307109179036145271e-15', '-2.76569307109179036145271e-15');
T('1.425171314e+8', '1.425171314e+8');
T('1.3702555167748408653e+11', '-1.3702555167748408653e+11');
T('5.146936435e+9', '5.146936435e+9');
T('4.183285814905222880076696e+19', '-4.183285814905222880076696e+19');
T('2.270923702039578057376e-16', '2.270923702039578057376e-16');
T('9.4963549e-12', '9.4963549e-12');
T('1.453060439e-3', '1.453060439e-3');
T('2.97303365e+2', '2.97303365e+2');
T('1.16485757109e+2', '-1.16485757109e+2');
T('7.7984946334626919799413338378e+5', '-7.7984946334626919799413338378e+5');
T('1.905453e+5', '1.905453e+5');
T('5.36989497616503e-20', '5.36989497616503e-20');
T('4.3e+0', '4.3e+0');
T('2.70434008699476809368089518776e+25', '-2.70434008699476809368089518776e+25');
T('2.8813069851e+10', '2.8813069851e+10');
T('7e+0', '7e+0');
T('1.0577487e-18', '-1.0577487e-18');
T('6.8e+1', '6.8e+1');
T('1e+0', '-1e+0');
T('8.446803887694575079e+6', '-8.446803887694575079e+6');
T('2.3384835e-6', '-2.3384835e-6');
T('1.072e-13', '1.072e-13');
T('7.13295350162e-5', '7.13295350162e-5');
T('4.59897478609e+3', '4.59897478609e+3');
T('4.11875744698515118e+11', '4.11875744698515118e+11');
T('3.12339620225171e+5', '3.12339620225171e+5');
T('3.79932554e+1', '3.79932554e+1');
T('2.457332691061964e+4', '-2.457332691061964e+4');
T('3.944602320705902e+6', '-3.944602320705902e+6');
T('3.164305812145e+4', '-3.164305812145e+4');
T('7.22239735515689399e+1', '-7.22239735515689399e+1');
T('5.261981e+3', '-5.261981e+3');
T('2.3642968462845e+7', '2.3642968462845e+7');
T('3.9326785e+3', '-3.9326785e+3');
T('8.5853e-11', '-8.5853e-11');
T('2.60532943946e+0', '2.60532943946e+0');
T('3.64630216318427246476533e+18', '-3.64630216318427246476533e+18');
T('3.031732127749e-3', '3.031732127749e-3');
T('2.49298080885329502254338e-12', '-2.49298080885329502254338e-12');
T('8.81838341457179780743504843e+2', '-8.81838341457179780743504843e+2');
T('2.285650225267766689304972e+5', '2.285650225267766689304972e+5');
T('4.5790517211306242e+7', '4.5790517211306242e+7');
T('3.0033340092338313923473428e+16', '-3.0033340092338313923473428e+16');
T('2.83879929283797623e+1', '-2.83879929283797623e+1');
T('4.5266377717178121183759377414e-5', '4.5266377717178121183759377414e-5');
T('5.3781e+4', '-5.3781e+4');
T('6.722035208213298413522819127e-18', '-6.722035208213298413522819127e-18');
T('3.02865707828281230987116e+23', '-3.02865707828281230987116e+23');
T('5.5879983320336874473209567979e+28', '-5.5879983320336874473209567979e+28');
log('\n ' + passed + ' of ' + total + ' tests passed in ' + (+new Date() - start) + ' ms \n');
return [passed, total];;
})(this.BigNumber);
if (typeof module !== 'undefined' && module.exports) module.exports = count; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.