code
stringlengths
2
1.05M
var path = require('path'); var config = { entry: ['webpack/hot/dev-server', path.resolve(__dirname, '../demo.js')], output: { path: path.resolve(__dirname, '../demo'), filename: 'AbsoluteGrid.js' }, module: { loaders: [{ test: /\.jsx?$/, // A regexp to test the require path. accepts either js or jsx loader: 'babel' // The module to load. "babel" is short for "babel-loader" }] } }; module.exports = config;
JSIL.ImplementExternals("System.IO.DirectoryInfo", function ($) { $.Method({ Static: false, Public: true }, ".ctor", (new JSIL.MethodSignature(null, [$.String], [])), function _ctor(path) { var storageRoot = JSIL.Host.getStorageRoot(); if (storageRoot) this.$fromNodeAndPath(storageRoot.resolvePath(path, false), storageRoot.normalizePath(path)); else this.$fromNodeAndPath(null, path); } ); $.Method({ Static: false, Public: true }, "Create", (JSIL.MethodSignature.Void), function Create() { System.IO.Directory.CreateDirectory(this._path); } ); $.Method({ Static: false, Public: true }, "Create", (new JSIL.MethodSignature(null, [$jsilcore.TypeRef("System.Security.AccessControl.DirectorySecurity")], [])), function Create(directorySecurity) { // FIXME: directorySecurity System.IO.Directory.CreateDirectory(this._path); } ); $.Method({ Static: false, Public: true }, "EnumerateDirectories", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Collections.Generic.IEnumerable`1", [$jsilcore.TypeRef("System.IO.DirectoryInfo")]), [], [])), function EnumerateDirectories() { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "EnumerateDirectories", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Collections.Generic.IEnumerable`1", [$jsilcore.TypeRef("System.IO.DirectoryInfo")]), [$.String], [])), function EnumerateDirectories(searchPattern) { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "EnumerateDirectories", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Collections.Generic.IEnumerable`1", [$jsilcore.TypeRef("System.IO.DirectoryInfo")]), [$.String, $jsilcore.TypeRef("System.IO.SearchOption")], [])), function EnumerateDirectories(searchPattern, searchOption) { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "EnumerateFiles", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Collections.Generic.IEnumerable`1", [$jsilcore.TypeRef("System.IO.FileInfo")]), [], [])), function EnumerateFiles() { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "EnumerateFiles", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Collections.Generic.IEnumerable`1", [$jsilcore.TypeRef("System.IO.FileInfo")]), [$.String], [])), function EnumerateFiles(searchPattern) { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "EnumerateFiles", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Collections.Generic.IEnumerable`1", [$jsilcore.TypeRef("System.IO.FileInfo")]), [$.String, $jsilcore.TypeRef("System.IO.SearchOption")], [])), function EnumerateFiles(searchPattern, searchOption) { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "EnumerateFileSystemInfos", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Collections.Generic.IEnumerable`1", [$jsilcore.TypeRef("System.IO.FileSystemInfo")]), [], [])), function EnumerateFileSystemInfos() { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "EnumerateFileSystemInfos", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Collections.Generic.IEnumerable`1", [$jsilcore.TypeRef("System.IO.FileSystemInfo")]), [$.String], [])), function EnumerateFileSystemInfos(searchPattern) { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "EnumerateFileSystemInfos", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Collections.Generic.IEnumerable`1", [$jsilcore.TypeRef("System.IO.FileSystemInfo")]), [$.String, $jsilcore.TypeRef("System.IO.SearchOption")], [])), function EnumerateFileSystemInfos(searchPattern, searchOption) { throw new Error('Not implemented'); } ); $.InheritBaseMethod("get_Exists", JSIL.MethodSignature.Return($.Boolean)); $.InheritBaseMethod("get_Name", JSIL.MethodSignature.Return($.String)); $.Method({ Static: false, Public: true }, "get_Parent", (new JSIL.MethodSignature($jsilcore.TypeRef("System.IO.DirectoryInfo"), [], [])), function get_Parent() { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "get_Root", (new JSIL.MethodSignature($jsilcore.TypeRef("System.IO.DirectoryInfo"), [], [])), function get_Root() { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "GetAccessControl", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Security.AccessControl.DirectorySecurity"), [], [])), function GetAccessControl() { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "GetAccessControl", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Security.AccessControl.DirectorySecurity"), [$jsilcore.TypeRef("System.Security.AccessControl.AccessControlSections")], [])), function GetAccessControl(includeSections) { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "GetDirectories", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Array", [$jsilcore.TypeRef("System.IO.DirectoryInfo")]), [], [])), function GetDirectories() { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "GetDirectories", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Array", [$jsilcore.TypeRef("System.IO.DirectoryInfo")]), [$.String], [])), function GetDirectories(searchPattern) { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "GetDirectories", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Array", [$jsilcore.TypeRef("System.IO.DirectoryInfo")]), [$.String, $jsilcore.TypeRef("System.IO.SearchOption")], [])), function GetDirectories(searchPattern, searchOption) { throw new Error('Not implemented'); } ); $.Method({ Static: true, Public: false }, "GetDirName", (new JSIL.MethodSignature($.String, [$.String], [])), function GetDirName(fullPath) { throw new Error('Not implemented'); } ); $.Method({ Static: true, Public: false }, "GetDisplayName", (new JSIL.MethodSignature($.String, [$.String, $.String], [])), function GetDisplayName(originalPath, fullPath) { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "GetFiles", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Array", [$jsilcore.TypeRef("System.IO.FileInfo")]), [$.String], [])), function GetFiles(searchPattern) { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "GetFiles", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Array", [$jsilcore.TypeRef("System.IO.FileInfo")]), [$.String, $jsilcore.TypeRef("System.IO.SearchOption")], [])), function GetFiles(searchPattern, searchOption) { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "GetFiles", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Array", [$jsilcore.TypeRef("System.IO.FileInfo")]), [], [])), function GetFiles() { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "GetFileSystemInfos", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Array", [$jsilcore.TypeRef("System.IO.FileSystemInfo")]), [$.String], [])), function GetFileSystemInfos(searchPattern) { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "GetFileSystemInfos", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Array", [$jsilcore.TypeRef("System.IO.FileSystemInfo")]), [$.String, $jsilcore.TypeRef("System.IO.SearchOption")], [])), function GetFileSystemInfos(searchPattern, searchOption) { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "GetFileSystemInfos", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Array", [$jsilcore.TypeRef("System.IO.FileSystemInfo")]), [], [])), function GetFileSystemInfos() { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "MoveTo", (new JSIL.MethodSignature(null, [$.String], [])), function MoveTo(destDirName) { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "SetAccessControl", (new JSIL.MethodSignature(null, [$jsilcore.TypeRef("System.Security.AccessControl.DirectorySecurity")], [])), function SetAccessControl(directorySecurity) { throw new Error('Not implemented'); } ); $.Method({ Static: false, Public: true }, "toString", (new JSIL.MethodSignature($.String, [], [])), function toString() { return "<DirectoryInfo " + this._path + ">"; } ); });
/* @license Copyright (c) 2011-2013 Brian Cavalier */ define([ 'require', 'app/slides/ArrayPresentationModel', 'app/slides/SlideView', 'app/slides/PresentationController', 'app/slides/tx/compose', 'app/slides/tx/fetch', 'app/slides/tx/markdown', 'app/slides/tx/highlight', 'app/slides/tx/split', 'css!highlightjs/styles/ir_black.css', 'css!themes/black/theme.css', 'css!themes/fade.css', 'domReady!' ], function (require, Model, View, Controller, compose, fetch, markdown, highlight, split) { var source, model, view, controller, splitSlides; splitSlides = /\s*\<hr\s*\/?\>\s*/i; source = compose(fetch(require), split(splitSlides)); model = new Model(source('slides/slides.html')); view = new View(document.getElementById('slide-container'), model); controller = new Controller(view); controller.start().then(function () { document.body.className = ''; }); } );
// The simplest 'use' just calls a named transition. this.transition( this.withinRoute('foo'), this.use('fade') ); // Named transitions may take arguments. For example, the predefined // 'fade' transition accepts an `opts` hash that's passed through to // Velocity, so you can say: this.transition( this.withinRoute('foo'), this.use('fade', { duration: 3000 }) ); // This declares two symmetric rules: "from foo to bar use toLeft" and // "from bar to foo use toRight". this.transition( this.fromRoute('foo'), this.toRoute('bar'), this.use('toLeft'), this.reverse('toRight') ); // You can also provide an implementation instead of a name, though // it's probably better to keep implementations in separate files. We // talk more about transition implementations in the next section. import { animate, stop } from "liquid-fire"; this.transition( this.withinRoute('foo'), this.use(function(oldView, insertNewView, opts) { stop(oldView); return animate(oldView, {opacity: 0}, opts) .then(insertNewView) .then(function(newView){ return animate(newView, {opacity: [1, 0]}, opts); }); }) );
import React, { Component } from 'react'; import { Link } from 'react-router'; class NotFound extends Component { render() { return( <article> <h1>Page not found.</h1> <Link to="/" className="btn">Home</Link> </article> ); } } export default NotFound;
'use strict'; var fs = require('fs'); var path = require('path'); var through = require('through'); var PluginError = require('gulp-util').PluginError; var File = require('gulp-util').File; var SourceMapConsumer = require('source-map').SourceMapConsumer; var SourceMapGenerator = require('source-map').SourceMapGenerator; var SourceNode = require('source-map').SourceNode; module.exports = function(fileName, opts) { if (!fileName) { throw new PluginError('gulp-concat-sourcemap', 'Missing fileName option for gulp-concat-sourcemap'); } opts = opts || {}; var firstFile = null; var sourceNode = new SourceNode(); function bufferContents(file) { if (file.isNull()) return; // ignore if (file.isStream()) return this.emit('error', new PluginError('gulp-concat-sourcemap', 'Streaming not supported')); if (!firstFile) firstFile = file; var rel = path.relative(file.cwd, file.path).replace(/\\/g, '/'); if(opts.prefix) { var p = opts.prefix; while(p-- > 0) { rel = rel.substring(rel.indexOf('/') + 1); } } // remove utf-8 byte order mark if (file.contents[0] === 0xEF && file.contents[1] === 0xBB && file.contents[2] === 0xBF) { file.contents = file.contents.slice(3); } if(file.sourceMap && file.sourceMap.mappings != '') { sourceNode.add(SourceNode.fromStringWithSourceMap(file.contents.toString('utf8') + '\n\n', new SourceMapConsumer(file.sourceMap))); } else { file.contents.toString('utf8').split('\n').forEach(function(line, j){ sourceNode.add(new SourceNode(j + 1, 0, rel, line + '\n')); }); sourceNode.add('\n'); } if (opts.sourcesContent) { sourceNode.setSourceContent(rel, file.contents.toString('utf8')); } } function endStream(){ if (!firstFile) return this.emit('end'); var contentPath = path.join(firstFile.base, fileName), mapPath = contentPath + '.map'; if(!firstFile.sourceMap) { if (/\.css$/.test(fileName)) { sourceNode.add('/*# sourceMappingURL=' + (opts.sourceMappingBaseURL || '') + fileName + '.map' + ' */'); } else { sourceNode.add('//# sourceMappingURL=' + (opts.sourceMappingBaseURL || '') + fileName + '.map'); } } var codeMap = sourceNode.toStringWithSourceMap({ file: fileName, sourceRoot: opts.sourceRoot || '' }); var sourceMap = codeMap.map.toJSON(); sourceMap.file = path.basename(sourceMap.file); var contentFile = new File({ cwd: firstFile.cwd, base: firstFile.base, path: contentPath, contents: new Buffer(codeMap.code) }); if(firstFile.sourceMap){ contentFile.sourceMap = sourceMap; } else { var mapFile = new File({ cwd: firstFile.cwd, base: firstFile.base, path: mapPath, contents: new Buffer(JSON.stringify(sourceMap, null, ' ')) }); } this.emit('data', contentFile); if(!firstFile.sourceMap) this.emit('data', mapFile); this.emit('end'); } return through(bufferContents, endStream); };
var types_1 = require("utils/types"); var page_1 = require("ui/page"); var view_1 = require("ui/core/view"); var file_system_1 = require("file-system"); var binding_builder_1 = require("./binding-builder"); var utils_1 = require("utils/utils"); require("ui/layouts/dock-layout"); require("ui/layouts/grid-layout"); require("ui/layouts/absolute-layout"); var special_properties_1 = require("ui/builder/special-properties"); var UI_PATH = "ui/"; var MODULES = { "TabViewItem": "ui/tab-view", "FormattedString": "text/formatted-string", "Span": "text/span", "ActionItem": "ui/action-bar", "NavigationButton": "ui/action-bar", "SegmentedBarItem": "ui/segmented-bar", }; var CODEFILE = "codeFile"; var CSSFILE = "cssFile"; var platform; function ensurePlatform() { if (!platform) { platform = require("platform"); } } function getComponentModule(elementName, namespace, attributes, exports) { var instance; var instanceModule; var componentModule; elementName = elementName.split("-").map(function (s) { return s[0].toUpperCase() + s.substring(1); }).join(""); var moduleId = MODULES[elementName] || UI_PATH + (elementName.toLowerCase().indexOf("layout") !== -1 ? "layouts/" : "") + elementName.split(/(?=[A-Z])/).join("-").toLowerCase(); try { if (types_1.isString(namespace)) { var pathInsideTNSModules = file_system_1.path.join(file_system_1.knownFolders.currentApp().path, "tns_modules", namespace); if (file_system_1.Folder.exists(pathInsideTNSModules)) { moduleId = pathInsideTNSModules; } else { moduleId = file_system_1.path.join(file_system_1.knownFolders.currentApp().path, namespace); } } instanceModule = global.loadModule(moduleId); var instanceType = instanceModule[elementName] || Object; instance = new instanceType(); } catch (ex) { var debug = require("utils/debug"); throw new debug.ScopeError(ex, "Module '" + moduleId + "' not found for element '" + (namespace ? namespace + ":" : "") + elementName + "'."); } if (attributes) { if (attributes[CODEFILE]) { if (instance instanceof page_1.Page) { var codeFilePath = attributes[CODEFILE].trim(); if (codeFilePath.indexOf("~/") === 0) { codeFilePath = file_system_1.path.join(file_system_1.knownFolders.currentApp().path, codeFilePath.replace("~/", "")); } var codeFilePathWithExt = codeFilePath.indexOf(".js") !== -1 ? codeFilePath : codeFilePath + ".js"; if (file_system_1.File.exists(codeFilePathWithExt)) { exports = global.loadModule(codeFilePath); instance.exports = exports; } else { throw new Error("Code file with path \"" + codeFilePathWithExt + "\" cannot be found!"); } } else { throw new Error("Code file atribute is valid only for pages!"); } } if (attributes[CSSFILE]) { if (instance instanceof page_1.Page) { var cssFilePath = attributes[CSSFILE].trim(); if (cssFilePath.indexOf("~/") === 0) { cssFilePath = file_system_1.path.join(file_system_1.knownFolders.currentApp().path, cssFilePath.replace("~/", "")); } if (file_system_1.File.exists(cssFilePath)) { instance.addCssFile(cssFilePath); instance[CSSFILE] = true; } else { throw new Error("Css file with path \"" + cssFilePath + "\" cannot be found!"); } } else { throw new Error("Css file atribute is valid only for pages!"); } } } if (instance && instanceModule) { for (var attr in attributes) { var attrValue = attributes[attr]; if (attr.indexOf(":") !== -1) { var platformName = attr.split(":")[0].trim(); ensurePlatform(); if (platformName.toLowerCase() === platform.device.os.toLowerCase()) { attr = attr.split(":")[1].trim(); } else { continue; } } if (attr.indexOf(".") !== -1) { var subObj = instance; var properties = attr.split("."); var subPropName = properties[properties.length - 1]; var i; for (i = 0; i < properties.length - 1; i++) { if (types_1.isDefined(subObj)) { subObj = subObj[properties[i]]; } } if (types_1.isDefined(subObj)) { setPropertyValue(subObj, instanceModule, exports, subPropName, attrValue); } } else { setPropertyValue(instance, instanceModule, exports, attr, attrValue); } } componentModule = { component: instance, exports: instanceModule }; } return componentModule; } exports.getComponentModule = getComponentModule; function setPropertyValue(instance, instanceModule, exports, propertyName, propertyValue) { if (isBinding(propertyValue) && instance.bind) { var bindOptions = binding_builder_1.getBindingOptions(propertyName, getBindingExpressionFromAttribute(propertyValue)); instance.bind({ sourceProperty: bindOptions[binding_builder_1.bindingConstants.sourceProperty], targetProperty: bindOptions[binding_builder_1.bindingConstants.targetProperty], expression: bindOptions[binding_builder_1.bindingConstants.expression], twoWay: bindOptions[binding_builder_1.bindingConstants.twoWay] }, bindOptions[binding_builder_1.bindingConstants.source]); } else if (view_1.isEventOrGesture(propertyName, instance)) { var handler = exports && exports[propertyValue]; if (types_1.isFunction(handler)) { instance.on(propertyName, handler); } } else { var attrHandled = false; var specialSetter = special_properties_1.getSpecialPropertySetter(propertyName); if (!attrHandled && specialSetter) { specialSetter(instance, propertyValue); attrHandled = true; } if (!attrHandled && instance._applyXmlAttribute) { attrHandled = instance._applyXmlAttribute(propertyName, propertyValue); } if (!attrHandled) { instance[propertyName] = utils_1.convertString(propertyValue); } } } exports.setPropertyValue = setPropertyValue; function getBindingExpressionFromAttribute(value) { return value.replace("{{", "").replace("}}", "").trim(); } function isBinding(value) { var isBinding; if (types_1.isString(value)) { var str = value.trim(); isBinding = str.indexOf("{{") === 0 && str.lastIndexOf("}}") === str.length - 2; } return isBinding; }
"use strict"; if (!require("./is-implemented")()) { Object.defineProperty(Math, "expm1", { value: require("./shim"), configurable: true, enumerable: false, writable: true }); }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * * Perform a swipe left on an element. * * @alias browser.swipeLeft * @param {String} selector element to swipe on * @param {Number} speed time (in seconds) to spend performing the swipe * @uses mobile/flick * @type mobile * */ var swipeLeft = function swipeLeft(selector, xOffset, speed) { /** * we can't use default values for function parameter here because this would * break the ability to chain the command with an element if reverse is used */ xOffset = typeof xOffset === 'number' ? xOffset : 100; speed = typeof speed === 'number' ? speed : 100; /** * make sure xoffset is positive so we scroll right */ xOffset = xOffset > 0 ? xOffset * -1 : xOffset; return this.pause(100).swipe(selector, xOffset, 0, speed); }; exports.default = swipeLeft; module.exports = exports['default'];
var app = { initialize: function() { document.addEventListener('deviceready', this.updateEuroValue, false); }, updateEuroValue: function() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { var euroPrice, displayText = '', resultsElement; if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { euroPrice = JSON.parse(xhr.responseText); displayText = 'US $1 = &euro;' + parseFloat(euroPrice.rates.EUR); } else { displayText = 'Error Connecting to API.' } resultsElement = document.getElementById('results'); resultsElement.innerHTML = displayText; document.getElementById('initializing').setAttribute('style', 'display:none;'); resultsElement.setAttribute('style', 'display:block;'); } }; xhr.open('GET', 'http://api.fixer.io/latest?base=USD&symbols=EUR' , true); xhr.send(); } }; app.initialize();
(function (Random) { describe("date distribution", function () { describe("when start is not a date", function () { it("throws a TypeError", function () { expect(function () { Random.date(1234); }).toThrow(new TypeError("Expected start to be a Date, got number")); }); }); describe("when end is not a date", function () { it("throws a TypeError", function () { expect(function () { Random.date(new Date(), 1234); }).toThrow(new TypeError("Expected end to be a Date, got number")); }); }); it("returns a wrapped integer distribution from start time to end time", function () { var now = new Date(); var later = new Date(now.getTime() + 86400); var resultDummy = now.getTime() + 40000; var spy = jasmine.createSpy().andReturn(resultDummy); spyOn(Random, "integer").andReturn(spy); var engine = function () {}; var distribution = Random.date(now, later); var actual = distribution(engine); expect(Random.integer).toHaveBeenCalledWith(now.getTime(), later.getTime()); expect(spy).toHaveBeenCalledWith(engine); expect(actual).toEqual(new Date(resultDummy)); }); }); }(typeof module !== "undefined" ? require("../lib/random") : Random));
import H from '../parts/Globals.js'; import '../parts/Axis.js'; import '../parts/Series.js'; /** * A point-like object, a mock point or a point uses in series. * * @typedef {Highcharts.Point | Annotation.MockPoint} Annotation.PointLike */ /** * A mock point configuration. * * @typedef {Object} Annotation.MockPoint.Options * @property {number} x x value for the point in xAxis scale or pixels * @property {number} y y value for the point in yAxis scale or pixels * @property {string|number|Highcharts.Axis} [xAxis] xAxis instance, index or id * @property {string|number|Highcharts.Axis} [yAxis] yAxis instance, index or id */ /** * A trimmed point object which imitates {@link Highchart.Point} class. * It is created when there is a need of pointing to some chart's position * using axis values or pixel values * * @class * @memberOf Annotation * * @param {Chart} chart a chart instance * @param {Controllable} [target] a controllable instance * @param {Annotation.MockPoint.Options} options an options object */ function MockPoint(chart, target, options) { /** * A mock series instance imitating a real series from a real point. * * @type {Object} * @property {boolean} series.visible=true - whether a series is visible * @property {Chart} series.chart - a chart instance * @property {function} series.getPlotBox */ this.series = { visible: true, chart: chart, getPlotBox: H.Series.prototype.getPlotBox }; /** * @type {?Controllable} */ this.target = target || null; /** * Options for the mock point. * * @type {Annotation.MockPoint.Options} */ this.options = options; /** * If an xAxis is set it represents the point's value in terms of the xAxis. * * @name Annotation.MockPoint#x * @type {?number} */ /** * If an yAxis is set it represents the point's value in terms of the yAxis. * * @name Annotation.MockPoint#y * @type {?number} */ /** * It represents the point's pixel x coordinate relative to its plot box. * * @name Annotation.MockPoint#plotX * @type {?number} */ /** * It represents the point's pixel y position relative to its plot box. * * @name Annotation.MockPoint#plotY * @type {?number} */ /** * Whether the point is inside the plot box. * * @name Annotation.MockPoint#isInside * @type {boolean} */ this.applyOptions(this.getOptions()); } /** * Create a mock point from a real Highcharts point. * * @param {Point} point * * @return {Annotation.MockPoint} a mock point instance. */ MockPoint.fromPoint = function (point) { return new MockPoint(point.series.chart, null, { x: point.x, y: point.y, xAxis: point.series.xAxis, yAxis: point.series.yAxis }); }; /** * @typedef Annotation.MockPoint.Position * @property {number} x * @property {number} y */ /** * Get the pixel position from the point like object. * * @param {Annotation.PointLike} point * @param {boolean} [paneCoordinates] * whether the pixel position should be relative * * @return {Annotation.MockPoint.Position} pixel position */ MockPoint.pointToPixels = function (point, paneCoordinates) { var series = point.series, chart = series.chart, x = point.plotX, y = point.plotY, plotBox; if (chart.inverted) { if (point.mock) { x = point.plotY; y = point.plotX; } else { x = chart.plotWidth - point.plotY; y = chart.plotHeight - point.plotX; } } if (series && !paneCoordinates) { plotBox = series.getPlotBox(); x += plotBox.translateX; y += plotBox.translateY; } return { x: x, y: y }; }; /** * Get fresh mock point options from the point like object. * * @param {Annotation.PointLike} point * * @return {Annotation.MockPoint.Options} mock point's options */ MockPoint.pointToOptions = function (point) { return { x: point.x, y: point.y, xAxis: point.series.xAxis, yAxis: point.series.yAxis }; }; H.extend(MockPoint.prototype, /** @lends Annotation.MockPoint# */ { /** * A flag indicating that a point is not the real one. * * @type {boolean} * @default true */ mock: true, /** * Check if the point has dynamic options. * * @return {boolean} A positive flag if the point has dynamic options. */ hasDynamicOptions: function () { return typeof this.options === 'function'; }, /** * Get the point's options. * * @return {Annotation.MockPoint.Options} the mock point's options. */ getOptions: function () { return this.hasDynamicOptions() ? this.options.call(this, this.target) : this.options; }, /** * Apply options for the point. * * @param {Annotation.MockPoint.Options} options */ applyOptions: function (options) { this.command = options.command; this.setAxis(options, 'x'); this.setAxis(options, 'y'); this.refresh(); }, /** * Set x or y axis. * * @param {Annotation.MockPoint.Options} options * @param {string} xOrY 'x' or 'y' string literal */ setAxis: function (options, xOrY) { var axisName = xOrY + 'Axis', axisOptions = options[axisName], chart = this.series.chart; this.series[axisName] = axisOptions instanceof H.Axis ? axisOptions : H.defined(axisOptions) ? chart[axisName][axisOptions] || chart.get(axisOptions) : null; }, /** * Transform the mock point to an anchor * (relative position on the chart). * * @return {Array<number>} A quadruple of numbers which denotes x, y, * width and height of the box **/ toAnchor: function () { var anchor = [this.plotX, this.plotY, 0, 0]; if (this.series.chart.inverted) { anchor[0] = this.plotY; anchor[1] = this.plotX; } return anchor; }, /** * @typedef {Object} Annotation.MockPoint.LabelConfig * @property {number|undefined} x x value translated to x axis scale * @property {number|undefined} y y value translated to y axis scale * @property {Annotation.MockPoint} point instance of the point */ /** * Returns a label config object - * the same as Highcharts.Point.prototype.getLabelConfig * * @return {Annotation.MockPoint.LabelConfig} the point's label config */ getLabelConfig: function () { return { x: this.x, y: this.y, point: this }; }, /** * Check if the point is inside its pane. * * @return {boolean} A flag indicating whether the point is inside the pane. */ isInsidePane: function () { var plotX = this.plotX, plotY = this.plotY, xAxis = this.series.xAxis, yAxis = this.series.yAxis, isInside = true; if (xAxis) { isInside = H.defined(plotX) && plotX >= 0 && plotX <= xAxis.len; } if (yAxis) { isInside = isInside && H.defined(plotY) && plotY >= 0 && plotY <= yAxis.len; } return isInside; }, /** * Refresh point values and coordinates based on its options. */ refresh: function () { var series = this.series, xAxis = series.xAxis, yAxis = series.yAxis, options = this.getOptions(); if (xAxis) { this.x = options.x; this.plotX = xAxis.toPixels(options.x, true); } else { this.x = null; this.plotX = options.x; } if (yAxis) { this.y = options.y; this.plotY = yAxis.toPixels(options.y, true); } else { this.y = null; this.plotY = options.y; } this.isInside = this.isInsidePane(); }, /** * Translate the point. * * @param {number} [cx] origin x transformation * @param {number} [cy] origin y transformation * @param {number} dx translation for x coordinate * @param {number} dy translation for y coordinate **/ translate: function (cx, cy, dx, dy) { if (!this.hasDynamicOptions()) { this.plotX += dx; this.plotY += dy; this.refreshOptions(); } }, /** * Scale the point. * * @param {number} cx origin x transformation * @param {number} cy origin y transformation * @param {number} sx scale factor x * @param {number} sy scale factor y */ scale: function (cx, cy, sx, sy) { if (!this.hasDynamicOptions()) { var x = this.plotX * sx, y = this.plotY * sy, tx = (1 - sx) * cx, ty = (1 - sy) * cy; this.plotX = tx + x; this.plotY = ty + y; this.refreshOptions(); } }, /** * Rotate the point. * * @param {number} cx origin x rotation * @param {number} cy origin y rotation * @param {number} radians */ rotate: function (cx, cy, radians) { if (!this.hasDynamicOptions()) { var cos = Math.cos(radians), sin = Math.sin(radians), x = this.plotX, y = this.plotY, tx, ty; x -= cx; y -= cy; tx = x * cos - y * sin; ty = x * sin + y * cos; this.plotX = tx + cx; this.plotY = ty + cy; this.refreshOptions(); } }, /** * Refresh point options based on its plot coordinates. */ refreshOptions: function () { var series = this.series, xAxis = series.xAxis, yAxis = series.yAxis; this.x = this.options.x = xAxis ? this.options.x = xAxis.toValue(this.plotX, true) : this.plotX; this.y = this.options.y = yAxis ? yAxis.toValue(this.plotY, true) : this.plotY; } }); export default MockPoint;
"use strict"; 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // A simple implementation of make-array function makeArray(subject) { return Array.isArray(subject) ? subject : [subject]; } var EMPTY = ''; var SPACE = ' '; var ESCAPE = '\\'; var REGEX_TEST_BLANK_LINE = /^\s+$/; var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/; var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/; var REGEX_SPLITALL_CRLF = /\r?\n/g; // /foo, // ./foo, // ../foo, // . // .. var REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/; var SLASH = '/'; var KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol["for"]('node-ignore') /* istanbul ignore next */ : 'node-ignore'; var define = function define(object, key, value) { return Object.defineProperty(object, key, { value: value }); }; var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; // Sanitize the range of a regular expression // The cases are complicated, see test cases for details var sanitizeRange = function sanitizeRange(range) { return range.replace(REGEX_REGEXP_RANGE, function (match, from, to) { return from.charCodeAt(0) <= to.charCodeAt(0) ? match // Invalid range (out of order) which is ok for gitignore rules but // fatal for JavaScript regular expression, so eliminate it. : EMPTY; }); }; // See fixtures #59 var cleanRangeBackSlash = function cleanRangeBackSlash(slashes) { var length = slashes.length; return slashes.slice(0, length - length % 2); }; // > If the pattern ends with a slash, // > it is removed for the purpose of the following description, // > but it would only find a match with a directory. // > In other words, foo/ will match a directory foo and paths underneath it, // > but will not match a regular file or a symbolic link foo // > (this is consistent with the way how pathspec works in general in Git). // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call // you could use option `mark: true` with `glob` // '`foo/`' should not continue with the '`..`' var REPLACERS = [// > Trailing spaces are ignored unless they are quoted with backslash ("\") [// (a\ ) -> (a ) // (a ) -> (a) // (a \ ) -> (a ) /\\?\s+$/, function (match) { return match.indexOf('\\') === 0 ? SPACE : EMPTY; }], // replace (\ ) with ' ' [/\\\s/g, function () { return SPACE; }], // Escape metacharacters // which is written down by users but means special for regular expressions. // > There are 12 characters with special meanings: // > - the backslash \, // > - the caret ^, // > - the dollar sign $, // > - the period or dot ., // > - the vertical bar or pipe symbol |, // > - the question mark ?, // > - the asterisk or star *, // > - the plus sign +, // > - the opening parenthesis (, // > - the closing parenthesis ), // > - and the opening square bracket [, // > - the opening curly brace {, // > These special characters are often called "metacharacters". [/[\\$.|*+(){^]/g, function (match) { return "\\".concat(match); }], [// > a question mark (?) matches a single character /(?!\\)\?/g, function () { return '[^/]'; }], // leading slash [// > A leading slash matches the beginning of the pathname. // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". // A leading slash matches the beginning of the pathname /^\//, function () { return '^'; }], // replace special metacharacter slash after the leading slash [/\//g, function () { return '\\/'; }], [// > A leading "**" followed by a slash means match in all directories. // > For example, "**/foo" matches file or directory "foo" anywhere, // > the same as pattern "foo". // > "**/foo/bar" matches file or directory "bar" anywhere that is directly // > under directory "foo". // Notice that the '*'s have been replaced as '\\*' /^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo' function () { return '^(?:.*\\/)?'; }], // starting [// there will be no leading '/' // (which has been replaced by section "leading slash") // If starts with '**', adding a '^' to the regular expression also works /^(?=[^^])/, function startingReplacer() { // If has a slash `/` at the beginning or middle return !/\/(?!$)/.test(this) // > Prior to 2.22.1 // > If the pattern does not contain a slash /, // > Git treats it as a shell glob pattern // Actually, if there is only a trailing slash, // git also treats it as a shell glob pattern // After 2.22.1 (compatible but clearer) // > If there is a separator at the beginning or middle (or both) // > of the pattern, then the pattern is relative to the directory // > level of the particular .gitignore file itself. // > Otherwise the pattern may also match at any level below // > the .gitignore level. ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for // > consumption by fnmatch(3) : '^'; }], // two globstars [// Use lookahead assertions so that we could match more than one `'/**'` /\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories // should not use '*', or it will be replaced by the next replacer // Check if it is not the last `'/**'` function (_, index, str) { return index + 6 < str.length // case: /**/ // > A slash followed by two consecutive asterisks then a slash matches // > zero or more directories. // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. // '/**/' ? '(?:\\/[^\\/]+)*' // case: /** // > A trailing `"/**"` matches everything inside. // #21: everything inside but it should not include the current folder : '\\/.+'; }], // intermediate wildcards [// Never replace escaped '*' // ignore rule '\*' will match the path '*' // 'abc.*/' -> go // 'abc.*' -> skip this rule /(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js' // '*.js' doesn't match 'abc' function (_, p1) { return "".concat(p1, "[^\\/]*"); }], [// unescape, revert step 3 except for back slash // For example, if a user escape a '\\*', // after step 3, the result will be '\\\\\\*' /\\\\\\(?=[$.|*+(){^])/g, function () { return ESCAPE; }], [// '\\\\' -> '\\' /\\\\/g, function () { return ESCAPE; }], [// > The range notation, e.g. [a-zA-Z], // > can be used to match one of the characters in a range. // `\` is escaped by step 3 /(\\)?\[([^\]/]*?)(\\*)($|\])/g, function (match, leadEscape, range, endEscape, close) { return leadEscape === ESCAPE // '\\[bar]' -> '\\\\[bar\\]' ? "\\[".concat(range).concat(cleanRangeBackSlash(endEscape)).concat(close) : close === ']' ? endEscape.length % 2 === 0 // A normal case, and it is a range notation // '[bar]' // '[bar\\\\]' ? "[".concat(sanitizeRange(range)).concat(endEscape, "]") // Invalid range notaton // '[bar\\]' -> '[bar\\\\]' : '[]' : '[]'; }], // ending [// 'js' will not match 'js.' // 'ab' will not match 'abc' /(?:[^*])$/, // WTF! // https://git-scm.com/docs/gitignore // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) // which re-fixes #24, #38 // > If there is a separator at the end of the pattern then the pattern // > will only match directories, otherwise the pattern can match both // > files and directories. // 'js*' will not match 'a.js' // 'js/' will not match 'a.js' // 'js' will match 'a.js' and 'a.js/' function (match) { return /\/$/.test(match) // foo/ will not match 'foo' ? "".concat(match, "$") // foo matches 'foo' and 'foo/' : "".concat(match, "(?=$|\\/$)"); }], // trailing wildcard [/(\^|\\\/)?\\\*$/, function (_, p1) { var prefix = p1 // '\^': // '/*' does not match EMPTY // '/*' does not match everything // '\\\/': // 'abc/*' does not match 'abc/' ? "".concat(p1, "[^/]+") // 'a*' matches 'a' // 'a*' matches 'aa' : '[^/]*'; return "".concat(prefix, "(?=$|\\/$)"); }]]; // A simple cache, because an ignore rule only has only one certain meaning var regexCache = Object.create(null); // @param {pattern} var makeRegex = function makeRegex(pattern, negative, ignorecase) { var r = regexCache[pattern]; if (r) { return r; } // const replacers = negative // ? NEGATIVE_REPLACERS // : POSITIVE_REPLACERS var source = REPLACERS.reduce(function (prev, current) { return prev.replace(current[0], current[1].bind(pattern)); }, pattern); return regexCache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source); }; var isString = function isString(subject) { return typeof subject === 'string'; }; // > A blank line matches no files, so it can serve as a separator for readability. var checkPattern = function checkPattern(pattern) { return pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment. && pattern.indexOf('#') !== 0; }; var splitPattern = function splitPattern(pattern) { return pattern.split(REGEX_SPLITALL_CRLF); }; var IgnoreRule = function IgnoreRule(origin, pattern, negative, regex) { _classCallCheck(this, IgnoreRule); this.origin = origin; this.pattern = pattern; this.negative = negative; this.regex = regex; }; var createRule = function createRule(pattern, ignorecase) { var origin = pattern; var negative = false; // > An optional prefix "!" which negates the pattern; if (pattern.indexOf('!') === 0) { negative = true; pattern = pattern.substr(1); } pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that // > begin with a literal "!", for example, `"\!important!.txt"`. .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that // > begin with a hash. .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#'); var regex = makeRegex(pattern, negative, ignorecase); return new IgnoreRule(origin, pattern, negative, regex); }; var throwError = function throwError(message, Ctor) { throw new Ctor(message); }; var checkPath = function checkPath(path, originalPath, doThrow) { if (!isString(path)) { return doThrow("path must be a string, but got `".concat(originalPath, "`"), TypeError); } // We don't know if we should ignore EMPTY, so throw if (!path) { return doThrow("path must not be empty", TypeError); } // Check if it is a relative path if (checkPath.isNotRelative(path)) { var r = '`path.relative()`d'; return doThrow("path should be a ".concat(r, " string, but got \"").concat(originalPath, "\""), RangeError); } return true; }; var isNotRelative = function isNotRelative(path) { return REGEX_TEST_INVALID_PATH.test(path); }; checkPath.isNotRelative = isNotRelative; checkPath.convert = function (p) { return p; }; var Ignore = /*#__PURE__*/function () { function Ignore() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$ignorecase = _ref.ignorecase, ignorecase = _ref$ignorecase === void 0 ? true : _ref$ignorecase; _classCallCheck(this, Ignore); this._rules = []; this._ignorecase = ignorecase; define(this, KEY_IGNORE, true); this._initCache(); } _createClass(Ignore, [{ key: "_initCache", value: function _initCache() { this._ignoreCache = Object.create(null); this._testCache = Object.create(null); } }, { key: "_addPattern", value: function _addPattern(pattern) { // #32 if (pattern && pattern[KEY_IGNORE]) { this._rules = this._rules.concat(pattern._rules); this._added = true; return; } if (checkPattern(pattern)) { var rule = createRule(pattern, this._ignorecase); this._added = true; this._rules.push(rule); } } // @param {Array<string> | string | Ignore} pattern }, { key: "add", value: function add(pattern) { this._added = false; makeArray(isString(pattern) ? splitPattern(pattern) : pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore, // making the behavior changed. if (this._added) { this._initCache(); } return this; } // legacy }, { key: "addPattern", value: function addPattern(pattern) { return this.add(pattern); } // | ignored : unignored // negative | 0:0 | 0:1 | 1:0 | 1:1 // -------- | ------- | ------- | ------- | -------- // 0 | TEST | TEST | SKIP | X // 1 | TESTIF | SKIP | TEST | X // - SKIP: always skip // - TEST: always test // - TESTIF: only test if checkUnignored // - X: that never happen // @param {boolean} whether should check if the path is unignored, // setting `checkUnignored` to `false` could reduce additional // path matching. // @returns {TestResult} true if a file is ignored }, { key: "_testOne", value: function _testOne(path, checkUnignored) { var ignored = false; var unignored = false; this._rules.forEach(function (rule) { var negative = rule.negative; if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) { return; } var matched = rule.regex.test(path); if (matched) { ignored = !negative; unignored = negative; } }); return { ignored: ignored, unignored: unignored }; } // @returns {TestResult} }, { key: "_test", value: function _test(originalPath, cache, checkUnignored, slices) { var path = originalPath // Supports nullable path && checkPath.convert(originalPath); checkPath(path, originalPath, throwError); return this._t(path, cache, checkUnignored, slices); } }, { key: "_t", value: function _t(path, cache, checkUnignored, slices) { if (path in cache) { return cache[path]; } if (!slices) { // path/to/a.js // ['path', 'to', 'a.js'] slices = path.split(SLASH); } slices.pop(); // If the path has no parent directory, just test it if (!slices.length) { return cache[path] = this._testOne(path, checkUnignored); } var parent = this._t(slices.join(SLASH) + SLASH, cache, checkUnignored, slices); // If the path contains a parent directory, check the parent first return cache[path] = parent.ignored // > It is not possible to re-include a file if a parent directory of // > that file is excluded. ? parent : this._testOne(path, checkUnignored); } }, { key: "ignores", value: function ignores(path) { return this._test(path, this._ignoreCache, false).ignored; } }, { key: "createFilter", value: function createFilter() { var _this = this; return function (path) { return !_this.ignores(path); }; } }, { key: "filter", value: function filter(paths) { return makeArray(paths).filter(this.createFilter()); } // @returns {TestResult} }, { key: "test", value: function test(path) { return this._test(path, this._testCache, true); } }]); return Ignore; }(); var factory = function factory(options) { return new Ignore(options); }; var returnFalse = function returnFalse() { return false; }; var isPathValid = function isPathValid(path) { return checkPath(path && checkPath.convert(path), path, returnFalse); }; factory.isPathValid = isPathValid; // Fixes typescript factory["default"] = factory; module.exports = factory; // Windows // -------------------------------------------------------------- /* istanbul ignore if */ if ( // Detect `process` so that it can run in browsers. typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) { /* eslint no-control-regex: "off" */ var makePosix = function makePosix(str) { return /^\\\\\?\\/.test(str) || /[\0-\x1F"<>\|]+/.test(str) ? str : str.replace(/\\/g, '/'); }; checkPath.convert = makePosix; // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' // 'd:\\foo' var REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i; checkPath.isNotRelative = function (path) { return REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path); }; }
version https://git-lfs.github.com/spec/v1 oid sha256:e25e279ade23fdb7b8a95335ea00855c8144fcd17bee4f70a2ba6901ac6db12d size 1050
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v17.1.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); 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); }; Object.defineProperty(exports, "__esModule", { value: true }); var component_1 = require("../widgets/component"); var context_1 = require("../context/context"); var rowNode_1 = require("../entities/rowNode"); var dragAndDropService_1 = require("../dragAndDrop/dragAndDropService"); var eventKeys_1 = require("../eventKeys"); var utils_1 = require("../utils"); var beanStub_1 = require("../context/beanStub"); var RowDragComp = (function (_super) { __extends(RowDragComp, _super); function RowDragComp(rowNode, column, cellValue, beans) { var _this = _super.call(this, "<span class=\"ag-row-drag\"></span>") || this; _this.rowNode = rowNode; _this.column = column; _this.cellValue = cellValue; _this.beans = beans; return _this; } RowDragComp.prototype.postConstruct = function () { this.addDragSource(); this.checkCompatibility(); if (this.beans.gridOptionsWrapper.isRowDragManaged()) { this.addFeature(this.beans.context, new ManagedVisibilityStrategy(this, this.beans, this.rowNode, this.column)); } else { this.addFeature(this.beans.context, new NonManagedVisibilityStrategy(this, this.beans, this.rowNode, this.column)); } }; // returns true if all compatibility items work out RowDragComp.prototype.checkCompatibility = function () { var managed = this.beans.gridOptionsWrapper.isRowDragManaged(); var treeData = this.beans.gridOptionsWrapper.isTreeData(); if (treeData && managed) { utils_1._.doOnce(function () { return console.warn('ag-Grid: If using row drag with tree data, you cannot have rowDragManaged=true'); }, 'RowDragComp.managedAndTreeData'); } }; RowDragComp.prototype.addDragSource = function () { var _this = this; var dragItem = { rowNode: this.rowNode }; var dragSource = { type: dragAndDropService_1.DragSourceType.RowDrag, eElement: this.getGui(), dragItemName: this.cellValue, dragItemCallback: function () { return dragItem; }, dragStartPixels: 0 }; this.beans.dragAndDropService.addDragSource(dragSource, true); this.addDestroyFunc(function () { return _this.beans.dragAndDropService.removeDragSource(dragSource); }); }; __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], RowDragComp.prototype, "postConstruct", null); return RowDragComp; }(component_1.Component)); exports.RowDragComp = RowDragComp; // when non managed, the visibility depends on suppressRowDrag property only var NonManagedVisibilityStrategy = (function (_super) { __extends(NonManagedVisibilityStrategy, _super); function NonManagedVisibilityStrategy(parent, beans, rowNode, column) { var _this = _super.call(this) || this; _this.parent = parent; _this.beans = beans; _this.column = column; _this.rowNode = rowNode; return _this; } NonManagedVisibilityStrategy.prototype.postConstruct = function () { this.addDestroyableEventListener(this.beans.gridOptionsWrapper, 'suppressRowDrag', this.onSuppressRowDrag.bind(this)); // in case data changes, then we need to update visibility of drag item this.addDestroyableEventListener(this.rowNode, rowNode_1.RowNode.EVENT_DATA_CHANGED, this.workOutVisibility.bind(this)); this.addDestroyableEventListener(this.rowNode, rowNode_1.RowNode.EVENT_CELL_CHANGED, this.workOutVisibility.bind(this)); this.workOutVisibility(); }; NonManagedVisibilityStrategy.prototype.onSuppressRowDrag = function () { this.workOutVisibility(); }; NonManagedVisibilityStrategy.prototype.workOutVisibility = function () { // only show the drag if both sort and filter are not present var suppressRowDrag = this.beans.gridOptionsWrapper.isSuppressRowDrag(); if (suppressRowDrag) { this.parent.setVisible(false); } else { var visible = this.column.isRowDrag(this.rowNode); this.parent.setVisible(visible); } }; __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], NonManagedVisibilityStrategy.prototype, "postConstruct", null); return NonManagedVisibilityStrategy; }(beanStub_1.BeanStub)); // when managed, the visibility depends on sort, filter and row group, as well as suppressRowDrag property var ManagedVisibilityStrategy = (function (_super) { __extends(ManagedVisibilityStrategy, _super); function ManagedVisibilityStrategy(parent, beans, rowNode, column) { var _this = _super.call(this) || this; _this.parent = parent; _this.beans = beans; _this.column = column; _this.rowNode = rowNode; return _this; } ManagedVisibilityStrategy.prototype.postConstruct = function () { // we do not show the component if sort, filter or grouping is active this.addDestroyableEventListener(this.beans.eventService, eventKeys_1.Events.EVENT_SORT_CHANGED, this.onSortChanged.bind(this)); this.addDestroyableEventListener(this.beans.eventService, eventKeys_1.Events.EVENT_FILTER_CHANGED, this.onFilterChanged.bind(this)); this.addDestroyableEventListener(this.beans.eventService, eventKeys_1.Events.EVENT_COLUMN_ROW_GROUP_CHANGED, this.onRowGroupChanged.bind(this)); // in case data changes, then we need to update visibility of drag item this.addDestroyableEventListener(this.rowNode, rowNode_1.RowNode.EVENT_DATA_CHANGED, this.workOutVisibility.bind(this)); this.addDestroyableEventListener(this.rowNode, rowNode_1.RowNode.EVENT_CELL_CHANGED, this.workOutVisibility.bind(this)); this.addDestroyableEventListener(this.beans.gridOptionsWrapper, 'suppressRowDrag', this.onSuppressRowDrag.bind(this)); this.updateSortActive(); this.updateFilterActive(); this.updateRowGroupActive(); this.workOutVisibility(); }; ManagedVisibilityStrategy.prototype.updateRowGroupActive = function () { var rowGroups = this.beans.columnController.getRowGroupColumns(); this.rowGroupActive = !utils_1._.missingOrEmpty(rowGroups); }; ManagedVisibilityStrategy.prototype.onRowGroupChanged = function () { this.updateRowGroupActive(); this.workOutVisibility(); }; ManagedVisibilityStrategy.prototype.updateSortActive = function () { var sortModel = this.beans.sortController.getSortModel(); this.sortActive = !utils_1._.missingOrEmpty(sortModel); }; ManagedVisibilityStrategy.prototype.onSortChanged = function () { this.updateSortActive(); this.workOutVisibility(); }; ManagedVisibilityStrategy.prototype.updateFilterActive = function () { this.filterActive = this.beans.filterManager.isAnyFilterPresent(); }; ManagedVisibilityStrategy.prototype.onFilterChanged = function () { this.updateFilterActive(); this.workOutVisibility(); }; ManagedVisibilityStrategy.prototype.onSuppressRowDrag = function () { this.workOutVisibility(); }; ManagedVisibilityStrategy.prototype.workOutVisibility = function () { // only show the drag if both sort and filter are not present var sortOrFilterOrGroupActive = this.sortActive || this.filterActive || this.rowGroupActive; var suppressRowDrag = this.beans.gridOptionsWrapper.isSuppressRowDrag(); var alwaysHide = sortOrFilterOrGroupActive || suppressRowDrag; if (alwaysHide) { this.parent.setVisible(false); } else { var visible = this.column.isRowDrag(this.rowNode); this.parent.setVisible(visible); } }; __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], ManagedVisibilityStrategy.prototype, "postConstruct", null); return ManagedVisibilityStrategy; }(beanStub_1.BeanStub));
CKEDITOR.plugins.setLang("easyimage","fa",{commands:{fullImage:"تصویر کامل",sideImage:"تصویر جانبی",altText:"تغییر متن جایگزین تصویر",upload:"آپلود تصویر"},uploadFailed:"به علت خطای شبکه، تصویر شما نمی‌تواند آپلود شود."});
function lookupProvider(container, providerName){ return container.lookup('torii-provider:'+providerName); } function proxyToProvider(methodName, requireMethod){ return function(providerName, options){ var container = this.container; var provider = lookupProvider(container, providerName); if (!provider) { throw new Error("Expected a provider named '"+providerName+"' " + ", did you forget to register it?"); } if (!provider[methodName]) { if (requireMethod) { throw new Error("Expected provider '"+providerName+"' to define " + "the '"+methodName+"' method."); } else { return Ember.RSVP.Promise.resolve({}); } } return new Ember.RSVP.Promise(function(resolve, reject){ resolve( provider[methodName](options) ); }); }; } /** * Torii is an engine for authenticating against various * providers. For example, you can open a session with * Linked In via Oauth2 and authorization codes by doing * the following: * * Torii.open('linked-in-oauth2').then(function(authData){ * console.log(authData.authorizationCode); * }); * * For traditional authentication flows, you will often use * Torii via the Torii.Session API. * * @class Torii */ var Torii = Ember.Object.extend({ /** * Open an authorization against an API. A promise resolving * with an authentication response object is returned. These * response objects, are found in the "torii/authentications" * namespace. * * @method open * @param {String} providerName The provider to open * @return {Ember.RSVP.Promise} Promise resolving to an authentication object */ open: proxyToProvider('open', true), /** * Return a promise which will resolve if the provider has * already been opened. * * @method fetch * @param {String} providerName The provider to open * @return {Ember.RSVP.Promise} Promise resolving to an authentication object */ fetch: proxyToProvider('fetch'), /** * Return a promise which will resolve when the provider has been * closed. Closing a provider may not always be a meaningful action, * and may be better handled by torii's session management instead. * * @method close * @param {String} providerName The provider to open * @return {Ember.RSVP.Promise} Promise resolving when the provider is closed */ close: proxyToProvider('close') }); export default Torii;
define(function(require) { 'use strict'; var Select2GridComponent; var _ = require('underscore'); var Select2Component = require('oro/select2-component'); Select2GridComponent = Select2Component.extend({ preConfig: function(config) { Select2GridComponent.__super__.preConfig.call(this, config); var that = this; var grid = config.grid; var gridName = grid.name; _.extend(config.ajax, { data: function(query, page, searchById) { var result = {}; var sortByKey; if (searchById) { result[gridName + '[_pager][_page]'] = 1; result[gridName + '[_pager][_per_page]'] = 1; result[gridName + '[_filter][id][type]'] = 3; result[gridName + '[_filter][id][value]'] = query; } else { sortByKey = grid.sort_by || config.properties[0]; result[gridName + '[_pager][_page]'] = page; result[gridName + '[_pager][_per_page]'] = that.perPage; result[gridName + '[_sort_by][' + sortByKey + ']'] = grid.sort_order || 'ASC'; result[gridName + '[_filter][' + config.properties[0] + '][type]'] = 1; result[gridName + '[_filter][' + config.properties[0] + '][value]'] = query; } return result; }, results: function(data, page) { return { results: data.data, more: page * that.perPage < data.options.totalRecords }; } }); return config; } }); return Select2GridComponent; });
/* jshint ignore:start */ import Ember from "ember"; import { test } from 'ember-qunit'; import { module } from 'qunit'; import startApp from '../helpers/start-app'; let App; let port; module('Info Tab', { beforeEach() { App = startApp({ adapter: 'basic' }); port = App.__container__.lookup('port:main'); port.reopen({ send(name) { if (name === 'general:getLibraries') { this.trigger('general:libraries', { libraries: [ { name: 'Ember', version: '1.0' }, { name: 'Handlebars', version: '2.1' } ] }); } } }); }, afterEach() { Ember.run(App, App.destroy); } }); test("Libraries are displayed correctly", async function t(assert) { const infoRoute = App.__container__.lookup('route:info'); infoRoute.reopen({ version: '9.9.9' }); await visit('/info'); let libraries = findByLabel('library-row'); assert.equal(libraries.length, 3, "The correct number of libraries is displayed"); assert.equal(findByLabel('lib-name', libraries[0]).text().trim(), 'Ember Inspector', 'Ember Inspector is added automatically'); assert.equal(findByLabel('lib-version', libraries[0]).text().trim(), '9.9.9'); assert.equal(findByLabel('lib-name', libraries[1]).text().trim(), 'Ember'); assert.equal(findByLabel('lib-version', libraries[1]).text().trim(), '1.0'); assert.equal(findByLabel('lib-name', libraries[2]).text().trim(), 'Handlebars'); assert.equal(findByLabel('lib-version', libraries[2]).text().trim(), '2.1'); });
/* 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-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314) */ /** * Utility class for setting/reading values from browser cookies. * Values can be written using the {@link #set} method. * Values can be read using the {@link #get} method. * A cookie can be invalidated on the client machine using the {@link #clear} method. */ Ext.define('Ext.util.Cookies', { singleton: true, /** * Creates a cookie with the specified name and value. Additional settings for the cookie may be optionally specified * (for example: expiration, access restriction, SSL). * @param {String} name The name of the cookie to set. * @param {Object} value The value to set for the cookie. * @param {Object} [expires] Specify an expiration date the cookie is to persist until. Note that the specified Date * object will be converted to Greenwich Mean Time (GMT). * @param {String} [path] Setting a path on the cookie restricts access to pages that match that path. Defaults to all * pages ('/'). * @param {String} [domain] Setting a domain restricts access to pages on a given domain (typically used to allow * cookie access across subdomains). For example, "sencha.com" will create a cookie that can be accessed from any * subdomain of sencha.com, including www.sencha.com, support.sencha.com, etc. * @param {Boolean} [secure] Specify true to indicate that the cookie should only be accessible via SSL on a page * using the HTTPS protocol. Defaults to false. Note that this will only work if the page calling this code uses the * HTTPS protocol, otherwise the cookie will be created with default options. */ set : function(name, value){ var argv = arguments, argc = arguments.length, expires = (argc > 2) ? argv[2] : null, path = (argc > 3) ? argv[3] : '/', domain = (argc > 4) ? argv[4] : null, secure = (argc > 5) ? argv[5] : false; document.cookie = name + "=" + escape(value) + ((expires === null) ? "" : ("; expires=" + expires.toGMTString())) + ((path === null) ? "" : ("; path=" + path)) + ((domain === null) ? "" : ("; domain=" + domain)) + ((secure === true) ? "; secure" : ""); }, /** * Retrieves cookies that are accessible by the current page. If a cookie does not exist, `get()` returns null. The * following example retrieves the cookie called "valid" and stores the String value in the variable validStatus. * * var validStatus = Ext.util.Cookies.get("valid"); * * @param {String} name The name of the cookie to get * @return {Object} Returns the cookie value for the specified name; * null if the cookie name does not exist. */ get : function(name){ var arg = name + "=", alen = arg.length, clen = document.cookie.length, i = 0, j = 0; while(i < clen){ j = i + alen; if(document.cookie.substring(i, j) == arg){ return this.getCookieVal(j); } i = document.cookie.indexOf(" ", i) + 1; if(i === 0){ break; } } return null; }, /** * Removes a cookie with the provided name from the browser * if found by setting its expiration date to sometime in the past. * @param {String} name The name of the cookie to remove * @param {String} [path] The path for the cookie. * This must be included if you included a path while setting the cookie. */ clear : function(name, path){ if(this.get(name)){ path = path || '/'; document.cookie = name + '=' + '; expires=Thu, 01-Jan-70 00:00:01 GMT; path=' + path; } }, /** * @private */ getCookieVal : function(offset){ var endstr = document.cookie.indexOf(";", offset); if(endstr == -1){ endstr = document.cookie.length; } return unescape(document.cookie.substring(offset, endstr)); } });
module.exports = function(hljs) { var KEYWORDS = { keyword: // Normal keywords. 'abstract as base bool break byte case catch char checked const continue decimal dynamic ' + 'default delegate do double else enum event explicit extern finally fixed float ' + 'for foreach goto if implicit in int interface internal is lock long when ' + 'object operator out override params private protected public readonly ref sbyte ' + 'sealed short sizeof stackalloc static string struct switch this try typeof ' + 'uint ulong unchecked unsafe ushort using virtual volatile void while async ' + 'protected public private internal ' + // Contextual keywords. 'ascending descending from get group into join let orderby partial select set value var ' + 'where yield', literal: 'null false true' }; var TYPE_IDENT_RE = hljs.IDENT_RE + '(<' + hljs.IDENT_RE + '>)?(\\[\\])?'; return { aliases: ['csharp'], keywords: KEYWORDS, illegal: /::/, contains: [ hljs.COMMENT( '///', '$', { returnBegin: true, contains: [ { className: 'doctag', variants: [ { begin: '///', relevance: 0 }, { begin: '<!--|-->' }, { begin: '</?', end: '>' } ] } ] } ), hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE, { className: 'meta', begin: '#', end: '$', keywords: {'meta-keyword': 'if else elif endif define undef warning error line region endregion pragma checksum'} }, { className: 'string', begin: '@"', end: '"', contains: [{begin: '""'}] }, hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE, hljs.C_NUMBER_MODE, { beginKeywords: 'class interface', end: /[{;=]/, illegal: /[^\s:]/, contains: [ hljs.TITLE_MODE, hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE ] }, { beginKeywords: 'namespace', end: /[{;=]/, illegal: /[^\s:]/, contains: [ hljs.inherit(hljs.TITLE_MODE, {begin: '[a-zA-Z](\\.?\\w)*'}), hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE ] }, { // Expression keywords prevent 'keyword Name(...)' from being // recognized as a function definition beginKeywords: 'new return throw await', relevance: 0 }, { className: 'function', begin: '(' + TYPE_IDENT_RE + '\\s+)+' + hljs.IDENT_RE + '\\s*\\(', returnBegin: true, end: /[{;=]/, excludeEnd: true, keywords: KEYWORDS, contains: [ { begin: hljs.IDENT_RE + '\\s*\\(', returnBegin: true, contains: [hljs.TITLE_MODE], relevance: 0 }, { className: 'params', begin: /\(/, end: /\)/, excludeBegin: true, excludeEnd: true, keywords: KEYWORDS, relevance: 0, contains: [ hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE, hljs.C_NUMBER_MODE, hljs.C_BLOCK_COMMENT_MODE ] }, hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE ] } ] }; };
$(document).ready(function () { var videos = $('iframe[src*="vimeo.com"], iframe[src*="youtube.com"]'); videos.each(function () { var el = $(this); el.wrap('<div class="responsive-embed widescreen"/>'); }); });
"use strict"; 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); }; var core_1 = require('@angular/core'); var AppComponent = (function () { function AppComponent() { this.name = 'Angular'; } AppComponent = __decorate([ core_1.Component({ selector: 'my-app', template: "<h1>Hello {{name}}</h1>", }), __metadata('design:paramtypes', []) ], AppComponent); return AppComponent; }()); exports.AppComponent = AppComponent; //# sourceMappingURL=app.component.js.map
/*! * froala_editor v2.7.5 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms/ * Copyright 2014-2018 Froala Labs */ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof module === 'object' && module.exports) { // Node/CommonJS module.exports = function( root, jQuery ) { if ( jQuery === undefined ) { // require('jQuery') returns a factory that requires window to // build a jQuery instance, we normalize how we use modules // that require this pattern but the window provided is a noop // if it's defined (how jquery works) if ( typeof window !== 'undefined' ) { jQuery = require('jquery'); } else { jQuery = require('jquery')(root); } } return factory(jQuery); }; } else { // Browser globals factory(window.jQuery); } }(function ($) { /** * English spoken in Great Britain */ $.FE.LANGUAGE['en_gb'] = { translation: { // Place holder "Type something": "Type something", // Basic formatting "Bold": "Bold", "Italic": "Italic", "Underline": "Underline", "Strikethrough": "Strikethrough", // Main buttons "Insert": "Insert", "Delete": "Delete", "Cancel": "Cancel", "OK": "OK", "Back": "Back", "Remove": "Remove", "More": "More", "Update": "Update", "Style": "Style", // Font "Font Family": "Font Family", "Font Size": "Font Size", // Colors "Colors": "Colours", "Background": "Background", "Text": "Text", "HEX Color": "HEX Colour", // Paragraphs "Paragraph Format": "Paragraph Format", "Normal": "Normal", "Code": "Code", "Heading 1": "Heading 1", "Heading 2": "Heading 2", "Heading 3": "Heading 3", "Heading 4": "Heading 4", // Style "Paragraph Style": "Paragraph Style", "Inline Style": "Inline Style", // Alignment "Align": "Align", "Align Left": "Align Left", "Align Center": "Align Centre", "Align Right": "Alight Right", "Align Justify": "Align Justify", "None": "None", // Lists "Ordered List": "Ordered List", "Unordered List": "Unordered List", // Indent "Decrease Indent": "Decrease Indent", "Increase Indent": "Increase Indent", // Links "Insert Link": "Insert Link", "Open in new tab": "Open in new tab", "Open Link": "Open Link", "Edit Link": "Edit Link", "Unlink": "Unlink", "Choose Link": "Choose Link", // Images "Insert Image": "Insert Image", "Upload Image": "Upload Image", "By URL": "By URL", "Browse": "Browse", "Drop image": "Drop image", "or click": "or click", "Manage Images": "Manage Images", "Loading": "Loading", "Deleting": "Deleting", "Tags": "Tags", "Are you sure? Image will be deleted.": "Are you sure? Image will be deleted.", "Replace": "Replace", "Uploading": "Uploading", "Loading image": "Loading image", "Display": "Display", "Inline": "Inline", "Break Text": "Break Text", "Alternate Text": "Alternate Text", "Change Size": "Change Size", "Width": "Width", "Height": "Height", "Something went wrong. Please try again.": "Something went wrong. Please try again.", "Image Caption": "Image Caption", "Advanced Edit": "Advanced Edit", // Video "Insert Video": "Insert Video", "Embedded Code": "Embedded Code", "Paste in a video URL": "Paste in a video URL", "Drop video": "Drop video", "Your browser does not support HTML5 video.": "Your browser does not support HTML5 video.", "Upload Video": "Upload Video", // Tables "Insert Table": "Insert Table", "Table Header": "Table Header", "Remove Table": "Remove Table", "Table Style": "Table Style", "Horizontal Align": "Horizontal Align", "Row": "Row", "Insert row above": "Insert row above", "Insert row below": "Insert row below", "Delete row": "Delete row", "Column": "Column", "Insert column before": "Insert column before", "Insert column after": "Insert column after", "Delete column": "Delete column", "Cell": "Cell", "Merge cells": "Merge cells", "Horizontal split": "Horizontal split", "Vertical split": "Vertical split", "Cell Background": "Cell Background", "Vertical Align": "Vertical Align", "Top": "Top", "Middle": "Middle", "Bottom": "Bottom", "Align Top": "Align Top", "Align Middle": "Align Middle", "Align Bottom": "Align Bottom", "Cell Style": "Cell Style", // Files "Upload File": "Upload File", "Drop file": "Drop file", // Emoticons "Emoticons": "Emoticons", // Line breaker "Break": "Break", // Math "Subscript": "Subscript", "Superscript": "Superscript", // Full screen "Fullscreen": "Fullscreen", // Horizontal line "Insert Horizontal Line": "Insert Horizontal Line", // Clear formatting "Clear Formatting": "Cell Formatting", // Undo, redo "Undo": "Undo", "Redo": "Redo", // Select all "Select All": "Select All", // Code view "Code View": "Code View", // Quote "Quote": "Quote", "Increase": "Increase", "Decrease": "Decrease", // Quick Insert "Quick Insert": "Quick Insert", // Spcial Characters "Special Characters": "Special Characters", "Latin": "Latin", "Greek": "Greek", "Cyrillic": "Cyrillic", "Punctuation": "Punctuation", "Currency": "Currency", "Arrows": "Arrows", "Math": "Math", "Misc": "Misc", // Print. "Print": "Print", // Spell Checker. "Spell Checker": "Spell Checker", // Help "Help": "Help", "Shortcuts": "Shortcuts", "Inline Editor": "Inline Editor", "Show the editor": "Show the editor", "Common actions": "Common actions", "Copy": "Copy", "Cut": "Cut", "Paste": "Paste", "Basic Formatting": "Basic Formatting", "Increase quote level": "Increase quote level", "Decrease quote level": "Decrease quote level", "Image / Video": "Image / Video", "Resize larger": "Resize larger", "Resize smaller": "Resize smaller", "Table": "Table", "Select table cell": "Select table cell", "Extend selection one cell": "Extend selection one cell", "Extend selection one row": "Extend selection one row", "Navigation": "Navigation", "Focus popup / toolbar": "Focus popup / toolbar", "Return focus to previous position": "Return focus to previous position", // Embed.ly "Embed URL": "Embed URL", "Paste in a URL to embed": "Paste in a URL to embed", // Word Paste. "The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?": "The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?", "Keep": "Keep", "Clean": "Clean", "Word Paste Detected": "Word Paste Detected" }, direction: "ltr" }; }));
/* eslint no-constant-condition:0 */ const findEndOfMath = function(delimiter, text, startIndex) { // Adapted from // https://github.com/Khan/perseus/blob/master/src/perseus-markdown.jsx let index = startIndex; let braceLevel = 0; const delimLength = delimiter.length; while (index < text.length) { const character = text[index]; if (braceLevel <= 0 && text.slice(index, index + delimLength) === delimiter) { return index; } else if (character === "\\") { index++; } else if (character === "{") { braceLevel++; } else if (character === "}") { braceLevel--; } index++; } return -1; }; const splitAtDelimiters = function(startData, leftDelim, rightDelim, display) { const finalData = []; for (let i = 0; i < startData.length; i++) { if (startData[i].type === "text") { const text = startData[i].data; let lookingForLeft = true; let currIndex = 0; let nextIndex; nextIndex = text.indexOf(leftDelim); if (nextIndex !== -1) { currIndex = nextIndex; finalData.push({ type: "text", data: text.slice(0, currIndex), }); lookingForLeft = false; } while (true) { if (lookingForLeft) { nextIndex = text.indexOf(leftDelim, currIndex); if (nextIndex === -1) { break; } finalData.push({ type: "text", data: text.slice(currIndex, nextIndex), }); currIndex = nextIndex; } else { nextIndex = findEndOfMath( rightDelim, text, currIndex + leftDelim.length); if (nextIndex === -1) { break; } finalData.push({ type: "math", data: text.slice( currIndex + leftDelim.length, nextIndex), rawData: text.slice( currIndex, nextIndex + rightDelim.length), display: display, }); currIndex = nextIndex + rightDelim.length; } lookingForLeft = !lookingForLeft; } finalData.push({ type: "text", data: text.slice(currIndex), }); } else { finalData.push(startData[i]); } } return finalData; }; export default splitAtDelimiters;
'use strict'; /* globals generateInputCompilerHelper: false */ describe('input', function() { var helper = {}, $compile, $rootScope, $browser, $sniffer, $timeout, $q; generateInputCompilerHelper(helper); beforeEach(inject(function(_$compile_, _$rootScope_, _$browser_, _$sniffer_, _$timeout_, _$q_) { $compile = _$compile_; $rootScope = _$rootScope_; $browser = _$browser_; $sniffer = _$sniffer_; $timeout = _$timeout_; $q = _$q_; })); it('should bind to a model', function() { var inputElm = helper.compileInput('<input type="text" ng-model="name" name="alias" ng-change="change()" />'); $rootScope.$apply("name = 'misko'"); expect(inputElm.val()).toBe('misko'); }); it('should not set readonly or disabled property on ie7', function() { jasmine.addMatchers({ toBeOff: function() { return { compare: function(actual, attributeName) { var actualValue = actual.attr(attributeName); var message = function() { return "Attribute '" + attributeName + "' expected to be off but was '" + actualValue + "' in: " + angular.mock.dump(actual); }; return { pass: !actualValue || actualValue == 'false', message: message }; } }; } }); var inputElm = helper.compileInput('<input type="text" ng-model="name" name="alias"/>'); expect(inputElm.prop('readOnly')).toBe(false); expect(inputElm.prop('disabled')).toBe(false); expect(inputElm).toBeOff('readOnly'); expect(inputElm).toBeOff('readonly'); expect(inputElm).toBeOff('disabled'); }); it('should update the model on "blur" event', function() { var inputElm = helper.compileInput('<input type="text" ng-model="name" name="alias" ng-change="change()" />'); helper.changeInputValueTo('adam'); expect($rootScope.name).toEqual('adam'); }); it('should not add the property to the scope if name is unspecified', function() { helper.compileInput('<input type="text" ng-model="name">'); expect($rootScope.form['undefined']).toBeUndefined(); expect($rootScope.form.$addControl).not.toHaveBeenCalled(); expect($rootScope.form.$$renameControl).not.toHaveBeenCalled(); }); it('should not set the `val` property when the value is equal to the current value', inject(function($rootScope, $compile) { // This is a workaround for Firefox validation. Look at #12102. var input = jqLite('<input type="text" ng-model="foo" required/>'); var setterCalls = 0; $rootScope.foo = ''; Object.defineProperty(input[0], 'value', { get: function() { return ''; }, set: function() { setterCalls++; } }); $compile(input)($rootScope); $rootScope.$digest(); expect(setterCalls).toBe(0); })); describe('compositionevents', function() { it('should not update the model between "compositionstart" and "compositionend" on non android', function() { $sniffer.android = false; var inputElm = helper.compileInput('<input type="text" ng-model="name" name="alias"" />'); helper.changeInputValueTo('a'); expect($rootScope.name).toEqual('a'); browserTrigger(inputElm, 'compositionstart'); helper.changeInputValueTo('adam'); expect($rootScope.name).toEqual('a'); browserTrigger(inputElm, 'compositionend'); helper.changeInputValueTo('adam'); expect($rootScope.name).toEqual('adam'); }); it('should update the model between "compositionstart" and "compositionend" on android', function() { $sniffer.android = true; var inputElm = helper.compileInput('<input type="text" ng-model="name" name="alias"" />'); helper.changeInputValueTo('a'); expect($rootScope.name).toEqual('a'); browserTrigger(inputElm, 'compositionstart'); helper.changeInputValueTo('adam'); expect($rootScope.name).toEqual('adam'); browserTrigger(inputElm, 'compositionend'); helper.changeInputValueTo('adam2'); expect($rootScope.name).toEqual('adam2'); }); it('should update the model on "compositionend"', function() { var inputElm = helper.compileInput('<input type="text" ng-model="name" name="alias" />'); browserTrigger(inputElm, 'compositionstart'); helper.changeInputValueTo('caitp'); expect($rootScope.name).toBeUndefined(); browserTrigger(inputElm, 'compositionend'); expect($rootScope.name).toEqual('caitp'); }); }); describe("IE placeholder input events", function() { //IE fires an input event whenever a placeholder visually changes, essentially treating it as a value //Events: // placeholder attribute change: *input* // focus (which visually removes the placeholder value): focusin focus *input* // blur (which visually creates the placeholder value): focusout *input* blur //However none of these occur if the placeholder is not visible at the time of the event. //These tests try simulate various scenarios which do/do-not fire the extra input event it('should not dirty the model on an input event in response to a placeholder change', function() { var inputElm = helper.compileInput('<input type="text" placeholder="Test" attr-capture ng-model="unsetValue" name="name" />'); msie && browserTrigger(inputElm, 'input'); expect(inputElm.attr('placeholder')).toBe('Test'); expect(inputElm).toBePristine(); helper.attrs.$set('placeholder', ''); msie && browserTrigger(inputElm, 'input'); expect(inputElm.attr('placeholder')).toBe(''); expect(inputElm).toBePristine(); helper.attrs.$set('placeholder', 'Test Again'); msie && browserTrigger(inputElm, 'input'); expect(inputElm.attr('placeholder')).toBe('Test Again'); expect(inputElm).toBePristine(); helper.attrs.$set('placeholder', undefined); msie && browserTrigger(inputElm, 'input'); expect(inputElm.attr('placeholder')).toBeUndefined(); expect(inputElm).toBePristine(); helper.changeInputValueTo('foo'); expect(inputElm).toBeDirty(); }); it('should not dirty the model on an input event in response to a interpolated placeholder change', function() { var inputElm = helper.compileInput('<input type="text" placeholder="{{ph}}" ng-model="unsetValue" name="name" />'); msie && browserTrigger(inputElm, 'input'); expect(inputElm).toBePristine(); $rootScope.ph = 1; $rootScope.$digest(); msie && browserTrigger(inputElm, 'input'); expect(inputElm).toBePristine(); $rootScope.ph = ""; $rootScope.$digest(); msie && browserTrigger(inputElm, 'input'); expect(inputElm).toBePristine(); helper.changeInputValueTo('foo'); expect(inputElm).toBeDirty(); }); it('should dirty the model on an input event while in focus even if the placeholder changes', function() { $rootScope.ph = 'Test'; var inputElm = helper.compileInput('<input type="text" ng-attr-placeholder="{{ph}}" ng-model="unsetValue" name="name" />'); expect(inputElm).toBePristine(); browserTrigger(inputElm, 'focusin'); browserTrigger(inputElm, 'focus'); msie && browserTrigger(inputElm, 'input'); expect(inputElm.attr('placeholder')).toBe('Test'); expect(inputElm).toBePristine(); $rootScope.ph = 'Test Again'; $rootScope.$digest(); expect(inputElm).toBePristine(); helper.changeInputValueTo('foo'); expect(inputElm).toBeDirty(); }); it('should not dirty the model on an input event in response to a ng-attr-placeholder change', function() { var inputElm = helper.compileInput('<input type="text" ng-attr-placeholder="{{ph}}" ng-model="unsetValue" name="name" />'); expect(inputElm).toBePristine(); $rootScope.ph = 1; $rootScope.$digest(); msie && browserTrigger(inputElm, 'input'); expect(inputElm).toBePristine(); $rootScope.ph = ""; $rootScope.$digest(); msie && browserTrigger(inputElm, 'input'); expect(inputElm).toBePristine(); helper.changeInputValueTo('foo'); expect(inputElm).toBeDirty(); }); it('should not dirty the model on an input event in response to a focus', function() { var inputElm = helper.compileInput('<input type="text" placeholder="Test" ng-model="unsetValue" name="name" />'); msie && browserTrigger(inputElm, 'input'); expect(inputElm.attr('placeholder')).toBe('Test'); expect(inputElm).toBePristine(); browserTrigger(inputElm, 'focusin'); browserTrigger(inputElm, 'focus'); msie && browserTrigger(inputElm, 'input'); expect(inputElm.attr('placeholder')).toBe('Test'); expect(inputElm).toBePristine(); helper.changeInputValueTo('foo'); expect(inputElm).toBeDirty(); }); it('should not dirty the model on an input event in response to a blur', function() { var inputElm = helper.compileInput('<input type="text" placeholder="Test" ng-model="unsetValue" name="name" />'); msie && browserTrigger(inputElm, 'input'); expect(inputElm.attr('placeholder')).toBe('Test'); expect(inputElm).toBePristine(); browserTrigger(inputElm, 'focusin'); browserTrigger(inputElm, 'focus'); msie && browserTrigger(inputElm, 'input'); expect(inputElm).toBePristine(); browserTrigger(inputElm, 'focusout'); msie && browserTrigger(inputElm, 'input'); browserTrigger(inputElm, 'blur'); expect(inputElm).toBePristine(); helper.changeInputValueTo('foo'); expect(inputElm).toBeDirty(); }); it('should dirty the model on an input event if there is a placeholder and value', function() { $rootScope.name = 'foo'; var inputElm = helper.compileInput('<input type="text" placeholder="Test" ng-model="name" value="init" name="name" />'); expect(inputElm.val()).toBe($rootScope.name); expect(inputElm).toBePristine(); helper.changeInputValueTo('bar'); expect(inputElm).toBeDirty(); }); it('should dirty the model on an input event if there is a placeholder and value after focusing', function() { $rootScope.name = 'foo'; var inputElm = helper.compileInput('<input type="text" placeholder="Test" ng-model="name" value="init" name="name" />'); expect(inputElm.val()).toBe($rootScope.name); expect(inputElm).toBePristine(); browserTrigger(inputElm, 'focusin'); browserTrigger(inputElm, 'focus'); helper.changeInputValueTo('bar'); expect(inputElm).toBeDirty(); }); it('should dirty the model on an input event if there is a placeholder and value after bluring', function() { $rootScope.name = 'foo'; var inputElm = helper.compileInput('<input type="text" placeholder="Test" ng-model="name" value="init" name="name" />'); expect(inputElm.val()).toBe($rootScope.name); expect(inputElm).toBePristine(); browserTrigger(inputElm, 'focusin'); browserTrigger(inputElm, 'focus'); expect(inputElm).toBePristine(); browserTrigger(inputElm, 'focusout'); browserTrigger(inputElm, 'blur'); helper.changeInputValueTo('bar'); expect(inputElm).toBeDirty(); }); }); describe('interpolated names', function() { it('should interpolate input names', function() { $rootScope.nameID = '47'; var inputElm = helper.compileInput('<input type="text" ng-model="name" name="name{{nameID}}" />'); expect($rootScope.form.name47.$pristine).toBeTruthy(); helper.changeInputValueTo('caitp'); expect($rootScope.form.name47.$dirty).toBeTruthy(); }); it('should rename form controls in form when interpolated name changes', function() { $rootScope.nameID = "A"; var inputElm = helper.compileInput('<input type="text" ng-model="name" name="name{{nameID}}" />'); expect($rootScope.form.nameA.$name).toBe('nameA'); var oldModel = $rootScope.form.nameA; $rootScope.nameID = "B"; $rootScope.$digest(); expect($rootScope.form.nameA).toBeUndefined(); expect($rootScope.form.nameB).toBe(oldModel); expect($rootScope.form.nameB.$name).toBe('nameB'); }); it('should rename form controls in null form when interpolated name changes', function() { $rootScope.nameID = "A"; var inputElm = helper.compileInput('<input type="text" ng-model="name" name="name{{nameID}}" />'); var model = inputElm.controller('ngModel'); expect(model.$name).toBe('nameA'); $rootScope.nameID = "B"; $rootScope.$digest(); expect(model.$name).toBe('nameB'); }); }); describe('"change" event', function() { var assertBrowserSupportsChangeEvent; beforeEach(function() { assertBrowserSupportsChangeEvent = function(inputEventSupported) { // Force browser to report a lack of an 'input' event $sniffer.hasEvent = function(eventName) { return !(eventName === 'input' && !inputEventSupported); }; var inputElm = helper.compileInput('<input type="text" ng-model="name" name="alias" />'); inputElm.val('mark'); browserTrigger(inputElm, 'change'); expect($rootScope.name).toEqual('mark'); }; }); it('should update the model event if the browser does not support the "input" event',function() { assertBrowserSupportsChangeEvent(false); }); it('should update the model event if the browser supports the "input" ' + 'event so that form auto complete works',function() { assertBrowserSupportsChangeEvent(true); }); if (!_jqLiteMode) { describe('double $digest when triggering an event using jQuery', function() { var run; beforeEach(function() { run = function(scope) { $sniffer.hasEvent = function(eventName) { return eventName !== 'input'; }; scope = scope || $rootScope; var inputElm = helper.compileInput('<input type="text" ng-model="name" name="alias" ng-change="change()" />', false, scope); scope.field = 'fake field'; scope.$watch('field', function() { // We need to use _originalTrigger since trigger is modified by Angular Scenario. inputElm._originalTrigger('change'); }); scope.$apply(); }; }); it('should not cause the double $digest with non isolate scopes', function() { run(); }); it('should not cause the double $digest with isolate scopes', function() { run($rootScope.$new(true)); }); }); } }); describe('"keydown", "paste" and "cut" events', function() { beforeEach(function() { // Force browser to report a lack of an 'input' event $sniffer.hasEvent = function(eventName) { return eventName !== 'input'; }; }); it('should update the model on "paste" event if the input value changes', function() { var inputElm = helper.compileInput('<input type="text" ng-model="name" name="alias" ng-change="change()" />'); browserTrigger(inputElm, 'keydown'); $browser.defer.flush(); expect(inputElm).toBePristine(); inputElm.val('mark'); browserTrigger(inputElm, 'paste'); $browser.defer.flush(); expect($rootScope.name).toEqual('mark'); }); it('should update the model on "cut" event', function() { var inputElm = helper.compileInput('<input type="text" ng-model="name" name="alias" ng-change="change()" />'); inputElm.val('john'); browserTrigger(inputElm, 'cut'); $browser.defer.flush(); expect($rootScope.name).toEqual('john'); }); it('should cancel the delayed dirty if a change occurs', function() { var inputElm = helper.compileInput('<input type="text" ng-model="name" />'); var ctrl = inputElm.controller('ngModel'); browserTrigger(inputElm, 'keydown', {target: inputElm[0]}); inputElm.val('f'); browserTrigger(inputElm, 'change'); expect(inputElm).toBeDirty(); ctrl.$setPristine(); $rootScope.$apply(); $browser.defer.flush(); expect(inputElm).toBePristine(); }); }); describe('ngTrim', function() { it('should update the model and trim the value', function() { var inputElm = helper.compileInput('<input type="text" ng-model="name" name="alias" ng-change="change()" />'); helper.changeInputValueTo(' a '); expect($rootScope.name).toEqual('a'); }); it('should update the model and not trim the value', function() { var inputElm = helper.compileInput('<input type="text" ng-model="name" name="alias" ng-trim="false" />'); helper.changeInputValueTo(' a '); expect($rootScope.name).toEqual(' a '); }); }); it('should allow complex reference binding', function() { var inputElm = helper.compileInput('<input type="text" ng-model="obj[\'abc\'].name"/>'); $rootScope.$apply("obj = { abc: { name: 'Misko'} }"); expect(inputElm.val()).toEqual('Misko'); }); it('should ignore input without ngModel directive', function() { var inputElm = helper.compileInput('<input type="text" name="whatever" required />'); helper.changeInputValueTo(''); expect(inputElm.hasClass('ng-valid')).toBe(false); expect(inputElm.hasClass('ng-invalid')).toBe(false); expect(inputElm.hasClass('ng-pristine')).toBe(false); expect(inputElm.hasClass('ng-dirty')).toBe(false); }); it('should report error on assignment error', function() { expect(function() { var inputElm = helper.compileInput('<input type="text" ng-model="throw \'\'">'); }).toThrowMinErr("$parse", "syntax", "Syntax Error: Token '''' is an unexpected token at column 7 of the expression [throw ''] starting at ['']."); }); it("should render as blank if null", function() { var inputElm = helper.compileInput('<input type="text" ng-model="age" />'); $rootScope.$apply('age = null'); expect($rootScope.age).toBeNull(); expect(inputElm.val()).toEqual(''); }); it('should render 0 even if it is a number', function() { var inputElm = helper.compileInput('<input type="text" ng-model="value" />'); $rootScope.$apply('value = 0'); expect(inputElm.val()).toBe('0'); }); it('should render the $viewValue when $modelValue is empty', function() { var inputElm = helper.compileInput('<input type="text" ng-model="value" />'); var ctrl = inputElm.controller('ngModel'); ctrl.$modelValue = null; expect(ctrl.$isEmpty(ctrl.$modelValue)).toBe(true); ctrl.$viewValue = 'abc'; ctrl.$render(); expect(inputElm.val()).toBe('abc'); }); // INPUT TYPES describe('month', function() { it('should throw if model is not a Date object', function() { var inputElm = helper.compileInput('<input type="month" ng-model="january"/>'); expect(function() { $rootScope.$apply(function() { $rootScope.january = '2013-01'; }); }).toThrowMinErr('ngModel', 'datefmt', 'Expected `2013-01` to be a date'); }); it('should set the view if the model is a valid Date object', function() { var inputElm = helper.compileInput('<input type="month" ng-model="march"/>'); $rootScope.$apply(function() { $rootScope.march = new Date(2013, 2, 1); }); expect(inputElm.val()).toBe('2013-03'); }); it('should set the model undefined if the input is an invalid month string', function() { var inputElm = helper.compileInput('<input type="month" ng-model="value"/>'); $rootScope.$apply(function() { $rootScope.value = new Date(2013, 0, 1); }); expect(inputElm.val()).toBe('2013-01'); //set to text for browsers with datetime-local validation. inputElm[0].setAttribute('type', 'text'); helper.changeInputValueTo('stuff'); expect(inputElm.val()).toBe('stuff'); expect($rootScope.value).toBeUndefined(); expect(inputElm).toBeInvalid(); }); it('should render as blank if null', function() { var inputElm = helper.compileInput('<input type="month" ng-model="test" />'); $rootScope.$apply('test = null'); expect($rootScope.test).toBeNull(); expect(inputElm.val()).toEqual(''); }); it('should come up blank when no value specified', function() { var inputElm = helper.compileInput('<input type="month" ng-model="test" />'); expect(inputElm.val()).toBe(''); $rootScope.$apply('test = null'); expect($rootScope.test).toBeNull(); expect(inputElm.val()).toBe(''); }); it('should parse empty string to null', function() { var inputElm = helper.compileInput('<input type="month" ng-model="test" />'); $rootScope.$apply(function() { $rootScope.test = new Date(2011, 0, 1); }); helper.changeInputValueTo(''); expect($rootScope.test).toBeNull(); expect(inputElm).toBeValid(); }); it('should use UTC if specified in the options', function() { var inputElm = helper.compileInput('<input type="month" ng-model="value" ng-model-options="{timezone: \'UTC\'}" />'); helper.changeInputValueTo('2013-07'); expect(+$rootScope.value).toBe(Date.UTC(2013, 6, 1)); $rootScope.$apply(function() { $rootScope.value = new Date(Date.UTC(2014, 6, 1)); }); expect(inputElm.val()).toBe('2014-07'); }); they('should use any timezone if specified in the options (format: $prop)', {'+HHmm': '+0500', '+HH:mm': '+05:00'}, function(tz) { var ngModelOptions = "{timezone: '" + tz + "'}"; var inputElm = helper.compileInput( '<input type="month" ng-model="value" ng-model-options="' + ngModelOptions + '" />'); helper.changeInputValueTo('2013-07'); expect(+$rootScope.value).toBe(Date.UTC(2013, 5, 30, 19, 0, 0)); $rootScope.$apply(function() { $rootScope.value = new Date(Date.UTC(2014, 5, 30, 19, 0, 0)); }); expect(inputElm.val()).toBe('2014-07'); } ); it('should label parse errors as `month`', function() { var inputElm = helper.compileInput('<input type="month" ng-model="val" name="alias" />', { valid: false, badInput: true }); helper.changeInputValueTo('xxx'); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$error.month).toBeTruthy(); }); it('should allow four or more digits in year', function() { var inputElm = helper.compileInput('<input type="month" ng-model="value" ng-model-options="{timezone: \'UTC\'}"/>'); helper.changeInputValueTo('10123-03'); expect(+$rootScope.value).toBe(Date.UTC(10123, 2, 1, 0, 0, 0)); $rootScope.$apply(function() { $rootScope.value = new Date(Date.UTC(20456, 3, 1, 0, 0, 0)); }); expect(inputElm.val()).toBe('20456-04'); }); it('should only change the month of a bound date', function() { var inputElm = helper.compileInput('<input type="month" ng-model="value" ng-model-options="{timezone: \'UTC\'}" />'); $rootScope.$apply(function() { $rootScope.value = new Date(Date.UTC(2013, 7, 1, 1, 0, 0, 0)); }); helper.changeInputValueTo('2013-12'); expect(+$rootScope.value).toBe(Date.UTC(2013, 11, 1, 1, 0, 0, 0)); expect(inputElm.val()).toBe('2013-12'); }); it('should only change the month of a bound date in any timezone', function() { var inputElm = helper.compileInput('<input type="month" ng-model="value" ng-model-options="{timezone: \'+0500\'}" />'); $rootScope.$apply(function() { $rootScope.value = new Date(Date.UTC(2013, 6, 31, 20, 0, 0)); }); helper.changeInputValueTo('2013-09'); expect(+$rootScope.value).toBe(Date.UTC(2013, 7, 31, 20, 0, 0)); expect(inputElm.val()).toBe('2013-09'); }); describe('min', function() { var inputElm; beforeEach(function() { $rootScope.minVal = '2013-01'; inputElm = helper.compileInput('<input type="month" ng-model="value" name="alias" min="{{ minVal }}" />'); }); it('should invalidate', function() { helper.changeInputValueTo('2012-12'); expect(inputElm).toBeInvalid(); expect($rootScope.value).toBeFalsy(); expect($rootScope.form.alias.$error.min).toBeTruthy(); }); it('should validate', function() { helper.changeInputValueTo('2013-07'); expect(inputElm).toBeValid(); expect(+$rootScope.value).toBe(+new Date(2013, 6, 1)); expect($rootScope.form.alias.$error.min).toBeFalsy(); }); it('should revalidate when the min value changes', function() { helper.changeInputValueTo('2013-07'); expect(inputElm).toBeValid(); expect($rootScope.form.alias.$error.min).toBeFalsy(); $rootScope.minVal = '2014-01'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$error.min).toBeTruthy(); }); it('should validate if min is empty', function() { $rootScope.minVal = undefined; $rootScope.value = new Date(-9999, 0, 1, 0, 0, 0); $rootScope.$digest(); expect($rootScope.form.alias.$error.min).toBeFalsy(); }); }); describe('max', function() { var inputElm; beforeEach(function() { $rootScope.maxVal = '2013-01'; inputElm = helper.compileInput('<input type="month" ng-model="value" name="alias" max="{{ maxVal }}" />'); }); it('should validate', function() { helper.changeInputValueTo('2012-03'); expect(inputElm).toBeValid(); expect(+$rootScope.value).toBe(+new Date(2012, 2, 1)); expect($rootScope.form.alias.$error.max).toBeFalsy(); }); it('should invalidate', function() { helper.changeInputValueTo('2013-05'); expect(inputElm).toBeInvalid(); expect($rootScope.value).toBeUndefined(); expect($rootScope.form.alias.$error.max).toBeTruthy(); }); it('should revalidate when the max value changes', function() { helper.changeInputValueTo('2012-07'); expect(inputElm).toBeValid(); expect($rootScope.form.alias.$error.max).toBeFalsy(); $rootScope.maxVal = '2012-01'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$error.max).toBeTruthy(); }); it('should validate if max is empty', function() { $rootScope.maxVal = undefined; $rootScope.value = new Date(9999, 11, 31, 23, 59, 59); $rootScope.$digest(); expect($rootScope.form.alias.$error.max).toBeFalsy(); }); }); }); describe('week', function() { it('should throw if model is not a Date object', function() { var inputElm = helper.compileInput('<input type="week" ng-model="secondWeek"/>'); expect(function() { $rootScope.$apply(function() { $rootScope.secondWeek = '2013-W02'; }); }).toThrowMinErr('ngModel', 'datefmt', 'Expected `2013-W02` to be a date'); }); it('should set the view if the model is a valid Date object', function() { var inputElm = helper.compileInput('<input type="week" ng-model="secondWeek"/>'); $rootScope.$apply(function() { $rootScope.secondWeek = new Date(2013, 0, 11); }); expect(inputElm.val()).toBe('2013-W02'); }); it('should not affect the hours or minutes of a bound date', function() { var inputElm = helper.compileInput('<input type="week" ng-model="secondWeek"/>'); $rootScope.$apply(function() { $rootScope.secondWeek = new Date(2013, 0, 11, 1, 0, 0, 0); }); helper.changeInputValueTo('2013-W03'); expect(+$rootScope.secondWeek).toBe(+new Date(2013, 0, 17, 1, 0, 0, 0)); }); it('should set the model undefined if the input is an invalid week string', function() { var inputElm = helper.compileInput('<input type="week" ng-model="value"/>'); $rootScope.$apply(function() { $rootScope.value = new Date(2013, 0, 11); }); expect(inputElm.val()).toBe('2013-W02'); //set to text for browsers with datetime-local validation. inputElm[0].setAttribute('type', 'text'); helper.changeInputValueTo('stuff'); expect(inputElm.val()).toBe('stuff'); expect($rootScope.value).toBeUndefined(); expect(inputElm).toBeInvalid(); }); it('should render as blank if null', function() { var inputElm = helper.compileInput('<input type="week" ng-model="test" />'); $rootScope.$apply('test = null'); expect($rootScope.test).toBeNull(); expect(inputElm.val()).toEqual(''); }); it('should come up blank when no value specified', function() { var inputElm = helper.compileInput('<input type="week" ng-model="test" />'); expect(inputElm.val()).toBe(''); $rootScope.$apply('test = null'); expect($rootScope.test).toBeNull(); expect(inputElm.val()).toBe(''); }); it('should parse empty string to null', function() { var inputElm = helper.compileInput('<input type="week" ng-model="test" />'); $rootScope.$apply(function() { $rootScope.test = new Date(2011, 0, 1); }); helper.changeInputValueTo(''); expect($rootScope.test).toBeNull(); expect(inputElm).toBeValid(); }); it('should allow four or more digits in year', function() { var inputElm = helper.compileInput('<input type="week" ng-model="value" ng-model-options="{timezone: \'UTC\'}"/>'); helper.changeInputValueTo('10123-W03'); expect(+$rootScope.value).toBe(Date.UTC(10123, 0, 21)); $rootScope.$apply(function() { $rootScope.value = new Date(Date.UTC(20456, 0, 28)); }); expect(inputElm.val()).toBe('20456-W04'); }); it('should use UTC if specified in the options', function() { var inputElm = helper.compileInput('<input type="week" ng-model="value" ng-model-options="{timezone: \'UTC\'}" />'); helper.changeInputValueTo('2013-W03'); expect(+$rootScope.value).toBe(Date.UTC(2013, 0, 17)); $rootScope.$apply(function() { $rootScope.value = new Date(Date.UTC(2014, 0, 17)); }); expect(inputElm.val()).toBe('2014-W03'); }); they('should use any timezone if specified in the options (format: $prop)', {'+HHmm': '+0500', '+HH:mm': '+05:00'}, function(tz) { var ngModelOptions = "{timezone: '" + tz + "'}"; var inputElm = helper.compileInput( '<input type="week" ng-model="value" ng-model-options="' + ngModelOptions + '" />'); helper.changeInputValueTo('2013-W03'); expect(+$rootScope.value).toBe(Date.UTC(2013, 0, 16, 19, 0, 0)); $rootScope.$apply(function() { $rootScope.value = new Date(Date.UTC(2014, 0, 16, 19, 0, 0)); }); expect(inputElm.val()).toBe('2014-W03'); } ); it('should label parse errors as `week`', function() { var inputElm = helper.compileInput('<input type="week" ng-model="val" name="alias" />', { valid: false, badInput: true }); helper.changeInputValueTo('yyy'); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$error.week).toBeTruthy(); }); describe('min', function() { var inputElm; beforeEach(function() { $rootScope.minVal = '2013-W01'; inputElm = helper.compileInput('<input type="week" ng-model="value" name="alias" min="{{ minVal }}" />'); }); it('should invalidate', function() { helper.changeInputValueTo('2012-W12'); expect(inputElm).toBeInvalid(); expect($rootScope.value).toBeFalsy(); expect($rootScope.form.alias.$error.min).toBeTruthy(); }); it('should validate', function() { helper.changeInputValueTo('2013-W03'); expect(inputElm).toBeValid(); expect(+$rootScope.value).toBe(+new Date(2013, 0, 17)); expect($rootScope.form.alias.$error.min).toBeFalsy(); }); it('should revalidate when the min value changes', function() { helper.changeInputValueTo('2013-W03'); expect(inputElm).toBeValid(); expect($rootScope.form.alias.$error.min).toBeFalsy(); $rootScope.minVal = '2014-W01'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$error.min).toBeTruthy(); }); it('should validate if min is empty', function() { $rootScope.minVal = undefined; $rootScope.value = new Date(-9999, 0, 1, 0, 0, 0); $rootScope.$digest(); expect($rootScope.form.alias.$error.min).toBeFalsy(); }); }); describe('max', function() { var inputElm; beforeEach(function() { $rootScope.maxVal = '2013-W01'; inputElm = helper.compileInput('<input type="week" ng-model="value" name="alias" max="{{ maxVal }}" />'); }); it('should validate', function() { helper.changeInputValueTo('2012-W01'); expect(inputElm).toBeValid(); expect(+$rootScope.value).toBe(+new Date(2012, 0, 5)); expect($rootScope.form.alias.$error.max).toBeFalsy(); }); it('should invalidate', function() { helper.changeInputValueTo('2013-W03'); expect(inputElm).toBeInvalid(); expect($rootScope.value).toBeUndefined(); expect($rootScope.form.alias.$error.max).toBeTruthy(); }); it('should revalidate when the max value changes', function() { helper.changeInputValueTo('2012-W03'); expect(inputElm).toBeValid(); expect($rootScope.form.alias.$error.max).toBeFalsy(); $rootScope.maxVal = '2012-W01'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$error.max).toBeTruthy(); }); it('should validate if max is empty', function() { $rootScope.maxVal = undefined; $rootScope.value = new Date(9999, 11, 31, 23, 59, 59); $rootScope.$digest(); expect($rootScope.form.alias.$error.max).toBeFalsy(); }); }); }); describe('datetime-local', function() { it('should throw if model is not a Date object', function() { var inputElm = helper.compileInput('<input type="datetime-local" ng-model="lunchtime"/>'); expect(function() { $rootScope.$apply(function() { $rootScope.lunchtime = '2013-12-16T11:30:00'; }); }).toThrowMinErr('ngModel', 'datefmt', 'Expected `2013-12-16T11:30:00` to be a date'); }); it('should set the view if the model if a valid Date object.', function() { var inputElm = helper.compileInput('<input type="datetime-local" ng-model="halfSecondToNextYear"/>'); $rootScope.$apply(function() { $rootScope.halfSecondToNextYear = new Date(2013, 11, 31, 23, 59, 59, 500); }); expect(inputElm.val()).toBe('2013-12-31T23:59:59.500'); }); it('should set the model undefined if the view is invalid', function() { var inputElm = helper.compileInput('<input type="datetime-local" ng-model="breakMe"/>'); $rootScope.$apply(function() { $rootScope.breakMe = new Date(2009, 0, 6, 16, 25, 0); }); expect(inputElm.val()).toBe('2009-01-06T16:25:00.000'); //set to text for browsers with datetime-local validation. inputElm[0].setAttribute('type', 'text'); helper.changeInputValueTo('stuff'); expect(inputElm.val()).toBe('stuff'); expect($rootScope.breakMe).toBeUndefined(); expect(inputElm).toBeInvalid(); }); it('should render as blank if null', function() { var inputElm = helper.compileInput('<input type="datetime-local" ng-model="test" />'); $rootScope.$apply('test = null'); expect($rootScope.test).toBeNull(); expect(inputElm.val()).toEqual(''); }); it('should come up blank when no value specified', function() { var inputElm = helper.compileInput('<input type="datetime-local" ng-model="test" />'); expect(inputElm.val()).toBe(''); $rootScope.$apply('test = null'); expect($rootScope.test).toBeNull(); expect(inputElm.val()).toBe(''); }); it('should parse empty string to null', function() { var inputElm = helper.compileInput('<input type="datetime-local" ng-model="test" />'); $rootScope.$apply(function() { $rootScope.test = new Date(2011, 0, 1); }); helper.changeInputValueTo(''); expect($rootScope.test).toBeNull(); expect(inputElm).toBeValid(); }); it('should use UTC if specified in the options', function() { var inputElm = helper.compileInput('<input type="datetime-local" ng-model="value" ng-model-options="{timezone: \'UTC\'}" />'); helper.changeInputValueTo('2000-01-01T01:02'); expect(+$rootScope.value).toBe(Date.UTC(2000, 0, 1, 1, 2, 0)); $rootScope.$apply(function() { $rootScope.value = new Date(Date.UTC(2001, 0, 1, 1, 2, 0)); }); expect(inputElm.val()).toBe('2001-01-01T01:02:00.000'); }); they('should use any timezone if specified in the options (format: $prop)', {'+HHmm': '+0500', '+HH:mm': '+05:00'}, function(tz) { var ngModelOptions = "{timezone: '" + tz + "'}"; var inputElm = helper.compileInput( '<input type="datetime-local" ng-model="value" ng-model-options="' + ngModelOptions + '" />'); helper.changeInputValueTo('2000-01-01T06:02'); expect(+$rootScope.value).toBe(Date.UTC(2000, 0, 1, 1, 2, 0)); $rootScope.$apply(function() { $rootScope.value = new Date(Date.UTC(2001, 0, 1, 1, 2, 0)); }); expect(inputElm.val()).toBe('2001-01-01T06:02:00.000'); } ); it('should fallback to default timezone in case an unknown timezone was passed', function() { var inputElm = helper.compileInput( '<input type="datetime-local" ng-model="value1" ng-model-options="{timezone: \'WTF\'}" />' + '<input type="datetime-local" ng-model="value2" />'); helper.changeGivenInputTo(inputElm.eq(0), '2000-01-01T06:02'); helper.changeGivenInputTo(inputElm.eq(1), '2000-01-01T06:02'); expect($rootScope.value1).toEqual($rootScope.value2); }); it('should allow to specify the milliseconds', function() { var inputElm = helper.compileInput('<input type="datetime-local" ng-model="value"" />'); helper.changeInputValueTo('2000-01-01T01:02:03.500'); expect(+$rootScope.value).toBe(+new Date(2000, 0, 1, 1, 2, 3, 500)); }); it('should allow to specify single digit milliseconds', function() { var inputElm = helper.compileInput('<input type="datetime-local" ng-model="value"" />'); helper.changeInputValueTo('2000-01-01T01:02:03.4'); expect(+$rootScope.value).toBe(+new Date(2000, 0, 1, 1, 2, 3, 400)); }); it('should allow to specify the seconds', function() { var inputElm = helper.compileInput('<input type="datetime-local" ng-model="value"" />'); helper.changeInputValueTo('2000-01-01T01:02:03'); expect(+$rootScope.value).toBe(+new Date(2000, 0, 1, 1, 2, 3)); $rootScope.$apply(function() { $rootScope.value = new Date(2001, 0, 1, 1, 2, 3); }); expect(inputElm.val()).toBe('2001-01-01T01:02:03.000'); }); it('should allow to skip the seconds', function() { var inputElm = helper.compileInput('<input type="datetime-local" ng-model="value"" />'); helper.changeInputValueTo('2000-01-01T01:02'); expect(+$rootScope.value).toBe(+new Date(2000, 0, 1, 1, 2, 0)); }); it('should allow four or more digits in year', function() { var inputElm = helper.compileInput('<input type="datetime-local" ng-model="value" />'); helper.changeInputValueTo('10123-01-01T01:02'); expect(+$rootScope.value).toBe(+new Date(10123, 0, 1, 1, 2, 0)); $rootScope.$apply(function() { $rootScope.value = new Date(20456, 1, 1, 1, 2, 0); }); expect(inputElm.val()).toBe('20456-02-01T01:02:00.000'); } ); it('should label parse errors as `datetimelocal`', function() { var inputElm = helper.compileInput('<input type="datetime-local" ng-model="val" name="alias" />', { valid: false, badInput: true }); helper.changeInputValueTo('zzz'); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$error.datetimelocal).toBeTruthy(); }); describe('min', function() { var inputElm; beforeEach(function() { $rootScope.minVal = '2000-01-01T12:30:00'; inputElm = helper.compileInput('<input type="datetime-local" ng-model="value" name="alias" min="{{ minVal }}" />'); }); it('should invalidate', function() { helper.changeInputValueTo('1999-12-31T01:02:00'); expect(inputElm).toBeInvalid(); expect($rootScope.value).toBeFalsy(); expect($rootScope.form.alias.$error.min).toBeTruthy(); }); it('should validate', function() { helper.changeInputValueTo('2000-01-01T23:02:00'); expect(inputElm).toBeValid(); expect(+$rootScope.value).toBe(+new Date(2000, 0, 1, 23, 2, 0)); expect($rootScope.form.alias.$error.min).toBeFalsy(); }); it('should revalidate when the min value changes', function() { helper.changeInputValueTo('2000-02-01T01:02:00'); expect(inputElm).toBeValid(); expect($rootScope.form.alias.$error.min).toBeFalsy(); $rootScope.minVal = '2010-01-01T01:02:00'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$error.min).toBeTruthy(); }); it('should validate if min is empty', function() { $rootScope.minVal = undefined; $rootScope.value = new Date(-9999, 0, 1, 0, 0, 0); $rootScope.$digest(); expect($rootScope.form.alias.$error.min).toBeFalsy(); }); }); describe('max', function() { var inputElm; beforeEach(function() { $rootScope.maxVal = '2019-01-01T01:02:00'; inputElm = helper.compileInput('<input type="datetime-local" ng-model="value" name="alias" max="{{ maxVal }}" />'); }); it('should invalidate', function() { helper.changeInputValueTo('2019-12-31T01:02:00'); expect(inputElm).toBeInvalid(); expect($rootScope.value).toBeFalsy(); expect($rootScope.form.alias.$error.max).toBeTruthy(); }); it('should validate', function() { helper.changeInputValueTo('2000-01-01T01:02:00'); expect(inputElm).toBeValid(); expect(+$rootScope.value).toBe(+new Date(2000, 0, 1, 1, 2, 0)); expect($rootScope.form.alias.$error.max).toBeFalsy(); }); it('should revalidate when the max value changes', function() { helper.changeInputValueTo('2000-02-01T01:02:00'); expect(inputElm).toBeValid(); expect($rootScope.form.alias.$error.max).toBeFalsy(); $rootScope.maxVal = '2000-01-01T01:02:00'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$error.max).toBeTruthy(); }); it('should validate if max is empty', function() { $rootScope.maxVal = undefined; $rootScope.value = new Date(3000, 11, 31, 23, 59, 59); $rootScope.$digest(); expect($rootScope.form.alias.$error.max).toBeFalsy(); }); }); it('should validate even if max value changes on-the-fly', function() { $rootScope.max = '2013-01-01T01:02:00'; var inputElm = helper.compileInput('<input type="datetime-local" ng-model="value" name="alias" max="{{max}}" />'); helper.changeInputValueTo('2014-01-01T12:34:00'); expect(inputElm).toBeInvalid(); $rootScope.max = '2001-01-01T01:02:00'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); $rootScope.max = '2024-01-01T01:02:00'; $rootScope.$digest(); expect(inputElm).toBeValid(); }); it('should validate even if min value changes on-the-fly', function() { $rootScope.min = '2013-01-01T01:02:00'; var inputElm = helper.compileInput('<input type="datetime-local" ng-model="value" name="alias" min="{{min}}" />'); helper.changeInputValueTo('2010-01-01T12:34:00'); expect(inputElm).toBeInvalid(); $rootScope.min = '2014-01-01T01:02:00'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); $rootScope.min = '2009-01-01T01:02:00'; $rootScope.$digest(); expect(inputElm).toBeValid(); }); it('should validate even if ng-max value changes on-the-fly', function() { $rootScope.max = '2013-01-01T01:02:00'; var inputElm = helper.compileInput('<input type="datetime-local" ng-model="value" name="alias" ng-max="max" />'); helper.changeInputValueTo('2014-01-01T12:34:00'); expect(inputElm).toBeInvalid(); $rootScope.max = '2001-01-01T01:02:00'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); $rootScope.max = '2024-01-01T01:02:00'; $rootScope.$digest(); expect(inputElm).toBeValid(); }); it('should validate even if ng-min value changes on-the-fly', function() { $rootScope.min = '2013-01-01T01:02:00'; var inputElm = helper.compileInput('<input type="datetime-local" ng-model="value" name="alias" ng-min="min" />'); helper.changeInputValueTo('2010-01-01T12:34:00'); expect(inputElm).toBeInvalid(); $rootScope.min = '2014-01-01T01:02:00'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); $rootScope.min = '2009-01-01T01:02:00'; $rootScope.$digest(); expect(inputElm).toBeValid(); }); }); describe('time', function() { it('should throw if model is not a Date object', function() { var inputElm = helper.compileInput('<input type="time" ng-model="lunchtime"/>'); expect(function() { $rootScope.$apply(function() { $rootScope.lunchtime = '11:30:00'; }); }).toThrowMinErr('ngModel', 'datefmt', 'Expected `11:30:00` to be a date'); }); it('should set the view if the model if a valid Date object.', function() { var inputElm = helper.compileInput('<input type="time" ng-model="threeFortyOnePm"/>'); $rootScope.$apply(function() { $rootScope.threeFortyOnePm = new Date(1970, 0, 1, 15, 41, 0, 500); }); expect(inputElm.val()).toBe('15:41:00.500'); }); it('should set the model undefined if the view is invalid', function() { var inputElm = helper.compileInput('<input type="time" ng-model="breakMe"/>'); $rootScope.$apply(function() { $rootScope.breakMe = new Date(1970, 0, 1, 16, 25, 0); }); expect(inputElm.val()).toBe('16:25:00.000'); //set to text for browsers with time validation. inputElm[0].setAttribute('type', 'text'); helper.changeInputValueTo('stuff'); expect(inputElm.val()).toBe('stuff'); expect($rootScope.breakMe).toBeUndefined(); expect(inputElm).toBeInvalid(); }); it('should render as blank if null', function() { var inputElm = helper.compileInput('<input type="time" ng-model="test" />'); $rootScope.$apply('test = null'); expect($rootScope.test).toBeNull(); expect(inputElm.val()).toEqual(''); }); it('should come up blank when no value specified', function() { var inputElm = helper.compileInput('<input type="time" ng-model="test" />'); expect(inputElm.val()).toBe(''); $rootScope.$apply('test = null'); expect($rootScope.test).toBeNull(); expect(inputElm.val()).toBe(''); }); it('should parse empty string to null', function() { var inputElm = helper.compileInput('<input type="time" ng-model="test" />'); $rootScope.$apply(function() { $rootScope.test = new Date(2011, 0, 1); }); helper.changeInputValueTo(''); expect($rootScope.test).toBeNull(); expect(inputElm).toBeValid(); }); it('should use UTC if specified in the options', function() { var inputElm = helper.compileInput('<input type="time" ng-model="value" ng-model-options="{timezone: \'UTC\'}" />'); helper.changeInputValueTo('23:02:00'); expect(+$rootScope.value).toBe(Date.UTC(1970, 0, 1, 23, 2, 0)); $rootScope.$apply(function() { $rootScope.value = new Date(Date.UTC(1971, 0, 1, 23, 2, 0)); }); expect(inputElm.val()).toBe('23:02:00.000'); }); they('should use any timezone if specified in the options (format: $prop)', {'+HHmm': '+0500', '+HH:mm': '+05:00'}, function(tz) { var ngModelOptions = "{timezone: '" + tz + "'}"; var inputElm = helper.compileInput( '<input type="time" ng-model="value" ng-model-options="' + ngModelOptions + '" />'); helper.changeInputValueTo('23:02:00'); expect(+$rootScope.value).toBe(Date.UTC(1970, 0, 1, 18, 2, 0)); $rootScope.$apply(function() { $rootScope.value = new Date(Date.UTC(1971, 0, 1, 18, 2, 0)); }); expect(inputElm.val()).toBe('23:02:00.000'); } ); it('should allow to specify the milliseconds', function() { var inputElm = helper.compileInput('<input type="time" ng-model="value"" />'); helper.changeInputValueTo('01:02:03.500'); expect(+$rootScope.value).toBe(+new Date(1970, 0, 1, 1, 2, 3, 500)); }); it('should allow to specify single digit milliseconds', function() { var inputElm = helper.compileInput('<input type="time" ng-model="value"" />'); helper.changeInputValueTo('01:02:03.4'); expect(+$rootScope.value).toBe(+new Date(1970, 0, 1, 1, 2, 3, 400)); }); it('should allow to specify the seconds', function() { var inputElm = helper.compileInput('<input type="time" ng-model="value"" />'); helper.changeInputValueTo('01:02:03'); expect(+$rootScope.value).toBe(+new Date(1970, 0, 1, 1, 2, 3)); $rootScope.$apply(function() { $rootScope.value = new Date(1970, 0, 1, 1, 2, 3); }); expect(inputElm.val()).toBe('01:02:03.000'); }); it('should allow to skip the seconds', function() { var inputElm = helper.compileInput('<input type="time" ng-model="value"" />'); helper.changeInputValueTo('01:02'); expect(+$rootScope.value).toBe(+new Date(1970, 0, 1, 1, 2, 0)); }); it('should label parse errors as `time`', function() { var inputElm = helper.compileInput('<input type="time" ng-model="val" name="alias" />', { valid: false, badInput: true }); helper.changeInputValueTo('mmm'); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$error.time).toBeTruthy(); }); it('should only change hours and minute of a bound date', function() { var inputElm = helper.compileInput('<input type="time" ng-model="value"" />'); $rootScope.$apply(function() { $rootScope.value = new Date(2013, 2, 3, 1, 0, 0); }); helper.changeInputValueTo('01:02'); expect(+$rootScope.value).toBe(+new Date(2013, 2, 3, 1, 2, 0)); }); describe('min', function() { var inputElm; beforeEach(function() { $rootScope.minVal = '09:30:00'; inputElm = helper.compileInput('<input type="time" ng-model="value" name="alias" min="{{ minVal }}" />'); }); it('should invalidate', function() { helper.changeInputValueTo('01:02:00'); expect(inputElm).toBeInvalid(); expect($rootScope.value).toBeFalsy(); expect($rootScope.form.alias.$error.min).toBeTruthy(); }); it('should validate', function() { helper.changeInputValueTo('23:02:00'); expect(inputElm).toBeValid(); expect(+$rootScope.value).toBe(+new Date(1970, 0, 1, 23, 2, 0)); expect($rootScope.form.alias.$error.min).toBeFalsy(); }); it('should revalidate when the min value changes', function() { helper.changeInputValueTo('23:02:00'); expect(inputElm).toBeValid(); expect($rootScope.form.alias.$error.min).toBeFalsy(); $rootScope.minVal = '23:55:00'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$error.min).toBeTruthy(); }); it('should validate if min is empty', function() { $rootScope.minVal = undefined; $rootScope.value = new Date(-9999, 0, 1, 0, 0, 0); $rootScope.$digest(); expect($rootScope.form.alias.$error.min).toBeFalsy(); }); }); describe('max', function() { var inputElm; beforeEach(function() { $rootScope.maxVal = '22:30:00'; inputElm = helper.compileInput('<input type="time" ng-model="value" name="alias" max="{{ maxVal }}" />'); }); it('should invalidate', function() { helper.changeInputValueTo('23:00:00'); expect(inputElm).toBeInvalid(); expect($rootScope.value).toBeFalsy(); expect($rootScope.form.alias.$error.max).toBeTruthy(); }); it('should validate', function() { helper.changeInputValueTo('05:30:00'); expect(inputElm).toBeValid(); expect(+$rootScope.value).toBe(+new Date(1970, 0, 1, 5, 30, 0)); expect($rootScope.form.alias.$error.max).toBeFalsy(); }); it('should validate if max is empty', function() { $rootScope.maxVal = undefined; $rootScope.value = new Date(9999, 11, 31, 23, 59, 59); $rootScope.$digest(); expect($rootScope.form.alias.$error.max).toBeFalsy(); }); }); it('should validate even if max value changes on-the-fly', function() { $rootScope.max = '04:02:00'; var inputElm = helper.compileInput('<input type="time" ng-model="value" name="alias" max="{{max}}" />'); helper.changeInputValueTo('05:34:00'); expect(inputElm).toBeInvalid(); $rootScope.max = '06:34:00'; $rootScope.$digest(); expect(inputElm).toBeValid(); }); it('should validate even if min value changes on-the-fly', function() { $rootScope.min = '08:45:00'; var inputElm = helper.compileInput('<input type="time" ng-model="value" name="alias" min="{{min}}" />'); helper.changeInputValueTo('06:15:00'); expect(inputElm).toBeInvalid(); $rootScope.min = '05:50:00'; $rootScope.$digest(); expect(inputElm).toBeValid(); }); it('should validate even if ng-max value changes on-the-fly', function() { $rootScope.max = '04:02:00'; var inputElm = helper.compileInput('<input type="time" ng-model="value" name="alias" ng-max="max" />'); helper.changeInputValueTo('05:34:00'); expect(inputElm).toBeInvalid(); $rootScope.max = '06:34:00'; $rootScope.$digest(); expect(inputElm).toBeValid(); }); it('should validate even if ng-min value changes on-the-fly', function() { $rootScope.min = '08:45:00'; var inputElm = helper.compileInput('<input type="time" ng-model="value" name="alias" ng-min="min" />'); helper.changeInputValueTo('06:15:00'); expect(inputElm).toBeInvalid(); $rootScope.min = '05:50:00'; $rootScope.$digest(); expect(inputElm).toBeValid(); }); }); describe('date', function() { it('should throw if model is not a Date object.', function() { var inputElm = helper.compileInput('<input type="date" ng-model="birthday"/>'); expect(function() { $rootScope.$apply(function() { $rootScope.birthday = '1977-10-22'; }); }).toThrowMinErr('ngModel', 'datefmt', 'Expected `1977-10-22` to be a date'); }); it('should set the view to empty when the model is an InvalidDate', function() { var inputElm = helper.compileInput('<input type="date" ng-model="val"/>'); // reset the element type to text otherwise newer browsers // would always set the input.value to empty for invalid dates... inputElm.attr('type', 'text'); $rootScope.$apply(function() { $rootScope.val = new Date('a'); }); expect(inputElm.val()).toBe(''); }); it('should set the view if the model if a valid Date object.', function() { var inputElm = helper.compileInput('<input type="date" ng-model="christmas"/>'); $rootScope.$apply(function() { $rootScope.christmas = new Date(2013, 11, 25); }); expect(inputElm.val()).toBe('2013-12-25'); }); it('should set the model undefined if the view is invalid', function() { var inputElm = helper.compileInput('<input type="date" ng-model="arrMatey"/>'); $rootScope.$apply(function() { $rootScope.arrMatey = new Date(2014, 8, 14); }); expect(inputElm.val()).toBe('2014-09-14'); //set to text for browsers with date validation. inputElm[0].setAttribute('type', 'text'); helper.changeInputValueTo('1-2-3'); expect(inputElm.val()).toBe('1-2-3'); expect($rootScope.arrMatey).toBeUndefined(); expect(inputElm).toBeInvalid(); }); it('should render as blank if null', function() { var inputElm = helper.compileInput('<input type="date" ng-model="test" />'); $rootScope.$apply('test = null'); expect($rootScope.test).toBeNull(); expect(inputElm.val()).toEqual(''); }); it('should come up blank when no value specified', function() { var inputElm = helper.compileInput('<input type="date" ng-model="test" />'); expect(inputElm.val()).toBe(''); $rootScope.$apply('test = null'); expect($rootScope.test).toBeNull(); expect(inputElm.val()).toBe(''); }); it('should parse empty string to null', function() { var inputElm = helper.compileInput('<input type="date" ng-model="test" />'); $rootScope.$apply(function() { $rootScope.test = new Date(2011, 0, 1); }); helper.changeInputValueTo(''); expect($rootScope.test).toBeNull(); expect(inputElm).toBeValid(); }); it('should use UTC if specified in the options', function() { var inputElm = helper.compileInput('<input type="date" ng-model="value" ng-model-options="{timezone: \'UTC\'}" />'); helper.changeInputValueTo('2000-01-01'); expect(+$rootScope.value).toBe(Date.UTC(2000, 0, 1)); $rootScope.$apply(function() { $rootScope.value = new Date(Date.UTC(2001, 0, 1)); }); expect(inputElm.val()).toBe('2001-01-01'); }); they('should use any timezone if specified in the options (format: $prop)', {'+HHmm': '+0500', '+HH:mm': '+05:00'}, function(tz) { var ngModelOptions = "{timezone: '" + tz + "'}"; var inputElm = helper.compileInput( '<input type="date" ng-model="value" ng-model-options="' + ngModelOptions + '" />'); helper.changeInputValueTo('2000-01-01'); expect(+$rootScope.value).toBe(Date.UTC(1999, 11, 31, 19, 0, 0)); $rootScope.$apply(function() { $rootScope.value = new Date(Date.UTC(2000, 11, 31, 19, 0, 0)); }); expect(inputElm.val()).toBe('2001-01-01'); } ); it('should allow four or more digits in year', function() { var inputElm = helper.compileInput('<input type="date" ng-model="value" ng-model-options="{timezone: \'UTC\'}" />'); helper.changeInputValueTo('10123-01-01'); expect(+$rootScope.value).toBe(Date.UTC(10123, 0, 1, 0, 0, 0)); $rootScope.$apply(function() { $rootScope.value = new Date(Date.UTC(20456, 1, 1, 0, 0, 0)); }); expect(inputElm.val()).toBe('20456-02-01'); } ); it('should label parse errors as `date`', function() { var inputElm = helper.compileInput('<input type="date" ng-model="val" name="alias" />', { valid: false, badInput: true }); helper.changeInputValueTo('nnn'); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$error.date).toBeTruthy(); }); it('should work with multiple date types bound to the same model', function() { var formElm = jqLite('<form name="form"></form>'); var timeElm = jqLite('<input type="time" ng-model="val" />'), monthElm = jqLite('<input type="month" ng-model="val" />'), weekElm = jqLite('<input type="week" ng-model="val" />'); formElm.append(timeElm); formElm.append(monthElm); formElm.append(weekElm); $compile(formElm)($rootScope); $rootScope.$apply(function() { $rootScope.val = new Date(2013, 1, 2, 3, 4, 5, 6); }); expect(timeElm.val()).toBe('03:04:05.006'); expect(monthElm.val()).toBe('2013-02'); expect(weekElm.val()).toBe('2013-W05'); helper.changeGivenInputTo(monthElm, '2012-02'); expect(monthElm.val()).toBe('2012-02'); expect(timeElm.val()).toBe('03:04:05.006'); expect(weekElm.val()).toBe('2012-W05'); helper.changeGivenInputTo(timeElm, '04:05:06'); expect(monthElm.val()).toBe('2012-02'); expect(timeElm.val()).toBe('04:05:06'); expect(weekElm.val()).toBe('2012-W05'); helper.changeGivenInputTo(weekElm, '2014-W01'); expect(monthElm.val()).toBe('2014-01'); expect(timeElm.val()).toBe('04:05:06.000'); expect(weekElm.val()).toBe('2014-W01'); expect(+$rootScope.val).toBe(+new Date(2014, 0, 2, 4, 5, 6, 0)); dealoc(formElm); }); describe('min', function() { it('should invalidate', function() { var inputElm = helper.compileInput('<input type="date" ng-model="value" name="alias" min="2000-01-01" />'); helper.changeInputValueTo('1999-12-31'); expect(inputElm).toBeInvalid(); expect($rootScope.value).toBeFalsy(); expect($rootScope.form.alias.$error.min).toBeTruthy(); }); it('should validate', function() { var inputElm = helper.compileInput('<input type="date" ng-model="value" name="alias" min="2000-01-01" />'); helper.changeInputValueTo('2000-01-01'); expect(inputElm).toBeValid(); expect(+$rootScope.value).toBe(+new Date(2000, 0, 1)); expect($rootScope.form.alias.$error.min).toBeFalsy(); }); it('should parse ISO-based date strings as a valid min date value', function() { var inputElm = helper.compileInput('<input name="myControl" type="date" min="{{ min }}" ng-model="value">'); $rootScope.value = new Date(2010, 1, 1, 0, 0, 0); $rootScope.min = new Date(2014, 10, 10, 0, 0, 0); $rootScope.$digest(); expect($rootScope.form.myControl.$error.min).toBeTruthy(); }); it('should validate if min is empty', function() { var inputElm = helper.compileInput( '<input type="date" name="alias" ng-model="value" min />'); $rootScope.value = new Date(-9999, 0, 1, 0, 0, 0); $rootScope.$digest(); expect($rootScope.form.alias.$error.min).toBeFalsy(); }); }); describe('max', function() { it('should invalidate', function() { var inputElm = helper.compileInput('<input type="date" ng-model="value" name="alias" max="2019-01-01" />'); helper.changeInputValueTo('2019-12-31'); expect(inputElm).toBeInvalid(); expect($rootScope.value).toBeFalsy(); expect($rootScope.form.alias.$error.max).toBeTruthy(); }); it('should validate', function() { var inputElm = helper.compileInput('<input type="date" ng-model="value" name="alias" max="2019-01-01" />'); helper.changeInputValueTo('2000-01-01'); expect(inputElm).toBeValid(); expect(+$rootScope.value).toBe(+new Date(2000, 0, 1)); expect($rootScope.form.alias.$error.max).toBeFalsy(); }); it('should parse ISO-based date strings as a valid max date value', function() { var inputElm = helper.compileInput('<input name="myControl" type="date" max="{{ max }}" ng-model="value">'); $rootScope.value = new Date(2020, 1, 1, 0, 0, 0); $rootScope.max = new Date(2014, 10, 10, 0, 0, 0); $rootScope.$digest(); expect($rootScope.form.myControl.$error.max).toBeTruthy(); }); it('should validate if max is empty', function() { var inputElm = helper.compileInput( '<input type="date" name="alias" ng-model="value" max />'); $rootScope.value = new Date(9999, 11, 31, 23, 59, 59); $rootScope.$digest(); expect($rootScope.form.alias.$error.max).toBeFalsy(); }); }); it('should validate even if max value changes on-the-fly', function() { $rootScope.max = '2013-01-01'; var inputElm = helper.compileInput('<input type="date" ng-model="value" name="alias" max="{{max}}" />'); helper.changeInputValueTo('2014-01-01'); expect(inputElm).toBeInvalid(); $rootScope.max = '2001-01-01'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); $rootScope.max = '2021-01-01'; $rootScope.$digest(); expect(inputElm).toBeValid(); }); it('should validate even if min value changes on-the-fly', function() { $rootScope.min = '2013-01-01'; var inputElm = helper.compileInput('<input type="date" ng-model="value" name="alias" min="{{min}}" />'); helper.changeInputValueTo('2010-01-01'); expect(inputElm).toBeInvalid(); $rootScope.min = '2014-01-01'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); $rootScope.min = '2009-01-01'; $rootScope.$digest(); expect(inputElm).toBeValid(); }); it('should validate even if ng-max value changes on-the-fly', function() { $rootScope.max = '2013-01-01'; var inputElm = helper.compileInput('<input type="date" ng-model="value" name="alias" ng-max="max" />'); helper.changeInputValueTo('2014-01-01'); expect(inputElm).toBeInvalid(); $rootScope.max = '2001-01-01'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); $rootScope.max = '2021-01-01'; $rootScope.$digest(); expect(inputElm).toBeValid(); }); it('should validate even if ng-min value changes on-the-fly', function() { $rootScope.min = '2013-01-01'; var inputElm = helper.compileInput('<input type="date" ng-model="value" name="alias" ng-min="min" />'); helper.changeInputValueTo('2010-01-01'); expect(inputElm).toBeInvalid(); $rootScope.min = '2014-01-01'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); $rootScope.min = '2009-01-01'; $rootScope.$digest(); expect(inputElm).toBeValid(); }); describe('ISO_DATE_REGEXP', function() { var dates = [ // Validate date ['00:00:00.0000+01:01', false], // date must be specified ['2010.06.15T00:00:00.0000+01:01', false], // date must use dash seperator ['x2010-06-15T00:00:00.0000+01:01', false], // invalid leading characters // Validate year ['2010-06-15T00:00:00.0000+01:01', true], // year has four or more digits ['20100-06-15T00:00:00.0000+01:01', true], // year has four or more digits ['-06-15T00:00:00.0000+01:01', false], // year has too few digits ['2-06-15T00:00:00.0000+01:01', false], // year has too few digits ['20-06-15T00:00:00.0000+01:01', false], // year has too few digits ['201-06-15T00:00:00.0000+01:01', false], // year has too few digits // Validate month ['2010-01-15T00:00:00.0000+01:01', true], // month has two digits ['2010--15T00:00:00.0000+01:01', false], // month has too few digits ['2010-0-15T00:00:00.0000+01:01', false], // month has too few digits ['2010-1-15T00:00:00.0000+01:01', false], // month has too few digits ['2010-111-15T00:00:00.0000+01:01', false], // month has too many digits ['2010-22-15T00:00:00.0000+01:01', false], // month is too large // Validate day ['2010-01-01T00:00:00.0000+01:01', true], // day has two digits ['2010-01-T00:00:00.0000+01:01', false], // day has too few digits ['2010-01-1T00:00:00.0000+01:01', false], // day has too few digits ['2010-01-200T00:00:00.0000+01:01', false], // day has too many digits ['2010-01-41T00:00:00.0000+01:01', false], // day is too large // Validate time ['2010-01-01', false], // time must be specified ['2010-01-0101:00:00.0000+01:01', false], // missing date time seperator ['2010-01-01V01:00:00.0000+01:01', false], // invalid date time seperator ['2010-01-01T01-00-00.0000+01:01', false], // time must use colon seperator // Validate hour ['2010-01-01T01:00:00.0000+01:01', true], // hour has two digits ['2010-01-01T-01:00:00.0000+01:01', false], // hour must be positive ['2010-01-01T:00:00.0000+01:01', false], // hour has too few digits ['2010-01-01T1:00:00.0000+01:01', false], // hour has too few digits ['2010-01-01T220:00:00.0000+01:01', false], // hour has too many digits ['2010-01-01T32:00:00.0000+01:01', false], // hour is too large // Validate minutes ['2010-01-01T01:00:00.0000+01:01', true], // minute has two digits ['2010-01-01T01:-00:00.0000+01:01', false], // minute must be positive ['2010-01-01T01::00.0000+01:01', false], // minute has too few digits ['2010-01-01T01:0:00.0000+01:01', false], // minute has too few digits ['2010-01-01T01:100:00.0000+01:01', false], // minute has too many digits ['2010-01-01T01:60:00.0000+01:01', false], // minute is too large // Validate seconds ['2010-01-01T01:00:00.0000+01:01', true], // second has two digits ['2010-01-01T01:00:-00.0000+01:01', false], // second must be positive ['2010-01-01T01:00:.0000+01:01', false], // second has too few digits ['2010-01-01T01:00:0.0000+01:01', false], // second has too few digits ['2010-01-01T01:00:100.0000+01:01', false], // second has too many digits ['2010-01-01T01:00:60.0000+01:01', false], // second is too large // Validate milliseconds ['2010-01-01T01:00:00+01:01', false], // millisecond must be specified ['2010-01-01T01:00:00.-0000+01:01', false], // millisecond must be positive ['2010-01-01T01:00:00:0000+01:01', false], // millisecond must use period seperator ['2010-01-01T01:00:00.+01:01', false], // millisecond has too few digits // Validate timezone ['2010-06-15T00:00:00.0000', false], // timezone must be specified // Validate timezone offset ['2010-06-15T00:00:00.0000+01:01', true], // timezone offset can be positive hours and minutes ['2010-06-15T00:00:00.0000-01:01', true], // timezone offset can be negative hours and minutes ['2010-06-15T00:00:00.0000~01:01', false], // timezone has postive/negative indicator ['2010-06-15T00:00:00.000001:01', false], // timezone has postive/negative indicator ['2010-06-15T00:00:00.0000+00:01Z', false], // timezone invalid trailing characters ['2010-06-15T00:00:00.0000+00:01 ', false], // timezone invalid trailing characters // Validate timezone hour offset ['2010-06-15T00:00:00.0000+:01', false], // timezone hour offset has too few digits ['2010-06-15T00:00:00.0000+0:01', false], // timezone hour offset has too few digits ['2010-06-15T00:00:00.0000+211:01', false], // timezone hour offset too many digits ['2010-06-15T00:00:00.0000+31:01', false], // timezone hour offset value too large // Validate timezone minute offset ['2010-06-15T00:00:00.0000+00:-01', false], // timezone minute offset must be positive ['2010-06-15T00:00:00.0000+00.01', false], // timezone minute offset must use colon seperator ['2010-06-15T00:00:00.0000+0101', false], // timezone minute offset must use colon seperator ['2010-06-15T00:00:00.0000+010', false], // timezone minute offset must use colon seperator ['2010-06-15T00:00:00.0000+00', false], // timezone minute offset has too few digits ['2010-06-15T00:00:00.0000+00:', false], // timezone minute offset has too few digits ['2010-06-15T00:00:00.0000+00:0', false], // timezone minute offset has too few digits ['2010-06-15T00:00:00.0000+00:211', false], // timezone minute offset has too many digits ['2010-06-15T00:00:00.0000+01010', false], // timezone minute offset has too many digits ['2010-06-15T00:00:00.0000+00:61', false], // timezone minute offset is too large // Validate timezone UTC ['2010-06-15T00:00:00.0000Z', true], // UTC timezone can be indicated with Z ['2010-06-15T00:00:00.0000K', false], // UTC timezone indicator is invalid ['2010-06-15T00:00:00.0000 Z', false], // UTC timezone indicator has extra space ['2010-06-15T00:00:00.0000ZZ', false], // UTC timezone indicator invalid trailing characters ['2010-06-15T00:00:00.0000Z ', false] // UTC timezone indicator invalid trailing characters ]; they('should validate date: $prop', dates, function(item) { var date = item[0]; var valid = item[1]; /* global ISO_DATE_REGEXP: false */ expect(ISO_DATE_REGEXP.test(date)).toBe(valid); }); }); }); ['month', 'week', 'time', 'date', 'datetime-local'].forEach(function(inputType) { if (jqLite('<input type="' + inputType + '">').prop('type') !== inputType) { return; } describe(inputType, function() { they('should re-validate and dirty when partially editing the input value ($prop event)', ['keydown', 'wheel', 'mousedown'], function(validationEvent) { var mockValidity = {valid: true, badInput: false}; var inputElm = helper.compileInput('<input type="' + inputType + '" ng-model="val" name="alias" />', mockValidity); expect(inputElm).toBeValid(); expect($rootScope.form.alias.$pristine).toBeTruthy(); inputElm.triggerHandler({type: validationEvent}); mockValidity.valid = false; mockValidity.badInput = true; $browser.defer.flush(); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$pristine).toBeFalsy(); } ); they('should do nothing when $prop event fired but validity does not change', ['keydown', 'wheel', 'mousedown'], function(validationEvent) { var mockValidity = {valid: true, badInput: false}; var inputElm = helper.compileInput('<input type="' + inputType + '" ng-model="val" name="alias" />', mockValidity); expect(inputElm).toBeValid(); expect($rootScope.form.alias.$pristine).toBeTruthy(); inputElm.triggerHandler({type: validationEvent}); $browser.defer.flush(); expect(inputElm).toBeValid(); expect($rootScope.form.alias.$pristine).toBeTruthy(); } ); they('should re-validate dirty when already $invalid and partially editing the input value ($prop event)', ['keydown', 'wheel', 'mousedown'], function(validationEvent) { var mockValidity = {valid: false, valueMissing: true, badInput: false}; var inputElm = helper.compileInput('<input type="' + inputType + '" required ng-model="val" name="alias" />', mockValidity); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$pristine).toBeTruthy(); inputElm.triggerHandler({type: validationEvent}); mockValidity.valid = false; mockValidity.valueMissing = true; mockValidity.badInput = true; $browser.defer.flush(); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$pristine).toBeFalsy(); } ); they('should do nothing when already $invalid and $prop event fired but validity does not change', ['keydown', 'wheel', 'mousedown'], function(validationEvent) { var mockValidity = {valid: false, valueMissing: true, badInput: false}; var inputElm = helper.compileInput('<input type="' + inputType + '" required ng-model="val" name="alias" />', mockValidity); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$pristine).toBeTruthy(); inputElm.triggerHandler({type: validationEvent}); $browser.defer.flush(); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$pristine).toBeTruthy(); } ); }); }); describe('number', function() { it('should reset the model if view is invalid', function() { var inputElm = helper.compileInput('<input type="number" ng-model="age"/>'); $rootScope.$apply('age = 123'); expect(inputElm.val()).toBe('123'); // to allow non-number values, we have to change type so that // the browser which have number validation will not interfere with // this test. inputElm[0].setAttribute('type', 'text'); helper.changeInputValueTo('123X'); expect(inputElm.val()).toBe('123X'); expect($rootScope.age).toBeUndefined(); expect(inputElm).toBeInvalid(); }); it('should render as blank if null', function() { var inputElm = helper.compileInput('<input type="number" ng-model="age" />'); $rootScope.$apply('age = null'); expect($rootScope.age).toBeNull(); expect(inputElm.val()).toEqual(''); }); it('should come up blank when no value specified', function() { var inputElm = helper.compileInput('<input type="number" ng-model="age" />'); expect(inputElm.val()).toBe(''); $rootScope.$apply('age = null'); expect($rootScope.age).toBeNull(); expect(inputElm.val()).toBe(''); }); it('should parse empty string to null', function() { var inputElm = helper.compileInput('<input type="number" ng-model="age" />'); $rootScope.$apply('age = 10'); helper.changeInputValueTo(''); expect($rootScope.age).toBeNull(); expect(inputElm).toBeValid(); }); it('should only invalidate the model if suffering from bad input when the data is parsed', function() { var inputElm = helper.compileInput('<input type="number" ng-model="age" />', { valid: false, badInput: true }); expect($rootScope.age).toBeUndefined(); expect(inputElm).toBeValid(); helper.changeInputValueTo('this-will-fail-because-of-the-badInput-flag'); expect($rootScope.age).toBeUndefined(); expect(inputElm).toBeInvalid(); }); it('should validate number if transition from bad input to empty string', function() { var validity = { valid: false, badInput: true }; var inputElm = helper.compileInput('<input type="number" ng-model="age" />', validity); helper.changeInputValueTo('10a'); validity.badInput = false; validity.valid = true; helper.changeInputValueTo(''); expect($rootScope.age).toBeNull(); expect(inputElm).toBeValid(); }); it('should validate with undefined viewValue when $validate() called', function() { var inputElm = helper.compileInput('<input type="number" name="alias" ng-model="value" />'); $rootScope.form.alias.$validate(); expect(inputElm).toBeValid(); expect($rootScope.form.alias.$error.number).toBeUndefined(); }); it('should throw if the model value is not a number', function() { expect(function() { $rootScope.value = 'one'; var inputElm = helper.compileInput('<input type="number" ng-model="value" />'); }).toThrowMinErr('ngModel', 'numfmt', "Expected `one` to be a number"); }); it('should parse exponential notation', function() { var inputElm = helper.compileInput('<input type="number" name="alias" ng-model="value" />'); // #.###e+## $rootScope.form.alias.$setViewValue("1.23214124123412412e+26"); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(1.23214124123412412e+26); // #.###e## $rootScope.form.alias.$setViewValue("1.23214124123412412e26"); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(1.23214124123412412e26); // #.###e-## $rootScope.form.alias.$setViewValue("1.23214124123412412e-26"); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(1.23214124123412412e-26); // ####e+## $rootScope.form.alias.$setViewValue("123214124123412412e+26"); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(123214124123412412e26); // ####e## $rootScope.form.alias.$setViewValue("123214124123412412e26"); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(123214124123412412e26); // ####e-## $rootScope.form.alias.$setViewValue("123214124123412412e-26"); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(123214124123412412e-26); // #.###E+## $rootScope.form.alias.$setViewValue("1.23214124123412412E+26"); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(1.23214124123412412e+26); // #.###E## $rootScope.form.alias.$setViewValue("1.23214124123412412E26"); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(1.23214124123412412e26); // #.###E-## $rootScope.form.alias.$setViewValue("1.23214124123412412E-26"); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(1.23214124123412412e-26); // ####E+## $rootScope.form.alias.$setViewValue("123214124123412412E+26"); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(123214124123412412e26); // ####E## $rootScope.form.alias.$setViewValue("123214124123412412E26"); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(123214124123412412e26); // ####E-## $rootScope.form.alias.$setViewValue("123214124123412412E-26"); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(123214124123412412e-26); }); describe('min', function() { it('should validate', function() { var inputElm = helper.compileInput('<input type="number" ng-model="value" name="alias" min="10" />'); helper.changeInputValueTo('1'); expect(inputElm).toBeInvalid(); expect($rootScope.value).toBeFalsy(); expect($rootScope.form.alias.$error.min).toBeTruthy(); helper.changeInputValueTo('100'); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(100); expect($rootScope.form.alias.$error.min).toBeFalsy(); }); it('should validate even if min value changes on-the-fly', function() { $rootScope.min = undefined; var inputElm = helper.compileInput('<input type="number" ng-model="value" name="alias" min="{{min}}" />'); expect(inputElm).toBeValid(); helper.changeInputValueTo('15'); expect(inputElm).toBeValid(); $rootScope.min = 10; $rootScope.$digest(); expect(inputElm).toBeValid(); $rootScope.min = 20; $rootScope.$digest(); expect(inputElm).toBeInvalid(); $rootScope.min = null; $rootScope.$digest(); expect(inputElm).toBeValid(); $rootScope.min = '20'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); $rootScope.min = 'abc'; $rootScope.$digest(); expect(inputElm).toBeValid(); }); }); describe('ngMin', function() { it('should validate', function() { var inputElm = helper.compileInput('<input type="number" ng-model="value" name="alias" ng-min="50" />'); helper.changeInputValueTo('1'); expect(inputElm).toBeInvalid(); expect($rootScope.value).toBeFalsy(); expect($rootScope.form.alias.$error.min).toBeTruthy(); helper.changeInputValueTo('100'); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(100); expect($rootScope.form.alias.$error.min).toBeFalsy(); }); it('should validate even if the ngMin value changes on-the-fly', function() { $rootScope.min = undefined; var inputElm = helper.compileInput('<input type="number" ng-model="value" name="alias" ng-min="min" />'); expect(inputElm).toBeValid(); helper.changeInputValueTo('15'); expect(inputElm).toBeValid(); $rootScope.min = 10; $rootScope.$digest(); expect(inputElm).toBeValid(); $rootScope.min = 20; $rootScope.$digest(); expect(inputElm).toBeInvalid(); $rootScope.min = null; $rootScope.$digest(); expect(inputElm).toBeValid(); $rootScope.min = '20'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); $rootScope.min = 'abc'; $rootScope.$digest(); expect(inputElm).toBeValid(); }); }); describe('max', function() { it('should validate', function() { var inputElm = helper.compileInput('<input type="number" ng-model="value" name="alias" max="10" />'); helper.changeInputValueTo('20'); expect(inputElm).toBeInvalid(); expect($rootScope.value).toBeUndefined(); expect($rootScope.form.alias.$error.max).toBeTruthy(); helper.changeInputValueTo('0'); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(0); expect($rootScope.form.alias.$error.max).toBeFalsy(); }); it('should validate even if max value changes on-the-fly', function() { $rootScope.max = undefined; var inputElm = helper.compileInput('<input type="number" ng-model="value" name="alias" max="{{max}}" />'); expect(inputElm).toBeValid(); helper.changeInputValueTo('5'); expect(inputElm).toBeValid(); $rootScope.max = 10; $rootScope.$digest(); expect(inputElm).toBeValid(); $rootScope.max = 0; $rootScope.$digest(); expect(inputElm).toBeInvalid(); $rootScope.max = null; $rootScope.$digest(); expect(inputElm).toBeValid(); $rootScope.max = '4'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); $rootScope.max = 'abc'; $rootScope.$digest(); expect(inputElm).toBeValid(); }); }); describe('ngMax', function() { it('should validate', function() { var inputElm = helper.compileInput('<input type="number" ng-model="value" name="alias" ng-max="5" />'); helper.changeInputValueTo('20'); expect(inputElm).toBeInvalid(); expect($rootScope.value).toBeUndefined(); expect($rootScope.form.alias.$error.max).toBeTruthy(); helper.changeInputValueTo('0'); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(0); expect($rootScope.form.alias.$error.max).toBeFalsy(); }); it('should validate even if the ngMax value changes on-the-fly', function() { $rootScope.max = undefined; var inputElm = helper.compileInput('<input type="number" ng-model="value" name="alias" ng-max="max" />'); expect(inputElm).toBeValid(); helper.changeInputValueTo('5'); expect(inputElm).toBeValid(); $rootScope.max = 10; $rootScope.$digest(); expect(inputElm).toBeValid(); $rootScope.max = 0; $rootScope.$digest(); expect(inputElm).toBeInvalid(); $rootScope.max = null; $rootScope.$digest(); expect(inputElm).toBeValid(); $rootScope.max = '4'; $rootScope.$digest(); expect(inputElm).toBeInvalid(); $rootScope.max = 'abc'; $rootScope.$digest(); expect(inputElm).toBeValid(); }); }); describe('required', function() { it('should be valid even if value is 0', function() { var inputElm = helper.compileInput('<input type="number" ng-model="value" name="alias" required />'); helper.changeInputValueTo('0'); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(0); expect($rootScope.form.alias.$error.required).toBeFalsy(); }); it('should be valid even if value 0 is set from model', function() { var inputElm = helper.compileInput('<input type="number" ng-model="value" name="alias" required />'); $rootScope.$apply('value = 0'); expect(inputElm).toBeValid(); expect(inputElm.val()).toBe('0'); expect($rootScope.form.alias.$error.required).toBeFalsy(); }); it('should register required on non boolean elements', function() { var inputElm = helper.compileInput('<div ng-model="value" name="alias" required>'); $rootScope.$apply("value = ''"); expect(inputElm).toBeInvalid(); expect($rootScope.form.alias.$error.required).toBeTruthy(); }); it('should not invalidate number if ng-required=false and viewValue has not been committed', function() { var inputElm = helper.compileInput('<input type="number" ng-model="value" name="alias" ng-required="required">'); $rootScope.$apply("required = false"); expect(inputElm).toBeValid(); }); }); describe('ngRequired', function() { describe('when the ngRequired expression initially evaluates to true', function() { it('should be valid even if value is 0', function() { var inputElm = helper.compileInput('<input type="number" ng-model="value" name="numberInput" ng-required="true" />'); helper.changeInputValueTo('0'); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(0); expect($rootScope.form.numberInput.$error.required).toBeFalsy(); }); it('should be valid even if value 0 is set from model', function() { var inputElm = helper.compileInput('<input type="number" ng-model="value" name="numberInput" ng-required="true" />'); $rootScope.$apply('value = 0'); expect(inputElm).toBeValid(); expect(inputElm.val()).toBe('0'); expect($rootScope.form.numberInput.$error.required).toBeFalsy(); }); it('should register required on non boolean elements', function() { var inputElm = helper.compileInput('<div ng-model="value" name="numberInput" ng-required="true">'); $rootScope.$apply("value = ''"); expect(inputElm).toBeInvalid(); expect($rootScope.form.numberInput.$error.required).toBeTruthy(); }); it('should change from invalid to valid when the value is empty and the ngRequired expression changes to false', function() { var inputElm = helper.compileInput('<input type="number" ng-model="value" name="numberInput" ng-required="ngRequiredExpr" />'); $rootScope.$apply('ngRequiredExpr = true'); expect(inputElm).toBeInvalid(); expect($rootScope.value).toBeUndefined(); expect($rootScope.form.numberInput.$error.required).toBeTruthy(); $rootScope.$apply('ngRequiredExpr = false'); expect(inputElm).toBeValid(); expect($rootScope.value).toBeUndefined(); expect($rootScope.form.numberInput.$error.required).toBeFalsy(); }); }); describe('when the ngRequired expression initially evaluates to false', function() { it('should be valid even if value is empty', function() { var inputElm = helper.compileInput('<input type="number" ng-model="value" name="numberInput" ng-required="false" />'); expect(inputElm).toBeValid(); expect($rootScope.value).toBeUndefined(); expect($rootScope.form.numberInput.$error.required).toBeFalsy(); expect($rootScope.form.numberInput.$error.number).toBeFalsy(); }); it('should be valid if value is non-empty', function() { var inputElm = helper.compileInput('<input type="number" ng-model="value" name="numberInput" ng-required="false" />'); helper.changeInputValueTo('42'); expect(inputElm).toBeValid(); expect($rootScope.value).toBe(42); expect($rootScope.form.numberInput.$error.required).toBeFalsy(); }); it('should not register required on non boolean elements', function() { var inputElm = helper.compileInput('<div ng-model="value" name="numberInput" ng-required="false">'); $rootScope.$apply("value = ''"); expect(inputElm).toBeValid(); expect($rootScope.form.numberInput.$error.required).toBeFalsy(); }); it('should change from valid to invalid when the value is empty and the ngRequired expression changes to true', function() { var inputElm = helper.compileInput('<input type="number" ng-model="value" name="numberInput" ng-required="ngRequiredExpr" />'); $rootScope.$apply('ngRequiredExpr = false'); expect(inputElm).toBeValid(); expect($rootScope.value).toBeUndefined(); expect($rootScope.form.numberInput.$error.required).toBeFalsy(); $rootScope.$apply('ngRequiredExpr = true'); expect(inputElm).toBeInvalid(); expect($rootScope.value).toBeUndefined(); expect($rootScope.form.numberInput.$error.required).toBeTruthy(); }); }); }); describe('minlength', function() { it('should invalidate values that are shorter than the given minlength', function() { var inputElm = helper.compileInput('<input type="number" ng-model="value" ng-minlength="3" />'); helper.changeInputValueTo('12'); expect(inputElm).toBeInvalid(); helper.changeInputValueTo('123'); expect(inputElm).toBeValid(); }); it('should listen on ng-minlength when minlength is observed', function() { var value = 0; var inputElm = helper.compileInput('<input type="number" ng-model="value" ng-minlength="min" attr-capture />'); helper.attrs.$observe('minlength', function(v) { value = toInt(helper.attrs.minlength); }); $rootScope.$apply(function() { $rootScope.min = 5; }); expect(value).toBe(5); }); it('should observe the standard minlength attribute and register it as a validator on the model', function() { var inputElm = helper.compileInput('<input type="number" name="input" ng-model="value" minlength="{{ min }}" />'); $rootScope.$apply(function() { $rootScope.min = 10; }); helper.changeInputValueTo('12345'); expect(inputElm).toBeInvalid(); expect($rootScope.form.input.$error.minlength).toBe(true); $rootScope.$apply(function() { $rootScope.min = 5; }); expect(inputElm).toBeValid(); expect($rootScope.form.input.$error.minlength).not.toBe(true); }); }); describe('maxlength', function() { it('should invalidate values that are longer than the given maxlength', function() { var inputElm = helper.compileInput('<input type="number" ng-model="value" ng-maxlength="5" />'); helper.changeInputValueTo('12345678'); expect(inputElm).toBeInvalid(); helper.changeInputValueTo('123'); expect(inputElm).toBeValid(); }); it('should listen on ng-maxlength when maxlength is observed', function() { var value = 0; var inputElm = helper.compileInput('<input type="number" ng-model="value" ng-maxlength="max" attr-capture />'); helper.attrs.$observe('maxlength', function(v) { value = toInt(helper.attrs.maxlength); }); $rootScope.$apply(function() { $rootScope.max = 10; }); expect(value).toBe(10); }); it('should observe the standard maxlength attribute and register it as a validator on the model', function() { var inputElm = helper.compileInput('<input type="number" name="input" ng-model="value" maxlength="{{ max }}" />'); $rootScope.$apply(function() { $rootScope.max = 1; }); helper.changeInputValueTo('12345'); expect(inputElm).toBeInvalid(); expect($rootScope.form.input.$error.maxlength).toBe(true); $rootScope.$apply(function() { $rootScope.max = 6; }); expect(inputElm).toBeValid(); expect($rootScope.form.input.$error.maxlength).not.toBe(true); }); }); }); describe('email', function() { it('should validate e-mail', function() { var inputElm = helper.compileInput('<input type="email" ng-model="email" name="alias" />'); var widget = $rootScope.form.alias; helper.changeInputValueTo('[email protected]'); expect($rootScope.email).toBe('[email protected]'); expect(inputElm).toBeValid(); expect(widget.$error.email).toBeFalsy(); helper.changeInputValueTo('invalid@'); expect($rootScope.email).toBeUndefined(); expect(inputElm).toBeInvalid(); expect(widget.$error.email).toBeTruthy(); }); describe('EMAIL_REGEXP', function() { /* global EMAIL_REGEXP: false */ it('should validate email', function() { expect(EMAIL_REGEXP.test('[email protected]')).toBe(true); expect(EMAIL_REGEXP.test('[email protected]')).toBe(true); expect(EMAIL_REGEXP.test('[email protected]')).toBe(true); expect(EMAIL_REGEXP.test('[email protected]')).toBe(false); expect(EMAIL_REGEXP.test('[email protected]')).toBe(false); expect(EMAIL_REGEXP.test('[email protected]')).toBe(false); expect(EMAIL_REGEXP.test('[email protected]')).toBe(true); expect(EMAIL_REGEXP.test('a@b')).toBe(true); }); }); }); describe('url', function() { it('should validate url', function() { var inputElm = helper.compileInput('<input type="url" ng-model="url" name="alias" />'); var widget = $rootScope.form.alias; helper.changeInputValueTo('http://www.something.com'); expect($rootScope.url).toBe('http://www.something.com'); expect(inputElm).toBeValid(); expect(widget.$error.url).toBeFalsy(); helper.changeInputValueTo('invalid.com'); expect($rootScope.url).toBeUndefined(); expect(inputElm).toBeInvalid(); expect(widget.$error.url).toBeTruthy(); }); describe('URL_REGEXP', function() { // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987) // Note: We are being more lenient, because browsers are too. var urls = [ ['scheme://hostname', true], ['scheme://username:[email protected]:7678/pa/t.h?q=u&e=r&y#fragment', true], // Validating `scheme` ['://example.com', false], ['0scheme://example.com', false], ['.scheme://example.com', false], ['+scheme://example.com', false], ['-scheme://example.com', false], ['_scheme://example.com', false], ['scheme0://example.com', true], ['scheme.://example.com', true], ['scheme+://example.com', true], ['scheme-://example.com', true], ['scheme_://example.com', false], // Vaidating `:` and `/` after `scheme` ['scheme//example.com', false], ['scheme:example.com', true], ['scheme:/example.com', true], ['scheme:///example.com', true], // Validating `username` and `password` ['scheme://@example.com', true], ['scheme://[email protected]', true], ['scheme://[email protected]', true], ['scheme://u#s$e%r^n&a*m;[email protected]', true], ['scheme://:[email protected]', true], ['scheme://username:[email protected]', true], ['scheme://username:pass:[email protected]', true], ['scheme://username:[email protected]', true], ['scheme://username:p#a$s%s^w&o*r;[email protected]', true], // Validating `hostname` ['scheme:', false], // Chrome, FF: true ['scheme://', false], // Chrome, FF: true ['scheme:// example.com:', false], // Chrome, FF: true ['scheme://example com:', false], // Chrome, FF: true ['scheme://:', false], // Chrome, FF: true ['scheme://?', false], // Chrome, FF: true ['scheme://#', false], // Chrome, FF: true ['scheme://username:password@:', false], // Chrome, FF: true ['scheme://username:password@/', false], // Chrome, FF: true ['scheme://username:password@?', false], // Chrome, FF: true ['scheme://username:password@#', false], // Chrome, FF: true ['scheme://host.name', true], ['scheme://123.456.789.10', true], ['scheme://[1234:0000:0000:5678:9abc:0000:0000:def]', true], ['scheme://[1234:0000:0000:5678:9abc:0000:0000:def]:7678', true], ['scheme://[1234:0:0:5678:9abc:0:0:def]', true], ['scheme://[1234::5678:9abc::def]', true], ['scheme://~`!@$%^&*-_=+|\\;\'",.()[]{}<>', true], // Validating `port` ['scheme://example.com/no-port', true], ['scheme://example.com:7678', true], ['scheme://example.com:76T8', false], // Chrome, FF: true ['scheme://example.com:port', false], // Chrome, FF: true // Validating `path` ['scheme://example.com/', true], ['scheme://example.com/path', true], ['scheme://example.com/path/~`!@$%^&*-_=+|\\;:\'",./()[]{}<>', true], // Validating `query` ['scheme://example.com?query', true], ['scheme://example.com/?query', true], ['scheme://example.com/path?query', true], ['scheme://example.com/path?~`!@$%^&*-_=+|\\;:\'",.?/()[]{}<>', true], // Validating `fragment` ['scheme://example.com#fragment', true], ['scheme://example.com/#fragment', true], ['scheme://example.com/path#fragment', true], ['scheme://example.com/path/#fragment', true], ['scheme://example.com/path?query#fragment', true], ['scheme://example.com/path?query#~`!@#$%^&*-_=+|\\;:\'",.?/()[]{}<>', true], // Validating miscellaneous ['scheme://☺.✪.⌘.➡/䨹', true], ['scheme://مثال.إختبار', true], ['scheme://例子.测试', true], ['scheme://उदाहरण.परीक्षा', true], // Legacy tests ['http://server:123/path', true], ['https://server:123/path', true], ['file:///home/user', true], ['mailto:[email protected]?subject=Foo', true], ['r2-d2.c3-p0://localhost/foo', true], ['abc:/foo', true], ['http://example.com/path;path', true], ['http://example.com/[]$\'()*,~)', true], ['http:', false], // FF: true ['[email protected]', false], ['a_B.c', false], ['0scheme://example.com', false], ['http://example.com:9999/``', true] ]; they('should validate url: $prop', urls, function(item) { var url = item[0]; var valid = item[1]; /* global URL_REGEXP: false */ expect(URL_REGEXP.test(url)).toBe(valid); }); }); }); describe('radio', function() { it('should update the model', function() { var inputElm = helper.compileInput( '<input type="radio" ng-model="color" value="white" />' + '<input type="radio" ng-model="color" value="red" />' + '<input type="radio" ng-model="color" value="blue" />'); $rootScope.$apply("color = 'white'"); expect(inputElm[0].checked).toBe(true); expect(inputElm[1].checked).toBe(false); expect(inputElm[2].checked).toBe(false); $rootScope.$apply("color = 'red'"); expect(inputElm[0].checked).toBe(false); expect(inputElm[1].checked).toBe(true); expect(inputElm[2].checked).toBe(false); browserTrigger(inputElm[2], 'click'); expect($rootScope.color).toBe('blue'); }); // We generally use strict comparison. This tests behavior we cannot change without a BC it('should use non-strict comparison the evaluate checked-ness', function() { var inputElm = helper.compileInput( '<input type="radio" ng-model="model" value="0" />'); $rootScope.$apply("model = '0'"); expect(inputElm[0].checked).toBe(true); $rootScope.$apply("model = 0"); expect(inputElm[0].checked).toBe(true); }); it('should allow {{expr}} as value', function() { $rootScope.some = 11; var inputElm = helper.compileInput( '<input type="radio" ng-model="value" value="{{some}}" />' + '<input type="radio" ng-model="value" value="{{other}}" />'); $rootScope.$apply(function() { $rootScope.value = 'blue'; $rootScope.some = 'blue'; $rootScope.other = 'red'; }); expect(inputElm[0].checked).toBe(true); expect(inputElm[1].checked).toBe(false); browserTrigger(inputElm[1], 'click'); expect($rootScope.value).toBe('red'); $rootScope.$apply("other = 'non-red'"); expect(inputElm[0].checked).toBe(false); expect(inputElm[1].checked).toBe(false); }); }); describe('checkbox', function() { it('should ignore checkbox without ngModel directive', function() { var inputElm = helper.compileInput('<input type="checkbox" name="whatever" required />'); helper.changeInputValueTo(''); expect(inputElm.hasClass('ng-valid')).toBe(false); expect(inputElm.hasClass('ng-invalid')).toBe(false); expect(inputElm.hasClass('ng-pristine')).toBe(false); expect(inputElm.hasClass('ng-dirty')).toBe(false); }); it('should format booleans', function() { var inputElm = helper.compileInput('<input type="checkbox" ng-model="name" />'); $rootScope.$apply("name = false"); expect(inputElm[0].checked).toBe(false); $rootScope.$apply("name = true"); expect(inputElm[0].checked).toBe(true); }); it('should support type="checkbox" with non-standard capitalization', function() { var inputElm = helper.compileInput('<input type="checkBox" ng-model="checkbox" />'); browserTrigger(inputElm, 'click'); expect($rootScope.checkbox).toBe(true); browserTrigger(inputElm, 'click'); expect($rootScope.checkbox).toBe(false); }); it('should allow custom enumeration', function() { var inputElm = helper.compileInput('<input type="checkbox" ng-model="name" ng-true-value="\'y\'" ' + 'ng-false-value="\'n\'">'); $rootScope.$apply("name = 'y'"); expect(inputElm[0].checked).toBe(true); $rootScope.$apply("name = 'n'"); expect(inputElm[0].checked).toBe(false); $rootScope.$apply("name = 'something else'"); expect(inputElm[0].checked).toBe(false); browserTrigger(inputElm, 'click'); expect($rootScope.name).toEqual('y'); browserTrigger(inputElm, 'click'); expect($rootScope.name).toEqual('n'); }); it('should throw if ngTrueValue is present and not a constant expression', function() { expect(function() { var inputElm = helper.compileInput('<input type="checkbox" ng-model="value" ng-true-value="yes" />'); }).toThrowMinErr('ngModel', 'constexpr', "Expected constant expression for `ngTrueValue`, but saw `yes`."); }); it('should throw if ngFalseValue is present and not a constant expression', function() { expect(function() { var inputElm = helper.compileInput('<input type="checkbox" ng-model="value" ng-false-value="no" />'); }).toThrowMinErr('ngModel', 'constexpr', "Expected constant expression for `ngFalseValue`, but saw `no`."); }); it('should not throw if ngTrueValue or ngFalseValue are not present', function() { expect(function() { var inputElm = helper.compileInput('<input type="checkbox" ng-model="value" />'); }).not.toThrow(); }); it('should be required if false', function() { var inputElm = helper.compileInput('<input type="checkbox" ng-model="value" required />'); browserTrigger(inputElm, 'click'); expect(inputElm[0].checked).toBe(true); expect(inputElm).toBeValid(); browserTrigger(inputElm, 'click'); expect(inputElm[0].checked).toBe(false); expect(inputElm).toBeInvalid(); }); it('should pass validation for "required" when trueValue is a string', function() { var inputElm = helper.compileInput('<input type="checkbox" required name="cb"' + 'ng-model="value" ng-true-value="\'yes\'" />'); expect(inputElm).toBeInvalid(); expect($rootScope.form.cb.$error.required).toBe(true); browserTrigger(inputElm, 'click'); expect(inputElm[0].checked).toBe(true); expect(inputElm).toBeValid(); expect($rootScope.form.cb.$error.required).toBeUndefined(); }); }); describe('textarea', function() { it("should process textarea", function() { var inputElm = helper.compileInput('<textarea ng-model="name"></textarea>'); $rootScope.$apply("name = 'Adam'"); expect(inputElm.val()).toEqual('Adam'); helper.changeInputValueTo('Shyam'); expect($rootScope.name).toEqual('Shyam'); helper.changeInputValueTo('Kai'); expect($rootScope.name).toEqual('Kai'); }); it('should ignore textarea without ngModel directive', function() { var inputElm = helper.compileInput('<textarea name="whatever" required></textarea>'); helper.changeInputValueTo(''); expect(inputElm.hasClass('ng-valid')).toBe(false); expect(inputElm.hasClass('ng-invalid')).toBe(false); expect(inputElm.hasClass('ng-pristine')).toBe(false); expect(inputElm.hasClass('ng-dirty')).toBe(false); }); }); describe('ngValue', function() { it('should update the dom "value" property and attribute', function() { var inputElm = helper.compileInput('<input type="submit" ng-value="value">'); $rootScope.$apply("value = 'something'"); expect(inputElm[0].value).toBe('something'); expect(inputElm[0].getAttribute('value')).toBe('something'); }); it('should evaluate and set constant expressions', function() { var inputElm = helper.compileInput('<input type="radio" ng-model="selected" ng-value="true">' + '<input type="radio" ng-model="selected" ng-value="false">' + '<input type="radio" ng-model="selected" ng-value="1">'); browserTrigger(inputElm[0], 'click'); expect($rootScope.selected).toBe(true); browserTrigger(inputElm[1], 'click'); expect($rootScope.selected).toBe(false); browserTrigger(inputElm[2], 'click'); expect($rootScope.selected).toBe(1); }); it('should watch the expression', function() { var inputElm = helper.compileInput('<input type="radio" ng-model="selected" ng-value="value">'); $rootScope.$apply(function() { $rootScope.selected = $rootScope.value = {some: 'object'}; }); expect(inputElm[0].checked).toBe(true); $rootScope.$apply(function() { $rootScope.value = {some: 'other'}; }); expect(inputElm[0].checked).toBe(false); browserTrigger(inputElm, 'click'); expect($rootScope.selected).toBe($rootScope.value); }); it('should work inside ngRepeat', function() { helper.compileInput( '<input type="radio" ng-repeat="i in items" ng-model="$parent.selected" ng-value="i.id">'); $rootScope.$apply(function() { $rootScope.items = [{id: 1}, {id: 2}]; $rootScope.selected = 1; }); var inputElms = helper.formElm.find('input'); expect(inputElms[0].checked).toBe(true); expect(inputElms[1].checked).toBe(false); browserTrigger(inputElms.eq(1), 'click'); expect($rootScope.selected).toBe(2); }); it('should work inside ngRepeat with primitive values', function() { helper.compileInput( '<div ng-repeat="i in items">' + '<input type="radio" name="sel_{{i.id}}" ng-model="i.selected" ng-value="true">' + '<input type="radio" name="sel_{{i.id}}" ng-model="i.selected" ng-value="false">' + '</div>'); $rootScope.$apply(function() { $rootScope.items = [{id: 1, selected: true}, {id: 2, selected: false}]; }); var inputElms = helper.formElm.find('input'); expect(inputElms[0].checked).toBe(true); expect(inputElms[1].checked).toBe(false); expect(inputElms[2].checked).toBe(false); expect(inputElms[3].checked).toBe(true); browserTrigger(inputElms.eq(1), 'click'); expect($rootScope.items[0].selected).toBe(false); }); it('should work inside ngRepeat without name attribute', function() { helper.compileInput( '<div ng-repeat="i in items">' + '<input type="radio" ng-model="i.selected" ng-value="true">' + '<input type="radio" ng-model="i.selected" ng-value="false">' + '</div>'); $rootScope.$apply(function() { $rootScope.items = [{id: 1, selected: true}, {id: 2, selected: false}]; }); var inputElms = helper.formElm.find('input'); expect(inputElms[0].checked).toBe(true); expect(inputElms[1].checked).toBe(false); expect(inputElms[2].checked).toBe(false); expect(inputElms[3].checked).toBe(true); browserTrigger(inputElms.eq(1), 'click'); expect($rootScope.items[0].selected).toBe(false); }); }); describe('password', function() { // Under no circumstances should input[type=password] trim inputs it('should not trim if ngTrim is unspecified', function() { var inputElm = helper.compileInput('<input type="password" ng-model="password">'); helper.changeInputValueTo(' - - untrimmed - - '); expect($rootScope.password.length).toBe(' - - untrimmed - - '.length); }); it('should not trim if ngTrim !== false', function() { var inputElm = helper.compileInput('<input type="password" ng-model="password" ng-trim="true">'); helper.changeInputValueTo(' - - untrimmed - - '); expect($rootScope.password.length).toBe(' - - untrimmed - - '.length); dealoc(inputElm); }); it('should not trim if ngTrim === false', function() { var inputElm = helper.compileInput('<input type="password" ng-model="password" ng-trim="false">'); helper.changeInputValueTo(' - - untrimmed - - '); expect($rootScope.password.length).toBe(' - - untrimmed - - '.length); dealoc(inputElm); }); }); });
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import all from 'prop-types-extra/lib/all'; import Button from './Button'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { vertical: PropTypes.bool, justified: PropTypes.bool, /** * Display block buttons; only useful when used with the "vertical" prop. * @type {bool} */ block: all(PropTypes.bool, function (_ref) { var block = _ref.block, vertical = _ref.vertical; return block && !vertical ? new Error('`block` requires `vertical` to be set to have any effect') : null; }) }; var defaultProps = { block: false, justified: false, vertical: false }; var ButtonGroup = function (_React$Component) { _inherits(ButtonGroup, _React$Component); function ButtonGroup() { _classCallCheck(this, ButtonGroup); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } ButtonGroup.prototype.render = function render() { var _extends2; var _props = this.props, block = _props.block, justified = _props.justified, vertical = _props.vertical, className = _props.className, props = _objectWithoutProperties(_props, ['block', 'justified', 'vertical', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps)] = !vertical, _extends2[prefix(bsProps, 'vertical')] = vertical, _extends2[prefix(bsProps, 'justified')] = justified, _extends2[prefix(Button.defaultProps, 'block')] = block, _extends2)); return React.createElement('div', _extends({}, elementProps, { className: classNames(className, classes) })); }; return ButtonGroup; }(React.Component); ButtonGroup.propTypes = propTypes; ButtonGroup.defaultProps = defaultProps; export default bsClass('btn-group', ButtonGroup);
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ /* jshint latedef:false */ /* jshint forin:false */ /* jshint noempty:false */ 'use strict'; var util = require('util'); var msRest = require('ms-rest'); var ServiceClient = msRest.ServiceClient; var models = require('./models'); var operations = require('./operations'); /** * @class * Initializes a new instance of the AutoRestParameterizedCustomHostTestClient class. * @constructor * * @param {string} subscriptionId - The subscription id with value 'test12'. * * @param {object} [options] - The parameter options * * @param {Array} [options.filters] - Filters to be added to the request pipeline * * @param {object} [options.requestOptions] - Options for the underlying request object * {@link https://github.com/request/request#requestoptions-callback Options doc} * * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy * * @param {string} [options.dnsSuffix] - A string value that is used as a global part of the parameterized host. Default value 'host'. * */ function AutoRestParameterizedCustomHostTestClient(subscriptionId, options) { this.dnsSuffix = 'host'; if (subscriptionId === null || subscriptionId === undefined) { throw new Error('\'subscriptionId\' cannot be null.'); } if (!options) options = {}; AutoRestParameterizedCustomHostTestClient['super_'].call(this, null, options); this.baseUri = '{vault}{secret}{dnsSuffix}'; this.subscriptionId = subscriptionId; if(options.dnsSuffix !== null && options.dnsSuffix !== undefined) { this.dnsSuffix = options.dnsSuffix; } this.paths = new operations.Paths(this); this.models = models; msRest.addSerializationMixin(this); } util.inherits(AutoRestParameterizedCustomHostTestClient, ServiceClient); module.exports = AutoRestParameterizedCustomHostTestClient;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _actions = require('../actions'); var describeUnregisterField = function describeUnregisterField(reducer, expect, _ref) { var fromJS = _ref.fromJS; return function () { it('should remove a field from registeredFields', function () { var state = reducer(fromJS({ foo: { registeredFields: { bar: { name: 'bar', type: 'field', count: 1 } } } }), (0, _actions.unregisterField)('foo', 'bar')); expect(state).toEqualMap({ foo: {} }); }); it('should do nothing if there are no registered fields', function () { var initialState = fromJS({ foo: {} }); var state = reducer(initialState, (0, _actions.unregisterField)('foo', 'bar')); expect(state).toEqual(initialState); }); it('should do nothing if the field is not registered', function () { var state = reducer(fromJS({ foo: { registeredFields: { bar: { name: 'bar', type: 'Field', count: 1 } } } }), (0, _actions.unregisterField)('foo', 'baz')); expect(state).toEqualMap({ foo: { registeredFields: { bar: { name: 'bar', type: 'Field', count: 1 } } } }); }); it('should set count to zero when not destroyOnUnmount', function () { var state = reducer(fromJS({ foo: { registeredFields: { bar: { name: 'bar', type: 'field', count: 1 } } } }), (0, _actions.unregisterField)('foo', 'bar', false)); expect(state).toEqualMap({ foo: { registeredFields: { bar: { name: 'bar', type: 'field', count: 0 } } } }); }); it('should decrease count if the field is registered multiple times', function () { var state = reducer(fromJS({ foo: { registeredFields: { bar: { name: 'bar', type: 'field', count: 8 } } } }), (0, _actions.unregisterField)('foo', 'bar')); expect(state).toEqualMap({ foo: { registeredFields: { bar: { name: 'bar', type: 'field', count: 7 } } } }); }); }; }; exports.default = describeUnregisterField;
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require bootstrap-sprockets //= require_tree .
/* VCO.MapMarker Creates a marker. Takes a data object and populates the marker with content. ================================================== */ VCO.MapMarker = VCO.Class.extend({ includes: [VCO.Events], /* Constructor ================================================== */ initialize: function(data, options) { // DOM Elements this._el = { container: {}, content_container: {}, content: {} }; // Components this._marker = {}; // Icon this._icon = {}; this._custom_icon = false; this._custom_icon_url = ""; this._custom_image_icon = false; // Marker Number this.marker_number = 0; // Media Icon this.media_icon_class = ""; // Timer this.timer = {}; // Data this.data = {}; // Options this.options = { // animation duration: 1000, ease: VCO.Ease.easeInSpline, width: 600, height: 600, map_popup: false, use_custom_markers: false }; // Animation Object this.animator = null; // Merge Data and Options VCO.Util.mergeData(this.options, options); VCO.Util.mergeData(this.data, data); this._initLayout(); }, /* Public ================================================== */ show: function() { }, hide: function() { }, addTo: function(m) { this._addTo(m); }, removeFrom: function(m) { this._removeFrom(m) }, updateDisplay: function(w, h, a) { this._updateDisplay(w, h, a); }, createMarker: function(d, o) { this._createMarker(d, o); }, createPopup: function(d, o) { this._createPopup(d, o); }, active: function(a) { this._active(a); }, location: function() { return this._location(); }, /* Marker Specific Specific to Map API ================================================== */ _createMarker: function(d, o) { }, _addTo: function(m) { }, _removeFrom: function(m) { }, _createPopup: function(d, o) { }, _active: function(a) { }, _location: function() { return {lat:0, lng:0} }, /* Events ================================================== */ _onMarkerClick: function(e) { this.fire("markerclick", {marker_number: this.marker_number}); }, /* Private Methods ================================================== */ _initLayout: function () { this._createMarker(this.data, this.options); }, // Update Display _updateDisplay: function(width, height, animate) { } });
(function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['videojs', 'wavesurfer'], 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(require('video.js'), require('wavesurfer.js')); } else { // Browser globals (root is window) root.returnExports = factory(root.videojs, root.WaveSurfer); } }(this, function (videojs, WaveSurfer) { var VjsComponent = videojs.getComponent('Component'); /** * Draw a waveform for audio and video files in a video.js player. */ videojs.Waveform = videojs.extend(VjsComponent, { /** * The constructor function for the class. * * @param {videojs.Player|Object} player * @param {Object} options Player options. */ constructor: function(player, options) { // run base component initializing with new options. VjsComponent.call(this, player, options); this.waveReady = false; this.waveFinished = false; this.liveMode = false; if (this.options_.options.src === 'live') { // check if the Microphone plugin can be enabled try { this.microphone = Object.create(WaveSurfer.Microphone); // listen for events this.microphone.on('deviceError', this.onWaveError.bind(this)); // enable audio input from a microphone this.liveMode = true; this.waveReady = true; } catch (TypeError) { console.warn('Could not find Microphone plugin!'); } } if (this.options_.options.msDisplayMax !== undefined) { // msDisplayMax indicates the number of seconds that is // considered the boundary value for displaying milliseconds // in the time controls. An audio clip with a total length of // 2 seconds and a msDisplayMax of 3 will use the format // M:SS:MMM. Clips longer than msDisplayMax will be displayed // as M:SS or HH:MM:SS. this.msDisplayMax = parseFloat(this.options_.options.msDisplayMax); } else { // default this.msDisplayMax = 3; } // wait until player ui is ready this.player().one('ready', this.setupUI.bind(this)); }, /** * Player UI is ready. */ setupUI: function() { // customize controls this.player().bigPlayButton.hide(); // the native controls don't work for this UI so disable // them no matter what if (this.player().usingNativeControls_ === true) { if (this.player().tech_.el_ !== undefined) { this.player().tech_.el_.controls = false; } } if (this.player().options_.controls) { // make sure controlBar is showing this.player().controlBar.show(); this.player().controlBar.el().style.display = 'flex'; // progress control isn't used by this plugin this.player().controlBar.progressControl.hide(); // prevent controlbar fadeout this.player().on('userinactive', function(event) { this.player().userActive(true); }); // make sure time display is visible var uiElements = [this.player().controlBar.currentTimeDisplay, this.player().controlBar.timeDivider, this.player().controlBar.durationDisplay]; for (var element in uiElements) { // ignore when elements have been disabled by user if (uiElements[element] !== undefined) { uiElements[element].el().style.display = 'block'; uiElements[element].show(); } } if (this.player().controlBar.remainingTimeDisplay !== undefined) { this.player().controlBar.remainingTimeDisplay.hide(); } if (this.player().controlBar.timeDivider !== undefined) { this.player().controlBar.timeDivider.el().style.textAlign = 'center'; this.player().controlBar.timeDivider.el().style.width = '2em'; } // disable play button until waveform is ready // (except when in live mode) if (!this.liveMode) { this.player().controlBar.playToggle.hide(); } } // waveform events this.surfer = Object.create(WaveSurfer); this.surfer.on('error', this.onWaveError.bind(this)); this.surfer.on('finish', this.onWaveFinish.bind(this)); this.surferReady = this.onWaveReady.bind(this); this.surferProgress = this.onWaveProgress.bind(this); this.surferSeek = this.onWaveSeek.bind(this); // only listen to these events when we're not in live mode if (!this.liveMode) { this.setupPlaybackEvents(true); } // player events this.player().on('play', this.onPlay.bind(this)); this.player().on('pause', this.onPause.bind(this)); this.player().on('volumechange', this.onVolumeChange.bind(this)); this.player().on('fullscreenchange', this.onScreenChange.bind(this)); // kick things off this.startPlayers(); }, /** * Starts or stops listening to events related to audio-playback. * * @param {boolean} enable Start or stop listening to playback related * events. */ setupPlaybackEvents: function(enable) { if (enable === false) { this.surfer.un('ready', this.surferReady); this.surfer.un('audioprocess', this.surferProgress); this.surfer.un('seek', this.surferSeek); } else if (enable === true) { this.surfer.on('ready', this.surferReady); this.surfer.on('audioprocess', this.surferProgress); this.surfer.on('seek', this.surferSeek); } }, /** * Start the players. */ startPlayers: function() { var options = this.options_.options; // init waveform this.initialize(options); if (options.src !== undefined) { if (this.microphone === undefined) { // show loading spinner this.player().loadingSpinner.show(); // start loading file this.load(options.src); } else { // hide loading spinner this.player().loadingSpinner.hide(); // connect microphone input to our waveform options.wavesurfer = this.surfer; this.microphone.init(options); } } else { // no valid src found, hide loading spinner this.player().loadingSpinner.hide(); } }, /** * Initializes the waveform. * * @param {Object} opts Plugin options. */ initialize: function(opts) { this.originalHeight = this.player().options_.height; var controlBarHeight = this.player().controlBar.height(); if (this.player().options_.controls === true && controlBarHeight === 0) { // The dimensions of the controlbar are not known yet, but we need // it now, so we can calculate the height of the waveform. // The default height is 30px, so use that instead. controlBarHeight = 30; } // set waveform element and dimensions // Set the container to player's container if "container" option is not provided // If a waveform needs to be appended to your custom element, then use below option // <code>container: document.querySelector("#vjs-waveform")</code> if (opts.container === undefined) { opts.container = this.el(); } // Set the height of generated waveform if user has provided height from options. // If height of waveform need to be customized then use option below. // Example: <code>waveformHeight:30</code> if (opts.waveformHeight === undefined) { opts.height = this.player().height() - controlBarHeight; } else { opts.height = opts.waveformHeight; } // customize waveform appearance this.surfer.init(opts); }, /** * Start loading waveform data. * * @param {String|Blob|File} url Either the URL of the audio file, * or a Blob or File object. */ load: function(url) { if (url instanceof Blob || url instanceof File) { this.surfer.loadBlob(url); } else { this.surfer.load(url); } }, /** * Start/resume playback or microphone. */ play: function() { if (this.liveMode) { // start/resume microphone visualization if (!this.microphone.active) { this.microphone.start(); } else { this.microphone.play(); } } else { // put video.js player UI in playback mode this.player().play(); // start surfer playback this.surfer.play(); } }, /** * Pauses playback or microphone visualization. */ pause: function() { if (this.liveMode) { // pause microphone visualization this.microphone.pause(); } else { // pause playback if (!this.waveFinished) { this.surfer.pause(); } else { this.waveFinished = false; } this.setCurrentTime(); } }, /** * Remove the player and waveform. */ destroy: function() { if (this.liveMode && this.microphone) { // destroy microphone plugin this.microphone.destroy(); } this.surfer.destroy(); this.player().dispose(); }, /** * Set the current volume. * * @param {Number} volume The new volume level. */ setVolume: function(volume) { if (volume !== undefined) { this.surfer.setVolume(volume); } }, /** * Updates the player's element displaying the current time. * * @param {Number} currentTime (optional) Current position of the * playhead (in seconds). * @param {Number} duration (optional) Duration of the waveform * (in seconds). */ setCurrentTime: function(currentTime, duration) { if (currentTime === undefined) { currentTime = this.surfer.getCurrentTime(); } if (duration === undefined) { duration = this.surfer.getDuration(); } currentTime = isNaN(currentTime) ? 0 : currentTime; duration = isNaN(duration) ? 0 : duration; var time = Math.min(currentTime, duration); // update control this.player().controlBar.currentTimeDisplay.contentEl( ).innerHTML = this.formatTime(time, duration); }, /** * Updates the player's element displaying the duration time. * * @param {Number} duration (optional) Duration of the waveform * (in seconds). */ setDuration: function(duration) { if (duration === undefined) { duration = this.surfer.getDuration(); } duration = isNaN(duration) ? 0 : duration; // update control this.player().controlBar.durationDisplay.contentEl( ).innerHTML = this.formatTime(duration, duration); }, /** * Audio is loaded, decoded and the waveform is drawn. */ onWaveReady: function() { this.waveReady = true; this.waveFinished = false; this.liveMode = false; // update time display this.setCurrentTime(); this.setDuration(); // enable and show play button this.player().controlBar.playToggle.show(); // hide loading spinner this.player().loadingSpinner.hide(); // auto-play when ready (if enabled) if (this.player().options_.autoplay) { this.play(); } }, /** * Fires when audio playback completed. */ onWaveFinish: function() { // check if player isn't paused already if (!this.player().paused()) { // check if loop is enabled if (this.player().options_.loop) { // reset waveform this.surfer.stop(); this.play(); } else { // finished this.waveFinished = true; // pause player this.player().pause(); } } }, /** * Fires continuously during audio playback. * * @param {Number} time Current time/location of the playhead. */ onWaveProgress: function(time) { this.setCurrentTime(); }, /** * Fires during seeking of the waveform. */ onWaveSeek: function() { this.setCurrentTime(); }, /** * Fired whenever the media in the player begins or resumes playback. */ onPlay: function() { // don't start playing until waveform's ready if (this.waveReady) { this.play(); } }, /** * Fired whenever the media in the player has been paused. */ onPause: function() { this.pause(); }, /** * Fired when the volume in the player changes. */ onVolumeChange: function() { var volume = this.player().volume(); if (this.player().muted()) { // muted volume volume = 0; } this.setVolume(volume); }, /** * Fired when the player switches in or out of fullscreen mode. */ onScreenChange: function() { var isFullscreen = this.player().isFullscreen(); var newHeight; if (!isFullscreen) { // restore original height newHeight = this.originalHeight; } else { // fullscreen height newHeight = window.outerHeight; } if (this.waveReady) { if (this.liveMode && !this.microphone.active) { // we're in live mode but the microphone hasn't been // started yet return; } // destroy old drawing this.surfer.drawer.destroy(); // set new height this.surfer.params.height = newHeight - this.player().controlBar.height(); this.surfer.createDrawer(); // redraw this.surfer.drawBuffer(); // make sure playhead is restored at right position this.surfer.drawer.progress(this.surfer.backend.getPlayedPercents()); } }, /** * Waveform error. * * @param {String} error The wavesurfer error. */ onWaveError: function(error) { this.player().trigger('error', error); }, /** * Format seconds as a time string, H:MM:SS, M:SS or M:SS:MMM. * * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide. * * @param {Number} seconds Number of seconds to be turned into a string * @param {Number} guide Number (in seconds) to model the string after * @return {String} Time formatted as H:MM:SS, M:SS or M:SS:MMM. */ formatTime: function(seconds, guide) { // Default to using seconds as guide seconds = seconds < 0 ? 0 : seconds; guide = guide || seconds; var s = Math.floor(seconds % 60), m = Math.floor(seconds / 60 % 60), h = Math.floor(seconds / 3600), gm = Math.floor(guide / 60 % 60), gh = Math.floor(guide / 3600), ms = Math.floor((seconds - s) * 1000); // handle invalid times if (isNaN(seconds) || seconds === Infinity) { // '-' is false for all relational operators (e.g. <, >=) so this // setting will add the minimum number of fields specified by the // guide h = m = s = ms = '-'; } // Check if we need to show milliseconds if (guide > 0 && guide < this.msDisplayMax) { if (ms < 100) { if (ms < 10) { ms = '00' + ms; } else { ms = '0' + ms; } } ms = ':' + ms; } else { ms = ''; } // Check if we need to show hours h = (h > 0 || gh > 0) ? h + ':' : ''; // If hours are showing, we may need to add a leading zero. // Always show at least one digit of minutes. m = (((h || gm >= 10) && m < 10) ? '0' + m : m) + ':'; // Check if leading zero is need for seconds s = ((s < 10) ? '0' + s : s); return h + m + s + ms; } }); var createWaveform = function() { var props = { className: 'vjs-waveform', tabIndex: 0 }; return VjsComponent.prototype.createEl('div', props); }; // plugin defaults var defaults = {}; /** * Initialize the plugin. * @param options (optional) {object} configuration for the plugin */ var wavesurferPlugin = function(options) { var settings = videojs.mergeOptions(defaults, options); var player = this; // create new waveform player.waveform = new videojs.Waveform(player, { 'el': createWaveform(), 'options': settings }); // add waveform to dom player.el().appendChild(player.waveform.el()); }; // register the plugin videojs.plugin('wavesurfer', wavesurferPlugin); // return a function to define the module export return wavesurferPlugin; }));
window.wpfc.dictionary = { "All cached files are deleted at the determinated time." : "Tous les fichiers mis en cache sont supprimés au moment determiné.:", "Choose One" :"Choisissez un", "Once an hour": "Une fois par heure", "Once a day": "Une fois par jour", "Twice a day":"Deux fois par jour", "Next due":"Suivant", "Schedule":"Fréquence", "Server time":"Heure du serveur", "You can decrease the size of page" :"Vous pouvez réduire la taille de la page", "WP Fastest Cache Options":"Options de WP Fastest Cache", "Options have been saved" :"Les options ont été sauvés", ".htacces is not writable": ".htaccess n'est pas accessible en écriture", "All cache files have been deleted" :"Tous les fichiers de cache ont été supprimées", "Language" :"Langue", "Settings" :"Configuration", "Delete Cache" :"Effacer le cache", "Cache Timeout" :"Validité du cache", "Delete Minified Css" :"Effacer fichiers CSS compressés", "Cache System" :"Système de cache", "Logged-in Users" :"Utilisateurs enregistrés", "Minify HTML" :"Réduire HTML", "Minify Css" :"Réduire Css", "Browser Caching" :"Cache du navigateur", "Enable" :"Activer", "New Post" :"Nouveau message", "Clear all cache files when a post or page is published" :"Effacer tous les fichiers de cache quand un article ou une page sont publiés", "Submit" :"Soumettre", "Delete Now" :"Effacer maintenant", "You can delete all cache files" :"Vous pouvez supprimer tous les fichiers du cache", "Target folder" :"Dossier cible", "It will active in the next version" : "Il sera actif dans la prochaine version", "You can decrease the size of css files" : "Vous pouvez réduire la taille des fichiers CSS", "Reduce the size of files sent from your server" : "Réduire la taille des fichiers envoyés à partir de votre serveur", "Having Issues?" : "Vous avez des questions?", "You can create a ticket" : "Vous pouvez créer un billet", "WordPress support forum" : "Forum de support WordPress", "Compacting HTML code, including any inline JavaScript and CSS contained in it, can save many bytes of data and speed up downloading, parsing, and execution time." : "Le compactage du code HTML, y compris en ligne JavaScript et CSS qu'il contient, peut économiser de nombreux octets de données et accélérer le téléchargement, l'analyse et le temps d'exécution.", "Compacting CSS code can save many bytes of data and speed up downloading, parsing, and execution time." : "Le compactage de code CSS peut économiser de nombreux octets de données et accélérer le téléchargement, l'analyse et le temps d'exécution.", "Enable Gzip Compression" : "Activer la compression Gzip", "Increase page speed" : "Augmenter la vitesse de chargement de la page", "Reduce sizes of pages by up to 70%" : "Réduire la taille des pages jusqu'à 70%", "Reduce the size of files sent from your server to increase the speed to which they are transferred to the browser." : "Réduire la taille des fichiers afin qu'ils soient transmis plus rapidement du serveur, au navigateur.", "Cost-benefit ratio: high" : "Rapport coûts-avantages: élevé", "All cache files will be removed as well" : "Tous les fichiers du cache seront aussi supprimés", "If you modify any css or js file, you have to delete minified js and css files" : "Si vous modifiez un fichier css ou js, vous devez supprimer les fichiers js et css compressés", "If you modify any css file, you have to delete minified css files" : "Si vous modifiez un fichier CSS, vous devez supprimer les fichiers css compressés", "Delete Minified Css & Js" : "Supprimer les fichiers Css et Js compressés", "Don't show the cached version for mobile devices" : "Ne pas afficher la version mise en cache pour les appareils mobiles", "Leverage Browser Caching" : "Augmenter l'utilisation de la mémoire cache du navigateur", "If you like it, Please vote and support us." : "", "Reduce the load times of pages by storing commonly used files from your website on your visitors browser." : "Réduire le temps de chargement des pages couramment utilisés en stockant les fichiers sur le navigateur de vos visiteurs.", "Reduce page load times for repeat visitors" : "Réduit le temps de chargement des pages pour les visiteurs réguliers", "Particularly effective on websites where users regularly re-visit the same areas of the website" : "Particulièrement efficace sur les sites Web où les utilisateurs re-visitent régulièrement les mêmes pages du site", "Don't show the cached version for logged-in users" : "Ne pas afficher la version mise en cache pour les utilisateurs inscrits", "Already deleted" : "Déjà supprimé", "Support Us" : "Soutenez-nous", "Reduce HTTP requests through combined js files" : "Réduire les requêtes HTTP par js combinés", "This feature combines the JS files between <head></head>. Decreasing the number of javascript files on a page reduces the number of HTTP requests required to render the page, resulting in faster page loads." : "Cette fonction fusionne les fichiers JS entre &#60;head&#62;&#60;/head&#62;. Fusionner du nombre de fichiers javascript en une même page réduit le nombre de requêtes HTTP nécessaires pour transmettre la page, ce qui accélère chargement de celle-ci.", "If you like it, Please vote and support us." : "Si vous aimez ce Plugin, S'il vous plaît, votez et soutenez-nous !", "Reduce HTTP requests through combined css files" : "Réduire les requêtes HTTP via des css fichiers combinés", "Decreasing the number of components on a page reduces the number of HTTP requests required to render the page, resulting in faster page loads." : "La diminution du nombre de composants sur une page réduit le nombre de requêtes HTTP nécessaires pour rendre la page, ce qui accélère chargement de celle-ci.", "Combine Css" : "Combinez Css", "*** Attention ***" : "*** Attention ***", "Open .htaccess and remove this rule" : "Ouvrez le fichier .htaccess et supprimer cette règle", "If your server does not support mod_expires.c, this option can cause the Internel Server Error (500). If you see such error please do the steps below." : "Si votre serveur ne supporte pas mod_expires.c, cette option peut provoquer l'erreur <<Internel Server Error (500)>>. Si vous voyez cette erreur, s'il vous plaît suivez les étapes ci-dessous." };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _actions = require('../actions'); var describeArrayInsert = function describeArrayInsert(reducer, expect, _ref) { var fromJS = _ref.fromJS; return function () { it('should work with empty state', function () { var state = reducer(undefined, (0, _actions.arrayInsert)('foo', 'myField', 0, 'myValue')); expect(state).toEqualMap({ foo: { values: { myField: ['myValue'] } } }); }); it('should insert at beginning', function () { var state = reducer(fromJS({ foo: { values: { myField: { subField: ['a', 'b', 'c'] } }, fields: { myField: { subField: [{ touched: true }, { touched: true, visited: true }, { touched: true }] } } } }), (0, _actions.arrayInsert)('foo', 'myField.subField', 0, 'newValue')); expect(state).toEqualMap({ foo: { values: { myField: { subField: ['newValue', 'a', 'b', 'c'] } }, fields: { myField: { subField: [{}, { touched: true }, { touched: true, visited: true }, { touched: true }] } } } }); }); it('should insert at end', function () { var state = reducer(fromJS({ foo: { values: { myField: { subField: ['a', 'b', 'c'] } }, fields: { myField: { subField: [{ touched: true }, { touched: true, visited: true }, { touched: true }] } } } }), (0, _actions.arrayInsert)('foo', 'myField.subField', 3, 'newValue')); expect(state).toEqualMap({ foo: { values: { myField: { subField: ['a', 'b', 'c', 'newValue'] } }, fields: { myField: { subField: [{ touched: true }, { touched: true, visited: true }, { touched: true }, {}] } } } }); }); it('should insert in middle', function () { var state = reducer(fromJS({ foo: { values: { myField: { subField: ['a', 'b', 'c'] } }, fields: { myField: { subField: [{ touched: true }, { touched: true, visited: true }, { touched: true }] } } } }), (0, _actions.arrayInsert)('foo', 'myField.subField', 1, 'newValue')); expect(state).toEqualMap({ foo: { values: { myField: { subField: ['a', 'newValue', 'b', 'c'] } }, fields: { myField: { subField: [{ touched: true }, {}, { touched: true, visited: true }, { touched: true }] } } } }); }); }; }; exports.default = describeArrayInsert;
/* * # Semantic - Form Validation * http://github.com/jlukic/semantic-ui/ * * * Copyright 2013 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { $.fn.form = function(fields, parameters) { var $allModules = $(this), settings = $.extend(true, {}, $.fn.form.settings, parameters), validation = $.extend({}, $.fn.form.settings.defaults, fields), namespace = settings.namespace, metadata = settings.metadata, selector = settings.selector, className = settings.className, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var $module = $(this), $field = $(this).find(selector.field), $group = $(this).find(selector.group), $message = $(this).find(selector.message), $prompt = $(this).find(selector.prompt), $submit = $(this).find(selector.submit), formErrors = [], element = this, instance = $module.data(moduleNamespace), module ; module = { initialize: function() { module.verbose('Initializing form validation', $module, validation, settings); if(settings.keyboardShortcuts) { $field .on('keydown' + eventNamespace, module.event.field.keydown) ; } $module .on('submit' + eventNamespace, module.validate.form) ; $field .on('blur' + eventNamespace, module.event.field.blur) ; $submit .on('click' + eventNamespace, module.submit) ; $field .on(module.get.changeEvent() + eventNamespace, module.event.field.change) ; module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying previous module', instance); $module .off(eventNamespace) .removeData(moduleNamespace) ; }, refresh: function() { module.verbose('Refreshing selector cache'); $field = $module.find(selector.field); }, submit: function() { module.verbose('Submitting form', $module); $module .submit() ; }, event: { field: { keydown: function(event) { var $field = $(this), key = event.which, keyCode = { enter : 13, escape : 27 } ; if( key == keyCode.escape) { module.verbose('Escape key pressed blurring field'); $field .blur() ; } if(!event.ctrlKey && key == keyCode.enter && $field.is(selector.input) ) { module.debug('Enter key pressed, submitting form'); $submit .addClass(className.down) ; $field .one('keyup' + eventNamespace, module.event.field.keyup) ; event.preventDefault(); return false; } }, keyup: function() { module.verbose('Doing keyboard shortcut form submit'); $submit.removeClass(className.down); module.submit(); }, blur: function() { var $field = $(this), $fieldGroup = $field.closest($group) ; if( $fieldGroup.hasClass(className.error) ) { module.debug('Revalidating field', $field, module.get.validation($field)); module.validate.field( module.get.validation($field) ); } else if(settings.on == 'blur' || settings.on == 'change') { module.validate.field( module.get.validation($field) ); } }, change: function() { var $field = $(this), $fieldGroup = $field.closest($group) ; if(settings.on == 'change' || ( $fieldGroup.hasClass(className.error) && settings.revalidate) ) { clearTimeout(module.timer); module.timer = setTimeout(function() { module.debug('Revalidating field', $field, module.get.validation($field)); module.validate.field( module.get.validation($field) ); }, settings.delay); } } } }, get: { changeEvent: function() { return (document.createElement('input').oninput !== undefined) ? 'input' : (document.createElement('input').onpropertychange !== undefined) ? 'propertychange' : 'keyup' ; }, field: function(identifier) { module.verbose('Finding field with identifier', identifier); if( $field.filter('#' + identifier).size() > 0 ) { return $field.filter('#' + identifier); } else if( $field.filter('[name="' + identifier +'"]').size() > 0 ) { return $field.filter('[name="' + identifier +'"]'); } else if( $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]').size() > 0 ) { return $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]'); } return $('<input/>'); }, validation: function($field) { var rules ; $.each(validation, function(fieldName, field) { if( module.get.field(field.identifier).get(0) == $field.get(0) ) { rules = field; } }); return rules || false; } }, has: { field: function(identifier) { module.verbose('Checking for existence of a field with identifier', identifier); if( $field.filter('#' + identifier).size() > 0 ) { return true; } else if( $field.filter('[name="' + identifier +'"]').size() > 0 ) { return true; } else if( $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]').size() > 0 ) { return true; } return false; } }, add: { prompt: function(field, errors) { var $field = module.get.field(field.identifier), $fieldGroup = $field.closest($group), $prompt = $fieldGroup.find(selector.prompt), promptExists = ($prompt.size() !== 0) ; module.verbose('Adding inline error', field); $fieldGroup .addClass(className.error) ; if(settings.inline) { if(!promptExists) { $prompt = settings.templates.prompt(errors); $prompt .appendTo($fieldGroup) ; } $prompt .html(errors[0]) ; if(!promptExists) { if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) { module.verbose('Displaying error with css transition', settings.transition); $prompt.transition(settings.transition + ' in', settings.duration); } else { module.verbose('Displaying error with fallback javascript animation'); $prompt .fadeIn(settings.duration) ; } } } }, errors: function(errors) { module.debug('Adding form error messages', errors); $message .html( settings.templates.error(errors) ) ; } }, remove: { prompt: function(field) { var $field = module.get.field(field.identifier), $fieldGroup = $field.closest($group), $prompt = $fieldGroup.find(selector.prompt) ; $fieldGroup .removeClass(className.error) ; if(settings.inline && $prompt.is(':visible')) { module.verbose('Removing prompt for field', field); if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) { $prompt.transition(settings.transition + ' out', settings.duration, function() { $prompt.remove(); }); } else { $prompt .fadeOut(settings.duration, function(){ $prompt.remove(); }) ; } } } }, validate: { form: function(event) { var allValid = true ; // reset errors formErrors = []; $.each(validation, function(fieldName, field) { if( !( module.validate.field(field) ) ) { allValid = false; } }); if(allValid) { module.debug('Form has no validation errors, submitting'); $module .removeClass(className.error) .addClass(className.success) ; $.proxy(settings.onSuccess, this)(event); } else { module.debug('Form has errors'); $module.addClass(className.error); if(!settings.inline) { module.add.errors(formErrors); } return $.proxy(settings.onFailure, this)(formErrors); } }, // takes a validation object and returns whether field passes validation field: function(field) { var $field = module.get.field(field.identifier), fieldValid = true, fieldErrors = [] ; if(field.rules !== undefined) { $.each(field.rules, function(index, rule) { if( module.has.field(field.identifier) && !( module.validate.rule(field, rule) ) ) { module.debug('Field is invalid', field.identifier, rule.type); fieldErrors.push(rule.prompt); fieldValid = false; } }); } if(fieldValid) { module.remove.prompt(field, fieldErrors); $.proxy(settings.onValid, $field)(); } else { formErrors = formErrors.concat(fieldErrors); module.add.prompt(field, fieldErrors); $.proxy(settings.onInvalid, $field)(fieldErrors); return false; } return true; }, // takes validation rule and returns whether field passes rule rule: function(field, validation) { var $field = module.get.field(field.identifier), type = validation.type, value = $.trim($field.val() + ''), bracketRegExp = /\[(.*?)\]/i, bracket = bracketRegExp.exec(type), isValid = true, ancillary, functionType ; // if bracket notation is used, pass in extra parameters if(bracket !== undefined && bracket !== null) { ancillary = '' + bracket[1]; functionType = type.replace(bracket[0], ''); isValid = $.proxy(settings.rules[functionType], $module)(value, ancillary); } // normal notation else { isValid = $.proxy(settings.rules[type], $field)(value); } return isValid; } }, setting: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Element' : element, 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 100); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if($allModules.size() > 1) { title += ' ' + '(' + $allModules.size() + ')'; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { module.destroy(); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.form.settings = { name : 'Form', namespace : 'form', debug : true, verbose : true, performance : true, keyboardShortcuts : true, on : 'submit', inline : false, delay : 200, revalidate : true, transition : 'scale', duration : 150, onValid : function() {}, onInvalid : function() {}, onSuccess : function() { return true; }, onFailure : function() { return false; }, metadata : { validate: 'validate' }, selector : { message : '.error.message', field : 'input, textarea, select', group : '.field', input : 'input', prompt : '.prompt', submit : '.submit' }, className : { error : 'error', success : 'success', down : 'down', label : 'ui label prompt' }, // errors error: { method : 'The method you called is not defined.' }, templates: { error: function(errors) { var html = '<ul class="list">' ; $.each(errors, function(index, value) { html += '<li>' + value + '</li>'; }); html += '</ul>'; return $(html); }, prompt: function(errors) { return $('<div/>') .addClass('ui red pointing prompt label') .html(errors[0]) ; } }, rules: { checked: function() { return ($(this).filter(':checked').size() > 0); }, empty: function(value) { return !(value === undefined || '' === value); }, email: function(value){ var emailRegExp = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", "i") ; return emailRegExp.test(value); }, length: function(value, requiredLength) { return (value !== undefined) ? (value.length >= requiredLength) : false ; }, not: function(value, notValue) { return (value != notValue); }, contains: function(value, text) { text = text.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); return (value.search(text) !== -1); }, is: function(value, text) { return (value == text); }, maxLength: function(value, maxLength) { return (value !== undefined) ? (value.length <= maxLength) : false ; }, match: function(value, fieldIdentifier) { // use either id or name of field var $form = $(this), matchingValue ; if($form.find('#' + fieldIdentifier).size() > 0) { matchingValue = $form.find('#' + fieldIdentifier).val(); } else if($form.find('[name=' + fieldIdentifier +']').size() > 0) { matchingValue = $form.find('[name=' + fieldIdentifier + ']').val(); } else if( $form.find('[data-validate="'+ fieldIdentifier +'"]').size() > 0 ) { matchingValue = $form.find('[data-validate="'+ fieldIdentifier +'"]').val(); } return (matchingValue !== undefined) ? ( value.toString() == matchingValue.toString() ) : false ; }, url: function(value) { var urlRegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ ; return urlRegExp.test(value); } } }; })( jQuery, window , document );
(function(define) { "use strict"; // Builder // ------- define(function(require, exports) { var _ = require('underscore'); var Common = require('./common').Common; var Raw = require('./raw').Raw; var Helpers = require('./helpers').Helpers; var JoinClause = require('./joinclause').JoinClause; var array = []; var push = array.push; var Builder = function(client) { if (client instanceof Builder) { this.client = client.client; this.grammar = this.client.grammar; } else { this.client = client; this.grammar = client.grammar; } this.reset(); }; // All operators used in the `where` clause generation. var operators = ['=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'between', 'ilike']; _.extend(Builder.prototype, Common, { _source: 'Builder', // Sets the `tableName` on the query. from: function(tableName) { if (!tableName) return this.table; this.table = tableName; return this; }, // Adds a column to the list of "columns" being selected // on the query. column: function(value) { this.columns.push(value); return this; }, // Adds a `distinct` clause to the query. distinct: function(column) { this.column(column); this.isDistinct = true; return this; }, // Compiles the current query builder. toSql: function() { this.type || (this.type = 'select'); return this.grammar['compile' + Helpers.capitalize(this.type)](this); }, // Clones the current query builder, including any // pieces that have been set thus far. clone: function() { var item = new Builder(this); item.table = this.table; var items = [ 'isDistinct', 'joins', 'wheres', 'orders', 'columns', 'bindings', 'grammar', 'transaction', 'unions' ]; for (var i = 0, l = items.length; i < l; i++) { var k = items[i]; item[k] = this[k]; } return item; }, // Resets all attributes on the query builder. reset: function() { this.joins = []; this.values = []; this.unions = []; this.wheres = []; this.orders = []; this.columns = []; this.bindings = []; this.isDistinct = false; this.isReturning = false; }, // Adds a join clause to the query, allowing for advanced joins // with an anonymous function as the second argument. join: function(table, first, operator, second, type) { var join; if (_.isFunction(first)) { type = operator; join = new JoinClause(type || 'inner', table); first.call(join, join); } else { join = new JoinClause(type || 'inner', table); join.on(first, operator, second); } this.joins.push(join); return this; }, // The where function can be used in several ways: // The most basic is `where(key, value)`, which expands to // where key = value. where: function(column, operator, value, bool) { var check; bool || (bool = 'and'); if (_.isFunction(column)) { return this._whereNested(column, bool); } if (column instanceof Raw) { return this.whereRaw(column.sql, column.bindings, bool); } if (_.isObject(column)) { for (var key in column) { value = column[key]; this[bool + 'Where'](key, '=', value); } return this; } if (_.isString(operator)) check = operator.toLowerCase(); if (!_.contains(operators, check)) { value = operator; operator = '='; } if (_.isFunction(value)) { return this._whereSub(column, operator, value, bool); } this.wheres.push({ type: 'Basic', column: column, operator: operator, value: value, bool: bool }); this.bindings.push(value); return this; }, // Alias to `where`, for internal builder consistency. andWhere: function() { return this.where.apply(this, arguments); }, // Adds an `or where` clause to the query. orWhere: function(column, operator, value) { return this.where(column, operator, value, 'or'); }, // Adds a raw `where` clause to the query. whereRaw: function(sql, bindings, bool) { bindings = _.isArray(bindings) ? bindings : (bindings ? [bindings] : []); this.wheres.push({type: 'Raw', sql: sql, bool: bool || 'and'}); push.apply(this.bindings, bindings); return this; }, // Adds a raw `or where` clause to the query. orWhereRaw: function(sql, bindings) { return this.whereRaw(sql, bindings, 'or'); }, // Adds a `where exists` clause to the query. whereExists: function(callback, bool, type) { var query = new Builder(this); callback.call(query, query); this.wheres.push({ type: (type || 'Exists'), query: query, bool: (bool || 'and') }); push.apply(this.bindings, query.bindings); return this; }, // Adds an `or where exists` clause to the query. orWhereExists: function(callback) { return this.whereExists(callback, 'or'); }, // Adds a `where not exists` clause to the query. whereNotExists: function(callback) { return this.whereExists(callback, 'and', 'NotExists'); }, // Adds a `or where not exists` clause to the query. orWhereNotExists: function(callback) { return this.whereExists(callback, 'or', 'NotExists'); }, // Adds a `where in` clause to the query. whereIn: function(column, values, bool, condition) { bool || (bool = 'and'); if (_.isFunction(values)) { return this._whereInSub(column, values, bool, (condition || 'In')); } this.wheres.push({ type: (condition || 'In'), column: column, value: values, bool: bool }); push.apply(this.bindings, values); return this; }, // Adds a `or where in` clause to the query. orWhereIn: function(column, values) { return this.whereIn(column, values, 'or'); }, // Adds a `where not in` clause to the query. whereNotIn: function(column, values) { return this.whereIn(column, values, 'and', 'NotIn'); }, // Adds a `or where not in` clause to the query. orWhereNotIn: function(column, values) { return this.whereIn(column, values, 'or', 'NotIn'); }, // Adds a `where null` clause to the query. whereNull: function(column, bool, type) { this.wheres.push({type: (type || 'Null'), column: column, bool: (bool || 'and')}); return this; }, // Adds a `or where null` clause to the query. orWhereNull: function(column) { return this.whereNull(column, 'or', 'Null'); }, // Adds a `where not null` clause to the query. whereNotNull: function(column) { return this.whereNull(column, 'and', 'NotNull'); }, // Adds a `or where not null` clause to the query. orWhereNotNull: function(column) { return this.whereNull(column, 'or', 'NotNull'); }, // Adds a `where between` clause to the query. whereBetween: function(column, values) { this.wheres.push({column: column, type: 'Between', bool: 'and'}); push.apply(this.bindings, values); return this; }, // Adds a `or where between` clause to the query. orWhereBetween: function(column, values) { this.wheres.push({column: column, type: 'Between', bool: 'or'}); push.apply(this.bindings, values); return this; }, // ---------------------------------------------------------------------- // Adds a `group by` clause to the query. groupBy: function() { this.groups = (this.groups || []).concat(_.toArray(arguments)); return this; }, // Adds a `order by` clause to the query. orderBy: function(column, direction) { this.orders.push({column: column, direction: (direction || 'asc')}); return this; }, // Add a union statement to the query. union: function(callback) { this._union(callback, false); return this; }, // Adds a union all statement to the query. unionAll: function(callback) { this._union(callback, true); return this; }, // Adds a `having` clause to the query. having: function(column, operator, value, bool) { if (column instanceof Raw) { return this.havingRaw(column.value, bool); } this.havings.push({column: column, operator: (operator || ''), value: (value || ''), bool: bool || 'and'}); this.bindings.push(value); return this; }, // Adds an `or having` clause to the query. orHaving: function(column, operator, value) { return this.having(column, operator, value, 'or'); }, // Adds a raw `having` clause to the query. havingRaw: function(sql, bool) { this.havings.push({type: 'Raw', sql: sql, bool: bool || 'and'}); return this; }, // Adds a raw `or having` clause to the query. orHavingRaw: function(sql) { return this.havingRaw(sql, 'or'); }, // ---------------------------------------------------------------------- offset: function(value) { if (value == null) return this.isOffset; this.isOffset = value; return this; }, limit: function(value) { if (value == null) return this.isLimit; this.isLimit = value; return this; }, // ---------------------------------------------------------------------- // Retrieve the "count" result of the query. count: function(column) { return this._aggregate('count', column); }, // Retrieve the minimum value of a given column. min: function(column) { return this._aggregate('min', column); }, // Retrieve the maximum value of a given column. max: function(column) { return this._aggregate('max', column); }, // Retrieve the sum of the values of a given column. sum: function(column) { return this._aggregate('sum', column); }, // Increments a column's value by the specified amount. increment: function(column, amount) { return this._counter(column, amount); }, // Decrements a column's value by the specified amount. decrement: function(column, amount) { return this._counter(column, amount, '-'); }, // Sets the values for a `select` query. select: function(columns) { if (columns) { push.apply(this.columns, _.isArray(columns) ? columns : _.toArray(arguments)); } return this._setType('select'); }, // Sets the values for an `insert` query. insert: function(values, returning) { if (returning) this.returning(returning); this.values = this._prepValues(_.clone(values)); return this._setType('insert'); }, // Sets the returning value for the query. returning: function(returning) { this.isReturning = returning; return this; }, // Sets the values for an `update` query. update: function(values) { var obj = Helpers.sortObject(values); var bindings = []; for (var i = 0, l = obj.length; i < l; i++) { bindings[i] = obj[i][1]; } this.bindings = bindings.concat(this.bindings || []); this.values = obj; return this._setType('update'); }, // Alias to del. "delete": function() { return this._setType('delete'); }, // Executes a delete statement on the query; del: function() { return this._setType('delete'); }, // Truncate truncate: function() { return this._setType('truncate'); }, // Set by `transacting` - contains the object with the connection // needed to execute a transaction transaction: false, // ---------------------------------------------------------------------- _prepValues: function(values) { if (!_.isArray(values)) values = values ? [values] : []; for (var i = 0, l = values.length; i<l; i++) { var obj = values[i] = Helpers.sortObject(values[i]); for (var i2 = 0, l2 = obj.length; i2 < l2; i2++) { this.bindings.push(obj[i2][1]); } } return values; }, // Helper for compiling any advanced `where in` queries. _whereInSub: function(column, callback, bool, condition) { condition += 'Sub'; var query = new Builder(this); callback.call(query, query); this.wheres.push({type: condition, column: column, query: query, bool: bool}); push.apply(this.bindings, query.bindings); return this; }, // Helper for compiling any advanced `where` queries. _whereNested: function(callback, bool) { var query = new Builder(this); query.table = this.table; callback.call(query, query); this.wheres.push({type: 'Nested', query: query, bool: bool}); push.apply(this.bindings, query.bindings); return this; }, // Helper for compiling any of the `where` advanced queries. _whereSub: function(column, operator, callback, bool) { var query = new Builder(this); callback.call(query, query); this.wheres.push({ type: 'Sub', column: column, operator: operator, query: query, bool: bool }); push.apply(this.bindings, query.bindings); return this; }, // Helper for compiling any aggregate queries. _aggregate: function(type, columns) { if (!_.isArray(columns)) columns = [columns]; this.aggregate = {type: type, columns: columns}; return this._setType('select'); }, // Helper for the incrementing/decrementing queries. _counter: function(column, amount, symbol) { var sql = {}; sql[column] = new Raw('' + this.grammar.wrap(column) + ' ' + (symbol || '+') + ' ' + amount); return this.update(sql); }, // Helper for compiling any `union` queries. _union: function(callback, bool) { var query = new Builder(this); callback.call(query, query); this.unions.push({query: query, all: bool}); push.apply(this.bindings, query.bindings); } }); exports.Builder = Builder; }); })( typeof define === 'function' && define.amd ? define : function (factory) { factory(require, exports); } );
var classblackbone_1_1_m_except = [ [ "MExcept", "classblackbone_1_1_m_except.html#a7c4a25f3ba08be0f02188acdfef933f7", null ], [ "~MExcept", "classblackbone_1_1_m_except.html#ad4a1c4f98f8fe20b68e265ee06570a65", null ], [ "CreateVEH", "classblackbone_1_1_m_except.html#a04078066ff12003a28758705d67156b4", null ], [ "RemoveVEH", "classblackbone_1_1_m_except.html#a2aca07f204a9d581938632bcad73a46c", null ] ];
/*! SWFMini - a SWFObject 2.2 cut down version for webshims * * based on SWFObject v2.2 <http://code.google.com/p/swfobject/> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ var swfmini = function() { var wasRemoved = function(){webshims.error('This method was removed from swfmini');}; var UNDEF = "undefined", OBJECT = "object", webshims = window.webshims, SHOCKWAVE_FLASH = "Shockwave Flash", SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash", FLASH_MIME_TYPE = "application/x-shockwave-flash", win = window, doc = document, nav = navigator, plugin = false, domLoadFnArr = [main], isDomLoaded = false, autoHideShow = true, /* Centralized function for browser feature detection - User agent string detection is only used when no good alternative is possible - Is executed directly for optimal performance */ ua = function() { var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF, u = nav.userAgent.toLowerCase(), p = nav.platform.toLowerCase(), windows = p ? /win/.test(p) : /win/.test(u), mac = p ? /mac/.test(p) : /mac/.test(u), webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html playerVersion = [0,0,0], d = null; if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) { d = nav.plugins[SHOCKWAVE_FLASH].description; if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+ plugin = true; ie = false; // cascaded feature detection for Internet Explorer d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10); playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10); playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0; } } else if (typeof win.ActiveXObject != UNDEF) { try { var a = new ActiveXObject(SHOCKWAVE_FLASH_AX); if (a) { // a will return null when ActiveX is disabled d = a.GetVariable("$version"); if (d) { ie = true; // cascaded feature detection for Internet Explorer d = d.split(" ")[1].split(","); playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } } catch(e) {} } return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac }; }(); function callDomLoadFunctions() { if (isDomLoaded) { return; } isDomLoaded = true; var dl = domLoadFnArr.length; for (var i = 0; i < dl; i++) { domLoadFnArr[i](); } } function addDomLoadEvent(fn) { if (isDomLoaded) { fn(); } else { domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+ } } /* Main function - Will preferably execute onDomLoad, otherwise onload (as a fallback) */ function main() { if (plugin) { testPlayerVersion(); } } /* Detect the Flash Player version for non-Internet Explorer browsers - Detecting the plug-in version via the object element is more precise than using the plugins collection item's description: a. Both release and build numbers can be detected b. Avoid wrong descriptions by corrupt installers provided by Adobe c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports - Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available */ function testPlayerVersion() { var b = doc.getElementsByTagName("body")[0]; var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); var t = b.appendChild(o); if (t) { var counter = 0; (function(){ if (typeof t.GetVariable != UNDEF) { var d = t.GetVariable("$version"); if (d) { d = d.split(" ")[1].split(","); ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } else if (counter < 10) { counter++; setTimeout(arguments.callee, 10); return; } b.removeChild(o); t = null; })(); } } function createElement(el) { return doc.createElement(el); } /* Flash Player and SWF content version matching */ function hasPlayerVersion(rv) { var pv = ua.pv, v = rv.split("."); v[0] = parseInt(v[0], 10); v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0" v[2] = parseInt(v[2], 10) || 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])) ? true : false; } webshims.ready('DOM', callDomLoadFunctions); webshims.loader.addModule('swfmini-embed', {d: ['swfmini']}); var loadEmbed = hasPlayerVersion('9.0.0') ? function(){ webshims.loader.loadList(['swfmini-embed']); return true; } : webshims.$.noop ; if(!webshims.support.mediaelement){ loadEmbed(); } else { webshims.ready('WINDOWLOAD', loadEmbed); } return { /* Public API - Reference: http://code.google.com/p/swfobject/wiki/documentation */ registerObject: wasRemoved, getObjectById: wasRemoved, embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) { var args = arguments; if(loadEmbed()){ webshims.ready('swfmini-embed', function(){ swfmini.embedSWF.apply(swfmini, args); }); } else if(callbackFn) { callbackFn({success:false, id:replaceElemIdStr}); } }, switchOffAutoHideShow: function() { autoHideShow = false; }, ua: ua, getFlashPlayerVersion: function() { return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] }; }, hasFlashPlayerVersion: hasPlayerVersion, createSWF: function(attObj, parObj, replaceElemIdStr) { if (ua.w3) { return createSWF(attObj, parObj, replaceElemIdStr); } else { return undefined; } }, showExpressInstall: wasRemoved, removeSWF: wasRemoved, createCSS: wasRemoved, addDomLoadEvent: addDomLoadEvent, addLoadEvent: wasRemoved, // For internal usage only expressInstallCallback: wasRemoved }; }(); webshims.isReady('swfmini', true); ; //this might was already extended by ES5 shim feature (function($){ "use strict"; var webshims = window.webshims; if(webshims.defineProperties){return;} var defineProperty = 'defineProperty'; var has = Object.prototype.hasOwnProperty; var descProps = ['configurable', 'enumerable', 'writable']; var extendUndefined = function(prop){ for(var i = 0; i < 3; i++){ if(prop[descProps[i]] === undefined && (descProps[i] !== 'writable' || prop.value !== undefined)){ prop[descProps[i]] = true; } } }; var extendProps = function(props){ if(props){ for(var i in props){ if(has.call(props, i)){ extendUndefined(props[i]); } } } }; if(Object.create){ webshims.objectCreate = function(proto, props, opts){ extendProps(props); var o = Object.create(proto, props); if(opts){ o.options = $.extend(true, {}, o.options || {}, opts); opts = o.options; } if(o._create && $.isFunction(o._create)){ o._create(opts); } return o; }; } if(Object[defineProperty]){ webshims[defineProperty] = function(obj, prop, desc){ extendUndefined(desc); return Object[defineProperty](obj, prop, desc); }; } if(Object.defineProperties){ webshims.defineProperties = function(obj, props){ extendProps(props); return Object.defineProperties(obj, props); }; } webshims.getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; webshims.getPrototypeOf = Object.getPrototypeOf; })(window.webshims.$); //DOM-Extension helper webshims.register('dom-extend', function($, webshims, window, document, undefined){ "use strict"; var supportHrefNormalized = !('hrefNormalized' in $.support) || $.support.hrefNormalized; var has = Object.prototype.hasOwnProperty; webshims.assumeARIA = true; if($('<input type="email" />').attr('type') == 'text' || $('<form />').attr('novalidate') === "" || ('required' in $('<input />')[0].attributes)){ webshims.error("IE browser modes are busted in IE10+. Make sure to run IE in edge mode (X-UA-Compatible). Please test your HTML/CSS/JS with a real IE version or at least IETester or similar tools. "); } if (!webshims.cfg.no$Switch) { var switch$ = function(){ if (window.jQuery && (!window.$ || window.jQuery == window.$) && !window.jQuery.webshims) { webshims.error("jQuery was included more than once. Make sure to include it only once or try the $.noConflict(extreme) feature! Webshims and other Plugins might not work properly. Or set webshims.cfg.no$Switch to 'true'."); if (window.$) { window.$ = webshims.$; } window.jQuery = webshims.$; } }; switch$(); setTimeout(switch$, 90); webshims.ready('DOM', switch$); $(switch$); webshims.ready('WINDOWLOAD', switch$); } //shortcus var listReg = /\s*,\s*/; //proxying attribute var olds = {}; var havePolyfill = {}; var hasPolyfillMethod = {}; var extendedProps = {}; var extendQ = {}; var modifyProps = {}; var oldVal = $.fn.val; var singleVal = function(elem, name, val, pass, _argless){ return (_argless) ? oldVal.call($(elem)) : oldVal.call($(elem), val); }; //jquery mobile and jquery ui if(!$.widget){ (function(){ var _cleanData = $.cleanData; $.cleanData = function( elems ) { if(!$.widget){ for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } } _cleanData( elems ); }; })(); } $.fn.val = function(val){ var elem = this[0]; if(arguments.length && val == null){ val = ''; } if(!arguments.length){ if(!elem || elem.nodeType !== 1){return oldVal.call(this);} return $.prop(elem, 'value', val, 'val', true); } if($.isArray(val)){ return oldVal.apply(this, arguments); } var isFunction = $.isFunction(val); return this.each(function(i){ elem = this; if(elem.nodeType === 1){ if(isFunction){ var genVal = val.call( elem, i, $.prop(elem, 'value', undefined, 'val', true)); if(genVal == null){ genVal = ''; } $.prop(elem, 'value', genVal, 'val') ; } else { $.prop(elem, 'value', val, 'val'); } } }); }; $.fn.onTrigger = function(evt, fn){ return this.on(evt, fn).each(fn); }; $.fn.onWSOff = function(evt, fn, trigger, evtDel){ if(!evtDel){ evtDel = document; } $(evtDel)[trigger ? 'onTrigger' : 'on'](evt, fn); this.on('remove', function(e){ if(!e.originalEvent){ $(evtDel).off(evt, fn); } }); return this; }; var idCount = 0; var dataID = '_webshims'+ (Math.round(Math.random() * 1000)); var elementData = function(elem, key, val){ elem = elem.jquery ? elem[0] : elem; if(!elem){return val || {};} var data = $.data(elem, dataID); if(val !== undefined){ if(!data){ data = $.data(elem, dataID, {}); } if(key){ data[key] = val; } } return key ? data && data[key] : data; }; [{name: 'getNativeElement', prop: 'nativeElement'}, {name: 'getShadowElement', prop: 'shadowElement'}, {name: 'getShadowFocusElement', prop: 'shadowFocusElement'}].forEach(function(data){ $.fn[data.name] = function(){ var elems = []; this.each(function(){ var shadowData = elementData(this, 'shadowData'); var elem = shadowData && shadowData[data.prop] || this; if($.inArray(elem, elems) == -1){ elems.push(elem); } }); return this.pushStack(elems); }; }); function clone(elem, dataAndEvents, uniqueIds){ var cloned = $.clone( elem, dataAndEvents, false ); $(cloned.querySelectorAll('.'+webshims.shadowClass)).detach(); if(uniqueIds){ idCount++; $(cloned.querySelectorAll('[id]')).prop('id', function(i, id){ return id +idCount; }); } else { $(cloned.querySelectorAll('audio[id^="ID-"], video[id^="ID-"], label[id^="ID-"]')).removeAttr('id'); } return cloned; } $.fn.clonePolyfill = function(dataAndEvents, uniqueIds){ dataAndEvents = dataAndEvents || false; return this .map(function() { var cloned = clone( this, dataAndEvents, uniqueIds ); setTimeout(function(){ if($.contains(document.body, cloned)){ $(cloned).updatePolyfill(); } }); return cloned; }) ; }; //add support for $('video').trigger('play') in case extendNative is set to false if(!webshims.cfg.extendNative && !webshims.cfg.noTriggerOverride){ (function(oldTrigger){ $.event.trigger = function(event, data, elem, onlyHandlers){ if(!hasPolyfillMethod[event] || onlyHandlers || !elem || elem.nodeType !== 1){ return oldTrigger.apply(this, arguments); } var ret, isOrig, origName; var origFn = elem[event]; var polyfilledFn = $.prop(elem, event); var changeFn = polyfilledFn && origFn != polyfilledFn; if(changeFn){ origName = '__ws'+event; isOrig = (event in elem) && has.call(elem, event); elem[event] = polyfilledFn; elem[origName] = origFn; } ret = oldTrigger.apply(this, arguments); if (changeFn) { if(isOrig){ elem[event] = origFn; } else { delete elem[event]; } delete elem[origName]; } return ret; }; })($.event.trigger); } ['removeAttr', 'prop', 'attr'].forEach(function(type){ olds[type] = $[type]; $[type] = function(elem, name, value, pass, _argless){ var isVal = (pass == 'val'); var oldMethod = !isVal ? olds[type] : singleVal; if( !elem || !havePolyfill[name] || elem.nodeType !== 1 || (!isVal && pass && type == 'attr' && $.attrFn[name]) ){ return oldMethod(elem, name, value, pass, _argless); } var nodeName = (elem.nodeName || '').toLowerCase(); var desc = extendedProps[nodeName]; var curType = (type == 'attr' && (value === false || value === null)) ? 'removeAttr' : type; var propMethod; var oldValMethod; var ret; if(!desc){ desc = extendedProps['*']; } if(desc){ desc = desc[name]; } if(desc){ propMethod = desc[curType]; } if(propMethod){ if(name == 'value'){ oldValMethod = propMethod.isVal; propMethod.isVal = isVal; } if(curType === 'removeAttr'){ return propMethod.value.call(elem); } else if(value === undefined){ return (propMethod.get) ? propMethod.get.call(elem) : propMethod.value ; } else if(propMethod.set) { if(type == 'attr' && value === true){ value = name; } ret = propMethod.set.call(elem, value); } if(name == 'value'){ propMethod.isVal = oldValMethod; } } else { ret = oldMethod(elem, name, value, pass, _argless); } if((value !== undefined || curType === 'removeAttr') && modifyProps[nodeName] && modifyProps[nodeName][name]){ var boolValue; if(curType == 'removeAttr'){ boolValue = false; } else if(curType == 'prop'){ boolValue = !!(value); } else { boolValue = true; } modifyProps[nodeName][name].forEach(function(fn){ if(!fn.only || (fn.only = 'prop' && type == 'prop') || (fn.only == 'attr' && type != 'prop')){ fn.call(elem, value, boolValue, (isVal) ? 'val' : curType, type); } }); } return ret; }; extendQ[type] = function(nodeName, prop, desc){ if(!extendedProps[nodeName]){ extendedProps[nodeName] = {}; } if(!extendedProps[nodeName][prop]){ extendedProps[nodeName][prop] = {}; } var oldDesc = extendedProps[nodeName][prop][type]; var getSup = function(propType, descriptor, oDesc){ var origProp; if(descriptor && descriptor[propType]){ return descriptor[propType]; } if(oDesc && oDesc[propType]){ return oDesc[propType]; } if(type == 'prop' && prop == 'value'){ return function(value){ var elem = this; return (desc.isVal) ? singleVal(elem, prop, value, false, (arguments.length === 0)) : olds[type](elem, prop, value) ; }; } if(type == 'prop' && propType == 'value' && desc.value.apply){ origProp = '__ws'+prop; hasPolyfillMethod[prop] = true; return function(value){ var sup = this[origProp] || olds[type](this, prop); if(sup && sup.apply){ sup = sup.apply(this, arguments); } return sup; }; } return function(value){ return olds[type](this, prop, value); }; }; extendedProps[nodeName][prop][type] = desc; if(desc.value === undefined){ if(!desc.set){ desc.set = desc.writeable ? getSup('set', desc, oldDesc) : (webshims.cfg.useStrict && prop == 'prop') ? function(){throw(prop +' is readonly on '+ nodeName);} : function(){webshims.info(prop +' is readonly on '+ nodeName);} ; } if(!desc.get){ desc.get = getSup('get', desc, oldDesc); } } ['value', 'get', 'set'].forEach(function(descProp){ if(desc[descProp]){ desc['_sup'+descProp] = getSup(descProp, oldDesc); } }); }; }); var extendNativeValue = (function(){ var UNKNOWN = webshims.getPrototypeOf(document.createElement('foobar')); //see also: https://github.com/lojjic/PIE/issues/40 | https://prototype.lighthouseapp.com/projects/8886/tickets/1107-ie8-fatal-crash-when-prototypejs-is-loaded-with-rounded-cornershtc var isExtendNativeSave = webshims.support.advancedObjectProperties && webshims.support.objectAccessor; return function(nodeName, prop, desc){ var elem , elemProto; if( isExtendNativeSave && (elem = document.createElement(nodeName)) && (elemProto = webshims.getPrototypeOf(elem)) && UNKNOWN !== elemProto && ( !elem[prop] || !has.call(elem, prop) ) ){ var sup = elem[prop]; desc._supvalue = function(){ if(sup && sup.apply){ return sup.apply(this, arguments); } return sup; }; elemProto[prop] = desc.value; } else { desc._supvalue = function(){ var data = elementData(this, 'propValue'); if(data && data[prop] && data[prop].apply){ return data[prop].apply(this, arguments); } return data && data[prop]; }; initProp.extendValue(nodeName, prop, desc.value); } desc.value._supvalue = desc._supvalue; }; })(); var initProp = (function(){ var initProps = {}; webshims.addReady(function(context, contextElem){ var nodeNameCache = {}; var getElementsByName = function(name){ if(!nodeNameCache[name]){ nodeNameCache[name] = $(context.getElementsByTagName(name)); if(contextElem[0] && $.nodeName(contextElem[0], name)){ nodeNameCache[name] = nodeNameCache[name].add(contextElem); } } }; $.each(initProps, function(name, fns){ getElementsByName(name); if(!fns || !fns.forEach){ webshims.warn('Error: with '+ name +'-property. methods: '+ fns); return; } fns.forEach(function(fn){ nodeNameCache[name].each(fn); }); }); nodeNameCache = null; }); var tempCache; var emptyQ = $([]); var createNodeNameInit = function(nodeName, fn){ if(!initProps[nodeName]){ initProps[nodeName] = [fn]; } else { initProps[nodeName].push(fn); } if($.isDOMReady){ (tempCache || $( document.getElementsByTagName(nodeName) )).each(fn); } }; return { createTmpCache: function(nodeName){ if($.isDOMReady){ tempCache = tempCache || $( document.getElementsByTagName(nodeName) ); } return tempCache || emptyQ; }, flushTmpCache: function(){ tempCache = null; }, content: function(nodeName, prop){ createNodeNameInit(nodeName, function(){ var val = $.attr(this, prop); if(val != null){ $.attr(this, prop, val); } }); }, createElement: function(nodeName, fn){ createNodeNameInit(nodeName, fn); }, extendValue: function(nodeName, prop, value){ createNodeNameInit(nodeName, function(){ $(this).each(function(){ var data = elementData(this, 'propValue', {}); data[prop] = this[prop]; this[prop] = value; }); }); } }; })(); var createPropDefault = function(descs, removeType){ if(descs.defaultValue === undefined){ descs.defaultValue = ''; } if(!descs.removeAttr){ descs.removeAttr = { value: function(){ descs[removeType || 'prop'].set.call(this, descs.defaultValue); descs.removeAttr._supvalue.call(this); } }; } if(!descs.attr){ descs.attr = {}; } }; $.extend(webshims, { xProps: havePolyfill, getID: (function(){ var ID = new Date().getTime(); return function(elem){ elem = $(elem); var id = elem.prop('id'); if(!id){ ID++; id = 'ID-'+ ID; elem.eq(0).prop('id', id); } return id; }; })(), domPrefixes: ["ws", "webkit", "moz", "ms", "o"], prefixed: function (prop, obj){ var i, testProp; var ret = false; if(obj[prop]){ ret = prop; } if(!ret){ prop = prop.charAt(0).toUpperCase() + prop.slice(1); for(i = 0; i < webshims.domPrefixes.length; i++){ testProp = webshims.domPrefixes[i]+prop; if(testProp in obj){ ret = testProp; break; } } } return ret; }, shadowClass: 'wsshadow-'+(Date.now()), implement: function(elem, type){ var data = elementData(elem, 'implemented') || elementData(elem, 'implemented', {}); if(data[type]){ webshims.warn(type +' already implemented for element #'+elem.id); return false; } data[type] = true; return !$(elem).hasClass('ws-nopolyfill'); }, extendUNDEFProp: function(obj, props){ $.each(props, function(name, prop){ if( !(name in obj) ){ obj[name] = prop; } }); }, getOptions: (function(){ var normalName = /\-([a-z])/g; var regs = {}; var nameRegs = {}; var regFn = function(f, upper){ return upper.toLowerCase(); }; var nameFn = function(f, dashed){ return dashed.toUpperCase(); }; return function(elem, name, bases, stringAllowed){ if(nameRegs[name]){ name = nameRegs[name]; } else { nameRegs[name] = name.replace(normalName, nameFn); name = nameRegs[name]; } var data = elementData(elem, 'cfg'+name); var dataName; var cfg = {}; if(data){ return data; } data = $(elem).data(); if(data && typeof data[name] == 'string'){ if(stringAllowed){ return elementData(elem, 'cfg'+name, data[name]); } webshims.error('data-'+ name +' attribute has to be a valid JSON, was: '+ data[name]); } if(!bases){ bases = [true, {}]; } else if(!Array.isArray(bases)){ bases = [true, {}, bases]; } else { bases.unshift(true, {}); } if(data && typeof data[name] == 'object'){ bases.push(data[name]); } if(!regs[name]){ regs[name] = new RegExp('^'+ name +'([A-Z])'); } for(dataName in data){ if(regs[name].test(dataName)){ cfg[dataName.replace(regs[name], regFn)] = data[dataName]; } } bases.push(cfg); return elementData(elem, 'cfg'+name, $.extend.apply($, bases)); }; })(), //http://www.w3.org/TR/html5/common-dom-interfaces.html#reflect createPropDefault: createPropDefault, data: elementData, moveToFirstEvent: function(elem, eventType, bindType){ var events = ($._data(elem, 'events') || {})[eventType]; var fn; if(events && events.length > 1){ fn = events.pop(); if(!bindType){ bindType = 'bind'; } if(bindType == 'bind' && events.delegateCount){ events.splice( events.delegateCount, 0, fn); } else { events.unshift( fn ); } } elem = null; }, addShadowDom: (function(){ var resizeTimer; var lastHeight; var lastWidth; var $window = $(window); var docObserve = { init: false, runs: 0, test: function(){ var height = docObserve.getHeight(); var width = docObserve.getWidth(); if(height != docObserve.height || width != docObserve.width){ docObserve.height = height; docObserve.width = width; docObserve.handler({type: 'docresize'}); docObserve.runs++; if(docObserve.runs < 9){ setTimeout(docObserve.test, 90); } } else { docObserve.runs = 0; } }, handler: (function(){ var evt; var trigger = function(){ $(document).triggerHandler('updateshadowdom', [evt]); }; var timed = function(){ if(evt && evt.type == 'resize'){ var width = $window.width(); var height = $window.width(); if(height == lastHeight && width == lastWidth){ return; } lastHeight = height; lastWidth = width; } if(evt && evt.type != 'docresize'){ docObserve.height = docObserve.getHeight(); docObserve.width = docObserve.getWidth(); } if(window.requestAnimationFrame){ requestAnimationFrame(trigger); } else { setTimeout(trigger, 0); } }; return function(e){ clearTimeout(resizeTimer); evt = e; resizeTimer = setTimeout(timed, (e.type == 'resize' && !window.requestAnimationFrame) ? 50 : 9); }; })(), _create: function(){ $.each({ Height: "getHeight", Width: "getWidth" }, function(name, type){ var body = document.body; var doc = document.documentElement; docObserve[type] = function (){ return Math.max( body[ "scroll" + name ], doc[ "scroll" + name ], body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); }; }); }, start: function(){ if(!this.init && document.body){ this.init = true; this._create(); this.height = docObserve.getHeight(); this.width = docObserve.getWidth(); setInterval(this.test, 999); $(this.test); if($.support.boxSizing == null){ $(function(){ if($.support.boxSizing){ docObserve.handler({type: 'boxsizing'}); } }); } webshims.ready('WINDOWLOAD', this.test); $(document).on('updatelayout.webshim pageinit popupafteropen panelbeforeopen tabsactivate collapsibleexpand shown.bs.modal shown.bs.collapse slid.bs.carousel playerdimensionchange', this.handler); $(window).on('resize', this.handler); } } }; webshims.docObserve = function(){ webshims.ready('DOM', function(){ docObserve.start(); }); }; return function(nativeElem, shadowElem, opts){ if(nativeElem && shadowElem){ opts = opts || {}; if(nativeElem.jquery){ nativeElem = nativeElem[0]; } if(shadowElem.jquery){ shadowElem = shadowElem[0]; } var nativeData = $.data(nativeElem, dataID) || $.data(nativeElem, dataID, {}); var shadowData = $.data(shadowElem, dataID) || $.data(shadowElem, dataID, {}); var shadowFocusElementData = {}; if(!opts.shadowFocusElement){ opts.shadowFocusElement = shadowElem; } else if(opts.shadowFocusElement){ if(opts.shadowFocusElement.jquery){ opts.shadowFocusElement = opts.shadowFocusElement[0]; } shadowFocusElementData = $.data(opts.shadowFocusElement, dataID) || $.data(opts.shadowFocusElement, dataID, shadowFocusElementData); } $(nativeElem).on('remove', function(e){ if (!e.originalEvent) { setTimeout(function(){ $(shadowElem).remove(); }, 4); } }); nativeData.hasShadow = shadowElem; shadowFocusElementData.nativeElement = shadowData.nativeElement = nativeElem; shadowFocusElementData.shadowData = shadowData.shadowData = nativeData.shadowData = { nativeElement: nativeElem, shadowElement: shadowElem, shadowFocusElement: opts.shadowFocusElement }; if(opts.shadowChilds){ opts.shadowChilds.each(function(){ elementData(this, 'shadowData', shadowData.shadowData); }); } if(opts.data){ shadowFocusElementData.shadowData.data = shadowData.shadowData.data = nativeData.shadowData.data = opts.data; } opts = null; } webshims.docObserve(); }; })(), propTypes: { standard: function(descs, name){ createPropDefault(descs); if(descs.prop){return;} descs.prop = { set: function(val){ descs.attr.set.call(this, ''+val); }, get: function(){ return descs.attr.get.call(this) || descs.defaultValue; } }; }, "boolean": function(descs, name){ createPropDefault(descs); if(descs.prop){return;} descs.prop = { set: function(val){ if(val){ descs.attr.set.call(this, ""); } else { descs.removeAttr.value.call(this); } }, get: function(){ return descs.attr.get.call(this) != null; } }; }, "src": (function(){ var anchor = document.createElement('a'); anchor.style.display = "none"; return function(descs, name){ createPropDefault(descs); if(descs.prop){return;} descs.prop = { set: function(val){ descs.attr.set.call(this, val); }, get: function(){ var href = this.getAttribute(name); var ret; if(href == null){return '';} anchor.setAttribute('href', href+'' ); if(!supportHrefNormalized){ try { $(anchor).insertAfter(this); ret = anchor.getAttribute('href', 4); } catch(er){ ret = anchor.getAttribute('href', 4); } $(anchor).detach(); } return ret || anchor.href; } }; }; })(), enumarated: function(descs, name){ createPropDefault(descs); if(descs.prop){return;} descs.prop = { set: function(val){ descs.attr.set.call(this, val); }, get: function(){ var val = (descs.attr.get.call(this) || '').toLowerCase(); if(!val || descs.limitedTo.indexOf(val) == -1){ val = descs.defaultValue; } return val; } }; } // ,unsignedLong: $.noop // ,"doubble": $.noop // ,"long": $.noop // ,tokenlist: $.noop // ,settableTokenlist: $.noop }, reflectProperties: function(nodeNames, props){ if(typeof props == 'string'){ props = props.split(listReg); } props.forEach(function(prop){ webshims.defineNodeNamesProperty(nodeNames, prop, { prop: { set: function(val){ $.attr(this, prop, val); }, get: function(){ return $.attr(this, prop) || ''; } } }); }); }, defineNodeNameProperty: function(nodeName, prop, descs){ havePolyfill[prop] = true; if(descs.reflect){ if(descs.propType && !webshims.propTypes[descs.propType]){ webshims.error('could not finde propType '+ descs.propType); } else { webshims.propTypes[descs.propType || 'standard'](descs, prop); } } ['prop', 'attr', 'removeAttr'].forEach(function(type){ var desc = descs[type]; if(desc){ if(type === 'prop'){ desc = $.extend({writeable: true}, desc); } else { desc = $.extend({}, desc, {writeable: true}); } extendQ[type](nodeName, prop, desc); if(nodeName != '*' && webshims.cfg.extendNative && type == 'prop' && desc.value && $.isFunction(desc.value)){ extendNativeValue(nodeName, prop, desc); } descs[type] = desc; } }); if(descs.initAttr){ initProp.content(nodeName, prop); } return descs; }, defineNodeNameProperties: function(name, descs, propType, _noTmpCache){ var olddesc; for(var prop in descs){ if(!_noTmpCache && descs[prop].initAttr){ initProp.createTmpCache(name); } if(propType){ if(descs[prop][propType]){ //webshims.log('override: '+ name +'['+prop +'] for '+ propType); } else { descs[prop][propType] = {}; ['value', 'set', 'get'].forEach(function(copyProp){ if(copyProp in descs[prop]){ descs[prop][propType][copyProp] = descs[prop][copyProp]; delete descs[prop][copyProp]; } }); } } descs[prop] = webshims.defineNodeNameProperty(name, prop, descs[prop]); } if(!_noTmpCache){ initProp.flushTmpCache(); } return descs; }, createElement: function(nodeName, create, descs){ var ret; if($.isFunction(create)){ create = { after: create }; } initProp.createTmpCache(nodeName); if(create.before){ initProp.createElement(nodeName, create.before); } if(descs){ ret = webshims.defineNodeNameProperties(nodeName, descs, false, true); } if(create.after){ initProp.createElement(nodeName, create.after); } initProp.flushTmpCache(); return ret; }, onNodeNamesPropertyModify: function(nodeNames, props, desc, only){ if(typeof nodeNames == 'string'){ nodeNames = nodeNames.split(listReg); } if($.isFunction(desc)){ desc = {set: desc}; } nodeNames.forEach(function(name){ if(!modifyProps[name]){ modifyProps[name] = {}; } if(typeof props == 'string'){ props = props.split(listReg); } if(desc.initAttr){ initProp.createTmpCache(name); } props.forEach(function(prop){ if(!modifyProps[name][prop]){ modifyProps[name][prop] = []; havePolyfill[prop] = true; } if(desc.set){ if(only){ desc.set.only = only; } modifyProps[name][prop].push(desc.set); } if(desc.initAttr){ initProp.content(name, prop); } }); initProp.flushTmpCache(); }); }, defineNodeNamesBooleanProperty: function(elementNames, prop, descs){ if(!descs){ descs = {}; } if($.isFunction(descs)){ descs.set = descs; } webshims.defineNodeNamesProperty(elementNames, prop, { attr: { set: function(val){ if(descs.useContentAttribute){ webshims.contentAttr(this, prop, val); } else { this.setAttribute(prop, val); } if(descs.set){ descs.set.call(this, true); } }, get: function(){ var ret = (descs.useContentAttribute) ? webshims.contentAttr(this, prop) : this.getAttribute(prop); return (ret == null) ? undefined : prop; } }, removeAttr: { value: function(){ this.removeAttribute(prop); if(descs.set){ descs.set.call(this, false); } } }, reflect: true, propType: 'boolean', initAttr: descs.initAttr || false }); }, contentAttr: function(elem, name, val){ if(!elem.nodeName){return;} var attr; if(val === undefined){ attr = (elem.attributes[name] || {}); val = attr.specified ? attr.value : null; return (val == null) ? undefined : val; } if(typeof val == 'boolean'){ if(!val){ elem.removeAttribute(name); } else { elem.setAttribute(name, name); } } else { elem.setAttribute(name, val); } }, activeLang: (function(){ var curLang = []; var langDatas = []; var loading = {}; var load = function(src, obj, loadingLang){ obj._isLoading = true; if(loading[src]){ loading[src].push(obj); } else { loading[src] = [obj]; webshims.loader.loadScript(src, function(){ if(loadingLang == curLang.join()){ $.each(loading[src], function(i, obj){ select(obj); }); } delete loading[src]; }); } }; var select = function(obj){ var oldLang = obj.__active; var selectLang = function(i, lang){ obj._isLoading = false; if(obj[lang] || obj.availableLangs.indexOf(lang) != -1){ if(obj[lang]){ obj.__active = obj[lang]; obj.__activeName = lang; } else { load(obj.langSrc+lang, obj, curLang.join()); } return false; } }; $.each(curLang, selectLang); if(!obj.__active){ obj.__active = obj['']; obj.__activeName = ''; } if(oldLang != obj.__active){ $(obj).trigger('change'); } }; return function(lang){ var shortLang; if(typeof lang == 'string'){ if(curLang[0] != lang){ curLang = [lang]; shortLang = curLang[0].split('-')[0]; if(shortLang && shortLang != lang){ curLang.push(shortLang); } langDatas.forEach(select); } } else if(typeof lang == 'object'){ if(!lang.__active){ langDatas.push(lang); select(lang); } return lang.__active; } return curLang[0]; }; })() }); $.each({ defineNodeNamesProperty: 'defineNodeNameProperty', defineNodeNamesProperties: 'defineNodeNameProperties', createElements: 'createElement' }, function(name, baseMethod){ webshims[name] = function(names, a, b, c){ if(typeof names == 'string'){ names = names.split(listReg); } var retDesc = {}; names.forEach(function(nodeName){ retDesc[nodeName] = webshims[baseMethod](nodeName, a, b, c); }); return retDesc; }; }); webshims.isReady('webshimLocalization', true); //html5a11y + hidden attribute (function(){ if(('content' in document.createElement('template'))){return;} $(function(){ var main = $('main').attr({role: 'main'}); if(main.length > 1){ webshims.error('only one main element allowed in document'); } else if(main.is('article *, section *')) { webshims.error('main not allowed inside of article/section elements'); } }); if(('hidden' in document.createElement('a'))){ return; } webshims.defineNodeNamesBooleanProperty(['*'], 'hidden'); var elemMappings = { article: "article", aside: "complementary", section: "region", nav: "navigation", address: "contentinfo" }; var addRole = function(elem, role){ var hasRole = elem.getAttribute('role'); if (!hasRole) { elem.setAttribute('role', role); } }; $.webshims.addReady(function(context, contextElem){ $.each(elemMappings, function(name, role){ var elems = $(name, context).add(contextElem.filter(name)); for (var i = 0, len = elems.length; i < len; i++) { addRole(elems[i], role); } }); if (context === document) { var header = document.getElementsByTagName('header')[0]; var footers = document.getElementsByTagName('footer'); var footerLen = footers.length; if (header && !$(header).closest('section, article')[0]) { addRole(header, 'banner'); } if (!footerLen) { return; } var footer = footers[footerLen - 1]; if (!$(footer).closest('section, article')[0]) { addRole(footer, 'contentinfo'); } } }); })(); }); ;webshims.register('form-core', function($, webshims, window, document, undefined, options){ "use strict"; webshims.capturingEventPrevented = function(e){ if(!e._isPolyfilled){ var isDefaultPrevented = e.isDefaultPrevented; var preventDefault = e.preventDefault; e.preventDefault = function(){ clearTimeout($.data(e.target, e.type + 'DefaultPrevented')); $.data(e.target, e.type + 'DefaultPrevented', setTimeout(function(){ $.removeData(e.target, e.type + 'DefaultPrevented'); }, 30)); return preventDefault.apply(this, arguments); }; e.isDefaultPrevented = function(){ return !!(isDefaultPrevented.apply(this, arguments) || $.data(e.target, e.type + 'DefaultPrevented') || false); }; e._isPolyfilled = true; } }; var modules = webshims.modules; var support = webshims.support; var isValid = function(elem){ return ($.prop(elem, 'validity') || {valid: 1}).valid; }; var lazyLoad = function(){ var toLoad = ['form-validation']; $(document).off('.lazyloadvalidation'); if(options.lazyCustomMessages){ options.customMessages = true; toLoad.push('form-message'); } if(webshims._getAutoEnhance(options.customDatalist)){ options.fD = true; toLoad.push('form-datalist'); } if(options.addValidators){ toLoad.push('form-validators'); } webshims.reTest(toLoad); }; /* * Selectors for all browsers */ var extendSels = function(){ var matches, matchesOverride; var exp = $.expr[":"]; var rElementsGroup = /^(?:form|fieldset)$/i; var hasInvalid = function(elem){ var ret = false; $(elem).jProp('elements').each(function(){ if(!rElementsGroup.test(this.nodeName || '')){ ret = exp.invalid(this); if(ret){ return false; } } }); return ret; }; $.extend(exp, { "valid-element": function(elem){ return rElementsGroup.test(elem.nodeName || '') ? !hasInvalid(elem) : !!($.prop(elem, 'willValidate') && isValid(elem)); }, "invalid-element": function(elem){ return rElementsGroup.test(elem.nodeName || '') ? hasInvalid(elem) : !!($.prop(elem, 'willValidate') && !isValid(elem)); }, "required-element": function(elem){ return !!($.prop(elem, 'willValidate') && $.prop(elem, 'required')); }, "user-error": function(elem){ return ($.prop(elem, 'willValidate') && $(elem).getShadowElement().hasClass((options.iVal.errorClass || 'user-error'))); }, "optional-element": function(elem){ return !!($.prop(elem, 'willValidate') && $.prop(elem, 'required') === false); } }); ['valid', 'invalid', 'required', 'optional'].forEach(function(name){ exp[name] = $.expr[":"][name+"-element"]; }); // sizzle/jQuery has a bug with :disabled/:enabled selectors if(support.fieldsetdisabled && !$('<fieldset disabled=""><input /><input /></fieldset>').find(':disabled').filter(':disabled').is(':disabled')){ matches = $.find.matches; matchesOverride = {':disabled': 1, ':enabled': 1}; $.find.matches = function(expr, elements){ if(matchesOverride[expr]){ return matches.call(this, '*'+expr, elements); } return matches.apply(this, arguments); }; $.extend(exp, { "enabled": function( elem ) { return 'disabled' in elem && elem.disabled === false && !$.find.matchesSelector(elem, 'fieldset[disabled] *'); }, "disabled": function( elem ) { return elem.disabled === true || ('disabled' in elem && $.find.matchesSelector(elem, 'fieldset[disabled] *')); } }); } //bug was partially fixed in 1.10.0 for IE9, but not IE8 (move to es5 as soon as 1.10.2 is used) if(typeof document.activeElement == 'unknown'){ var pseudoFocus = exp.focus; exp.focus = function(){ try { return pseudoFocus.apply(this, arguments); } catch(e){ webshims.error(e); } return false; }; } }; var formExtras = { noAutoCallback: true, options: options }; var addModule = webshims.loader.addModule; var lazyLoadProxy = function(obj, fn, args){ lazyLoad(); webshims.ready('form-validation', function(){ obj[fn].apply(obj, args); }); }; var transClass = ('transitionDelay' in document.documentElement.style) ? '' : ' no-transition'; var poCFG = webshims.cfg.wspopover; addModule('form-validation', $.extend({d: ['form-message']}, formExtras)); addModule('form-validators', $.extend({}, formExtras)); if(support.formvalidation && !webshims.bugs.bustedValidity){ //create delegatable events webshims.capturingEvents(['invalid'], true); } if($.expr.filters){ extendSels(); } else { webshims.ready('sizzle', extendSels); } webshims.triggerInlineForm = function(elem, event){ $(elem).trigger(event); }; if(!poCFG.position && poCFG.position !== false){ poCFG.position = { at: 'left bottom', my: 'left top', collision: 'fit flip' }; } webshims.wsPopover = { id: 0, _create: function(){ this.options = $.extend(true, {}, poCFG, this.options); this.id = webshims.wsPopover.id++; this.eventns = '.wsoverlay' + this.id; this.timers = {}; this.element = $('<div class="ws-popover'+transClass+'" tabindex="-1"><div class="ws-po-outerbox"><div class="ws-po-arrow"><div class="ws-po-arrowbox" /></div><div class="ws-po-box" /></div></div>'); this.contentElement = $('.ws-po-box', this.element); this.lastElement = $([]); this.bindElement(); this.element.data('wspopover', this); }, options: {}, content: function(html){ this.contentElement.html(html); }, bindElement: function(){ var that = this; var stopBlur = function(){ that.stopBlur = false; }; this.preventBlur = function(e){ that.stopBlur = true; clearTimeout(that.timers.stopBlur); that.timers.stopBlur = setTimeout(stopBlur, 9); }; this.element.on({ 'mousedown': this.preventBlur }); }, show: function(){ lazyLoadProxy(this, 'show', arguments); } }; /* some extra validation UI */ webshims.validityAlert = { showFor: function(){ lazyLoadProxy(this, 'showFor', arguments); } }; webshims.getContentValidationMessage = function(elem, validity, key){ var customRule; if(webshims.errorbox && webshims.errorbox.initIvalContentMessage){ webshims.errorbox.initIvalContentMessage(elem); } var message = (webshims.getOptions && webshims.errorbox ? webshims.getOptions(elem, 'errormessage', false, true) : $(elem).data('errormessage')) || elem.getAttribute('x-moz-errormessage') || ''; if(key && message[key]){ message = message[key]; } else if(message) { validity = validity || $.prop(elem, 'validity') || {valid: 1}; if(validity.valid){ message = ''; } } if(typeof message == 'object'){ validity = validity || $.prop(elem, 'validity') || {valid: 1}; if(validity.customError && (customRule = $.data(elem, 'customMismatchedRule')) && message[customRule] && typeof message[customRule] == 'string'){ message = message[customRule]; } else if(!validity.valid){ $.each(validity, function(name, prop){ if(prop && name != 'valid' && message[name]){ message = message[name]; return false; } }); if(typeof message == 'object'){ if(validity.typeMismatch && message.badInput){ message = message.badInput; } if(validity.badInput && message.typeMismatch){ message = message.typeMismatch; } } } } if(typeof message == 'object'){ message = message.defaultMessage; } if(webshims.replaceValidationplaceholder){ message = webshims.replaceValidationplaceholder(elem, message); } return message || ''; }; $.fn.getErrorMessage = function(key){ var message = ''; var elem = this[0]; if(elem){ message = webshims.getContentValidationMessage(elem, false, key) || $.prop(elem, 'customValidationMessage') || $.prop(elem, 'validationMessage'); } return message; }; $.event.special.valuevalidation = { setup: function(){ webshims.error('valuevalidation was renamed to validatevalue!'); } }; $.event.special.validatevalue = { setup: function(){ var data = $(this).data() || $.data(this, {}); if(!('validatevalue' in data)){ data.validatevalue = true; } } }; $(document).on('focusin.lazyloadvalidation mousedown.lazyloadvalidation touchstart.lazyloadvalidation', function(e){ if('form' in e.target){ lazyLoad(); } }); webshims.ready('WINDOWLOAD', lazyLoad); if(modules['form-number-date-ui'].loaded && !options.customMessages && (modules['form-number-date-api'].test() || (support.inputtypes.range && support.inputtypes.color))){ webshims.isReady('form-number-date-ui', true); } webshims.ready('DOM', function(){ if(document.querySelector('.ws-custom-file')){ webshims.reTest(['form-validation']); } }); if(options.addValidators && options.fastValidators){ webshims.reTest(['form-validators', 'form-validation']); } if(document.readyState == 'complete'){ webshims.isReady('WINDOWLOAD', true); } }); ;webshims.register('form-datalist', function($, webshims, window, document, undefined, options){ "use strict"; var lazyLoad = function(name){ if(!name || typeof name != 'string'){ name = 'DOM'; } if(!lazyLoad[name+'Loaded']){ lazyLoad[name+'Loaded'] = true; webshims.ready(name, function(){ webshims.loader.loadList(['form-datalist-lazy']); }); } }; var noDatalistSupport = { submit: 1, button: 1, reset: 1, hidden: 1, range: 1, date: 1, month: 1 }; if(webshims.modules["form-number-date-ui"].loaded){ $.extend(noDatalistSupport, { number: 1, time: 1 }); } /* * implement propType "element" currently only used for list-attribute (will be moved to dom-extend, if needed) */ webshims.propTypes.element = function(descs, name){ webshims.createPropDefault(descs, 'attr'); if(descs.prop){return;} descs.prop = { get: function(){ var elem = $.attr(this, name); if(elem){ elem = document.getElementById(elem); if(elem && descs.propNodeName && !$.nodeName(elem, descs.propNodeName)){ elem = null; } } return elem || null; }, writeable: false }; }; /* * Implements datalist element and list attribute */ (function(){ var formsCFG = webshims.cfg.forms; var listSupport = webshims.support.datalist; if(listSupport && !formsCFG.customDatalist){return;} var initializeDatalist = function(){ var updateDatlistAndOptions = function(){ var id; if(!$.data(this, 'datalistWidgetData') && (id = $.prop(this, 'id'))){ $('input[list="'+ id +'"], input[data-wslist="'+ id +'"]').eq(0).attr('list', id); } else { $(this).triggerHandler('updateDatalist'); } }; var inputListProto = { //override autocomplete autocomplete: { attr: { get: function(){ var elem = this; var data = $.data(elem, 'datalistWidget'); if(data){ return data._autocomplete; } return ('autocomplete' in elem) ? elem.autocomplete : elem.getAttribute('autocomplete'); }, set: function(value){ var elem = this; var data = $.data(elem, 'datalistWidget'); if(data){ data._autocomplete = value; if(value == 'off'){ data.hideList(); } } else { if('autocomplete' in elem){ elem.autocomplete = value; } else { elem.setAttribute('autocomplete', value); } } } } } }; if(listSupport){ //options only return options, if option-elements are rooted: but this makes this part of HTML5 less backwards compatible if(!($('<datalist><select><option></option></select></datalist>').prop('options') || []).length ){ webshims.defineNodeNameProperty('datalist', 'options', { prop: { writeable: false, get: function(){ var options = this.options || []; if(!options.length){ var elem = this; var select = $('select', elem); if(select[0] && select[0].options && select[0].options.length){ options = select[0].options; } } return options; } } }); } inputListProto.list = { attr: { get: function(){ var val = webshims.contentAttr(this, 'list'); if(val != null){ $.data(this, 'datalistListAttr', val); if(!noDatalistSupport[$.prop(this, 'type')] && !noDatalistSupport[$.attr(this, 'type')]){ this.removeAttribute('list'); } } else { val = $.data(this, 'datalistListAttr'); } return (val == null) ? undefined : val; }, set: function(value){ var elem = this; $.data(elem, 'datalistListAttr', value); if (!noDatalistSupport[$.prop(this, 'type')] && !noDatalistSupport[$.attr(this, 'type')]) { webshims.objectCreate(shadowListProto, undefined, { input: elem, id: value, datalist: $.prop(elem, 'list') }); elem.setAttribute('data-wslist', value); } else { elem.setAttribute('list', value); } $(elem).triggerHandler('listdatalistchange'); } }, initAttr: true, reflect: true, propType: 'element', propNodeName: 'datalist' }; } else { webshims.defineNodeNameProperties('input', { list: { attr: { get: function(){ var val = webshims.contentAttr(this, 'list'); return (val == null) ? undefined : val; }, set: function(value){ var elem = this; webshims.contentAttr(elem, 'list', value); webshims.objectCreate(options.shadowListProto, undefined, {input: elem, id: value, datalist: $.prop(elem, 'list')}); $(elem).triggerHandler('listdatalistchange'); } }, initAttr: true, reflect: true, propType: 'element', propNodeName: 'datalist' } }); } webshims.defineNodeNameProperties('input', inputListProto); webshims.addReady(function(context, contextElem){ contextElem .filter('datalist > select, datalist, datalist > option, datalist > select > option') .closest('datalist') .each(updateDatlistAndOptions) ; }); }; /* * ShadowList */ var shadowListProto = { _create: function(opts){ if(noDatalistSupport[$.prop(opts.input, 'type')] || noDatalistSupport[$.attr(opts.input, 'type')]){return;} var datalist = opts.datalist; var data = $.data(opts.input, 'datalistWidget'); var that = this; if(datalist && data && data.datalist !== datalist){ data.datalist = datalist; data.id = opts.id; $(data.datalist) .off('updateDatalist.datalistWidget') .on('updateDatalist.datalistWidget', $.proxy(data, '_resetListCached')) ; data._resetListCached(); return; } else if(!datalist){ if(data){ data.destroy(); } return; } else if(data && data.datalist === datalist){ return; } this.datalist = datalist; this.id = opts.id; this.hasViewableData = true; this._autocomplete = $.attr(opts.input, 'autocomplete'); $.data(opts.input, 'datalistWidget', this); $.data(datalist, 'datalistWidgetData', this); lazyLoad('WINDOWLOAD'); if(webshims.isReady('form-datalist-lazy')){ if(window.QUnit){ that._lazyCreate(opts); } else { setTimeout(function(){ that._lazyCreate(opts); }, 9); } } else { $(opts.input).one('focus', lazyLoad); webshims.ready('form-datalist-lazy', function(){ if(!that._destroyed){ that._lazyCreate(opts); } }); } }, destroy: function(e){ var input; var autocomplete = $.attr(this.input, 'autocomplete'); $(this.input) .off('.datalistWidget') .removeData('datalistWidget') ; this.shadowList.remove(); $(document).off('.datalist'+this.id); $(window).off('.datalist'+this.id); if(this.input.form && this.input.id){ $(this.input.form).off('submit.datalistWidget'+this.input.id); } this.input.removeAttribute('aria-haspopup'); if(autocomplete === undefined){ this.input.removeAttribute('autocomplete'); } else { $(this.input).attr('autocomplete', autocomplete); } if(e && e.type == 'beforeunload'){ input = this.input; setTimeout(function(){ $.attr(input, 'list', $.attr(input, 'list')); }, 9); } this._destroyed = true; } }; webshims.loader.addModule('form-datalist-lazy', { noAutoCallback: true, options: $.extend(options, {shadowListProto: shadowListProto}) }); if(!options.list){ options.list = {}; } //init datalist update initializeDatalist(); })(); }); ;(function(webshims){ "use strict"; var support = webshims.support; var hasNative = support.mediaelement; var supportsLoop = false; var bugs = webshims.bugs; var swfType = 'mediaelement-jaris'; var loadSwf = function(){ webshims.ready(swfType, function(){ if(!webshims.mediaelement.createSWF){ webshims.mediaelement.loadSwf = true; webshims.reTest([swfType], hasNative); } }); }; var wsCfg = webshims.cfg; var options = wsCfg.mediaelement; var isIE = navigator.userAgent.indexOf('MSIE') != -1; if(!options){ webshims.error("mediaelement wasn't implemented but loaded"); return; } if(hasNative){ var videoElem = document.createElement('video'); support.videoBuffered = ('buffered' in videoElem); support.mediaDefaultMuted = ('defaultMuted' in videoElem); supportsLoop = ('loop' in videoElem); support.mediaLoop = supportsLoop; webshims.capturingEvents(['play', 'playing', 'waiting', 'paused', 'ended', 'durationchange', 'loadedmetadata', 'canplay', 'volumechange']); if( !support.videoBuffered || !supportsLoop || (!support.mediaDefaultMuted && isIE && 'ActiveXObject' in window) ){ webshims.addPolyfill('mediaelement-native-fix', { d: ['dom-support'] }); webshims.loader.loadList(['mediaelement-native-fix']); } } if(support.track && !bugs.track){ (function(){ if(!bugs.track){ if(window.VTTCue && !window.TextTrackCue){ window.TextTrackCue = window.VTTCue; } else if(!window.VTTCue){ window.VTTCue = window.TextTrackCue; } try { new VTTCue(2, 3, ''); } catch(e){ bugs.track = true; } } })(); } if(window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype){ CanvasRenderingContext2D.prototype.wsImageComplete = function(cb){ cb.call(this, this); }; } webshims.register('mediaelement-core', function($, webshims, window, document, undefined, options){ var hasSwf = swfmini.hasFlashPlayerVersion('11.3'); var mediaelement = webshims.mediaelement; var allowYtLoading = false; mediaelement.parseRtmp = function(data){ var src = data.src.split('://'); var paths = src[1].split('/'); var i, len, found; data.server = src[0]+'://'+paths[0]+'/'; data.streamId = []; for(i = 1, len = paths.length; i < len; i++){ if(!found && paths[i].indexOf(':') !== -1){ paths[i] = paths[i].split(':')[1]; found = true; } if(!found){ data.server += paths[i]+'/'; } else { data.streamId.push(paths[i]); } } if(!data.streamId.length){ webshims.error('Could not parse rtmp url'); } data.streamId = data.streamId.join('/'); }; var getSrcObj = function(elem, nodeName){ elem = $(elem); var src = {src: elem.attr('src') || '', elem: elem, srcProp: elem.prop('src')}; var tmp; if(!src.src){return src;} tmp = elem.attr('data-server'); if(tmp != null){ src.server = tmp; } tmp = elem.attr('type') || elem.attr('data-type'); if(tmp){ src.type = tmp; src.container = $.trim(tmp.split(';')[0]); } else { if(!nodeName){ nodeName = elem[0].nodeName.toLowerCase(); if(nodeName == 'source'){ nodeName = (elem.closest('video, audio')[0] || {nodeName: 'video'}).nodeName.toLowerCase(); } } if(src.server){ src.type = nodeName+'/rtmp'; src.container = nodeName+'/rtmp'; } else { tmp = mediaelement.getTypeForSrc( src.src, nodeName, src ); if(tmp){ src.type = tmp; src.container = tmp; } } } tmp = elem.attr('media'); if(tmp){ src.media = tmp; } if(src.type == 'audio/rtmp' || src.type == 'video/rtmp'){ if(src.server){ src.streamId = src.src; } else { mediaelement.parseRtmp(src); } } return src; }; var hasYt = !hasSwf && ('postMessage' in window) && hasNative; var loadTrackUi = function(){ if(loadTrackUi.loaded){return;} loadTrackUi.loaded = true; if(!options.noAutoTrack){ webshims.ready('WINDOWLOAD', function(){ loadThird(); webshims.loader.loadList(['track-ui']); }); } }; var loadYt = (function(){ var loaded; return function(){ if(loaded || !hasYt){return;} loaded = true; if(allowYtLoading){ webshims.loader.loadScript("https://www.youtube.com/player_api"); } $(function(){ webshims._polyfill(["mediaelement-yt"]); }); }; })(); var loadThird = function(){ if(hasSwf){ loadSwf(); } else { loadYt(); } }; webshims.addPolyfill('mediaelement-yt', { test: !hasYt, d: ['dom-support'] }); mediaelement.mimeTypes = { audio: { //ogm shouldn´t be used! 'audio/ogg': ['ogg','oga', 'ogm'], 'audio/ogg;codecs="opus"': 'opus', 'audio/mpeg': ['mp2','mp3','mpga','mpega'], 'audio/mp4': ['mp4','mpg4', 'm4r', 'm4a', 'm4p', 'm4b', 'aac'], 'audio/wav': ['wav'], 'audio/3gpp': ['3gp','3gpp'], 'audio/webm': ['webm'], 'audio/fla': ['flv', 'f4a', 'fla'], 'application/x-mpegURL': ['m3u8', 'm3u'] }, video: { //ogm shouldn´t be used! 'video/ogg': ['ogg','ogv', 'ogm'], 'video/mpeg': ['mpg','mpeg','mpe'], 'video/mp4': ['mp4','mpg4', 'm4v'], 'video/quicktime': ['mov','qt'], 'video/x-msvideo': ['avi'], 'video/x-ms-asf': ['asf', 'asx'], 'video/flv': ['flv', 'f4v'], 'video/3gpp': ['3gp','3gpp'], 'video/webm': ['webm'], 'application/x-mpegURL': ['m3u8', 'm3u'], 'video/MP2T': ['ts'] } } ; mediaelement.mimeTypes.source = $.extend({}, mediaelement.mimeTypes.audio, mediaelement.mimeTypes.video); mediaelement.getTypeForSrc = function(src, nodeName){ if(src.indexOf('youtube.com/watch?') != -1 || src.indexOf('youtube.com/v/') != -1){ return 'video/youtube'; } if(!src.indexOf('mediastream:') || !src.indexOf('blob:http')){ return 'usermedia'; } if(!src.indexOf('webshimstream')){ return 'jarisplayer/stream'; } if(!src.indexOf('rtmp')){ return nodeName+'/rtmp'; } src = src.split('?')[0].split('#')[0].split('.'); src = src[src.length - 1]; var mt; $.each(mediaelement.mimeTypes[nodeName], function(mimeType, exts){ if(exts.indexOf(src) !== -1){ mt = mimeType; return false; } }); return mt; }; mediaelement.srces = function(mediaElem){ var srces = []; mediaElem = $(mediaElem); var nodeName = mediaElem[0].nodeName.toLowerCase(); var src = getSrcObj(mediaElem, nodeName); if(!src.src){ $('source', mediaElem).each(function(){ src = getSrcObj(this, nodeName); if(src.src){srces.push(src);} }); } else { srces.push(src); } return srces; }; mediaelement.swfMimeTypes = ['video/3gpp', 'video/x-msvideo', 'video/quicktime', 'video/x-m4v', 'video/mp4', 'video/m4p', 'video/x-flv', 'video/flv', 'audio/mpeg', 'audio/aac', 'audio/mp4', 'audio/x-m4a', 'audio/m4a', 'audio/mp3', 'audio/x-fla', 'audio/fla', 'youtube/flv', 'video/jarisplayer', 'jarisplayer/jarisplayer', 'jarisplayer/stream', 'video/youtube', 'video/rtmp', 'audio/rtmp']; mediaelement.canThirdPlaySrces = function(mediaElem, srces){ var ret = ''; if(hasSwf || hasYt){ mediaElem = $(mediaElem); srces = srces || mediaelement.srces(mediaElem); $.each(srces, function(i, src){ if(src.container && src.src && ((hasSwf && mediaelement.swfMimeTypes.indexOf(src.container) != -1) || (hasYt && src.container == 'video/youtube'))){ ret = src; return false; } }); } return ret; }; var nativeCanPlayType = {}; mediaelement.canNativePlaySrces = function(mediaElem, srces){ var ret = ''; if(hasNative){ mediaElem = $(mediaElem); var nodeName = (mediaElem[0].nodeName || '').toLowerCase(); var nativeCanPlay = (nativeCanPlayType[nodeName] || {prop: {_supvalue: false}}).prop._supvalue || mediaElem[0].canPlayType; if(!nativeCanPlay){return ret;} srces = srces || mediaelement.srces(mediaElem); $.each(srces, function(i, src){ if(src.type == 'usermedia' || (src.type && nativeCanPlay.call(mediaElem[0], src.type)) ){ ret = src; return false; } }); } return ret; }; var emptyType = (/^\s*application\/octet\-stream\s*$/i); var getRemoveEmptyType = function(){ var ret = emptyType.test($.attr(this, 'type') || ''); if(ret){ $(this).removeAttr('type'); } return ret; }; mediaelement.setError = function(elem, message){ if($('source', elem).filter(getRemoveEmptyType).length){ webshims.error('"application/octet-stream" is a useless mimetype for audio/video. Please change this attribute.'); try { $(elem).mediaLoad(); } catch(er){} } else { if(!message){ message = "can't play sources"; } $(elem).pause().data('mediaerror', message); webshims.error('mediaelementError: '+ message +'. Run the following line in your console to get more info: webshim.mediaelement.loadDebugger();'); setTimeout(function(){ if($(elem).data('mediaerror')){ $(elem).addClass('media-error').trigger('mediaerror'); } }, 1); } }; var handleThird = (function(){ var requested; var readyType = hasSwf ? swfType : 'mediaelement-yt'; return function( mediaElem, ret, data ){ //readd to ready webshims.ready(readyType, function(){ if(mediaelement.createSWF && $(mediaElem).parent()[0]){ mediaelement.createSWF( mediaElem, ret, data ); } else if(!requested) { requested = true; loadThird(); handleThird( mediaElem, ret, data ); } }); if(!requested && hasYt && !mediaelement.createSWF){ allowYtLoading = true; loadYt(); } }; })(); var activate = { native: function(elem, src, data){ if(data && data.isActive == 'third') { mediaelement.setActive(elem, 'html5', data); } }, third: handleThird }; var stepSources = function(elem, data, srces){ var i, src; var testOrder = [{test: 'canNativePlaySrces', activate: 'native'}, {test: 'canThirdPlaySrces', activate: 'third'}]; if(options.preferFlash || (data && data.isActive == 'third') ){ testOrder.reverse(); } for(i = 0; i < 2; i++){ src = mediaelement[testOrder[i].test](elem, srces); if(src){ activate[testOrder[i].activate](elem, src, data); break; } } if(!src){ mediaelement.setError(elem, false); if(data && data.isActive == 'third') { mediaelement.setActive(elem, 'html5', data); } } }; var stopParent = /^(?:embed|object|datalist|picture)$/i; var selectSource = function(elem, data){ var baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {}); var _srces = mediaelement.srces(elem); var parent = elem.parentNode; clearTimeout(baseData.loadTimer); $(elem).removeClass('media-error'); $.data(elem, 'mediaerror', false); if(!_srces.length || !parent || parent.nodeType != 1 || stopParent.test(parent.nodeName || '')){return;} data = data || webshims.data(elem, 'mediaelement'); if(mediaelement.sortMedia){ _srces.sort(mediaelement.sortMedia); } stepSources(elem, data, _srces); }; mediaelement.selectSource = selectSource; $(document).on('ended', function(e){ var data = webshims.data(e.target, 'mediaelement'); if( supportsLoop && (!data || data.isActive == 'html5') && !$.prop(e.target, 'loop')){return;} setTimeout(function(){ if( $.prop(e.target, 'paused') || !$.prop(e.target, 'loop') ){return;} $(e.target).prop('currentTime', 0).play(); }); }); var handleMedia = false; var initMediaElements = function(){ var testFixMedia = function(){ if(webshims.implement(this, 'mediaelement')){ selectSource(this); if(!support.mediaDefaultMuted && $.attr(this, 'muted') != null){ $.prop(this, 'muted', true); } } }; webshims.ready('dom-support', function(){ handleMedia = true; if(!supportsLoop){ webshims.defineNodeNamesBooleanProperty(['audio', 'video'], 'loop'); } ['audio', 'video'].forEach(function(nodeName){ var supLoad; supLoad = webshims.defineNodeNameProperty(nodeName, 'load', { prop: { value: function(){ var data = webshims.data(this, 'mediaelement'); selectSource(this, data); if(hasNative && (!data || data.isActive == 'html5') && supLoad.prop._supvalue){ supLoad.prop._supvalue.apply(this, arguments); } if(!loadTrackUi.loaded && this.querySelector('track')){ loadTrackUi(); } $(this).triggerHandler('wsmediareload'); } } }); nativeCanPlayType[nodeName] = webshims.defineNodeNameProperty(nodeName, 'canPlayType', { prop: { value: function(type){ var ret = ''; if(hasNative && nativeCanPlayType[nodeName].prop._supvalue){ ret = nativeCanPlayType[nodeName].prop._supvalue.call(this, type); if(ret == 'no'){ ret = ''; } } if(!ret && hasSwf){ type = $.trim((type || '').split(';')[0]); if(mediaelement.swfMimeTypes.indexOf(type) != -1){ ret = 'maybe'; } } if(!ret && hasYt && type == 'video/youtube'){ ret = 'maybe'; } return ret; } } }); }); webshims.onNodeNamesPropertyModify(['audio', 'video'], ['src', 'poster'], { set: function(){ var elem = this; var baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {}); clearTimeout(baseData.loadTimer); baseData.loadTimer = setTimeout(function(){ selectSource(elem); elem = null; }, 9); } }); webshims.addReady(function(context, insertedElement){ var media = $('video, audio', context) .add(insertedElement.filter('video, audio')) .each(testFixMedia) ; if(!loadTrackUi.loaded && $('track', media).length){ loadTrackUi(); } media = null; }); }); if(hasNative && !handleMedia){ webshims.addReady(function(context, insertedElement){ if(!handleMedia){ $('video, audio', context) .add(insertedElement.filter('video, audio')) .each(function(){ if(!mediaelement.canNativePlaySrces(this)){ allowYtLoading = true; loadThird(); handleMedia = true; return false; } }) ; } }); } }; mediaelement.loadDebugger = function(){ webshims.ready('dom-support', function(){ webshims.loader.loadScript('mediaelement-debug'); }); }; if(({noCombo: 1, media: 1})[webshims.cfg.debug]){ $(document).on('mediaerror', function(e){ mediaelement.loadDebugger(); }); } //set native implementation ready, before swf api is retested if(hasNative){ webshims.isReady('mediaelement-core', true); initMediaElements(); webshims.ready('WINDOWLOAD mediaelement', loadThird); } else { webshims.ready(swfType, initMediaElements); } webshims.ready('track', loadTrackUi); if(document.readyState == 'complete'){ webshims.isReady('WINDOWLOAD', true); } }); })(webshims);
/* http://keith-wood.name/calendars.html Danish localisation for calendars datepicker for jQuery. Written by Jan Christensen ( [email protected]). */ (function($) { 'use strict'; $.calendarsPicker.regionalOptions.da = { renderer: $.calendarsPicker.defaultRenderer, prevText: '&#x3c;Forrige', prevStatus: 'Vis forrige måned', prevJumpText: '&#x3c;&#x3c;', prevJumpStatus: '', nextText: 'Næste&#x3e;', nextStatus: 'Vis næste måned', nextJumpText: '&#x3e;&#x3e;', nextJumpStatus: '', currentText: 'Idag', currentStatus: 'Vis aktuel måned', todayText: 'Idag', todayStatus: 'Vis aktuel måned', clearText: 'Nulstil', clearStatus: 'Nulstil den aktuelle dato', closeText: 'Luk', closeStatus: 'Luk uden ændringer', yearStatus: 'Vis et andet år', monthStatus: 'Vis en anden måned', weekText: 'Uge', weekStatus: 'Årets uge', dayStatus: 'Vælg D, M d', defaultStatus: 'Vælg en dato', isRTL: false }; $.calendarsPicker.setDefaults($.calendarsPicker.regionalOptions.da); })(jQuery);
// Copyright: 2015 AlignAlytics // License: "https://github.com/PMSI-AlignAlytics/dimple/blob/master/MIT-LICENSE.txt" // Source: /src/objects/axis/methods/_parseDate.js this._parseDate = function (inDate) { // A javascript date object var outDate; if (this.dateParseFormat === null || this.dateParseFormat === undefined) { // Moved this into the condition so that using epoch time requires no data format to be set. // For example 20131122 might be parsed as %Y%m%d not treated as epoch time. if (!isNaN(inDate)) { // If inDate is a number, assume it's epoch time outDate = new Date(inDate); } else { // If nothing has been explicity defined you are in the hands of the browser gods // may they smile upon you... outDate = Date.parse(inDate); } } else { outDate = d3.time.format(this.dateParseFormat).parse(inDate); } // Return the date return outDate; };
import createHasError from '../hasError'; var createIsValid = function createIsValid(structure) { var getIn = structure.getIn, keys = structure.keys; var hasError = createHasError(structure); return function (form) { var getFormState = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (state) { return getIn(state, 'form'); }; var ignoreSubmitErrors = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; return function (state) { var formState = getFormState(state); var syncError = getIn(formState, form + '.syncError'); if (syncError) { return false; } if (!ignoreSubmitErrors) { var error = getIn(formState, form + '.error'); if (error) { return false; } } var syncErrors = getIn(formState, form + '.syncErrors'); var asyncErrors = getIn(formState, form + '.asyncErrors'); var submitErrors = ignoreSubmitErrors ? undefined : getIn(formState, form + '.submitErrors'); if (!syncErrors && !asyncErrors && !submitErrors) { return true; } var registeredFields = getIn(formState, form + '.registeredFields'); if (!registeredFields) { return true; } return !keys(registeredFields).filter(function (name) { return getIn(registeredFields, '[\'' + name + '\'].count') > 0; }).some(function (name) { return hasError(getIn(registeredFields, '[\'' + name + '\']'), syncErrors, asyncErrors, submitErrors); }); }; }; }; export default createIsValid;
define({ greeting: 'Hello', five: 5 });
var searchData= [ ['hit_5fcount',['hit_count',['../structv8_1_1_cpu_profile_node_1_1_line_tick.html#a62653fb1e6d381a5747d24b83aab1c1b',1,'v8::CpuProfileNode::LineTick']]] ];
!function(t){"use strict" function e(){return ot}function n(t){ot[t.name]=t}function r(t){return!!t||0===t||!1===t}function i(t){return"function"==typeof t}function a(t){return"number"==typeof t}function f(t){return"object"==typeof t&&!!t}function u(t){return"string"==typeof t}function o(t){return t&&isFinite(t.length)&&!u(t)}function c(t){return t instanceof SVGElement}function s(t){return t.nodeType||c(t)}function l(t,e,n,r){return i(t)?l(t(e,n,r),e,n,r):t}function v(){return performance&&performance.now()||Date.now()}function m(t){return requestAnimationFrame(t)}function g(t){cancelAnimationFrame(t)}function p(t,e){if(!t||1>t.length)return _ if(e===_)return t[0] for(var n=0,r=t.length;r>n;n++)if(e(t[n]))return t[n] return _}function d(t,e){var n=t&&t.length if(!t||1>n)return _ if(e===_)return t[n-1] for(var r=0;n>r;r++){var i=t[r] if(e(i))return i}return _}function h(t,e){for(var n=0,r=t.length;r>n;n++)if(e(t[n]))return n return-1}function y(t){return function(e,n){var r=e[t],i=n[t] return i>r?-1:r>i?1:0}}function k(t){return o(t)?t:[t]}function b(t,e){return Array.prototype.push.call(t,e),e}function x(t,e){return-1!==t.indexOf(e)?e:(b(t,e),e)}function w(t,e){for(var n=[],r=0,i=t.length;i>r;r++){var a=e(t[r]) o(a)?O(n,a):b(n,a)}return n}function O(t,e){for(var n=0,i=e.length;i>n;n++)r(e[n])&&b(t,e[n])}function A(t,e){if(t)for(var n=0,r=t.length;r>n&&!1!==e(t[n],n,r);n++);}function T(){g(lt),lt=vt=_}function E(){var t=ct.length vt=vt||v() var e=v(),n=e-vt if(t){vt=e,lt=m(E) for(var r=0;t>r;r++){var i=st[r]+n st[r]=i,ct[r](n,i)}}else T()}function M(t){-1===ct.indexOf(t)&&(b(ct,t),b(st,0)),lt||(lt=m(E))}function z(t){var e=ct.indexOf(t);-1!==e&&(ct.splice(e,1),st.splice(e,1)),ct.length||T()}function P(t,e,n){return t!==_&&t>=e&&n>=t}function j(t,e,n){return pt(gt(t,e),n)}function L(t,e){var n=[] return A(e,function(e){var r=e.from,i=e.to,a=e.duration,f=e.keyframes,u=e.target,o=e.targetLength,c={} A(f,function(t){var e=c[t.prop]||(c[t.prop]=[]),n=(t.time-r)/(a||1),i=t.easing,f=l(t.value,u,t.index,o),s=p(e,function(t){return t.offset===n})||b(e,{easing:i,offset:n,value:f}) s.easing=i,s.value=f}),t.onWillAnimate&&t.onWillAnimate(e,c) for(var s in c){var v=c[s] if(v){v.sort(dt) var m=p(v,function(t){return 0===t.offset}) if(m===_||m.value===_){var g=t.getValue(u,s) m===_?v.splice(0,0,{offset:0,value:g,easing:e.easing}):(m.value=g,m.easing=e.easing)}var h=d(v,function(t){return 1===t.offset}) if(h===_||h.value===_){var y=v[v.length-1].value h===_?b(v,{offset:1,value:y,easing:e.easing}):(h.value=y,h.easing=e.easing)}b(n,{plugin:t.name,target:u,prop:s,from:r,to:i,keyframes:v})}}}),n}function D(t,e,n,r){var i=r[t],a=r.stagger&&r.stagger*(n+1)||0,f=l(r.delay,e,n,e.targetLength)||0,u=gt(a+f+r.from,0),o=r.to-r.from,c=r.easing||"ease" for(var s in i)i.hasOwnProperty(s)&&F(e,n,s,i[s],o,u,c)}function F(t,e,n,i,u,o,c){if(r(i)){x(t.propNames,n) var s=k(i).map(function(n,r,i){var u=l(n,t.target,e,t.targetLength),o=u,s=f(u),v=s?o.value:u return{offset:s&&a(o.offset)?o.offset:r===i.length-1?1:0===r?0:_,value:v,easing:o.easing||c}}) R(s),s.forEach(function(r){var i=r.offset,a=r.value,f=r.easing,c=mt(u*i+o),s=h(t.keyframes,function(t){return t.prop===n&&t.time===c});-1===s?b(t.keyframes,{easing:f,index:e,prop:n,time:c,value:a}):t.keyframes[s].value=a}),p(t.keyframes,function(t){return t.prop===n&&t.time===o})||b(t.keyframes,{easing:c,index:e,prop:n,time:o,value:_}) var v=o+u d(t.keyframes,function(t){return t.prop===n&&t.time===v})||b(t.keyframes,{easing:c,index:e,prop:n,time:v,value:_})}}function R(t){if(t.length){var e=p(t,function(t){return 0===t.offset})||t[0] r(e.offset)||(e.offset=0) var n=d(t,function(t){return 1===t.offset})||t[t.length-1] t.length>1&&!r(n.offset)&&(n.offset=1) for(var i=1,a=t.length;a>i;i++)if(!r(t[i].offset))for(var f=i+1;a>f;f++){var u=t[f].offset if(r(u)){for(var o=t[i-1].offset,c=u-o,s=f-i+1,l=1;s>l;l++)t[l-1+i].offset=l/f*c+o i=f break}}}}function S(t){return u(t)?Array.prototype.slice.call(document.querySelectorAll(t)):i(t)?S(t()):o(t)?w(t,S):f(t)?[t]:[]}function V(t){var e=0,n=0 for(var r in t._configs)A(t._configs[r],function(t){var r,i A(t.keyframes,function(t){var n=t.time;(r>n||r===_)&&(r=n),(n>i||i===_)&&(i=n,n>e&&(e=n))}),t.to=i,t.from=r,t.duration=i-r,n=gt(i+t.endDelay,n)}) t._nextTime=n,t.duration=e}function q(t){if(!t._effects){var n=[],r=e() for(var i in r)!function(e){var i=r[e],a=t._configs[e] if(!a)return"continue" A(L(i,a),function(t){var e=i.animate(t) e&&(e.from=t.from,e.to=t.to,b(n,e))})}(i) t._time=0>t._rate?t.duration:0,t._effects=n}}function C(t,e){if(e===nt)t._iteration=0,t._state=Q else if(e===rt)t._iteration=0,t._state=et,t._alternate||(t._time=0>t._rate?0:t.duration) else if(e===it)t._state=tt else if(e===at){var n=t._rate>=0 n&&t._time===t.duration?t._time=0:n||0!==t._time||(t._time=t.duration)}var r=t._state===Y,i=t._state!==Q,a=t.currentTime return i&&t._effects===_&&q(t),i&&A(t._effects,function(e){var n=e.from,i=e.to,f=r&&P(mt(a),n,i),u=j((a-n)/(i-n),0,1) e.update(u,t._rate,f)}),r||z(t._tick),e===at&&M(t._tick),i||(A(t._effects,function(t){return t.cancel()}),t._time=0,t._iteration=_,t._effects=_),e===rt&&A(t._listeners[ut],function(t){return t(a)}),A(t._listeners[e],function(t){return t(a)}),t}function I(t,e){var n=t._state if(n!==Q)if(n!==et)if(n!==tt){var r=t.duration,i=t._repeat,a=t._rate,f=0>a,u=t._time===_?0>a?r:0:t._time,o=t._iteration||0 t._state===X&&(t._state=Y,(u===_||f&&u>r||!f&&0>u)&&(u=f?r:0),o===i&&(o=0)) var c=!1 if(P(u+=e*a,0,r)||(t._iteration=++o,u=f?0:r,c=!0,t._alternate&&(t._rate=-1*(t._rate||0)),u=0>t._rate?r:0),t._iteration=o,t._time=u,!c)return A(t._listeners[ut],function(t){return t(u)}),void C(t,ut) i!==o?(A(t._listeners[ut],function(t){return t(u)}),C(t,ut)):C(t,rt)}else C(t,it) else C(t,rt) else C(t,nt)}function N(){var t=Object.create(yt) return t.duration=0,t._nextTime=0,t._rate=1,t._time=0,t._alternate=!1,t._state=Q,t._configs={},t._listeners={},t._tick=function(e){return I(t,e)},t}function W(t,e){for(var n=t.length,r=0;n>r;r++)if(t[r]>e)return r return n-1}function $(t){return Rt.exec((_t(1e5*t)/1e5).toString())[1]}function G(t,e,n){return $(t+(e-t)*n)}function U(t,e,n){return.5>n?t:e}function Z(t,e){var n,r=e.map(function(e){return e.offset*t}),i=e.map(function(t){return t.value}),f=e.map(function(t){return St(t.easing)}),u=i[0] return n=a(u)?G:U,function(e){var a=t*e,u=W(r,a),o=u?u-1:0,c=r[u],s=r[o],l=(a-s)/(c-s),v=f[o](l) return n(i[o],i[u],v)}}function B(t){return t.replace(/([A-Z])/g,function(t){return"-"+t[0].toLowerCase()})}function H(t,e){var n=B(e) return function(e){return t.setAttribute(n,e)}}function J(t,e){return function(n){t.style.setProperty(e,n?n+"":"")}}function K(t,e){return function(n){return t[e]=n}}var Q=1,X=2,Y=3,tt=4,et=5,_=void 0,nt="cancel",rt="finish",it="pause",at="play",ft="reverse",ut="update",ot={},ct=[],st=[],lt=_,vt=_,mt=Math.floor,gt=Math.max,pt=Math.min,_t=Math.round,dt=y("offset"),ht=y("time"),yt={get currentTime(){return this._time},set currentTime(t){var e=this t=+t,e._time=isFinite(t)?t:0>e._rate?e.duration:0,C(e,ut)},get playbackRate(){return this._rate},set playbackRate(t){var e=this e._rate=+t||1,C(e,ft)},add:function(t){var e,n,i=this,a=i._nextTime,f=r(t.to),u=r(t.from),o=r(t.duration) if(u&&f)e=t.from,n=t.to else if(u&&o)n=(e=t.from)+t.duration else if(f&&o)e=(n=t.to)-t.duration else if(f&&!o)n=(e=a)+t.to else{if(!o)throw new Error("Missing duration") n=(e=a)+t.duration}return i.fromTo(e,n,t)},fromTo:function(t,n,r){var i=this,a=e(),f=r f.from=t,f.to=n,f.duration=f.to-f.from for(var u in a)!function(t){var e=a[t] if(!r.hasOwnProperty(t))return"continue" var n=i._configs[t]||(i._configs[t]=[]) A(S(r.targets),function(t,r,i){var a=l(f.delay,t,r,i)||0,u=p(n,function(e){return e.target===t})||b(n,{from:gt(f.from+a,0),to:gt(f.to+a,0),easing:f.easing||"ease",duration:f.to-f.from,endDelay:l(f.endDelay,t,r,i)||0,target:t,targetLength:i,keyframes:[],propNames:[]}) D(e.name,u,r,f)}),A(n,function(t){return t.keyframes.sort(ht)})}(u) return V(i),i},cancel:function(){return C(this,nt)},finish:function(){return C(this,rt)},on:function(t,e){var n=this,r=n._listeners,i=r[t]||(r[t]=[]) return-1===i.indexOf(e)&&b(i,e),n},off:function(t,e){var n=this,r=n._listeners[t] if(r){var i=r.indexOf(e);-1!==i&&r.splice(i,1)}return n},pause:function(){return C(this,it)},play:function(t){var e=this return t&&(e._repeat=t.repeat,e._alternate=!0===t.alternate),e._repeat=e._repeat||1,e._alternate=e._alternate||!1,e._state=Y,C(e,at)},reverse:function(){var t=this return t.playbackRate=-1*(t.playbackRate||0),t},seek:function(t){var e=this return e.currentTime=t,e},getEffects:function(){var t=this._configs,n=e() return w(Object.keys(t),function(e){return L(n[e],t[e])})}},kt=1e-4,bt="cubic-bezier",xt="steps",wt=/([a-z])[- ]([a-z])/gi,Ot=/^([a-z-]+)\(([^\)]+)\)$/i,At={ease:bt+"(.25,.1,.25,1)",easeIn:bt+"(.42,0,1,1)",easeOut:bt+"(0,0,.58,1)",easeInOut:bt+"(.42,0,.58,1)",stepStart:xt+"(1,1)",stepEnd:xt+"(1,0)",linear:bt+"(0,0,1,1)"},Tt=function(t,e,n){return e+n.toUpperCase()},Et=function(t){return"string"==typeof t?t.replace(wt,Tt):""},Mt=function(t){var e=Et(t),n=At[e]||t,r=Ot.exec(n) if(!r)throw new Error("could not parse css function") return[r[1]].concat(r[2].split(","))},zt=function(t,e,n){return 3*t*(1-n)*(1-n)*n+3*e*(1-n)*n*n+n*n*n},Pt=function(t,e,n,r){return 0>t||t>1||0>n||n>1?function(t){return t}:function(i){if(0===i||1===i)return i var a=0,f=1,u=19 do{var o=.5*(a+f),c=zt(t,n,o) if(Lt(i-c)<kt)return zt(e,r,o) i>c?a=o:f=o}while(--u) return i}},jt=function(t){var e=1/(t-1) return function(n){var r=Dt(n*t)*e return n>=0&&0>r?0:1>=n&&r>1?1:r}},Lt=Math.abs,Dt=Math.floor,Ft=function(t,e){var n=t/1,r="end"===e?0:"start"===e?1:e||0 return function(t){return 1>t?r*n+t-(r*n+t)%n:1}},Rt=/^(\-?\d+\.?\d{0,5})/,St=function(t){var e=[] return function(){for(var n=arguments,r=0,i=e.length;i>r;r++){var a=e[r].args if(a.length===i){for(var f=0,u=n.length,o=0;u>o&&a[o]===n[o];o++)++f if(f===u)return e[r].value}}var c=t.apply(_,n) return e.push({args:n,value:c}),c}}(function(t){var e=Mt(t),n=e[0] if("steps"===n)return Ft(+e[1],e[2]) if("cubic-bezier"===n)return Pt(+e[1],+e[2],+e[3],+e[4]) if("frames"===n)return jt(+e[1]) throw new Error("unknown css function")}),Vt=/^\-\-[a-z0-9\-]+$/i n({name:"props",animate:function(t){var e,n=t.target,r=t.prop,i=Z(t.to-t.from,t.keyframes) e=s(n)&&"undefined"==typeof n[r]?Vt.test(r)?J(t.target,r):H(t.target,r):K(t.target,r) var a=n[t.prop] return{cancel:function(){a!==_&&e(a),a=_},update:function(t,n,r){e(i(t))}}},getValue:function(t,e){return s(t)&&"undefined"==typeof t[e]?Vt.test(e)?t.style.getPropertyValue(e):t.getAttribute(B(e)):t[e]}}),t.animate=function(t){var e=N() return t&&A(k(t),function(t){t.from=t.from||0,e.add(t)}),e},t.sequence=function(t){var e=N() return A(t,function(t){return e.add(t)}),e},t.timeline=N,t.addPlugin=n,t.removePlugin=function(t){delete ot[t.name]}}(this.just=this.just||{})
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/tomorrow_night_eighties', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-tomorrow-night-eighties"; exports.cssText = ".ace-tomorrow-night-eighties .ace_gutter {\ background: #272727;\ color: #CCC\ }\ .ace-tomorrow-night-eighties .ace_print-margin {\ width: 1px;\ background: #272727\ }\ .ace-tomorrow-night-eighties {\ background-color: #2D2D2D;\ color: #CCCCCC\ }\ .ace-tomorrow-night-eighties .ace_constant.ace_other {\ color: #CCCCCC\ }\ .ace-tomorrow-night-eighties .ace_cursor {\ color: #CCCCCC\ }\ .ace-tomorrow-night-eighties .ace_marker-layer .ace_selection {\ background: #515151\ }\ .ace-tomorrow-night-eighties.ace_multiselect .ace_selection.ace_start {\ box-shadow: 0 0 3px 0px #2D2D2D;\ border-radius: 2px\ }\ .ace-tomorrow-night-eighties .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0)\ }\ .ace-tomorrow-night-eighties .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #6A6A6A\ }\ .ace-tomorrow-night-bright .ace_stack {\ background: rgb(66, 90, 44)\ }\ .ace-tomorrow-night-eighties .ace_marker-layer .ace_active-line {\ background: #393939\ }\ .ace-tomorrow-night-eighties .ace_gutter-active-line {\ background-color: #393939\ }\ .ace-tomorrow-night-eighties .ace_marker-layer .ace_selected-word {\ border: 1px solid #515151\ }\ .ace-tomorrow-night-eighties .ace_invisible {\ color: #6A6A6A\ }\ .ace-tomorrow-night-eighties .ace_keyword,\ .ace-tomorrow-night-eighties .ace_meta,\ .ace-tomorrow-night-eighties .ace_storage,\ .ace-tomorrow-night-eighties .ace_storage.ace_type,\ .ace-tomorrow-night-eighties .ace_support.ace_type {\ color: #CC99CC\ }\ .ace-tomorrow-night-eighties .ace_keyword.ace_operator {\ color: #66CCCC\ }\ .ace-tomorrow-night-eighties .ace_constant.ace_character,\ .ace-tomorrow-night-eighties .ace_constant.ace_language,\ .ace-tomorrow-night-eighties .ace_constant.ace_numeric,\ .ace-tomorrow-night-eighties .ace_keyword.ace_other.ace_unit,\ .ace-tomorrow-night-eighties .ace_support.ace_constant,\ .ace-tomorrow-night-eighties .ace_variable.ace_parameter {\ color: #F99157\ }\ .ace-tomorrow-night-eighties .ace_invalid {\ color: #CDCDCD;\ background-color: #F2777A\ }\ .ace-tomorrow-night-eighties .ace_invalid.ace_deprecated {\ color: #CDCDCD;\ background-color: #CC99CC\ }\ .ace-tomorrow-night-eighties .ace_fold {\ background-color: #6699CC;\ border-color: #CCCCCC\ }\ .ace-tomorrow-night-eighties .ace_entity.ace_name.ace_function,\ .ace-tomorrow-night-eighties .ace_support.ace_function,\ .ace-tomorrow-night-eighties .ace_variable {\ color: #6699CC\ }\ .ace-tomorrow-night-eighties .ace_support.ace_class,\ .ace-tomorrow-night-eighties .ace_support.ace_type {\ color: #FFCC66\ }\ .ace-tomorrow-night-eighties .ace_heading,\ .ace-tomorrow-night-eighties .ace_string {\ color: #99CC99\ }\ .ace-tomorrow-night-eighties .ace_comment {\ color: #999999\ }\ .ace-tomorrow-night-eighties .ace_entity.ace_name.ace_tag,\ .ace-tomorrow-night-eighties .ace_entity.ace_other.ace_attribute-name,\ .ace-tomorrow-night-eighties .ace_meta.ace_tag,\ .ace-tomorrow-night-eighties .ace_variable {\ color: #F2777A\ }\ .ace-tomorrow-night-eighties .ace_indent-guide {\ background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWPQ09NrYAgMjP4PAAtGAwchHMyAAAAAAElFTkSuQmCC) right repeat-y\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'contextmenu', 'eu', { options: 'Testuingurko Menuaren Aukerak' } );
import*as React from"react";export default function mergeRefs(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return function(r){n.forEach(function(e){null!=e&&("function"!=typeof e?"object"!=typeof e?console.error("mergeRefs cannot handle Refs of type boolean, number or string, received ref "+String(e)):e.current=r:e(r))})}}
module["exports"] = [ "ā", "āb", "āččūšāmūš", "āččūšāņtīūm", "ād", "ādīpīščī", "āļīāš", "āļīqūām", "āļīqūīd", "āmēt", "āņīmī", "āpērīām", "ārčhītēčto", "āšpērīorēš", "āšpērņātūr", "āššūmēņdā", "āt", "ātqūē", "āūt", "āūtēm", "āūtēm", "bēātāē", "bļāņdītīīš", "čommodī", "čoņšēčtētūr", "čoņšēqūātūr", "čoņšēqūūņtūr", "čorporīš", "čorrūptī", "čūļpā", "čūm", "čūmqūē", "čūpīdītātē", "dēbītīš", "dēļēčtūš", "dēļēņītī", "dēšērūņt", "dīčtā", "dīģņīššīmoš", "dīštīņčtīo", "doļor", "doļorē", "doļorēm", "doļorēmqūē", "doļorēš", "doļorībūš", "doļorūm", "dūčīmūš", "ēā", "ēāqūē", "ēārūm", "ēīūš", "ēļīģēņdī", "ēņīm", "ēoš", "ērror", "ēššē", "ēšt", "ēt", "ēūm", "ēvēņīēt", "ēx", "ēxčēptūrī", "ēxērčītātīoņēm", "ēxpēdītā", "ēxpļīčābo", "fāčērē", "fāčīļīš", "fūģā", "fūģīāt", "fūģīt", "hārūm", "hīč", "īd", "īļļo", "īļļūm", "īmpēdīt", "īņ", "īņčīdūņt", "īņvēņtorē", "īpšā", "īpšām", "īpšūm", "īštē", "ītāqūē", "īūrē", "īūšto", "ļāborē", "ļāborīošām", "ļāborūm", "ļāūdāņtīūm", "ļībēro", "māģņām", "māģņī", "māīorēš", "māxīmē", "mīņīmā", "mīņūš", "modī", "moļēštīāē", "moļēštīāš", "moļļītīā", "ņām", "ņātūš", "ņēčēššītātībūš", "ņēmo", "ņēqūē", "ņēščīūņt", "ņīhīļ", "ņīšī", "ņobīš", "ņoņ", "ņoštrūm", "ņūļļā", "ņūmqūām", "oččāēčātī", "odīo", "odīt", "offīčīā", "offīčīīš", "omņīš", "optīo", "pārīātūr", "pērfērēņdīš", "pēršpīčīātīš", "pļāčēāt", "porro", "poššīmūš", "prāēšēņtīūm", "provīdēņt", "qūāē", "qūāērāt", "qūām", "qūāš", "qūāšī", "qūī", "qūīā", "qūībūšdām", "qūīdēm", "qūīš", "qūīšqūām", "qūo", "qūod", "qūoš", "rātīoņē", "rēčūšāņdāē", "rēīčīēņdīš", "rēm", "rēpēļļāt", "rēpēļļēņdūš", "rēprēhēņdērīt", "rēpūdīāņdāē", "rērūm", "šāēpē", "šāpīēņtē", "šēd", "šēqūī", "šīmīļīqūē", "šīņt", "šīt", "šoļūtā", "šūņt", "šūščīpīt", "tēmporā", "tēmporē", "tēmporībūš", "tēņētūr", "totām", "ūļļām", "ūņdē", "ūt", "vēļ", "vēļīt", "vēņīām", "vērītātīš", "vēro", "vītāē", "voļūptāš", "voļūptāš", "voļūptātē", "voļūptātēm", "voļūptātēš", "voļūptātībūš", "voļūptātūm" ];
/*! UIkit 2.27.3 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */ (function(UI) { "use strict"; UI.component('tab', { defaults: { target : '>li:not(.uk-tab-responsive, .uk-disabled)', connect : false, active : 0, animation : false, duration : 200, swiping : true }, boot: function() { // init code UI.ready(function(context) { UI.$('[data-uk-tab]', context).each(function() { var tab = UI.$(this); if (!tab.data('tab')) { var obj = UI.tab(tab, UI.Utils.options(tab.attr('data-uk-tab'))); } }); }); }, init: function() { var $this = this; this.current = false; this.on('click.uk.tab', this.options.target, function(e) { e.preventDefault(); if ($this.switcher && $this.switcher.animating) { return; } var current = $this.find($this.options.target).not(this); current.removeClass('uk-active').blur(); $this.trigger('change.uk.tab', [UI.$(this).addClass('uk-active'), $this.current]); $this.current = UI.$(this); // Update ARIA if (!$this.options.connect) { current.attr('aria-expanded', 'false'); UI.$(this).attr('aria-expanded', 'true'); } }); if (this.options.connect) { this.connect = UI.$(this.options.connect); } // init responsive tab this.responsivetab = UI.$('<li class="uk-tab-responsive uk-active"><a></a></li>').append('<div class="uk-dropdown uk-dropdown-small"><ul class="uk-nav uk-nav-dropdown"></ul><div>'); this.responsivetab.dropdown = this.responsivetab.find('.uk-dropdown'); this.responsivetab.lst = this.responsivetab.dropdown.find('ul'); this.responsivetab.caption = this.responsivetab.find('a:first'); if (this.element.hasClass('uk-tab-bottom')) this.responsivetab.dropdown.addClass('uk-dropdown-up'); // handle click this.responsivetab.lst.on('click.uk.tab', 'a', function(e) { e.preventDefault(); e.stopPropagation(); var link = UI.$(this); $this.element.children('li:not(.uk-tab-responsive)').eq(link.data('index')).trigger('click'); }); this.on('show.uk.switcher change.uk.tab', function(e, tab) { $this.responsivetab.caption.html(tab.text()); }); this.element.append(this.responsivetab); // init UIkit components if (this.options.connect) { this.switcher = UI.switcher(this.element, { toggle : '>li:not(.uk-tab-responsive)', connect : this.options.connect, active : this.options.active, animation : this.options.animation, duration : this.options.duration, swiping : this.options.swiping }); } UI.dropdown(this.responsivetab, {mode: 'click', preventflip: 'y'}); // init $this.trigger('change.uk.tab', [this.element.find(this.options.target).not('.uk-tab-responsive').filter('.uk-active')]); this.check(); UI.$win.on('resize orientationchange', UI.Utils.debounce(function(){ if ($this.element.is(':visible')) $this.check(); }, 100)); this.on('display.uk.check', function(){ if ($this.element.is(':visible')) $this.check(); }); }, check: function() { var children = this.element.children('li:not(.uk-tab-responsive)').removeClass('uk-hidden'); if (!children.length) { this.responsivetab.addClass('uk-hidden'); return; } var top = (children.eq(0).offset().top + Math.ceil(children.eq(0).height()/2)), doresponsive = false, item, link, clone; this.responsivetab.lst.empty(); children.each(function(){ if (UI.$(this).offset().top > top) { doresponsive = true; } }); if (doresponsive) { for (var i = 0; i < children.length; i++) { item = UI.$(children.eq(i)); link = item.find('a'); if (item.css('float') != 'none' && !item.attr('uk-dropdown')) { if (!item.hasClass('uk-disabled')) { clone = UI.$(item[0].outerHTML); clone.find('a').data('index', i); this.responsivetab.lst.append(clone); } item.addClass('uk-hidden'); } } } this.responsivetab[this.responsivetab.lst.children('li').length ? 'removeClass':'addClass']('uk-hidden'); } }); })(UIkit2);
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.nl = {})); }(this, function (exports) { 'use strict'; var fp = typeof window !== "undefined" && window.flatpickr !== undefined ? window.flatpickr : { l10ns: {} }; var Dutch = { weekdays: { shorthand: ["zo", "ma", "di", "wo", "do", "vr", "za"], longhand: [ "zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag", ] }, months: { shorthand: [ "jan", "feb", "mrt", "apr", "mei", "jun", "jul", "aug", "sept", "okt", "nov", "dec", ], longhand: [ "januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december", ] }, firstDayOfWeek: 1, weekAbbreviation: "wk", rangeSeparator: " tot ", scrollTitle: "Scroll voor volgende / vorige", toggleTitle: "Klik om te wisselen", ordinal: function (nth) { if (nth === 1 || nth === 8 || nth >= 20) return "ste"; return "de"; } }; fp.l10ns.nl = Dutch; var nl = fp.l10ns; exports.Dutch = Dutch; exports.default = nl; Object.defineProperty(exports, '__esModule', { value: true }); }));
/* * Youtube Embed Plugin * * @author Jonnas Fonini <[email protected]> * @version 1.0.7 */ ( function() { CKEDITOR.plugins.add( 'youtube', { lang: [ 'en', 'pt', 'ja', 'hu', 'it', 'fr', 'tr', 'ru', 'de' ], init: function( editor ) { editor.addCommand( 'youtube', new CKEDITOR.dialogCommand( 'youtube', { allowedContent: 'iframe[!width,!height,!src,!frameborder,!allowfullscreen]; object param[*]' })); editor.ui.addButton( 'Youtube', { label : editor.lang.youtube.button, toolbar : 'insert', command : 'youtube', icon : this.path + 'images/icon.png' }); CKEDITOR.dialog.add( 'youtube', function ( instance ) { var video; return { title : editor.lang.youtube.title, minWidth : 500, minHeight : 200, contents : [{ id : 'youtubePlugin', expand : true, elements : [{ id : 'txtEmbed', type : 'textarea', label : editor.lang.youtube.txtEmbed, autofocus : 'autofocus', onKeyUp : function ( api ) { if ( this.getValue().length > 0 ) { this.getDialog().getContentElement( 'youtubePlugin', 'txtUrl' ).disable(); } else { this.getDialog().getContentElement( 'youtubePlugin', 'txtUrl' ).enable(); } }, validate : function () { if ( this.isEnabled() ) { if ( !this.getValue() ) { alert( editor.lang.youtube.noCode ); return false; } else if ( this.getValue().length === 0 || this.getValue().indexOf( '//' ) === -1 ) { alert( editor.lang.youtube.invalidEmbed ); return false; } } } }, { type : 'html', html : editor.lang.youtube.or + '<hr>' }, { type : 'hbox', widths : [ '70%', '15%', '15%' ], children : [ { id : 'txtUrl', type : 'text', label : editor.lang.youtube.txtUrl, onKeyUp : function ( api ) { if ( this.getValue().length > 0 ) { this.getDialog().getContentElement( 'youtubePlugin', 'txtEmbed' ).disable(); } else { this.getDialog().getContentElement( 'youtubePlugin', 'txtEmbed' ).enable(); } }, validate : function () { if ( this.isEnabled() ) { if ( !this.getValue() ) { alert( editor.lang.youtube.noCode ); return false; } else{ video = ytVidId(this.getValue()); if ( this.getValue().length === 0 || video === false) { alert( editor.lang.youtube.invalidUrl ); return false; } } } } }, { type : 'text', id : 'txtWidth', width : '60px', label : editor.lang.youtube.txtWidth, 'default' : editor.config.youtube_width != null ? editor.config.youtube_width : '640', validate : function () { if ( this.getValue() ) { var width = parseInt ( this.getValue() ) || 0; if ( width === 0 ) { alert( editor.lang.youtube.invalidWidth ); return false; } } else { alert( editor.lang.youtube.noWidth ); return false; } } }, { type : 'text', id : 'txtHeight', width : '60px', label : editor.lang.youtube.txtHeight, 'default' : editor.config.youtube_height != null ? editor.config.youtube_height : '360', validate : function () { if ( this.getValue() ) { var height = parseInt ( this.getValue() ) || 0; if ( height === 0 ) { alert( editor.lang.youtube.invalidHeight ); return false; } } else { alert( editor.lang.youtube.noHeight ); return false; } } } ] }, { type : 'hbox', widths : [ '55%', '45%' ], children : [ { id : 'chkRelated', type : 'checkbox', 'default' : editor.config.youtube_related != null ? editor.config.youtube_related : true, label : editor.lang.youtube.chkRelated }, { id : 'chkOlderCode', type : 'checkbox', 'default' : editor.config.youtube_older != null ? editor.config.youtube_older : false, label : editor.lang.youtube.chkOlderCode } ] }, { type : 'hbox', widths : [ '55%', '45%' ], children : [ { id : 'chkPrivacy', type : 'checkbox', label : editor.lang.youtube.chkPrivacy, 'default' : editor.config.youtube_privacy != null ? editor.config.youtube_privacy : false }, { id : 'txtStartAt', type : 'text', label : editor.lang.youtube.txtStartAt, validate : function () { if ( this.getValue() ) { var str = this.getValue(); if ( !/^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)$/i.test( str ) ) { alert( editor.lang.youtube.invalidTime ); return false; } } } } ] } ] } ], onOk: function() { var content = ''; if ( this.getContentElement( 'youtubePlugin', 'txtEmbed' ).isEnabled() ) { content = this.getValueOf( 'youtubePlugin', 'txtEmbed' ); } else { var url = '//', params = [], startSecs; var width = this.getValueOf( 'youtubePlugin', 'txtWidth' ); var height = this.getValueOf( 'youtubePlugin', 'txtHeight' ); if ( this.getContentElement( 'youtubePlugin', 'chkPrivacy' ).getValue() === true ) { url += 'www.youtube-nocookie.com/'; } else { url += 'www.youtube.com/'; } url += 'embed/' + video; if ( this.getContentElement( 'youtubePlugin', 'chkRelated' ).getValue() === false ) { params.push('rel=0'); } startSecs = this.getValueOf( 'youtubePlugin', 'txtStartAt' ); if ( startSecs ){ var seconds = hmsToSeconds( startSecs ); params.push('start=' + seconds); } if ( this.getContentElement( 'youtubePlugin', 'chkOlderCode' ).getValue() === true ) { url = url.replace('embed/', 'v/'); url = url.replace(/&/g, '&amp;'); if ( params.length == 0 ) { url += '?'; } url += 'hl=pt_BR&amp;version=3'; content = '<object width="' + width + '" height="' + height + '">'; content += '<param name="movie" value="' + url + '"></param>'; content += '<param name="allowFullScreen" value="true"></param>'; content += '<param name="allowscriptaccess" value="always"></param>'; content += '<embed src="' + url + '" type="application/x-shockwave-flash" '; content += 'width="' + width + '" height="' + height + '" allowscriptaccess="always" '; content += 'allowfullscreen="true"></embed>'; content += '</object>'; } else { if ( params.length > 0 ) { url = url + '?' + params.join( '&' ); } content = '<iframe width="' + width + '" height="' + height + '" src="' + url + '" '; content += 'frameborder="0" allowfullscreen></iframe>'; } } var instance = this.getParentEditor(); instance.insertHtml( content ); } }; }); } }); })(); /** * JavaScript function to match (and return) the video Id * of any valid Youtube Url, given as input string. * @author: Stephan Schmitz <[email protected]> * @url: http://stackoverflow.com/a/10315969/624466 */ function ytVidId( url ) { var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/; return ( url.match( p ) ) ? RegExp.$1 : false; } /** * Converts time in hms format to seconds only */ function hmsToSeconds( time ) { var arr = time.split(':'), s = 0, m = 1; while (arr.length > 0) { s += m * parseInt(arr.pop(), 10); m *= 60; } return s; }
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v9.0.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var component_1 = require("../../widgets/component"); var constants_1 = require("../../constants"); var utils_1 = require("../../utils"); var LargeTextCellEditor = (function (_super) { __extends(LargeTextCellEditor, _super); function LargeTextCellEditor() { return _super.call(this, LargeTextCellEditor.TEMPLATE) || this; } LargeTextCellEditor.prototype.init = function (params) { this.params = params; this.focusAfterAttached = params.cellStartedEdit; this.textarea = document.createElement("textarea"); this.textarea.maxLength = params.maxLength ? params.maxLength : "200"; this.textarea.cols = params.cols ? params.cols : "60"; this.textarea.rows = params.rows ? params.rows : "10"; if (utils_1.Utils.exists(params.value)) { this.textarea.value = params.value.toString(); } this.getGui().querySelector('.ag-large-textarea').appendChild(this.textarea); this.addGuiEventListener('keydown', this.onKeyDown.bind(this)); }; LargeTextCellEditor.prototype.onKeyDown = function (event) { var key = event.which || event.keyCode; if (key == constants_1.Constants.KEY_LEFT || key == constants_1.Constants.KEY_UP || key == constants_1.Constants.KEY_RIGHT || key == constants_1.Constants.KEY_DOWN || (event.shiftKey && key == constants_1.Constants.KEY_ENTER)) { event.stopPropagation(); } }; LargeTextCellEditor.prototype.afterGuiAttached = function () { if (this.focusAfterAttached) { this.textarea.focus(); } }; LargeTextCellEditor.prototype.getValue = function () { return this.textarea.value; }; LargeTextCellEditor.prototype.isPopup = function () { return true; }; return LargeTextCellEditor; }(component_1.Component)); LargeTextCellEditor.TEMPLATE = // tab index is needed so we can focus, which is needed for keyboard events '<div class="ag-large-text" tabindex="0">' + '<div class="ag-large-textarea"></div>' + '</div>'; exports.LargeTextCellEditor = LargeTextCellEditor;
/************************************************************* * * MathJax/jax/output/HTML-CSS/optable/BasicLatin.js * * Copyright (c) 2010-2014 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. * */ (function (MML) { var MO = MML.mo.OPTYPES; var TEXCLASS = MML.TEXCLASS; MathJax.Hub.Insert(MML.mo.prototype,{ OPTABLE: { prefix: { '||': [0,0,TEXCLASS.BIN,{fence: true, stretchy: true, symmetric: true}], // multiple character operator: || '|||': [0,0,TEXCLASS.ORD,{fence: true, stretchy: true, symmetric: true}] // multiple character operator: ||| }, postfix: { '!!': [1,0,TEXCLASS.BIN], // multiple character operator: !! '\'': MO.ACCENT, // apostrophe '++': [0,0,TEXCLASS.BIN], // multiple character operator: ++ '--': [0,0,TEXCLASS.BIN], // multiple character operator: -- '..': [0,0,TEXCLASS.BIN], // multiple character operator: .. '...': MO.ORD, // multiple character operator: ... '||': [0,0,TEXCLASS.BIN,{fence: true, stretchy: true, symmetric: true}], // multiple character operator: || '|||': [0,0,TEXCLASS.ORD,{fence: true, stretchy: true, symmetric: true}] // multiple character operator: ||| }, infix: { '!=': MO.BIN4, // multiple character operator: != '&&': MO.BIN4, // multiple character operator: && '**': [1,1,TEXCLASS.BIN], // multiple character operator: ** '*=': MO.BIN4, // multiple character operator: *= '+=': MO.BIN4, // multiple character operator: += '-=': MO.BIN4, // multiple character operator: -= '->': MO.BIN5, // multiple character operator: -> '//': [1,1,TEXCLASS.BIN], // multiple character operator: // '/=': MO.BIN4, // multiple character operator: /= ':=': MO.BIN4, // multiple character operator: := '<=': MO.BIN5, // multiple character operator: <= '<>': [1,1,TEXCLASS.BIN], // multiple character operator: <> '==': MO.BIN4, // multiple character operator: == '>=': MO.BIN5, // multiple character operator: >= '@': MO.ORD11, // commercial at '||': [2,2,TEXCLASS.BIN,{fence: true, stretchy: true, symmetric: true}], // multiple character operator: || '|||': [2,2,TEXCLASS.ORD,{fence: true, stretchy: true, symmetric: true}] // multiple character operator: ||| } } }); MathJax.Ajax.loadComplete(MML.optableDir+"/BasicLatin.js"); })(MathJax.ElementJax.mml);
module.exports={title:"Dialogflow",slug:"dialogflow",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Dialogflow icon</title><path d="M11.996 0a1.639 1.639 0 0 0-.82.22L3.344 4.74a1.648 1.648 0 0 0-.535.498l9.136 5.28 9.213-5.32a1.652 1.652 0 0 0-.51-.458L12.818.22a1.639 1.639 0 0 0-.822-.22zm9.336 5.5l-9.387 5.422-9.3-5.373a1.648 1.648 0 0 0-.12.615v9.043a1.643 1.643 0 0 0 .819 1.42l3.918 2.266v4.617a.493.493 0 0 0 .74.424l12.654-7.303a1.639 1.639 0 0 0 .819-1.42V6.162a1.652 1.652 0 0 0-.143-.662z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://en.wikipedia.org/wiki/File:Dialogflow_logo.svg",hex:"FF9800"};
define(['jquery'], function (jq) { return jq.noConflict( true ); });
/** * angular-input-masks * Personalized input masks for AngularJS * @version v2.6.0 * @link http://github.com/assisrafael/angular-input-masks * @license MIT */ require=(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){ 'use strict'; module.exports = angular.module('ui.utils.masks', [ require('./global/global-masks'), require('./br/br-masks'), require('./us/us-masks'), require('./ch/ch-masks') ]).name; },{"./br/br-masks":3,"./ch/ch-masks":12,"./global/global-masks":16,"./us/us-masks":24}],2:[function(require,module,exports){ 'use strict'; var StringMask = require('string-mask'); var maskFactory = require('mask-factory'); var boletoBancarioMask = new StringMask('00000.00000 00000.000000 00000.000000 0 00000000000000'); module.exports = maskFactory({ clearValue: function(rawValue) { return rawValue.replace(/[^0-9]/g, '').slice(0, 47); }, format: function(cleanValue) { if (cleanValue.length === 0) { return cleanValue; } return boletoBancarioMask.apply(cleanValue).replace(/[^0-9]$/, ''); }, validations: { brBoletoBancario: function(value) { return value.length === 47; } } }); },{"mask-factory":"mask-factory","string-mask":undefined}],3:[function(require,module,exports){ 'use strict'; var m = angular.module('ui.utils.masks.br', [ require('../helpers'), ]) .directive('uiBrBoletoBancarioMask', require('./boleto-bancario/boleto-bancario')) .directive('uiBrCepMask', require('./cep/cep')) .directive('uiBrCnpjMask', require('./cnpj/cnpj')) .directive('uiBrCpfMask', require('./cpf/cpf')) .directive('uiBrCpfcnpjMask', require('./cpf-cnpj/cpf-cnpj')) .directive('uiBrIeMask', require('./inscricao-estadual/ie')) .directive('uiNfeAccessKeyMask', require('./nfe/nfe')) .directive('uiBrCarPlateMask', require('./car-plate/car-plate')) .directive('uiBrPhoneNumber', require('./phone/br-phone')); module.exports = m.name; },{"../helpers":22,"./boleto-bancario/boleto-bancario":2,"./car-plate/car-plate":4,"./cep/cep":5,"./cnpj/cnpj":6,"./cpf-cnpj/cpf-cnpj":7,"./cpf/cpf":8,"./inscricao-estadual/ie":9,"./nfe/nfe":10,"./phone/br-phone":11}],4:[function(require,module,exports){ 'use strict'; var StringMask = require('string-mask'); var maskFactory = require('mask-factory'); var carPlateMask = new StringMask('UUU-0000'); module.exports = maskFactory({ clearValue: function(rawValue) { return rawValue.replace(/[^a-zA-Z0-9]/g, '').slice(0, 7); }, format: function(cleanValue) { return (carPlateMask.apply(cleanValue) || '').replace(/[^a-zA-Z0-9]$/, ''); }, validations: { carPlate: function(value) { return value.length === 7; } } }); },{"mask-factory":"mask-factory","string-mask":undefined}],5:[function(require,module,exports){ 'use strict'; var StringMask = require('string-mask'); var maskFactory = require('mask-factory'); var cepMask = new StringMask('00000-000'); module.exports = maskFactory({ clearValue: function(rawValue) { return rawValue.toString().replace(/[^0-9]/g, '').slice(0, 8); }, format: function(cleanValue) { return (cepMask.apply(cleanValue) || '').replace(/[^0-9]$/, ''); }, validations: { cep: function(value) { return value.length === 8; } } }); },{"mask-factory":"mask-factory","string-mask":undefined}],6:[function(require,module,exports){ 'use strict'; var StringMask = require('string-mask'); var BrV = require('br-validations'); var maskFactory = require('mask-factory'); var cnpjPattern = new StringMask('00.000.000\/0000-00'); module.exports = maskFactory({ clearValue: function(rawValue) { return rawValue.replace(/[^\d]/g, '').slice(0, 14); }, format: function(cleanValue) { return (cnpjPattern.apply(cleanValue) || '').trim().replace(/[^0-9]$/, ''); }, validations: { cnpj: function(value) { return BrV.cnpj.validate(value); } } }); },{"br-validations":undefined,"mask-factory":"mask-factory","string-mask":undefined}],7:[function(require,module,exports){ 'use strict'; var StringMask = require('string-mask'); var BrV = require('br-validations'); var maskFactory = require('mask-factory'); var cnpjPattern = new StringMask('00.000.000\/0000-00'); var cpfPattern = new StringMask('000.000.000-00'); module.exports = maskFactory({ clearValue: function(rawValue) { return rawValue.replace(/[^\d]/g, '').slice(0, 14); }, format: function(cleanValue) { var formatedValue; if (cleanValue.length > 11) { formatedValue = cnpjPattern.apply(cleanValue); } else { formatedValue = cpfPattern.apply(cleanValue) || ''; } return formatedValue.trim().replace(/[^0-9]$/, ''); }, validations: { cpf: function(value) { return value.length > 11 || BrV.cpf.validate(value); }, cnpj: function(value) { return value.length <= 11 || BrV.cnpj.validate(value); } } }); },{"br-validations":undefined,"mask-factory":"mask-factory","string-mask":undefined}],8:[function(require,module,exports){ 'use strict'; var StringMask = require('string-mask'); var BrV = require('br-validations'); var maskFactory = require('mask-factory'); var cpfPattern = new StringMask('000.000.000-00'); module.exports = maskFactory({ clearValue: function(rawValue) { return rawValue.replace(/[^\d]/g, '').slice(0, 11); }, format: function(cleanValue) { return (cpfPattern.apply(cleanValue) || '').trim().replace(/[^0-9]$/, ''); }, validations: { cpf: function(value) { return BrV.cpf.validate(value); } } }); },{"br-validations":undefined,"mask-factory":"mask-factory","string-mask":undefined}],9:[function(require,module,exports){ 'use strict'; var StringMask = require('string-mask'); var BrV = require('br-validations'); function BrIeMaskDirective($parse) { var ieMasks = { 'AC': [{mask: new StringMask('00.000.000/000-00')}], 'AL': [{mask: new StringMask('000000000')}], 'AM': [{mask: new StringMask('00.000.000-0')}], 'AP': [{mask: new StringMask('000000000')}], 'BA': [{chars: 8, mask: new StringMask('000000-00')}, {mask: new StringMask('0000000-00')}], 'CE': [{mask: new StringMask('00000000-0')}], 'DF': [{mask: new StringMask('00000000000-00')}], 'ES': [{mask: new StringMask('00000000-0')}], 'GO': [{mask: new StringMask('00.000.000-0')}], 'MA': [{mask: new StringMask('000000000')}], 'MG': [{mask: new StringMask('000.000.000/0000')}], 'MS': [{mask: new StringMask('000000000')}], 'MT': [{mask: new StringMask('0000000000-0')}], 'PA': [{mask: new StringMask('00-000000-0')}], 'PB': [{mask: new StringMask('00000000-0')}], 'PE': [{chars: 9, mask: new StringMask('0000000-00')}, {mask: new StringMask('00.0.000.0000000-0')}], 'PI': [{mask: new StringMask('000000000')}], 'PR': [{mask: new StringMask('000.00000-00')}], 'RJ': [{mask: new StringMask('00.000.00-0')}], 'RN': [{chars: 9, mask: new StringMask('00.000.000-0')}, {mask: new StringMask('00.0.000.000-0')}], 'RO': [{mask: new StringMask('0000000000000-0')}], 'RR': [{mask: new StringMask('00000000-0')}], 'RS': [{mask: new StringMask('000/0000000')}], 'SC': [{mask: new StringMask('000.000.000')}], 'SE': [{mask: new StringMask('00000000-0')}], 'SP': [{mask: new StringMask('000.000.000.000')}, {mask: new StringMask('-00000000.0/000')}], 'TO': [{mask: new StringMask('00000000000')}] }; function clearValue(value) { if (!value) { return value; } return value.replace(/[^0-9]/g, ''); } function getMask(uf, value) { if (!uf || !ieMasks[uf]) { return; } if (uf === 'SP' && /^P/i.test(value)) { return ieMasks.SP[1].mask; } var masks = ieMasks[uf]; var i = 0; while (masks[i].chars && masks[i].chars < clearValue(value).length && i < masks.length - 1) { i++; } return masks[i].mask; } function applyIEMask(value, uf) { var mask = getMask(uf, value); if (!mask) { return value; } var processed = mask.process(clearValue(value)); var formatedValue = processed.result || ''; formatedValue = formatedValue.trim().replace(/[^0-9]$/, ''); if (uf === 'SP' && /^p/i.test(value)) { return 'P' + formatedValue; } return formatedValue; } return { restrict: 'A', require: 'ngModel', link: function(scope, element, attrs, ctrl) { var state = ($parse(attrs.uiBrIeMask)(scope) || '').toUpperCase(); function formatter(value) { if (ctrl.$isEmpty(value)) { return value; } return applyIEMask(value, state); } function parser(value) { if (ctrl.$isEmpty(value)) { return value; } var formatedValue = applyIEMask(value, state); var actualValue = clearValue(formatedValue); if (ctrl.$viewValue !== formatedValue) { ctrl.$setViewValue(formatedValue); ctrl.$render(); } if (state && state.toUpperCase() === 'SP' && /^p/i.test(value)) { return 'P' + actualValue; } return actualValue; } ctrl.$formatters.push(formatter); ctrl.$parsers.push(parser); ctrl.$validators.ie = function validator(modelValue) { return ctrl.$isEmpty(modelValue) || BrV.ie(state).validate(modelValue); }; scope.$watch(attrs.uiBrIeMask, function(newState) { state = (newState || '').toUpperCase(); parser(ctrl.$viewValue); ctrl.$validate(); }); } }; } BrIeMaskDirective.$inject = ['$parse']; module.exports = BrIeMaskDirective; },{"br-validations":undefined,"string-mask":undefined}],10:[function(require,module,exports){ 'use strict'; var StringMask = require('string-mask'); var maskFactory = require('mask-factory'); var nfeAccessKeyMask = new StringMask('0000 0000 0000 0000 0000' + ' 0000 0000 0000 0000 0000 0000'); module.exports = maskFactory({ clearValue: function(rawValue) { return rawValue.replace(/[^0-9]/g, '').slice(0, 44); }, format: function(cleanValue) { return (nfeAccessKeyMask.apply(cleanValue) || '').replace(/[^0-9]$/, ''); }, validations: { nfeAccessKey: function(value) { return value.length === 44; } } }); },{"mask-factory":"mask-factory","string-mask":undefined}],11:[function(require,module,exports){ 'use strict'; var StringMask = require('string-mask'); var maskFactory = require('mask-factory'); /** * FIXME: all numbers will have 9 digits after 2016. * see http://portal.embratel.com.br/embratel/9-digito/ */ var phoneMask8D = { areaCode: new StringMask('(00) 0000-0000'), //with area code simple: new StringMask('0000-0000') //without area code }, phoneMask9D = { areaCode: new StringMask('(00) 00000-0000'), //with area code simple: new StringMask('00000-0000') //without area code }, phoneMask0800 = { areaCode: null, //N/A simple: new StringMask('0000-000-0000') //N/A, so it's "simple" }; module.exports = maskFactory({ clearValue: function(rawValue) { return rawValue.toString().replace(/[^0-9]/g, '').slice(0, 11); }, format: function(cleanValue) { var formattedValue; if (cleanValue.indexOf('0800') === 0) { formattedValue = phoneMask0800.simple.apply(cleanValue); } else if (cleanValue.length < 9) { formattedValue = phoneMask8D.simple.apply(cleanValue) || ''; } else if (cleanValue.length < 10) { formattedValue = phoneMask9D.simple.apply(cleanValue); } else if (cleanValue.length < 11) { formattedValue = phoneMask8D.areaCode.apply(cleanValue); } else { formattedValue = phoneMask9D.areaCode.apply(cleanValue); } return formattedValue.trim().replace(/[^0-9]$/, ''); }, getModelValue: function(formattedValue, originalModelType) { var cleanValue = this.clearValue(formattedValue); return originalModelType === 'number' ? parseInt(cleanValue) : cleanValue; }, validations: { brPhoneNumber: function(value) { var valueLength = value && value.toString().length; //8- 8D without DD //9- 9D without DD //10- 9D with DD //11- 8D with DD and 0800 return valueLength >= 8 && valueLength <= 11; } } }); },{"mask-factory":"mask-factory","string-mask":undefined}],12:[function(require,module,exports){ 'use strict'; var m = angular.module('ui.utils.masks.ch', [ require('../helpers'), ]) .directive('uiChPhoneNumber', require('./phone/ch-phone')); module.exports = m.name; },{"../helpers":22,"./phone/ch-phone":13}],13:[function(require,module,exports){ 'use strict'; var StringMask = require('string-mask'); var maskFactory = require('mask-factory'); var phoneMask = new StringMask('+00 00 000 00 00'); module.exports = maskFactory({ clearValue: function(rawValue) { return rawValue.toString().replace(/[^0-9]/g, '').slice(0, 11); }, format: function(cleanValue) { var formatedValue; formatedValue = phoneMask.apply(cleanValue) || ''; return formatedValue.trim().replace(/[^0-9]$/, ''); }, validations: { chPhoneNumber: function(value) { var valueLength = value && value.toString().length; return valueLength === 11; } } }); },{"mask-factory":"mask-factory","string-mask":undefined}],14:[function(require,module,exports){ 'use strict'; var StringMask = require('string-mask'); var maskFactory = require('mask-factory'); var ccSize = 16; var ccMask = new StringMask('0000 0000 0000 0000'); module.exports = maskFactory({ clearValue: function(rawValue) { return rawValue.toString().replace(/[^0-9]/g, '').slice(0, ccSize); }, format: function(cleanValue) { var formatedValue; formatedValue = ccMask.apply(cleanValue) || ''; return formatedValue.trim().replace(/[^0-9]$/, ''); }, validations: { creditCard: function(value) { var valueLength = value && value.toString().length; return valueLength === ccSize; } } }); },{"mask-factory":"mask-factory","string-mask":undefined}],15:[function(require,module,exports){ 'use strict'; var moment = require('moment'); var StringMask = require('string-mask'); function isISODateString(date) { return /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}([-+][0-9]{2}:[0-9]{2}|Z)$/ .test(date.toString()); } function DateMaskDirective($locale) { var dateFormatMapByLocale = { 'pt-br': 'DD/MM/YYYY', 'ru': 'DD.MM.YYYY', }; var dateFormat = dateFormatMapByLocale[$locale.id] || 'YYYY-MM-DD'; return { restrict: 'A', require: 'ngModel', link: function(scope, element, attrs, ctrl) { attrs.parse = attrs.parse || 'true'; dateFormat = attrs.uiDateMask || dateFormat; var dateMask = new StringMask(dateFormat.replace(/[YMD]/g,'0')); function formatter(value) { if (ctrl.$isEmpty(value)) { return value; } var cleanValue = value; if (typeof value === 'object' || isISODateString(value)) { cleanValue = moment(value).format(dateFormat); } cleanValue = cleanValue.replace(/[^0-9]/g, ''); var formatedValue = dateMask.apply(cleanValue) || ''; return formatedValue.trim().replace(/[^0-9]$/, ''); } ctrl.$formatters.push(formatter); ctrl.$parsers.push(function parser(value) { if (ctrl.$isEmpty(value)) { return value; } var formatedValue = formatter(value); if (ctrl.$viewValue !== formatedValue) { ctrl.$setViewValue(formatedValue); ctrl.$render(); } return attrs.parse === 'false' ? formatedValue : moment(formatedValue, dateFormat).toDate(); }); ctrl.$validators.date = function validator(modelValue, viewValue) { if (ctrl.$isEmpty(modelValue)) { return true; } return moment(viewValue, dateFormat).isValid() && viewValue.length === dateFormat.length; }; } }; } DateMaskDirective.$inject = ['$locale']; module.exports = DateMaskDirective; },{"moment":undefined,"string-mask":undefined}],16:[function(require,module,exports){ 'use strict'; var m = angular.module('ui.utils.masks.global', [ require('../helpers'), ]) .directive('uiDateMask', require('./date/date')) .directive('uiMoneyMask', require('./money/money')) .directive('uiNumberMask', require('./number/number')) .directive('uiPercentageMask', require('./percentage/percentage')) .directive('uiScientificNotationMask', require('./scientific-notation/scientific-notation')) .directive('uiTimeMask', require('./time/time')) .directive('uiCreditCard', require('./credit-card/credit-card')); module.exports = m.name; },{"../helpers":22,"./credit-card/credit-card":14,"./date/date":15,"./money/money":17,"./number/number":18,"./percentage/percentage":19,"./scientific-notation/scientific-notation":20,"./time/time":21}],17:[function(require,module,exports){ 'use strict'; var StringMask = require('string-mask'); var validators = require('validators'); function MoneyMaskDirective($locale, $parse, PreFormatters) { return { restrict: 'A', require: 'ngModel', link: function(scope, element, attrs, ctrl) { var decimalDelimiter = $locale.NUMBER_FORMATS.DECIMAL_SEP, thousandsDelimiter = $locale.NUMBER_FORMATS.GROUP_SEP, currencySym = $locale.NUMBER_FORMATS.CURRENCY_SYM, symbolSeparation = ' ', decimals = $parse(attrs.uiMoneyMask)(scope), backspacePressed = false; element.bind('keydown keypress', function(event) { backspacePressed = event.which === 8; }); function maskFactory(decimals) { var decimalsPattern = decimals > 0 ? decimalDelimiter + new Array(decimals + 1).join('0') : ''; var maskPattern = '#' + thousandsDelimiter + '##0' + decimalsPattern; if (angular.isDefined(attrs.uiCurrencyAfter)) { maskPattern += symbolSeparation; } else { maskPattern = symbolSeparation + maskPattern; } return new StringMask(maskPattern, {reverse: true}); } if (angular.isDefined(attrs.uiDecimalDelimiter)) { decimalDelimiter = attrs.uiDecimalDelimiter; } if (angular.isDefined(attrs.uiThousandsDelimiter)) { thousandsDelimiter = attrs.uiThousandsDelimiter; } if (angular.isDefined(attrs.uiHideGroupSep)) { thousandsDelimiter = ''; } if (angular.isDefined(attrs.uiHideSpace)) { symbolSeparation = ''; } if (angular.isDefined(attrs.currencySymbol)) { currencySym = attrs.currencySymbol; if (attrs.currencySymbol.length === 0) { symbolSeparation = ''; } } if (isNaN(decimals)) { decimals = 2; } decimals = parseInt(decimals); var moneyMask = maskFactory(decimals); function formatter(value) { if (ctrl.$isEmpty(value)) { return value; } var prefix = (angular.isDefined(attrs.uiNegativeNumber) && value < 0) ? '-' : ''; var valueToFormat = PreFormatters.prepareNumberToFormatter(value, decimals); if (angular.isDefined(attrs.uiCurrencyAfter)) { return prefix + moneyMask.apply(valueToFormat) + currencySym; } return prefix + currencySym + moneyMask.apply(valueToFormat); } function parser(value) { if (ctrl.$isEmpty(value)) { return value; } var actualNumber = value.replace(/[^\d]+/g,''), formatedValue; actualNumber = actualNumber.replace(/^[0]+([1-9])/,'$1'); actualNumber = actualNumber || '0'; if (backspacePressed && angular.isDefined(attrs.uiCurrencyAfter) && actualNumber !== 0) { actualNumber = actualNumber.substring(0, actualNumber.length - 1); backspacePressed = false; } if (angular.isDefined(attrs.uiCurrencyAfter)) { formatedValue = moneyMask.apply(actualNumber) + currencySym; } else { formatedValue = currencySym + moneyMask.apply(actualNumber); } if (angular.isDefined(attrs.uiNegativeNumber)) { var isNegative = (value[0] === '-'), needsToInvertSign = (value.slice(-1) === '-'); //only apply the minus sign if it is negative or(exclusive) //needs to be negative and the number is different from zero if (needsToInvertSign ^ isNegative && !!actualNumber) { actualNumber *= -1; formatedValue = '-' + formatedValue; } } if (value !== formatedValue) { ctrl.$setViewValue(formatedValue); ctrl.$render(); } return formatedValue ? parseInt(formatedValue.replace(/[^\d\-]+/g,''))/Math.pow(10,decimals) : null; } ctrl.$formatters.push(formatter); ctrl.$parsers.push(parser); if (attrs.uiMoneyMask) { scope.$watch(attrs.uiMoneyMask, function(_decimals) { decimals = isNaN(_decimals) ? 2 : _decimals; decimals = parseInt(decimals); moneyMask = maskFactory(decimals); parser(ctrl.$viewValue); }); } if (attrs.min) { var minVal; ctrl.$validators.min = function(modelValue) { return validators.minNumber(ctrl, modelValue, minVal); }; scope.$watch(attrs.min, function(value) { minVal = value; ctrl.$validate(); }); } if (attrs.max) { var maxVal; ctrl.$validators.max = function(modelValue) { return validators.maxNumber(ctrl, modelValue, maxVal); }; scope.$watch(attrs.max, function(value) { maxVal = value; ctrl.$validate(); }); } } }; } MoneyMaskDirective.$inject = ['$locale', '$parse', 'PreFormatters']; module.exports = MoneyMaskDirective; },{"string-mask":undefined,"validators":"validators"}],18:[function(require,module,exports){ 'use strict'; var validators = require('validators'); function NumberMaskDirective($locale, $parse, PreFormatters, NumberMasks) { return { restrict: 'A', require: 'ngModel', link: function(scope, element, attrs, ctrl) { var decimalDelimiter = $locale.NUMBER_FORMATS.DECIMAL_SEP, thousandsDelimiter = $locale.NUMBER_FORMATS.GROUP_SEP, decimals = $parse(attrs.uiNumberMask)(scope); if (angular.isDefined(attrs.uiHideGroupSep)) { thousandsDelimiter = ''; } if (isNaN(decimals)) { decimals = 2; } var viewMask = NumberMasks.viewMask(decimals, decimalDelimiter, thousandsDelimiter), modelMask = NumberMasks.modelMask(decimals); function parser(value) { if (ctrl.$isEmpty(value)) { return null; } var valueToFormat = PreFormatters.clearDelimitersAndLeadingZeros(value) || '0'; var formatedValue = viewMask.apply(valueToFormat); var actualNumber = parseFloat(modelMask.apply(valueToFormat)); if (angular.isDefined(attrs.uiNegativeNumber)) { var isNegative = (value[0] === '-'), needsToInvertSign = (value.slice(-1) === '-'); //only apply the minus sign if it is negative or(exclusive) or the first character //needs to be negative and the number is different from zero if ((needsToInvertSign ^ isNegative) || value === '-') { actualNumber *= -1; formatedValue = '-' + ((actualNumber !== 0) ? formatedValue : ''); } } if (ctrl.$viewValue !== formatedValue) { ctrl.$setViewValue(formatedValue); ctrl.$render(); } return actualNumber; } function formatter(value) { if (ctrl.$isEmpty(value)) { return value; } var prefix = (angular.isDefined(attrs.uiNegativeNumber) && value < 0) ? '-' : ''; var valueToFormat = PreFormatters.prepareNumberToFormatter(value, decimals); return prefix + viewMask.apply(valueToFormat); } function clearViewValueIfMinusSign() { if (ctrl.$viewValue === '-') { ctrl.$setViewValue(''); ctrl.$render(); } } element.on('blur', clearViewValueIfMinusSign); ctrl.$formatters.push(formatter); ctrl.$parsers.push(parser); if (attrs.uiNumberMask) { scope.$watch(attrs.uiNumberMask, function(_decimals) { decimals = isNaN(_decimals) ? 2 : _decimals; viewMask = NumberMasks.viewMask(decimals, decimalDelimiter, thousandsDelimiter); modelMask = NumberMasks.modelMask(decimals); parser(ctrl.$viewValue); }); } if (attrs.min) { var minVal; ctrl.$validators.min = function(modelValue) { return validators.minNumber(ctrl, modelValue, minVal); }; scope.$watch(attrs.min, function(value) { minVal = value; ctrl.$validate(); }); } if (attrs.max) { var maxVal; ctrl.$validators.max = function(modelValue) { return validators.maxNumber(ctrl, modelValue, maxVal); }; scope.$watch(attrs.max, function(value) { maxVal = value; ctrl.$validate(); }); } } }; } NumberMaskDirective.$inject = ['$locale', '$parse', 'PreFormatters', 'NumberMasks']; module.exports = NumberMaskDirective; },{"validators":"validators"}],19:[function(require,module,exports){ 'use strict'; var validators = require('validators'); function PercentageMaskDirective($locale, $parse, PreFormatters, NumberMasks) { function preparePercentageToFormatter(value, decimals, modelMultiplier) { return PreFormatters.clearDelimitersAndLeadingZeros((parseFloat(value)*modelMultiplier).toFixed(decimals)); } return { restrict: 'A', require: 'ngModel', link: function(scope, element, attrs, ctrl) { var decimalDelimiter = $locale.NUMBER_FORMATS.DECIMAL_SEP, thousandsDelimiter = $locale.NUMBER_FORMATS.GROUP_SEP, decimals = parseInt(attrs.uiPercentageMask), hideSpace = false, backspacePressed = false; element.bind('keydown keypress', function(event) { backspacePressed = event.which === 8; }); var modelValue = { multiplier : 100, decimalMask: 2 }; if (angular.isDefined(attrs.uiHideGroupSep)) { thousandsDelimiter = ''; } if (angular.isDefined(attrs.uiHideSpace)) { hideSpace = true; } if (angular.isDefined(attrs.uiPercentageValue)) { modelValue.multiplier = 1; modelValue.decimalMask = 0; } if (isNaN(decimals)) { decimals = 2; } var numberDecimals = decimals + modelValue.decimalMask; var viewMask = NumberMasks.viewMask(decimals, decimalDelimiter, thousandsDelimiter), modelMask = NumberMasks.modelMask(numberDecimals); function formatter(value) { if (ctrl.$isEmpty(value)) { return value; } var valueToFormat = preparePercentageToFormatter(value, decimals, modelValue.multiplier); return viewMask.apply(valueToFormat) + (hideSpace ? '%' : ' %'); } function parse(value) { if (ctrl.$isEmpty(value)) { return null; } var valueToFormat = PreFormatters.clearDelimitersAndLeadingZeros(value) || '0'; if (value.length > 1 && value.indexOf('%') === -1) { valueToFormat = valueToFormat.slice(0,valueToFormat.length-1); } if (backspacePressed && value.length === 1 && value !== '%') { valueToFormat = '0'; } var percentSign = hideSpace ? '%' : ' %'; var formatedValue = viewMask.apply(valueToFormat) + percentSign; var actualNumber = parseFloat(modelMask.apply(valueToFormat)); if (ctrl.$viewValue !== formatedValue) { ctrl.$setViewValue(formatedValue); ctrl.$render(); } return actualNumber; } ctrl.$formatters.push(formatter); ctrl.$parsers.push(parse); if (attrs.uiPercentageMask) { scope.$watch(attrs.uiPercentageMask, function(_decimals) { decimals = isNaN(_decimals) ? 2 : _decimals; if (angular.isDefined(attrs.uiPercentageValue)) { modelValue.multiplier = 1; modelValue.decimalMask = 0; } numberDecimals = decimals + modelValue.decimalMask; viewMask = NumberMasks.viewMask(decimals, decimalDelimiter, thousandsDelimiter); modelMask = NumberMasks.modelMask(numberDecimals); parse(ctrl.$viewValue); }); } if (attrs.min) { var minVal; ctrl.$validators.min = function(modelValue) { return validators.minNumber(ctrl, modelValue, minVal); }; scope.$watch(attrs.min, function(value) { minVal = value; ctrl.$validate(); }); } if (attrs.max) { var maxVal; ctrl.$validators.max = function(modelValue) { return validators.maxNumber(ctrl, modelValue, maxVal); }; scope.$watch(attrs.max, function(value) { maxVal = value; ctrl.$validate(); }); } } }; } PercentageMaskDirective.$inject = ['$locale', '$parse', 'PreFormatters', 'NumberMasks']; module.exports = PercentageMaskDirective; },{"validators":"validators"}],20:[function(require,module,exports){ 'use strict'; var StringMask = require('string-mask'); function ScientificNotationMaskDirective($locale, $parse) { var decimalDelimiter = $locale.NUMBER_FORMATS.DECIMAL_SEP, defaultPrecision = 2; function significandMaskBuilder(decimals) { var mask = '0'; if (decimals > 0) { mask += decimalDelimiter; for (var i = 0; i < decimals; i++) { mask += '0'; } } return new StringMask(mask, { reverse: true }); } return { restrict: 'A', require: 'ngModel', link: function(scope, element, attrs, ctrl) { var decimals = $parse(attrs.uiScientificNotationMask)(scope); if (isNaN(decimals)) { decimals = defaultPrecision; } var significandMask = significandMaskBuilder(decimals); function splitNumber(value) { var stringValue = value.toString(), splittedNumber = stringValue.match(/(-?[0-9]*)[\.]?([0-9]*)?[Ee]?([\+-]?[0-9]*)?/); return { integerPartOfSignificand: splittedNumber[1], decimalPartOfSignificand: splittedNumber[2], exponent: splittedNumber[3] | 0 }; } function formatter(value) { if (ctrl.$isEmpty(value)) { return value; } if (typeof value === 'string') { value = value.replace(decimalDelimiter, '.'); } else if (typeof value === 'number') { value = value.toExponential(decimals); } var formattedValue, exponent; var splittedNumber = splitNumber(value); var integerPartOfSignificand = splittedNumber.integerPartOfSignificand || 0; var numberToFormat = integerPartOfSignificand.toString(); if (angular.isDefined(splittedNumber.decimalPartOfSignificand)) { numberToFormat += splittedNumber.decimalPartOfSignificand; } var needsNormalization = (integerPartOfSignificand >= 1 || integerPartOfSignificand <= -1) && ( (angular.isDefined(splittedNumber.decimalPartOfSignificand) && splittedNumber.decimalPartOfSignificand.length > decimals) || (decimals === 0 && numberToFormat.length >= 2) ); if (needsNormalization) { exponent = numberToFormat.slice(decimals + 1, numberToFormat.length); numberToFormat = numberToFormat.slice(0, decimals + 1); } formattedValue = significandMask.apply(numberToFormat); if (splittedNumber.exponent !== 0) { exponent = splittedNumber.exponent; } if (angular.isDefined(exponent)) { formattedValue += 'e' + exponent; } return formattedValue; } function parser(value) { if (ctrl.$isEmpty(value)) { return value; } var viewValue = formatter(value), modelValue = parseFloat(viewValue.replace(decimalDelimiter, '.')); if (ctrl.$viewValue !== viewValue) { ctrl.$setViewValue(viewValue); ctrl.$render(); } return modelValue; } ctrl.$formatters.push(formatter); ctrl.$parsers.push(parser); ctrl.$validators.max = function validator(value) { return ctrl.$isEmpty(value) || value < Number.MAX_VALUE; }; } }; } ScientificNotationMaskDirective.$inject = ['$locale', '$parse']; module.exports = ScientificNotationMaskDirective; },{"string-mask":undefined}],21:[function(require,module,exports){ 'use strict'; var StringMask = require('string-mask'); module.exports = function TimeMaskDirective() { return { restrict: 'A', require: 'ngModel', link: function(scope, element, attrs, ctrl) { var timeFormat = '00:00:00'; if (angular.isDefined(attrs.uiTimeMask) && attrs.uiTimeMask === 'short') { timeFormat = '00:00'; } var formattedValueLength = timeFormat.length; var unformattedValueLength = timeFormat.replace(':', '').length; var timeMask = new StringMask(timeFormat); function formatter(value) { if (ctrl.$isEmpty(value)) { return value; } var cleanValue = value.replace(/[^0-9]/g, '').slice(0, unformattedValueLength) || ''; return (timeMask.apply(cleanValue) || '').replace(/[^0-9]$/, ''); } ctrl.$formatters.push(formatter); ctrl.$parsers.push(function parser(value) { if (ctrl.$isEmpty(value)) { return value; } var viewValue = formatter(value); var modelValue = viewValue; if (ctrl.$viewValue !== viewValue) { ctrl.$setViewValue(viewValue); ctrl.$render(); } return modelValue; }); ctrl.$validators.time = function(modelValue) { if (ctrl.$isEmpty(modelValue)) { return true; } var splittedValue = modelValue.toString().split(/:/).filter(function(v) { return !!v; }); var hours = parseInt(splittedValue[0]), minutes = parseInt(splittedValue[1]), seconds = parseInt(splittedValue[2] || 0); return modelValue.toString().length === formattedValueLength && hours < 24 && minutes < 60 && seconds < 60; }; } }; }; },{"string-mask":undefined}],22:[function(require,module,exports){ 'use strict'; var StringMask = require('string-mask'); var m = angular.module('ui.utils.masks.helpers', []); module.exports = m.name; m.factory('PreFormatters', [function() { function clearDelimitersAndLeadingZeros(value) { if (value === '0') { return '0'; } var cleanValue = value.replace(/^-/,'').replace(/^0*/, ''); return cleanValue.replace(/[^0-9]/g, ''); } function prepareNumberToFormatter(value, decimals) { return clearDelimitersAndLeadingZeros((parseFloat(value)).toFixed(decimals)); } return { clearDelimitersAndLeadingZeros: clearDelimitersAndLeadingZeros, prepareNumberToFormatter: prepareNumberToFormatter }; }]) .factory('NumberMasks', [function() { return { viewMask: function(decimals, decimalDelimiter, thousandsDelimiter) { var mask = '#' + thousandsDelimiter + '##0'; if (decimals > 0) { mask += decimalDelimiter; for (var i = 0; i < decimals; i++) { mask += '0'; } } return new StringMask(mask, { reverse: true }); }, modelMask: function(decimals) { var mask = '###0'; if (decimals > 0) { mask += '.'; for (var i = 0; i < decimals; i++) { mask += '0'; } } return new StringMask(mask, { reverse: true }); } }; }]); },{"string-mask":undefined}],23:[function(require,module,exports){ 'use strict'; var StringMask = require('string-mask'); var maskFactory = require('mask-factory'); var phoneMaskUS = new StringMask('(000) 000-0000'), phoneMaskINTL = new StringMask('+00-00-000-000000'); module.exports = maskFactory({ clearValue: function(rawValue) { return rawValue.toString().replace(/[^0-9]/g, ''); }, format: function(cleanValue) { var formattedValue; if (cleanValue.length < 11) { formattedValue = phoneMaskUS.apply(cleanValue) || ''; } else { formattedValue = phoneMaskINTL.apply(cleanValue); } return formattedValue.trim().replace(/[^0-9]$/, ''); }, validations: { usPhoneNumber: function(value) { return value && value.toString().length > 9; } } }); },{"mask-factory":"mask-factory","string-mask":undefined}],24:[function(require,module,exports){ 'use strict'; var m = angular.module('ui.utils.masks.us', [ require('../helpers') ]) .directive('uiUsPhoneNumber', require('./phone/us-phone')); module.exports = m.name; },{"../helpers":22,"./phone/us-phone":23}],"mask-factory":[function(require,module,exports){ 'use strict'; module.exports = function maskFactory(maskDefinition) { return function MaskDirective() { return { restrict: 'A', require: 'ngModel', link: function(scope, element, attrs, ctrl) { ctrl.$formatters.push(function formatter(value) { if (ctrl.$isEmpty(value)) { return value; } var cleanValue = maskDefinition.clearValue(value); return maskDefinition.format(cleanValue); }); ctrl.$parsers.push(function parser(value) { if (ctrl.$isEmpty(value)) { return value; } var cleanValue = maskDefinition.clearValue(value); var formattedValue = maskDefinition.format(cleanValue); if (ctrl.$viewValue !== formattedValue) { ctrl.$setViewValue(formattedValue); ctrl.$render(); } if (angular.isUndefined(maskDefinition.getModelValue)) { return cleanValue; } var actualModelType = typeof ctrl.$modelValue; return maskDefinition.getModelValue(formattedValue, actualModelType); }); angular.forEach(maskDefinition.validations, function(validatorFn, validationErrorKey) { ctrl.$validators[validationErrorKey] = function validator(modelValue, viewValue) { return ctrl.$isEmpty(modelValue) || validatorFn(modelValue, viewValue); }; }); } }; }; }; },{}],"validators":[function(require,module,exports){ 'use strict'; module.exports = { maxNumber: function(ctrl, value, limit) { var max = parseFloat(limit, 10); return ctrl.$isEmpty(value) || isNaN(max) || value <= max; }, minNumber: function(ctrl, value, limit) { var min = parseFloat(limit, 10); return ctrl.$isEmpty(value) || isNaN(min) || value >= min; } }; },{}]},{},[1]);
Package.describe({ name: 'rocketchat:ui-master', version: '0.1.0', // Brief, one-line summary of the package. summary: '', // URL to the Git repository containing the source code for this package. git: '', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Npm.depends({ 'clipboard': '1.5.12' }); Package.onUse(function(api) { api.use([ 'mongo', 'ecmascript', 'templating', 'coffeescript', 'underscore', 'rocketchat:lib', 'meteorhacks:inject-initial' ]); api.addFiles('master/main.html', 'client'); api.addFiles('master/loading.html', 'client'); api.addFiles('master/error.html', 'client'); api.addFiles('master/logoLayout.html', 'client'); api.addFiles('master/main.coffee', 'client'); api.addFiles('server/inject.js', 'server'); });
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'format', 'en', { label: 'Format', panelTitle: 'Paragraph Format', tag_address: 'Address', tag_div: 'Normal (DIV)', tag_h1: 'Heading 1', tag_h2: 'Heading 2', tag_h3: 'Heading 3', tag_h4: 'Heading 4', tag_h5: 'Heading 5', tag_h6: 'Heading 6', tag_p: 'Normal', tag_pre: 'Formatted' } );
'use strict'; exports.__esModule = true; var _ReactUpdates = require('react-dom/lib/ReactUpdates'); var _ReactUpdates2 = _interopRequireDefault(_ReactUpdates); var _createUncontrollable = require('./createUncontrollable'); var _createUncontrollable2 = _interopRequireDefault(_createUncontrollable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var mixin = { componentWillReceiveProps: function componentWillReceiveProps() { // if the update already happend then don't fire it twice this._needsUpdate = false; } }; function set(component, propName, handler, value, args) { component._needsUpdate = true; component._values[propName] = value; if (handler) handler.call.apply(handler, [component, value].concat(args)); _ReactUpdates2.default.batchedUpdates(function () { _ReactUpdates2.default.asap(function () { if (!component.unmounted && component._needsUpdate) { component._needsUpdate = false; if (!component.unmounted) component.forceUpdate(); } }); }); } exports.default = (0, _createUncontrollable2.default)(mixin, set); module.exports = exports['default'];
/** @module ember @submodule ember-runtime */ import Ember from "ember-metal/core"; // Ember.STRINGS, Ember.FEATURES import { isArray, inspect as emberInspect } from "ember-metal/utils"; import Cache from "ember-metal/cache"; var STRING_DASHERIZE_REGEXP = (/[ _]/g); var STRING_DASHERIZE_CACHE = new Cache(1000, function(key) { return decamelize(key).replace(STRING_DASHERIZE_REGEXP, '-'); }); var CAMELIZE_CACHE = new Cache(1000, function(key) { return key.replace(STRING_CAMELIZE_REGEXP, function(match, separator, chr) { return chr ? chr.toUpperCase() : ''; }).replace(/^([A-Z])/, function(match, separator, chr) { return match.toLowerCase(); }); }); var CLASSIFY_CACHE = new Cache(1000, function(str) { var parts = str.split("."); var out = []; for (var i=0, l=parts.length; i<l; i++) { var camelized = camelize(parts[i]); out.push(camelized.charAt(0).toUpperCase() + camelized.substr(1)); } return out.join("."); }); var UNDERSCORE_CACHE = new Cache(1000, function(str) { return str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2'). replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase(); }); var CAPITALIZE_CACHE = new Cache(1000, function(str) { return str.charAt(0).toUpperCase() + str.substr(1); }); var DECAMELIZE_CACHE = new Cache(1000, function(str) { return str.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase(); }); var STRING_DECAMELIZE_REGEXP = (/([a-z\d])([A-Z])/g); var STRING_CAMELIZE_REGEXP = (/(\-|_|\.|\s)+(.)?/g); var STRING_UNDERSCORE_REGEXP_1 = (/([a-z\d])([A-Z]+)/g); var STRING_UNDERSCORE_REGEXP_2 = (/\-|\s+/g); function fmt(str, formats) { var cachedFormats = formats; if (!isArray(cachedFormats) || arguments.length > 2) { cachedFormats = new Array(arguments.length - 1); for (var i = 1, l = arguments.length; i < l; i++) { cachedFormats[i - 1] = arguments[i]; } } // first, replace any ORDERED replacements. var idx = 0; // the current index for non-numerical replacements return str.replace(/%@([0-9]+)?/g, function(s, argIndex) { argIndex = (argIndex) ? parseInt(argIndex, 10) - 1 : idx++; s = cachedFormats[argIndex]; return (s === null) ? '(null)' : (s === undefined) ? '' : emberInspect(s); }); } function loc(str, formats) { if (!isArray(formats) || arguments.length > 2) { formats = Array.prototype.slice.call(arguments, 1); } str = Ember.STRINGS[str] || str; return fmt(str, formats); } function w(str) { return str.split(/\s+/); } function decamelize(str) { return DECAMELIZE_CACHE.get(str); } function dasherize(str) { return STRING_DASHERIZE_CACHE.get(str); } function camelize(str) { return CAMELIZE_CACHE.get(str); } function classify(str) { return CLASSIFY_CACHE.get(str); } function underscore(str) { return UNDERSCORE_CACHE.get(str); } function capitalize(str) { return CAPITALIZE_CACHE.get(str); } /** Defines the hash of localized strings for the current language. Used by the `Ember.String.loc()` helper. To localize, add string values to this hash. @property STRINGS @for Ember @type Hash */ Ember.STRINGS = {}; /** Defines string helper methods including string formatting and localization. Unless `Ember.EXTEND_PROTOTYPES.String` is `false` these methods will also be added to the `String.prototype` as well. @class String @namespace Ember @static */ export default { /** Apply formatting options to the string. This will look for occurrences of "%@" in your string and substitute them with the arguments you pass into this method. If you want to control the specific order of replacement, you can add a number after the key as well to indicate which argument you want to insert. Ordered insertions are most useful when building loc strings where values you need to insert may appear in different orders. ```javascript "Hello %@ %@".fmt('John', 'Doe'); // "Hello John Doe" "Hello %@2, %@1".fmt('John', 'Doe'); // "Hello Doe, John" ``` @method fmt @param {String} str The string to format @param {Array} formats An array of parameters to interpolate into string. @return {String} formatted string */ fmt: fmt, /** Formats the passed string, but first looks up the string in the localized strings hash. This is a convenient way to localize text. See `Ember.String.fmt()` for more information on formatting. Note that it is traditional but not required to prefix localized string keys with an underscore or other character so you can easily identify localized strings. ```javascript Ember.STRINGS = { '_Hello World': 'Bonjour le monde', '_Hello %@ %@': 'Bonjour %@ %@' }; Ember.String.loc("_Hello World"); // 'Bonjour le monde'; Ember.String.loc("_Hello %@ %@", ["John", "Smith"]); // "Bonjour John Smith"; ``` @method loc @param {String} str The string to format @param {Array} formats Optional array of parameters to interpolate into string. @return {String} formatted string */ loc: loc, /** Splits a string into separate units separated by spaces, eliminating any empty strings in the process. This is a convenience method for split that is mostly useful when applied to the `String.prototype`. ```javascript Ember.String.w("alpha beta gamma").forEach(function(key) { console.log(key); }); // > alpha // > beta // > gamma ``` @method w @param {String} str The string to split @return {Array} array containing the split strings */ w: w, /** Converts a camelized string into all lower case separated by underscores. ```javascript 'innerHTML'.decamelize(); // 'inner_html' 'action_name'.decamelize(); // 'action_name' 'css-class-name'.decamelize(); // 'css-class-name' 'my favorite items'.decamelize(); // 'my favorite items' ``` @method decamelize @param {String} str The string to decamelize. @return {String} the decamelized string. */ decamelize: decamelize, /** Replaces underscores, spaces, or camelCase with dashes. ```javascript 'innerHTML'.dasherize(); // 'inner-html' 'action_name'.dasherize(); // 'action-name' 'css-class-name'.dasherize(); // 'css-class-name' 'my favorite items'.dasherize(); // 'my-favorite-items' ``` @method dasherize @param {String} str The string to dasherize. @return {String} the dasherized string. */ dasherize: dasherize, /** Returns the lowerCamelCase form of a string. ```javascript 'innerHTML'.camelize(); // 'innerHTML' 'action_name'.camelize(); // 'actionName' 'css-class-name'.camelize(); // 'cssClassName' 'my favorite items'.camelize(); // 'myFavoriteItems' 'My Favorite Items'.camelize(); // 'myFavoriteItems' ``` @method camelize @param {String} str The string to camelize. @return {String} the camelized string. */ camelize: camelize, /** Returns the UpperCamelCase form of a string. ```javascript 'innerHTML'.classify(); // 'InnerHTML' 'action_name'.classify(); // 'ActionName' 'css-class-name'.classify(); // 'CssClassName' 'my favorite items'.classify(); // 'MyFavoriteItems' ``` @method classify @param {String} str the string to classify @return {String} the classified string */ classify: classify, /** More general than decamelize. Returns the lower\_case\_and\_underscored form of a string. ```javascript 'innerHTML'.underscore(); // 'inner_html' 'action_name'.underscore(); // 'action_name' 'css-class-name'.underscore(); // 'css_class_name' 'my favorite items'.underscore(); // 'my_favorite_items' ``` @method underscore @param {String} str The string to underscore. @return {String} the underscored string. */ underscore: underscore, /** Returns the Capitalized form of a string ```javascript 'innerHTML'.capitalize() // 'InnerHTML' 'action_name'.capitalize() // 'Action_name' 'css-class-name'.capitalize() // 'Css-class-name' 'my favorite items'.capitalize() // 'My favorite items' ``` @method capitalize @param {String} str The string to capitalize. @return {String} The capitalized string. */ capitalize: capitalize }; export { fmt, loc, w, decamelize, dasherize, camelize, classify, underscore, capitalize };
/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextComponent */ 'use strict'; var _assign = require('object-assign'); var DOMChildrenOperations = require('./DOMChildrenOperations'); var DOMLazyTree = require('./DOMLazyTree'); var ReactDOMComponentTree = require('./ReactDOMComponentTree'); var ReactPerf = require('./ReactPerf'); var escapeTextContentForBrowser = require('./escapeTextContentForBrowser'); var invariant = require('fbjs/lib/invariant'); var validateDOMNesting = require('./validateDOMNesting'); /** * Text nodes violate a couple assumptions that React makes about components: * * - When mounting text into the DOM, adjacent text nodes are merged. * - Text nodes cannot be assigned a React root ID. * * This component is used to wrap strings between comment nodes so that they * can undergo the same reconciliation that is applied to elements. * * TODO: Investigate representing React components in the DOM with text nodes. * * @class ReactDOMTextComponent * @extends ReactComponent * @internal */ var ReactDOMTextComponent = function (text) { // TODO: This is really a ReactText (ReactNode), not a ReactElement this._currentElement = text; this._stringText = '' + text; // ReactDOMComponentTree uses these: this._nativeNode = null; this._nativeParent = null; // Properties this._domID = null; this._mountIndex = 0; this._closingComment = null; this._commentNodes = null; }; _assign(ReactDOMTextComponent.prototype, { /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup for this text node. * @internal */ mountComponent: function (transaction, nativeParent, nativeContainerInfo, context) { if (process.env.NODE_ENV !== 'production') { var parentInfo; if (nativeParent != null) { parentInfo = nativeParent._ancestorInfo; } else if (nativeContainerInfo != null) { parentInfo = nativeContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting('#text', this, parentInfo); } } var domID = nativeContainerInfo._idCounter++; var openingValue = ' react-text: ' + domID + ' '; var closingValue = ' /react-text '; this._domID = domID; this._nativeParent = nativeParent; if (transaction.useCreateElement) { var ownerDocument = nativeContainerInfo._ownerDocument; var openingComment = ownerDocument.createComment(openingValue); var closingComment = ownerDocument.createComment(closingValue); var lazyTree = DOMLazyTree(ownerDocument.createDocumentFragment()); DOMLazyTree.queueChild(lazyTree, DOMLazyTree(openingComment)); if (this._stringText) { DOMLazyTree.queueChild(lazyTree, DOMLazyTree(ownerDocument.createTextNode(this._stringText))); } DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment)); ReactDOMComponentTree.precacheNode(this, openingComment); this._closingComment = closingComment; return lazyTree; } else { var escapedText = escapeTextContentForBrowser(this._stringText); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this between comment nodes for the reasons stated // above, but since this is a situation where React won't take over // (static pages), we can simply return the text as it is. return escapedText; } return '<!--' + openingValue + '-->' + escapedText + '<!--' + closingValue + '-->'; } }, /** * Updates this component by updating the text content. * * @param {ReactText} nextText The next text content * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function (nextText, transaction) { if (nextText !== this._currentElement) { this._currentElement = nextText; var nextStringText = '' + nextText; if (nextStringText !== this._stringText) { // TODO: Save this as pending props and use performUpdateIfNecessary // and/or updateComponent to do the actual update for consistency with // other component types? this._stringText = nextStringText; var commentNodes = this.getNativeNode(); DOMChildrenOperations.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText); } } }, getNativeNode: function () { var nativeNode = this._commentNodes; if (nativeNode) { return nativeNode; } if (!this._closingComment) { var openingComment = ReactDOMComponentTree.getNodeFromInstance(this); var node = openingComment.nextSibling; while (true) { !(node != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Missing closing comment for text component %s', this._domID) : invariant(false) : void 0; if (node.nodeType === 8 && node.nodeValue === ' /react-text ') { this._closingComment = node; break; } node = node.nextSibling; } } nativeNode = [this._nativeNode, this._closingComment]; this._commentNodes = nativeNode; return nativeNode; }, unmountComponent: function () { this._closingComment = null; this._commentNodes = null; ReactDOMComponentTree.uncacheNode(this); } }); ReactPerf.measureMethods(ReactDOMTextComponent.prototype, 'ReactDOMTextComponent', { mountComponent: 'mountComponent', receiveComponent: 'receiveComponent' }); module.exports = ReactDOMTextComponent;
/* Copyright (c) 2006-2013 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/BaseTypes/Class.js */ /** * Class: OpenLayers.Control * Controls affect the display or behavior of the map. They allow everything * from panning and zooming to displaying a scale indicator. Controls by * default are added to the map they are contained within however it is * possible to add a control to an external div by passing the div in the * options parameter. * * Example: * The following example shows how to add many of the common controls * to a map. * * > var map = new OpenLayers.Map('map', { controls: [] }); * > * > map.addControl(new OpenLayers.Control.PanZoomBar()); * > map.addControl(new OpenLayers.Control.LayerSwitcher({'ascending':false})); * > map.addControl(new OpenLayers.Control.Permalink()); * > map.addControl(new OpenLayers.Control.Permalink('permalink')); * > map.addControl(new OpenLayers.Control.MousePosition()); * > map.addControl(new OpenLayers.Control.OverviewMap()); * > map.addControl(new OpenLayers.Control.KeyboardDefaults()); * * The next code fragment is a quick example of how to intercept * shift-mouse click to display the extent of the bounding box * dragged out by the user. Usually controls are not created * in exactly this manner. See the source for a more complete * example: * * > var control = new OpenLayers.Control(); * > OpenLayers.Util.extend(control, { * > draw: function () { * > // this Handler.Box will intercept the shift-mousedown * > // before Control.MouseDefault gets to see it * > this.box = new OpenLayers.Handler.Box( control, * > {"done": this.notice}, * > {keyMask: OpenLayers.Handler.MOD_SHIFT}); * > this.box.activate(); * > }, * > * > notice: function (bounds) { * > OpenLayers.Console.userError(bounds); * > } * > }); * > map.addControl(control); * */ OpenLayers.Control = OpenLayers.Class({ /** * Property: id * {String} */ id: null, /** * Property: map * {<OpenLayers.Map>} this gets set in the addControl() function in * OpenLayers.Map */ map: null, /** * APIProperty: div * {DOMElement} The element that contains the control, if not present the * control is placed inside the map. */ div: null, /** * APIProperty: type * {Number} Controls can have a 'type'. The type determines the type of * interactions which are possible with them when they are placed in an * <OpenLayers.Control.Panel>. */ type: null, /** * Property: allowSelection * {Boolean} By default, controls do not allow selection, because * it may interfere with map dragging. If this is true, OpenLayers * will not prevent selection of the control. * Default is false. */ allowSelection: false, /** * Property: displayClass * {string} This property is used for CSS related to the drawing of the * Control. */ displayClass: "", /** * APIProperty: title * {string} This property is used for showing a tooltip over the * Control. */ title: "", /** * APIProperty: autoActivate * {Boolean} Activate the control when it is added to a map. Default is * false. */ autoActivate: false, /** * APIProperty: active * {Boolean} The control is active (read-only). Use <activate> and * <deactivate> to change control state. */ active: null, /** * Property: handlerOptions * {Object} Used to set non-default properties on the control's handler */ handlerOptions: null, /** * Property: handler * {<OpenLayers.Handler>} null */ handler: null, /** * APIProperty: eventListeners * {Object} If set as an option at construction, the eventListeners * object will be registered with <OpenLayers.Events.on>. Object * structure must be a listeners object as shown in the example for * the events.on method. */ eventListeners: null, /** * APIProperty: events * {<OpenLayers.Events>} Events instance for listeners and triggering * control specific events. * * Register a listener for a particular event with the following syntax: * (code) * control.events.register(type, obj, listener); * (end) * * Listeners will be called with a reference to an event object. The * properties of this event depends on exactly what happened. * * All event objects have at least the following properties: * object - {Object} A reference to control.events.object (a reference * to the control). * element - {DOMElement} A reference to control.events.element (which * will be null unless documented otherwise). * * Supported map event types: * activate - Triggered when activated. * deactivate - Triggered when deactivated. */ events: null, /** * Constructor: OpenLayers.Control * Create an OpenLayers Control. The options passed as a parameter * directly extend the control. For example passing the following: * * > var control = new OpenLayers.Control({div: myDiv}); * * Overrides the default div attribute value of null. * * Parameters: * options - {Object} */ initialize: function (options) { // We do this before the extend so that instances can override // className in options. this.displayClass = this.CLASS_NAME.replace("OpenLayers.", "ol").replace(/\./g, ""); OpenLayers.Util.extend(this, options); this.events = new OpenLayers.Events(this); if(this.eventListeners instanceof Object) { this.events.on(this.eventListeners); } if (this.id == null) { this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_"); } }, /** * Method: destroy * The destroy method is used to perform any clean up before the control * is dereferenced. Typically this is where event listeners are removed * to prevent memory leaks. */ destroy: function () { if(this.events) { if(this.eventListeners) { this.events.un(this.eventListeners); } this.events.destroy(); this.events = null; } this.eventListeners = null; // eliminate circular references if (this.handler) { this.handler.destroy(); this.handler = null; } if(this.handlers) { for(var key in this.handlers) { if(this.handlers.hasOwnProperty(key) && typeof this.handlers[key].destroy == "function") { this.handlers[key].destroy(); } } this.handlers = null; } if (this.map) { this.map.removeControl(this); this.map = null; } this.div = null; }, /** * Method: setMap * Set the map property for the control. This is done through an accessor * so that subclasses can override this and take special action once * they have their map variable set. * * Parameters: * map - {<OpenLayers.Map>} */ setMap: function(map) { this.map = map; if (this.handler) { this.handler.setMap(map); } }, /** * Method: draw * The draw method is called when the control is ready to be displayed * on the page. If a div has not been created one is created. Controls * with a visual component will almost always want to override this method * to customize the look of control. * * Parameters: * px - {<OpenLayers.Pixel>} The top-left pixel position of the control * or null. * * Returns: * {DOMElement} A reference to the DIV DOMElement containing the control */ draw: function (px) { if (this.div == null) { this.div = OpenLayers.Util.createDiv(this.id); this.div.className = this.displayClass; if (!this.allowSelection) { this.div.className += " olControlNoSelect"; this.div.setAttribute("unselectable", "on", 0); this.div.onselectstart = OpenLayers.Function.False; } if (this.title != "") { this.div.title = this.title; } } if (px != null) { this.position = px.clone(); } this.moveTo(this.position); return this.div; }, /** * Method: moveTo * Sets the left and top style attributes to the passed in pixel * coordinates. * * Parameters: * px - {<OpenLayers.Pixel>} */ moveTo: function (px) { if ((px != null) && (this.div != null)) { this.div.style.left = px.x + "px"; this.div.style.top = px.y + "px"; } }, /** * APIMethod: activate * Explicitly activates a control and its associated * handler if one has been set. Controls can be * deactivated by calling the deactivate() method. * * Returns: * {Boolean} True if the control was successfully activated or * false if the control was already active. */ activate: function () { if (this.active) { return false; } if (this.handler) { this.handler.activate(); } this.active = true; if(this.map) { OpenLayers.Element.addClass( this.map.viewPortDiv, this.displayClass.replace(/ /g, "") + "Active" ); } this.events.triggerEvent("activate"); return true; }, /** * APIMethod: deactivate * Deactivates a control and its associated handler if any. The exact * effect of this depends on the control itself. * * Returns: * {Boolean} True if the control was effectively deactivated or false * if the control was already inactive. */ deactivate: function () { if (this.active) { if (this.handler) { this.handler.deactivate(); } this.active = false; if(this.map) { OpenLayers.Element.removeClass( this.map.viewPortDiv, this.displayClass.replace(/ /g, "") + "Active" ); } this.events.triggerEvent("deactivate"); return true; } return false; }, CLASS_NAME: "OpenLayers.Control" }); /** * Constant: OpenLayers.Control.TYPE_BUTTON */ OpenLayers.Control.TYPE_BUTTON = 1; /** * Constant: OpenLayers.Control.TYPE_TOGGLE */ OpenLayers.Control.TYPE_TOGGLE = 2; /** * Constant: OpenLayers.Control.TYPE_TOOL */ OpenLayers.Control.TYPE_TOOL = 3;
define( [ "qunit", "jquery", "./helper", "ui/widgets/draggable" ], function( QUnit, $, testHelper ) { var element; QUnit.module( "draggable: methods", { beforeEach: function() { element = $( "<div style='background: green; width: 200px; height: 100px; position: absolute; top: 10px; left: 10px;'><span>Absolute</span></div>" ).appendTo( "#qunit-fixture" ); }, afterEach: function() { element.remove(); } } ); QUnit.test( "init", function( assert ) { assert.expect( 5 ); element.draggable(); assert.ok( true, ".draggable() called on element" ); $( [] ).draggable(); assert.ok( true, ".draggable() called on empty collection" ); $( "<div></div>" ).draggable(); assert.ok( true, ".draggable() called on disconnected DOMElement" ); element.draggable( "option", "foo" ); assert.ok( true, "arbitrary option getter after init" ); element.draggable( "option", "foo", "bar" ); assert.ok( true, "arbitrary option setter after init" ); } ); QUnit.test( "destroy", function( assert ) { assert.expect( 4 ); element.draggable().draggable( "destroy" ); assert.ok( true, ".draggable('destroy') called on element" ); $( [] ).draggable().draggable( "destroy" ); assert.ok( true, ".draggable('destroy') called on empty collection" ); element.draggable().draggable( "destroy" ); assert.ok( true, ".draggable('destroy') called on disconnected DOMElement" ); var expected = element.draggable(), actual = expected.draggable( "destroy" ); assert.equal( actual, expected, "destroy is chainable" ); } ); QUnit.test( "enable", function( assert ) { assert.expect( 11 ); element.draggable( { disabled: true } ); testHelper.shouldNotDrag( assert, element, ".draggable({ disabled: true })" ); element.draggable( "enable" ); testHelper.shouldMove( assert, element, ".draggable('enable')" ); assert.equal( element.draggable( "option", "disabled" ), false, "disabled option getter" ); element.draggable( "destroy" ); element.draggable( { disabled: true } ); testHelper.shouldNotDrag( assert, element, ".draggable({ disabled: true })" ); element.draggable( "option", "disabled", false ); assert.equal( element.draggable( "option", "disabled" ), false, "disabled option setter" ); testHelper.shouldMove( assert, element, ".draggable('option', 'disabled', false)" ); var expected = element.draggable(), actual = expected.draggable( "enable" ); assert.equal( actual, expected, "enable is chainable" ); } ); QUnit.test( "disable", function( assert ) { assert.expect( 14 ); element = $( "#draggable2" ).draggable( { disabled: false } ); testHelper.shouldMove( assert, element, ".draggable({ disabled: false })" ); element.draggable( "disable" ); testHelper.shouldNotDrag( assert, element, ".draggable('disable')" ); assert.equal( element.draggable( "option", "disabled" ), true, "disabled option getter" ); element.draggable( "destroy" ); element.draggable( { disabled: false } ); testHelper.shouldMove( assert, element, ".draggable({ disabled: false })" ); element.draggable( "option", "disabled", true ); assert.equal( element.draggable( "option", "disabled" ), true, "disabled option setter" ); testHelper.shouldNotDrag( assert, element, ".draggable('option', 'disabled', true)" ); assert.lacksClasses( element.draggable( "widget" ), "ui-state-disabled" ); assert.ok( !element.draggable( "widget" ).attr( "aria-disabled" ), "element does not get aria-disabled" ); assert.hasClasses( element.draggable( "widget" ), "ui-draggable-disabled" ); var expected = element.draggable(), actual = expected.draggable( "disable" ); assert.equal( actual, expected, "disable is chainable" ); } ); } );
/** * @author Chad Engler <[email protected]> */ /** * The Circle object can be used to specify a hit area for displayobjects * * @class Circle * @constructor * @param x {Number} The X coord of the upper-left corner of the framing rectangle of this circle * @param y {Number} The Y coord of the upper-left corner of the framing rectangle of this circle * @param radius {Number} The radius of the circle */ PIXI.Circle = function(x, y, radius) { /** * @property x * @type Number * @default 0 */ this.x = x || 0; /** * @property y * @type Number * @default 0 */ this.y = y || 0; /** * @property radius * @type Number * @default 0 */ this.radius = radius || 0; }; /** * Creates a clone of this Circle instance * * @method clone * @return {Circle} a copy of the polygon */ PIXI.Circle.prototype.clone = function() { return new PIXI.Circle(this.x, this.y, this.radius); }; /** * Checks if the x, and y coords passed to this function are contained within this circle * * @method contains * @param x {Number} The X coord of the point to test * @param y {Number} The Y coord of the point to test * @return {Boolean} if the x/y coords are within this polygon */ PIXI.Circle.prototype.contains = function(x, y) { if(this.radius <= 0) return false; var dx = (this.x - x), dy = (this.y - y), r2 = this.radius * this.radius; dx *= dx; dy *= dy; return (dx + dy <= r2); }; // constructor PIXI.Circle.prototype.constructor = PIXI.Circle;
import { Promise, allSettled, hash, hashSettled, denodeify, on, off, map, filter, resolve, reject, rethrow, all, defer, EventTarget, configure, race, async } from './rsvp'; var RSVP = { 'race': race, 'Promise': Promise, 'allSettled': allSettled, 'hash': hash, 'hashSettled': hashSettled, 'denodeify': denodeify, 'on': on, 'off': off, 'map': map, 'filter': filter, 'resolve': resolve, 'reject': reject, 'all': all, 'rethrow': rethrow, 'defer': defer, 'EventTarget': EventTarget, 'configure': configure, 'async': async }; /* global define:true module:true window: true */ if (typeof define === 'function' && define.amd) { define(function() { return RSVP; }); } else if (typeof module !== 'undefined' && module.exports) { module.exports = RSVP; } else if (typeof this !== 'undefined') { this['RSVP'] = RSVP; }
import get from 'ember-metal/property_get'; import { isArray } from 'ember-runtime/utils'; QUnit.module('Global API Tests'); function confirmExport(property, internal) { QUnit.test('confirm ' + property + ' is exported', function() { var theExport = get(window, property); ok(theExport + ' is exported'); if (internal !== undefined) { equal(theExport, internal, theExport + ' is exported properly'); } }); } confirmExport('Ember.DefaultResolver'); confirmExport('Ember.generateController'); confirmExport('Ember.Helper'); confirmExport('Ember.Helper.helper'); confirmExport('Ember.isArray', isArray);
/* Project: angular-gantt v1.3.0 - Gantt chart component for AngularJS Authors: Marco Schweighauser, Rémi Alvergnat License: MIT Homepage: https://www.angular-gantt.com Github: https://github.com/angular-gantt/angular-gantt.git */ (function() { 'use strict'; angular.module('gantt.dependencies', ['gantt', 'gantt.dependencies.templates']).directive('ganttDependencies', ['$timeout', '$document', 'ganttDebounce', 'GanttDependenciesManager', 'GanttDependenciesChecker', function($timeout, $document, debounce, DependenciesManager, DependenciesChecker) { return { restrict: 'E', require: '^gantt', scope: { enabled: '=?', readOnly: '=?', jsPlumbDefaults: '=?', endpoints: '=?', fallbackEndpoints: '=?', conflictChecker: '=?' }, link: function(scope, element, attrs, ganttCtrl) { var api = ganttCtrl.gantt.api; // Load options from global options attribute. if (scope.options && typeof(scope.options.dependencies) === 'object') { for (var option in scope.options.dependencies) { scope[option] = scope.options[option]; } } if (scope.enabled === undefined) { scope.enabled = true; } if (scope.readOnly === undefined) { scope.readOnly = false; } if (scope.jsPlumbDefaults === undefined) { // https://jsplumbtoolkit.com/community/doc/defaults.html scope.jsPlumbDefaults = { Endpoint: ['Dot', {radius: 4}], EndpointStyle: {fillStyle: '#456', strokeStyle: '#456', lineWidth: 1}, Connector: 'Flowchart', ConnectionOverlays: [['Arrow', {location: 1, length: 12, width: 12}]] }; } function createLeftOverlay() { return angular.element('<span><span class="gantt-endpoint-overlay start-endpoint arrow-right"></span></span>'); } function createRightOverlay() { return angular.element('<span><span class="gantt-endpoint-overlay end-endpoint arrow-right"></span></span>'); } function createLeftFallbackOverlay() { return angular.element('<span><span class="gantt-endpoint-overlay start-endpoint fallback-endpoint"></span></span>'); } function createRightFallbackOverlay() { return angular.element('<span><span class="gantt-endpoint-overlay end-endpoint fallback-endpoint"></span></span>'); } if (scope.endpoints === undefined) { scope.endpoints = [ { anchor: 'Left', isSource: false, isTarget: true, maxConnections: -1, cssClass: 'gantt-endpoint start-endpoint target-endpoint', overlays: [ ['Custom', {create: createLeftOverlay}] ] }, { anchor: 'Right', isSource: true, isTarget: false, maxConnections: -1, cssClass: 'gantt-endpoint end-endpoint source-endpoint', overlays: [ ['Custom', {create: createRightOverlay}] ] } ]; } if (scope.fallbackEndpoints === undefined) { scope.fallbackEndpoints = [ { endpoint: 'Blank', anchor: 'Left', isSource: false, isTarget: true, maxConnections: 0, cssClass: 'gantt-endpoint start-endpoint fallback-endpoint', overlays: [ ['Custom', {create: createLeftFallbackOverlay}] ] }, { endpoint: 'Blank', anchor: 'Right', isSource: true, isTarget: false, maxConnections: 0, cssClass: 'gantt-endpoint end-endpoint fallback-endpoint', overlays: [ ['Custom', {create: createRightFallbackOverlay}] ] } ]; } if (scope.conflictChecker === undefined) { scope.conflictChecker = false; } var manager = new DependenciesManager(ganttCtrl.gantt, scope, api); var checker = new DependenciesChecker(manager, scope, api); scope.$watchGroup(['conflictChecker', 'enabled'], function(newValue, oldValue) { if (newValue !== oldValue) { var rows = ganttCtrl.gantt.rowsManager.rows; var allTasks = []; for (var i = 0; i < rows.length; i++) { allTasks.push.apply(allTasks, rows[i].tasks); } if (scope.conflictChecker && scope.enabled) { checker.refresh(allTasks); } else { checker.clear(allTasks); } } }); api.directives.on.new(scope, function(directiveName, directiveScope, directiveElement) { if (directiveName === 'ganttBody') { manager.plumb.setContainer(directiveElement); } }); api.tasks.on.add(scope, function(task) { manager.addDependenciesFromTask(task, true); }); api.tasks.on.remove(scope, function(task) { manager.removeDependenciesFromTask(task); }); api.tasks.on.displayed(scope, debounce(function(tasks) { manager.setTasks(tasks); manager.refresh(); if (scope.conflictChecker && scope.enabled) { checker.refresh(tasks); } })); api.rows.on.displayed(scope, function() { manager.refresh(); }); api.tasks.on.viewChange(scope, function(task) { if (task.$element) { manager.plumb.revalidate(task.$element[0]); } if (scope.conflictChecker && scope.enabled) { checker.refresh([task]); } }); api.tasks.on.viewRowChange(scope, function(task) { manager.setTask(task); if (scope.conflictChecker && scope.enabled) { checker.refresh([task]); } }); api.dependencies.on.add(scope, function(dependency) { if (scope.conflictChecker && scope.enabled) { checker.refresh([dependency.getFromTask(), dependency.getToTask()]); } }); api.dependencies.on.change(scope, function(dependency) { if (scope.conflictChecker && scope.enabled) { checker.refresh([dependency.getFromTask(), dependency.getToTask()]); } }); api.dependencies.on.remove(scope, function(dependency) { if (scope.conflictChecker && scope.enabled) { var fromTask = dependency.getFromTask(); var toTask = dependency.getToTask(); if (fromTask && toTask) { checker.refresh([fromTask, toTask]); } else { if (fromTask) { checker.removeConflictClass(fromTask); } else { checker.removeConflictClass(toTask); } } } }); } }; }]); }()); (function() { 'use strict'; angular.module('gantt.dependencies').factory('GanttDependenciesChecker', [function() { /** * Creates a new DependenciesChecker object. * * @constructor */ var GanttDependenciesChecker = function(manager) { function handleTaskConflict(conflictsList, task) { if (!(task.model.id in conflictsList) && task.$element) { task.$element.addClass('gantt-task-conflict'); conflictsList[task.model.id] = task; } } function handleTaskNonConflict(conflictsList, allTasks) { for (var i = 0, l = allTasks.length; i < l; i++) { var task = allTasks[i]; if (!(task.model.id in conflictsList) && task.$element) { task.$element.removeClass('gantt-task-conflict'); } } } /** * Refresh the conflict status of given tasks. * * @param tasks */ this.refresh = function(tasks) { var allTasks = tasks.slice(0); var conflictsList = []; for (var i = 0; i < tasks.length; i++) { var taskDependencies = manager.getTaskDependencies(tasks[i]); for (var j = 0; j < taskDependencies.length; j++) { var dependency = taskDependencies[j]; var fromTask = dependency.getFromTask(); var toTask = dependency.getToTask(); if (!(fromTask in allTasks)) { allTasks.push(fromTask); } if (!(toTask in allTasks)) { allTasks.push(toTask); } if (fromTask.model.to > toTask.model.from) { handleTaskConflict(conflictsList, fromTask); handleTaskConflict(conflictsList, toTask); } } } handleTaskNonConflict(conflictsList, allTasks); }; this.removeConflictClass = function(task) { task.$element.removeClass('gantt-task-conflict'); }; /** * Remove the conflict status of given tasks. * * @param tasks */ this.clear = function(tasks) { var allTasks = tasks.slice(0); handleTaskNonConflict([], allTasks); }; }; return GanttDependenciesChecker; }]); }()); (function() { 'use strict'; angular.module('gantt.dependencies').factory('GanttDependenciesEvents', [function() { /** * Creates a new DependenciesEvents object. * * @param manager DependenciesManager object * @constructor */ var DependenciesEvents = function(manager) { var self = this; this.manager = manager; // Deny the start of a drag when in readonly var denyDragWhenReadOnly = function () { return !self.manager.pluginScope.readOnly; }; this.manager.plumb.bind('beforeDrag', denyDragWhenReadOnly); this.manager.plumb.bind('beforeStartDetach', denyDragWhenReadOnly); // Deny drop on the same task. var denyDropOnSameTask = function(params) { return params.sourceId !== params.targetId; }; this.manager.plumb.bind('beforeDrop', denyDropOnSameTask); // Notify the manager that a connection is being created. this.manager.plumb.bind('connectionDrag', function(connection) { self.manager.setDraggingConnection(connection); }); this.manager.plumb.bind('connectionDragStop', function() { self.manager.setDraggingConnection(undefined); }); this.manager.plumb.bind('beforeDrop', function() { self.manager.setDraggingConnection(undefined); return true; }); var createConnection = function(info, mouseEvent) { if (mouseEvent) { var oldDependency; if (info.connection.$dependency) { oldDependency = info.connection.$dependency; } var sourceEndpoint = info.sourceEndpoint; var targetEndpoint = info.targetEndpoint; var sourceModel = sourceEndpoint.$task.model; var dependenciesModel = sourceModel.dependencies; if (dependenciesModel === undefined) { dependenciesModel = []; sourceModel.dependencies = dependenciesModel; } var connectionModel = {to: targetEndpoint.$task.model.id}; dependenciesModel.push(connectionModel); if (oldDependency) { oldDependency.removeFromTaskModel(); self.manager.removeDependency(oldDependency, true); // Connection will be disconnected later by jsPlumb. } var dependency = self.manager.addDependency(sourceEndpoint.$task, connectionModel); info.connection.$dependency = dependency; dependency.connection = info.connection; self.manager.api.dependencies.raise.add(dependency); } }; var updateConnection = function(info, mouseEvent) { if (mouseEvent) { var oldDependency; if (info.connection.$dependency) { oldDependency = info.connection.$dependency; } var sourceEndpoint = info.newSourceEndpoint; var targetEndpoint = info.newTargetEndpoint; var sourceModel = sourceEndpoint.$task.model; var dependenciesModel = sourceModel.dependencies; if (dependenciesModel === undefined) { dependenciesModel = []; sourceModel.dependencies = dependenciesModel; } var connectionModel = {to: targetEndpoint.$task.model.id}; dependenciesModel.push(connectionModel); if (oldDependency) { oldDependency.removeFromTaskModel(); self.manager.removeDependency(oldDependency, true); // Connection will be disconnected later by jsPlumb. } var dependency = self.manager.addDependency(sourceEndpoint.$task, connectionModel); info.connection.$dependency = dependency; dependency.connection = info.connection; self.manager.api.dependencies.raise.change(dependency, oldDependency); } }; var deleteConnection = function(info, mouseEvent) { if (mouseEvent) { var dependency = info.connection.$dependency; dependency.removeFromTaskModel(); self.manager.removeDependency(dependency, true); // Connection will be disconnected later by jsPlumb. self.manager.api.dependencies.raise.remove(dependency); } }; this.manager.plumb.bind('connectionMoved', updateConnection); this.manager.plumb.bind('connection', createConnection); this.manager.plumb.bind('connectionDetached', deleteConnection); }; return DependenciesEvents; }]); }()); /* globals jsPlumb */ (function() { 'use strict'; angular.module('gantt.dependencies').factory('GanttDependenciesManager', ['GanttDependency', 'GanttDependenciesEvents', 'GanttDependencyTaskMouseHandler', function(Dependency, DependenciesEvents, TaskMouseHandler) { var DependenciesManager = function(gantt, pluginScope, api) { var self = this; this.gantt = gantt; this.pluginScope = pluginScope; this.api = api; this.api.registerEvent('dependencies', 'add'); this.api.registerEvent('dependencies', 'change'); this.api.registerEvent('dependencies', 'remove'); this.plumb = jsPlumb.getInstance(); this.plumb.importDefaults(this.pluginScope.jsPlumbDefaults); this.dependenciesFrom = {}; this.dependenciesTo = {}; this.tasksList = []; this.tasks = {}; this.events = new DependenciesEvents(this); this.pluginScope.$watch('enabled', function(newValue, oldValue) { if (newValue !== oldValue) { self.refresh(); } }); this.pluginScope.$watch('readOnly', function(newValue, oldValue) { if (newValue !== oldValue) { self.setTasks(self.tasksList); self.refresh(); } }); this.pluginScope.$watch('jsPlumbDefaults', function(newValue, oldValue) { if (newValue !== oldValue) { self.plumb.importDefaults(newValue); self.refresh(); } }, true); /** * Add all dependencies defined from a task. Dependencies will be added only if plugin is enabled. * * @param task * @param allowPartial if true, dependency linking to a missing task will still be added. */ this.addDependenciesFromTask = function(task, allowPartial) { if (this.pluginScope.enabled) { var taskDependencies = task.model.dependencies; if (taskDependencies !== undefined && taskDependencies) { if (!angular.isArray(taskDependencies)) { taskDependencies = [taskDependencies]; task.model.dependencies = taskDependencies; } for (var i = 0, l = taskDependencies.length; i < l; i++) { var dependency = self.addDependency(task, taskDependencies[i], allowPartial); if (dependency) { dependency.connect(); } } } } }; /** * Remove all dependencies defined for a task. * * @param task * @param keepConnection if true, dependency will not be disconnected. */ this.removeDependenciesFromTask = function(task, keepConnection) { var dependencies = this.getTaskDependencies(task); if (dependencies) { for (var i = 0; i < dependencies.length; i++) { if (!keepConnection) { dependencies[i].disconnect(); } self.removeDependency(dependencies[i]); } } }; /** * Add definition of a dependency. * * @param task Task defining the dependency. * @param model Model object for the dependency. * @param allowPartial if true, dependency linking to a missing task will still be added. */ this.addDependency = function(task, model, allowPartial) { var dependency = new Dependency(this, task, model); var fromTaskId = dependency.getFromTaskId(); var fromTask = dependency.getFromTask(); var toTaskId = dependency.getToTaskId(); var toTask = dependency.getToTask(); var manager = dependency.manager; if (!(fromTaskId in this.dependenciesFrom)) { this.dependenciesFrom[fromTaskId] = []; } if (!(toTaskId in this.dependenciesTo)) { this.dependenciesTo[toTaskId] = []; } if (!allowPartial && (!toTask || !fromTask)) { // Partial dependency is not allowed, remove it. this.removeDependency(dependency, true); manager.api.dependencies.raise.remove(dependency); return null; } else { if (fromTaskId) { this.dependenciesFrom[fromTaskId].push(dependency); } if (toTaskId) { this.dependenciesTo[toTaskId].push(dependency); } } return dependency; }; /** * Remove definition of a dependency * * @param dependency Dependency object * @param keepConnection if true, dependency will not be disconnected. */ this.removeDependency = function(dependency, keepConnection) { var fromDependencies = this.dependenciesFrom[dependency.getFromTaskId()]; var fromRemove = []; var i; if (fromDependencies) { for (i = 0; i < fromDependencies.length; i++) { if (dependency === fromDependencies[i]) { fromRemove.push(dependency); } } } var toDependencies = this.dependenciesTo[dependency.getToTaskId()]; var toRemove = []; if (toDependencies) { for (i = 0; i < toDependencies.length; i++) { if (dependency === toDependencies[i]) { toRemove.push(dependency); } } } for (i = 0; i < fromRemove.length; i++) { if (!keepConnection) { fromRemove[i].disconnect(); } fromDependencies.splice(fromDependencies.indexOf(dependency), 1); } for (i = 0; i < toRemove.length; i++) { if (!keepConnection) { toRemove[i].disconnect(); } toDependencies.splice(toDependencies.indexOf(dependency), 1); } if (this.dependenciesFrom[dependency.getFromTaskId()] && this.dependenciesFrom[dependency.getFromTaskId()].length === 0) { delete this.dependenciesFrom[dependency.getFromTaskId()]; } if (this.dependenciesTo[dependency.getToTaskId()] && this.dependenciesTo[dependency.getToTaskId()].length === 0) { delete this.dependenciesTo[dependency.getToTaskId()]; } }; this.getTaskDependencies = function(task) { var dependencies = []; var fromDependencies = self.dependenciesFrom[task.model.id]; if (fromDependencies) { dependencies = dependencies.concat(fromDependencies); } var toDependencies = self.dependenciesTo[task.model.id]; if (toDependencies) { dependencies = dependencies.concat(toDependencies); } return dependencies; }; this.setDraggingConnection = function(connection) { if (connection) { self.draggingConnection = connection; angular.forEach(self.tasks, function(task) { task.dependencies.mouseHandler.release(); }); } else { self.draggingConnection = undefined; angular.forEach(self.tasks, function(task) { task.dependencies.mouseHandler.install(); }); } }; var isTaskEnabled = function(task) { var rowDependencies = task.row.model.dependencies; if (rowDependencies !== undefined) { return rowDependencies !== false; } var taskDependencies = task.model.dependencies; if (taskDependencies !== undefined) { return taskDependencies !== false; } return true; }; var addTaskEndpoints = function(task) { if (!task.dependencies) { task.dependencies = {}; } task.dependencies.endpoints = []; if (self.pluginScope.endpoints && task.$element) { for (var i = 0; i < self.pluginScope.endpoints.length; i++) { var endpointObject = self.plumb.addEndpoint(task.$element, self.pluginScope.endpoints[i]); endpointObject.setVisible(false, true, true); // hide endpoint endpointObject.$task = task; task.dependencies.endpoints.push(endpointObject); } } }; var removeTaskEndpoint = function(task) { if (task.dependencies.endpoints) { for (var i = 0; i < task.dependencies.endpoints.length; i++) { var endpointObject = task.dependencies.endpoints[i]; self.plumb.deleteEndpoint(endpointObject); endpointObject.$task = undefined; } task.dependencies.endpoints = undefined; } }; var addTaskMouseHandler = function(task) { if (!task.dependencies) { task.dependencies = {}; } if (!self.pluginScope.readOnly) { task.dependencies.mouseHandler = new TaskMouseHandler(self, task); task.dependencies.mouseHandler.install(); } }; var removeTaskMouseHandler = function(task) { if (task.dependencies.mouseHandler) { task.dependencies.mouseHandler.release(); task.dependencies.mouseHandler = undefined; } }; /** * Set tasks objects that can be used to display dependencies. * * @param tasks */ this.setTasks = function(tasks) { angular.forEach(self.tasks, function(task) { removeTaskMouseHandler(task); removeTaskEndpoint(task); }); var newTasks = {}; var tasksList = []; for (var i = 0; i < tasks.length; i++) { var task = tasks[i]; if (isTaskEnabled(task)) { newTasks[task.model.id] = task; tasksList.push(task); addTaskEndpoints(task); addTaskMouseHandler(task); } } self.tasks = newTasks; self.tasksList = tasks; }; var disconnectTaskDependencies = function(task) { var dependencies = self.getTaskDependencies(task); if (dependencies) { for (var i = 0; i < dependencies.length; i++) { dependencies[i].disconnect(); } } return dependencies; }; var connectTaskDependencies = function(task) { var dependencies = self.getTaskDependencies(task); if (dependencies) { for (var i = 0; i < dependencies.length; i++) { dependencies[i].connect(); } } return dependencies; }; /** * Set task object in replacement of an existing with the same id. * * @param task */ this.setTask = function(task) { self.plumb.setSuspendDrawing(true); try { var oldTask = self.tasks[task.model.id]; if (oldTask !== undefined) { disconnectTaskDependencies(oldTask); removeTaskMouseHandler(oldTask); removeTaskEndpoint(oldTask); } if (isTaskEnabled(task)) { self.tasks[task.model.id] = task; addTaskEndpoints(task); addTaskMouseHandler(task); connectTaskDependencies(task); } } finally { self.plumb.setSuspendDrawing(false, true); } }; /** * Retrieve the task from it's id. * * @param taskId id of the task element to retrieve. * @returns {*} */ this.getTask = function(taskId) { return self.tasks[taskId]; }; var getSourceEndpoints = function(task) { return task.dependencies.endpoints.filter(function(endpoint) { return endpoint.isSource; }); }; var getTargetEndpoints = function(task) { return task.dependencies.endpoints.filter(function(endpoint) { return endpoint.isTarget; }); }; /** * Connects two tasks together using source endpoint from fromTask and target endpoint from toTask. * * @param fromTask * @param toTask * @param model * @returns connection object */ this.connect = function(fromTask, toTask, model) { var sourceEndpoints = getSourceEndpoints(fromTask); var targetEndpoints = getTargetEndpoints(toTask); if (sourceEndpoints && targetEndpoints) { var sourceEndpoint; var targetEndpoint; if (model.connectParameters && model.connectParameters.sourceEndpointIndex) { sourceEndpoint = sourceEndpoints[model.connectParameters.sourceEndpointIndex]; } else { sourceEndpoint = sourceEndpoints[0]; } if (model.connectParameters && model.connectParameters.targetEndpointIndex) { targetEndpoint = targetEndpoints[model.connectParameters.targetEndpointIndex]; } else { targetEndpoint = targetEndpoints[0]; } var connection = self.plumb.connect({ source: sourceEndpoint, target: targetEndpoint }, model.connectParameters); return connection; } }; /** * Get all defined dependencies. * * @returns {Array} */ this.getDependencies = function() { var allDependencies = []; angular.forEach(this.dependenciesFrom, function(dependencies) { for (var i = 0; i < dependencies.length; i++) { if (!(dependencies[i] in allDependencies)) { allDependencies.push(dependencies[i]); } } }); return allDependencies; }; /** * Refresh jsplumb status based on tasks dependencies models. */ this.refresh = function(tasks) { self.plumb.setSuspendDrawing(true); try { var tasksDependencies; var i; if (tasks && !angular.isArray(tasks)) { tasks = [tasks]; } if (tasks === undefined) { tasks = this.tasks; tasksDependencies = this.getDependencies(); } else { tasksDependencies = []; angular.forEach(tasks, function(task) { var taskDependencies = self.getTaskDependencies(task); angular.forEach(taskDependencies, function(taskDependency) { if (!(taskDependency in tasksDependencies)) { tasksDependencies.push(taskDependency); } }); }); } for (i = 0; i < tasksDependencies.length; i++) { self.removeDependency(tasksDependencies[i]); } angular.forEach(tasks, function(task) { self.addDependenciesFromTask(task); }); } finally { self.plumb.setSuspendDrawing(false, true); } }; this.api.registerMethod('dependencies', 'refresh', this.refresh, this); }; return DependenciesManager; }]); }()); (function() { 'use strict'; angular.module('gantt.dependencies').factory('GanttDependency', ['ganttUtils', 'ganttDom', function(utils, dom) { /** * Constructor of Dependency object. *  * @param manager Dependency manager used by this dependency * @param task Task declaring the dependency * @param model model of the dependency * * @constructor * * @see https://jsplumbtoolkit.com/community/apidocs/classes/jsPlumb.html#method_connect */ var Dependency = function(manager, task, model) { var self = this; this.manager = manager; this.task = task; this.model = model; this.connection = undefined; this.fallbackEndpoints = []; /** * Check if this dependency is connected. * * @returns {boolean} */ this.isConnected = function() { if (this.connection) { return true; } return false; }; /** * Disconnect this dependency. */ this.disconnect = function() { if (this.connection) { if (this.connection.endpoints) { this.manager.plumb.detach(this.connection); } this.connection.$dependency = undefined; this.connection = undefined; } this.deleteFallbackEndpoints(); }; this.deleteFallbackEndpoints = function() { if (this.fallbackEndpoints) { for (var i=0; i<this.fallbackEndpoints.length; i++) { self.manager.plumb.deleteEndpoint(this.fallbackEndpoints[i]); } this.fallbackEndpoints = []; } }; this.getFromTaskId = function() { if (this.model.from !== undefined) { return this.model.from; } return this.task.model.id; }; this.getToTaskId = function() { if (this.model.to !== undefined) { return this.model.to; } return this.task.model.id; }; this.getFromTask = function() { if (this.model.from !== undefined) { return this.manager.getTask(this.model.from); } return this.task; }; this.getToTask = function() { if (this.model.to !== undefined) { return this.manager.getTask(this.model.to); } return this.task; }; this.removeFromTaskModel = function() { var modelIndex = utils.angularIndexOf(this.task.model.dependencies, this.model); if (modelIndex >= 0) { this.task.model.dependencies.splice(modelIndex, 1); } return modelIndex; }; var isTaskVisible = function(task) { if (task === undefined || task.$element === undefined) { return false; } var element = task.$element[0]; return dom.isElementVisible(element); }; /** * Connect this dependency if both elements are available. * * @returns {boolean} */ this.connect = function() { var fromTask = this.getFromTask(); var toTask = this.getToTask(); if (!isTaskVisible(fromTask)) { fromTask = undefined; } if (!isTaskVisible(toTask)) { toTask = undefined; } if (fromTask && toTask) { var connection = this.manager.connect(fromTask, toTask, this.model); if (connection) { connection.$dependency = this; this.connection = connection; return true; } } this.deleteFallbackEndpoints(); if (fromTask !== undefined) { var toFallbackEndpoint = this.manager.pluginScope.fallbackEndpoints[1]; this.fallbackEndpoints.push(this.manager.plumb.addEndpoint(fromTask.$element, toFallbackEndpoint)); } if (toTask !== undefined) { var fromFallbackEndpoint = this.manager.pluginScope.fallbackEndpoints[0]; this.fallbackEndpoints.push(this.manager.plumb.addEndpoint(toTask.$element, fromFallbackEndpoint)); } return false; }; }; return Dependency; }]); }()); (function() { 'use strict'; angular.module('gantt.dependencies').factory('GanttDependencyTaskMouseHandler', ['$timeout', function($timeout) { var TaskMouseHandler = function(manager, task) { var self = this; this.manager = manager; this.task = task; this.installed = false; this.elementHandlers = []; this.display = true; this.hideEndpointsPromise = undefined; /** * Handler for a single DOM element. * * @param element * @constructor */ var ElementHandler = function(element) { this.element = element; this.mouseExitHandler = function() { $timeout.cancel(self.hideEndpointsPromise); self.hideEndpointsPromise = $timeout(self.hideEndpoints, 1000, false); }; this.mouseEnterHandler = function() { $timeout.cancel(self.hideEndpointsPromise); self.displayEndpoints(); }; this.install = function() { this.element.bind('mouseenter', this.mouseEnterHandler); this.element.bind('mouseleave', this.mouseExitHandler); }; this.release = function() { this.element.unbind('mouseenter', this.mouseEnterHandler); this.element.unbind('mouseleave', this.mouseExitHandler); $timeout.cancel(self.hideEndpointsPromise); }; }; /** * Install mouse handler for this task, and hide all endpoints. */ this.install = function() { if (!self.installed) { self.hideEndpoints(); if (self.task.getContentElement()) { self.elementHandlers.push(new ElementHandler(self.task.getContentElement())); angular.forEach(self.task.dependencies.endpoints, function(endpoint) { self.elementHandlers.push(new ElementHandler(angular.element(endpoint.canvas))); }); angular.forEach(self.elementHandlers, function(elementHandler) { elementHandler.install(); }); self.installed = true; } } }; /** * Release mouse handler for this task, and display all endpoints. */ this.release = function() { if (self.installed) { angular.forEach(self.elementHandlers, function(elementHandler) { elementHandler.release(); }); self.elementHandlers = []; self.displayEndpoints(); self.installed = false; } }; /** * Display all endpoints for this task. */ this.displayEndpoints = function() { self.display = true; angular.forEach(self.task.dependencies.endpoints, function(endpoint) { endpoint.setVisible(true, true, true); }); }; /** * Hide all endpoints for this task. */ this.hideEndpoints = function() { angular.forEach(self.task.dependencies.endpoints, function(endpoint) { endpoint.setVisible(false, true, true); }); self.display = false; }; }; return TaskMouseHandler; }]); }()); angular.module('gantt.dependencies.templates', []).run(['$templateCache', function($templateCache) { }]); //# sourceMappingURL=angular-gantt-dependencies-plugin.js.map
/*! * pagepiling.js 1.5.3 * * https://github.com/alvarotrigo/pagePiling.js * MIT licensed * * Copyright (C) 2013 alvarotrigo.com - A project by Alvaro Trigo */ (function(b,h,k,z){b.fn.pagepiling=function(M){function N(a){var f=b(".pp-section.active").index(".pp-section");a=a.index(".pp-section");return f>a?"up":"down"}function l(a,f){var d={destination:a,animated:f,activeSection:b(".pp-section.active"),anchorLink:a.data("anchor"),sectionIndex:a.index(".pp-section"),toMove:a,yMovement:N(a),leavingSection:b(".pp-section.active").index(".pp-section")+1};d.activeSection.is(a)||("undefined"===typeof d.animated&&(d.animated=!0),"undefined"!==typeof d.anchorLink&& O(d.anchorLink,d.sectionIndex),d.destination.addClass("active").siblings().removeClass("active"),d.sectionsToMove=P(d),"down"===d.yMovement?(d.translate3d="vertical"!==c.direction?"translate3d(-100%, 0px, 0px)":"translate3d(0px, -100%, 0px)",d.scrolling="-100%",c.css3||d.sectionsToMove.each(function(a){a!=d.activeSection.index(".pp-section")&&b(this).css(v(d.scrolling))}),d.animateSection=d.activeSection):(d.translate3d="translate3d(0px, 0px, 0px)",d.scrolling="0",d.animateSection=a),b.isFunction(c.onLeave)&& c.onLeave.call(this,d.leavingSection,d.sectionIndex+1,d.yMovement),Q(d),R(d.anchorLink),S(d.anchorLink,d.sectionIndex),A=d.anchorLink,B=(new Date).getTime())}function Q(a){c.css3?(C(a.animateSection,a.translate3d,a.animated),a.sectionsToMove.each(function(){C(b(this),a.translate3d,a.animated)}),setTimeout(function(){w(a)},c.scrollingSpeed)):(a.scrollOptions=v(a.scrolling),a.animated?a.animateSection.animate(a.scrollOptions,c.scrollingSpeed,c.easing,function(){D(a);w(a)}):(a.animateSection.css(v(a.scrolling)), setTimeout(function(){D(a);w(a)},400)))}function w(a){b.isFunction(c.afterLoad)&&c.afterLoad.call(this,a.anchorLink,a.sectionIndex+1)}function P(a){return"down"===a.yMovement?b(".pp-section").map(function(f){if(f<a.destination.index(".pp-section"))return b(this)}):b(".pp-section").map(function(f){if(f>a.destination.index(".pp-section"))return b(this)})}function D(a){"up"===a.yMovement&&a.sectionsToMove.each(function(f){b(this).css(v(a.scrolling))})}function v(a){return"vertical"===c.direction?{top:a}: {left:a}}function O(a,b){c.anchors.length?(location.hash=a,E(location.hash)):E(String(b))}function E(a){a=a.replace("#","");b("body")[0].className=b("body")[0].className.replace(/\b\s?pp-viewing-[^\s]+\b/g,"");b("body").addClass("pp-viewing-"+a)}function x(){return(new Date).getTime()-B<600+c.scrollingSpeed?!0:!1}function C(a,b,d){a.toggleClass("pp-easing",d);a.css({"-webkit-transform":b,"-moz-transform":b,"-ms-transform":b,transform:b})}function m(a){var f=(new Date).getTime();a=a||k.event;var d= a.wheelDelta||-a.deltaY||-a.detail,c=Math.max(-1,Math.min(1,d)),e="undefined"!==typeof a.wheelDeltaX||"undefined"!==typeof a.deltaX;a=Math.abs(a.wheelDeltaX)<Math.abs(a.wheelDelta)||Math.abs(a.deltaX)<Math.abs(a.deltaY)||!e;149<n.length&&n.shift();n.push(Math.abs(d));d=f-F;F=f;200<d&&(n=[]);if(!x())return f=b(".pp-section.active").filter(".pp-scrollable"),d=G(n,10),e=G(n,70),d>=e&&a&&(0>c?p("down",f):0<c&&p("up",f)),!1}function G(a,b){for(var d=0,c=a.slice(Math.max(a.length-b,1)),e=0;e<c.length;e++)d+= c[e];return Math.ceil(d/b)}function p(a,b){var d,c;"down"==a?(d="bottom",c=e.moveSectionDown):(d="top",c=e.moveSectionUp);if(0<b.length)if(d="top"===d?!b.scrollTop():"bottom"===d?b.scrollTop()+1+b.innerHeight()>=b[0].scrollHeight:void 0,d)c();else return!0;else c()}function H(){return k.PointerEvent?{down:"pointerdown",move:"pointermove",up:"pointerup"}:{down:"MSPointerDown",move:"MSPointerMove",up:"MSPointerUp"}}function I(a){var b=[];b.y="undefined"!==typeof a.pageY&&(a.pageY||a.pageX)?a.pageY: a.touches[0].pageY;b.x="undefined"!==typeof a.pageX&&(a.pageY||a.pageX)?a.pageX:a.touches[0].pageX;return b}function J(a){return"undefined"===typeof a.pointerType||"mouse"!=a.pointerType}function T(a){a=a.originalEvent;J(a)&&(a=I(a),q=a.y,r=a.x)}function U(a){var f=a.originalEvent;if(!K(a.target)&&J(f)){var d=b(".pp-section.active").filter(".pp-scrollable");d.length||a.preventDefault();x()||(a=I(f),t=a.y,u=a.x,"horizontal"===c.direction&&Math.abs(r-u)>Math.abs(q-t)?Math.abs(r-u)>g.width()/100*c.touchSensitivity&& (r>u?p("down",d):u>r&&p("up",d)):Math.abs(q-t)>g.height()/100*c.touchSensitivity&&(q>t?p("down",d):t>q&&p("up",d)))}}function K(a,f){f=f||0;var d=b(a).parent();return f<c.normalScrollElementTouchThreshold&&d.is(c.normalScrollElements)?!0:f==c.normalScrollElementTouchThreshold?!1:K(d,++f)}function V(){b("body").append('<div id="pp-nav"><ul></ul></div>');var a=b("#pp-nav");a.css("color",c.navigation.textColor);a.addClass(c.navigation.position);for(var f=0;f<b(".pp-section").length;f++){var d="";c.anchors.length&& (d=c.anchors[f]);if("undefined"!==c.navigation.tooltips){var e=c.navigation.tooltips[f];"undefined"===typeof e&&(e="")}a.find("ul").append('<li data-tooltip="'+e+'"><a href="#'+d+'"><span></span></a></li>')}a.find("span").css("border-color",c.navigation.bulletsColor)}function S(a,f){c.navigation&&(b("#pp-nav").find(".active").removeClass("active"),a?b("#pp-nav").find('a[href="#'+a+'"]').addClass("active"):b("#pp-nav").find("li").eq(f).find("a").addClass("active"))}function R(a){c.menu&&(b(c.menu).find(".active").removeClass("active"), b(c.menu).find('[data-menuanchor="'+a+'"]').addClass("active"))}function W(){var a=h.createElement("p"),b,d={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};h.body.insertBefore(a,null);for(var c in d)a.style[c]!==z&&(a.style[c]="translate3d(1px,1px,1px)",b=k.getComputedStyle(a).getPropertyValue(d[c]));h.body.removeChild(a);return b!==z&&0<b.length&&"none"!==b}var e=b.fn.pagepiling,g=b(this),A,B=0,L="ontouchstart"in k||0<navigator.msMaxTouchPoints||navigator.maxTouchPoints,q=0,r=0,t=0,u=0,n=[],c=b.extend(!0,{direction:"vertical",menu:null,verticalCentered:!0,sectionsColor:[],anchors:[],scrollingSpeed:700,easing:"easeInQuart",loopBottom:!1,loopTop:!1,css3:!0,navigation:{textColor:"#000",bulletsColor:"#000",position:"right",tooltips:[]},normalScrollElements:null,normalScrollElementTouchThreshold:5,touchSensitivity:5,keyboardScrolling:!0,sectionSelector:".section",animateAnchor:!1,afterLoad:null,onLeave:null,afterRender:null}, M);b.extend(b.easing,{easeInQuart:function(a,b,c,e,g){return e*(b/=g)*b*b*b+c}});e.setScrollingSpeed=function(a){c.scrollingSpeed=a};e.setMouseWheelScrolling=function(a){a?g.get(0).addEventListener?(g.get(0).addEventListener("mousewheel",m,!1),g.get(0).addEventListener("wheel",m,!1)):g.get(0).attachEvent("onmousewheel",m):g.get(0).addEventListener?(g.get(0).removeEventListener("mousewheel",m,!1),g.get(0).removeEventListener("wheel",m,!1)):g.get(0).detachEvent("onmousewheel",m)};e.setAllowScrolling= function(a){a?(e.setMouseWheelScrolling(!0),L&&(a=H(),g.off("touchstart "+a.down).on("touchstart "+a.down,T),g.off("touchmove "+a.move).on("touchmove "+a.move,U))):(e.setMouseWheelScrolling(!1),L&&(a=H(),g.off("touchstart "+a.down),g.off("touchmove "+a.move)))};e.setKeyboardScrolling=function(a){c.keyboardScrolling=a};e.moveSectionUp=function(){var a=b(".pp-section.active").prev(".pp-section");!a.length&&c.loopTop&&(a=b(".pp-section").last());a.length&&l(a)};e.moveSectionDown=function(){var a=b(".pp-section.active").next(".pp-section"); !a.length&&c.loopBottom&&(a=b(".pp-section").first());a.length&&l(a)};e.moveTo=function(a){var c="",c=isNaN(a)?b(h).find('[data-anchor="'+a+'"]'):b(".pp-section").eq(a-1);0<c.length&&l(c)};b(c.sectionSelector).each(function(){b(this).addClass("pp-section")});c.css3&&(c.css3=W());b(g).css({overflow:"hidden","-ms-touch-action":"none","touch-action":"none"});e.setAllowScrolling(!0);b.isEmptyObject(c.navigation)||V();var y=b(".pp-section").length;b(".pp-section").each(function(a){b(this).data("data-index", a);b(this).css("z-index",y);a||0!==b(".pp-section.active").length||b(this).addClass("active");"undefined"!==typeof c.anchors[a]&&b(this).attr("data-anchor",c.anchors[a]);"undefined"!==typeof c.sectionsColor[a]&&b(this).css("background-color",c.sectionsColor[a]);c.verticalCentered&&!b(this).hasClass("pp-scrollable")&&b(this).addClass("pp-table").wrapInner('<div class="pp-tableCell" style="height:100%" />');--y}).promise().done(function(){c.navigation&&(b("#pp-nav").css("margin-top","-"+b("#pp-nav").height()/ 2+"px"),b("#pp-nav").find("li").eq(b(".pp-section.active").index(".pp-section")).find("a").addClass("active"));b(k).on("load",function(){var a=k.location.hash.replace("#",""),a=b(h).find('.pp-section[data-anchor="'+a+'"]');0<a.length&&l(a,c.animateAnchor)});b.isFunction(c.afterRender)&&c.afterRender.call(this)});b(k).on("hashchange",function(){var a=k.location.hash.replace("#","").split("/")[0];a.length&&a&&a!==A&&(a=isNaN(a)?b(h).find('[data-anchor="'+a+'"]'):b(".pp-section").eq(a-1),l(a))});b(h).keydown(function(a){if(c.keyboardScrolling&& !x())switch(a.which){case 38:case 33:e.moveSectionUp();break;case 40:case 34:e.moveSectionDown();break;case 36:e.moveTo(1);break;case 35:e.moveTo(b(".pp-section").length);break;case 37:e.moveSectionUp();break;case 39:e.moveSectionDown()}});c.normalScrollElements&&(b(h).on("mouseenter",c.normalScrollElements,function(){e.setMouseWheelScrolling(!1)}),b(h).on("mouseleave",c.normalScrollElements,function(){e.setMouseWheelScrolling(!0)}));var F=(new Date).getTime();b(h).on("click touchstart","#pp-nav a", function(a){a.preventDefault();a=b(this).parent().index();l(b(".pp-section").eq(a))});b(h).on({mouseenter:function(){var a=b(this).data("tooltip");b('<div class="pp-tooltip '+c.navigation.position+'">'+a+"</div>").hide().appendTo(b(this)).fadeIn(200)},mouseleave:function(){b(this).find(".pp-tooltip").fadeOut(200,function(){b(this).remove()})}},"#pp-nav li")}})(jQuery,document,window);
/* Plugin Name: amCharts Export Description: Adds export capabilities to amCharts products Author: Benjamin Maertz, amCharts Version: 1.4.43 Author URI: http://www.amcharts.com/ Copyright 2016 amCharts 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. Please note that the above license covers only this plugin. It by all means does not apply to any other amCharts products that are covered by different licenses. */ /* ** Polyfill translation */ if ( !AmCharts.translations[ "export" ] ) { AmCharts.translations[ "export" ] = {} } if ( !AmCharts.translations[ "export" ][ "en" ] ) { AmCharts.translations[ "export" ][ "en" ] = { "fallback.save.text": "CTRL + C to copy the data into the clipboard.", "fallback.save.image": "Rightclick -> Save picture as... to save the image.", "capturing.delayed.menu.label": "{{duration}}", "capturing.delayed.menu.title": "Click to cancel", "menu.label.print": "Print", "menu.label.undo": "Undo", "menu.label.redo": "Redo", "menu.label.cancel": "Cancel", "menu.label.save.image": "Download as ...", "menu.label.save.data": "Save as ...", "menu.label.draw": "Annotate ...", "menu.label.draw.change": "Change ...", "menu.label.draw.add": "Add ...", "menu.label.draw.shapes": "Shape ...", "menu.label.draw.colors": "Color ...", "menu.label.draw.widths": "Size ...", "menu.label.draw.opacities": "Opacity ...", "menu.label.draw.text": "Text", "menu.label.draw.modes": "Mode ...", "menu.label.draw.modes.pencil": "Pencil", "menu.label.draw.modes.line": "Line", "menu.label.draw.modes.arrow": "Arrow", "label.saved.from": "Saved from: " } } /* ** Polyfill export class */ ( function() { AmCharts[ "export" ] = function( chart, config ) { var _timer; var _this = { name: "export", version: "1.4.43", libs: { async: true, autoLoad: true, reload: false, resources: [ "fabric.js/fabric.min.js", "FileSaver.js/FileSaver.min.js", "jszip/jszip.min.js", "xlsx/xlsx.min.js", { "pdfmake/pdfmake.min.js": [ "pdfmake/vfs_fonts.js" ] } ], namespaces: { "pdfmake.min.js": "pdfMake", "jszip.min.js": "JSZip", "xlsx.min.js": "XLSX", "fabric.min.js": "fabric", "FileSaver.min.js": "saveAs" }, loadTimeout: 10000 }, config: {}, setup: { chart: chart, hasBlob: false, wrapper: false, isIE: !!window.document.documentMode, IEversion: window.document.documentMode, hasTouch: typeof window.Touch == "object" }, drawing: { enabled: false, undos: [], redos: [], buffer: { position: { x1: 0, y1: 0, x2: 0, y2: 0, xD: 0, yD: 0 } }, handler: { undo: function( options, skipped ) { var item = _this.drawing.undos.pop(); if ( item ) { item.selectable = true; _this.drawing.redos.push( item ); if ( item.action == "added" ) { _this.setup.fabric.remove( item.target ); } var state = JSON.parse( item.state ); item.target.set( state ); if ( item.target instanceof fabric.Group ) { _this.drawing.handler.change( { color: state.cfg.color, width: state.cfg.width, opacity: state.cfg.opacity }, true, item.target ); } _this.setup.fabric.renderAll(); // RECALL if ( item.state == item.target.recentState && !skipped ) { _this.drawing.handler.undo( item, true ); } } }, redo: function( options, skipped ) { var item = _this.drawing.redos.pop(); if ( item ) { item.selectable = true; _this.drawing.undos.push( item ); if ( item.action == "added" ) { _this.setup.fabric.add( item.target ); } var state = JSON.parse( item.state ); item.target.recentState = item.state; item.target.set( state ); if ( item.target instanceof fabric.Group ) { _this.drawing.handler.change( { color: state.cfg.color, width: state.cfg.width, opacity: state.cfg.opacity }, true, item.target ); } _this.setup.fabric.renderAll(); // RECALL if ( item.action == "addified" ) { _this.drawing.handler.redo(); } } }, done: function( options ) { _this.drawing.enabled = false; _this.drawing.buffer.enabled = false; _this.drawing.undos = []; _this.drawing.redos = []; _this.createMenu( _this.config.menu ); _this.setup.fabric.deactivateAll(); if ( _this.setup.wrapper ) { _this.setup.chart.containerDiv.removeChild( _this.setup.wrapper ); _this.setup.wrapper = false; } }, add: function( options ) { var cfg = _this.deepMerge( { top: _this.setup.fabric.height / 2, left: _this.setup.fabric.width / 2 }, options || {} ); var method = cfg.url.indexOf( ".svg" ) != -1 ? fabric.loadSVGFromURL : fabric.Image.fromURL; method( cfg.url, function( objects, options ) { var group = options !== undefined ? fabric.util.groupSVGElements( objects, options ) : objects; var ratio = false; // RESCALE ONLY IF IT EXCEEDS THE CANVAS if ( group.height > _this.setup.fabric.height || group.width > _this.setup.fabric.width ) { ratio = ( _this.setup.fabric.height / 2 ) / group.height; } if ( cfg.top > _this.setup.fabric.height ) { cfg.top = _this.setup.fabric.height / 2; } if ( cfg.left > _this.setup.fabric.width ) { cfg.left = _this.setup.fabric.width / 2; } group.set( { originX: "center", originY: "center", top: cfg.top, left: cfg.left, width: ratio ? group.width * ratio : group.width, height: ratio ? group.height * ratio : group.height, fill: _this.drawing.color } ); _this.setup.fabric.add( group ); } ); }, change: function( options, skipped, target ) { var cfg = _this.deepMerge( {}, options || {} ); var state, i1, rgba; var current = target || _this.drawing.buffer.target; var objects = current ? current._objects ? current._objects : [ current ] : null; // UPDATE DRAWING OBJECT if ( cfg.mode ) { _this.drawing.mode = cfg.mode; } if ( cfg.width ) { _this.drawing.width = cfg.width; _this.drawing.fontSize = cfg.width * 3; } if ( cfg.fontSize ) { _this.drawing.fontSize = cfg.fontSize; } if ( cfg.color ) { _this.drawing.color = cfg.color; } if ( cfg.opacity ) { _this.drawing.opacity = cfg.opacity; } // APPLY OPACITY ON CURRENT COLOR rgba = _this.getRGBA( _this.drawing.color ); rgba.pop(); rgba.push( _this.drawing.opacity ); _this.drawing.color = "rgba(" + rgba.join() + ")"; _this.setup.fabric.freeDrawingBrush.color = _this.drawing.color; _this.setup.fabric.freeDrawingBrush.width = _this.drawing.width; // UPDATE CURRENT SELECTION if ( current ) { state = JSON.parse( current.recentState ).cfg; // UPDATE GIVE OPTIONS ONLY if ( state ) { cfg.color = cfg.color || state.color; cfg.width = cfg.width || state.width; cfg.opacity = cfg.opacity || state.opacity; cfg.fontSize = cfg.fontSize || cfg.width * 3; rgba = _this.getRGBA( cfg.color ); rgba.pop(); rgba.push( cfg.opacity ); cfg.color = "rgba(" + rgba.join() + ")"; } // UPDATE OBJECTS for ( i1 = 0; i1 < objects.length; i1++ ) { if ( objects[ i1 ] instanceof fabric.Text || objects[ i1 ] instanceof fabric.PathGroup || objects[ i1 ] instanceof fabric.Triangle ) { if ( cfg.color || cfg.opacity ) { objects[ i1 ].set( { fill: cfg.color } ); } if ( cfg.fontSize ) { objects[ i1 ].set( { fontSize: cfg.fontSize } ); } } else if ( objects[ i1 ] instanceof fabric.Path || objects[ i1 ] instanceof fabric.Line ) { if ( current instanceof fabric.Group ) { if ( cfg.color || cfg.opacity ) { objects[ i1 ].set( { stroke: cfg.color } ); } } else { if ( cfg.color || cfg.opacity ) { objects[ i1 ].set( { stroke: cfg.color } ); } if ( cfg.width ) { objects[ i1 ].set( { strokeWidth: cfg.width } ); } } } } // ADD UNDO if ( !skipped ) { state = JSON.stringify( _this.deepMerge( current.saveState().originalState, { cfg: { color: cfg.color, width: cfg.width, opacity: cfg.opacity } } ) ); current.recentState = state; _this.drawing.redos = []; _this.drawing.undos.push( { action: "modified", target: current, state: state } ); } _this.setup.fabric.renderAll(); } }, text: function( options ) { var cfg = _this.deepMerge( { text: _this.i18l( "menu.label.draw.text" ), top: _this.setup.fabric.height / 2, left: _this.setup.fabric.width / 2, fontSize: _this.drawing.fontSize, fontFamily: _this.setup.chart.fontFamily || "Verdana", fill: _this.drawing.color }, options || {} ); cfg.click = function() {}; var text = new fabric.IText( cfg.text, cfg ); _this.setup.fabric.add( text ); _this.setup.fabric.setActiveObject( text ); text.selectAll(); text.enterEditing(); return text; }, line: function( options ) { var cfg = _this.deepMerge( { x1: ( _this.setup.fabric.width / 2 ) - ( _this.setup.fabric.width / 10 ), x2: ( _this.setup.fabric.width / 2 ) + ( _this.setup.fabric.width / 10 ), y1: ( _this.setup.fabric.height / 2 ), y2: ( _this.setup.fabric.height / 2 ), angle: 90, strokeLineCap: _this.drawing.lineCap, arrow: _this.drawing.arrow, color: _this.drawing.color, width: _this.drawing.width, group: [], }, options || {} ); var i1, arrow, arrowTop, arrowLeft; var line = new fabric.Line( [ cfg.x1, cfg.y1, cfg.x2, cfg.y2 ], { stroke: cfg.color, strokeWidth: cfg.width, strokeLineCap: cfg.strokeLineCap } ); cfg.group.push( line ); if ( cfg.arrow ) { cfg.angle = cfg.angle ? cfg.angle : _this.getAngle( cfg.x1, cfg.y1, cfg.x2, cfg.y2 ); if ( cfg.arrow == "start" ) { arrowTop = cfg.y1 + ( cfg.width / 2 ); arrowLeft = cfg.x1 + ( cfg.width / 2 ); } else if ( cfg.arrow == "middle" ) { arrowTop = cfg.y2 + ( cfg.width / 2 ) - ( ( cfg.y2 - cfg.y1 ) / 2 ); arrowLeft = cfg.x2 + ( cfg.width / 2 ) - ( ( cfg.x2 - cfg.x1 ) / 2 ); } else { // arrow: end arrowTop = cfg.y2 + ( cfg.width / 2 ); arrowLeft = cfg.x2 + ( cfg.width / 2 ); } arrow = new fabric.Triangle( { top: arrowTop, left: arrowLeft, fill: cfg.color, height: cfg.width * 7, width: cfg.width * 7, angle: cfg.angle, originX: "center", originY: "bottom" } ); cfg.group.push( arrow ); } if ( cfg.action != "config" ) { if ( cfg.arrow ) { var group = new fabric.Group( cfg.group ); group.set( { cfg: cfg, fill: cfg.color, action: cfg.action, selectable: true, known: cfg.action == "change" } ); if ( cfg.action == "change" ) { _this.setup.fabric.setActiveObject( group ); } _this.setup.fabric.add( group ); return group; } else { _this.setup.fabric.add( line ); return line; } } else { for ( i1 = 0; i1 < cfg.group.length; i1++ ) { cfg.group[ i1 ].noUndo = true; _this.setup.fabric.add( cfg.group[ i1 ] ); } } return cfg; } } }, defaults: { position: "top-right", fileName: "amCharts", action: "download", overflow: true, path: ( ( chart.path || "" ) + "plugins/export/" ), formats: { JPG: { mimeType: "image/jpg", extension: "jpg", capture: true }, PNG: { mimeType: "image/png", extension: "png", capture: true }, SVG: { mimeType: "text/xml", extension: "svg", capture: true }, PDF: { mimeType: "application/pdf", extension: "pdf", capture: true }, CSV: { mimeType: "text/plain", extension: "csv" }, JSON: { mimeType: "text/plain", extension: "json" }, XLSX: { mimeType: "application/octet-stream", extension: "xlsx" } }, fabric: { backgroundColor: "#FFFFFF", removeImages: true, forceRemoveImages: false, selection: false, loadTimeout: 5000, drawing: { enabled: true, arrow: "end", lineCap: "butt", mode: "pencil", modes: [ "pencil", "line", "arrow" ], color: "#000000", colors: [ "#000000", "#FFFFFF", "#FF0000", "#00FF00", "#0000FF" ], shapes: [ "11.svg", "14.svg", "16.svg", "17.svg", "20.svg", "27.svg" ], width: 1, fontSize: 11, widths: [ 1, 5, 10, 15 ], opacity: 1, opacities: [ 1, 0.8, 0.6, 0.4, 0.2 ], menu: undefined, autoClose: true }, border: { fill: "", fillOpacity: 0, stroke: "#000000", strokeWidth: 1, strokeOpacity: 1 } }, pdfMake: { images: {}, pageOrientation: "portrait", pageMargins: 40, pageOrigin: true, pageSize: "A4", pageSizes: { "4A0": [ 4767.87, 6740.79 ], "2A0": [ 3370.39, 4767.87 ], "A0": [ 2383.94, 3370.39 ], "A1": [ 1683.78, 2383.94 ], "A2": [ 1190.55, 1683.78 ], "A3": [ 841.89, 1190.55 ], "A4": [ 595.28, 841.89 ], "A5": [ 419.53, 595.28 ], "A6": [ 297.64, 419.53 ], "A7": [ 209.76, 297.64 ], "A8": [ 147.40, 209.76 ], "A9": [ 104.88, 147.40 ], "A10": [ 73.70, 104.88 ], "B0": [ 2834.65, 4008.19 ], "B1": [ 2004.09, 2834.65 ], "B2": [ 1417.32, 2004.09 ], "B3": [ 1000.63, 1417.32 ], "B4": [ 708.66, 1000.63 ], "B5": [ 498.90, 708.66 ], "B6": [ 354.33, 498.90 ], "B7": [ 249.45, 354.33 ], "B8": [ 175.75, 249.45 ], "B9": [ 124.72, 175.75 ], "B10": [ 87.87, 124.72 ], "C0": [ 2599.37, 3676.54 ], "C1": [ 1836.85, 2599.37 ], "C2": [ 1298.27, 1836.85 ], "C3": [ 918.43, 1298.27 ], "C4": [ 649.13, 918.43 ], "C5": [ 459.21, 649.13 ], "C6": [ 323.15, 459.21 ], "C7": [ 229.61, 323.15 ], "C8": [ 161.57, 229.61 ], "C9": [ 113.39, 161.57 ], "C10": [ 79.37, 113.39 ], "RA0": [ 2437.80, 3458.27 ], "RA1": [ 1729.13, 2437.80 ], "RA2": [ 1218.90, 1729.13 ], "RA3": [ 864.57, 1218.90 ], "RA4": [ 609.45, 864.57 ], "SRA0": [ 2551.18, 3628.35 ], "SRA1": [ 1814.17, 2551.18 ], "SRA2": [ 1275.59, 1814.17 ], "SRA3": [ 907.09, 1275.59 ], "SRA4": [ 637.80, 907.09 ], "EXECUTIVE": [ 521.86, 756.00 ], "FOLIO": [ 612.00, 936.00 ], "LEGAL": [ 612.00, 1008.00 ], "LETTER": [ 612.00, 792.00 ], "TABLOID": [ 792.00, 1224.00 ] } }, menu: undefined, divId: null, menuReviver: null, menuWalker: null, fallback: true, keyListener: true, fileListener: true, compress: true }, /** * Returns translated message, takes english as default */ i18l: function( key, language ) { var lang = language ? langugage : _this.setup.chart.language ? _this.setup.chart.language : "en"; var catalog = AmCharts.translations[ _this.name ][ lang ] || AmCharts.translations[ _this.name ][ "en" ]; return catalog[ key ] || key; }, /** * Generates download file; if unsupported offers fallback to save manually */ download: function( data, type, filename ) { // SAVE if ( window.saveAs && _this.setup.hasBlob ) { var blob = _this.toBlob( { data: data, type: type }, function( data ) { saveAs( data, filename ); } ); // FALLBACK TEXTAREA } else if ( _this.config.fallback && type == "text/plain" ) { var div = document.createElement( "div" ); var msg = document.createElement( "div" ); var textarea = document.createElement( "textarea" ); msg.innerHTML = _this.i18l( "fallback.save.text" ); div.appendChild( msg ); div.appendChild( textarea ); msg.setAttribute( "class", "amcharts-export-fallback-message" ); div.setAttribute( "class", "amcharts-export-fallback" ); _this.setup.chart.containerDiv.appendChild( div ); // FULFILL TEXTAREA AND PRESELECT textarea.setAttribute( "readonly", "" ); textarea.value = data; textarea.focus(); textarea.select(); // UPDATE MENU _this.createMenu( [ { "class": "export-main export-close", label: "Done", click: function() { _this.createMenu( _this.config.menu ); _this.setup.chart.containerDiv.removeChild( div ); } } ] ); // FALLBACK IMAGE } else if ( _this.config.fallback && type.split( "/" )[ 0 ] == "image" ) { var div = document.createElement( "div" ); var msg = document.createElement( "div" ); var img = _this.toImage( { data: data } ); msg.innerHTML = _this.i18l( "fallback.save.image" ); // FULFILL TEXTAREA AND PRESELECT div.appendChild( msg ); div.appendChild( img ); msg.setAttribute( "class", "amcharts-export-fallback-message" ); div.setAttribute( "class", "amcharts-export-fallback" ); _this.setup.chart.containerDiv.appendChild( div ); // UPDATE MENU _this.createMenu( [ { "class": "export-main export-close", label: "Done", click: function() { _this.createMenu( _this.config.menu ); _this.setup.chart.containerDiv.removeChild( div ); } } ] ); // ERROR } else { throw new Error( "Unable to create file. Ensure saveAs (FileSaver.js) is supported." ); } return data; }, /** * Generates script, links tags and places them into the document's head * In case of reload it replaces the node to force the download */ loadResource: function( src, addons ) { var i1, exist, node, item, check, type; var url = src.indexOf( "//" ) != -1 ? src : [ _this.libs.path, src ].join( "" ); var loadCallback = function callback() { if ( addons ) { for ( i1 = 0; i1 < addons.length; i1++ ) { _this.loadResource( addons[ i1 ] ); } } } if ( src.indexOf( ".js" ) != -1 ) { node = document.createElement( "script" ); node.setAttribute( "type", "text/javascript" ); node.setAttribute( "src", url ); if ( _this.libs.async ) { node.setAttribute( "async", "" ); } } else if ( src.indexOf( ".css" ) != -1 ) { node = document.createElement( "link" ); node.setAttribute( "type", "text/css" ); node.setAttribute( "rel", "stylesheet" ); node.setAttribute( "href", url ); } // NODE CHECK for ( i1 = 0; i1 < document.head.childNodes.length; i1++ ) { item = document.head.childNodes[ i1 ]; check = item ? ( item.src || item.href ) : false; type = item ? item.tagName : false; if ( item && check && check.indexOf( src ) != -1 ) { if ( _this.libs.reload ) { document.head.removeChild( item ); } exist = true; break; } } // NAMESPACE CHECK for ( i1 in _this.libs.namespaces ) { var namespace = _this.libs.namespaces[ i1 ]; var check = src.toLowerCase(); var item = i1.toLowerCase(); if ( check.indexOf( item ) != -1 && window[ namespace ] !== undefined ) { exist = true; break; } } if ( !exist || _this.libs.reload ) { node.addEventListener( "load", loadCallback ); document.head.appendChild( node ); if ( !_this.listenersToRemove ) { _this.listenersToRemove = []; } _this.listenersToRemove.push( { node: node, method: loadCallback, event: "load" } ); } }, /** * Walker to generate the script,link tags */ loadDependencies: function() { var i1, i2; if ( _this.libs.autoLoad ) { for ( i1 = 0; i1 < _this.libs.resources.length; i1++ ) { if ( _this.libs.resources[ i1 ] instanceof Object ) { for ( i2 in _this.libs.resources[ i1 ] ) { _this.loadResource( i2, _this.libs.resources[ i1 ][ i2 ] ); } } else { _this.loadResource( _this.libs.resources[ i1 ] ); } } } }, /** * Converts string to number */ pxToNumber: function( attr, returnUndefined ) { if ( !attr && returnUndefined ) { return undefined; } return Number( String( attr ).replace( "px", "" ) ) || 0; }, /** * Converts number to string */ numberToPx: function( attr ) { return String( attr ) + "px"; }, /** * Referenceless copy of object type variables */ cloneObject: function( o ) { var clone, v, k, isObject, isDate; clone = Array.isArray( o ) ? [] : {}; // Walkthrough values for ( k in o ) { v = o[ k ]; isObject = typeof v === "object"; isDate = v instanceof Date; // Set value; call recursivly if value is an object clone[ k ] = isObject && !isDate ? _this.cloneObject( v ) : v; } return clone; }, /** * Recursive method to merge the given objects together * Overwrite flag replaces the value instead to crawl through */ deepMerge: function( a, b, overwrite ) { var i1, v, type = b instanceof Array ? "array" : "object"; for ( i1 in b ) { // PREVENT METHODS if ( type == "array" && isNaN( i1 ) ) { continue; } v = b[ i1 ]; // NEW if ( a[ i1 ] == undefined || overwrite ) { if ( v instanceof Array ) { a[ i1 ] = new Array(); } else if ( v instanceof Function ) { a[ i1 ] = function() {}; } else if ( v instanceof Date ) { a[ i1 ] = new Date(); } else if ( v instanceof Object ) { a[ i1 ] = new Object(); } else if ( v instanceof Number ) { a[ i1 ] = new Number(); } else if ( v instanceof String ) { a[ i1 ] = new String(); } } if ( ( a instanceof Object || a instanceof Array ) && ( v instanceof Object || v instanceof Array ) && !( v instanceof Function || v instanceof Date || _this.isElement( v ) ) && i1 != "chart" ) { _this.deepMerge( a[ i1 ], v, overwrite ); } else { if ( a instanceof Array && !overwrite ) { a.push( v ); } else { a[ i1 ] = v; } } } return a; }, /** * Checks if given argument is a valid node */ isElement: function( thingy ) { return thingy instanceof Object && thingy && thingy.nodeType === 1; }, /** * Checks if given argument contains a hashbang and returns it */ isHashbanged: function( thingy ) { var str = String( thingy ).replace( /\"/g, "" ); return str.slice( 0, 3 ) == "url" ? str.slice( str.indexOf( "#" ) + 1, str.length - 1 ) : false; }, /** * Checks if given event has been thrown with pressed click / touch */ isPressed: function( event ) { // IE EXCEPTION if ( event.type == "mousemove" && event.which === 1 ) { // IGNORE // OTHERS } else if ( event.type == "touchmove" || event.buttons === 1 || event.button === 1 || event.which === 1 ) { _this.drawing.buffer.isPressed = true; } else { _this.drawing.buffer.isPressed = false; } return _this.drawing.buffer.isPressed; }, /** * Checks if given source needs to be removed */ removeImage: function( source ) { if ( source ) { // FORCE REMOVAL if ( _this.config.fabric.forceRemoveImages ) { return true; // REMOVE TAINTED } else if ( _this.config.fabric.removeImages && _this.isTainted( source ) ) { return true; // IE 10 internal bug handling SVG images in canvas context } else if ( _this.setup.isIE && ( _this.setup.IEversion == 10 || _this.setup.IEversion == 11 ) && source.toLowerCase().indexOf( ".svg" ) != -1 ) { return true; } } return false }, /** * Checks if given source is within the current origin */ isTainted: function( source ) { var origin = String( window.location.origin || window.location.protocol + "//" + window.location.hostname + ( window.location.port ? ':' + window.location.port : '' ) ); // CHECK GIVEN SOURCE if ( source ) { // LOCAL FILES ARE ALWAYS TAINTED if ( origin.indexOf( ":\\" ) != -1 || source.indexOf( ":\\" ) != -1 || origin.indexOf( "file://" ) != -1 || source.indexOf( "file://" ) != -1 ) { return true // MISMATCHING ORIGIN } else if ( source.indexOf( "//" ) != -1 && source.indexOf( origin.replace( /.*:/, "" ) ) == -1 ) { return true; } } return false; }, /* ** Checks several indicators for acceptance; */ isSupported: function() { // CHECK CONFIG if ( !_this.config.enabled ) { return false; } // CHECK IE; ATTEMPT TO ACCESS HEAD ELEMENT if ( _this.setup.isIE && _this.setup.IEversion <= 9 ) { if ( !Array.prototype.indexOf || !document.head || _this.config.fallback === false ) { return false; } } return true; }, getAngle: function( x1, y1, x2, y2 ) { var x = x2 - x1; var y = y2 - y1; var angle; if ( x == 0 ) { if ( y == 0 ) { angle = 0; } else if ( y > 0 ) { angle = Math.PI / 2; } else { angle = Math.PI * 3 / 2; } } else if ( y == 0 ) { if ( x > 0 ) { angle = 0; } else { angle = Math.PI; } } else { if ( x < 0 ) { angle = Math.atan( y / x ) + Math.PI; } else if ( y < 0 ) { angle = Math.atan( y / x ) + ( 2 * Math.PI ); } else { angle = Math.atan( y / x ); } } return angle * 180 / Math.PI; }, /** * Recursive method which crawls upwards to gather the requested attribute */ gatherAttribute: function( elm, attr, limit, lvl ) { var value, lvl = lvl ? lvl : 0, limit = limit ? limit : 3; if ( elm ) { value = elm.getAttribute( attr ); if ( !value && lvl < limit ) { return _this.gatherAttribute( elm.parentNode, attr, limit, lvl + 1 ); } } return value; }, /** * Recursive method which crawls upwards to gather the requested classname */ gatherClassName: function( elm, className, limit, lvl ) { var value, lvl = lvl ? lvl : 0, limit = limit ? limit : 3; if ( _this.isElement( elm ) ) { value = ( elm.getAttribute( "class" ) || "" ).split( " " ).indexOf( className ) != -1; if ( !value && lvl < limit ) { return _this.gatherClassName( elm.parentNode, className, limit, lvl + 1 ); } else if ( value ) { value = elm; } } return value; }, /** * Collects the clip-paths and patterns */ gatherElements: function( group, cfg, images ) { var i1, i2; for ( i1 = 0; i1 < group.children.length; i1++ ) { var childNode = group.children[ i1 ]; // CLIPPATH if ( childNode.tagName == "clipPath" ) { var bbox = {}; var transform = fabric.parseTransformAttribute( _this.gatherAttribute( childNode, "transform" ) ); // HIDE SIBLINGS; GATHER IT'S DIMENSIONS for ( i2 = 0; i2 < childNode.childNodes.length; i2++ ) { childNode.childNodes[ i2 ].setAttribute( "fill", "transparent" ); bbox = { x: _this.pxToNumber( childNode.childNodes[ i2 ].getAttribute( "x" ) ), y: _this.pxToNumber( childNode.childNodes[ i2 ].getAttribute( "y" ) ), width: _this.pxToNumber( childNode.childNodes[ i2 ].getAttribute( "width" ) ), height: _this.pxToNumber( childNode.childNodes[ i2 ].getAttribute( "height" ) ) } } group.clippings[ childNode.id ] = { svg: childNode, bbox: bbox, transform: transform }; // PATTERN } else if ( childNode.tagName == "pattern" ) { var props = { node: childNode, source: childNode.getAttribute( "xlink:href" ), width: Number( childNode.getAttribute( "width" ) ), height: Number( childNode.getAttribute( "height" ) ), repeat: "repeat", offsetX: 0, offsetY: 0 } // GATHER BACKGROUND for ( i2 = 0; i2 < childNode.childNodes.length; i2++ ) { // RECT; COLOR if ( childNode.childNodes[ i2 ].tagName == "rect" ) { props.fill = childNode.childNodes[ i2 ].getAttribute( "fill" ); // IMAGE } else if ( childNode.childNodes[ i2 ].tagName == "image" ) { var attrs = fabric.parseAttributes( childNode.childNodes[ i2 ], fabric.SHARED_ATTRIBUTES ); if ( attrs.transformMatrix ) { props.offsetX = attrs.transformMatrix[ 4 ]; props.offsetY = attrs.transformMatrix[ 5 ]; } } } // TAINTED if ( _this.removeImage( props.source ) ) { group.patterns[ childNode.id ] = props.fill ? props.fill : "transparent"; } else { group.patterns[ props.node.id ] = props; } // IMAGES } else if ( childNode.tagName == "image" ) { images.included++; // LOAD IMAGE MANUALLY; TO RERENDER THE CANVAS fabric.Image.fromURL( childNode.getAttribute( "xlink:href" ), function( img ) { images.loaded++; } ); // FILL STROKE POLYFILL ON EVERY ELEMENT } else { var attrs = [ "fill", "stroke" ]; for ( i2 = 0; i2 < attrs.length; i2++ ) { var attr = attrs[ i2 ]; var attrVal = childNode.getAttribute( attr ); var attrRGBA = _this.getRGBA( attrVal ); var isHashbanged = _this.isHashbanged( attrVal ); // VALIDATE AND RESET UNKNOWN COLORS (avoids fabric to crash) if ( attrVal && !attrRGBA && !isHashbanged ) { childNode.setAttribute( attr, "none" ); childNode.setAttribute( attr + "-opacity", "0" ); } } } } return group; }, /* ** GET RGBA COLOR ARRAY FROM INPUT */ getRGBA: function( source, returnInstance ) { if ( source != "none" && source != "transparent" && !_this.isHashbanged( source ) ) { source = new fabric.Color( source ); if ( source._source ) { return returnInstance ? source : source.getSource(); } } return false; }, /* ** GATHER MOUSE POSITION; */ gatherPosition: function( event, type ) { var ref = _this.drawing.buffer.position; var ivt = fabric.util.invertTransform( _this.setup.fabric.viewportTransform ); var pos; if ( event.type == "touchmove" ) { if ( "touches" in event ) { event = event.touches[ 0 ]; } else if ( "changedTouches" in event ) { event = event.changedTouches[ 0 ]; } } pos = fabric.util.transformPoint( _this.setup.fabric.getPointer( event, true ), ivt ); if ( type == 1 ) { ref.x1 = pos.x; ref.y1 = pos.y; } ref.x2 = pos.x; ref.y2 = pos.y; ref.xD = ( ref.x1 - ref.x2 ) < 0 ? ( ref.x1 - ref.x2 ) * -1 : ( ref.x1 - ref.x2 ); ref.yD = ( ref.y1 - ref.y2 ) < 0 ? ( ref.y1 - ref.y2 ) * -1 : ( ref.y1 - ref.y2 ); return ref; }, modifyFabric: function() { // ADAPTED THE WAY TO RECEIVE THE GRADIENTID fabric.ElementsParser.prototype.resolveGradient = function( obj, property ) { var instanceFillValue = obj.get( property ); if ( !( /^url\(/ ).test( instanceFillValue ) ) { return; } var gradientId = instanceFillValue.slice( instanceFillValue.indexOf( "#" ) + 1, instanceFillValue.length - 1 ); if ( fabric.gradientDefs[ this.svgUid ][ gradientId ] ) { obj.set( property, fabric.Gradient.fromElement( fabric.gradientDefs[ this.svgUid ][ gradientId ], obj ) ); } }; // MULTILINE SUPPORT; TODO: BETTER POSITIONING fabric.Text.fromElement = function( element, options ) { if ( !element ) { return null; } var parsedAttributes = fabric.parseAttributes( element, fabric.Text.ATTRIBUTE_NAMES ); options = fabric.util.object.extend( ( options ? fabric.util.object.clone( options ) : {} ), parsedAttributes ); options.top = options.top || 0; options.left = options.left || 0; if ( 'dx' in parsedAttributes ) { options.left += parsedAttributes.dx; } if ( 'dy' in parsedAttributes ) { options.top += parsedAttributes.dy; } if ( !( 'fontSize' in options ) ) { options.fontSize = fabric.Text.DEFAULT_SVG_FONT_SIZE; } if ( !options.originX ) { options.originX = 'left'; } var textContent = ''; var textBuffer = []; // The XML is not properly parsed in IE9 so a workaround to get // textContent is through firstChild.data. Another workaround would be // to convert XML loaded from a file to be converted using DOMParser (same way loadSVGFromString() does) if ( !( 'textContent' in element ) ) { if ( 'firstChild' in element && element.firstChild !== null ) { if ( 'data' in element.firstChild && element.firstChild.data !== null ) { textBuffer.push( element.firstChild.data ); } } } else if ( element.childNodes ) { for ( var i1 = 0; i1 < element.childNodes.length; i1++ ) { textBuffer.push( element.childNodes[ i1 ].textContent ); } } else { textBuffer.push( element.textContent ); } textContent = textBuffer.join( "\n" ); //textContent = textContent.replace(/^\s+|\s+$|\n+/g, '').replace(/\s+/g, ' '); var text = new fabric.Text( textContent, options ), /* Adjust positioning: x/y attributes in SVG correspond to the bottom-left corner of text bounding box top/left properties in Fabric correspond to center point of text bounding box */ offX = 0; if ( text.originX === 'left' ) { offX = text.getWidth() / 2; } if ( text.originX === 'right' ) { offX = -text.getWidth() / 2; } if ( textBuffer.length > 1 ) { text.set( { left: text.getLeft() + offX, top: text.getTop() + text.fontSize * ( textBuffer.length - 1 ) * ( 0.18 + text._fontSizeFraction ), textAlign: options.originX, lineHeight: textBuffer.length > 1 ? 0.965 : 1.16, } ); } else { text.set( { left: text.getLeft() + offX, top: text.getTop() - text.getHeight() / 2 + text.fontSize * ( 0.18 + text._fontSizeFraction ) /* 0.3 is the old lineHeight */ } ); } return text; }; }, /** * Method to capture the current state of the chart */ capture: function( options, callback ) { var i1; var cfg = _this.deepMerge( _this.deepMerge( {}, _this.config.fabric ), options || {} ); var groups = []; var offset = { x: 0, y: 0, pX: 0, pY: 0, lX: 0, lY: 0, width: _this.setup.chart.divRealWidth, height: _this.setup.chart.divRealHeight }; var images = { loaded: 0, included: 0 } var legends = { items: [], width: 0, height: 0, maxWidth: 0, maxHeight: 0 } // MODIFY FABRIC UNTIL IT'S OFFICIALLY SUPPORTED _this.modifyFabric(); // BEFORE CAPTURING _this.handleCallback( cfg.beforeCapture, cfg ); // GATHER SVGS var svgs = _this.setup.chart.containerDiv.getElementsByTagName( "svg" ); for ( i1 = 0; i1 < svgs.length; i1++ ) { var group = { svg: svgs[ i1 ], parent: svgs[ i1 ].parentNode, children: svgs[ i1 ].getElementsByTagName( "*" ), offset: { x: 0, y: 0 }, patterns: {}, clippings: {}, has: { legend: false, panel: false, scrollbar: false } } // CHECK IT'S SURROUNDINGS group.has.legend = _this.gatherClassName( group.parent, _this.setup.chart.classNamePrefix + "-legend-div", 1 ); group.has.panel = _this.gatherClassName( group.parent, _this.setup.chart.classNamePrefix + "-stock-panel-div" ); group.has.scrollbar = _this.gatherClassName( group.parent, _this.setup.chart.classNamePrefix + "-scrollbar-chart-div" ); // GATHER ELEMENTS group = _this.gatherElements( group, cfg, images ); // APPEND GROUP groups.push( group ); } // GATHER EXTERNAL LEGEND if ( _this.config.legend ) { // STOCK if ( _this.setup.chart.type == "stock" ) { for ( i1 = 0; i1 < _this.setup.chart.panels.length; i1++ ) { if ( _this.setup.chart.panels[ i1 ].stockLegend && _this.setup.chart.panels[ i1 ].stockLegend.divId ) { legends.items.push( _this.setup.chart.panels[ i1 ].stockLegend ); } } // NORMAL } else if ( _this.setup.chart.legend && _this.setup.chart.legend.divId ) { legends.items.push( _this.setup.chart.legend ); } // WALKTHROUGH for ( i1 = 0; i1 < legends.items.length; i1++ ) { var legend = legends.items[ i1 ]; var group = { svg: legend.container.container, parent: legend.container.container.parentNode, children: legend.container.container.getElementsByTagName( "*" ), offset: { x: 0, y: 0 }, legend: { id: i1, type: [ "top", "left" ].indexOf( _this.config.legend.position ) != -1 ? "unshift" : "push", position: _this.config.legend.position, width: _this.config.legend.width ? _this.config.legend.width : legend.container.div.offsetWidth, height: _this.config.legend.height ? _this.config.legend.height : legend.container.div.offsetHeight }, patterns: {}, clippings: {}, has: { legend: false, panel: false, scrollbar: false } } // GATHER DIMENSIONS legends.width += group.legend.width; legends.height += group.legend.height; legends.maxWidth = group.legend.width > legends.maxWidth ? group.legend.width : legends.maxWidth; legends.maxHeight = group.legend.height > legends.maxHeight ? group.legend.height : legends.maxHeight; // GATHER ELEMENTS group = _this.gatherElements( group, cfg, images ); // PRE/APPEND SVG groups[ group.legend.type ]( group ); } // ADAPT WIDTH IF NEEDED; EXPAND HEIGHT if ( [ "top", "bottom" ].indexOf( _this.config.legend.position ) != -1 ) { offset.width = legends.maxWidth > offset.width ? legends.maxWidth : offset.width; offset.height += legends.height; // EXPAND WIDTH; ADAPT HEIGHT IF NEEDED } else if ( [ "left", "right" ].indexOf( _this.config.legend.position ) != -1 ) { offset.width += legends.maxWidth; offset.height = legends.height > offset.height ? legends.height : offset.height; // SIMPLY EXPAND CANVAS } else { offset.height += legends.height; offset.width += legends.maxWidth; } } // CLEAR IF EXIST _this.drawing.enabled = cfg.drawing.enabled = cfg.action == "draw"; _this.drawing.buffer.enabled = _this.drawing.enabled; // history reasons _this.setup.wrapper = document.createElement( "div" ); _this.setup.wrapper.setAttribute( "class", _this.setup.chart.classNamePrefix + "-export-canvas" ); _this.setup.chart.containerDiv.appendChild( _this.setup.wrapper ); // STOCK CHART; SELECTOR OFFSET if ( _this.setup.chart.type == "stock" ) { var padding = { top: 0, right: 0, bottom: 0, left: 0 } if ( _this.setup.chart.leftContainer ) { offset.width -= _this.setup.chart.leftContainer.offsetWidth; padding.left = _this.setup.chart.leftContainer.offsetWidth + ( _this.setup.chart.panelsSettings.panelSpacing * 2 ); } if ( _this.setup.chart.rightContainer ) { offset.width -= _this.setup.chart.rightContainer.offsetWidth; padding.right = _this.setup.chart.rightContainer.offsetWidth + ( _this.setup.chart.panelsSettings.panelSpacing * 2 ); } if ( _this.setup.chart.periodSelector && [ "top", "bottom" ].indexOf( _this.setup.chart.periodSelector.position ) != -1 ) { offset.height -= _this.setup.chart.periodSelector.offsetHeight + _this.setup.chart.panelsSettings.panelSpacing; padding[ _this.setup.chart.periodSelector.position ] += _this.setup.chart.periodSelector.offsetHeight + _this.setup.chart.panelsSettings.panelSpacing; } if ( _this.setup.chart.dataSetSelector && [ "top", "bottom" ].indexOf( _this.setup.chart.dataSetSelector.position ) != -1 ) { offset.height -= _this.setup.chart.dataSetSelector.offsetHeight; padding[ _this.setup.chart.dataSetSelector.position ] += _this.setup.chart.dataSetSelector.offsetHeight; } // APPLY OFFSET ON WRAPPER _this.setup.wrapper.style.paddingTop = _this.numberToPx( padding.top ); _this.setup.wrapper.style.paddingRight = _this.numberToPx( padding.right ); _this.setup.wrapper.style.paddingBottom = _this.numberToPx( padding.bottom ); _this.setup.wrapper.style.paddingLeft = _this.numberToPx( padding.left ); } // CREATE CANVAS _this.setup.canvas = document.createElement( "canvas" ); _this.setup.wrapper.appendChild( _this.setup.canvas ); _this.setup.fabric = new fabric.Canvas( _this.setup.canvas, _this.deepMerge( { width: offset.width, height: offset.height, isDrawingMode: true }, cfg ) ); // REAPPLY FOR SOME REASON _this.deepMerge( _this.setup.fabric, cfg ); _this.deepMerge( _this.setup.fabric.freeDrawingBrush, cfg.drawing ); // RELIABLE VARIABLES; UPDATE DRAWING _this.deepMerge( _this.drawing, cfg.drawing ); _this.drawing.handler.change( cfg.drawing ); // OBSERVE MOUSE EVENTS _this.setup.fabric.on( "mouse:down", function( e ) { var p = _this.gatherPosition( e.e, 1 ); _this.drawing.buffer.pressedTS = Number( new Date() ); _this.isPressed( e.e ); } ); _this.setup.fabric.on( "mouse:move", function( e ) { var p = _this.gatherPosition( e.e, 2 ); _this.isPressed( e.e ); // CREATE INITIAL LINE / ARROW; JUST ON LEFT CLICK if ( _this.drawing.buffer.isPressed && !_this.drawing.buffer.line ) { if ( !_this.drawing.buffer.isSelected && _this.drawing.mode != "pencil" && ( p.xD > 5 || p.xD > 5 ) ) { _this.drawing.buffer.hasLine = true; _this.setup.fabric.isDrawingMode = false; _this.setup.fabric._onMouseUpInDrawingMode( e ); _this.drawing.buffer.line = _this.drawing.handler.line( { x1: p.x1, y1: p.y1, x2: p.x2, y2: p.y2, arrow: _this.drawing.mode == "line" ? false : _this.drawing.arrow, action: "config" } ); } } // UPDATE LINE / ARROW if ( _this.drawing.buffer.line ) { var obj, top, left; var l = _this.drawing.buffer.line; l.x2 = p.x2; l.y2 = p.y2; for ( i1 = 0; i1 < l.group.length; i1++ ) { obj = l.group[ i1 ]; if ( obj instanceof fabric.Line ) { obj.set( { x2: l.x2, y2: l.y2 } ); } else if ( obj instanceof fabric.Triangle ) { l.angle = ( _this.getAngle( l.x1, l.y1, l.x2, l.y2 ) + 90 ); if ( l.arrow == "start" ) { top = l.y1 + ( l.width / 2 ); left = l.x1 + ( l.width / 2 ); } else if ( l.arrow == "middle" ) { top = l.y2 + ( l.width / 2 ) - ( ( l.y2 - l.y1 ) / 2 ); left = l.x2 + ( l.width / 2 ) - ( ( l.x2 - l.x1 ) / 2 ); } else { // arrow: end top = l.y2 + ( l.width / 2 ); left = l.x2 + ( l.width / 2 ); } obj.set( { top: top, left: left, angle: l.angle } ); } } _this.setup.fabric.renderAll(); } } ); _this.setup.fabric.on( "mouse:up", function( e ) { // SELECT TARGET if ( Number( new Date() ) - _this.drawing.buffer.pressedTS < 200 ) { var target = _this.setup.fabric.findTarget( e.e ); if ( target && target.selectable ) { _this.setup.fabric.setActiveObject( target ); } } // UPDATE LINE / ARROW if ( _this.drawing.buffer.line ) { for ( i1 = 0; i1 < _this.drawing.buffer.line.group.length; i1++ ) { _this.drawing.buffer.line.group[ i1 ].remove(); } delete _this.drawing.buffer.line.action; delete _this.drawing.buffer.line.group; _this.drawing.handler.line( _this.drawing.buffer.line ); } _this.drawing.buffer.line = false; _this.drawing.buffer.hasLine = false; _this.drawing.buffer.isPressed = false; } ); // OBSERVE OBJECT SELECTION _this.setup.fabric.on( "object:selected", function( e ) { _this.drawing.buffer.isSelected = true; _this.drawing.buffer.target = e.target; _this.setup.fabric.isDrawingMode = false; } ); _this.setup.fabric.on( "selection:cleared", function( e ) { _this.drawing.buffer.onMouseDown = _this.setup.fabric.freeDrawingBrush.onMouseDown; _this.drawing.buffer.target = false; // FREEHAND WORKAROUND if ( _this.drawing.buffer.isSelected ) { _this.setup.fabric._isCurrentlyDrawing = false; _this.setup.fabric.freeDrawingBrush.onMouseDown = function() {}; } // DELAYED DESELECTION TO PREVENT DRAWING setTimeout( function() { _this.drawing.buffer.isSelected = false; _this.setup.fabric.isDrawingMode = true; _this.setup.fabric.freeDrawingBrush.onMouseDown = _this.drawing.buffer.onMouseDown; }, 10 ); } ); _this.setup.fabric.on( "path:created", function( e ) { var item = e.path; if ( Number( new Date() ) - _this.drawing.buffer.pressedTS < 200 || _this.drawing.buffer.hasLine ) { _this.setup.fabric.remove( item ); _this.setup.fabric.renderAll(); return; } } ); // OBSERVE OBJECT MODIFICATIONS _this.setup.fabric.on( "object:added", function( e ) { var item = e.target; var state = _this.deepMerge( item.saveState().originalState, { cfg: { color: _this.drawing.color, width: _this.drawing.width, opacity: _this.drawing.opacity, fontSize: _this.drawing.fontSize } } ); if ( Number( new Date() ) - _this.drawing.buffer.pressedTS < 200 && !item.noUndo ) { _this.setup.fabric.remove( item ); _this.setup.fabric.renderAll(); return; } state = JSON.stringify( state ); item.recentState = state; if ( item.selectable && !item.known && !item.noUndo ) { item.isAnnotation = true; _this.drawing.undos.push( { action: "added", target: item, state: state } ); _this.drawing.undos.push( { action: "addified", target: item, state: state } ); _this.drawing.redos = []; } item.known = true; _this.setup.fabric.isDrawingMode = true; } ); _this.setup.fabric.on( "object:modified", function( e ) { var item = e.target; var recentState = JSON.parse( item.recentState ); var state = _this.deepMerge( item.saveState().originalState, { cfg: recentState.cfg } ); state = JSON.stringify( state ); item.recentState = state; _this.drawing.undos.push( { action: "modified", target: item, state: state } ); _this.drawing.redos = []; } ); _this.setup.fabric.on( "text:changed", function( e ) { var item = e.target; clearTimeout( item.timer ); item.timer = setTimeout( function() { var state = JSON.stringify( item.saveState().originalState ); item.recentState = state; _this.drawing.redos = []; _this.drawing.undos.push( { action: "modified", target: item, state: state } ); }, 250 ); } ); // DRAWING if ( _this.drawing.enabled ) { _this.setup.wrapper.setAttribute( "class", _this.setup.chart.classNamePrefix + "-export-canvas active" ); _this.setup.wrapper.style.backgroundColor = cfg.backgroundColor; _this.setup.wrapper.style.display = "block"; } else { _this.setup.wrapper.setAttribute( "class", _this.setup.chart.classNamePrefix + "-export-canvas" ); _this.setup.wrapper.style.display = "none"; } for ( i1 = 0; i1 < groups.length; i1++ ) { var group = groups[ i1 ]; // STOCK CHART; SVG OFFSET; SVG OFFSET if ( _this.setup.chart.type == "stock" && _this.setup.chart.legendSettings.position ) { // TOP / BOTTOM if ( [ "top", "bottom" ].indexOf( _this.setup.chart.legendSettings.position ) != -1 ) { // POSITION; ABSOLUTE if ( group.parent.style.top && group.parent.style.left ) { group.offset.y = _this.pxToNumber( group.parent.style.top ); group.offset.x = _this.pxToNumber( group.parent.style.left ); // POSITION; RELATIVE } else { group.offset.x = offset.x; group.offset.y = offset.y; offset.y += _this.pxToNumber( group.parent.style.height ); // LEGEND; OFFSET if ( group.has.panel ) { offset.pY = _this.pxToNumber( group.has.panel.style.marginTop ); group.offset.y += offset.pY; // SCROLLBAR; OFFSET } else if ( group.has.scrollbar ) { group.offset.y += offset.pY; } } // LEFT / RIGHT } else if ( [ "left", "right" ].indexOf( _this.setup.chart.legendSettings.position ) != -1 ) { group.offset.y = _this.pxToNumber( group.parent.style.top ) + offset.pY; group.offset.x = _this.pxToNumber( group.parent.style.left ) + offset.pX; // LEGEND; OFFSET if ( group.has.legend ) { offset.pY += _this.pxToNumber( group.has.panel.style.height ) + _this.setup.chart.panelsSettings.panelSpacing; // SCROLLBAR; OFFSET } else if ( group.has.scrollbar ) { group.offset.y -= _this.setup.chart.panelsSettings.panelSpacing; } } // REGULAR CHARTS; SVG OFFSET } else { // POSITION; ABSOLUTE if ( group.parent.style.position == "absolute" ) { group.offset.absolute = true; group.offset.top = _this.pxToNumber( group.parent.style.top ); group.offset.right = _this.pxToNumber( group.parent.style.right, true ); group.offset.bottom = _this.pxToNumber( group.parent.style.bottom, true ); group.offset.left = _this.pxToNumber( group.parent.style.left ); group.offset.width = _this.pxToNumber( group.parent.style.width ); group.offset.height = _this.pxToNumber( group.parent.style.height ); // POSITION; RELATIVE } else if ( group.parent.style.top && group.parent.style.left ) { group.offset.y = _this.pxToNumber( group.parent.style.top ); group.offset.x = _this.pxToNumber( group.parent.style.left ); // POSITION; GENERIC } else { // EXTERNAL LEGEND if ( group.legend ) { if ( group.legend.position == "left" ) { offset.x = legends.maxWidth; } else if ( group.legend.position == "right" ) { group.offset.x = offset.width - legends.maxWidth; } else if ( group.legend.position == "top" ) { offset.y += group.legend.height; } else if ( group.legend.position == "bottom" ) { group.offset.y = offset.height - legends.height; } // STACK LEGENDS group.offset.y += offset.lY; offset.lY += group.legend.height; // NORMAL } else { group.offset.x = offset.x; group.offset.y = offset.y + offset.pY; offset.y += _this.pxToNumber( group.parent.style.height ); } } // PANEL OFFSET (STOCK CHARTS) if ( group.has.legend && group.has.panel && group.has.panel.style.marginTop ) { offset.y += _this.pxToNumber( group.has.panel.style.marginTop ); group.offset.y += _this.pxToNumber( group.has.panel.style.marginTop ); // GENERAL LEFT / RIGHT POSITION } else if ( _this.setup.chart.legend && [ "left", "right" ].indexOf( _this.setup.chart.legend.position ) != -1 ) { group.offset.y = _this.pxToNumber( group.parent.style.top ); group.offset.x = _this.pxToNumber( group.parent.style.left ); } } // ADD TO CANVAS fabric.parseSVGDocument( group.svg, ( function( group ) { return function( objects, options ) { var i1, i2; var g = fabric.util.groupSVGElements( objects, options ); var paths = []; var tmp = { selectable: false, isCoreElement: true }; // GROUP OFFSET; ABSOLUTE if ( group.offset.absolute ) { if ( group.offset.bottom !== undefined ) { tmp.top = offset.height - group.offset.height - group.offset.bottom; } else { tmp.top = group.offset.top; } if ( group.offset.right !== undefined ) { tmp.left = offset.width - group.offset.width - group.offset.right; } else { tmp.left = group.offset.left; } // GROUP OFFSET; REGULAR } else { tmp.top = group.offset.y; tmp.left = group.offset.x; } // WALKTHROUGH ELEMENTS for ( i1 = 0; i1 < g.paths.length; i1++ ) { var PID = null; // OPACITY; TODO: DISTINGUISH OPACITY TYPES if ( g.paths[ i1 ] ) { // CHECK ORIGIN; REMOVE TAINTED if ( _this.removeImage( g.paths[ i1 ][ "xlink:href" ] ) ) { continue; } // SET OPACITY if ( g.paths[ i1 ].fill instanceof Object ) { // MISINTERPRETATION OF FABRIC if ( g.paths[ i1 ].fill.type == "radial" ) { // OTHERS if ( [ "pie", "gauge" ].indexOf( _this.setup.chart.type ) == -1 ) { g.paths[ i1 ].fill.coords.r2 = g.paths[ i1 ].fill.coords.r1 * -1; g.paths[ i1 ].fill.coords.r1 = 0; g.paths[ i1 ].set( { opacity: g.paths[ i1 ].fillOpacity } ); } } // FILLING; TODO: DISTINGUISH OPACITY TYPES } else if ( PID = _this.isHashbanged( g.paths[ i1 ].fill ) ) { // PATTERN if ( group.patterns && group.patterns[ PID ] ) { var props = group.patterns[ PID ]; images.included++; // LOAD IMAGE MANUALLY; TO RERENDER THE CANVAS fabric.Image.fromURL( props.source, ( function( props, i1 ) { return function( img ) { images.loaded++; // ADAPT IMAGE img.set( { top: props.offsetY, left: props.offsetX, width: props.width, height: props.height } ); // RETINA DISPLAY if ( _this.setup.fabric._isRetinaScaling() ) { img.set( { top: props.offsetY / 2, left: props.offsetX / 2, scaleX: 0.5, scaleY: 0.5 } ); } // CREATE CANVAS WITH BACKGROUND COLOR var patternSourceCanvas = new fabric.StaticCanvas( undefined, { backgroundColor: props.fill, width: img.getWidth(), height: img.getHeight() } ); patternSourceCanvas.add( img ); // CREATE PATTERN OBTAIN OFFSET TO TARGET var pattern = new fabric.Pattern( { source: patternSourceCanvas.getElement(), offsetX: g.paths[ i1 ].width / 2, offsetY: g.paths[ i1 ].height / 2, repeat: 'repeat', } ); // ASSIGN TO OBJECT g.paths[ i1 ].set( { fill: pattern, opacity: g.paths[ i1 ].fillOpacity } ); } } )( props, i1 ) ); } } // CLIPPATH; if ( PID = _this.isHashbanged( g.paths[ i1 ].clipPath ) ) { if ( group.clippings && group.clippings[ PID ] ) { // TODO: WAIT UNTIL FABRICJS HANDLES CLIPPATH FOR SVG OUTPUT ( function( i1, PID ) { var toSVG = g.paths[ i1 ].toSVG; g.paths[ i1 ].toSVG = function( original_reviver ) { return toSVG.apply( this, [ function( string ) { return original_reviver( string, group.clippings[ PID ] ); } ] ); } } )( i1, PID ); g.paths[ i1 ].set( { clipTo: ( function( i1, PID ) { return function( ctx ) { var cp = group.clippings[ PID ]; var tm = this.transformMatrix || [ 1, 0, 0, 1, 0, 0 ]; var dim = { top: cp.bbox.y, left: cp.bbox.x, width: cp.bbox.width, height: cp.bbox.height } if ( _this.setup.chart.type == "map" ) { dim.top += cp.transform[ 5 ]; dim.left += cp.transform[ 4 ]; } if ( cp.bbox.x && tm[ 4 ] && cp.bbox.y && tm[ 5 ] ) { dim.top -= tm[ 5 ]; dim.left -= tm[ 4 ]; } ctx.rect( dim.left, dim.top, dim.width, dim.height ); } } )( i1, PID ) } ); } } } paths.push( g.paths[ i1 ] ); } // REPLACE WITH WHITELIST g.paths = paths; // SET PROPS g.set( tmp ); // ADD TO CANVAS _this.setup.fabric.add( g ); // ADD BALLOONS if ( group.svg.parentNode && group.svg.parentNode.getElementsByTagName ) { var balloons = group.svg.parentNode.getElementsByClassName( _this.setup.chart.classNamePrefix + "-balloon-div" ); for ( i1 = 0; i1 < balloons.length; i1++ ) { if ( cfg.balloonFunction instanceof Function ) { cfg.balloonFunction.apply( _this, [ balloons[ i1 ], group ] ); } else { var elm_parent = balloons[ i1 ]; var style_parent = fabric.parseStyleAttribute( elm_parent ); var style_text = fabric.parseStyleAttribute( elm_parent.childNodes[ 0 ] ); var fabric_label = new fabric.Text( elm_parent.innerText || elm_parent.textContent || elm_parent.innerHTML, { selectable: false, top: style_parent.top + group.offset.y, left: style_parent.left + group.offset.x, fill: style_text[ "color" ], fontSize: style_text[ "fontSize" ], fontFamily: style_text[ "fontFamily" ], textAlign: style_text[ "text-align" ], isCoreElement: true } ); _this.setup.fabric.add( fabric_label ); } } } if ( group.svg.nextSibling && group.svg.nextSibling.tagName == "A" ) { var elm_parent = group.svg.nextSibling; var style_parent = fabric.parseStyleAttribute( elm_parent ); var fabric_label = new fabric.Text( elm_parent.innerText || elm_parent.textContent || elm_parent.innerHTML, { selectable: false, top: style_parent.top + group.offset.y, left: style_parent.left + group.offset.x, fill: style_parent[ "color" ], fontSize: style_parent[ "fontSize" ], fontFamily: style_parent[ "fontFamily" ], opacity: style_parent[ "opacity" ], isCoreElement: true } ); if ( !group.has.scrollbar ) { _this.setup.fabric.add( fabric_label ); } } groups.pop(); // TRIGGER CALLBACK WITH SAFETY DELAY if ( !groups.length ) { var ts1 = Number( new Date() ); var timer = setInterval( function() { var ts2 = Number( new Date() ); // WAIT FOR LOADED IMAGES OR UNTIL THE TIMEOUT KICKS IN if ( images.loaded == images.included || ts2 - ts1 > _this.config.fabric.loadTimeout ) { clearTimeout( timer ); _this.handleBorder( cfg ); _this.handleCallback( cfg.afterCapture, cfg ); _this.setup.fabric.renderAll(); _this.handleCallback( callback, cfg ); } }, AmCharts.updateRate ); } } // IDENTIFY ELEMENTS THROUGH CLASSNAMES } )( group ), function( svg, obj ) { var i1; var className = _this.gatherAttribute( svg, "class" ); var visibility = _this.gatherAttribute( svg, "visibility" ); var clipPath = _this.gatherAttribute( svg, "clip-path" ); obj.className = String( className ); obj.classList = String( className ).split( " " ); obj.clipPath = clipPath; obj.svg = svg; // TRANSPORT FILL/STROKE OPACITY var attrs = [ "fill", "stroke" ]; for ( i1 = 0; i1 < attrs.length; i1++ ) { var attr = attrs[ i1 ] var attrVal = String( svg.getAttribute( attr ) || "none" ); var attrOpacity = Number( svg.getAttribute( attr + "-opacity" ) || "1" ); var attrRGBA = _this.getRGBA( attrVal ); // HIDE HIDDEN ELEMENTS; TODO: FIND A BETTER WAY TO HANDLE THAT if ( visibility == "hidden" ) { obj.opacity = 0; attrOpacity = 0; } // SET COLOR if ( attrRGBA ) { attrRGBA.pop(); attrRGBA.push( attrOpacity ) obj[ attr ] = "rgba(" + attrRGBA.join() + ")"; obj[ attr + _this.capitalize( "opacity" ) ] = attrOpacity; } } // REVIVER _this.handleCallback( cfg.reviver, obj, svg ); } ); } }, /** * Returns the current canvas */ toCanvas: function( options, callback ) { var cfg = _this.deepMerge( { // NUFFIN }, options || {} ); var data = _this.setup.canvas; // TRIGGER CALLBACK _this.handleCallback( callback, data, cfg ); return data; }, /** * Returns an image; by default PNG */ toImage: function( options, callback ) { var cfg = _this.deepMerge( { format: "png", quality: 1, multiplier: _this.config.multiplier }, options || {} ); var data = cfg.data; var img = document.createElement( "img" ); if ( !cfg.data ) { if ( cfg.lossless || cfg.format == "svg" ) { data = _this.toSVG( _this.deepMerge( cfg, { getBase64: true } ) ); } else { data = _this.setup.fabric.toDataURL( cfg ); } } img.setAttribute( "src", data ); _this.handleCallback( callback, img, cfg ); return img; }, /** * Generates a blob instance image; returns base64 datastring */ toBlob: function( options, callback ) { var cfg = _this.deepMerge( { data: "empty", type: "text/plain" }, options || {} ); var data; var isBase64 = /^data:.+;base64,(.*)$/.exec( cfg.data ); // GATHER BODY if ( isBase64 ) { cfg.data = isBase64[ 0 ]; cfg.type = cfg.data.slice( 5, cfg.data.indexOf( "," ) - 7 ); cfg.data = _this.toByteArray( { data: cfg.data.slice( cfg.data.indexOf( "," ) + 1, cfg.data.length ) } ); } if ( cfg.getByteArray ) { data = cfg.data; } else { data = new Blob( [ cfg.data ], { type: cfg.type } ); } // TRIGGER CALLBACK _this.handleCallback( callback, data, cfg ); return data; }, /** * Generates JPG image; returns base64 datastring */ toJPG: function( options, callback ) { var cfg = _this.deepMerge( { format: "jpeg", quality: 1, multiplier: _this.config.multiplier }, options || {} ); cfg.format = cfg.format.toLowerCase(); var data = _this.setup.fabric.toDataURL( cfg ); // TRIGGER CALLBACK _this.handleCallback( callback, data, cfg ); return data; }, /** * Generates PNG image; returns base64 datastring */ toPNG: function( options, callback ) { var cfg = _this.deepMerge( { format: "png", quality: 1, multiplier: _this.config.multiplier }, options || {} ); var data = _this.setup.fabric.toDataURL( cfg ); // TRIGGER CALLBACK _this.handleCallback( callback, data, cfg ); return data; }, /** * Generates SVG image; returns base64 datastring */ toSVG: function( options, callback ) { var clipPaths = []; var cfg = _this.deepMerge( { compress: _this.config.compress, reviver: function( string, clipPath ) { var matcher = new RegExp( /\bstyle=(['"])(.*?)\1/ ); var match = matcher.exec( string )[ 0 ].slice( 7, -1 ); var styles = match.split( ";" ); var replacement = []; // BEAUTIFY STYLES for ( i1 = 0; i1 < styles.length; i1++ ) { if ( styles[ i1 ] ) { var pair = styles[ i1 ].replace( /\s/g, "" ).split( ":" ); var key = pair[ 0 ]; var value = pair[ 1 ]; if ( [ "fill", "stroke" ].indexOf( key ) != -1 ) { value = _this.getRGBA( value, true ); if ( value ) { var color = "#" + value.toHex(); var opacity = value._source[ 3 ]; replacement.push( [ key, color ].join( ":" ) ); replacement.push( [ key + "-opacity", opacity ].join( ":" ) ); } else { replacement.push( styles[ i1 ] ); } } else if ( key != "opactiy" ) { replacement.push( styles[ i1 ] ); } } } string = string.replace( match, replacement.join( ";" ) ); // TODO: WAIT UNTIL FABRICJS HANDLES CLIPPATH FOR SVG OUTPUT if ( clipPath ) { var sliceOffset = 2; var end = string.slice( -sliceOffset ); if ( end != "/>" ) { sliceOffset = 3; end = string.slice( -sliceOffset ); } var start = string.slice( 0, string.length - sliceOffset ); var clipPathAttr = " clip-path=\"url(#" + clipPath.svg.id + ")\" "; var clipPathString = new XMLSerializer().serializeToString( clipPath.svg ); string = start + clipPathAttr + end; clipPaths.push( clipPathString ); } return string; } }, options || {} ); var data = _this.setup.fabric.toSVG( cfg, cfg.reviver ); // TODO: WAIT UNTIL FABRICJS HANDLES CLIPPATH FOR SVG OUTPUT if ( clipPaths.length ) { var start = data.slice( 0, data.length - 6 ); var end = data.slice( -6 ); data = start + clipPaths.join( "" ) + end; } // SOLVES #21840 if ( cfg.compress ) { data = data.replace( /[\t\r\n]+/g, "" ); } if ( cfg.getBase64 ) { data = "data:image/svg+xml;base64," + btoa( data ); } // TRIGGER CALLBACK _this.handleCallback( callback, data, cfg ); return data; }, /** * Generates PDF; returns base64 datastring */ toPDF: function( options, callback ) { var cfg = _this.deepMerge( _this.deepMerge( { multiplier: _this.config.multiplier || 2, pageOrigin: _this.config.pageOrigin === undefined ? true : false }, _this.config.pdfMake ), options || {}, true ); var data = new pdfMake.createPdf( cfg ); // Get image data cfg.images.reference = _this.toPNG( cfg ); // Get page margins; exported from pdfMake function getMargins( margin ) { if ( typeof margin === 'number' || margin instanceof Number ) { margin = { left: margin, right: margin, top: margin, bottom: margin }; } else if ( margin instanceof Array ) { if ( margin.length === 2 ) { margin = { left: margin[ 0 ], top: margin[ 1 ], right: margin[ 0 ], bottom: margin[ 1 ] }; } else if ( margin.length === 4 ) { margin = { left: margin[ 0 ], top: margin[ 1 ], right: margin[ 2 ], bottom: margin[ 3 ] }; } else throw 'Invalid pageMargins definition'; } else { margin = { left: _this.defaults.pdfMake.pageMargins, top: _this.defaults.pdfMake.pageMargins, right: _this.defaults.pdfMake.pageMargins, bottom: _this.defaults.pdfMake.pageMargins }; } return margin; } // Get page dimensions function getSize( pageSize, pageOrientation ) { var pageDimensions = _this.defaults.pdfMake.pageSizes[ String( pageSize ).toUpperCase() ].slice(); if ( !pageDimensions ) { throw new Error( "The given pageSize \"" + pageSize + "\" does not exist!" ); } // Revers in case of landscape if ( pageOrientation == "landscape" ) { pageDimensions.reverse(); } return pageDimensions; } // Polyfill default content if none is given if ( !cfg.content ) { var pageContent = []; var pageDimensions = getSize( cfg.pageSize, cfg.pageOrientation ); var pageMargins = getMargins( cfg.pageMargins ); pageDimensions[ 0 ] -= ( pageMargins.left + pageMargins.right ); pageDimensions[ 1 ] -= ( pageMargins.top + pageMargins.bottom ); if ( cfg.pageOrigin ) { pageContent.push( _this.i18l( "label.saved.from" ) ); pageContent.push( window.location.href ); pageDimensions[ 1 ] -= ( 14.064 * 2 ); } pageContent.push( { image: "reference", fit: pageDimensions } ); cfg.content = pageContent; } if ( callback ) { data.getDataUrl( ( function( callback ) { return function( a ) { callback.apply( _this, arguments ); } } )( callback ) ); } return data; }, /** * Generates an image; hides all elements on page to trigger native print method */ toPRINT: function( options, callback ) { var i1; var cfg = _this.deepMerge( { delay: 1, lossless: false }, options || {} ); var data = _this.toImage( cfg ); var states = []; var items = document.body.childNodes; var scroll = document.documentElement.scrollTop || document.body.scrollTop; data.setAttribute( "style", "width: 100%; max-height: 100%;" ); for ( i1 = 0; i1 < items.length; i1++ ) { if ( _this.isElement( items[ i1 ] ) ) { states[ i1 ] = items[ i1 ].style.display; items[ i1 ].style.display = "none"; } } document.body.appendChild( data ); window.print(); setTimeout( function() { for ( i1 = 0; i1 < items.length; i1++ ) { if ( _this.isElement( items[ i1 ] ) ) { items[ i1 ].style.display = states[ i1 ]; } } document.body.removeChild( data ); document.documentElement.scrollTop = document.body.scrollTop = scroll; // TRIGGER CALLBACK _this.handleCallback( callback, data, cfg ); }, cfg.delay ); return data; }, /** * Generates JSON string */ toJSON: function( options, callback ) { var cfg = _this.deepMerge( { dateFormat: _this.config.dateFormat || "dateObject", }, options || {}, true ); var data = {}; // GATHER DATA cfg.data = cfg.data !== undefined ? cfg.data : _this.getChartData( cfg ); // STRINGIFY DATA data = JSON.stringify( cfg.data, undefined, "\t" ); // TRIGGER CALLBACK _this.handleCallback( callback, data, cfg ); return data; }, /** * Generates CSV string */ toCSV: function( options, callback ) { var row, col; var cfg = _this.deepMerge( { delimiter: ",", quotes: true, escape: true, withHeader: true }, options || {}, true ); var buffer = []; var data = ""; // GATHER DATA buffer = _this.toArray( cfg ); // MERGE for ( row in buffer ) { if ( !isNaN( row ) ) { data += buffer[ row ].join( cfg.delimiter ) + "\n"; } } // TRIGGER CALLBACK _this.handleCallback( callback, data, cfg ); return data; }, /** * Generates excel sheet; returns base64 datastring */ toXLSX: function( options, callback ) { var cfg = _this.deepMerge( { name: "amCharts", dateFormat: _this.config.dateFormat || "dateObject", withHeader: true, stringify: false }, options || {}, true ); var buffer = []; var data = ""; var wb = { SheetNames: [], Sheets: {} } // GATHER DATA buffer = _this.toArray( cfg ); function datenum( v, date1904 ) { if ( date1904 ) v += 1462; var epoch = Date.parse( v ); var offset = v.getTimezoneOffset() * 60 * 1000; return ( epoch - offset - new Date( Date.UTC( 1899, 11, 30 ) ) ) / ( 24 * 60 * 60 * 1000 ); } function sheet_from_array_of_arrays( data, opts ) { var ws = {}; var range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 } }; for ( var R = 0; R != data.length; ++R ) { for ( var C = 0; C != data[ R ].length; ++C ) { if ( range.s.r > R ) range.s.r = R; if ( range.s.c > C ) range.s.c = C; if ( range.e.r < R ) range.e.r = R; if ( range.e.c < C ) range.e.c = C; var cell = { v: data[ R ][ C ] }; if ( cell.v == null ) continue; var cell_ref = XLSX.utils.encode_cell( { c: C, r: R } ); if ( typeof cell.v === "number" ) cell.t = "n"; else if ( typeof cell.v === "boolean" ) cell.t = "b"; else if ( cell.v instanceof Date ) { cell.t = "n"; cell.z = XLSX.SSF._table[ 14 ]; cell.v = datenum( cell.v ); } else cell.t = "s"; ws[ cell_ref ] = cell; } } if ( range.s.c < 10000000 ) ws[ "!ref" ] = XLSX.utils.encode_range( range ); return ws; } wb.SheetNames.push( cfg.name ); wb.Sheets[ cfg.name ] = sheet_from_array_of_arrays( buffer ); data = XLSX.write( wb, { bookType: "xlsx", bookSST: true, type: "base64" } ); data = "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," + data; // TRIGGER CALLBACK _this.handleCallback( callback, data, cfg ); return data; }, /** * Generates an array of arrays */ toArray: function( options, callback ) { var row, col; var cfg = _this.deepMerge( { withHeader: false, stringify: true, escape: false, quotes: false }, options || {}, true ); var data = []; var cols = []; var buffer = []; var _processData = _this.config.processData; // RETRIEVES RIGHT FIELD ORDER OF TRANSLATED FIELDS function processData( data, cfg ) { var fields = cfg.exportFields || Object.keys( cfg.dataFieldsMap ); // WALKTHROUGH FIELDS for ( col = 0; col < fields.length; col++ ) { var key = fields[ col ]; var field = cfg.dataFieldsTitlesMap[ key ]; cols.push( field ); } // TRIGGER GIVEN CALLBACK if ( _processData ) { return _this.handleCallback( _processData, data, cfg ); } return data; } // STRING PROCESSOR function enchant( value ) { if ( typeof value === "string" ) { if ( cfg.escape ) { value = value.replace( '"', '""' ); } if ( cfg.quotes ) { value = [ '"', value, '"' ].join( "" ); } } return value; } // INVOKE PROCESS DATA cfg.processData = processData; // GET DATA cfg.data = cfg.data !== undefined ? cfg.data : _this.getChartData( cfg ); // HEADER if ( cfg.withHeader ) { buffer = []; for ( col in cols ) { if ( !isNaN( col ) ) { buffer.push( enchant( cols[ col ] ) ); } } data.push( buffer ); } // BODY for ( row in cfg.data ) { buffer = []; if ( !isNaN( row ) ) { for ( col in cols ) { if ( !isNaN( col ) ) { var col = cols[ col ]; var value = cfg.data[ row ][ col ]; if ( value == null ) { value = ""; } else if ( cfg.stringify ) { value = String( value ); } else { value = value; } buffer.push( enchant( value ) ); } } data.push( buffer ); } } // TRIGGER CALLBACK _this.handleCallback( callback, data, cfg ); return data; }, /** * Generates byte array with given base64 datastring; returns byte array */ toByteArray: function( options, callback ) { var cfg = _this.deepMerge( { // NUFFIN }, options || {} ); var Arr = ( typeof Uint8Array !== 'undefined' ) ? Uint8Array : Array var PLUS = '+'.charCodeAt( 0 ) var SLASH = '/'.charCodeAt( 0 ) var NUMBER = '0'.charCodeAt( 0 ) var LOWER = 'a'.charCodeAt( 0 ) var UPPER = 'A'.charCodeAt( 0 ) var data = b64ToByteArray( cfg.data ); function decode( elt ) { var code = elt.charCodeAt( 0 ) if ( code === PLUS ) return 62 // '+' if ( code === SLASH ) return 63 // '/' if ( code < NUMBER ) return -1 //no match if ( code < NUMBER + 10 ) return code - NUMBER + 26 + 26 if ( code < UPPER + 26 ) return code - UPPER if ( code < LOWER + 26 ) return code - LOWER + 26 } function b64ToByteArray( b64 ) { var i, j, l, tmp, placeHolders, arr if ( b64.length % 4 > 0 ) { throw new Error( 'Invalid string. Length must be a multiple of 4' ) } // THE NUMBER OF EQUAL SIGNS (PLACE HOLDERS) // IF THERE ARE TWO PLACEHOLDERS, THAN THE TWO CHARACTERS BEFORE IT // REPRESENT ONE BYTE // IF THERE IS ONLY ONE, THEN THE THREE CHARACTERS BEFORE IT REPRESENT 2 BYTES // THIS IS JUST A CHEAP HACK TO NOT DO INDEXOF TWICE var len = b64.length placeHolders = '=' === b64.charAt( len - 2 ) ? 2 : '=' === b64.charAt( len - 1 ) ? 1 : 0 // BASE64 IS 4/3 + UP TO TWO CHARACTERS OF THE ORIGINAL DATA arr = new Arr( b64.length * 3 / 4 - placeHolders ) // IF THERE ARE PLACEHOLDERS, ONLY GET UP TO THE LAST COMPLETE 4 CHARS l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push( v ) { arr[ L++ ] = v } for ( i = 0, j = 0; i < l; i += 4, j += 3 ) { tmp = ( decode( b64.charAt( i ) ) << 18 ) | ( decode( b64.charAt( i + 1 ) ) << 12 ) | ( decode( b64.charAt( i + 2 ) ) << 6 ) | decode( b64.charAt( i + 3 ) ) push( ( tmp & 0xFF0000 ) >> 16 ) push( ( tmp & 0xFF00 ) >> 8 ) push( tmp & 0xFF ) } if ( placeHolders === 2 ) { tmp = ( decode( b64.charAt( i ) ) << 2 ) | ( decode( b64.charAt( i + 1 ) ) >> 4 ) push( tmp & 0xFF ) } else if ( placeHolders === 1 ) { tmp = ( decode( b64.charAt( i ) ) << 10 ) | ( decode( b64.charAt( i + 1 ) ) << 4 ) | ( decode( b64.charAt( i + 2 ) ) >> 2 ) push( ( tmp >> 8 ) & 0xFF ) push( tmp & 0xFF ) } return arr } // TRIGGER CALLBACK _this.handleCallback( callback, data, cfg ); return data; }, /** * Callback handler; injects additional arguments to callback */ handleCallback: function( callback ) { var i1, data = Array(); if ( callback && callback instanceof Function ) { for ( i1 = 0; i1 < arguments.length; i1++ ) { if ( i1 > 0 ) { data.push( arguments[ i1 ] ); } } return callback.apply( _this, data ); } }, /** * Border handler; injects additional border to canvas */ handleBorder: function( options ) { if ( _this.config.border instanceof Object ) { var cfg = _this.deepMerge( _this.defaults.fabric.border, options.border || {}, true ); var border = new fabric.Rect(); cfg.width = _this.setup.fabric.width - cfg.strokeWidth; cfg.height = _this.setup.fabric.height - cfg.strokeWidth; border.set( cfg ); _this.setup.fabric.add( border ); } }, /** * Handles drag/drop events; loads given imagery */ handleDropbox: function( e ) { if ( _this.drawing.enabled ) { e.preventDefault(); e.stopPropagation(); // DRAG OVER if ( e.type == "dragover" ) { _this.setup.wrapper.setAttribute( "class", _this.setup.chart.classNamePrefix + "-export-canvas active dropbox" ); // DRAGLEAVE; DROP } else { _this.setup.wrapper.setAttribute( "class", _this.setup.chart.classNamePrefix + "-export-canvas active" ); if ( e.type == "drop" && e.dataTransfer.files.length ) { for ( var i1 = 0; i1 < e.dataTransfer.files.length; i1++ ) { var reader = new FileReader(); reader.onloadend = ( function( index ) { return function() { _this.drawing.handler.add( { url: reader.result, top: e.layerY - ( index * 10 ), left: e.layerX - ( index * 10 ) } ); } } )( i1 ); reader.readAsDataURL( e.dataTransfer.files[ i1 ] ); } } } } }, /** * Calls ready callback when dependencies are available within window scope */ handleReady: function( callback ) { var t1, t2; var _this = this; var tsStart = Number( new Date() ); // READY FOR DATA EXPORT _this.handleCallback( callback, "data", false ); // READY CALLBACK FOR EACH DEPENDENCY for ( filename in _this.libs.namespaces ) { var namespace = _this.libs.namespaces[ filename ]; ( function( namespace ) { var t1 = setInterval( function() { var tsEnd = Number( new Date() ); if ( tsEnd - tsStart > _this.libs.loadTimeout || namespace in window ) { clearTimeout( t1 ); _this.handleCallback( callback, namespace, tsEnd - tsStart > _this.libs.loadTimeout ); } }, AmCharts.updateRate ) } )( namespace ); } }, /** * Gathers chart data according to its type */ getChartData: function( options ) { var cfg = _this.deepMerge( { data: [], titles: {}, dateFields: [], dataFields: [], dataFieldsMap: {}, exportTitles: _this.config.exportTitles, exportFields: _this.config.exportFields, exportSelection: _this.config.exportSelection, columnNames: _this.config.columnNames }, options || {}, true ); var uid, i1, i2, i3; var lookupFields = [ "valueField", "openField", "closeField", "highField", "lowField", "xField", "yField" ]; var buffer; // HANDLE FIELDS function addField( field, title, type ) { function checkExistance( field, type ) { if ( cfg.dataFields.indexOf( field ) != -1 ) { return checkExistance( [ field, ".", type ].join( "" ) ); } return field; } if ( field && cfg.exportTitles && _this.setup.chart.type != "gantt" ) { uid = checkExistance( field, type ); cfg.dataFieldsMap[ uid ] = field; cfg.dataFields.push( uid ); cfg.titles[ uid ] = title || uid; } } if ( cfg.data.length == 0 ) { // STOCK DATA; GATHER COMPARED GRAPHS if ( _this.setup.chart.type == "stock" ) { cfg.data = _this.cloneObject( _this.setup.chart.mainDataSet.dataProvider ); // CATEGORY AXIS addField( _this.setup.chart.mainDataSet.categoryField ); cfg.dateFields.push( _this.setup.chart.mainDataSet.categoryField ); // WALKTHROUGH GRAPHS for ( i1 = 0; i1 < _this.setup.chart.mainDataSet.fieldMappings.length; i1++ ) { var fieldMap = _this.setup.chart.mainDataSet.fieldMappings[ i1 ]; for ( i2 = 0; i2 < _this.setup.chart.panels.length; i2++ ) { var panel = _this.setup.chart.panels[ i2 ] for ( i3 = 0; i3 < panel.stockGraphs.length; i3++ ) { var graph = panel.stockGraphs[ i3 ]; for ( i4 = 0; i4 < lookupFields.length; i4++ ) { if ( graph[ lookupFields[ i4 ] ] == fieldMap.toField ) { addField( fieldMap.fromField, graph.title, lookupFields[ i4 ] ); } } } } } // MERGE DATA OF COMPARED GRAPHS IN RIGHT PLACE if ( _this.setup.chart.comparedGraphs.length ) { // BUFFER DATES FROM MAIN DATA SET buffer = []; for ( i1 = 0; i1 < cfg.data.length; i1++ ) { buffer.push( cfg.data[ i1 ][ _this.setup.chart.mainDataSet.categoryField ] ); } // WALKTHROUGH COMPARISON AND MERGE IT'S DATA for ( i1 = 0; i1 < _this.setup.chart.comparedGraphs.length; i1++ ) { var graph = _this.setup.chart.comparedGraphs[ i1 ]; for ( i2 = 0; i2 < graph.dataSet.dataProvider.length; i2++ ) { var categoryField = graph.dataSet.categoryField; var categoryValue = graph.dataSet.dataProvider[ i2 ][ categoryField ]; var comparedIndex = buffer.indexOf( categoryValue ); // PLACE IN RIGHT PLACE if ( comparedIndex != -1 ) { for ( i3 = 0; i3 < graph.dataSet.fieldMappings.length; i3++ ) { var fieldMap = graph.dataSet.fieldMappings[ i3 ]; var uid = graph.dataSet.id + "_" + fieldMap.toField; cfg.data[ comparedIndex ][ uid ] = graph.dataSet.dataProvider[ i2 ][ fieldMap.fromField ]; // UNIQUE TITLE if ( !cfg.titles[ uid ] ) { addField( uid, graph.dataSet.title ) } } } } } } // GANTT DATA; FLATTEN SEGMENTS } else if ( _this.setup.chart.type == "gantt" ) { // CATEGORY AXIS addField( _this.setup.chart.categoryField ); cfg.dateFields.push( _this.setup.chart.categoryField ); var field = _this.setup.chart.segmentsField; for ( i1 = 0; i1 < _this.setup.chart.dataProvider.length; i1++ ) { var dataItem = _this.setup.chart.dataProvider[ i1 ]; if ( dataItem[ field ] ) { for ( i2 = 0; i2 < dataItem[ field ].length; i2++ ) { dataItem[ field ][ i2 ][ _this.setup.chart.categoryField ] = dataItem[ _this.setup.chart.categoryField ]; cfg.data.push( dataItem[ field ][ i2 ] ); } } } // GRAPHS for ( i1 = 0; i1 < _this.setup.chart.graphs.length; i1++ ) { var graph = _this.setup.chart.graphs[ i1 ]; for ( i2 = 0; i2 < lookupFields.length; i2++ ) { var dataField = lookupFields[ i2 ]; var graphField = graph[ dataField ]; var title = graph.title; addField( graphField, graph.title, dataField ); } } // PIE/FUNNEL DATA; } else if ( [ "pie", "funnel" ].indexOf( _this.setup.chart.type ) != -1 ) { cfg.data = _this.setup.chart.dataProvider; // CATEGORY AXIS addField( _this.setup.chart.titleField ); cfg.dateFields.push( _this.setup.chart.titleField ); // VALUE addField( _this.setup.chart.valueField ); // DEFAULT DATA; } else if ( _this.setup.chart.type != "map" ) { cfg.data = _this.setup.chart.dataProvider; // CATEGORY AXIS if ( _this.setup.chart.categoryAxis ) { addField( _this.setup.chart.categoryField, _this.setup.chart.categoryAxis.title ); if ( _this.setup.chart.categoryAxis.parseDates !== false ) { cfg.dateFields.push( _this.setup.chart.categoryField ); } } // GRAPHS for ( i1 = 0; i1 < _this.setup.chart.graphs.length; i1++ ) { var graph = _this.setup.chart.graphs[ i1 ]; for ( i2 = 0; i2 < lookupFields.length; i2++ ) { var dataField = lookupFields[ i2 ]; var graphField = graph[ dataField ]; addField( graphField, graph.title, dataField ); } } } } return _this.processData( cfg ); }, /** * Returns embedded annotations in an array */ getAnnotations: function( options, callback ) { var cfg = _this.deepMerge( { // For the future }, options || {}, true ); var i1; var data = []; // Collect annotations for ( i1 = 0; i1 < _this.setup.fabric._objects.length; i1++ ) { // Internal flag to distinguish between annotations and "core" elements if ( !_this.setup.fabric._objects[ i1 ].isCoreElement ) { var obj = _this.setup.fabric._objects[ i1 ].toJSON(); // Revive before adding to allow modifying the object _this.handleCallback( cfg.reviver, obj, i1 ); // Push into output data.push( obj ); } } _this.handleCallback( callback, data ); return data; }, /** * Inserts the given annotations */ setAnnotations: function( options, callback ) { var cfg = _this.deepMerge( { data: [] }, options || {}, true ); // Convert annotations objects into fabric instances fabric.util.enlivenObjects( cfg.data, function( enlivenedObjects ) { enlivenedObjects.forEach( function( obj, i1 ) { // Revive before adding to allow modifying the object _this.handleCallback( cfg.reviver, obj, i1 ); // Add into active instance canvas _this.setup.fabric.add( obj ); } ); _this.handleCallback( callback, cfg ); } ); return cfg.data; }, /** * Walkthrough data to format dates and titles */ processData: function( options ) { var cfg = _this.deepMerge( { data: [], titles: {}, dateFields: [], dataFields: [], dataFieldsMap: {}, dataFieldsTitlesMap: {}, dataDateFormat: _this.setup.chart.dataDateFormat, dateFormat: _this.config.dateFormat || _this.setup.chart.dataDateFormat || "YYYY-MM-DD", exportTitles: _this.config.exportTitles, exportFields: _this.config.exportFields, exportSelection: _this.config.exportSelection, columnNames: _this.config.columnNames, processData: _this.config.processData }, options || {}, true ); var i1, i2; if ( cfg.data.length ) { // GATHER MISSING FIELDS for ( i1 = 0; i1 < cfg.data.length; i1++ ) { for ( i2 in cfg.data[ i1 ] ) { if ( cfg.dataFields.indexOf( i2 ) == -1 ) { cfg.dataFields.push( i2 ); cfg.dataFieldsMap[ i2 ] = i2; } } } // REMOVE FIELDS SELECTIVELY if ( cfg.exportFields !== undefined ) { cfg.dataFields = cfg.exportFields.filter( function( n ) { return cfg.dataFields.indexOf( n ) != -1; } ); } // REBUILD DATA var buffer = []; for ( i1 = 0; i1 < cfg.data.length; i1++ ) { var tmp = {}; var skip = false; for ( i2 = 0; i2 < cfg.dataFields.length; i2++ ) { var uniqueField = cfg.dataFields[ i2 ]; var dataField = cfg.dataFieldsMap[ uniqueField ]; var title = ( cfg.columnNames && cfg.columnNames[ uniqueField ] ) || cfg.titles[ uniqueField ] || uniqueField; var value = cfg.data[ i1 ][ dataField ]; // SKIP NULL ONES if ( value == null ) { value = undefined; } // TITLEFY if ( cfg.exportTitles && _this.setup.chart.type != "gantt" ) { if ( title in tmp ) { title += [ "( ", uniqueField, " )" ].join( "" ); } } // PROCESS CATEGORY if ( cfg.dateFields.indexOf( dataField ) != -1 ) { // CONVERT DATESTRING TO DATE OBJECT if ( cfg.dataDateFormat && ( value instanceof String || typeof value == "string" ) ) { value = AmCharts.stringToDate( value, cfg.dataDateFormat ); // CONVERT TIMESTAMP TO DATE OBJECT } else if ( cfg.dateFormat && ( value instanceof Number || typeof value == "number" ) ) { value = new Date( value ); } // CATEGORY RANGE if ( cfg.exportSelection ) { if ( value instanceof Date ) { if ( value < chart.startDate || value > chart.endDate ) { skip = true; } } else if ( i1 < chart.startIndex || i1 > chart.endIndex ) { skip = true; } } // CATEGORY FORMAT if ( cfg.dateFormat && cfg.dateFormat != "dateObject" && value instanceof Date ) { value = AmCharts.formatDate( value, cfg.dateFormat ); } } cfg.dataFieldsTitlesMap[ dataField ] = title; tmp[ title ] = value; } if ( !skip ) { buffer.push( tmp ); } } cfg.data = buffer; } if ( cfg.processData !== undefined ) { cfg.data = _this.handleCallback( cfg.processData, cfg.data, cfg ); } return cfg.data; }, /** * Prettifies string */ capitalize: function( string ) { return string.charAt( 0 ).toUpperCase() + string.slice( 1 ).toLowerCase(); }, /** * Generates export menu; returns UL node */ createMenu: function( list, container ) { var div; var buffer = []; function buildList( list, container ) { var i1, i2, ul = document.createElement( "ul" ); for ( i1 = 0; i1 < list.length; i1++ ) { var item = typeof list[ i1 ] === "string" ? { format: list[ i1 ] } : list[ i1 ]; var li = document.createElement( "li" ); var a = document.createElement( "a" ); var img = document.createElement( "img" ); var span = document.createElement( "span" ); var action = String( item.action ? item.action : item.format ).toLowerCase(); item.format = String( item.format ).toUpperCase(); // MERGE WITH GIVEN FORMAT if ( _this.config.formats[ item.format ] ) { item = _this.deepMerge( { label: item.icon ? "" : item.format, format: item.format, mimeType: _this.config.formats[ item.format ].mimeType, extension: _this.config.formats[ item.format ].extension, capture: _this.config.formats[ item.format ].capture, action: _this.config.action, fileName: _this.config.fileName }, item ); } else if ( !item.label ) { item.label = item.label ? item.label : _this.i18l( "menu.label." + action ); } // FILTER; TOGGLE FLAG if ( [ "CSV", "JSON", "XLSX" ].indexOf( item.format ) != -1 && [ "map", "gauge" ].indexOf( _this.setup.chart.type ) != -1 ) { continue; // BLOB EXCEPTION } else if ( !_this.setup.hasBlob && item.format != "UNDEFINED" ) { if ( item.mimeType && item.mimeType.split( "/" )[ 0 ] != "image" && item.mimeType != "text/plain" ) { continue; } } // DRAWING if ( item.action == "draw" ) { if ( _this.config.fabric.drawing.enabled ) { item.menu = item.menu ? item.menu : _this.config.fabric.drawing.menu; item.click = ( function( item ) { return function() { this.capture( item, function() { this.createMenu( item.menu ); } ); } } )( item ); } else { item.menu = []; } // DRAWING CHOICES } else if ( !item.populated && item.action && item.action.indexOf( "draw." ) != -1 ) { var type = item.action.split( "." )[ 1 ]; var items = item[ type ] || _this.config.fabric.drawing[ type ] || []; item.menu = []; item.populated = true; for ( i2 = 0; i2 < items.length; i2++ ) { var tmp = { "label": items[ i2 ] } if ( type == "shapes" ) { var io = items[ i2 ].indexOf( "//" ) == -1; var url = ( io ? _this.config.path + "shapes/" : "" ) + items[ i2 ]; tmp.action = "add"; tmp.url = url; tmp.icon = url; tmp.ignore = io; tmp[ "class" ] = "export-drawing-shape"; } else if ( type == "colors" ) { tmp.style = "background-color: " + items[ i2 ]; tmp.action = "change"; tmp.color = items[ i2 ]; tmp[ "class" ] = "export-drawing-color"; } else if ( type == "widths" ) { tmp.action = "change"; tmp.width = items[ i2 ]; tmp.label = document.createElement( "span" ); tmp.label.style.width = _this.numberToPx( items[ i2 ] ); tmp.label.style.height = _this.numberToPx( items[ i2 ] ); tmp[ "class" ] = "export-drawing-width"; } else if ( type == "opacities" ) { tmp.style = "opacity: " + items[ i2 ]; tmp.action = "change"; tmp.opacity = items[ i2 ]; tmp.label = ( items[ i2 ] * 100 ) + "%"; tmp[ "class" ] = "export-drawing-opacity"; } else if ( type == "modes" ) { tmp.label = _this.i18l( "menu.label.draw.modes." + items[ i2 ] ); tmp.click = ( function( mode ) { return function() { _this.drawing.mode = mode; } } )( items[ i2 ] ); tmp[ "class" ] = "export-drawing-mode"; } item.menu.push( tmp ); } // ADD CLICK HANDLER } else if ( !item.click && !item.menu && !item.items ) { // DRAWING METHODS if ( _this.drawing.handler[ action ] instanceof Function ) { item.action = action; item.click = ( function( item ) { return function() { this.drawing.handler[ item.action ]( item ); } } )( item ); // DRAWING } else if ( _this.drawing.enabled ) { item.click = ( function( item ) { return function() { if ( this.config.drawing.autoClose ) { this.drawing.handler.done(); } this[ "to" + item.format ]( item, function( data ) { if ( item.action == "download" ) { this.download( data, item.mimeType, [ item.fileName, item.extension ].join( "." ) ); } } ); } } )( item ); // REGULAR } else if ( item.format != "UNDEFINED" ) { item.click = ( function( item ) { return function() { if ( item.capture || item.action == "print" || item.format == "PRINT" ) { this.capture( item, function() { this.drawing.handler.done(); this[ "to" + item.format ]( item, function( data ) { if ( item.action == "download" ) { this.download( data, item.mimeType, [ item.fileName, item.extension ].join( "." ) ); } } ); } ) } else if ( this[ "to" + item.format ] ) { this[ "to" + item.format ]( item, function( data ) { this.download( data, item.mimeType, [ item.fileName, item.extension ].join( "." ) ); } ); } else { throw new Error( 'Invalid format. Could not determine output type.' ); } } } )( item ); } } // HIDE EMPTY ONES if ( item.menu !== undefined && !item.menu.length ) { continue; } // ADD LINK ATTR a.setAttribute( "href", "#" ); a.addEventListener( "click", ( function( callback, item ) { return function( e ) { e.preventDefault(); var args = [ e, item ]; // DELAYED if ( ( item.action == "draw" || item.format == "PRINT" || ( item.format != "UNDEFINED" && item.capture ) ) && !_this.drawing.enabled ) { item.delay = item.delay ? item.delay : _this.config.delay; if ( item.delay ) { _this.delay( item, callback ); return; } } callback.apply( _this, args ); } } )( item.click || function( e ) { e.preventDefault(); }, item ) ); // ENABLE MANUAL ACTIVE STATE ON TOUCH DEVICES if ( _this.setup.hasTouch && li.classList ) { a.addEventListener( "click", ( function( item ) { return function( e ) { e.preventDefault(); var li = item.elements.li; var parentIsActive = hasActiveParent( li ); var siblingIsActive = hasActiveSibling( li ); var childHasSubmenu = hasSubmenu( li ); // CHECK IF PARENT IS ACTIVE function hasActiveParent( elm ) { var parentNode = elm.parentNode.parentNode; var classList = parentNode.classList; if ( parentNode.tagName == "LI" && classList.contains( "active" ) ) { return true; } return false; } // CHECK IF ANY SIBLING IS ACTIVE function hasActiveSibling( elm ) { var siblings = elm.parentNode.children; for ( i1 = 0; i1 < siblings.length; i1++ ) { var sibling = siblings[ i1 ]; var classList = sibling.classList; if ( sibling !== elm && classList.contains( "active" ) ) { classList.remove( "active" ); return true; } } return false; } // CHECK IF SUBEMNU EXIST function hasSubmenu( elm ) { return elm.getElementsByTagName( "ul" ).length > 0; } // CHECK FOR ROOT ITEMS function isRoot( elm ) { return elm.classList.contains( "export-main" ) || elm.classList.contains( "export-drawing" ); } // TOGGLE MAIN MENU if ( isRoot( li ) || !childHasSubmenu ) { _this.setup.menu.classList.toggle( "active" ); } // UNTOGGLE BUFFERED ITEMS if ( !parentIsActive || !childHasSubmenu ) { while ( buffer.length ) { var tmp = buffer.pop(); var tmpRoot = isRoot( tmp ); var tmpOdd = tmp !== li; if ( tmpRoot ) { if ( !childHasSubmenu ) { tmp.classList.remove( "active" ); } } else if ( tmpOdd ) { tmp.classList.remove( "active" ); } } } // BUFFER ITEMS buffer.push( li ); // TOGGLE CLASS if ( childHasSubmenu ) { li.classList.toggle( "active" ); } } } )( item ) ); } li.appendChild( a ); // ADD LABEL if ( _this.isElement( item.label ) ) { span.appendChild( item.label ); } else { span.innerHTML = item.label; } // APPEND ITEMS if ( item[ "class" ] ) { li.className = item[ "class" ]; } if ( item.style ) { li.setAttribute( "style", item.style ); } if ( item.icon ) { img.setAttribute( "src", ( !item.ignore && item.icon.slice( 0, 10 ).indexOf( "//" ) == -1 ? chart.pathToImages : "" ) + item.icon ); a.appendChild( img ); } if ( item.label ) { a.appendChild( span ); } if ( item.title ) { a.setAttribute( "title", item.title ); } // CALLBACK; REVIVER FOR MENU ITEMS if ( _this.config.menuReviver ) { li = _this.config.menuReviver.apply( _this, [ item, li ] ); } // ADD ELEMENTS FOR EASY ACCESS item.elements = { li: li, a: a, img: img, span: span } // ADD SUBLIST; JUST WITH ENTRIES if ( ( item.menu || item.items ) && item.action != "draw" ) { if ( buildList( item.menu || item.items, li ).childNodes.length ) { ul.appendChild( li ); } } else { ul.appendChild( li ); } } // JUST ADD THOSE WITH ENTRIES if ( ul.childNodes.length ) { container.appendChild( ul ); } return ul; } // DETERMINE CONTAINER if ( !container ) { if ( typeof _this.config.divId == "string" ) { _this.config.divId = container = document.getElementById( _this.config.divId ); } else if ( _this.isElement( _this.config.divId ) ) { container = _this.config.divId; } else { container = _this.setup.chart.containerDiv; } } // CREATE / RESET MENU CONTAINER if ( _this.isElement( _this.setup.menu ) ) { _this.setup.menu.innerHTML = ""; } else { _this.setup.menu = document.createElement( "div" ); } _this.setup.menu.setAttribute( "class", _this.setup.chart.classNamePrefix + "-export-menu " + _this.setup.chart.classNamePrefix + "-export-menu-" + _this.config.position + " amExportButton" ); // CALLBACK; REPLACES THE MENU WALKER if ( _this.config.menuWalker ) { buildList = _this.config.menuWalker; } buildList.apply( this, [ list, _this.setup.menu ] ); // JUST ADD THOSE WITH ENTRIES if ( _this.setup.menu.childNodes.length ) { container.appendChild( _this.setup.menu ); } return _this.setup.menu; }, /** * Method to trigger the callback delayed */ delay: function( options, callback ) { var cfg = _this.deepMerge( { delay: 3, precision: 2 }, options || {} ); var t1, t2, start = Number( new Date() ); var menu = _this.createMenu( [ { label: _this.i18l( "capturing.delayed.menu.label" ).replace( "{{duration}}", AmCharts.toFixed( cfg.delay, cfg.precision ) ), title: _this.i18l( "capturing.delayed.menu.title" ), "class": "export-delayed-capturing", click: function() { clearTimeout( t1 ); clearTimeout( t2 ); _this.createMenu( _this.config.menu ); } } ] ); var label = menu.getElementsByTagName( "a" )[ 0 ]; // MENU UPDATE t1 = setInterval( function() { var diff = cfg.delay - ( Number( new Date() ) - start ) / 1000; if ( diff <= 0 ) { clearTimeout( t1 ); if ( cfg.action != "draw" ) { _this.createMenu( _this.config.menu ); } } else if ( label ) { label.innerHTML = _this.i18l( "capturing.delayed.menu.label" ).replace( "{{duration}}", AmCharts.toFixed( diff, 2 ) ); } }, AmCharts.updateRate ); // CALLBACK t2 = setTimeout( function() { callback.apply( _this, arguments ); }, cfg.delay * 1000 ); }, /** * Migration method to support old export setup */ migrateSetup: function( setup ) { var cfg = { enabled: true, migrated: true, libs: { autoLoad: true }, menu: [] }; function crawler( object ) { var key; for ( key in object ) { var value = object[ key ]; if ( key.slice( 0, 6 ) == "export" && value ) { cfg.menu.push( key.slice( 6 ) ); } else if ( key == "userCFG" ) { crawler( value ); } else if ( key == "menuItems" ) { cfg.menu = value; } else if ( key == "libs" ) { cfg.libs = value; } else if ( typeof key == "string" ) { cfg[ key ] = value; } } } crawler( setup ); return cfg; }, clear: function() { _this.setup = undefined; if ( _this.docListener ) { document.removeEventListener( "keydown", _this.docListener ); } var listenersToRemove = _this.listenersToRemove; if ( listenersToRemove ) { for ( var i = 0; i < listenersToRemove.length; i++ ) { var listenerToRemove = listenersToRemove[ i ]; listenerToRemove.node.removeEventListener( listenerToRemove.event, listenerToRemove.method ) } } _this.listenersToRemove = []; }, /* ** Add event listener */ loadListeners: function() { function handleClone( clone ) { if ( clone ) { clone.set( { top: clone.top + 10, left: clone.left + 10 } ); _this.setup.fabric.add( clone ); } } // OBSERVE; KEY LISTENER; DRAWING FEATURES if ( _this.config.keyListener && _this.config.keyListener != "attached" ) { _this.docListener = function( e ) { var current = _this.drawing.buffer.target; // REMOVE; key: BACKSPACE / DELETE if ( ( e.keyCode == 8 || e.keyCode == 46 ) && current ) { e.preventDefault(); _this.setup.fabric.remove( current ); // ESCAPE DRAWIN MODE; key: escape } else if ( e.keyCode == 27 && _this.drawing.enabled ) { e.preventDefault(); _this.drawing.handler.done(); // COPY; key: C } else if ( e.keyCode == 67 && ( e.metaKey || e.ctrlKey ) && current ) { _this.drawing.buffer.copy = current; // CUT; key: X } else if ( e.keyCode == 88 && ( e.metaKey || e.ctrlKey ) && current ) { _this.drawing.buffer.copy = current; _this.setup.fabric.remove( current ); // PASTE; key: V } else if ( e.keyCode == 86 && ( e.metaKey || e.ctrlKey ) ) { if ( _this.drawing.buffer.copy ) { handleClone( _this.drawing.buffer.copy.clone( handleClone ) ) } // UNDO / REDO; key: Z } else if ( e.keyCode == 90 && ( e.metaKey || e.ctrlKey ) ) { e.preventDefault(); if ( e.shiftKey ) { _this.drawing.handler.redo(); } else { _this.drawing.handler.undo(); } } } _this.config.keyListener = "attached"; document.addEventListener( "keydown", _this.docListener ); } // OBSERVE; DRAG AND DROP LISTENER; DRAWING FEATURE if ( _this.config.fileListener ) { _this.setup.chart.containerDiv.addEventListener( "dragover", _this.handleDropbox ); _this.setup.chart.containerDiv.addEventListener( "dragleave", _this.handleDropbox ); _this.setup.chart.containerDiv.addEventListener( "drop", _this.handleDropbox ); } }, /** * Initiate export menu; waits for chart container to place menu */ init: function() { clearTimeout( _timer ); _timer = setInterval( function() { if ( _this.setup.chart.containerDiv ) { clearTimeout( _timer ); if ( _this.config.enabled ) { // CREATE REFERENCE _this.setup.chart.AmExport = _this; // OVERWRITE PARENT OVERFLOW if ( _this.config.overflow ) { _this.setup.chart.div.style.overflow = "visible"; } // ATTACH EVENTS _this.loadListeners(); // CREATE MENU _this.createMenu( _this.config.menu ); _this.handleReady( _this.config.onReady ); } } }, AmCharts.updateRate ); }, /** * Initiates export instance; merges given config; attaches event listener */ construct: function() { // ANNOTATION; MAP "DONE" _this.drawing.handler.cancel = _this.drawing.handler.done; // CHECK BLOB CONSTRUCTOR try { _this.setup.hasBlob = !!new Blob; } catch ( e ) {} // WORK AROUND TO BYPASS FILESAVER CHECK TRYING TO OPEN THE BLOB URL IN SAFARI BROWSER window.safari = window.safari ? window.safari : {}; // OVERTAKE CHART FONTSIZE IF GIVEN _this.defaults.fabric.drawing.fontSize = _this.setup.chart.fontSize || 11; // MERGE SETTINGS _this.config.drawing = _this.deepMerge( _this.defaults.fabric.drawing, _this.config.drawing || {}, true ); if ( _this.config.border ) { _this.config.border = _this.deepMerge( _this.defaults.fabric.border, _this.config.border || {}, true ); } _this.deepMerge( _this.defaults.fabric, _this.config, true ); _this.deepMerge( _this.defaults.fabric, _this.config.fabric || {}, true ); _this.deepMerge( _this.defaults.pdfMake, _this.config, true ); _this.deepMerge( _this.defaults.pdfMake, _this.config.pdfMake || {}, true ); _this.deepMerge( _this.libs, _this.config.libs || {}, true ); // UPDATE CONFIG _this.config.drawing = _this.defaults.fabric.drawing; _this.config.fabric = _this.defaults.fabric; _this.config.pdfMake = _this.defaults.pdfMake; _this.config = _this.deepMerge( _this.defaults, _this.config, true ); // MERGE; SETUP DRAWING MENU if ( _this.config.fabric.drawing.enabled ) { if ( _this.config.fabric.drawing.menu === undefined ) { _this.config.fabric.drawing.menu = []; _this.deepMerge( _this.config.fabric.drawing.menu, [ { "class": "export-drawing", menu: [ { label: _this.i18l( "menu.label.draw.add" ), menu: [ { label: _this.i18l( "menu.label.draw.shapes" ), action: "draw.shapes" }, { label: _this.i18l( "menu.label.draw.text" ), action: "text" } ] }, { label: _this.i18l( "menu.label.draw.change" ), menu: [ { label: _this.i18l( "menu.label.draw.modes" ), action: "draw.modes" }, { label: _this.i18l( "menu.label.draw.colors" ), action: "draw.colors" }, { label: _this.i18l( "menu.label.draw.widths" ), action: "draw.widths" }, { label: _this.i18l( "menu.label.draw.opacities" ), action: "draw.opacities" }, "UNDO", "REDO" ] }, { label: _this.i18l( "menu.label.save.image" ), menu: [ "PNG", "JPG", "SVG", "PDF" ] }, "PRINT", "CANCEL" ] } ] ); } } // MERGE; SETUP MAIN MENU if ( _this.config.menu === undefined ) { _this.config.menu = []; // PARENT MENU _this.deepMerge( _this.config, { menu: [ { "class": "export-main", menu: [ { label: _this.i18l( "menu.label.save.image" ), menu: [ "PNG", "JPG", "SVG", "PDF" ] }, { label: _this.i18l( "menu.label.save.data" ), menu: [ "CSV", "XLSX", "JSON" ] }, { label: _this.i18l( "menu.label.draw" ), action: "draw", menu: _this.config.fabric.drawing.menu }, { format: "PRINT", label: _this.i18l( "menu.label.print" ) } ] } ] } ); } // ADD MISSING PATH if ( !_this.libs.path ) { _this.libs.path = _this.config.path + "libs/"; } // CHECK ACCEPTANCE if ( _this.isSupported() ) { // LOAD DEPENDENCIES _this.loadDependencies( _this.libs.resources, _this.libs.reload ); // ADD CLASSNAMES _this.setup.chart.addClassNames = true; // REFERENCE _this.setup.chart[ _this.name ] = _this; // INIT MENU; WAIT FOR CHART INSTANCE _this.init(); } } } // USE GIVEN CONFIG if ( config ) { _this.config = config; // USE CHART EXPORT CONFIG } else if ( _this.setup.chart[ _this.name ] ) { _this.config = _this.setup.chart[ _this.name ]; // MIGRATE OLD EXPORT CHART CONFIG } else if ( _this.setup.chart.amExport || _this.setup.chart.exportConfig ) { _this.config = _this.migrateSetup( _this.setup.chart.amExport || _this.setup.chart.exportConfig ); // EXIT; NO CONFIG } else { return; } // CONSTRUCT INSTANCE _this.construct(); // EXPORT SCOPE return _this.deepMerge( this, _this ); } } )(); /** * Set init handler */ AmCharts.addInitHandler( function( chart ) { new AmCharts[ "export" ]( chart ); }, [ "pie", "serial", "xy", "funnel", "radar", "gauge", "stock", "map", "gantt" ] );
var $jscomp={scope:{}};$jscomp.defineProperty="function"==typeof Object.defineProperties?Object.defineProperty:function(a,g,r){if(r.get||r.set)throw new TypeError("ES3 does not support getters and setters.");a!=Array.prototype&&a!=Object.prototype&&(a[g]=r.value)};$jscomp.getGlobal=function(a){return"undefined"!=typeof window&&window===a?a:"undefined"!=typeof global&&null!=global?global:a};$jscomp.global=$jscomp.getGlobal(this);$jscomp.SYMBOL_PREFIX="jscomp_symbol_"; $jscomp.initSymbol=function(){$jscomp.initSymbol=function(){};$jscomp.global.Symbol||($jscomp.global.Symbol=$jscomp.Symbol)};$jscomp.symbolCounter_=0;$jscomp.Symbol=function(a){return $jscomp.SYMBOL_PREFIX+(a||"")+$jscomp.symbolCounter_++}; $jscomp.initSymbolIterator=function(){$jscomp.initSymbol();var a=$jscomp.global.Symbol.iterator;a||(a=$jscomp.global.Symbol.iterator=$jscomp.global.Symbol("iterator"));"function"!=typeof Array.prototype[a]&&$jscomp.defineProperty(Array.prototype,a,{configurable:!0,writable:!0,value:function(){return $jscomp.arrayIterator(this)}});$jscomp.initSymbolIterator=function(){}};$jscomp.arrayIterator=function(a){var g=0;return $jscomp.iteratorPrototype(function(){return g<a.length?{done:!1,value:a[g++]}:{done:!0}})}; $jscomp.iteratorPrototype=function(a){$jscomp.initSymbolIterator();a={next:a};a[$jscomp.global.Symbol.iterator]=function(){return this};return a};$jscomp.array=$jscomp.array||{};$jscomp.iteratorFromArray=function(a,g){$jscomp.initSymbolIterator();a instanceof String&&(a+="");var r=0,e={next:function(){if(r<a.length){var u=r++;return{value:g(u,a[u]),done:!1}}e.next=function(){return{done:!0,value:void 0}};return e.next()}};e[Symbol.iterator]=function(){return e};return e}; $jscomp.polyfill=function(a,g,r,e){if(g){r=$jscomp.global;a=a.split(".");for(e=0;e<a.length-1;e++){var u=a[e];u in r||(r[u]={});r=r[u]}a=a[a.length-1];e=r[a];g=g(e);g!=e&&null!=g&&$jscomp.defineProperty(r,a,{configurable:!0,writable:!0,value:g})}};$jscomp.polyfill("Array.prototype.keys",function(a){return a?a:function(){return $jscomp.iteratorFromArray(this,function(a){return a})}},"es6-impl","es3"); $jscomp.findInternal=function(a,g,r){a instanceof String&&(a=String(a));for(var e=a.length,u=0;u<e;u++){var D=a[u];if(g.call(r,D,u,a))return{i:u,v:D}}return{i:-1,v:void 0}};$jscomp.polyfill("Array.prototype.find",function(a){return a?a:function(a,r){return $jscomp.findInternal(this,a,r).v}},"es6-impl","es3"); (function(a){"function"===typeof define&&define.amd?define(["jquery","./grid.base","./jquery.fmatter","./grid.common"],a):"object"===typeof exports?a(require("jquery")):a(jQuery)})(function(a){var g=a.jgrid,r=g.fullBoolFeedback,e=g.hasOneFromClasses,u=a.fn.jqGrid,D=function(a){return u.getGuiStyles.call(this,"states."+a)},H=function(d){var f=a.makeArray(arguments).slice(1);f.unshift("");f.unshift("Inline");f.unshift(d);return g.feedback.apply(this,f)};g.inlineEdit=g.inlineEdit||{};g.extend({editRow:function(d, f,p,l,c,v,e,B,m,b){var h={},n=a.makeArray(arguments).slice(1);"object"===a.type(n[0])?h=n[0]:(void 0!==f&&(h.keys=f),a.isFunction(p)&&(h.oneditfunc=p),a.isFunction(l)&&(h.successfunc=l),void 0!==c&&(h.url=c),null!=v&&(h.extraparam=v),a.isFunction(e)&&(h.aftersavefunc=e),a.isFunction(B)&&(h.errorfunc=B),a.isFunction(m)&&(h.afterrestorefunc=m),a.isFunction(b)&&(h.beforeEditRow=b));return this.each(function(){var b=this,c=a(b),l=b.p,v=0,f=null,p={},m=l.colModel,e=l.prmNames;if(b.grid){var x=a.extend(!0, {keys:!1,oneditfunc:null,successfunc:null,url:null,extraparam:{},aftersavefunc:null,errorfunc:null,afterrestorefunc:null,restoreAfterError:!0,beforeEditRow:null,mtype:"POST",focusField:!0},g.inlineEdit,l.inlineEditing||{},h),q=c.jqGrid("getInd",d,!0),n=x.focusField,B="object"===typeof n&&null!=n?a(n.target||n).closest("tr.jqgrow>td")[0]:null;if(!1!==q&&(x.extraparam[e.oper]===e.addoper||H.call(b,x,"beforeEditRow",x,d))&&"0"===(a(q).attr("editable")||"0")&&!a(q).hasClass("not-editable-row")){e=g.detectRowEditing.call(b, d);if(null!=e&&"cellEditing"===e.mode){var e=e.savedRow,F=b.rows[e.id],u=D.call(b,"select");c.jqGrid("restoreCell",e.id,e.ic);a(F.cells[e.ic]).removeClass("edit-cell "+u);a(F).addClass(u).attr({"aria-selected":"true",tabindex:"0"})}g.enumEditableCells.call(b,q,a(q).hasClass("jqgrid-new-row")?"add":"edit",function(c){var k=c.cm,h=a(c.dataElement),e=c.dataWidth,w,m=k.name,n=k.edittype,q=c.iCol,t=k.editoptions||{};if("hidden"!==c.editable){try{w=a.unformat.call(this,c.td,{rowId:d,colModel:k},q)}catch(P){w= "textarea"===n?h.text():h.html()}p[m]=w;h.html("");k=a.extend({},t,{id:d+"_"+m,name:m,rowId:d,mode:c.mode,cm:k,iCol:q});if("&nbsp;"===w||"&#160;"===w||1===w.length&&160===w.charCodeAt(0))w="";w=g.createEl.call(b,n,k,w,!0,a.extend({},g.ajaxOptions,l.ajaxSelectOptions||{}));a(w).addClass("editable");h.append(w);e&&a(w).width(c.dataWidth);g.bindEv.call(b,w,k);"select"===n&&!0===t.multiple&&void 0===t.dataUrl&&g.msie&&a(w).width(a(w).width());null===f&&(f=q);v++}});0<v&&(p.id=d,l.savedRow.push(p),a(q).attr("editable", "1"),n&&("number"===typeof n&&parseInt(n,10)<=m.length?f=n:"string"===typeof n?f=l.iColByName[n]:null!=B&&(f=B.cellIndex),setTimeout(function(){var d=c.jqGrid("getNumberOfFrozenColumns"),k=function(a){return l.frozenColumns&&0<d&&f<d?b.grid.fbRows[q.rowIndex].cells[a]:q.cells[a]},g=function(b){return a(b).find("input,textarea,select,button,object,*[tabindex]").filter(":input:visible:not(:disabled)")},h=function(){return g(l.frozenColumns&&0<d?b.grid.fbRows[q.rowIndex]:q).first()},w=g(k(f));0<w.length? w.first().focus():"number"===typeof x.defaultFocusField||"string"===typeof x.defaultFocusField?(w=g(k("number"===typeof x.defaultFocusField?x.defaultFocusField:l.iColByName[x.defaultFocusField])),0===w.length&&(w=h()),w.first().focus()):h().focus()},0)),!0===x.keys&&(m=a(q),l.frozenColumns&&(m=m.add(b.grid.fbRows[q.rowIndex])),m.on("keydown",function(a){if(27===a.keyCode)return c.jqGrid("restoreRow",d,x.afterrestorefunc),!1;if(13===a.keyCode){if("TEXTAREA"===a.target.tagName)return!0;c.jqGrid("saveRow", d,x);return!1}})),r.call(b,x.oneditfunc,"jqGridInlineEditRow",d,x))}}})},saveRow:function(d,f,e,l,c,v,F,B){var m=a.makeArray(arguments).slice(1),b={},h=this[0],n=a(h),k=null!=h?h.p:null,p,u=g.info_dialog,z=a.isFunction,K=null!=g.defaults&&z(g.defaults.fatalError)?g.defaults.fatalError:alert;if(h.grid&&null!=k){"object"===a.type(m[0])?b=m[0]:(z(f)&&(b.successfunc=f),void 0!==e&&(b.url=e),void 0!==l&&(b.extraparam=l),z(c)&&(b.aftersavefunc=c),z(v)&&(b.errorfunc=v),z(F)&&(b.afterrestorefunc=F),z(B)&& (b.beforeSaveRow=B));var m=function(a){return n.jqGrid("getGridRes",a)},b=a.extend(!0,{successfunc:null,url:null,extraparam:{},aftersavefunc:null,errorfunc:null,afterrestorefunc:null,restoreAfterError:!0,beforeSaveRow:null,ajaxSaveOptions:{},serializeSaveData:null,mtype:"POST",saveui:"enable",savetext:m("defaults.savetext")||"Saving..."},g.inlineEdit,k.inlineEditing||{},b),t={},I={},A={},x,q,G,y=n.jqGrid("getInd",d,!0),C=a(y),E=k.prmNames,L=m("errors.errcap"),M=m("edit.bClose"),J,N;if(!1!==y&&(p= b.extraparam[E.oper]===E.addoper?"add":"edit",H.call(h,b,"beforeSaveRow",b,d,p)&&(m=C.attr("editable"),b.url=b.url||k.editurl,J="clientArray"!==b.url,"1"===m&&(g.enumEditableCells.call(h,y,C.hasClass("jqgrid-new-row")?"add":"edit",function(b){var c=b.cm,k=c.formatter,l=c.editoptions||{},w=c.formatoptions||{},p={},e=(a.jgrid.detectRowEditing.call(h,d)||{}).savedRow,f=g.getEditedValue.call(h,a(b.dataElement),c,p,b.editable);"select"===c.edittype&&"select"!==c.formatter&&(I[c.name]=p.text);G=g.checkValues.call(h, f,b.iCol,void 0,void 0,a.extend(b,{oldValue:null!=e?e[c.name]:null,newValue:f,oldRowData:e}));if(null!=G&&!1===G[0]){N=!0;try{var m=g.getRelativeRect.call(h,b.td);u.call(h,L,G[1],M,{top:m.top,left:m.left+a(h).closest(".ui-jqgrid").offset().left})}catch(Q){K(G[1])}return!1}"date"===k&&!0!==w.sendFormatted&&(f=a.unformat.date.call(h,f,c));J&&!0===l.NullIfEmpty&&""===f&&(f="null");t[c.name]=f}),!N))))if(m=d,E=k.prmNames,q=!1===k.keyName?E.id:k.keyName,t&&(t[E.oper]=E.editoper,void 0===t[q]||""===t[q]? t[q]=d:y.id!==k.idPrefix+t[q]&&(y=g.stripPref(k.idPrefix,d),void 0!==k._index[y]&&(k._index[t[q]]=k._index[y],delete k._index[y]),d=k.idPrefix+t[q],C.attr("id",d),k.selrow===m&&(k.selrow=d),a.isArray(k.selarrrow)&&(y=a.inArray(m,k.selarrrow),0<=y&&(k.selarrrow[y]=d)),k.multiselect&&(y="jqg_"+k.id+"_"+d,C.find("input.cbox").attr("id",y).attr("name",y))),t=a.extend({},t,k.inlineData||{},b.extraparam)),J)n.jqGrid("progressBar",{method:"show",loadtype:b.saveui,htmlcontent:b.savetext}),A=a.extend({},t, A),A[q]=g.stripPref(k.idPrefix,A[q]),k.autoEncodeOnEdit&&a.each(A,function(a,b){z(b)||(A[a]=g.oldEncodePostedData(b))}),a.ajax(a.extend({url:z(b.url)?b.url.call(h,A[q],p,A,b):b.url,data:g.serializeFeedback.call(h,z(b.serializeSaveData)?b.serializeSaveData:k.serializeRowData,"jqGridInlineSerializeSaveData",A),type:z(b.mtype)?b.mtype.call(h,p,b,A[q],A):b.mtype,complete:function(c,l){n.jqGrid("progressBar",{method:"hide",loadtype:b.saveui});if((300>c.status||304===c.status)&&(0!==c.status||4!==c.readyState)){var f, e;e=n.triggerHandler("jqGridInlineSuccessSaveRow",[c,d,b]);if(null==e||!0===e)e=[!0,t];e[0]&&z(b.successfunc)&&(e=b.successfunc.call(h,c));a.isArray(e)?(f=e[0],t=e[1]||t):f=e;if(!0===f){k.autoEncodeOnEdit&&a.each(t,function(a,b){t[a]=g.oldDecodePostedData(b)});t=a.extend({},t,I);n.jqGrid("setRowData",d,t);C.attr("editable","0");for(f=0;f<k.savedRow.length;f++)if(String(k.savedRow[f].id)===String(d)){x=f;break}0<=x&&k.savedRow.splice(x,1);r.call(h,b.aftersavefunc,"jqGridInlineAfterSaveRow",d,c,t,b); C.removeClass("jqgrid-new-row").off("keydown")}else r.call(h,b.errorfunc,"jqGridInlineErrorSaveRow",d,c,l,null,b),!0===b.restoreAfterError&&n.jqGrid("restoreRow",d,b.afterrestorefunc)}},error:function(a,c,k){n.triggerHandler("jqGridInlineErrorSaveRow",[d,a,c,k,b]);if(z(b.errorfunc))b.errorfunc.call(h,d,a,c,k);else{a=a.responseText||a.statusText;try{u.call(h,L,'<div class="'+D.call(h,"error")+'">'+a+"</div>",M,{buttonalign:"right"})}catch(O){K(a)}}!0===b.restoreAfterError&&n.jqGrid("restoreRow",d, b.afterrestorefunc)}},g.ajaxOptions,k.ajaxRowOptions,b.ajaxSaveOptions||{}));else{t=a.extend({},t,I);q=n.jqGrid("setRowData",d,t);C.attr("editable","0");for(p=0;p<k.savedRow.length;p++)if(String(k.savedRow[p].id)===String(m)){x=p;break}0<=x&&k.savedRow.splice(x,1);r.call(h,b.aftersavefunc,"jqGridInlineAfterSaveRow",d,q,t,b);C.removeClass("jqgrid-new-row").off("keydown")}}},restoreRow:function(d,f){var e=a.makeArray(arguments).slice(1),l={};"object"===a.type(e[0])?l=e[0]:a.isFunction(f)&&(l.afterrestorefunc= f);return this.each(function(){var c=this,e=a(c),f=c.p,p=-1,m={},b;if(c.grid){var h=a.extend(!0,{},g.inlineEdit,f.inlineEditing||{},l),n=e.jqGrid("getInd",d,!0);if(!1!==n&&H.call(c,h,"beforeCancelRow",h,d)){for(b=0;b<f.savedRow.length;b++)if(String(f.savedRow[b].id)===String(d)){p=b;break}if(0<=p){if(a.isFunction(a.fn.datepicker))try{a("input.hasDatepicker","#"+g.jqID(n.id)).datepicker("hide")}catch(k){}a.each(f.colModel,function(){var b=this.name;f.savedRow[p].hasOwnProperty(b)&&(m[b]=f.savedRow[p][b], !this.formatter||"date"!==this.formatter||null!=this.formatoptions&&!0===this.formatoptions.sendFormatted||(m[b]=a.unformat.date.call(c,m[b],this)))});e.jqGrid("setRowData",d,m);a(n).attr("editable","0").off("keydown");f.savedRow.splice(p,1);a("#"+g.jqID(d),c).hasClass("jqgrid-new-row")&&setTimeout(function(){e.jqGrid("delRowData",d);e.jqGrid("showAddEditButtons",!1)},0)}r.call(c,h.afterrestorefunc,"jqGridInlineAfterRestoreRow",d)}}})},addRow:function(d){return this.each(function(){if(this.grid){var f= this,e=a(f),l=f.p,c=a.extend(!0,{rowID:null,initdata:{},position:"first",useDefValues:!0,useFormatter:!1,beforeAddRow:null,addRowParams:{extraparam:{}}},g.inlineEdit,l.inlineEditing||{},d||{});H.call(f,c,"beforeAddRow",c.addRowParams)&&(c.rowID=a.isFunction(c.rowID)?c.rowID.call(f,c):null!=c.rowID?c.rowID:g.randId(),!0===c.useDefValues&&a(l.colModel).each(function(){if(this.editoptions&&this.editoptions.defaultValue){var d=this.editoptions.defaultValue;c.initdata[this.name]=a.isFunction(d)?d.call(f): d}}),c.rowID=l.idPrefix+c.rowID,e.jqGrid("addRowData",c.rowID,c.initdata,c.position),a("#"+g.jqID(c.rowID),f).addClass("jqgrid-new-row"),c.useFormatter?a("#"+g.jqID(c.rowID)+" .ui-inline-edit",f).click():(l=l.prmNames,c.addRowParams.extraparam[l.oper]=l.addoper,e.jqGrid("editRow",c.rowID,c.addRowParams),e.jqGrid("setSelection",c.rowID)))}})},inlineNav:function(d,f){"object"===typeof d&&(f=d,d=void 0);return this.each(function(){var p=this,l=a(p),c=p.p;if(this.grid&&null!=c){var v,r=d===c.toppager? c.idSel+"_top":c.idSel,u=d===c.toppager?c.id+"_top":c.id,m=D.call(p,"disabled"),b=a.extend(!0,{edit:!0,editicon:"ui-icon-pencil",add:!0,addicon:"ui-icon-plus",save:!0,saveicon:"ui-icon-disk",cancel:!0,cancelicon:"ui-icon-cancel",commonIconClass:"ui-icon",iconsOverText:!1,addParams:{addRowParams:{extraparam:{}}},editParams:{},restoreAfterSelect:!0},l.jqGrid("getGridRes","nav"),g.nav||{},c.navOptions||{},g.inlineNav||{},c.inlineNavOptions||{},f||{});if(void 0===d)if(c.pager)if(l.jqGrid("inlineNav", c.pager,b),c.toppager)d=c.toppager,r=c.idSel+"_top",u=c.id+"_top";else return;else c.toppager&&(d=c.toppager,r=c.idSel+"_top",u=c.id+"_top");if(void 0!==d&&(v=a(d),!(0>=v.length))){0>=v.find(".navtable").length&&l.jqGrid("navGrid",d,{add:!1,edit:!1,del:!1,search:!1,refresh:!1,view:!1});c._inlinenav=!0;if(!0===b.addParams.useFormatter){v=c.colModel;var h,n;for(h=0;h<v.length;h++)if(v[h].formatter&&"actions"===v[h].formatter){v[h].formatoptions&&(n={keys:!1,onEdit:null,onSuccess:null,afterSave:null, onError:null,afterRestore:null,extraparam:{},url:null},v=a.extend(n,v[h].formatoptions),b.addParams.addRowParams={keys:v.keys,oneditfunc:v.onEdit,successfunc:v.onSuccess,url:v.url,extraparam:v.extraparam,aftersavefunc:v.afterSave,errorfunc:v.onError,afterrestorefunc:v.afterRestore});break}}b.add&&l.jqGrid("navButtonAdd",d,{caption:b.addtext,title:b.addtitle,commonIconClass:b.commonIconClass,buttonicon:b.addicon,iconsOverText:b.iconsOverText,id:u+"_iladd",onClickButton:function(){e(this,m)||l.jqGrid("addRow", b.addParams)}});b.edit&&l.jqGrid("navButtonAdd",d,{caption:b.edittext,title:b.edittitle,commonIconClass:b.commonIconClass,buttonicon:b.editicon,iconsOverText:b.iconsOverText,id:u+"_iledit",onClickButton:function(){if(!e(this,m)){var a=c.selrow;a?l.jqGrid("editRow",a,b.editParams):p.modalAlert()}}});b.save&&(l.jqGrid("navButtonAdd",d,{caption:b.savetext,title:b.savetitle,commonIconClass:b.commonIconClass,buttonicon:b.saveicon,iconsOverText:b.iconsOverText,id:u+"_ilsave",onClickButton:function(){if(!e(this, m)){var d=c.savedRow[0].id;if(d){var f=c.prmNames,h=f.oper,n=b.editParams;a("#"+g.jqID(d),p).hasClass("jqgrid-new-row")?(b.addParams.addRowParams.extraparam[h]=f.addoper,n=b.addParams.addRowParams):(b.editParams.extraparam||(b.editParams.extraparam={}),b.editParams.extraparam[h]=f.editoper);l.jqGrid("saveRow",d,n)}else p.modalAlert()}}}),a(r+"_ilsave").addClass(m));b.cancel&&(l.jqGrid("navButtonAdd",d,{caption:b.canceltext,title:b.canceltitle,commonIconClass:b.commonIconClass,buttonicon:b.cancelicon, iconsOverText:b.iconsOverText,id:u+"_ilcancel",onClickButton:function(){if(!e(this,m)){var d=c.savedRow[0].id,f=b.editParams;d?(a("#"+g.jqID(d),p).hasClass("jqgrid-new-row")&&(f=b.addParams.addRowParams),l.jqGrid("restoreRow",d,f)):p.modalAlert()}}}),a(r+"_ilcancel").addClass(m));if(!0===b.restoreAfterSelect)l.on("jqGridSelectRow",function(a,d){if(0<c.savedRow.length&&!0===c._inlinenav){var f=c.savedRow[0].id;d!==f&&"number"!==typeof f&&l.jqGrid("restoreRow",f,b.editParams)}});l.on("jqGridInlineAfterRestoreRow jqGridInlineAfterSaveRow", function(){l.jqGrid("showAddEditButtons",!1)});l.on("jqGridInlineEditRow",function(a,b){l.jqGrid("showAddEditButtons",!0,b)})}}})},showAddEditButtons:function(d){return this.each(function(){if(this.grid){var f=this.p,e=f.idSel,g=D.call(this,"disabled"),c=e+"_ilsave,"+e+"_ilcancel"+(f.toppager?","+e+"_top_ilsave,"+e+"_top_ilcancel":""),f=e+"_iladd,"+e+"_iledit"+(f.toppager?","+e+"_top_iladd,"+e+"_top_iledit":"");a(d?f:c).addClass(g);a(d?c:f).removeClass(g)}})}})}); //# sourceMappingURL=grid.inlinedit.map
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var async_1 = require('../src/facade/async'); var collection_1 = require('../src/facade/collection'); var lang_1 = require('../src/facade/lang'); /** * `RouteParams` is an immutable map of parameters for the given route * based on the url matcher and optional parameters for that route. * * You can inject `RouteParams` into the constructor of a component to use it. * * ### Example * * ``` * import {Component} from '@angular/core'; * import {bootstrap} from '@angular/platform-browser/browser'; * import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig, RouteParams} from * 'angular2/router'; * * @Component({directives: [ROUTER_DIRECTIVES]}) * @RouteConfig([ * {path: '/user/:id', component: UserCmp, name: 'UserCmp'}, * ]) * class AppCmp {} * * @Component({ template: 'user: {{id}}' }) * class UserCmp { * id: string; * constructor(params: RouteParams) { * this.id = params.get('id'); * } * } * * bootstrap(AppCmp, ROUTER_PROVIDERS); * ``` */ var RouteParams = (function () { function RouteParams(params) { this.params = params; } RouteParams.prototype.get = function (param) { return lang_1.normalizeBlank(collection_1.StringMapWrapper.get(this.params, param)); }; return RouteParams; }()); exports.RouteParams = RouteParams; /** * `RouteData` is an immutable map of additional data you can configure in your {@link Route}. * * You can inject `RouteData` into the constructor of a component to use it. * * ### Example * * ``` * import {Component} from '@angular/core'; * import {bootstrap} from '@angular/platform-browser/browser'; * import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig, RouteData} from * 'angular2/router'; * * @Component({directives: [ROUTER_DIRECTIVES]}) * @RouteConfig([ * {path: '/user/:id', component: UserCmp, name: 'UserCmp', data: {isAdmin: true}}, * ]) * class AppCmp {} * * @Component({ * ..., * template: 'user: {{isAdmin}}' * }) * class UserCmp { * string: isAdmin; * constructor(data: RouteData) { * this.isAdmin = data.get('isAdmin'); * } * } * * bootstrap(AppCmp, ROUTER_PROVIDERS); * ``` */ var RouteData = (function () { function RouteData(data) { if (data === void 0) { data = {}; } this.data = data; } RouteData.prototype.get = function (key) { return lang_1.normalizeBlank(collection_1.StringMapWrapper.get(this.data, key)); }; return RouteData; }()); exports.RouteData = RouteData; exports.BLANK_ROUTE_DATA = new RouteData(); /** * `Instruction` is a tree of {@link ComponentInstruction}s with all the information needed * to transition each component in the app to a given route, including all auxiliary routes. * * `Instruction`s can be created using {@link Router#generate}, and can be used to * perform route changes with {@link Router#navigateByInstruction}. * * ### Example * * ``` * import {Component} from '@angular/core'; * import {bootstrap} from '@angular/platform-browser/browser'; * import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig} from * '@angular/router-deprecated'; * * @Component({directives: [ROUTER_DIRECTIVES]}) * @RouteConfig([ * {...}, * ]) * class AppCmp { * constructor(router: Router) { * var instruction = router.generate(['/MyRoute']); * router.navigateByInstruction(instruction); * } * } * * bootstrap(AppCmp, ROUTER_PROVIDERS); * ``` */ var Instruction = (function () { function Instruction(component, child, auxInstruction) { this.component = component; this.child = child; this.auxInstruction = auxInstruction; } Object.defineProperty(Instruction.prototype, "urlPath", { get: function () { return lang_1.isPresent(this.component) ? this.component.urlPath : ''; }, enumerable: true, configurable: true }); Object.defineProperty(Instruction.prototype, "urlParams", { get: function () { return lang_1.isPresent(this.component) ? this.component.urlParams : []; }, enumerable: true, configurable: true }); Object.defineProperty(Instruction.prototype, "specificity", { get: function () { var total = ''; if (lang_1.isPresent(this.component)) { total += this.component.specificity; } if (lang_1.isPresent(this.child)) { total += this.child.specificity; } return total; }, enumerable: true, configurable: true }); /** * converts the instruction into a URL string */ Instruction.prototype.toRootUrl = function () { return this.toUrlPath() + this.toUrlQuery(); }; /** @internal */ Instruction.prototype._toNonRootUrl = function () { return this._stringifyPathMatrixAuxPrefixed() + (lang_1.isPresent(this.child) ? this.child._toNonRootUrl() : ''); }; Instruction.prototype.toUrlQuery = function () { return this.urlParams.length > 0 ? ('?' + this.urlParams.join('&')) : ''; }; /** * Returns a new instruction that shares the state of the existing instruction, but with * the given child {@link Instruction} replacing the existing child. */ Instruction.prototype.replaceChild = function (child) { return new ResolvedInstruction(this.component, child, this.auxInstruction); }; /** * If the final URL for the instruction is `` */ Instruction.prototype.toUrlPath = function () { return this.urlPath + this._stringifyAux() + (lang_1.isPresent(this.child) ? this.child._toNonRootUrl() : ''); }; // default instructions override these Instruction.prototype.toLinkUrl = function () { return this.urlPath + this._stringifyAux() + (lang_1.isPresent(this.child) ? this.child._toLinkUrl() : '') + this.toUrlQuery(); }; // this is the non-root version (called recursively) /** @internal */ Instruction.prototype._toLinkUrl = function () { return this._stringifyPathMatrixAuxPrefixed() + (lang_1.isPresent(this.child) ? this.child._toLinkUrl() : ''); }; /** @internal */ Instruction.prototype._stringifyPathMatrixAuxPrefixed = function () { var primary = this._stringifyPathMatrixAux(); if (primary.length > 0) { primary = '/' + primary; } return primary; }; /** @internal */ Instruction.prototype._stringifyMatrixParams = function () { return this.urlParams.length > 0 ? (';' + this.urlParams.join(';')) : ''; }; /** @internal */ Instruction.prototype._stringifyPathMatrixAux = function () { if (lang_1.isBlank(this.component) && lang_1.isBlank(this.urlPath)) { return ''; } return this.urlPath + this._stringifyMatrixParams() + this._stringifyAux(); }; /** @internal */ Instruction.prototype._stringifyAux = function () { var routes = []; collection_1.StringMapWrapper.forEach(this.auxInstruction, function (auxInstruction, _) { routes.push(auxInstruction._stringifyPathMatrixAux()); }); if (routes.length > 0) { return '(' + routes.join('//') + ')'; } return ''; }; return Instruction; }()); exports.Instruction = Instruction; /** * a resolved instruction has an outlet instruction for itself, but maybe not for... */ var ResolvedInstruction = (function (_super) { __extends(ResolvedInstruction, _super); function ResolvedInstruction(component, child, auxInstruction) { _super.call(this, component, child, auxInstruction); } ResolvedInstruction.prototype.resolveComponent = function () { return async_1.PromiseWrapper.resolve(this.component); }; return ResolvedInstruction; }(Instruction)); exports.ResolvedInstruction = ResolvedInstruction; /** * Represents a resolved default route */ var DefaultInstruction = (function (_super) { __extends(DefaultInstruction, _super); function DefaultInstruction(component, child) { _super.call(this, component, child, {}); } DefaultInstruction.prototype.toLinkUrl = function () { return ''; }; /** @internal */ DefaultInstruction.prototype._toLinkUrl = function () { return ''; }; return DefaultInstruction; }(ResolvedInstruction)); exports.DefaultInstruction = DefaultInstruction; /** * Represents a component that may need to do some redirection or lazy loading at a later time. */ var UnresolvedInstruction = (function (_super) { __extends(UnresolvedInstruction, _super); function UnresolvedInstruction(_resolver, _urlPath, _urlParams) { if (_urlPath === void 0) { _urlPath = ''; } if (_urlParams === void 0) { _urlParams = []; } _super.call(this, null, null, {}); this._resolver = _resolver; this._urlPath = _urlPath; this._urlParams = _urlParams; } Object.defineProperty(UnresolvedInstruction.prototype, "urlPath", { get: function () { if (lang_1.isPresent(this.component)) { return this.component.urlPath; } if (lang_1.isPresent(this._urlPath)) { return this._urlPath; } return ''; }, enumerable: true, configurable: true }); Object.defineProperty(UnresolvedInstruction.prototype, "urlParams", { get: function () { if (lang_1.isPresent(this.component)) { return this.component.urlParams; } if (lang_1.isPresent(this._urlParams)) { return this._urlParams; } return []; }, enumerable: true, configurable: true }); UnresolvedInstruction.prototype.resolveComponent = function () { var _this = this; if (lang_1.isPresent(this.component)) { return async_1.PromiseWrapper.resolve(this.component); } return this._resolver().then(function (instruction) { _this.child = lang_1.isPresent(instruction) ? instruction.child : null; return _this.component = lang_1.isPresent(instruction) ? instruction.component : null; }); }; return UnresolvedInstruction; }(Instruction)); exports.UnresolvedInstruction = UnresolvedInstruction; var RedirectInstruction = (function (_super) { __extends(RedirectInstruction, _super); function RedirectInstruction(component, child, auxInstruction, _specificity) { _super.call(this, component, child, auxInstruction); this._specificity = _specificity; } Object.defineProperty(RedirectInstruction.prototype, "specificity", { get: function () { return this._specificity; }, enumerable: true, configurable: true }); return RedirectInstruction; }(ResolvedInstruction)); exports.RedirectInstruction = RedirectInstruction; /** * A `ComponentInstruction` represents the route state for a single component. * * `ComponentInstructions` is a public API. Instances of `ComponentInstruction` are passed * to route lifecycle hooks, like {@link CanActivate}. * * `ComponentInstruction`s are [hash consed](https://en.wikipedia.org/wiki/Hash_consing). You should * never construct one yourself with "new." Instead, rely on router's internal recognizer to * construct `ComponentInstruction`s. * * You should not modify this object. It should be treated as immutable. */ var ComponentInstruction = (function () { /** * @internal */ function ComponentInstruction(urlPath, urlParams, data, componentType /** TODO #9100 */, terminal, specificity, params, routeName) { if (params === void 0) { params = null; } this.urlPath = urlPath; this.urlParams = urlParams; this.componentType = componentType; this.terminal = terminal; this.specificity = specificity; this.params = params; this.routeName = routeName; this.reuse = false; this.routeData = lang_1.isPresent(data) ? data : exports.BLANK_ROUTE_DATA; } return ComponentInstruction; }()); exports.ComponentInstruction = ComponentInstruction; //# sourceMappingURL=instruction.js.map
import Mmenu from './../oncanvas/mmenu.oncanvas'; import options from './_options'; import configs from './_configs'; import translate from './translations/translate'; import * as DOM from '../_dom'; import { extendShorthandOptions } from './_options'; import { extend } from '../../core/_helpers'; // Add the translations. translate(); // Add the options and configs. Mmenu.options.screenReader = options; Mmenu.configs.screenReader = configs; export default function () { // Extend options. var options = extendShorthandOptions(this.opts.screenReader); this.opts.screenReader = extend(options, Mmenu.options.screenReader); // Extend configs. var configs = this.conf.screenReader; // Add Aria-* attributes if (options.aria) { // Add screenreader / aria hooks for add-ons // In orde to keep this list short, only extend hooks that are actually used by other add-ons. this.bind('initAddons:after', () => { this.bind('initMenu:after', function () { this.trigger('initMenu:after:sr-aria', [].slice.call(arguments)); }); this.bind('initNavbar:after', function () { this.trigger('initNavbar:after:sr-aria', [].slice.call(arguments)); }); this.bind('openPanel:start', function () { this.trigger('openPanel:start:sr-aria', [].slice.call(arguments)); }); this.bind('close:start', function () { this.trigger('close:start:sr-aria', [].slice.call(arguments)); }); this.bind('close:finish', function () { this.trigger('close:finish:sr-aria', [].slice.call(arguments)); }); this.bind('open:start', function () { this.trigger('open:start:sr-aria', [].slice.call(arguments)); }); this.bind('initOpened:after', function () { this.trigger('initOpened:after:sr-aria', [].slice.call(arguments)); }); }); // Update aria-hidden for hidden / visible listitems this.bind('updateListview', () => { this.node.pnls .querySelectorAll('.mm-listitem') .forEach(listitem => { Mmenu.sr_aria(listitem, 'hidden', listitem.matches('.mm-hidden')); }); }); // Update aria-hidden for the panels when opening and closing a panel. this.bind('openPanel:start', (panel) => { /** Panels that should be considered "hidden". */ var hidden = DOM.find(this.node.pnls, '.mm-panel') .filter(hide => hide !== panel) .filter(hide => !hide.parentElement.matches('.mm-panel')); /** Panels that should be considered "visible". */ var visible = [panel]; DOM.find(panel, '.mm-listitem_vertical .mm-listitem_opened').forEach(listitem => { visible.push(...DOM.children(listitem, '.mm-panel')); }); // Set the panels to be considered "hidden" or "visible". hidden.forEach(panel => { Mmenu.sr_aria(panel, 'hidden', true); }); visible.forEach(panel => { Mmenu.sr_aria(panel, 'hidden', false); }); }); this.bind('closePanel', (panel) => { Mmenu.sr_aria(panel, 'hidden', true); }); // Add aria-haspopup and aria-owns to prev- and next buttons. this.bind('initPanels:after', (panels) => { panels.forEach(panel => { DOM.find(panel, '.mm-btn').forEach(button => { Mmenu.sr_aria(button, 'haspopup', true); let href = button.getAttribute('href'); if (href) { Mmenu.sr_aria(button, 'owns', href.replace('#', '')); } }); }); }); // Add aria-hidden for navbars in panels. this.bind('initNavbar:after', (panel) => { /** The navbar in the panel. */ var navbar = DOM.children(panel, '.mm-navbar')[0]; /** Whether or not the navbar should be considered "hidden". */ var hidden = navbar.matches('.mm-hidden'); // Set the navbar to be considered "hidden" or "visible". Mmenu.sr_aria(navbar, 'hidden', hidden); }); // Text if (options.text) { // Add aria-hidden to titles in navbars if (this.opts.navbar.titleLink == 'parent') { this.bind('initNavbar:after', (panel) => { /** The navbar in the panel. */ var navbar = DOM.children(panel, '.mm-navbar')[0]; /** Whether or not the navbar should be considered "hidden". */ var hidden = navbar.querySelector('.mm-btn_prev') ? true : false; // Set the navbar-title to be considered "hidden" or "visible". Mmenu.sr_aria(DOM.find(navbar, '.mm-navbar__title')[0], 'hidden', hidden); }); } } } // Add screenreader text if (options.text) { // Add screenreader / text hooks for add-ons // In orde to keep this list short, only extend hooks that are actually used by other add-ons. this.bind('initAddons:after', () => { this.bind('setPage:after', function () { this.trigger('setPage:after:sr-text', [].slice.call(arguments)); }); this.bind('initBlocker:after', function () { this.trigger('initBlocker:after:sr-text', [].slice.call(arguments)); }); }); // Add text to the prev-buttons. this.bind('initNavbar:after', (panel) => { let navbar = DOM.children(panel, '.mm-navbar')[0]; if (navbar) { let button = DOM.children(navbar, '.mm-btn_prev')[0]; if (button) { button.innerHTML = Mmenu.sr_text(this.i18n(configs.text.closeSubmenu)); } } }); // Add text to the next-buttons. this.bind('initListview:after', (panel) => { let parent = panel['mmParent']; if (parent) { let next = DOM.children(parent, '.mm-btn_next')[0]; if (next) { let text = this.i18n(configs.text[next.parentElement.matches('.mm-listitem_vertical') ? 'toggleSubmenu' : 'openSubmenu']); next.innerHTML += Mmenu.sr_text(text); } } }); } } // Methods (function () { var attr = function (element, attr, value) { element[attr] = value; if (value) { element.setAttribute(attr, value.toString()); } else { element.removeAttribute(attr); } }; /** * Add aria (property and) attribute to a HTML element. * * @param {HTMLElement} element The node to add the attribute to. * @param {string} name The (non-aria-prefixed) attribute name. * @param {string|boolean} value The attribute value. */ Mmenu.sr_aria = function (element, name, value) { attr(element, 'aria-' + name, value); }; /** * Add role attribute to a HTML element. * * @param {HTMLElement} element The node to add the attribute to. * @param {string|boolean} value The attribute value. */ Mmenu.sr_role = function (element, value) { attr(element, 'role', value); }; /** * Wrap a text in a screen-reader-only node. * * @param {string} text The text to wrap. * @return {string} The wrapped text. */ Mmenu.sr_text = function (text) { return '<span class="mm-sronly">' + text + '</span>'; }; })();
/* Copyright 2014 Mozilla Foundation * * 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. */ (function (root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define('pdfjs-dist/web/pdf_viewer', [ 'exports', 'pdfjs-dist/build/pdf' ], factory); } else if (typeof exports !== 'undefined') { factory(exports, require('../build/pdf.js')); } else { factory(root.pdfjsDistWebPDFViewer = {}, root.pdfjsDistBuildPdf); } }(this, function (exports, pdfjsLib) { 'use strict'; var pdfViewerLibs = { pdfjsWebPDFJS: pdfjsLib }; (function () { (function (root, factory) { factory(root.pdfjsWebPDFRenderingQueue = {}); }(this, function (exports) { var CLEANUP_TIMEOUT = 30000; var RenderingStates = { INITIAL: 0, RUNNING: 1, PAUSED: 2, FINISHED: 3 }; var PDFRenderingQueue = function PDFRenderingQueueClosure() { function PDFRenderingQueue() { this.pdfViewer = null; this.pdfThumbnailViewer = null; this.onIdle = null; this.highestPriorityPage = null; this.idleTimeout = null; this.printing = false; this.isThumbnailViewEnabled = false; } PDFRenderingQueue.prototype = { setViewer: function PDFRenderingQueue_setViewer(pdfViewer) { this.pdfViewer = pdfViewer; }, setThumbnailViewer: function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) { this.pdfThumbnailViewer = pdfThumbnailViewer; }, isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) { return this.highestPriorityPage === view.renderingId; }, renderHighestPriority: function PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) { if (this.idleTimeout) { clearTimeout(this.idleTimeout); this.idleTimeout = null; } if (this.pdfViewer.forceRendering(currentlyVisiblePages)) { return; } if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) { if (this.pdfThumbnailViewer.forceRendering()) { return; } } if (this.printing) { return; } if (this.onIdle) { this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT); } }, getHighestPriority: function PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) { var visibleViews = visible.views; var numVisible = visibleViews.length; if (numVisible === 0) { return false; } for (var i = 0; i < numVisible; ++i) { var view = visibleViews[i].view; if (!this.isViewFinished(view)) { return view; } } if (scrolledDown) { var nextPageIndex = visible.last.id; if (views[nextPageIndex] && !this.isViewFinished(views[nextPageIndex])) { return views[nextPageIndex]; } } else { var previousPageIndex = visible.first.id - 2; if (views[previousPageIndex] && !this.isViewFinished(views[previousPageIndex])) { return views[previousPageIndex]; } } return null; }, isViewFinished: function PDFRenderingQueue_isViewFinished(view) { return view.renderingState === RenderingStates.FINISHED; }, renderView: function PDFRenderingQueue_renderView(view) { var state = view.renderingState; switch (state) { case RenderingStates.FINISHED: return false; case RenderingStates.PAUSED: this.highestPriorityPage = view.renderingId; view.resume(); break; case RenderingStates.RUNNING: this.highestPriorityPage = view.renderingId; break; case RenderingStates.INITIAL: this.highestPriorityPage = view.renderingId; var continueRendering = function () { this.renderHighestPriority(); }.bind(this); view.draw().then(continueRendering, continueRendering); break; } return true; } }; return PDFRenderingQueue; }(); exports.RenderingStates = RenderingStates; exports.PDFRenderingQueue = PDFRenderingQueue; })); (function (root, factory) { factory(root.pdfjsWebDownloadManager = {}, root.pdfjsWebPDFJS); }(this, function (exports, pdfjsLib) { function download(blobUrl, filename) { var a = document.createElement('a'); if (a.click) { a.href = blobUrl; a.target = '_parent'; if ('download' in a) { a.download = filename; } (document.body || document.documentElement).appendChild(a); a.click(); a.parentNode.removeChild(a); } else { if (window.top === window && blobUrl.split('#')[0] === window.location.href.split('#')[0]) { var padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&'; blobUrl = blobUrl.replace(/#|$/, padCharacter + '$&'); } window.open(blobUrl, '_parent'); } } function DownloadManager() { } DownloadManager.prototype = { downloadUrl: function DownloadManager_downloadUrl(url, filename) { if (!pdfjsLib.createValidAbsoluteUrl(url, 'http://example.com')) { return; } download(url + '#pdfjs.action=download', filename); }, downloadData: function DownloadManager_downloadData(data, filename, contentType) { if (navigator.msSaveBlob) { return navigator.msSaveBlob(new Blob([data], { type: contentType }), filename); } var blobUrl = pdfjsLib.createObjectURL(data, contentType, pdfjsLib.PDFJS.disableCreateObjectURL); download(blobUrl, filename); }, download: function DownloadManager_download(blob, url, filename) { if (!URL) { this.downloadUrl(url, filename); return; } if (navigator.msSaveBlob) { if (!navigator.msSaveBlob(blob, filename)) { this.downloadUrl(url, filename); } return; } var blobUrl = URL.createObjectURL(blob); download(blobUrl, filename); } }; exports.DownloadManager = DownloadManager; })); (function (root, factory) { factory(root.pdfjsWebUIUtils = {}, root.pdfjsWebPDFJS); }(this, function (exports, pdfjsLib) { var CSS_UNITS = 96.0 / 72.0; var DEFAULT_SCALE_VALUE = 'auto'; var DEFAULT_SCALE = 1.0; var MIN_SCALE = 0.25; var MAX_SCALE = 10.0; var UNKNOWN_SCALE = 0; var MAX_AUTO_SCALE = 1.25; var SCROLLBAR_PADDING = 40; var VERTICAL_PADDING = 5; var mozL10n = document.mozL10n || document.webL10n; var PDFJS = pdfjsLib.PDFJS; PDFJS.disableFullscreen = PDFJS.disableFullscreen === undefined ? false : PDFJS.disableFullscreen; PDFJS.useOnlyCssZoom = PDFJS.useOnlyCssZoom === undefined ? false : PDFJS.useOnlyCssZoom; PDFJS.maxCanvasPixels = PDFJS.maxCanvasPixels === undefined ? 16777216 : PDFJS.maxCanvasPixels; PDFJS.disableHistory = PDFJS.disableHistory === undefined ? false : PDFJS.disableHistory; PDFJS.disableTextLayer = PDFJS.disableTextLayer === undefined ? false : PDFJS.disableTextLayer; PDFJS.ignoreCurrentPositionOnZoom = PDFJS.ignoreCurrentPositionOnZoom === undefined ? false : PDFJS.ignoreCurrentPositionOnZoom; PDFJS.locale = PDFJS.locale === undefined ? navigator.language : PDFJS.locale; function getOutputScale(ctx) { var devicePixelRatio = window.devicePixelRatio || 1; var backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1; var pixelRatio = devicePixelRatio / backingStoreRatio; return { sx: pixelRatio, sy: pixelRatio, scaled: pixelRatio !== 1 }; } function scrollIntoView(element, spot, skipOverflowHiddenElements) { var parent = element.offsetParent; if (!parent) { console.error('offsetParent is not set -- cannot scroll'); return; } var checkOverflow = skipOverflowHiddenElements || false; var offsetY = element.offsetTop + element.clientTop; var offsetX = element.offsetLeft + element.clientLeft; while (parent.clientHeight === parent.scrollHeight || checkOverflow && getComputedStyle(parent).overflow === 'hidden') { if (parent.dataset._scaleY) { offsetY /= parent.dataset._scaleY; offsetX /= parent.dataset._scaleX; } offsetY += parent.offsetTop; offsetX += parent.offsetLeft; parent = parent.offsetParent; if (!parent) { return; } } if (spot) { if (spot.top !== undefined) { offsetY += spot.top; } if (spot.left !== undefined) { offsetX += spot.left; parent.scrollLeft = offsetX; } } parent.scrollTop = offsetY; } function watchScroll(viewAreaElement, callback) { var debounceScroll = function debounceScroll(evt) { if (rAF) { return; } rAF = window.requestAnimationFrame(function viewAreaElementScrolled() { rAF = null; var currentY = viewAreaElement.scrollTop; var lastY = state.lastY; if (currentY !== lastY) { state.down = currentY > lastY; } state.lastY = currentY; callback(state); }); }; var state = { down: true, lastY: viewAreaElement.scrollTop, _eventHandler: debounceScroll }; var rAF = null; viewAreaElement.addEventListener('scroll', debounceScroll, true); return state; } function parseQueryString(query) { var parts = query.split('&'); var params = {}; for (var i = 0, ii = parts.length; i < ii; ++i) { var param = parts[i].split('='); var key = param[0].toLowerCase(); var value = param.length > 1 ? param[1] : null; params[decodeURIComponent(key)] = decodeURIComponent(value); } return params; } function binarySearchFirstItem(items, condition) { var minIndex = 0; var maxIndex = items.length - 1; if (items.length === 0 || !condition(items[maxIndex])) { return items.length; } if (condition(items[minIndex])) { return minIndex; } while (minIndex < maxIndex) { var currentIndex = minIndex + maxIndex >> 1; var currentItem = items[currentIndex]; if (condition(currentItem)) { maxIndex = currentIndex; } else { minIndex = currentIndex + 1; } } return minIndex; } function approximateFraction(x) { if (Math.floor(x) === x) { return [ x, 1 ]; } var xinv = 1 / x; var limit = 8; if (xinv > limit) { return [ 1, limit ]; } else if (Math.floor(xinv) === xinv) { return [ 1, xinv ]; } var x_ = x > 1 ? xinv : x; var a = 0, b = 1, c = 1, d = 1; while (true) { var p = a + c, q = b + d; if (q > limit) { break; } if (x_ <= p / q) { c = p; d = q; } else { a = p; b = q; } } if (x_ - a / b < c / d - x_) { return x_ === x ? [ a, b ] : [ b, a ]; } else { return x_ === x ? [ c, d ] : [ d, c ]; } } function roundToDivide(x, div) { var r = x % div; return r === 0 ? x : Math.round(x - r + div); } function getVisibleElements(scrollEl, views, sortByVisibility) { var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight; var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth; function isElementBottomBelowViewTop(view) { var element = view.div; var elementBottom = element.offsetTop + element.clientTop + element.clientHeight; return elementBottom > top; } var visible = [], view, element; var currentHeight, viewHeight, hiddenHeight, percentHeight; var currentWidth, viewWidth; var firstVisibleElementInd = views.length === 0 ? 0 : binarySearchFirstItem(views, isElementBottomBelowViewTop); for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) { view = views[i]; element = view.div; currentHeight = element.offsetTop + element.clientTop; viewHeight = element.clientHeight; if (currentHeight > bottom) { break; } currentWidth = element.offsetLeft + element.clientLeft; viewWidth = element.clientWidth; if (currentWidth + viewWidth < left || currentWidth > right) { continue; } hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, currentHeight + viewHeight - bottom); percentHeight = (viewHeight - hiddenHeight) * 100 / viewHeight | 0; visible.push({ id: view.id, x: currentWidth, y: currentHeight, view: view, percent: percentHeight }); } var first = visible[0]; var last = visible[visible.length - 1]; if (sortByVisibility) { visible.sort(function (a, b) { var pc = a.percent - b.percent; if (Math.abs(pc) > 0.001) { return -pc; } return a.id - b.id; }); } return { first: first, last: last, views: visible }; } function noContextMenuHandler(e) { e.preventDefault(); } function getPDFFileNameFromURL(url) { var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/; var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i; var splitURI = reURI.exec(url); var suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]); if (suggestedFilename) { suggestedFilename = suggestedFilename[0]; if (suggestedFilename.indexOf('%') !== -1) { try { suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0]; } catch (e) { } } } return suggestedFilename || 'document.pdf'; } function normalizeWheelEventDelta(evt) { var delta = Math.sqrt(evt.deltaX * evt.deltaX + evt.deltaY * evt.deltaY); var angle = Math.atan2(evt.deltaY, evt.deltaX); if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) { delta = -delta; } var MOUSE_DOM_DELTA_PIXEL_MODE = 0; var MOUSE_DOM_DELTA_LINE_MODE = 1; var MOUSE_PIXELS_PER_LINE = 30; var MOUSE_LINES_PER_PAGE = 30; if (evt.deltaMode === MOUSE_DOM_DELTA_PIXEL_MODE) { delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE; } else if (evt.deltaMode === MOUSE_DOM_DELTA_LINE_MODE) { delta /= MOUSE_LINES_PER_PAGE; } return delta; } var animationStarted = new Promise(function (resolve) { window.requestAnimationFrame(resolve); }); var localized = new Promise(function (resolve, reject) { if (!mozL10n) { reject(new Error('mozL10n service is not available.')); return; } if (mozL10n.getReadyState() !== 'loading') { resolve(); return; } window.addEventListener('localized', function localized(evt) { resolve(); }); }); var EventBus = function EventBusClosure() { function EventBus() { this._listeners = Object.create(null); } EventBus.prototype = { on: function EventBus_on(eventName, listener) { var eventListeners = this._listeners[eventName]; if (!eventListeners) { eventListeners = []; this._listeners[eventName] = eventListeners; } eventListeners.push(listener); }, off: function EventBus_on(eventName, listener) { var eventListeners = this._listeners[eventName]; var i; if (!eventListeners || (i = eventListeners.indexOf(listener)) < 0) { return; } eventListeners.splice(i, 1); }, dispatch: function EventBus_dispath(eventName) { var eventListeners = this._listeners[eventName]; if (!eventListeners || eventListeners.length === 0) { return; } var args = Array.prototype.slice.call(arguments, 1); eventListeners.slice(0).forEach(function (listener) { listener.apply(null, args); }); } }; return EventBus; }(); var ProgressBar = function ProgressBarClosure() { function clamp(v, min, max) { return Math.min(Math.max(v, min), max); } function ProgressBar(id, opts) { this.visible = true; this.div = document.querySelector(id + ' .progress'); this.bar = this.div.parentNode; this.height = opts.height || 100; this.width = opts.width || 100; this.units = opts.units || '%'; this.div.style.height = this.height + this.units; this.percent = 0; } ProgressBar.prototype = { updateBar: function ProgressBar_updateBar() { if (this._indeterminate) { this.div.classList.add('indeterminate'); this.div.style.width = this.width + this.units; return; } this.div.classList.remove('indeterminate'); var progressSize = this.width * this._percent / 100; this.div.style.width = progressSize + this.units; }, get percent() { return this._percent; }, set percent(val) { this._indeterminate = isNaN(val); this._percent = clamp(val, 0, 100); this.updateBar(); }, setWidth: function ProgressBar_setWidth(viewer) { if (viewer) { var container = viewer.parentNode; var scrollbarWidth = container.offsetWidth - viewer.offsetWidth; if (scrollbarWidth > 0) { this.bar.setAttribute('style', 'width: calc(100% - ' + scrollbarWidth + 'px);'); } } }, hide: function ProgressBar_hide() { if (!this.visible) { return; } this.visible = false; this.bar.classList.add('hidden'); document.body.classList.remove('loadingInProgress'); }, show: function ProgressBar_show() { if (this.visible) { return; } this.visible = true; document.body.classList.add('loadingInProgress'); this.bar.classList.remove('hidden'); } }; return ProgressBar; }(); exports.CSS_UNITS = CSS_UNITS; exports.DEFAULT_SCALE_VALUE = DEFAULT_SCALE_VALUE; exports.DEFAULT_SCALE = DEFAULT_SCALE; exports.MIN_SCALE = MIN_SCALE; exports.MAX_SCALE = MAX_SCALE; exports.UNKNOWN_SCALE = UNKNOWN_SCALE; exports.MAX_AUTO_SCALE = MAX_AUTO_SCALE; exports.SCROLLBAR_PADDING = SCROLLBAR_PADDING; exports.VERTICAL_PADDING = VERTICAL_PADDING; exports.mozL10n = mozL10n; exports.EventBus = EventBus; exports.ProgressBar = ProgressBar; exports.getPDFFileNameFromURL = getPDFFileNameFromURL; exports.noContextMenuHandler = noContextMenuHandler; exports.parseQueryString = parseQueryString; exports.getVisibleElements = getVisibleElements; exports.roundToDivide = roundToDivide; exports.approximateFraction = approximateFraction; exports.getOutputScale = getOutputScale; exports.scrollIntoView = scrollIntoView; exports.watchScroll = watchScroll; exports.binarySearchFirstItem = binarySearchFirstItem; exports.normalizeWheelEventDelta = normalizeWheelEventDelta; exports.animationStarted = animationStarted; exports.localized = localized; })); (function (root, factory) { factory(root.pdfjsWebDOMEvents = {}, root.pdfjsWebUIUtils); }(this, function (exports, uiUtils) { var EventBus = uiUtils.EventBus; function attachDOMEventsToEventBus(eventBus) { eventBus.on('documentload', function () { var event = document.createEvent('CustomEvent'); event.initCustomEvent('documentload', true, true, {}); window.dispatchEvent(event); }); eventBus.on('pagerendered', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('pagerendered', true, true, { pageNumber: e.pageNumber, cssTransform: e.cssTransform }); e.source.div.dispatchEvent(event); }); eventBus.on('textlayerrendered', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('textlayerrendered', true, true, { pageNumber: e.pageNumber }); e.source.textLayerDiv.dispatchEvent(event); }); eventBus.on('pagechange', function (e) { var event = document.createEvent('UIEvents'); event.initUIEvent('pagechange', true, true, window, 0); event.pageNumber = e.pageNumber; e.source.container.dispatchEvent(event); }); eventBus.on('pagesinit', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('pagesinit', true, true, null); e.source.container.dispatchEvent(event); }); eventBus.on('pagesloaded', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('pagesloaded', true, true, { pagesCount: e.pagesCount }); e.source.container.dispatchEvent(event); }); eventBus.on('scalechange', function (e) { var event = document.createEvent('UIEvents'); event.initUIEvent('scalechange', true, true, window, 0); event.scale = e.scale; event.presetValue = e.presetValue; e.source.container.dispatchEvent(event); }); eventBus.on('updateviewarea', function (e) { var event = document.createEvent('UIEvents'); event.initUIEvent('updateviewarea', true, true, window, 0); event.location = e.location; e.source.container.dispatchEvent(event); }); eventBus.on('find', function (e) { if (e.source === window) { return; } var event = document.createEvent('CustomEvent'); event.initCustomEvent('find' + e.type, true, true, { query: e.query, phraseSearch: e.phraseSearch, caseSensitive: e.caseSensitive, highlightAll: e.highlightAll, findPrevious: e.findPrevious }); window.dispatchEvent(event); }); eventBus.on('attachmentsloaded', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('attachmentsloaded', true, true, { attachmentsCount: e.attachmentsCount }); e.source.container.dispatchEvent(event); }); eventBus.on('sidebarviewchanged', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('sidebarviewchanged', true, true, { view: e.view }); e.source.outerContainer.dispatchEvent(event); }); eventBus.on('pagemode', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('pagemode', true, true, { mode: e.mode }); e.source.pdfViewer.container.dispatchEvent(event); }); eventBus.on('namedaction', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('namedaction', true, true, { action: e.action }); e.source.pdfViewer.container.dispatchEvent(event); }); eventBus.on('presentationmodechanged', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('presentationmodechanged', true, true, { active: e.active, switchInProgress: e.switchInProgress }); window.dispatchEvent(event); }); eventBus.on('outlineloaded', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('outlineloaded', true, true, { outlineCount: e.outlineCount }); e.source.container.dispatchEvent(event); }); } var globalEventBus = null; function getGlobalEventBus() { if (globalEventBus) { return globalEventBus; } globalEventBus = new EventBus(); attachDOMEventsToEventBus(globalEventBus); return globalEventBus; } exports.attachDOMEventsToEventBus = attachDOMEventsToEventBus; exports.getGlobalEventBus = getGlobalEventBus; })); (function (root, factory) { factory(root.pdfjsWebPDFFindController = {}, root.pdfjsWebUIUtils); }(this, function (exports, uiUtils) { var scrollIntoView = uiUtils.scrollIntoView; var FindStates = { FIND_FOUND: 0, FIND_NOTFOUND: 1, FIND_WRAPPED: 2, FIND_PENDING: 3 }; var FIND_SCROLL_OFFSET_TOP = -50; var FIND_SCROLL_OFFSET_LEFT = -400; var CHARACTERS_TO_NORMALIZE = { '\u2018': '\'', '\u2019': '\'', '\u201A': '\'', '\u201B': '\'', '\u201C': '"', '\u201D': '"', '\u201E': '"', '\u201F': '"', '\u00BC': '1/4', '\u00BD': '1/2', '\u00BE': '3/4' }; var PDFFindController = function PDFFindControllerClosure() { function PDFFindController(options) { this.pdfViewer = options.pdfViewer || null; this.onUpdateResultsCount = null; this.onUpdateState = null; this.reset(); var replace = Object.keys(CHARACTERS_TO_NORMALIZE).join(''); this.normalizationRegex = new RegExp('[' + replace + ']', 'g'); } PDFFindController.prototype = { reset: function PDFFindController_reset() { this.startedTextExtraction = false; this.extractTextPromises = []; this.pendingFindMatches = Object.create(null); this.active = false; this.pageContents = []; this.pageMatches = []; this.pageMatchesLength = null; this.matchCount = 0; this.selected = { pageIdx: -1, matchIdx: -1 }; this.offset = { pageIdx: null, matchIdx: null }; this.pagesToSearch = null; this.resumePageIdx = null; this.state = null; this.dirtyMatch = false; this.findTimeout = null; this.firstPagePromise = new Promise(function (resolve) { this.resolveFirstPage = resolve; }.bind(this)); }, normalize: function PDFFindController_normalize(text) { return text.replace(this.normalizationRegex, function (ch) { return CHARACTERS_TO_NORMALIZE[ch]; }); }, _prepareMatches: function PDFFindController_prepareMatches(matchesWithLength, matches, matchesLength) { function isSubTerm(matchesWithLength, currentIndex) { var currentElem, prevElem, nextElem; currentElem = matchesWithLength[currentIndex]; nextElem = matchesWithLength[currentIndex + 1]; if (currentIndex < matchesWithLength.length - 1 && currentElem.match === nextElem.match) { currentElem.skipped = true; return true; } for (var i = currentIndex - 1; i >= 0; i--) { prevElem = matchesWithLength[i]; if (prevElem.skipped) { continue; } if (prevElem.match + prevElem.matchLength < currentElem.match) { break; } if (prevElem.match + prevElem.matchLength >= currentElem.match + currentElem.matchLength) { currentElem.skipped = true; return true; } } return false; } var i, len; matchesWithLength.sort(function (a, b) { return a.match === b.match ? a.matchLength - b.matchLength : a.match - b.match; }); for (i = 0, len = matchesWithLength.length; i < len; i++) { if (isSubTerm(matchesWithLength, i)) { continue; } matches.push(matchesWithLength[i].match); matchesLength.push(matchesWithLength[i].matchLength); } }, calcFindPhraseMatch: function PDFFindController_calcFindPhraseMatch(query, pageIndex, pageContent) { var matches = []; var queryLen = query.length; var matchIdx = -queryLen; while (true) { matchIdx = pageContent.indexOf(query, matchIdx + queryLen); if (matchIdx === -1) { break; } matches.push(matchIdx); } this.pageMatches[pageIndex] = matches; }, calcFindWordMatch: function PDFFindController_calcFindWordMatch(query, pageIndex, pageContent) { var matchesWithLength = []; var queryArray = query.match(/\S+/g); var subquery, subqueryLen, matchIdx; for (var i = 0, len = queryArray.length; i < len; i++) { subquery = queryArray[i]; subqueryLen = subquery.length; matchIdx = -subqueryLen; while (true) { matchIdx = pageContent.indexOf(subquery, matchIdx + subqueryLen); if (matchIdx === -1) { break; } matchesWithLength.push({ match: matchIdx, matchLength: subqueryLen, skipped: false }); } } if (!this.pageMatchesLength) { this.pageMatchesLength = []; } this.pageMatchesLength[pageIndex] = []; this.pageMatches[pageIndex] = []; this._prepareMatches(matchesWithLength, this.pageMatches[pageIndex], this.pageMatchesLength[pageIndex]); }, calcFindMatch: function PDFFindController_calcFindMatch(pageIndex) { var pageContent = this.normalize(this.pageContents[pageIndex]); var query = this.normalize(this.state.query); var caseSensitive = this.state.caseSensitive; var phraseSearch = this.state.phraseSearch; var queryLen = query.length; if (queryLen === 0) { return; } if (!caseSensitive) { pageContent = pageContent.toLowerCase(); query = query.toLowerCase(); } if (phraseSearch) { this.calcFindPhraseMatch(query, pageIndex, pageContent); } else { this.calcFindWordMatch(query, pageIndex, pageContent); } this.updatePage(pageIndex); if (this.resumePageIdx === pageIndex) { this.resumePageIdx = null; this.nextPageMatch(); } if (this.pageMatches[pageIndex].length > 0) { this.matchCount += this.pageMatches[pageIndex].length; this.updateUIResultsCount(); } }, extractText: function PDFFindController_extractText() { if (this.startedTextExtraction) { return; } this.startedTextExtraction = true; this.pageContents = []; var extractTextPromisesResolves = []; var numPages = this.pdfViewer.pagesCount; for (var i = 0; i < numPages; i++) { this.extractTextPromises.push(new Promise(function (resolve) { extractTextPromisesResolves.push(resolve); })); } var self = this; function extractPageText(pageIndex) { self.pdfViewer.getPageTextContent(pageIndex).then(function textContentResolved(textContent) { var textItems = textContent.items; var str = []; for (var i = 0, len = textItems.length; i < len; i++) { str.push(textItems[i].str); } self.pageContents.push(str.join('')); extractTextPromisesResolves[pageIndex](pageIndex); if (pageIndex + 1 < self.pdfViewer.pagesCount) { extractPageText(pageIndex + 1); } }); } extractPageText(0); }, executeCommand: function PDFFindController_executeCommand(cmd, state) { if (this.state === null || cmd !== 'findagain') { this.dirtyMatch = true; } this.state = state; this.updateUIState(FindStates.FIND_PENDING); this.firstPagePromise.then(function () { this.extractText(); clearTimeout(this.findTimeout); if (cmd === 'find') { this.findTimeout = setTimeout(this.nextMatch.bind(this), 250); } else { this.nextMatch(); } }.bind(this)); }, updatePage: function PDFFindController_updatePage(index) { if (this.selected.pageIdx === index) { this.pdfViewer.currentPageNumber = index + 1; } var page = this.pdfViewer.getPageView(index); if (page.textLayer) { page.textLayer.updateMatches(); } }, nextMatch: function PDFFindController_nextMatch() { var previous = this.state.findPrevious; var currentPageIndex = this.pdfViewer.currentPageNumber - 1; var numPages = this.pdfViewer.pagesCount; this.active = true; if (this.dirtyMatch) { this.dirtyMatch = false; this.selected.pageIdx = this.selected.matchIdx = -1; this.offset.pageIdx = currentPageIndex; this.offset.matchIdx = null; this.hadMatch = false; this.resumePageIdx = null; this.pageMatches = []; this.matchCount = 0; this.pageMatchesLength = null; var self = this; for (var i = 0; i < numPages; i++) { this.updatePage(i); if (!(i in this.pendingFindMatches)) { this.pendingFindMatches[i] = true; this.extractTextPromises[i].then(function (pageIdx) { delete self.pendingFindMatches[pageIdx]; self.calcFindMatch(pageIdx); }); } } } if (this.state.query === '') { this.updateUIState(FindStates.FIND_FOUND); return; } if (this.resumePageIdx) { return; } var offset = this.offset; this.pagesToSearch = numPages; if (offset.matchIdx !== null) { var numPageMatches = this.pageMatches[offset.pageIdx].length; if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) { this.hadMatch = true; offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1; this.updateMatch(true); return; } this.advanceOffsetPage(previous); } this.nextPageMatch(); }, matchesReady: function PDFFindController_matchesReady(matches) { var offset = this.offset; var numMatches = matches.length; var previous = this.state.findPrevious; if (numMatches) { this.hadMatch = true; offset.matchIdx = previous ? numMatches - 1 : 0; this.updateMatch(true); return true; } else { this.advanceOffsetPage(previous); if (offset.wrapped) { offset.matchIdx = null; if (this.pagesToSearch < 0) { this.updateMatch(false); return true; } } return false; } }, updateMatchPosition: function PDFFindController_updateMatchPosition(pageIndex, index, elements, beginIdx) { if (this.selected.matchIdx === index && this.selected.pageIdx === pageIndex) { var spot = { top: FIND_SCROLL_OFFSET_TOP, left: FIND_SCROLL_OFFSET_LEFT }; scrollIntoView(elements[beginIdx], spot, true); } }, nextPageMatch: function PDFFindController_nextPageMatch() { if (this.resumePageIdx !== null) { console.error('There can only be one pending page.'); } do { var pageIdx = this.offset.pageIdx; var matches = this.pageMatches[pageIdx]; if (!matches) { this.resumePageIdx = pageIdx; break; } } while (!this.matchesReady(matches)); }, advanceOffsetPage: function PDFFindController_advanceOffsetPage(previous) { var offset = this.offset; var numPages = this.extractTextPromises.length; offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1; offset.matchIdx = null; this.pagesToSearch--; if (offset.pageIdx >= numPages || offset.pageIdx < 0) { offset.pageIdx = previous ? numPages - 1 : 0; offset.wrapped = true; } }, updateMatch: function PDFFindController_updateMatch(found) { var state = FindStates.FIND_NOTFOUND; var wrapped = this.offset.wrapped; this.offset.wrapped = false; if (found) { var previousPage = this.selected.pageIdx; this.selected.pageIdx = this.offset.pageIdx; this.selected.matchIdx = this.offset.matchIdx; state = wrapped ? FindStates.FIND_WRAPPED : FindStates.FIND_FOUND; if (previousPage !== -1 && previousPage !== this.selected.pageIdx) { this.updatePage(previousPage); } } this.updateUIState(state, this.state.findPrevious); if (this.selected.pageIdx !== -1) { this.updatePage(this.selected.pageIdx); } }, updateUIResultsCount: function PDFFindController_updateUIResultsCount() { if (this.onUpdateResultsCount) { this.onUpdateResultsCount(this.matchCount); } }, updateUIState: function PDFFindController_updateUIState(state, previous) { if (this.onUpdateState) { this.onUpdateState(state, previous, this.matchCount); } } }; return PDFFindController; }(); exports.FindStates = FindStates; exports.PDFFindController = PDFFindController; })); (function (root, factory) { factory(root.pdfjsWebPDFHistory = {}, root.pdfjsWebDOMEvents); }(this, function (exports, domEvents) { function PDFHistory(options) { this.linkService = options.linkService; this.eventBus = options.eventBus || domEvents.getGlobalEventBus(); this.initialized = false; this.initialDestination = null; this.initialBookmark = null; } PDFHistory.prototype = { initialize: function pdfHistoryInitialize(fingerprint) { this.initialized = true; this.reInitialized = false; this.allowHashChange = true; this.historyUnlocked = true; this.isViewerInPresentationMode = false; this.previousHash = window.location.hash.substring(1); this.currentBookmark = ''; this.currentPage = 0; this.updatePreviousBookmark = false; this.previousBookmark = ''; this.previousPage = 0; this.nextHashParam = ''; this.fingerprint = fingerprint; this.currentUid = this.uid = 0; this.current = {}; var state = window.history.state; if (this._isStateObjectDefined(state)) { if (state.target.dest) { this.initialDestination = state.target.dest; } else { this.initialBookmark = state.target.hash; } this.currentUid = state.uid; this.uid = state.uid + 1; this.current = state.target; } else { if (state && state.fingerprint && this.fingerprint !== state.fingerprint) { this.reInitialized = true; } this._pushOrReplaceState({ fingerprint: this.fingerprint }, true); } var self = this; window.addEventListener('popstate', function pdfHistoryPopstate(evt) { if (!self.historyUnlocked) { return; } if (evt.state) { self._goTo(evt.state); return; } if (self.uid === 0) { var previousParams = self.previousHash && self.currentBookmark && self.previousHash !== self.currentBookmark ? { hash: self.currentBookmark, page: self.currentPage } : { page: 1 }; replacePreviousHistoryState(previousParams, function () { updateHistoryWithCurrentHash(); }); } else { updateHistoryWithCurrentHash(); } }, false); function updateHistoryWithCurrentHash() { self.previousHash = window.location.hash.slice(1); self._pushToHistory({ hash: self.previousHash }, false, true); self._updatePreviousBookmark(); } function replacePreviousHistoryState(params, callback) { self.historyUnlocked = false; self.allowHashChange = false; window.addEventListener('popstate', rewriteHistoryAfterBack); history.back(); function rewriteHistoryAfterBack() { window.removeEventListener('popstate', rewriteHistoryAfterBack); window.addEventListener('popstate', rewriteHistoryAfterForward); self._pushToHistory(params, false, true); history.forward(); } function rewriteHistoryAfterForward() { window.removeEventListener('popstate', rewriteHistoryAfterForward); self.allowHashChange = true; self.historyUnlocked = true; callback(); } } function pdfHistoryBeforeUnload() { var previousParams = self._getPreviousParams(null, true); if (previousParams) { var replacePrevious = !self.current.dest && self.current.hash !== self.previousHash; self._pushToHistory(previousParams, false, replacePrevious); self._updatePreviousBookmark(); } window.removeEventListener('beforeunload', pdfHistoryBeforeUnload, false); } window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false); window.addEventListener('pageshow', function pdfHistoryPageShow(evt) { window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false); }, false); self.eventBus.on('presentationmodechanged', function (e) { self.isViewerInPresentationMode = e.active; }); }, clearHistoryState: function pdfHistory_clearHistoryState() { this._pushOrReplaceState(null, true); }, _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) { return state && state.uid >= 0 && state.fingerprint && this.fingerprint === state.fingerprint && state.target && state.target.hash ? true : false; }, _pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj, replace) { if (replace) { window.history.replaceState(stateObj, '', document.URL); } else { window.history.pushState(stateObj, '', document.URL); } }, get isHashChangeUnlocked() { if (!this.initialized) { return true; } return this.allowHashChange; }, _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() { if (this.updatePreviousBookmark && this.currentBookmark && this.currentPage) { this.previousBookmark = this.currentBookmark; this.previousPage = this.currentPage; this.updatePreviousBookmark = false; } }, updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark, pageNum) { if (this.initialized) { this.currentBookmark = bookmark.substring(1); this.currentPage = pageNum | 0; this._updatePreviousBookmark(); } }, updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) { if (this.initialized) { this.nextHashParam = param; } }, push: function pdfHistoryPush(params, isInitialBookmark) { if (!(this.initialized && this.historyUnlocked)) { return; } if (params.dest && !params.hash) { params.hash = this.current.hash && this.current.dest && this.current.dest === params.dest ? this.current.hash : this.linkService.getDestinationHash(params.dest).split('#')[1]; } if (params.page) { params.page |= 0; } if (isInitialBookmark) { var target = window.history.state.target; if (!target) { this._pushToHistory(params, false); this.previousHash = window.location.hash.substring(1); } this.updatePreviousBookmark = this.nextHashParam ? false : true; if (target) { this._updatePreviousBookmark(); } return; } if (this.nextHashParam) { if (this.nextHashParam === params.hash) { this.nextHashParam = null; this.updatePreviousBookmark = true; return; } else { this.nextHashParam = null; } } if (params.hash) { if (this.current.hash) { if (this.current.hash !== params.hash) { this._pushToHistory(params, true); } else { if (!this.current.page && params.page) { this._pushToHistory(params, false, true); } this.updatePreviousBookmark = true; } } else { this._pushToHistory(params, true); } } else if (this.current.page && params.page && this.current.page !== params.page) { this._pushToHistory(params, true); } }, _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage, beforeUnload) { if (!(this.currentBookmark && this.currentPage)) { return null; } else if (this.updatePreviousBookmark) { this.updatePreviousBookmark = false; } if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) { return null; } if (!this.current.dest && !onlyCheckPage || beforeUnload) { if (this.previousBookmark === this.currentBookmark) { return null; } } else if (this.current.page || onlyCheckPage) { if (this.previousPage === this.currentPage) { return null; } } else { return null; } var params = { hash: this.currentBookmark, page: this.currentPage }; if (this.isViewerInPresentationMode) { params.hash = null; } return params; }, _stateObj: function pdfHistory_stateObj(params) { return { fingerprint: this.fingerprint, uid: this.uid, target: params }; }, _pushToHistory: function pdfHistory_pushToHistory(params, addPrevious, overwrite) { if (!this.initialized) { return; } if (!params.hash && params.page) { params.hash = 'page=' + params.page; } if (addPrevious && !overwrite) { var previousParams = this._getPreviousParams(); if (previousParams) { var replacePrevious = !this.current.dest && this.current.hash !== this.previousHash; this._pushToHistory(previousParams, false, replacePrevious); } } this._pushOrReplaceState(this._stateObj(params), overwrite || this.uid === 0); this.currentUid = this.uid++; this.current = params; this.updatePreviousBookmark = true; }, _goTo: function pdfHistory_goTo(state) { if (!(this.initialized && this.historyUnlocked && this._isStateObjectDefined(state))) { return; } if (!this.reInitialized && state.uid < this.currentUid) { var previousParams = this._getPreviousParams(true); if (previousParams) { this._pushToHistory(this.current, false); this._pushToHistory(previousParams, false); this.currentUid = state.uid; window.history.back(); return; } } this.historyUnlocked = false; if (state.target.dest) { this.linkService.navigateTo(state.target.dest); } else { this.linkService.setHash(state.target.hash); } this.currentUid = state.uid; if (state.uid > this.uid) { this.uid = state.uid; } this.current = state.target; this.updatePreviousBookmark = true; var currentHash = window.location.hash.substring(1); if (this.previousHash !== currentHash) { this.allowHashChange = false; } this.previousHash = currentHash; this.historyUnlocked = true; }, back: function pdfHistoryBack() { this.go(-1); }, forward: function pdfHistoryForward() { this.go(1); }, go: function pdfHistoryGo(direction) { if (this.initialized && this.historyUnlocked) { var state = window.history.state; if (direction === -1 && state && state.uid > 0) { window.history.back(); } else if (direction === 1 && state && state.uid < this.uid - 1) { window.history.forward(); } } } }; exports.PDFHistory = PDFHistory; })); (function (root, factory) { factory(root.pdfjsWebPDFLinkService = {}, root.pdfjsWebUIUtils, root.pdfjsWebDOMEvents); }(this, function (exports, uiUtils, domEvents) { var parseQueryString = uiUtils.parseQueryString; var PageNumberRegExp = /^\d+$/; function isPageNumber(str) { return PageNumberRegExp.test(str); } var PDFLinkService = function PDFLinkServiceClosure() { function PDFLinkService(options) { options = options || {}; this.eventBus = options.eventBus || domEvents.getGlobalEventBus(); this.baseUrl = null; this.pdfDocument = null; this.pdfViewer = null; this.pdfHistory = null; this._pagesRefCache = null; } PDFLinkService.prototype = { setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) { this.baseUrl = baseUrl; this.pdfDocument = pdfDocument; this._pagesRefCache = Object.create(null); }, setViewer: function PDFLinkService_setViewer(pdfViewer) { this.pdfViewer = pdfViewer; }, setHistory: function PDFLinkService_setHistory(pdfHistory) { this.pdfHistory = pdfHistory; }, get pagesCount() { return this.pdfDocument ? this.pdfDocument.numPages : 0; }, get page() { return this.pdfViewer.currentPageNumber; }, set page(value) { this.pdfViewer.currentPageNumber = value; }, navigateTo: function PDFLinkService_navigateTo(dest) { var destString = ''; var self = this; var goToDestination = function (destRef) { var pageNumber; if (destRef instanceof Object) { pageNumber = self._cachedPageNumber(destRef); } else if ((destRef | 0) === destRef) { pageNumber = destRef + 1; } else { console.error('PDFLinkService_navigateTo: "' + destRef + '" is not a valid destination reference.'); return; } if (pageNumber) { if (pageNumber < 1 || pageNumber > self.pagesCount) { console.error('PDFLinkService_navigateTo: "' + pageNumber + '" is a non-existent page number.'); return; } self.pdfViewer.scrollPageIntoView({ pageNumber: pageNumber, destArray: dest }); if (self.pdfHistory) { self.pdfHistory.push({ dest: dest, hash: destString, page: pageNumber }); } } else { self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) { self.cachePageRef(pageIndex + 1, destRef); goToDestination(destRef); }).catch(function () { console.error('PDFLinkService_navigateTo: "' + destRef + '" is not a valid page reference.'); return; }); } }; var destinationPromise; if (typeof dest === 'string') { destString = dest; destinationPromise = this.pdfDocument.getDestination(dest); } else { destinationPromise = Promise.resolve(dest); } destinationPromise.then(function (destination) { dest = destination; if (!(destination instanceof Array)) { console.error('PDFLinkService_navigateTo: "' + destination + '" is not a valid destination array.'); return; } goToDestination(destination[0]); }); }, getDestinationHash: function PDFLinkService_getDestinationHash(dest) { if (typeof dest === 'string') { return this.getAnchorUrl('#' + (isPageNumber(dest) ? 'nameddest=' : '') + escape(dest)); } if (dest instanceof Array) { var str = JSON.stringify(dest); return this.getAnchorUrl('#' + escape(str)); } return this.getAnchorUrl(''); }, getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) { return (this.baseUrl || '') + anchor; }, setHash: function PDFLinkService_setHash(hash) { var pageNumber, dest; if (hash.indexOf('=') >= 0) { var params = parseQueryString(hash); if ('search' in params) { this.eventBus.dispatch('findfromurlhash', { source: this, query: params['search'].replace(/"/g, ''), phraseSearch: params['phrase'] === 'true' }); } if ('nameddest' in params) { if (this.pdfHistory) { this.pdfHistory.updateNextHashParam(params.nameddest); } this.navigateTo(params.nameddest); return; } if ('page' in params) { pageNumber = params.page | 0 || 1; } if ('zoom' in params) { var zoomArgs = params.zoom.split(','); var zoomArg = zoomArgs[0]; var zoomArgNumber = parseFloat(zoomArg); if (zoomArg.indexOf('Fit') === -1) { dest = [ null, { name: 'XYZ' }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null, zoomArgs.length > 2 ? zoomArgs[2] | 0 : null, zoomArgNumber ? zoomArgNumber / 100 : zoomArg ]; } else { if (zoomArg === 'Fit' || zoomArg === 'FitB') { dest = [ null, { name: zoomArg } ]; } else if (zoomArg === 'FitH' || zoomArg === 'FitBH' || (zoomArg === 'FitV' || zoomArg === 'FitBV')) { dest = [ null, { name: zoomArg }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null ]; } else if (zoomArg === 'FitR') { if (zoomArgs.length !== 5) { console.error('PDFLinkService_setHash: ' + 'Not enough parameters for \'FitR\'.'); } else { dest = [ null, { name: zoomArg }, zoomArgs[1] | 0, zoomArgs[2] | 0, zoomArgs[3] | 0, zoomArgs[4] | 0 ]; } } else { console.error('PDFLinkService_setHash: \'' + zoomArg + '\' is not a valid zoom value.'); } } } if (dest) { this.pdfViewer.scrollPageIntoView({ pageNumber: pageNumber || this.page, destArray: dest, allowNegativeOffset: true }); } else if (pageNumber) { this.page = pageNumber; } if ('pagemode' in params) { this.eventBus.dispatch('pagemode', { source: this, mode: params.pagemode }); } } else { if (isPageNumber(hash) && hash <= this.pagesCount) { console.warn('PDFLinkService_setHash: specifying a page number ' + 'directly after the hash symbol (#) is deprecated, ' + 'please use the "#page=' + hash + '" form instead.'); this.page = hash | 0; } dest = unescape(hash); try { dest = JSON.parse(dest); if (!(dest instanceof Array)) { dest = dest.toString(); } } catch (ex) { } if (typeof dest === 'string' || isValidExplicitDestination(dest)) { if (this.pdfHistory) { this.pdfHistory.updateNextHashParam(dest); } this.navigateTo(dest); return; } console.error('PDFLinkService_setHash: \'' + unescape(hash) + '\' is not a valid destination.'); } }, executeNamedAction: function PDFLinkService_executeNamedAction(action) { switch (action) { case 'GoBack': if (this.pdfHistory) { this.pdfHistory.back(); } break; case 'GoForward': if (this.pdfHistory) { this.pdfHistory.forward(); } break; case 'NextPage': if (this.page < this.pagesCount) { this.page++; } break; case 'PrevPage': if (this.page > 1) { this.page--; } break; case 'LastPage': this.page = this.pagesCount; break; case 'FirstPage': this.page = 1; break; default: break; } this.eventBus.dispatch('namedaction', { source: this, action: action }); }, cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) { var refStr = pageRef.num + ' ' + pageRef.gen + ' R'; this._pagesRefCache[refStr] = pageNum; }, _cachedPageNumber: function PDFLinkService_cachedPageNumber(pageRef) { var refStr = pageRef.num + ' ' + pageRef.gen + ' R'; return this._pagesRefCache && this._pagesRefCache[refStr] || null; } }; function isValidExplicitDestination(dest) { if (!(dest instanceof Array)) { return false; } var destLength = dest.length, allowNull = true; if (destLength < 2) { return false; } var page = dest[0]; if (!(typeof page === 'object' && typeof page.num === 'number' && (page.num | 0) === page.num && typeof page.gen === 'number' && (page.gen | 0) === page.gen) && !(typeof page === 'number' && (page | 0) === page && page >= 0)) { return false; } var zoom = dest[1]; if (!(typeof zoom === 'object' && typeof zoom.name === 'string')) { return false; } switch (zoom.name) { case 'XYZ': if (destLength !== 5) { return false; } break; case 'Fit': case 'FitB': return destLength === 2; case 'FitH': case 'FitBH': case 'FitV': case 'FitBV': if (destLength !== 3) { return false; } break; case 'FitR': if (destLength !== 6) { return false; } allowNull = false; break; default: return false; } for (var i = 2; i < destLength; i++) { var param = dest[i]; if (!(typeof param === 'number' || allowNull && param === null)) { return false; } } return true; } return PDFLinkService; }(); var SimpleLinkService = function SimpleLinkServiceClosure() { function SimpleLinkService() { } SimpleLinkService.prototype = { get page() { return 0; }, set page(value) { }, navigateTo: function (dest) { }, getDestinationHash: function (dest) { return '#'; }, getAnchorUrl: function (hash) { return '#'; }, setHash: function (hash) { }, executeNamedAction: function (action) { }, cachePageRef: function (pageNum, pageRef) { } }; return SimpleLinkService; }(); exports.PDFLinkService = PDFLinkService; exports.SimpleLinkService = SimpleLinkService; })); (function (root, factory) { factory(root.pdfjsWebPDFPageView = {}, root.pdfjsWebUIUtils, root.pdfjsWebPDFRenderingQueue, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS); }(this, function (exports, uiUtils, pdfRenderingQueue, domEvents, pdfjsLib) { var CSS_UNITS = uiUtils.CSS_UNITS; var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE; var getOutputScale = uiUtils.getOutputScale; var approximateFraction = uiUtils.approximateFraction; var roundToDivide = uiUtils.roundToDivide; var RenderingStates = pdfRenderingQueue.RenderingStates; var TEXT_LAYER_RENDER_DELAY = 200; var PDFPageView = function PDFPageViewClosure() { function PDFPageView(options) { var container = options.container; var id = options.id; var scale = options.scale; var defaultViewport = options.defaultViewport; var renderingQueue = options.renderingQueue; var textLayerFactory = options.textLayerFactory; var annotationLayerFactory = options.annotationLayerFactory; var enhanceTextSelection = options.enhanceTextSelection || false; var renderInteractiveForms = options.renderInteractiveForms || false; this.id = id; this.renderingId = 'page' + id; this.pageLabel = null; this.rotation = 0; this.scale = scale || DEFAULT_SCALE; this.viewport = defaultViewport; this.pdfPageRotate = defaultViewport.rotation; this.hasRestrictedScaling = false; this.enhanceTextSelection = enhanceTextSelection; this.renderInteractiveForms = renderInteractiveForms; this.eventBus = options.eventBus || domEvents.getGlobalEventBus(); this.renderingQueue = renderingQueue; this.textLayerFactory = textLayerFactory; this.annotationLayerFactory = annotationLayerFactory; this.renderTask = null; this.renderingState = RenderingStates.INITIAL; this.resume = null; this.onBeforeDraw = null; this.onAfterDraw = null; this.textLayer = null; this.zoomLayer = null; this.annotationLayer = null; var div = document.createElement('div'); div.id = 'pageContainer' + this.id; div.className = 'page'; div.style.width = Math.floor(this.viewport.width) + 'px'; div.style.height = Math.floor(this.viewport.height) + 'px'; div.setAttribute('data-page-number', this.id); this.div = div; container.appendChild(div); } PDFPageView.prototype = { setPdfPage: function PDFPageView_setPdfPage(pdfPage) { this.pdfPage = pdfPage; this.pdfPageRotate = pdfPage.rotate; var totalRotation = (this.rotation + this.pdfPageRotate) % 360; this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS, totalRotation); this.stats = pdfPage.stats; this.reset(); }, destroy: function PDFPageView_destroy() { this.zoomLayer = null; this.reset(); if (this.pdfPage) { this.pdfPage.cleanup(); } }, reset: function PDFPageView_reset(keepZoomLayer, keepAnnotations) { this.cancelRendering(); var div = this.div; div.style.width = Math.floor(this.viewport.width) + 'px'; div.style.height = Math.floor(this.viewport.height) + 'px'; var childNodes = div.childNodes; var currentZoomLayerNode = keepZoomLayer && this.zoomLayer || null; var currentAnnotationNode = keepAnnotations && this.annotationLayer && this.annotationLayer.div || null; for (var i = childNodes.length - 1; i >= 0; i--) { var node = childNodes[i]; if (currentZoomLayerNode === node || currentAnnotationNode === node) { continue; } div.removeChild(node); } div.removeAttribute('data-loaded'); if (currentAnnotationNode) { this.annotationLayer.hide(); } else { this.annotationLayer = null; } if (this.canvas && !currentZoomLayerNode) { this.canvas.width = 0; this.canvas.height = 0; delete this.canvas; } this.loadingIconDiv = document.createElement('div'); this.loadingIconDiv.className = 'loadingIcon'; div.appendChild(this.loadingIconDiv); }, update: function PDFPageView_update(scale, rotation) { this.scale = scale || this.scale; if (typeof rotation !== 'undefined') { this.rotation = rotation; } var totalRotation = (this.rotation + this.pdfPageRotate) % 360; this.viewport = this.viewport.clone({ scale: this.scale * CSS_UNITS, rotation: totalRotation }); var isScalingRestricted = false; if (this.canvas && pdfjsLib.PDFJS.maxCanvasPixels > 0) { var outputScale = this.outputScale; if ((Math.floor(this.viewport.width) * outputScale.sx | 0) * (Math.floor(this.viewport.height) * outputScale.sy | 0) > pdfjsLib.PDFJS.maxCanvasPixels) { isScalingRestricted = true; } } if (this.canvas) { if (pdfjsLib.PDFJS.useOnlyCssZoom || this.hasRestrictedScaling && isScalingRestricted) { this.cssTransform(this.canvas, true); this.eventBus.dispatch('pagerendered', { source: this, pageNumber: this.id, cssTransform: true }); return; } if (!this.zoomLayer) { this.zoomLayer = this.canvas.parentNode; this.zoomLayer.style.position = 'absolute'; } } if (this.zoomLayer) { this.cssTransform(this.zoomLayer.firstChild); } this.reset(true, true); }, cancelRendering: function PDFPageView_cancelRendering() { if (this.renderTask) { this.renderTask.cancel(); this.renderTask = null; } this.renderingState = RenderingStates.INITIAL; this.resume = null; if (this.textLayer) { this.textLayer.cancel(); this.textLayer = null; } }, updatePosition: function PDFPageView_updatePosition() { if (this.textLayer) { this.textLayer.render(TEXT_LAYER_RENDER_DELAY); } }, cssTransform: function PDFPageView_transform(canvas, redrawAnnotations) { var CustomStyle = pdfjsLib.CustomStyle; var width = this.viewport.width; var height = this.viewport.height; var div = this.div; canvas.style.width = canvas.parentNode.style.width = div.style.width = Math.floor(width) + 'px'; canvas.style.height = canvas.parentNode.style.height = div.style.height = Math.floor(height) + 'px'; var relativeRotation = this.viewport.rotation - canvas._viewport.rotation; var absRotation = Math.abs(relativeRotation); var scaleX = 1, scaleY = 1; if (absRotation === 90 || absRotation === 270) { scaleX = height / width; scaleY = width / height; } var cssTransform = 'rotate(' + relativeRotation + 'deg) ' + 'scale(' + scaleX + ',' + scaleY + ')'; CustomStyle.setProp('transform', canvas, cssTransform); if (this.textLayer) { var textLayerViewport = this.textLayer.viewport; var textRelativeRotation = this.viewport.rotation - textLayerViewport.rotation; var textAbsRotation = Math.abs(textRelativeRotation); var scale = width / textLayerViewport.width; if (textAbsRotation === 90 || textAbsRotation === 270) { scale = width / textLayerViewport.height; } var textLayerDiv = this.textLayer.textLayerDiv; var transX, transY; switch (textAbsRotation) { case 0: transX = transY = 0; break; case 90: transX = 0; transY = '-' + textLayerDiv.style.height; break; case 180: transX = '-' + textLayerDiv.style.width; transY = '-' + textLayerDiv.style.height; break; case 270: transX = '-' + textLayerDiv.style.width; transY = 0; break; default: console.error('Bad rotation value.'); break; } CustomStyle.setProp('transform', textLayerDiv, 'rotate(' + textAbsRotation + 'deg) ' + 'scale(' + scale + ', ' + scale + ') ' + 'translate(' + transX + ', ' + transY + ')'); CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%'); } if (redrawAnnotations && this.annotationLayer) { this.annotationLayer.render(this.viewport, 'display'); } }, get width() { return this.viewport.width; }, get height() { return this.viewport.height; }, getPagePoint: function PDFPageView_getPagePoint(x, y) { return this.viewport.convertToPdfPoint(x, y); }, draw: function PDFPageView_draw() { if (this.renderingState !== RenderingStates.INITIAL) { console.error('Must be in new state before drawing'); this.reset(); } this.renderingState = RenderingStates.RUNNING; var pdfPage = this.pdfPage; var viewport = this.viewport; var div = this.div; var canvasWrapper = document.createElement('div'); canvasWrapper.style.width = div.style.width; canvasWrapper.style.height = div.style.height; canvasWrapper.classList.add('canvasWrapper'); var canvas = document.createElement('canvas'); canvas.id = 'page' + this.id; canvas.setAttribute('hidden', 'hidden'); var isCanvasHidden = true; canvasWrapper.appendChild(canvas); if (this.annotationLayer && this.annotationLayer.div) { div.insertBefore(canvasWrapper, this.annotationLayer.div); } else { div.appendChild(canvasWrapper); } this.canvas = canvas; canvas.mozOpaque = true; var ctx = canvas.getContext('2d', { alpha: false }); var outputScale = getOutputScale(ctx); this.outputScale = outputScale; if (pdfjsLib.PDFJS.useOnlyCssZoom) { var actualSizeViewport = viewport.clone({ scale: CSS_UNITS }); outputScale.sx *= actualSizeViewport.width / viewport.width; outputScale.sy *= actualSizeViewport.height / viewport.height; outputScale.scaled = true; } if (pdfjsLib.PDFJS.maxCanvasPixels > 0) { var pixelsInViewport = viewport.width * viewport.height; var maxScale = Math.sqrt(pdfjsLib.PDFJS.maxCanvasPixels / pixelsInViewport); if (outputScale.sx > maxScale || outputScale.sy > maxScale) { outputScale.sx = maxScale; outputScale.sy = maxScale; outputScale.scaled = true; this.hasRestrictedScaling = true; } else { this.hasRestrictedScaling = false; } } var sfx = approximateFraction(outputScale.sx); var sfy = approximateFraction(outputScale.sy); canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]); canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]); canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px'; canvas.style.height = roundToDivide(viewport.height, sfy[1]) + 'px'; canvas._viewport = viewport; var textLayerDiv = null; var textLayer = null; if (this.textLayerFactory) { textLayerDiv = document.createElement('div'); textLayerDiv.className = 'textLayer'; textLayerDiv.style.width = canvasWrapper.style.width; textLayerDiv.style.height = canvasWrapper.style.height; if (this.annotationLayer && this.annotationLayer.div) { div.insertBefore(textLayerDiv, this.annotationLayer.div); } else { div.appendChild(textLayerDiv); } textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv, this.id - 1, this.viewport, this.enhanceTextSelection); } this.textLayer = textLayer; var resolveRenderPromise, rejectRenderPromise; var promise = new Promise(function (resolve, reject) { resolveRenderPromise = resolve; rejectRenderPromise = reject; }); var self = this; function pageViewDrawCallback(error) { if (renderTask === self.renderTask) { self.renderTask = null; } if (error === 'cancelled') { rejectRenderPromise(error); return; } self.renderingState = RenderingStates.FINISHED; if (isCanvasHidden) { self.canvas.removeAttribute('hidden'); isCanvasHidden = false; } if (self.loadingIconDiv) { div.removeChild(self.loadingIconDiv); delete self.loadingIconDiv; } if (self.zoomLayer) { var zoomLayerCanvas = self.zoomLayer.firstChild; zoomLayerCanvas.width = 0; zoomLayerCanvas.height = 0; if (div.contains(self.zoomLayer)) { div.removeChild(self.zoomLayer); } self.zoomLayer = null; } self.error = error; self.stats = pdfPage.stats; if (self.onAfterDraw) { self.onAfterDraw(); } self.eventBus.dispatch('pagerendered', { source: self, pageNumber: self.id, cssTransform: false }); if (!error) { resolveRenderPromise(undefined); } else { rejectRenderPromise(error); } } var renderContinueCallback = null; if (this.renderingQueue) { renderContinueCallback = function renderContinueCallback(cont) { if (!self.renderingQueue.isHighestPriority(self)) { self.renderingState = RenderingStates.PAUSED; self.resume = function resumeCallback() { self.renderingState = RenderingStates.RUNNING; cont(); }; return; } if (isCanvasHidden) { self.canvas.removeAttribute('hidden'); isCanvasHidden = false; } cont(); }; } var transform = !outputScale.scaled ? null : [ outputScale.sx, 0, 0, outputScale.sy, 0, 0 ]; var renderContext = { canvasContext: ctx, transform: transform, viewport: this.viewport, renderInteractiveForms: this.renderInteractiveForms }; var renderTask = this.renderTask = this.pdfPage.render(renderContext); renderTask.onContinue = renderContinueCallback; this.renderTask.promise.then(function pdfPageRenderCallback() { pageViewDrawCallback(null); if (textLayer) { self.pdfPage.getTextContent({ normalizeWhitespace: true }).then(function textContentResolved(textContent) { textLayer.setTextContent(textContent); textLayer.render(TEXT_LAYER_RENDER_DELAY); }); } }, function pdfPageRenderError(error) { pageViewDrawCallback(error); }); if (this.annotationLayerFactory) { if (!this.annotationLayer) { this.annotationLayer = this.annotationLayerFactory.createAnnotationLayerBuilder(div, this.pdfPage, this.renderInteractiveForms); } this.annotationLayer.render(this.viewport, 'display'); } div.setAttribute('data-loaded', true); if (self.onBeforeDraw) { self.onBeforeDraw(); } return promise; }, setPageLabel: function PDFView_setPageLabel(label) { this.pageLabel = typeof label === 'string' ? label : null; if (this.pageLabel !== null) { this.div.setAttribute('data-page-label', this.pageLabel); } else { this.div.removeAttribute('data-page-label'); } } }; return PDFPageView; }(); exports.PDFPageView = PDFPageView; })); (function (root, factory) { factory(root.pdfjsWebTextLayerBuilder = {}, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS); }(this, function (exports, domEvents, pdfjsLib) { var EXPAND_DIVS_TIMEOUT = 300; var TextLayerBuilder = function TextLayerBuilderClosure() { function TextLayerBuilder(options) { this.textLayerDiv = options.textLayerDiv; this.eventBus = options.eventBus || domEvents.getGlobalEventBus(); this.textContent = null; this.renderingDone = false; this.pageIdx = options.pageIndex; this.pageNumber = this.pageIdx + 1; this.matches = []; this.viewport = options.viewport; this.textDivs = []; this.findController = options.findController || null; this.textLayerRenderTask = null; this.enhanceTextSelection = options.enhanceTextSelection; this._bindMouse(); } TextLayerBuilder.prototype = { _finishRendering: function TextLayerBuilder_finishRendering() { this.renderingDone = true; if (!this.enhanceTextSelection) { var endOfContent = document.createElement('div'); endOfContent.className = 'endOfContent'; this.textLayerDiv.appendChild(endOfContent); } this.eventBus.dispatch('textlayerrendered', { source: this, pageNumber: this.pageNumber, numTextDivs: this.textDivs.length }); }, render: function TextLayerBuilder_render(timeout) { if (!this.textContent || this.renderingDone) { return; } this.cancel(); this.textDivs = []; var textLayerFrag = document.createDocumentFragment(); this.textLayerRenderTask = pdfjsLib.renderTextLayer({ textContent: this.textContent, container: textLayerFrag, viewport: this.viewport, textDivs: this.textDivs, timeout: timeout, enhanceTextSelection: this.enhanceTextSelection }); this.textLayerRenderTask.promise.then(function () { this.textLayerDiv.appendChild(textLayerFrag); this._finishRendering(); this.updateMatches(); }.bind(this), function (reason) { }); }, cancel: function TextLayerBuilder_cancel() { if (this.textLayerRenderTask) { this.textLayerRenderTask.cancel(); this.textLayerRenderTask = null; } }, setTextContent: function TextLayerBuilder_setTextContent(textContent) { this.cancel(); this.textContent = textContent; }, convertMatches: function TextLayerBuilder_convertMatches(matches, matchesLength) { var i = 0; var iIndex = 0; var bidiTexts = this.textContent.items; var end = bidiTexts.length - 1; var queryLen = this.findController === null ? 0 : this.findController.state.query.length; var ret = []; if (!matches) { return ret; } for (var m = 0, len = matches.length; m < len; m++) { var matchIdx = matches[m]; while (i !== end && matchIdx >= iIndex + bidiTexts[i].str.length) { iIndex += bidiTexts[i].str.length; i++; } if (i === bidiTexts.length) { console.error('Could not find a matching mapping'); } var match = { begin: { divIdx: i, offset: matchIdx - iIndex } }; if (matchesLength) { matchIdx += matchesLength[m]; } else { matchIdx += queryLen; } while (i !== end && matchIdx > iIndex + bidiTexts[i].str.length) { iIndex += bidiTexts[i].str.length; i++; } match.end = { divIdx: i, offset: matchIdx - iIndex }; ret.push(match); } return ret; }, renderMatches: function TextLayerBuilder_renderMatches(matches) { if (matches.length === 0) { return; } var bidiTexts = this.textContent.items; var textDivs = this.textDivs; var prevEnd = null; var pageIdx = this.pageIdx; var isSelectedPage = this.findController === null ? false : pageIdx === this.findController.selected.pageIdx; var selectedMatchIdx = this.findController === null ? -1 : this.findController.selected.matchIdx; var highlightAll = this.findController === null ? false : this.findController.state.highlightAll; var infinity = { divIdx: -1, offset: undefined }; function beginText(begin, className) { var divIdx = begin.divIdx; textDivs[divIdx].textContent = ''; appendTextToDiv(divIdx, 0, begin.offset, className); } function appendTextToDiv(divIdx, fromOffset, toOffset, className) { var div = textDivs[divIdx]; var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset); var node = document.createTextNode(content); if (className) { var span = document.createElement('span'); span.className = className; span.appendChild(node); div.appendChild(span); return; } div.appendChild(node); } var i0 = selectedMatchIdx, i1 = i0 + 1; if (highlightAll) { i0 = 0; i1 = matches.length; } else if (!isSelectedPage) { return; } for (var i = i0; i < i1; i++) { var match = matches[i]; var begin = match.begin; var end = match.end; var isSelected = isSelectedPage && i === selectedMatchIdx; var highlightSuffix = isSelected ? ' selected' : ''; if (this.findController) { this.findController.updateMatchPosition(pageIdx, i, textDivs, begin.divIdx); } if (!prevEnd || begin.divIdx !== prevEnd.divIdx) { if (prevEnd !== null) { appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); } beginText(begin); } else { appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset); } if (begin.divIdx === end.divIdx) { appendTextToDiv(begin.divIdx, begin.offset, end.offset, 'highlight' + highlightSuffix); } else { appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, 'highlight begin' + highlightSuffix); for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) { textDivs[n0].className = 'highlight middle' + highlightSuffix; } beginText(end, 'highlight end' + highlightSuffix); } prevEnd = end; } if (prevEnd) { appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); } }, updateMatches: function TextLayerBuilder_updateMatches() { if (!this.renderingDone) { return; } var matches = this.matches; var textDivs = this.textDivs; var bidiTexts = this.textContent.items; var clearedUntilDivIdx = -1; for (var i = 0, len = matches.length; i < len; i++) { var match = matches[i]; var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx); for (var n = begin, end = match.end.divIdx; n <= end; n++) { var div = textDivs[n]; div.textContent = bidiTexts[n].str; div.className = ''; } clearedUntilDivIdx = match.end.divIdx + 1; } if (this.findController === null || !this.findController.active) { return; } var pageMatches, pageMatchesLength; if (this.findController !== null) { pageMatches = this.findController.pageMatches[this.pageIdx] || null; pageMatchesLength = this.findController.pageMatchesLength ? this.findController.pageMatchesLength[this.pageIdx] || null : null; } this.matches = this.convertMatches(pageMatches, pageMatchesLength); this.renderMatches(this.matches); }, _bindMouse: function TextLayerBuilder_bindMouse() { var div = this.textLayerDiv; var self = this; var expandDivsTimer = null; div.addEventListener('mousedown', function (e) { if (self.enhanceTextSelection && self.textLayerRenderTask) { self.textLayerRenderTask.expandTextDivs(true); if (expandDivsTimer) { clearTimeout(expandDivsTimer); expandDivsTimer = null; } return; } var end = div.querySelector('.endOfContent'); if (!end) { return; } var adjustTop = e.target !== div; adjustTop = adjustTop && window.getComputedStyle(end).getPropertyValue('-moz-user-select') !== 'none'; if (adjustTop) { var divBounds = div.getBoundingClientRect(); var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height); end.style.top = (r * 100).toFixed(2) + '%'; } end.classList.add('active'); }); div.addEventListener('mouseup', function (e) { if (self.enhanceTextSelection && self.textLayerRenderTask) { expandDivsTimer = setTimeout(function () { if (self.textLayerRenderTask) { self.textLayerRenderTask.expandTextDivs(false); } expandDivsTimer = null; }, EXPAND_DIVS_TIMEOUT); return; } var end = div.querySelector('.endOfContent'); if (!end) { return; } end.style.top = ''; end.classList.remove('active'); }); } }; return TextLayerBuilder; }(); function DefaultTextLayerFactory() { } DefaultTextLayerFactory.prototype = { createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport, enhanceTextSelection) { return new TextLayerBuilder({ textLayerDiv: textLayerDiv, pageIndex: pageIndex, viewport: viewport, enhanceTextSelection: enhanceTextSelection }); } }; exports.TextLayerBuilder = TextLayerBuilder; exports.DefaultTextLayerFactory = DefaultTextLayerFactory; })); (function (root, factory) { factory(root.pdfjsWebAnnotationLayerBuilder = {}, root.pdfjsWebUIUtils, root.pdfjsWebPDFLinkService, root.pdfjsWebPDFJS); }(this, function (exports, uiUtils, pdfLinkService, pdfjsLib) { var mozL10n = uiUtils.mozL10n; var SimpleLinkService = pdfLinkService.SimpleLinkService; var AnnotationLayerBuilder = function AnnotationLayerBuilderClosure() { function AnnotationLayerBuilder(options) { this.pageDiv = options.pageDiv; this.pdfPage = options.pdfPage; this.renderInteractiveForms = options.renderInteractiveForms; this.linkService = options.linkService; this.downloadManager = options.downloadManager; this.div = null; } AnnotationLayerBuilder.prototype = { render: function AnnotationLayerBuilder_render(viewport, intent) { var self = this; var parameters = { intent: intent === undefined ? 'display' : intent }; this.pdfPage.getAnnotations(parameters).then(function (annotations) { viewport = viewport.clone({ dontFlip: true }); parameters = { viewport: viewport, div: self.div, annotations: annotations, page: self.pdfPage, renderInteractiveForms: self.renderInteractiveForms, linkService: self.linkService, downloadManager: self.downloadManager }; if (self.div) { pdfjsLib.AnnotationLayer.update(parameters); } else { if (annotations.length === 0) { return; } self.div = document.createElement('div'); self.div.className = 'annotationLayer'; self.pageDiv.appendChild(self.div); parameters.div = self.div; pdfjsLib.AnnotationLayer.render(parameters); if (typeof mozL10n !== 'undefined') { mozL10n.translate(self.div); } } }); }, hide: function AnnotationLayerBuilder_hide() { if (!this.div) { return; } this.div.setAttribute('hidden', 'true'); } }; return AnnotationLayerBuilder; }(); function DefaultAnnotationLayerFactory() { } DefaultAnnotationLayerFactory.prototype = { createAnnotationLayerBuilder: function (pageDiv, pdfPage, renderInteractiveForms) { return new AnnotationLayerBuilder({ pageDiv: pageDiv, pdfPage: pdfPage, renderInteractiveForms: renderInteractiveForms, linkService: new SimpleLinkService() }); } }; exports.AnnotationLayerBuilder = AnnotationLayerBuilder; exports.DefaultAnnotationLayerFactory = DefaultAnnotationLayerFactory; })); (function (root, factory) { factory(root.pdfjsWebPDFViewer = {}, root.pdfjsWebUIUtils, root.pdfjsWebPDFPageView, root.pdfjsWebPDFRenderingQueue, root.pdfjsWebTextLayerBuilder, root.pdfjsWebAnnotationLayerBuilder, root.pdfjsWebPDFLinkService, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS); }(this, function (exports, uiUtils, pdfPageView, pdfRenderingQueue, textLayerBuilder, annotationLayerBuilder, pdfLinkService, domEvents, pdfjsLib) { var UNKNOWN_SCALE = uiUtils.UNKNOWN_SCALE; var SCROLLBAR_PADDING = uiUtils.SCROLLBAR_PADDING; var VERTICAL_PADDING = uiUtils.VERTICAL_PADDING; var MAX_AUTO_SCALE = uiUtils.MAX_AUTO_SCALE; var CSS_UNITS = uiUtils.CSS_UNITS; var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE; var DEFAULT_SCALE_VALUE = uiUtils.DEFAULT_SCALE_VALUE; var scrollIntoView = uiUtils.scrollIntoView; var watchScroll = uiUtils.watchScroll; var getVisibleElements = uiUtils.getVisibleElements; var PDFPageView = pdfPageView.PDFPageView; var RenderingStates = pdfRenderingQueue.RenderingStates; var PDFRenderingQueue = pdfRenderingQueue.PDFRenderingQueue; var TextLayerBuilder = textLayerBuilder.TextLayerBuilder; var AnnotationLayerBuilder = annotationLayerBuilder.AnnotationLayerBuilder; var SimpleLinkService = pdfLinkService.SimpleLinkService; var PresentationModeState = { UNKNOWN: 0, NORMAL: 1, CHANGING: 2, FULLSCREEN: 3 }; var DEFAULT_CACHE_SIZE = 10; var PDFViewer = function pdfViewer() { function PDFPageViewBuffer(size) { var data = []; this.push = function cachePush(view) { var i = data.indexOf(view); if (i >= 0) { data.splice(i, 1); } data.push(view); if (data.length > size) { data.shift().destroy(); } }; this.resize = function (newSize) { size = newSize; while (data.length > size) { data.shift().destroy(); } }; } function isSameScale(oldScale, newScale) { if (newScale === oldScale) { return true; } if (Math.abs(newScale - oldScale) < 1e-15) { return true; } return false; } function PDFViewer(options) { this.container = options.container; this.viewer = options.viewer || options.container.firstElementChild; this.eventBus = options.eventBus || domEvents.getGlobalEventBus(); this.linkService = options.linkService || new SimpleLinkService(); this.downloadManager = options.downloadManager || null; this.removePageBorders = options.removePageBorders || false; this.enhanceTextSelection = options.enhanceTextSelection || false; this.renderInteractiveForms = options.renderInteractiveForms || false; this.defaultRenderingQueue = !options.renderingQueue; if (this.defaultRenderingQueue) { this.renderingQueue = new PDFRenderingQueue(); this.renderingQueue.setViewer(this); } else { this.renderingQueue = options.renderingQueue; } this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this)); this.presentationModeState = PresentationModeState.UNKNOWN; this._resetView(); if (this.removePageBorders) { this.viewer.classList.add('removePageBorders'); } } PDFViewer.prototype = { get pagesCount() { return this._pages.length; }, getPageView: function (index) { return this._pages[index]; }, get pageViewsReady() { return this._pageViewsReady; }, get currentPageNumber() { return this._currentPageNumber; }, set currentPageNumber(val) { if ((val | 0) !== val) { throw new Error('Invalid page number.'); } if (!this.pdfDocument) { this._currentPageNumber = val; return; } this._setCurrentPageNumber(val, true); }, _setCurrentPageNumber: function PDFViewer_setCurrentPageNumber(val, resetCurrentPageView) { if (this._currentPageNumber === val) { if (resetCurrentPageView) { this._resetCurrentPageView(); } return; } if (!(0 < val && val <= this.pagesCount)) { console.error('PDFViewer_setCurrentPageNumber: "' + val + '" is out of bounds.'); return; } var arg = { source: this, pageNumber: val, pageLabel: this._pageLabels && this._pageLabels[val - 1] }; this._currentPageNumber = val; this.eventBus.dispatch('pagechanging', arg); this.eventBus.dispatch('pagechange', arg); if (resetCurrentPageView) { this._resetCurrentPageView(); } }, get currentPageLabel() { return this._pageLabels && this._pageLabels[this._currentPageNumber - 1]; }, set currentPageLabel(val) { var pageNumber = val | 0; if (this._pageLabels) { var i = this._pageLabels.indexOf(val); if (i >= 0) { pageNumber = i + 1; } } this.currentPageNumber = pageNumber; }, get currentScale() { return this._currentScale !== UNKNOWN_SCALE ? this._currentScale : DEFAULT_SCALE; }, set currentScale(val) { if (isNaN(val)) { throw new Error('Invalid numeric scale'); } if (!this.pdfDocument) { this._currentScale = val; this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null; return; } this._setScale(val, false); }, get currentScaleValue() { return this._currentScaleValue; }, set currentScaleValue(val) { if (!this.pdfDocument) { this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val; this._currentScaleValue = val.toString(); return; } this._setScale(val, false); }, get pagesRotation() { return this._pagesRotation; }, set pagesRotation(rotation) { if (!(typeof rotation === 'number' && rotation % 90 === 0)) { throw new Error('Invalid pages rotation angle.'); } this._pagesRotation = rotation; if (!this.pdfDocument) { return; } for (var i = 0, l = this._pages.length; i < l; i++) { var pageView = this._pages[i]; pageView.update(pageView.scale, rotation); } this._setScale(this._currentScaleValue, true); if (this.defaultRenderingQueue) { this.update(); } }, setDocument: function (pdfDocument) { if (this.pdfDocument) { this._cancelRendering(); this._resetView(); } this.pdfDocument = pdfDocument; if (!pdfDocument) { return; } var pagesCount = pdfDocument.numPages; var self = this; var resolvePagesPromise; var pagesPromise = new Promise(function (resolve) { resolvePagesPromise = resolve; }); this.pagesPromise = pagesPromise; pagesPromise.then(function () { self._pageViewsReady = true; self.eventBus.dispatch('pagesloaded', { source: self, pagesCount: pagesCount }); }); var isOnePageRenderedResolved = false; var resolveOnePageRendered = null; var onePageRendered = new Promise(function (resolve) { resolveOnePageRendered = resolve; }); this.onePageRendered = onePageRendered; var bindOnAfterAndBeforeDraw = function (pageView) { pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() { self._buffer.push(this); }; pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() { if (!isOnePageRenderedResolved) { isOnePageRenderedResolved = true; resolveOnePageRendered(); } }; }; var firstPagePromise = pdfDocument.getPage(1); this.firstPagePromise = firstPagePromise; return firstPagePromise.then(function (pdfPage) { var scale = this.currentScale; var viewport = pdfPage.getViewport(scale * CSS_UNITS); for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) { var textLayerFactory = null; if (!pdfjsLib.PDFJS.disableTextLayer) { textLayerFactory = this; } var pageView = new PDFPageView({ container: this.viewer, eventBus: this.eventBus, id: pageNum, scale: scale, defaultViewport: viewport.clone(), renderingQueue: this.renderingQueue, textLayerFactory: textLayerFactory, annotationLayerFactory: this, enhanceTextSelection: this.enhanceTextSelection, renderInteractiveForms: this.renderInteractiveForms }); bindOnAfterAndBeforeDraw(pageView); this._pages.push(pageView); } var linkService = this.linkService; onePageRendered.then(function () { if (!pdfjsLib.PDFJS.disableAutoFetch) { var getPagesLeft = pagesCount; for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) { pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) { var pageView = self._pages[pageNum - 1]; if (!pageView.pdfPage) { pageView.setPdfPage(pdfPage); } linkService.cachePageRef(pageNum, pdfPage.ref); getPagesLeft--; if (!getPagesLeft) { resolvePagesPromise(); } }.bind(null, pageNum)); } } else { resolvePagesPromise(); } }); self.eventBus.dispatch('pagesinit', { source: self }); if (this.defaultRenderingQueue) { this.update(); } if (this.findController) { this.findController.resolveFirstPage(); } }.bind(this)); }, setPageLabels: function PDFViewer_setPageLabels(labels) { if (!this.pdfDocument) { return; } if (!labels) { this._pageLabels = null; } else if (!(labels instanceof Array && this.pdfDocument.numPages === labels.length)) { this._pageLabels = null; console.error('PDFViewer_setPageLabels: Invalid page labels.'); } else { this._pageLabels = labels; } for (var i = 0, ii = this._pages.length; i < ii; i++) { var pageView = this._pages[i]; var label = this._pageLabels && this._pageLabels[i]; pageView.setPageLabel(label); } }, _resetView: function () { this._pages = []; this._currentPageNumber = 1; this._currentScale = UNKNOWN_SCALE; this._currentScaleValue = null; this._pageLabels = null; this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE); this._location = null; this._pagesRotation = 0; this._pagesRequests = []; this._pageViewsReady = false; this.viewer.textContent = ''; }, _scrollUpdate: function PDFViewer_scrollUpdate() { if (this.pagesCount === 0) { return; } this.update(); for (var i = 0, ii = this._pages.length; i < ii; i++) { this._pages[i].updatePosition(); } }, _setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(newScale, newValue, preset) { var arg = { source: this, scale: newScale, presetValue: preset ? newValue : undefined }; this.eventBus.dispatch('scalechanging', arg); this.eventBus.dispatch('scalechange', arg); }, _setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(newScale, newValue, noScroll, preset) { this._currentScaleValue = newValue.toString(); if (isSameScale(this._currentScale, newScale)) { if (preset) { this._setScaleDispatchEvent(newScale, newValue, true); } return; } for (var i = 0, ii = this._pages.length; i < ii; i++) { this._pages[i].update(newScale); } this._currentScale = newScale; if (!noScroll) { var page = this._currentPageNumber, dest; if (this._location && !pdfjsLib.PDFJS.ignoreCurrentPositionOnZoom && !(this.isInPresentationMode || this.isChangingPresentationMode)) { page = this._location.pageNumber; dest = [ null, { name: 'XYZ' }, this._location.left, this._location.top, null ]; } this.scrollPageIntoView({ pageNumber: page, destArray: dest, allowNegativeOffset: true }); } this._setScaleDispatchEvent(newScale, newValue, preset); if (this.defaultRenderingQueue) { this.update(); } }, _setScale: function PDFViewer_setScale(value, noScroll) { var scale = parseFloat(value); if (scale > 0) { this._setScaleUpdatePages(scale, value, noScroll, false); } else { var currentPage = this._pages[this._currentPageNumber - 1]; if (!currentPage) { return; } var hPadding = this.isInPresentationMode || this.removePageBorders ? 0 : SCROLLBAR_PADDING; var vPadding = this.isInPresentationMode || this.removePageBorders ? 0 : VERTICAL_PADDING; var pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale; var pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale; switch (value) { case 'page-actual': scale = 1; break; case 'page-width': scale = pageWidthScale; break; case 'page-height': scale = pageHeightScale; break; case 'page-fit': scale = Math.min(pageWidthScale, pageHeightScale); break; case 'auto': var isLandscape = currentPage.width > currentPage.height; var horizontalScale = isLandscape ? Math.min(pageHeightScale, pageWidthScale) : pageWidthScale; scale = Math.min(MAX_AUTO_SCALE, horizontalScale); break; default: console.error('PDFViewer_setScale: "' + value + '" is an unknown zoom value.'); return; } this._setScaleUpdatePages(scale, value, noScroll, true); } }, _resetCurrentPageView: function () { if (this.isInPresentationMode) { this._setScale(this._currentScaleValue, true); } var pageView = this._pages[this._currentPageNumber - 1]; scrollIntoView(pageView.div); }, scrollPageIntoView: function PDFViewer_scrollPageIntoView(params) { if (!this.pdfDocument) { return; } if (arguments.length > 1 || typeof params === 'number') { console.warn('Call of scrollPageIntoView() with obsolete signature.'); var paramObj = {}; if (typeof params === 'number') { paramObj.pageNumber = params; } if (arguments[1] instanceof Array) { paramObj.destArray = arguments[1]; } params = paramObj; } var pageNumber = params.pageNumber || 0; var dest = params.destArray || null; var allowNegativeOffset = params.allowNegativeOffset || false; if (this.isInPresentationMode || !dest) { this._setCurrentPageNumber(pageNumber, true); return; } var pageView = this._pages[pageNumber - 1]; if (!pageView) { console.error('PDFViewer_scrollPageIntoView: ' + 'Invalid "pageNumber" parameter.'); return; } var x = 0, y = 0; var width = 0, height = 0, widthScale, heightScale; var changeOrientation = pageView.rotation % 180 === 0 ? false : true; var pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / CSS_UNITS; var pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / CSS_UNITS; var scale = 0; switch (dest[1].name) { case 'XYZ': x = dest[2]; y = dest[3]; scale = dest[4]; x = x !== null ? x : 0; y = y !== null ? y : pageHeight; break; case 'Fit': case 'FitB': scale = 'page-fit'; break; case 'FitH': case 'FitBH': y = dest[2]; scale = 'page-width'; if (y === null && this._location) { x = this._location.left; y = this._location.top; } break; case 'FitV': case 'FitBV': x = dest[2]; width = pageWidth; height = pageHeight; scale = 'page-height'; break; case 'FitR': x = dest[2]; y = dest[3]; width = dest[4] - x; height = dest[5] - y; var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING; var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING; widthScale = (this.container.clientWidth - hPadding) / width / CSS_UNITS; heightScale = (this.container.clientHeight - vPadding) / height / CSS_UNITS; scale = Math.min(Math.abs(widthScale), Math.abs(heightScale)); break; default: console.error('PDFViewer_scrollPageIntoView: \'' + dest[1].name + '\' is not a valid destination type.'); return; } if (scale && scale !== this._currentScale) { this.currentScaleValue = scale; } else if (this._currentScale === UNKNOWN_SCALE) { this.currentScaleValue = DEFAULT_SCALE_VALUE; } if (scale === 'page-fit' && !dest[4]) { scrollIntoView(pageView.div); return; } var boundingRect = [ pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height) ]; var left = Math.min(boundingRect[0][0], boundingRect[1][0]); var top = Math.min(boundingRect[0][1], boundingRect[1][1]); if (!allowNegativeOffset) { left = Math.max(left, 0); top = Math.max(top, 0); } scrollIntoView(pageView.div, { left: left, top: top }); }, _updateLocation: function (firstPage) { var currentScale = this._currentScale; var currentScaleValue = this._currentScaleValue; var normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue; var pageNumber = firstPage.id; var pdfOpenParams = '#page=' + pageNumber; pdfOpenParams += '&zoom=' + normalizedScaleValue; var currentPageView = this._pages[pageNumber - 1]; var container = this.container; var topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y); var intLeft = Math.round(topLeft[0]); var intTop = Math.round(topLeft[1]); pdfOpenParams += ',' + intLeft + ',' + intTop; this._location = { pageNumber: pageNumber, scale: normalizedScaleValue, top: intTop, left: intLeft, pdfOpenParams: pdfOpenParams }; }, update: function PDFViewer_update() { var visible = this._getVisiblePages(); var visiblePages = visible.views; if (visiblePages.length === 0) { return; } var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * visiblePages.length + 1); this._buffer.resize(suggestedCacheSize); this.renderingQueue.renderHighestPriority(visible); var currentId = this._currentPageNumber; var firstPage = visible.first; for (var i = 0, ii = visiblePages.length, stillFullyVisible = false; i < ii; ++i) { var page = visiblePages[i]; if (page.percent < 100) { break; } if (page.id === currentId) { stillFullyVisible = true; break; } } if (!stillFullyVisible) { currentId = visiblePages[0].id; } if (!this.isInPresentationMode) { this._setCurrentPageNumber(currentId); } this._updateLocation(firstPage); this.eventBus.dispatch('updateviewarea', { source: this, location: this._location }); }, containsElement: function (element) { return this.container.contains(element); }, focus: function () { this.container.focus(); }, get isInPresentationMode() { return this.presentationModeState === PresentationModeState.FULLSCREEN; }, get isChangingPresentationMode() { return this.presentationModeState === PresentationModeState.CHANGING; }, get isHorizontalScrollbarEnabled() { return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth; }, _getVisiblePages: function () { if (!this.isInPresentationMode) { return getVisibleElements(this.container, this._pages, true); } else { var visible = []; var currentPage = this._pages[this._currentPageNumber - 1]; visible.push({ id: currentPage.id, view: currentPage }); return { first: currentPage, last: currentPage, views: visible }; } }, cleanup: function () { for (var i = 0, ii = this._pages.length; i < ii; i++) { if (this._pages[i] && this._pages[i].renderingState !== RenderingStates.FINISHED) { this._pages[i].reset(); } } }, _cancelRendering: function PDFViewer_cancelRendering() { for (var i = 0, ii = this._pages.length; i < ii; i++) { if (this._pages[i]) { this._pages[i].cancelRendering(); } } }, _ensurePdfPageLoaded: function (pageView) { if (pageView.pdfPage) { return Promise.resolve(pageView.pdfPage); } var pageNumber = pageView.id; if (this._pagesRequests[pageNumber]) { return this._pagesRequests[pageNumber]; } var promise = this.pdfDocument.getPage(pageNumber).then(function (pdfPage) { pageView.setPdfPage(pdfPage); this._pagesRequests[pageNumber] = null; return pdfPage; }.bind(this)); this._pagesRequests[pageNumber] = promise; return promise; }, forceRendering: function (currentlyVisiblePages) { var visiblePages = currentlyVisiblePages || this._getVisiblePages(); var pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, this.scroll.down); if (pageView) { this._ensurePdfPageLoaded(pageView).then(function () { this.renderingQueue.renderView(pageView); }.bind(this)); return true; } return false; }, getPageTextContent: function (pageIndex) { return this.pdfDocument.getPage(pageIndex + 1).then(function (page) { return page.getTextContent({ normalizeWhitespace: true }); }); }, createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport, enhanceTextSelection) { return new TextLayerBuilder({ textLayerDiv: textLayerDiv, eventBus: this.eventBus, pageIndex: pageIndex, viewport: viewport, findController: this.isInPresentationMode ? null : this.findController, enhanceTextSelection: this.isInPresentationMode ? false : enhanceTextSelection }); }, createAnnotationLayerBuilder: function (pageDiv, pdfPage, renderInteractiveForms) { return new AnnotationLayerBuilder({ pageDiv: pageDiv, pdfPage: pdfPage, renderInteractiveForms: renderInteractiveForms, linkService: this.linkService, downloadManager: this.downloadManager }); }, setFindController: function (findController) { this.findController = findController; }, getPagesOverview: function () { return this._pages.map(function (pageView) { var viewport = pageView.pdfPage.getViewport(1); return { width: viewport.width, height: viewport.height }; }); } }; return PDFViewer; }(); exports.PresentationModeState = PresentationModeState; exports.PDFViewer = PDFViewer; })); }.call(pdfViewerLibs)); var PDFJS = pdfjsLib.PDFJS; PDFJS.PDFViewer = pdfViewerLibs.pdfjsWebPDFViewer.PDFViewer; PDFJS.PDFPageView = pdfViewerLibs.pdfjsWebPDFPageView.PDFPageView; PDFJS.PDFLinkService = pdfViewerLibs.pdfjsWebPDFLinkService.PDFLinkService; PDFJS.TextLayerBuilder = pdfViewerLibs.pdfjsWebTextLayerBuilder.TextLayerBuilder; PDFJS.DefaultTextLayerFactory = pdfViewerLibs.pdfjsWebTextLayerBuilder.DefaultTextLayerFactory; PDFJS.AnnotationLayerBuilder = pdfViewerLibs.pdfjsWebAnnotationLayerBuilder.AnnotationLayerBuilder; PDFJS.DefaultAnnotationLayerFactory = pdfViewerLibs.pdfjsWebAnnotationLayerBuilder.DefaultAnnotationLayerFactory; PDFJS.PDFHistory = pdfViewerLibs.pdfjsWebPDFHistory.PDFHistory; PDFJS.PDFFindController = pdfViewerLibs.pdfjsWebPDFFindController.PDFFindController; PDFJS.EventBus = pdfViewerLibs.pdfjsWebUIUtils.EventBus; PDFJS.DownloadManager = pdfViewerLibs.pdfjsWebDownloadManager.DownloadManager; PDFJS.ProgressBar = pdfViewerLibs.pdfjsWebUIUtils.ProgressBar; exports.PDFJS = PDFJS; }));
/*! * typeahead.js 1.0.1 * https://github.com/twitter/typeahead.js * Copyright 2013-2016 Twitter, Inc. and other contributors; Licensed MIT */ (function(root, factory) { if (typeof define === "function" && define.amd) { define([ "jquery" ], function(a0) { return root["Bloodhound"] = factory(a0); }); } else if (typeof exports === "object") { module.exports = factory(require("jquery")); } else { root["Bloodhound"] = factory(root["jQuery"]); } })(this, function($) { var _ = function() { "use strict"; return { isMsie: function() { return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false; }, isBlankString: function(str) { return !str || /^\s*$/.test(str); }, escapeRegExChars: function(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); }, isString: function(obj) { return typeof obj === "string"; }, isNumber: function(obj) { return typeof obj === "number"; }, isArray: $.isArray, isFunction: $.isFunction, isObject: $.isPlainObject, isUndefined: function(obj) { return typeof obj === "undefined"; }, isElement: function(obj) { return !!(obj && obj.nodeType === 1); }, isJQuery: function(obj) { return obj instanceof $; }, toStr: function toStr(s) { return _.isUndefined(s) || s === null ? "" : s + ""; }, bind: $.proxy, each: function(collection, cb) { $.each(collection, reverseArgs); function reverseArgs(index, value) { return cb(value, index); } }, map: $.map, filter: $.grep, every: function(obj, test) { var result = true; if (!obj) { return result; } $.each(obj, function(key, val) { if (!(result = test.call(null, val, key, obj))) { return false; } }); return !!result; }, some: function(obj, test) { var result = false; if (!obj) { return result; } $.each(obj, function(key, val) { if (result = test.call(null, val, key, obj)) { return false; } }); return !!result; }, mixin: $.extend, identity: function(x) { return x; }, clone: function(obj) { return $.extend(true, {}, obj); }, getIdGenerator: function() { var counter = 0; return function() { return counter++; }; }, templatify: function templatify(obj) { return $.isFunction(obj) ? obj : template; function template() { return String(obj); } }, defer: function(fn) { setTimeout(fn, 0); }, debounce: function(func, wait, immediate) { var timeout, result; return function() { var context = this, args = arguments, later, callNow; later = function() { timeout = null; if (!immediate) { result = func.apply(context, args); } }; callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); } return result; }; }, throttle: function(func, wait) { var context, args, timeout, result, previous, later; previous = 0; later = function() { previous = new Date(); timeout = null; result = func.apply(context, args); }; return function() { var now = new Date(), remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout) { timeout = setTimeout(later, remaining); } return result; }; }, stringify: function(val) { return _.isString(val) ? val : JSON.stringify(val); }, noop: function() {} }; }(); var VERSION = "1.0.1"; var tokenizers = function() { "use strict"; return { nonword: nonword, whitespace: whitespace, ngram: ngram, obj: { nonword: getObjTokenizer(nonword), whitespace: getObjTokenizer(whitespace), ngram: getObjTokenizer(ngram) } }; function whitespace(str) { str = _.toStr(str); return str ? str.split(/\s+/) : []; } function nonword(str) { str = _.toStr(str); return str ? str.split(/\W+/) : []; } function ngram(str) { str = _.toStr(str); var tokens = [], word = ""; _.each(str.split(""), function(char) { if (char.match(/\s+/)) { word = ""; } else { tokens.push(word + char); word += char; } }); return tokens; } function getObjTokenizer(tokenizer) { return function setKey(keys) { keys = _.isArray(keys) ? keys : [].slice.call(arguments, 0); return function tokenize(o) { var tokens = []; _.each(keys, function(k) { tokens = tokens.concat(tokenizer(_.toStr(o[k]))); }); return tokens; }; }; } }(); var LruCache = function() { "use strict"; function LruCache(maxSize) { this.maxSize = _.isNumber(maxSize) ? maxSize : 100; this.reset(); if (this.maxSize <= 0) { this.set = this.get = $.noop; } } _.mixin(LruCache.prototype, { set: function set(key, val) { var tailItem = this.list.tail, node; if (this.size >= this.maxSize) { this.list.remove(tailItem); delete this.hash[tailItem.key]; this.size--; } if (node = this.hash[key]) { node.val = val; this.list.moveToFront(node); } else { node = new Node(key, val); this.list.add(node); this.hash[key] = node; this.size++; } }, get: function get(key) { var node = this.hash[key]; if (node) { this.list.moveToFront(node); return node.val; } }, reset: function reset() { this.size = 0; this.hash = {}; this.list = new List(); } }); function List() { this.head = this.tail = null; } _.mixin(List.prototype, { add: function add(node) { if (this.head) { node.next = this.head; this.head.prev = node; } this.head = node; this.tail = this.tail || node; }, remove: function remove(node) { node.prev ? node.prev.next = node.next : this.head = node.next; node.next ? node.next.prev = node.prev : this.tail = node.prev; }, moveToFront: function(node) { this.remove(node); this.add(node); } }); function Node(key, val) { this.key = key; this.val = val; this.prev = this.next = null; } return LruCache; }(); var PersistentStorage = function() { "use strict"; var LOCAL_STORAGE; try { LOCAL_STORAGE = window.localStorage; LOCAL_STORAGE.setItem("~~~", "!"); LOCAL_STORAGE.removeItem("~~~"); } catch (err) { LOCAL_STORAGE = null; } function PersistentStorage(namespace, override) { this.prefix = [ "__", namespace, "__" ].join(""); this.ttlKey = "__ttl__"; this.keyMatcher = new RegExp("^" + _.escapeRegExChars(this.prefix)); this.ls = override || LOCAL_STORAGE; !this.ls && this._noop(); } _.mixin(PersistentStorage.prototype, { _prefix: function(key) { return this.prefix + key; }, _ttlKey: function(key) { return this._prefix(key) + this.ttlKey; }, _noop: function() { this.get = this.set = this.remove = this.clear = this.isExpired = _.noop; }, _safeSet: function(key, val) { try { this.ls.setItem(key, val); } catch (err) { if (err.name === "QuotaExceededError") { this.clear(); this._noop(); } } }, get: function(key) { if (this.isExpired(key)) { this.remove(key); } return decode(this.ls.getItem(this._prefix(key))); }, set: function(key, val, ttl) { if (_.isNumber(ttl)) { this._safeSet(this._ttlKey(key), encode(now() + ttl)); } else { this.ls.removeItem(this._ttlKey(key)); } return this._safeSet(this._prefix(key), encode(val)); }, remove: function(key) { this.ls.removeItem(this._ttlKey(key)); this.ls.removeItem(this._prefix(key)); return this; }, clear: function() { var i, keys = gatherMatchingKeys(this.keyMatcher); for (i = keys.length; i--; ) { this.remove(keys[i]); } return this; }, isExpired: function(key) { var ttl = decode(this.ls.getItem(this._ttlKey(key))); return _.isNumber(ttl) && now() > ttl ? true : false; } }); return PersistentStorage; function now() { return new Date().getTime(); } function encode(val) { return JSON.stringify(_.isUndefined(val) ? null : val); } function decode(val) { return $.parseJSON(val); } function gatherMatchingKeys(keyMatcher) { var i, key, keys = [], len = LOCAL_STORAGE.length; for (i = 0; i < len; i++) { if ((key = LOCAL_STORAGE.key(i)).match(keyMatcher)) { keys.push(key.replace(keyMatcher, "")); } } return keys; } }(); var Transport = function() { "use strict"; var pendingRequestsCount = 0, pendingRequests = {}, sharedCache = new LruCache(10); function Transport(o) { o = o || {}; this.maxPendingRequests = o.maxPendingRequests || 6; this.cancelled = false; this.lastReq = null; this._send = o.transport; this._get = o.limiter ? o.limiter(this._get) : this._get; this._cache = o.cache === false ? new LruCache(0) : sharedCache; } Transport.setMaxPendingRequests = function setMaxPendingRequests(num) { this.maxPendingRequests = num; }; Transport.resetCache = function resetCache() { sharedCache.reset(); }; _.mixin(Transport.prototype, { _fingerprint: function fingerprint(o) { o = o || {}; return o.url + o.type + $.param(o.data || {}); }, _get: function(o, cb) { var that = this, fingerprint, jqXhr; fingerprint = this._fingerprint(o); if (this.cancelled || fingerprint !== this.lastReq) { return; } if (jqXhr = pendingRequests[fingerprint]) { jqXhr.done(done).fail(fail); } else if (pendingRequestsCount < this.maxPendingRequests) { pendingRequestsCount++; pendingRequests[fingerprint] = this._send(o).done(done).fail(fail).always(always); } else { this.onDeckRequestArgs = [].slice.call(arguments, 0); } function done(resp) { cb(null, resp); that._cache.set(fingerprint, resp); } function fail() { cb(true); } function always() { pendingRequestsCount--; delete pendingRequests[fingerprint]; if (that.onDeckRequestArgs) { that._get.apply(that, that.onDeckRequestArgs); that.onDeckRequestArgs = null; } } }, get: function(o, cb) { var resp, fingerprint; cb = cb || $.noop; o = _.isString(o) ? { url: o } : o || {}; fingerprint = this._fingerprint(o); this.cancelled = false; this.lastReq = fingerprint; if (resp = this._cache.get(fingerprint)) { cb(null, resp); } else { this._get(o, cb); } }, cancel: function() { this.cancelled = true; } }); return Transport; }(); var SearchIndex = window.SearchIndex = function() { "use strict"; var CHILDREN = "c", IDS = "i"; function SearchIndex(o) { o = o || {}; if (!o.datumTokenizer || !o.queryTokenizer) { $.error("datumTokenizer and queryTokenizer are both required"); } this.identify = o.identify || _.stringify; this.datumTokenizer = o.datumTokenizer; this.queryTokenizer = o.queryTokenizer; this.matchAnyQueryToken = o.matchAnyQueryToken; this.reset(); } _.mixin(SearchIndex.prototype, { bootstrap: function bootstrap(o) { this.datums = o.datums; this.trie = o.trie; }, add: function(data) { var that = this; data = _.isArray(data) ? data : [ data ]; _.each(data, function(datum) { var id, tokens; that.datums[id = that.identify(datum)] = datum; tokens = normalizeTokens(that.datumTokenizer(datum)); _.each(tokens, function(token) { var node, chars, ch; node = that.trie; chars = token.split(""); while (ch = chars.shift()) { node = node[CHILDREN][ch] || (node[CHILDREN][ch] = newNode()); node[IDS].push(id); } }); }); }, get: function get(ids) { var that = this; return _.map(ids, function(id) { return that.datums[id]; }); }, search: function search(query) { var that = this, tokens, matches; tokens = normalizeTokens(this.queryTokenizer(query)); _.each(tokens, function(token) { var node, chars, ch, ids; if (matches && matches.length === 0 && !that.matchAnyQueryToken) { return false; } node = that.trie; chars = token.split(""); while (node && (ch = chars.shift())) { node = node[CHILDREN][ch]; } if (node && chars.length === 0) { ids = node[IDS].slice(0); matches = matches ? getIntersection(matches, ids) : ids; } else { if (!that.matchAnyQueryToken) { matches = []; return false; } } }); return matches ? _.map(unique(matches), function(id) { return that.datums[id]; }) : []; }, all: function all() { var values = []; for (var key in this.datums) { values.push(this.datums[key]); } return values; }, reset: function reset() { this.datums = {}; this.trie = newNode(); }, serialize: function serialize() { return { datums: this.datums, trie: this.trie }; } }); return SearchIndex; function normalizeTokens(tokens) { tokens = _.filter(tokens, function(token) { return !!token; }); tokens = _.map(tokens, function(token) { return token.toLowerCase(); }); return tokens; } function newNode() { var node = {}; node[IDS] = []; node[CHILDREN] = {}; return node; } function unique(array) { var seen = {}, uniques = []; for (var i = 0, len = array.length; i < len; i++) { if (!seen[array[i]]) { seen[array[i]] = true; uniques.push(array[i]); } } return uniques; } function getIntersection(arrayA, arrayB) { var ai = 0, bi = 0, intersection = []; arrayA = arrayA.sort(); arrayB = arrayB.sort(); var lenArrayA = arrayA.length, lenArrayB = arrayB.length; while (ai < lenArrayA && bi < lenArrayB) { if (arrayA[ai] < arrayB[bi]) { ai++; } else if (arrayA[ai] > arrayB[bi]) { bi++; } else { intersection.push(arrayA[ai]); ai++; bi++; } } return intersection; } }(); var Prefetch = function() { "use strict"; var keys; keys = { data: "data", protocol: "protocol", thumbprint: "thumbprint" }; function Prefetch(o) { this.url = o.url; this.ttl = o.ttl; this.cache = o.cache; this.prepare = o.prepare; this.transform = o.transform; this.transport = o.transport; this.thumbprint = o.thumbprint; this.storage = new PersistentStorage(o.cacheKey); } _.mixin(Prefetch.prototype, { _settings: function settings() { return { url: this.url, type: "GET", dataType: "json" }; }, store: function store(data) { if (!this.cache) { return; } this.storage.set(keys.data, data, this.ttl); this.storage.set(keys.protocol, location.protocol, this.ttl); this.storage.set(keys.thumbprint, this.thumbprint, this.ttl); }, fromCache: function fromCache() { var stored = {}, isExpired; if (!this.cache) { return null; } stored.data = this.storage.get(keys.data); stored.protocol = this.storage.get(keys.protocol); stored.thumbprint = this.storage.get(keys.thumbprint); isExpired = stored.thumbprint !== this.thumbprint || stored.protocol !== location.protocol; return stored.data && !isExpired ? stored.data : null; }, fromNetwork: function(cb) { var that = this, settings; if (!cb) { return; } settings = this.prepare(this._settings()); this.transport(settings).fail(onError).done(onResponse); function onError() { cb(true); } function onResponse(resp) { cb(null, that.transform(resp)); } }, clear: function clear() { this.storage.clear(); return this; } }); return Prefetch; }(); var Remote = function() { "use strict"; function Remote(o) { this.url = o.url; this.prepare = o.prepare; this.transform = o.transform; this.indexResponse = o.indexResponse; this.transport = new Transport({ cache: o.cache, limiter: o.limiter, transport: o.transport, maxPendingRequests: o.maxPendingRequests }); } _.mixin(Remote.prototype, { _settings: function settings() { return { url: this.url, type: "GET", dataType: "json" }; }, get: function get(query, cb) { var that = this, settings; if (!cb) { return; } query = query || ""; settings = this.prepare(query, this._settings()); return this.transport.get(settings, onResponse); function onResponse(err, resp) { err ? cb([]) : cb(that.transform(resp)); } }, cancelLastRequest: function cancelLastRequest() { this.transport.cancel(); } }); return Remote; }(); var oParser = function() { "use strict"; return function parse(o) { var defaults, sorter; defaults = { initialize: true, identify: _.stringify, datumTokenizer: null, queryTokenizer: null, matchAnyQueryToken: false, sufficient: 5, indexRemote: false, sorter: null, local: [], prefetch: null, remote: null }; o = _.mixin(defaults, o || {}); !o.datumTokenizer && $.error("datumTokenizer is required"); !o.queryTokenizer && $.error("queryTokenizer is required"); sorter = o.sorter; o.sorter = sorter ? function(x) { return x.sort(sorter); } : _.identity; o.local = _.isFunction(o.local) ? o.local() : o.local; o.prefetch = parsePrefetch(o.prefetch); o.remote = parseRemote(o.remote); return o; }; function parsePrefetch(o) { var defaults; if (!o) { return null; } defaults = { url: null, ttl: 24 * 60 * 60 * 1e3, cache: true, cacheKey: null, thumbprint: "", prepare: _.identity, transform: _.identity, transport: null }; o = _.isString(o) ? { url: o } : o; o = _.mixin(defaults, o); !o.url && $.error("prefetch requires url to be set"); o.transform = o.filter || o.transform; o.cacheKey = o.cacheKey || o.url; o.thumbprint = VERSION + o.thumbprint; o.transport = o.transport ? callbackToDeferred(o.transport) : $.ajax; return o; } function parseRemote(o) { var defaults; if (!o) { return; } defaults = { url: null, cache: true, prepare: null, replace: null, wildcard: null, limiter: null, rateLimitBy: "debounce", rateLimitWait: 300, transform: _.identity, transport: null }; o = _.isString(o) ? { url: o } : o; o = _.mixin(defaults, o); !o.url && $.error("remote requires url to be set"); o.transform = o.filter || o.transform; o.prepare = toRemotePrepare(o); o.limiter = toLimiter(o); o.transport = o.transport ? callbackToDeferred(o.transport) : $.ajax; delete o.replace; delete o.wildcard; delete o.rateLimitBy; delete o.rateLimitWait; return o; } function toRemotePrepare(o) { var prepare, replace, wildcard; prepare = o.prepare; replace = o.replace; wildcard = o.wildcard; if (prepare) { return prepare; } if (replace) { prepare = prepareByReplace; } else if (o.wildcard) { prepare = prepareByWildcard; } else { prepare = idenityPrepare; } return prepare; function prepareByReplace(query, settings) { settings.url = replace(settings.url, query); return settings; } function prepareByWildcard(query, settings) { settings.url = settings.url.replace(wildcard, encodeURIComponent(query)); return settings; } function idenityPrepare(query, settings) { return settings; } } function toLimiter(o) { var limiter, method, wait; limiter = o.limiter; method = o.rateLimitBy; wait = o.rateLimitWait; if (!limiter) { limiter = /^throttle$/i.test(method) ? throttle(wait) : debounce(wait); } return limiter; function debounce(wait) { return function debounce(fn) { return _.debounce(fn, wait); }; } function throttle(wait) { return function throttle(fn) { return _.throttle(fn, wait); }; } } function callbackToDeferred(fn) { return function wrapper(o) { var deferred = $.Deferred(); fn(o, onSuccess, onError); return deferred; function onSuccess(resp) { _.defer(function() { deferred.resolve(resp); }); } function onError(err) { _.defer(function() { deferred.reject(err); }); } }; } }(); var Bloodhound = function() { "use strict"; var old; old = window && window.Bloodhound; function Bloodhound(o) { o = oParser(o); this.sorter = o.sorter; this.identify = o.identify; this.sufficient = o.sufficient; this.indexRemote = o.indexRemote; this.local = o.local; this.remote = o.remote ? new Remote(o.remote) : null; this.prefetch = o.prefetch ? new Prefetch(o.prefetch) : null; this.index = new SearchIndex({ identify: this.identify, datumTokenizer: o.datumTokenizer, queryTokenizer: o.queryTokenizer }); o.initialize !== false && this.initialize(); } Bloodhound.noConflict = function noConflict() { window && (window.Bloodhound = old); return Bloodhound; }; Bloodhound.tokenizers = tokenizers; _.mixin(Bloodhound.prototype, { __ttAdapter: function ttAdapter() { var that = this; return this.remote ? withAsync : withoutAsync; function withAsync(query, sync, async) { return that.search(query, sync, async); } function withoutAsync(query, sync) { return that.search(query, sync); } }, _loadPrefetch: function loadPrefetch() { var that = this, deferred, serialized; deferred = $.Deferred(); if (!this.prefetch) { deferred.resolve(); } else if (serialized = this.prefetch.fromCache()) { this.index.bootstrap(serialized); deferred.resolve(); } else { this.prefetch.fromNetwork(done); } return deferred.promise(); function done(err, data) { if (err) { return deferred.reject(); } that.add(data); that.prefetch.store(that.index.serialize()); deferred.resolve(); } }, _initialize: function initialize() { var that = this, deferred; this.clear(); (this.initPromise = this._loadPrefetch()).done(addLocalToIndex); return this.initPromise; function addLocalToIndex() { that.add(that.local); } }, initialize: function initialize(force) { return !this.initPromise || force ? this._initialize() : this.initPromise; }, add: function add(data) { this.index.add(data); return this; }, get: function get(ids) { ids = _.isArray(ids) ? ids : [].slice.call(arguments); return this.index.get(ids); }, search: function search(query, sync, async) { var that = this, local; sync = sync || _.noop; async = async || _.noop; local = this.sorter(this.index.search(query)); sync(this.remote ? local.slice() : local); if (this.remote && local.length < this.sufficient) { this.remote.get(query, processRemote); } else if (this.remote) { this.remote.cancelLastRequest(); } return this; function processRemote(remote) { var nonDuplicates = []; _.each(remote, function(r) { !_.some(local, function(l) { return that.identify(r) === that.identify(l); }) && nonDuplicates.push(r); }); that.indexRemote && that.add(nonDuplicates); async(nonDuplicates); } }, all: function all() { return this.index.all(); }, clear: function clear() { this.index.reset(); return this; }, clearPrefetchCache: function clearPrefetchCache() { this.prefetch && this.prefetch.clear(); return this; }, clearRemoteCache: function clearRemoteCache() { Transport.resetCache(); return this; }, ttAdapter: function ttAdapter() { return this.__ttAdapter(); } }); return Bloodhound; }(); return Bloodhound; }); (function(root, factory) { if (typeof define === "function" && define.amd) { define([ "jquery" ], function(a0) { return factory(a0); }); } else if (typeof exports === "object") { module.exports = factory(require("jquery")); } else { factory(root["jQuery"]); } })(this, function($) { var _ = function() { "use strict"; return { isMsie: function() { return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false; }, isBlankString: function(str) { return !str || /^\s*$/.test(str); }, escapeRegExChars: function(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); }, isString: function(obj) { return typeof obj === "string"; }, isNumber: function(obj) { return typeof obj === "number"; }, isArray: $.isArray, isFunction: $.isFunction, isObject: $.isPlainObject, isUndefined: function(obj) { return typeof obj === "undefined"; }, isElement: function(obj) { return !!(obj && obj.nodeType === 1); }, isJQuery: function(obj) { return obj instanceof $; }, toStr: function toStr(s) { return _.isUndefined(s) || s === null ? "" : s + ""; }, bind: $.proxy, each: function(collection, cb) { $.each(collection, reverseArgs); function reverseArgs(index, value) { return cb(value, index); } }, map: $.map, filter: $.grep, every: function(obj, test) { var result = true; if (!obj) { return result; } $.each(obj, function(key, val) { if (!(result = test.call(null, val, key, obj))) { return false; } }); return !!result; }, some: function(obj, test) { var result = false; if (!obj) { return result; } $.each(obj, function(key, val) { if (result = test.call(null, val, key, obj)) { return false; } }); return !!result; }, mixin: $.extend, identity: function(x) { return x; }, clone: function(obj) { return $.extend(true, {}, obj); }, getIdGenerator: function() { var counter = 0; return function() { return counter++; }; }, templatify: function templatify(obj) { return $.isFunction(obj) ? obj : template; function template() { return String(obj); } }, defer: function(fn) { setTimeout(fn, 0); }, debounce: function(func, wait, immediate) { var timeout, result; return function() { var context = this, args = arguments, later, callNow; later = function() { timeout = null; if (!immediate) { result = func.apply(context, args); } }; callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); } return result; }; }, throttle: function(func, wait) { var context, args, timeout, result, previous, later; previous = 0; later = function() { previous = new Date(); timeout = null; result = func.apply(context, args); }; return function() { var now = new Date(), remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout) { timeout = setTimeout(later, remaining); } return result; }; }, stringify: function(val) { return _.isString(val) ? val : JSON.stringify(val); }, noop: function() {} }; }(); var WWW = function() { "use strict"; var defaultClassNames = { wrapper: "twitter-typeahead", input: "tt-input", hint: "tt-hint", menu: "tt-menu", dataset: "tt-dataset", suggestion: "tt-suggestion", selectable: "tt-selectable", empty: "tt-empty", open: "tt-open", cursor: "tt-cursor", highlight: "tt-highlight" }; return build; function build(o) { var www, classes; classes = _.mixin({}, defaultClassNames, o); www = { css: buildCss(), classes: classes, html: buildHtml(classes), selectors: buildSelectors(classes) }; return { css: www.css, html: www.html, classes: www.classes, selectors: www.selectors, mixin: function(o) { _.mixin(o, www); } }; } function buildHtml(c) { return { wrapper: '<span class="' + c.wrapper + '"></span>', menu: '<div class="' + c.menu + '"></div>' }; } function buildSelectors(classes) { var selectors = {}; _.each(classes, function(v, k) { selectors[k] = "." + v; }); return selectors; } function buildCss() { var css = { wrapper: { position: "relative", display: "inline-block" }, hint: { position: "absolute", top: "0", left: "0", borderColor: "transparent", boxShadow: "none", opacity: "1" }, input: { position: "relative", verticalAlign: "top", backgroundColor: "transparent" }, inputWithNoHint: { position: "relative", verticalAlign: "top" }, menu: { position: "absolute", top: "100%", left: "0", zIndex: "100", display: "none" }, ltr: { left: "0", right: "auto" }, rtl: { left: "auto", right: " 0" } }; if (_.isMsie()) { _.mixin(css.input, { backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)" }); } return css; } }(); var EventBus = function() { "use strict"; var namespace, deprecationMap; namespace = "typeahead:"; deprecationMap = { render: "rendered", cursorchange: "cursorchanged", select: "selected", autocomplete: "autocompleted" }; function EventBus(o) { if (!o || !o.el) { $.error("EventBus initialized without el"); } this.$el = $(o.el); } _.mixin(EventBus.prototype, { _trigger: function(type, args) { var $e = $.Event(namespace + type); this.$el.trigger.call(this.$el, $e, args || []); return $e; }, before: function(type) { var args, $e; args = [].slice.call(arguments, 1); $e = this._trigger("before" + type, args); return $e.isDefaultPrevented(); }, trigger: function(type) { var deprecatedType; this._trigger(type, [].slice.call(arguments, 1)); if (deprecatedType = deprecationMap[type]) { this._trigger(deprecatedType, [].slice.call(arguments, 1)); } } }); return EventBus; }(); var EventEmitter = function() { "use strict"; var splitter = /\s+/, nextTick = getNextTick(); return { onSync: onSync, onAsync: onAsync, off: off, trigger: trigger }; function on(method, types, cb, context) { var type; if (!cb) { return this; } types = types.split(splitter); cb = context ? bindContext(cb, context) : cb; this._callbacks = this._callbacks || {}; while (type = types.shift()) { this._callbacks[type] = this._callbacks[type] || { sync: [], async: [] }; this._callbacks[type][method].push(cb); } return this; } function onAsync(types, cb, context) { return on.call(this, "async", types, cb, context); } function onSync(types, cb, context) { return on.call(this, "sync", types, cb, context); } function off(types) { var type; if (!this._callbacks) { return this; } types = types.split(splitter); while (type = types.shift()) { delete this._callbacks[type]; } return this; } function trigger(types) { var type, callbacks, args, syncFlush, asyncFlush; if (!this._callbacks) { return this; } types = types.split(splitter); args = [].slice.call(arguments, 1); while ((type = types.shift()) && (callbacks = this._callbacks[type])) { syncFlush = getFlush(callbacks.sync, this, [ type ].concat(args)); asyncFlush = getFlush(callbacks.async, this, [ type ].concat(args)); syncFlush() && nextTick(asyncFlush); } return this; } function getFlush(callbacks, context, args) { return flush; function flush() { var cancelled; for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) { cancelled = callbacks[i].apply(context, args) === false; } return !cancelled; } } function getNextTick() { var nextTickFn; if (window.setImmediate) { nextTickFn = function nextTickSetImmediate(fn) { setImmediate(function() { fn(); }); }; } else { nextTickFn = function nextTickSetTimeout(fn) { setTimeout(function() { fn(); }, 0); }; } return nextTickFn; } function bindContext(fn, context) { return fn.bind ? fn.bind(context) : function() { fn.apply(context, [].slice.call(arguments, 0)); }; } }(); var highlight = function(doc) { "use strict"; var defaults = { node: null, pattern: null, tagName: "strong", className: null, wordsOnly: false, caseSensitive: false, diacriticInsensitive: false }; var accented = { A: "[AaªÀ-Åà-åĀ-ąǍǎȀ-ȃȦȧᴬᵃḀḁẚẠ-ảₐ℀℁℻⒜Ⓐⓐ㍱-㍴㎀-㎄㎈㎉㎩-㎯㏂㏊㏟㏿Aa]", B: "[BbᴮᵇḂ-ḇℬ⒝Ⓑⓑ㍴㎅-㎇㏃㏈㏔㏝Bb]", C: "[CcÇçĆ-čᶜ℀ℂ℃℅℆ℭⅭⅽ⒞Ⓒⓒ㍶㎈㎉㎝㎠㎤㏄-㏇Cc]", D: "[DdĎďDŽ-džDZ-dzᴰᵈḊ-ḓⅅⅆⅮⅾ⒟Ⓓⓓ㋏㍲㍷-㍹㎗㎭-㎯㏅㏈Dd]", E: "[EeÈ-Ëè-ëĒ-ěȄ-ȇȨȩᴱᵉḘ-ḛẸ-ẽₑ℡ℯℰⅇ⒠Ⓔⓔ㉐㋍㋎Ee]", F: "[FfᶠḞḟ℉ℱ℻⒡Ⓕⓕ㎊-㎌㎙ff-fflFf]", G: "[GgĜ-ģǦǧǴǵᴳᵍḠḡℊ⒢Ⓖⓖ㋌㋍㎇㎍-㎏㎓㎬㏆㏉㏒㏿Gg]", H: "[HhĤĥȞȟʰᴴḢ-ḫẖℋ-ℎ⒣Ⓗⓗ㋌㍱㎐-㎔㏊㏋㏗Hh]", I: "[IiÌ-Ïì-ïĨ-İIJijǏǐȈ-ȋᴵᵢḬḭỈ-ịⁱℐℑℹⅈⅠ-ⅣⅥ-ⅨⅪⅫⅰ-ⅳⅵ-ⅸⅺⅻ⒤Ⓘⓘ㍺㏌㏕fiffiIi]", J: "[JjIJ-ĵLJ-njǰʲᴶⅉ⒥ⒿⓙⱼJj]", K: "[KkĶķǨǩᴷᵏḰ-ḵK⒦Ⓚⓚ㎄㎅㎉㎏㎑㎘㎞㎢㎦㎪㎸㎾㏀㏆㏍-㏏Kk]", L: "[LlĹ-ŀLJ-ljˡᴸḶḷḺ-ḽℒℓ℡Ⅼⅼ⒧Ⓛⓛ㋏㎈㎉㏐-㏓㏕㏖㏿flfflLl]", M: "[MmᴹᵐḾ-ṃ℠™ℳⅯⅿ⒨Ⓜⓜ㍷-㍹㎃㎆㎎㎒㎖㎙-㎨㎫㎳㎷㎹㎽㎿㏁㏂㏎㏐㏔-㏖㏘㏙㏞㏟Mm]", N: "[NnÑñŃ-ʼnNJ-njǸǹᴺṄ-ṋⁿℕ№⒩Ⓝⓝ㎁㎋㎚㎱㎵㎻㏌㏑Nn]", O: "[OoºÒ-Öò-öŌ-őƠơǑǒǪǫȌ-ȏȮȯᴼᵒỌ-ỏₒ℅№ℴ⒪Ⓞⓞ㍵㏇㏒㏖Oo]", P: "[PpᴾᵖṔ-ṗℙ⒫Ⓟⓟ㉐㍱㍶㎀㎊㎩-㎬㎰㎴㎺㏋㏗-㏚Pp]", Q: "[Qqℚ⒬Ⓠⓠ㏃Qq]", R: "[RrŔ-řȐ-ȓʳᴿᵣṘ-ṛṞṟ₨ℛ-ℝ⒭Ⓡⓡ㋍㍴㎭-㎯㏚㏛Rr]", S: "[SsŚ-šſȘșˢṠ-ṣ₨℁℠⒮Ⓢⓢ㎧㎨㎮-㎳㏛㏜stSs]", T: "[TtŢ-ťȚțᵀᵗṪ-ṱẗ℡™⒯Ⓣⓣ㉐㋏㎔㏏ſtstTt]", U: "[UuÙ-Üù-üŨ-ųƯưǓǔȔ-ȗᵁᵘᵤṲ-ṷỤ-ủ℆⒰Ⓤⓤ㍳㍺Uu]", V: "[VvᵛᵥṼ-ṿⅣ-Ⅷⅳ-ⅷ⒱Ⓥⓥⱽ㋎㍵㎴-㎹㏜㏞Vv]", W: "[WwŴŵʷᵂẀ-ẉẘ⒲Ⓦⓦ㎺-㎿㏝Ww]", X: "[XxˣẊ-ẍₓ℻Ⅸ-Ⅻⅸ-ⅻ⒳Ⓧⓧ㏓Xx]", Y: "[YyÝýÿŶ-ŸȲȳʸẎẏẙỲ-ỹ⒴Ⓨⓨ㏉Yy]", Z: "[ZzŹ-žDZ-dzᶻẐ-ẕℤℨ⒵Ⓩⓩ㎐-㎔Zz]" }; return function hightlight(o) { var regex; o = _.mixin({}, defaults, o); if (!o.node || !o.pattern) { return; } o.pattern = _.isArray(o.pattern) ? o.pattern : [ o.pattern ]; regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly, o.diacriticInsensitive); traverse(o.node, hightlightTextNode); function hightlightTextNode(textNode) { var match, patternNode, wrapperNode; if (match = regex.exec(textNode.data)) { wrapperNode = doc.createElement(o.tagName); o.className && (wrapperNode.className = o.className); patternNode = textNode.splitText(match.index); patternNode.splitText(match[0].length); wrapperNode.appendChild(patternNode.cloneNode(true)); textNode.parentNode.replaceChild(wrapperNode, patternNode); } return !!match; } function traverse(el, hightlightTextNode) { var childNode, TEXT_NODE_TYPE = 3; for (var i = 0; i < el.childNodes.length; i++) { childNode = el.childNodes[i]; if (childNode.nodeType === TEXT_NODE_TYPE) { i += hightlightTextNode(childNode) ? 1 : 0; } else { traverse(childNode, hightlightTextNode); } } } }; function accent_replacer(chr) { return accented[chr.toUpperCase()] || chr; } function getRegex(patterns, caseSensitive, wordsOnly, diacriticInsensitive) { var escapedPatterns = [], regexStr; for (var i = 0, len = patterns.length; i < len; i++) { var escapedWord = _.escapeRegExChars(patterns[i]); if (diacriticInsensitive) { escapedWord = escapedWord.replace(/\S/g, accent_replacer); } escapedPatterns.push(escapedWord); } regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")"; return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i"); } }(window.document); var Input = function() { "use strict"; var specialKeyCodeMap; specialKeyCodeMap = { 9: "tab", 27: "esc", 37: "left", 39: "right", 13: "enter", 38: "up", 40: "down" }; function Input(o, www) { o = o || {}; if (!o.input) { $.error("input is missing"); } www.mixin(this); this.$hint = $(o.hint); this.$input = $(o.input); this.query = this.$input.val(); this.queryWhenFocused = this.hasFocus() ? this.query : null; this.$overflowHelper = buildOverflowHelper(this.$input); this._checkLanguageDirection(); if (this.$hint.length === 0) { this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop; } } Input.normalizeQuery = function(str) { return _.toStr(str).replace(/^\s*/g, "").replace(/\s{2,}/g, " "); }; _.mixin(Input.prototype, EventEmitter, { _onBlur: function onBlur() { this.resetInputValue(); this.trigger("blurred"); }, _onFocus: function onFocus() { this.queryWhenFocused = this.query; this.trigger("focused"); }, _onKeydown: function onKeydown($e) { var keyName = specialKeyCodeMap[$e.which || $e.keyCode]; this._managePreventDefault(keyName, $e); if (keyName && this._shouldTrigger(keyName, $e)) { this.trigger(keyName + "Keyed", $e); } }, _onInput: function onInput() { this._setQuery(this.getInputValue()); this.clearHintIfInvalid(); this._checkLanguageDirection(); }, _managePreventDefault: function managePreventDefault(keyName, $e) { var preventDefault; switch (keyName) { case "up": case "down": preventDefault = !withModifier($e); break; default: preventDefault = false; } preventDefault && $e.preventDefault(); }, _shouldTrigger: function shouldTrigger(keyName, $e) { var trigger; switch (keyName) { case "tab": trigger = !withModifier($e); break; default: trigger = true; } return trigger; }, _checkLanguageDirection: function checkLanguageDirection() { var dir = (this.$input.css("direction") || "ltr").toLowerCase(); if (this.dir !== dir) { this.dir = dir; this.$hint.attr("dir", dir); this.trigger("langDirChanged", dir); } }, _setQuery: function setQuery(val, silent) { var areEquivalent, hasDifferentWhitespace; areEquivalent = areQueriesEquivalent(val, this.query); hasDifferentWhitespace = areEquivalent ? this.query.length !== val.length : false; this.query = val; if (!silent && !areEquivalent) { this.trigger("queryChanged", this.query); } else if (!silent && hasDifferentWhitespace) { this.trigger("whitespaceChanged", this.query); } }, bind: function() { var that = this, onBlur, onFocus, onKeydown, onInput; onBlur = _.bind(this._onBlur, this); onFocus = _.bind(this._onFocus, this); onKeydown = _.bind(this._onKeydown, this); onInput = _.bind(this._onInput, this); this.$input.on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown); if (!_.isMsie() || _.isMsie() > 9) { this.$input.on("input.tt", onInput); } else { this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) { if (specialKeyCodeMap[$e.which || $e.keyCode]) { return; } _.defer(_.bind(that._onInput, that, $e)); }); } return this; }, focus: function focus() { this.$input.focus(); }, blur: function blur() { this.$input.blur(); }, getLangDir: function getLangDir() { return this.dir; }, getQuery: function getQuery() { return this.query || ""; }, setQuery: function setQuery(val, silent) { this.setInputValue(val); this._setQuery(val, silent); }, hasQueryChangedSinceLastFocus: function hasQueryChangedSinceLastFocus() { return this.query !== this.queryWhenFocused; }, getInputValue: function getInputValue() { return this.$input.val(); }, setInputValue: function setInputValue(value) { this.$input.val(value); this.clearHintIfInvalid(); this._checkLanguageDirection(); }, resetInputValue: function resetInputValue() { this.setInputValue(this.query); }, getHint: function getHint() { return this.$hint.val(); }, setHint: function setHint(value) { this.$hint.val(value); }, clearHint: function clearHint() { this.setHint(""); }, clearHintIfInvalid: function clearHintIfInvalid() { var val, hint, valIsPrefixOfHint, isValid; val = this.getInputValue(); hint = this.getHint(); valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0; isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow(); !isValid && this.clearHint(); }, hasFocus: function hasFocus() { return this.$input.is(":focus"); }, hasOverflow: function hasOverflow() { var constraint = this.$input.width() - 2; this.$overflowHelper.text(this.getInputValue()); return this.$overflowHelper.width() >= constraint; }, isCursorAtEnd: function() { var valueLength, selectionStart, range; valueLength = this.$input.val().length; selectionStart = this.$input[0].selectionStart; if (_.isNumber(selectionStart)) { return selectionStart === valueLength; } else if (document.selection) { range = document.selection.createRange(); range.moveStart("character", -valueLength); return valueLength === range.text.length; } return true; }, destroy: function destroy() { this.$hint.off(".tt"); this.$input.off(".tt"); this.$overflowHelper.remove(); this.$hint = this.$input = this.$overflowHelper = $("<div>"); } }); return Input; function buildOverflowHelper($input) { return $('<pre aria-hidden="true"></pre>').css({ position: "absolute", visibility: "hidden", whiteSpace: "pre", fontFamily: $input.css("font-family"), fontSize: $input.css("font-size"), fontStyle: $input.css("font-style"), fontVariant: $input.css("font-variant"), fontWeight: $input.css("font-weight"), wordSpacing: $input.css("word-spacing"), letterSpacing: $input.css("letter-spacing"), textIndent: $input.css("text-indent"), textRendering: $input.css("text-rendering"), textTransform: $input.css("text-transform") }).insertAfter($input); } function areQueriesEquivalent(a, b) { return Input.normalizeQuery(a) === Input.normalizeQuery(b); } function withModifier($e) { return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey; } }(); var Dataset = function() { "use strict"; var keys, nameGenerator; keys = { dataset: "tt-selectable-dataset", val: "tt-selectable-display", obj: "tt-selectable-object" }; nameGenerator = _.getIdGenerator(); function Dataset(o, www) { o = o || {}; o.templates = o.templates || {}; o.templates.notFound = o.templates.notFound || o.templates.empty; if (!o.source) { $.error("missing source"); } if (!o.node) { $.error("missing node"); } if (o.name && !isValidName(o.name)) { $.error("invalid dataset name: " + o.name); } www.mixin(this); this.highlight = !!o.highlight; this.name = _.toStr(o.name || nameGenerator()); this.limit = o.limit || 5; this.displayFn = getDisplayFn(o.display || o.displayKey); this.templates = getTemplates(o.templates, this.displayFn); this.source = o.source.__ttAdapter ? o.source.__ttAdapter() : o.source; this.async = _.isUndefined(o.async) ? this.source.length > 2 : !!o.async; this._resetLastSuggestion(); this.$el = $(o.node).addClass(this.classes.dataset).addClass(this.classes.dataset + "-" + this.name); } Dataset.extractData = function extractData(el) { var $el = $(el); if ($el.data(keys.obj)) { return { dataset: $el.data(keys.dataset) || "", val: $el.data(keys.val) || "", obj: $el.data(keys.obj) || null }; } return null; }; _.mixin(Dataset.prototype, EventEmitter, { _overwrite: function overwrite(query, suggestions) { suggestions = suggestions || []; if (suggestions.length) { this._renderSuggestions(query, suggestions); } else if (this.async && this.templates.pending) { this._renderPending(query); } else if (!this.async && this.templates.notFound) { this._renderNotFound(query); } else { this._empty(); } this.trigger("rendered", suggestions, false, this.name); }, _append: function append(query, suggestions) { suggestions = suggestions || []; if (suggestions.length && this.$lastSuggestion.length) { this._appendSuggestions(query, suggestions); } else if (suggestions.length) { this._renderSuggestions(query, suggestions); } else if (!this.$lastSuggestion.length && this.templates.notFound) { this._renderNotFound(query); } this.trigger("rendered", suggestions, true, this.name); }, _renderSuggestions: function renderSuggestions(query, suggestions) { var $fragment; $fragment = this._getSuggestionsFragment(query, suggestions); this.$lastSuggestion = $fragment.children().last(); this.$el.html($fragment).prepend(this._getHeader(query, suggestions)).append(this._getFooter(query, suggestions)); }, _appendSuggestions: function appendSuggestions(query, suggestions) { var $fragment, $lastSuggestion; $fragment = this._getSuggestionsFragment(query, suggestions); $lastSuggestion = $fragment.children().last(); this.$lastSuggestion.after($fragment); this.$lastSuggestion = $lastSuggestion; }, _renderPending: function renderPending(query) { var template = this.templates.pending; this._resetLastSuggestion(); template && this.$el.html(template({ query: query, dataset: this.name })); }, _renderNotFound: function renderNotFound(query) { var template = this.templates.notFound; this._resetLastSuggestion(); template && this.$el.html(template({ query: query, dataset: this.name })); }, _empty: function empty() { this.$el.empty(); this._resetLastSuggestion(); }, _getSuggestionsFragment: function getSuggestionsFragment(query, suggestions) { var that = this, fragment; fragment = document.createDocumentFragment(); _.each(suggestions, function getSuggestionNode(suggestion) { var $el, context; context = that._injectQuery(query, suggestion); $el = $(that.templates.suggestion(context)).data(keys.dataset, that.name).data(keys.obj, suggestion).data(keys.val, that.displayFn(suggestion)).addClass(that.classes.suggestion + " " + that.classes.selectable); fragment.appendChild($el[0]); }); this.highlight && highlight({ className: this.classes.highlight, node: fragment, pattern: query }); return $(fragment); }, _getFooter: function getFooter(query, suggestions) { return this.templates.footer ? this.templates.footer({ query: query, suggestions: suggestions, dataset: this.name }) : null; }, _getHeader: function getHeader(query, suggestions) { return this.templates.header ? this.templates.header({ query: query, suggestions: suggestions, dataset: this.name }) : null; }, _resetLastSuggestion: function resetLastSuggestion() { this.$lastSuggestion = $(); }, _injectQuery: function injectQuery(query, obj) { return _.isObject(obj) ? _.mixin({ _query: query }, obj) : obj; }, update: function update(query) { var that = this, canceled = false, syncCalled = false, rendered = 0; this.cancel(); this.cancel = function cancel() { canceled = true; that.cancel = $.noop; that.async && that.trigger("asyncCanceled", query, that.name); }; this.source(query, sync, async); !syncCalled && sync([]); function sync(suggestions) { if (syncCalled) { return; } syncCalled = true; suggestions = (suggestions || []).slice(0, that.limit); rendered = suggestions.length; that._overwrite(query, suggestions); if (rendered < that.limit && that.async) { that.trigger("asyncRequested", query, that.name); } } function async(suggestions) { suggestions = suggestions || []; if (!canceled && rendered < that.limit) { that.cancel = $.noop; var idx = Math.abs(rendered - that.limit); rendered += idx; that._append(query, suggestions.slice(0, idx)); that.async && that.trigger("asyncReceived", query, that.name); } } }, cancel: $.noop, clear: function clear() { this._empty(); this.cancel(); this.trigger("cleared"); }, isEmpty: function isEmpty() { return this.$el.is(":empty"); }, destroy: function destroy() { this.$el = $("<div>"); } }); return Dataset; function getDisplayFn(display) { display = display || _.stringify; return _.isFunction(display) ? display : displayFn; function displayFn(obj) { return obj[display]; } } function getTemplates(templates, displayFn) { return { notFound: templates.notFound && _.templatify(templates.notFound), pending: templates.pending && _.templatify(templates.pending), header: templates.header && _.templatify(templates.header), footer: templates.footer && _.templatify(templates.footer), suggestion: templates.suggestion || suggestionTemplate }; function suggestionTemplate(context) { return $("<div>").text(displayFn(context)); } } function isValidName(str) { return /^[_a-zA-Z0-9-]+$/.test(str); } }(); var Menu = function() { "use strict"; function Menu(o, www) { var that = this; o = o || {}; if (!o.node) { $.error("node is required"); } www.mixin(this); this.$node = $(o.node); this.query = null; this.datasets = _.map(o.datasets, initializeDataset); function initializeDataset(oDataset) { var node = that.$node.find(oDataset.node).first(); oDataset.node = node.length ? node : $("<div>").appendTo(that.$node); return new Dataset(oDataset, www); } } _.mixin(Menu.prototype, EventEmitter, { _onSelectableClick: function onSelectableClick($e) { this.trigger("selectableClicked", $($e.currentTarget)); }, _onRendered: function onRendered(type, dataset, suggestions, async) { this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty()); this.trigger("datasetRendered", dataset, suggestions, async); }, _onCleared: function onCleared() { this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty()); this.trigger("datasetCleared"); }, _propagate: function propagate() { this.trigger.apply(this, arguments); }, _allDatasetsEmpty: function allDatasetsEmpty() { return _.every(this.datasets, isDatasetEmpty); function isDatasetEmpty(dataset) { return dataset.isEmpty(); } }, _getSelectables: function getSelectables() { return this.$node.find(this.selectors.selectable); }, _removeCursor: function _removeCursor() { var $selectable = this.getActiveSelectable(); $selectable && $selectable.removeClass(this.classes.cursor); }, _ensureVisible: function ensureVisible($el) { var elTop, elBottom, nodeScrollTop, nodeHeight; elTop = $el.position().top; elBottom = elTop + $el.outerHeight(true); nodeScrollTop = this.$node.scrollTop(); nodeHeight = this.$node.height() + parseInt(this.$node.css("paddingTop"), 10) + parseInt(this.$node.css("paddingBottom"), 10); if (elTop < 0) { this.$node.scrollTop(nodeScrollTop + elTop); } else if (nodeHeight < elBottom) { this.$node.scrollTop(nodeScrollTop + (elBottom - nodeHeight)); } }, bind: function() { var that = this, onSelectableClick; onSelectableClick = _.bind(this._onSelectableClick, this); this.$node.on("click.tt", this.selectors.selectable, onSelectableClick); this.$node.on("mouseover", this.selectors.selectable, function() { that.setCursor($(this)); }); this.$node.on("mouseleave", function() { that._removeCursor(); }); _.each(this.datasets, function(dataset) { dataset.onSync("asyncRequested", that._propagate, that).onSync("asyncCanceled", that._propagate, that).onSync("asyncReceived", that._propagate, that).onSync("rendered", that._onRendered, that).onSync("cleared", that._onCleared, that); }); return this; }, isOpen: function isOpen() { return this.$node.hasClass(this.classes.open); }, open: function open() { this.$node.scrollTop(0); this.$node.addClass(this.classes.open); }, close: function close() { this.$node.removeClass(this.classes.open); this._removeCursor(); }, setLanguageDirection: function setLanguageDirection(dir) { this.$node.attr("dir", dir); }, selectableRelativeToCursor: function selectableRelativeToCursor(delta) { var $selectables, $oldCursor, oldIndex, newIndex; $oldCursor = this.getActiveSelectable(); $selectables = this._getSelectables(); oldIndex = $oldCursor ? $selectables.index($oldCursor) : -1; newIndex = oldIndex + delta; newIndex = (newIndex + 1) % ($selectables.length + 1) - 1; newIndex = newIndex < -1 ? $selectables.length - 1 : newIndex; return newIndex === -1 ? null : $selectables.eq(newIndex); }, setCursor: function setCursor($selectable) { this._removeCursor(); if ($selectable = $selectable && $selectable.first()) { $selectable.addClass(this.classes.cursor); this._ensureVisible($selectable); } }, getSelectableData: function getSelectableData($el) { return $el && $el.length ? Dataset.extractData($el) : null; }, getActiveSelectable: function getActiveSelectable() { var $selectable = this._getSelectables().filter(this.selectors.cursor).first(); return $selectable.length ? $selectable : null; }, getTopSelectable: function getTopSelectable() { var $selectable = this._getSelectables().first(); return $selectable.length ? $selectable : null; }, update: function update(query) { var isValidUpdate = query !== this.query; if (isValidUpdate) { this.query = query; _.each(this.datasets, updateDataset); } return isValidUpdate; function updateDataset(dataset) { dataset.update(query); } }, empty: function empty() { _.each(this.datasets, clearDataset); this.query = null; this.$node.addClass(this.classes.empty); function clearDataset(dataset) { dataset.clear(); } }, destroy: function destroy() { this.$node.off(".tt"); this.$node = $("<div>"); _.each(this.datasets, destroyDataset); function destroyDataset(dataset) { dataset.destroy(); } } }); return Menu; }(); var DefaultMenu = function() { "use strict"; var s = Menu.prototype; function DefaultMenu() { Menu.apply(this, [].slice.call(arguments, 0)); } _.mixin(DefaultMenu.prototype, Menu.prototype, { open: function open() { !this._allDatasetsEmpty() && this._show(); return s.open.apply(this, [].slice.call(arguments, 0)); }, close: function close() { this._hide(); return s.close.apply(this, [].slice.call(arguments, 0)); }, _onRendered: function onRendered() { if (this._allDatasetsEmpty()) { this._hide(); } else { this.isOpen() && this._show(); } return s._onRendered.apply(this, [].slice.call(arguments, 0)); }, _onCleared: function onCleared() { if (this._allDatasetsEmpty()) { this._hide(); } else { this.isOpen() && this._show(); } return s._onCleared.apply(this, [].slice.call(arguments, 0)); }, setLanguageDirection: function setLanguageDirection(dir) { this.$node.css(dir === "ltr" ? this.css.ltr : this.css.rtl); return s.setLanguageDirection.apply(this, [].slice.call(arguments, 0)); }, _hide: function hide() { this.$node.hide(); }, _show: function show() { this.$node.css("display", "block"); } }); return DefaultMenu; }(); var Typeahead = function() { "use strict"; function Typeahead(o, www) { var onFocused, onBlurred, onEnterKeyed, onTabKeyed, onEscKeyed, onUpKeyed, onDownKeyed, onLeftKeyed, onRightKeyed, onQueryChanged, onWhitespaceChanged; o = o || {}; if (!o.input) { $.error("missing input"); } if (!o.menu) { $.error("missing menu"); } if (!o.eventBus) { $.error("missing event bus"); } www.mixin(this); this.eventBus = o.eventBus; this.minLength = _.isNumber(o.minLength) ? o.minLength : 1; this.input = o.input; this.menu = o.menu; this.enabled = true; this.active = false; this.input.hasFocus() && this.activate(); this.dir = this.input.getLangDir(); this._hacks(); this.menu.bind().onSync("selectableClicked", this._onSelectableClicked, this).onSync("asyncRequested", this._onAsyncRequested, this).onSync("asyncCanceled", this._onAsyncCanceled, this).onSync("asyncReceived", this._onAsyncReceived, this).onSync("datasetRendered", this._onDatasetRendered, this).onSync("datasetCleared", this._onDatasetCleared, this); onFocused = c(this, "activate", "open", "_onFocused"); onBlurred = c(this, "deactivate", "_onBlurred"); onEnterKeyed = c(this, "isActive", "isOpen", "_onEnterKeyed"); onTabKeyed = c(this, "isActive", "isOpen", "_onTabKeyed"); onEscKeyed = c(this, "isActive", "_onEscKeyed"); onUpKeyed = c(this, "isActive", "open", "_onUpKeyed"); onDownKeyed = c(this, "isActive", "open", "_onDownKeyed"); onLeftKeyed = c(this, "isActive", "isOpen", "_onLeftKeyed"); onRightKeyed = c(this, "isActive", "isOpen", "_onRightKeyed"); onQueryChanged = c(this, "_openIfActive", "_onQueryChanged"); onWhitespaceChanged = c(this, "_openIfActive", "_onWhitespaceChanged"); this.input.bind().onSync("focused", onFocused, this).onSync("blurred", onBlurred, this).onSync("enterKeyed", onEnterKeyed, this).onSync("tabKeyed", onTabKeyed, this).onSync("escKeyed", onEscKeyed, this).onSync("upKeyed", onUpKeyed, this).onSync("downKeyed", onDownKeyed, this).onSync("leftKeyed", onLeftKeyed, this).onSync("rightKeyed", onRightKeyed, this).onSync("queryChanged", onQueryChanged, this).onSync("whitespaceChanged", onWhitespaceChanged, this).onSync("langDirChanged", this._onLangDirChanged, this); } _.mixin(Typeahead.prototype, { _hacks: function hacks() { var $input, $menu; $input = this.input.$input || $("<div>"); $menu = this.menu.$node || $("<div>"); $input.on("blur.tt", function($e) { var active, isActive, hasActive; active = document.activeElement; isActive = $menu.is(active); hasActive = $menu.has(active).length > 0; if (_.isMsie() && (isActive || hasActive)) { $e.preventDefault(); $e.stopImmediatePropagation(); _.defer(function() { $input.focus(); }); } }); $menu.on("mousedown.tt", function($e) { $e.preventDefault(); }); }, _onSelectableClicked: function onSelectableClicked(type, $el) { this.select($el); }, _onDatasetCleared: function onDatasetCleared() { this._updateHint(); }, _onDatasetRendered: function onDatasetRendered(type, suggestions, async, dataset) { this._updateHint(); this.eventBus.trigger("render", suggestions, async, dataset); }, _onAsyncRequested: function onAsyncRequested(type, dataset, query) { this.eventBus.trigger("asyncrequest", query, dataset); }, _onAsyncCanceled: function onAsyncCanceled(type, dataset, query) { this.eventBus.trigger("asynccancel", query, dataset); }, _onAsyncReceived: function onAsyncReceived(type, dataset, query) { this.eventBus.trigger("asyncreceive", query, dataset); }, _onFocused: function onFocused() { this._minLengthMet() && this.menu.update(this.input.getQuery()); }, _onBlurred: function onBlurred() { if (this.input.hasQueryChangedSinceLastFocus()) { this.eventBus.trigger("change", this.input.getQuery()); } }, _onEnterKeyed: function onEnterKeyed(type, $e) { var $selectable; if ($selectable = this.menu.getActiveSelectable()) { if (this.select($selectable)) { $e.preventDefault(); $e.stopPropagation(); } } }, _onTabKeyed: function onTabKeyed(type, $e) { var $selectable; if ($selectable = this.menu.getActiveSelectable()) { this.select($selectable) && $e.preventDefault(); } else if ($selectable = this.menu.getTopSelectable()) { this.autocomplete($selectable) && $e.preventDefault(); } }, _onEscKeyed: function onEscKeyed() { this.close(); }, _onUpKeyed: function onUpKeyed() { this.moveCursor(-1); }, _onDownKeyed: function onDownKeyed() { this.moveCursor(+1); }, _onLeftKeyed: function onLeftKeyed() { if (this.dir === "rtl" && this.input.isCursorAtEnd()) { this.autocomplete(this.menu.getActiveSelectable() || this.menu.getTopSelectable()); } }, _onRightKeyed: function onRightKeyed() { if (this.dir === "ltr" && this.input.isCursorAtEnd()) { this.autocomplete(this.menu.getActiveSelectable() || this.menu.getTopSelectable()); } }, _onQueryChanged: function onQueryChanged(e, query) { this._minLengthMet(query) ? this.menu.update(query) : this.menu.empty(); }, _onWhitespaceChanged: function onWhitespaceChanged() { this._updateHint(); }, _onLangDirChanged: function onLangDirChanged(e, dir) { if (this.dir !== dir) { this.dir = dir; this.menu.setLanguageDirection(dir); } }, _openIfActive: function openIfActive() { this.isActive() && this.open(); }, _minLengthMet: function minLengthMet(query) { query = _.isString(query) ? query : this.input.getQuery() || ""; return query.length >= this.minLength; }, _updateHint: function updateHint() { var $selectable, data, val, query, escapedQuery, frontMatchRegEx, match; $selectable = this.menu.getTopSelectable(); data = this.menu.getSelectableData($selectable); val = this.input.getInputValue(); if (data && !_.isBlankString(val) && !this.input.hasOverflow()) { query = Input.normalizeQuery(val); escapedQuery = _.escapeRegExChars(query); frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i"); match = frontMatchRegEx.exec(data.val); match && this.input.setHint(val + match[1]); } else { this.input.clearHint(); } }, isEnabled: function isEnabled() { return this.enabled; }, enable: function enable() { this.enabled = true; }, disable: function disable() { this.enabled = false; }, isActive: function isActive() { return this.active; }, activate: function activate() { if (this.isActive()) { return true; } else if (!this.isEnabled() || this.eventBus.before("active")) { return false; } else { this.active = true; this.eventBus.trigger("active"); return true; } }, deactivate: function deactivate() { if (!this.isActive()) { return true; } else if (this.eventBus.before("idle")) { return false; } else { this.active = false; this.close(); this.eventBus.trigger("idle"); return true; } }, isOpen: function isOpen() { return this.menu.isOpen(); }, open: function open() { if (!this.isOpen() && !this.eventBus.before("open")) { this.menu.open(); this._updateHint(); this.eventBus.trigger("open"); } return this.isOpen(); }, close: function close() { if (this.isOpen() && !this.eventBus.before("close")) { this.menu.close(); this.input.clearHint(); this.input.resetInputValue(); this.eventBus.trigger("close"); } return !this.isOpen(); }, setVal: function setVal(val) { this.input.setQuery(_.toStr(val)); }, getVal: function getVal() { return this.input.getQuery(); }, select: function select($selectable) { var data = this.menu.getSelectableData($selectable); if (data && !this.eventBus.before("select", data.obj, data.dataset)) { this.input.setQuery(data.val, true); this.eventBus.trigger("select", data.obj, data.dataset); this.close(); return true; } return false; }, autocomplete: function autocomplete($selectable) { var query, data, isValid; query = this.input.getQuery(); data = this.menu.getSelectableData($selectable); isValid = data && query !== data.val; if (isValid && !this.eventBus.before("autocomplete", data.obj, data.dataset)) { this.input.setQuery(data.val); this.eventBus.trigger("autocomplete", data.obj, data.dataset); return true; } return false; }, moveCursor: function moveCursor(delta) { var query, $candidate, data, suggestion, datasetName, cancelMove; query = this.input.getQuery(); $candidate = this.menu.selectableRelativeToCursor(delta); data = this.menu.getSelectableData($candidate); suggestion = data ? data.obj : null; datasetName = data ? data.dataset : null; cancelMove = this._minLengthMet() && this.menu.update(query); if (!cancelMove && !this.eventBus.before("cursorchange", suggestion, datasetName)) { this.menu.setCursor($candidate); if (data) { this.input.setInputValue(data.val); } else { this.input.resetInputValue(); this._updateHint(); } this.eventBus.trigger("cursorchange", suggestion, datasetName); return true; } return false; }, destroy: function destroy() { this.input.destroy(); this.menu.destroy(); } }); return Typeahead; function c(ctx) { var methods = [].slice.call(arguments, 1); return function() { var args = [].slice.call(arguments); _.each(methods, function(method) { return ctx[method].apply(ctx, args); }); }; } }(); (function() { "use strict"; var old, keys, methods; old = $.fn.typeahead; keys = { www: "tt-www", attrs: "tt-attrs", typeahead: "tt-typeahead" }; methods = { initialize: function initialize(o, datasets) { var www; datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1); o = o || {}; www = WWW(o.classNames); return this.each(attach); function attach() { var $input, $wrapper, $hint, $menu, defaultHint, defaultMenu, eventBus, input, menu, typeahead, MenuConstructor; _.each(datasets, function(d) { d.highlight = !!o.highlight; }); $input = $(this); $wrapper = $(www.html.wrapper); $hint = $elOrNull(o.hint); $menu = $elOrNull(o.menu); defaultHint = o.hint !== false && !$hint; defaultMenu = o.menu !== false && !$menu; defaultHint && ($hint = buildHintFromInput($input, www)); defaultMenu && ($menu = $(www.html.menu).css(www.css.menu)); $hint && $hint.val(""); $input = prepInput($input, www); if (defaultHint || defaultMenu) { $wrapper.css(www.css.wrapper); $input.css(defaultHint ? www.css.input : www.css.inputWithNoHint); $input.wrap($wrapper).parent().prepend(defaultHint ? $hint : null).append(defaultMenu ? $menu : null); } MenuConstructor = defaultMenu ? DefaultMenu : Menu; eventBus = new EventBus({ el: $input }); input = new Input({ hint: $hint, input: $input }, www); menu = new MenuConstructor({ node: $menu, datasets: datasets }, www); typeahead = new Typeahead({ input: input, menu: menu, eventBus: eventBus, minLength: o.minLength }, www); $input.data(keys.www, www); $input.data(keys.typeahead, typeahead); } }, isEnabled: function isEnabled() { var enabled; ttEach(this.first(), function(t) { enabled = t.isEnabled(); }); return enabled; }, enable: function enable() { ttEach(this, function(t) { t.enable(); }); return this; }, disable: function disable() { ttEach(this, function(t) { t.disable(); }); return this; }, isActive: function isActive() { var active; ttEach(this.first(), function(t) { active = t.isActive(); }); return active; }, activate: function activate() { ttEach(this, function(t) { t.activate(); }); return this; }, deactivate: function deactivate() { ttEach(this, function(t) { t.deactivate(); }); return this; }, isOpen: function isOpen() { var open; ttEach(this.first(), function(t) { open = t.isOpen(); }); return open; }, open: function open() { ttEach(this, function(t) { t.open(); }); return this; }, close: function close() { ttEach(this, function(t) { t.close(); }); return this; }, select: function select(el) { var success = false, $el = $(el); ttEach(this.first(), function(t) { success = t.select($el); }); return success; }, autocomplete: function autocomplete(el) { var success = false, $el = $(el); ttEach(this.first(), function(t) { success = t.autocomplete($el); }); return success; }, moveCursor: function moveCursoe(delta) { var success = false; ttEach(this.first(), function(t) { success = t.moveCursor(delta); }); return success; }, val: function val(newVal) { var query; if (!arguments.length) { ttEach(this.first(), function(t) { query = t.getVal(); }); return query; } else { ttEach(this, function(t) { t.setVal(_.toStr(newVal)); }); return this; } }, destroy: function destroy() { ttEach(this, function(typeahead, $input) { revert($input); typeahead.destroy(); }); return this; } }; $.fn.typeahead = function(method) { if (methods[method]) { return methods[method].apply(this, [].slice.call(arguments, 1)); } else { return methods.initialize.apply(this, arguments); } }; $.fn.typeahead.noConflict = function noConflict() { $.fn.typeahead = old; return this; }; function ttEach($els, fn) { $els.each(function() { var $input = $(this), typeahead; (typeahead = $input.data(keys.typeahead)) && fn(typeahead, $input); }); } function buildHintFromInput($input, www) { return $input.clone().addClass(www.classes.hint).removeData().css(www.css.hint).css(getBackgroundStyles($input)).prop("readonly", true).removeAttr("id name placeholder required").attr({ autocomplete: "off", spellcheck: "false", tabindex: -1 }); } function prepInput($input, www) { $input.data(keys.attrs, { dir: $input.attr("dir"), autocomplete: $input.attr("autocomplete"), spellcheck: $input.attr("spellcheck"), style: $input.attr("style") }); $input.addClass(www.classes.input).attr({ autocomplete: "off", spellcheck: false }); try { !$input.attr("dir") && $input.attr("dir", "auto"); } catch (e) {} return $input; } function getBackgroundStyles($el) { return { backgroundAttachment: $el.css("background-attachment"), backgroundClip: $el.css("background-clip"), backgroundColor: $el.css("background-color"), backgroundImage: $el.css("background-image"), backgroundOrigin: $el.css("background-origin"), backgroundPosition: $el.css("background-position"), backgroundRepeat: $el.css("background-repeat"), backgroundSize: $el.css("background-size") }; } function revert($input) { var www, $wrapper; www = $input.data(keys.www); $wrapper = $input.parent().filter(www.selectors.wrapper); _.each($input.data(keys.attrs), function(val, key) { _.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val); }); $input.removeData(keys.typeahead).removeData(keys.www).removeData(keys.attr).removeClass(www.classes.input); if ($wrapper.length) { $input.detach().insertAfter($wrapper); $wrapper.remove(); } } function $elOrNull(obj) { var isValid, $el; isValid = _.isJQuery(obj) || _.isElement(obj); $el = isValid ? $(obj).first() : []; return $el.length ? $el : null; } })(); });
/* http://keith-wood.name/datepick.html Georgian localisation for jQuery Datepicker. Andrei Gorbushkin. */ (function($) { $.datepick.regionalOptions.ka = { monthNames: ['იანვარი','თებერვალი','მარტი','აპრილი','მაისი','ივნისი', 'ივლისი','აგვისტო','სექტემბერი','ოქტომბერი','ნოემბერი','დეკემბერი'], monthNamesShort: ['იან', 'თებ', 'მარ', 'აპრ', 'მაისი', 'ივნ', 'ივლ', 'აგვ', 'სექ', 'ოქტ', 'ნოე', 'დეკ'], dayNames: ['კვირა', 'ორშაბათი', 'სამშაბათი', 'ოთხშაბათი', 'ხუთშაბათი', 'პარასკევი', 'შაბათი'], dayNamesShort: ['კვ', 'ორშ', 'სამ', 'ოთხ', 'ხუთ', 'პარ', 'შაბ'], dayNamesMin: ['კვ','ორ','სმ','ოთ', 'ხშ', 'პრ','შბ'], dateFormat: 'dd/mm/yyyy', firstDay: 1, renderer: $.datepick.defaultRenderer, prevText: '<უკან', prevStatus: 'წინა თვე', prevJumpText: '&#x3c;&#x3c;', prevJumpStatus: 'წინა წელი', nextText: 'წინ>', nextStatus: 'შემდეგი თვე', nextJumpText: '&#x3e;&#x3e;', nextJumpStatus: 'შემდეგი წელი', currentText: 'მიმდინარე', currentStatus: 'მიმდინარე თვე', todayText: 'დღეს', todayStatus: 'მიმდინარე დღე', clearText: 'გასუფთავება', clearStatus: 'მიმდინარე თარიღის წაშლა', closeText: 'არის', closeStatus: 'დახურვა უცვლილებოდ', yearStatus: 'სხვა წელი', monthStatus: 'სხვა თვე', weekText: 'კვ', weekStatus: 'წლის კვირა', dayStatus: 'აირჩიეთ DD, M d', defaultStatus: 'აიღჩიეთ თარიღი', isRTL: false }; $.datepick.setDefaults($.datepick.regionalOptions.ka); })(jQuery);
/* * /MathJax/jax/output/CommonHTML/autoload/ms.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.Register.StartupHook("CommonHTML Jax Ready",function(){var c="2.7.0-beta";var a=MathJax.ElementJax.mml,b=MathJax.OutputJax.CommonHTML;a.ms.Augment({toCommonHTML:function(e){e=this.CHTMLcreateNode(e);this.CHTMLhandleStyle(e);this.CHTMLgetVariant();this.CHTMLhandleScale(e);b.BBOX.empty(this.CHTML);var d=this.getValues("lquote","rquote","mathvariant");if(!this.hasValue("lquote")||d.lquote==='"'){d.lquote="\u201C"}if(!this.hasValue("rquote")||d.rquote==='"'){d.rquote="\u201D"}if(d.lquote==="\u201C"&&d.mathvariant==="monospace"){d.lquote='"'}if(d.rquote==="\u201D"&&d.mathvariant==="monospace"){d.rquote='"'}var f=d.lquote+this.data.join("")+d.rquote;this.CHTMLhandleText(e,f,this.CHTMLvariant);this.CHTML.clean();this.CHTMLhandleSpace(e);this.CHTMLhandleBBox(e);this.CHTMLhandleColor(e);return e}});MathJax.Hub.Startup.signal.Post("CommonHTML ms Ready");MathJax.Ajax.loadComplete(b.autoloadDir+"/ms.js")});
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v6.2.1 * @link http://www.ag-grid.com/ * @license MIT */ 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); }; var columnUtils_1 = require("./columnUtils"); var columnGroup_1 = require("../entities/columnGroup"); var originalColumnGroup_1 = require("../entities/originalColumnGroup"); var context_1 = require("../context/context"); var context_2 = require("../context/context"); // takes in a list of columns, as specified by the column definitions, and returns column groups var DisplayedGroupCreator = (function () { function DisplayedGroupCreator() { } DisplayedGroupCreator.prototype.createDisplayedGroups = function (sortedVisibleColumns, balancedColumnTree, groupInstanceIdCreator) { var _this = this; var result = []; var previousRealPath; var previousOriginalPath; // go through each column, then do a bottom up comparison to the previous column, and start // to share groups if they converge at any point. sortedVisibleColumns.forEach(function (currentColumn) { var currentOriginalPath = _this.getOriginalPathForColumn(balancedColumnTree, currentColumn); var currentRealPath = []; var firstColumn = !previousOriginalPath; for (var i = 0; i < currentOriginalPath.length; i++) { if (firstColumn || currentOriginalPath[i] !== previousOriginalPath[i]) { // new group needed var originalGroup = currentOriginalPath[i]; var groupId = originalGroup.getGroupId(); var instanceId = groupInstanceIdCreator.getInstanceIdForKey(groupId); var newGroup = new columnGroup_1.ColumnGroup(originalGroup, groupId, instanceId); currentRealPath[i] = newGroup; // if top level, add to result, otherwise add to parent if (i == 0) { result.push(newGroup); } else { currentRealPath[i - 1].addChild(newGroup); } } else { // reuse old group currentRealPath[i] = previousRealPath[i]; } } var noColumnGroups = currentRealPath.length === 0; if (noColumnGroups) { // if we are not grouping, then the result of the above is an empty // path (no groups), and we just add the column to the root list. result.push(currentColumn); } else { var leafGroup = currentRealPath[currentRealPath.length - 1]; leafGroup.addChild(currentColumn); } previousRealPath = currentRealPath; previousOriginalPath = currentOriginalPath; }); this.setupParentsIntoColumns(result, null); return result; }; DisplayedGroupCreator.prototype.setupParentsIntoColumns = function (columnsOrGroups, parent) { var _this = this; columnsOrGroups.forEach(function (columnsOrGroup) { columnsOrGroup.setParent(parent); if (columnsOrGroup instanceof columnGroup_1.ColumnGroup) { var columnGroup = columnsOrGroup; _this.setupParentsIntoColumns(columnGroup.getChildren(), columnGroup); } }); }; DisplayedGroupCreator.prototype.createFakePath = function (balancedColumnTree) { var result = []; var currentChildren = balancedColumnTree; // this while look does search on the balanced tree, so our result is the right length var index = 0; while (currentChildren && currentChildren[0] && currentChildren[0] instanceof originalColumnGroup_1.OriginalColumnGroup) { // putting in a deterministic fake id, in case the API in the future needs to reference the col result.push(new originalColumnGroup_1.OriginalColumnGroup(null, 'FAKE_PATH_' + index, true)); currentChildren = currentChildren[0].getChildren(); index++; } return result; }; DisplayedGroupCreator.prototype.getOriginalPathForColumn = function (balancedColumnTree, column) { var result = []; var found = false; recursePath(balancedColumnTree, 0); // it's possible we didn't find a path. this happens if the column is generated // by the grid, in that the definition didn't come from the client. in this case, // we create a fake original path. if (found) { return result; } else { return this.createFakePath(balancedColumnTree); } function recursePath(balancedColumnTree, dept) { for (var i = 0; i < balancedColumnTree.length; i++) { if (found) { // quit the search, so 'result' is kept with the found result return; } var node = balancedColumnTree[i]; if (node instanceof originalColumnGroup_1.OriginalColumnGroup) { var nextNode = node; recursePath(nextNode.getChildren(), dept + 1); result[dept] = node; } else { if (node === column) { found = true; } } } } }; __decorate([ context_2.Autowired('columnUtils'), __metadata('design:type', columnUtils_1.ColumnUtils) ], DisplayedGroupCreator.prototype, "columnUtils", void 0); DisplayedGroupCreator = __decorate([ context_1.Bean('displayedGroupCreator'), __metadata('design:paramtypes', []) ], DisplayedGroupCreator); return DisplayedGroupCreator; })(); exports.DisplayedGroupCreator = DisplayedGroupCreator;
import Ember from 'ember'; import AuthenticatedRoute from 'ghost/routes/authenticated'; import ShortcutsRoute from 'ghost/mixins/shortcuts-route'; import PaginationRouteMixin from 'ghost/mixins/pagination-route'; export default AuthenticatedRoute.extend(ShortcutsRoute, PaginationRouteMixin, { titleToken: 'Content', paginationModel: 'post', paginationSettings: { status: 'all', staticPages: 'all' }, model() { let paginationSettings = this.get('paginationSettings'); return this.get('session.user').then((user) => { if (user.get('isAuthor')) { paginationSettings.filter = paginationSettings.filter ? `${paginationSettings.filter}+author:${user.get('slug')}` : `author:${user.get('slug')}`; } return this.loadFirstPage().then(() => { // using `.filter` allows the template to auto-update when new models are pulled in from the server. // we just need to 'return true' to allow all models by default. return this.store.filter('post', (post) => { if (user.get('isAuthor')) { return post.isAuthoredByUser(user); } return true; }); }); }); }, stepThroughPosts(step) { let currentPost = this.get('controller.currentPost'); let posts = this.get('controller.sortedPosts'); let length = posts.get('length'); let newPosition = posts.indexOf(currentPost) + step; // if we are on the first or last item // just do nothing (desired behavior is to not // loop around) if (newPosition >= length) { return; } else if (newPosition < 0) { return; } this.transitionTo('posts.post', posts.objectAt(newPosition)); }, scrollContent(amount) { let content = Ember.$('.js-content-preview'); let scrolled = content.scrollTop(); content.scrollTop(scrolled + 50 * amount); }, shortcuts: { 'up, k': 'moveUp', 'down, j': 'moveDown', left: 'focusList', right: 'focusContent', c: 'newPost' }, actions: { focusList() { this.controller.set('keyboardFocus', 'postList'); }, focusContent() { this.controller.set('keyboardFocus', 'postContent'); }, newPost() { this.transitionTo('editor.new'); }, moveUp() { if (this.controller.get('postContentFocused')) { this.scrollContent(-1); } else { this.stepThroughPosts(-1); } }, moveDown() { if (this.controller.get('postContentFocused')) { this.scrollContent(1); } else { this.stepThroughPosts(1); } } } });
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v4.2.4 * @link http://www.ag-grid.com/ * @license MIT */ 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); }; var utils_1 = require("../utils"); var svgFactory_1 = require("../svgFactory"); var columnController_1 = require("../columnController/columnController"); var filterManager_1 = require("../filter/filterManager"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var column_1 = require("../entities/column"); var horizontalDragService_1 = require("./horizontalDragService"); var context_1 = require("../context/context"); var cssClassApplier_1 = require("./cssClassApplier"); var dragAndDropService_1 = require("../dragAndDrop/dragAndDropService"); var svgFactory = svgFactory_1.SvgFactory.getInstance(); var RenderedHeaderGroupCell = (function () { function RenderedHeaderGroupCell(columnGroup, eRoot, parentScope, dragSourceDropTarget) { this.destroyFunctions = []; this.columnGroup = columnGroup; this.parentScope = parentScope; this.eRoot = eRoot; this.parentScope = parentScope; this.dragSourceDropTarget = dragSourceDropTarget; } RenderedHeaderGroupCell.prototype.getGui = function () { return this.eHeaderGroupCell; }; RenderedHeaderGroupCell.prototype.onIndividualColumnResized = function (column) { if (this.columnGroup.isChildInThisGroupDeepSearch(column)) { this.setWidth(); } }; RenderedHeaderGroupCell.prototype.init = function () { this.eHeaderGroupCell = document.createElement('div'); cssClassApplier_1.CssClassApplier.addHeaderClassesFromCollDef(this.columnGroup.getColGroupDef(), this.eHeaderGroupCell, this.gridOptionsWrapper); this.displayName = this.columnGroup.getHeaderName(); this.setupResize(); this.addClasses(); this.setupLabel(); this.setupMove(); this.setWidth(); }; RenderedHeaderGroupCell.prototype.setupLabel = function () { // no renderer, default text render if (this.displayName && this.displayName !== '') { var eGroupCellLabel = document.createElement("div"); eGroupCellLabel.className = 'ag-header-group-cell-label'; this.eHeaderGroupCell.appendChild(eGroupCellLabel); if (utils_1.Utils.isBrowserSafari()) { eGroupCellLabel.style.display = 'table-cell'; } var eInnerText = document.createElement("span"); eInnerText.className = 'ag-header-group-text'; eInnerText.innerHTML = this.displayName; eGroupCellLabel.appendChild(eInnerText); if (this.columnGroup.isExpandable()) { this.addGroupExpandIcon(eGroupCellLabel); } } }; RenderedHeaderGroupCell.prototype.addClasses = function () { utils_1.Utils.addCssClass(this.eHeaderGroupCell, 'ag-header-group-cell'); // having different classes below allows the style to not have a bottom border // on the group header, if no group is specified if (this.columnGroup.getColGroupDef()) { utils_1.Utils.addCssClass(this.eHeaderGroupCell, 'ag-header-group-cell-with-group'); } else { utils_1.Utils.addCssClass(this.eHeaderGroupCell, 'ag-header-group-cell-no-group'); } }; RenderedHeaderGroupCell.prototype.setupResize = function () { var _this = this; if (!this.gridOptionsWrapper.isEnableColResize()) { return; } this.eHeaderCellResize = document.createElement("div"); this.eHeaderCellResize.className = "ag-header-cell-resize"; this.eHeaderGroupCell.appendChild(this.eHeaderCellResize); this.dragService.addDragHandling({ eDraggableElement: this.eHeaderCellResize, eBody: this.eRoot, cursor: 'col-resize', startAfterPixels: 0, onDragStart: this.onDragStart.bind(this), onDragging: this.onDragging.bind(this) }); if (!this.gridOptionsWrapper.isSuppressAutoSize()) { this.eHeaderCellResize.addEventListener('dblclick', function (event) { // get list of all the column keys we are responsible for var keys = []; _this.columnGroup.getDisplayedLeafColumns().forEach(function (column) { // not all cols in the group may be participating with auto-resize if (!column.getColDef().suppressAutoSize) { keys.push(column.getColId()); } }); if (keys.length > 0) { _this.columnController.autoSizeColumns(keys); } }); } }; RenderedHeaderGroupCell.prototype.setupMove = function () { var eLabel = this.eHeaderGroupCell.querySelector('.ag-header-group-cell-label'); if (!eLabel) { return; } if (this.gridOptionsWrapper.isSuppressMovableColumns()) { return; } // if any child is fixed, then don't allow moving var atLeastOneChildNotMovable = false; this.columnGroup.getLeafColumns().forEach(function (column) { if (column.getColDef().suppressMovable) { atLeastOneChildNotMovable = true; } }); if (atLeastOneChildNotMovable) { return; } // don't allow moving of headers when forPrint, as the header overlay doesn't exist if (this.gridOptionsWrapper.isForPrint()) { return; } if (eLabel) { var dragSource = { eElement: eLabel, dragItemName: this.displayName, // we add in the original group leaf columns, so we move both visible and non-visible items dragItem: this.getAllColumnsInThisGroup(), dragSourceDropTarget: this.dragSourceDropTarget }; this.dragAndDropService.addDragSource(dragSource); } }; // when moving the columns, we want to move all the columns in this group in one go, and in the order they // are currently in the screen. RenderedHeaderGroupCell.prototype.getAllColumnsInThisGroup = function () { var allColumnsOriginalOrder = this.columnGroup.getOriginalColumnGroup().getLeafColumns(); var allColumnsCurrentOrder = []; this.columnController.getAllDisplayedColumns().forEach(function (column) { if (allColumnsOriginalOrder.indexOf(column) >= 0) { allColumnsCurrentOrder.push(column); utils_1.Utils.removeFromArray(allColumnsOriginalOrder, column); } }); // we are left with non-visible columns, stick these in at the end allColumnsOriginalOrder.forEach(function (column) { return allColumnsCurrentOrder.push(column); }); return allColumnsCurrentOrder; }; RenderedHeaderGroupCell.prototype.setWidth = function () { var _this = this; var widthChangedListener = function () { _this.eHeaderGroupCell.style.width = _this.columnGroup.getActualWidth() + 'px'; }; this.columnGroup.getLeafColumns().forEach(function (column) { column.addEventListener(column_1.Column.EVENT_WIDTH_CHANGED, widthChangedListener); _this.destroyFunctions.push(function () { column.removeEventListener(column_1.Column.EVENT_WIDTH_CHANGED, widthChangedListener); }); }); widthChangedListener(); }; RenderedHeaderGroupCell.prototype.destroy = function () { this.destroyFunctions.forEach(function (func) { func(); }); }; RenderedHeaderGroupCell.prototype.addGroupExpandIcon = function (eGroupCellLabel) { var eGroupIcon; if (this.columnGroup.isExpanded()) { eGroupIcon = utils_1.Utils.createIcon('columnGroupOpened', this.gridOptionsWrapper, null, svgFactory.createGroupContractedIcon); } else { eGroupIcon = utils_1.Utils.createIcon('columnGroupClosed', this.gridOptionsWrapper, null, svgFactory.createGroupExpandedIcon); } eGroupIcon.className = 'ag-header-expand-icon'; eGroupCellLabel.appendChild(eGroupIcon); var that = this; eGroupIcon.onclick = function () { var newExpandedValue = !that.columnGroup.isExpanded(); that.columnController.setColumnGroupOpened(that.columnGroup, newExpandedValue); }; }; RenderedHeaderGroupCell.prototype.onDragStart = function () { var _this = this; this.groupWidthStart = this.columnGroup.getActualWidth(); this.childrenWidthStarts = []; this.columnGroup.getDisplayedLeafColumns().forEach(function (column) { _this.childrenWidthStarts.push(column.getActualWidth()); }); }; RenderedHeaderGroupCell.prototype.onDragging = function (dragChange, finished) { var _this = this; var newWidth = this.groupWidthStart + dragChange; var minWidth = this.columnGroup.getMinWidth(); if (newWidth < minWidth) { newWidth = minWidth; } // distribute the new width to the child headers var changeRatio = newWidth / this.groupWidthStart; // keep track of pixels used, and last column gets the remaining, // to cater for rounding errors, and min width adjustments var pixelsToDistribute = newWidth; var displayedColumns = this.columnGroup.getDisplayedLeafColumns(); displayedColumns.forEach(function (column, index) { var notLastCol = index !== (displayedColumns.length - 1); var newChildSize; if (notLastCol) { // if not the last col, calculate the column width as normal var startChildSize = _this.childrenWidthStarts[index]; newChildSize = startChildSize * changeRatio; if (newChildSize < column.getMinWidth()) { newChildSize = column.getMinWidth(); } pixelsToDistribute -= newChildSize; } else { // if last col, give it the remaining pixels newChildSize = pixelsToDistribute; } _this.columnController.setColumnWidth(column, newChildSize, finished); }); }; __decorate([ context_1.Autowired('filterManager'), __metadata('design:type', filterManager_1.FilterManager) ], RenderedHeaderGroupCell.prototype, "filterManager", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper) ], RenderedHeaderGroupCell.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('horizontalDragService'), __metadata('design:type', horizontalDragService_1.HorizontalDragService) ], RenderedHeaderGroupCell.prototype, "dragService", void 0); __decorate([ context_1.Autowired('columnController'), __metadata('design:type', columnController_1.ColumnController) ], RenderedHeaderGroupCell.prototype, "columnController", void 0); __decorate([ context_1.Autowired('dragAndDropService'), __metadata('design:type', dragAndDropService_1.DragAndDropService) ], RenderedHeaderGroupCell.prototype, "dragAndDropService", void 0); __decorate([ context_1.PostConstruct, __metadata('design:type', Function), __metadata('design:paramtypes', []), __metadata('design:returntype', void 0) ], RenderedHeaderGroupCell.prototype, "init", null); return RenderedHeaderGroupCell; })(); exports.RenderedHeaderGroupCell = RenderedHeaderGroupCell;
angular.module('example', ['angular-meteor', 'ngFileUpload']); angular.module('example').controller('ExampleCtrl', ['$scope', function ($scope) { $scope.images = $scope.$meteorCollectionFS(Images, false, Images); $scope.addImages = function (files) { $scope.images.save(files); }; $scope.removeImage = function(image) { $scope.images.remove(image); }; }]);
//>>built define("dojox/mobile/bidi/SpinWheelSlot",["dojo/_base/declare","dojo/_base/window","dojo/_base/array","dojo/dom-construct","./common"],function(_1,_2,_3,_4,_5){ return _1(null,{postCreate:function(){ this.inherited(arguments); if(!this.textDir&&this.getParent()&&this.getParent().get("textDir")){ this.set("textDir",this.getParent().get("textDir")); } },_setTextDirAttr:function(_6){ if(_6&&(!this._created||this.textDir!==_6)){ this.textDir=_6; this._setTextDirToNodes(this.textDir); } },_setTextDirToNodes:function(_7){ _3.forEach(this.panelNodes,function(_8){ _3.forEach(_8.childNodes,function(_9,i){ _9.innerHTML=_5.removeUCCFromText(_9.innerHTML); _9.innerHTML=_5.enforceTextDirWithUcc(_9.innerHTML,this.textDir); _9.style.textAlign=(this.dir.toLowerCase()==="rtl")?"right":"left"; },this); },this); }}); });
/* * /MathJax/localization/gl/HTML-CSS.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.Localization.addTranslation("gl","HTML-CSS",{version:"2.7.0",isLoaded:true,strings:{LoadWebFont:"Cargando o tipo de letra web %1",CantLoadWebFont:"Non se pode cargar o tipo de letra web %1",FirefoxCantLoadWebFont:"Firefox non pode cargar os tipos de letra web desde un servidor remoto",CantFindFontUsing:"Non se pode atopar un tipo de letra v\u00E1lido utilizando %1",WebFontsNotAvailable:"Os tipos de letra web non est\u00E1n dispo\u00F1ibles; use os tipos de letra de imaxe no seu lugar"}});MathJax.Ajax.loadComplete("[MathJax]/localization/gl/HTML-CSS.js");
/*! * jQuery UI Effects 1.11.3 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/effects-core/ */ (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { var dataSpace = "ui-effects-", // Create a local jQuery because jQuery Color relies on it and the // global may not exist with AMD and a custom build (#10199) jQuery = $; $.effects = { effect: {} }; /*! * jQuery Color Animations v2.1.2 * https://github.com/jquery/jquery-color * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * Date: Wed Jan 16 08:47:09 2013 -0600 */ (function( jQuery, undefined ) { var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor", // plusequals test for += 100 -= 100 rplusequals = /^([\-+])=\s*(\d+\.?\d*)/, // a set of RE's that can match strings and generate color tuples. stringParsers = [ { re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ], execResult[ 3 ], execResult[ 4 ] ]; } }, { re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ] * 2.55, execResult[ 2 ] * 2.55, execResult[ 3 ] * 2.55, execResult[ 4 ] ]; } }, { // this regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ], 16 ), parseInt( execResult[ 2 ], 16 ), parseInt( execResult[ 3 ], 16 ) ]; } }, { // this regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9])([a-f0-9])([a-f0-9])/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ), parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ), parseInt( execResult[ 3 ] + execResult[ 3 ], 16 ) ]; } }, { re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, space: "hsla", parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ] / 100, execResult[ 3 ] / 100, execResult[ 4 ] ]; } } ], // jQuery.Color( ) color = jQuery.Color = function( color, green, blue, alpha ) { return new jQuery.Color.fn.parse( color, green, blue, alpha ); }, spaces = { rgba: { props: { red: { idx: 0, type: "byte" }, green: { idx: 1, type: "byte" }, blue: { idx: 2, type: "byte" } } }, hsla: { props: { hue: { idx: 0, type: "degrees" }, saturation: { idx: 1, type: "percent" }, lightness: { idx: 2, type: "percent" } } } }, propTypes = { "byte": { floor: true, max: 255 }, "percent": { max: 1 }, "degrees": { mod: 360, floor: true } }, support = color.support = {}, // element for support tests supportElem = jQuery( "<p>" )[ 0 ], // colors = jQuery.Color.names colors, // local aliases of functions called often each = jQuery.each; // determine rgba support immediately supportElem.style.cssText = "background-color:rgba(1,1,1,.5)"; support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1; // define cache name and alpha properties // for rgba and hsla spaces each( spaces, function( spaceName, space ) { space.cache = "_" + spaceName; space.props.alpha = { idx: 3, type: "percent", def: 1 }; }); function clamp( value, prop, allowEmpty ) { var type = propTypes[ prop.type ] || {}; if ( value == null ) { return (allowEmpty || !prop.def) ? null : prop.def; } // ~~ is an short way of doing floor for positive numbers value = type.floor ? ~~value : parseFloat( value ); // IE will pass in empty strings as value for alpha, // which will hit this case if ( isNaN( value ) ) { return prop.def; } if ( type.mod ) { // we add mod before modding to make sure that negatives values // get converted properly: -10 -> 350 return (value + type.mod) % type.mod; } // for now all property types without mod have min and max return 0 > value ? 0 : type.max < value ? type.max : value; } function stringParse( string ) { var inst = color(), rgba = inst._rgba = []; string = string.toLowerCase(); each( stringParsers, function( i, parser ) { var parsed, match = parser.re.exec( string ), values = match && parser.parse( match ), spaceName = parser.space || "rgba"; if ( values ) { parsed = inst[ spaceName ]( values ); // if this was an rgba parse the assignment might happen twice // oh well.... inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ]; rgba = inst._rgba = parsed._rgba; // exit each( stringParsers ) here because we matched return false; } }); // Found a stringParser that handled it if ( rgba.length ) { // if this came from a parsed string, force "transparent" when alpha is 0 // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0) if ( rgba.join() === "0,0,0,0" ) { jQuery.extend( rgba, colors.transparent ); } return inst; } // named colors return colors[ string ]; } color.fn = jQuery.extend( color.prototype, { parse: function( red, green, blue, alpha ) { if ( red === undefined ) { this._rgba = [ null, null, null, null ]; return this; } if ( red.jquery || red.nodeType ) { red = jQuery( red ).css( green ); green = undefined; } var inst = this, type = jQuery.type( red ), rgba = this._rgba = []; // more than 1 argument specified - assume ( red, green, blue, alpha ) if ( green !== undefined ) { red = [ red, green, blue, alpha ]; type = "array"; } if ( type === "string" ) { return this.parse( stringParse( red ) || colors._default ); } if ( type === "array" ) { each( spaces.rgba.props, function( key, prop ) { rgba[ prop.idx ] = clamp( red[ prop.idx ], prop ); }); return this; } if ( type === "object" ) { if ( red instanceof color ) { each( spaces, function( spaceName, space ) { if ( red[ space.cache ] ) { inst[ space.cache ] = red[ space.cache ].slice(); } }); } else { each( spaces, function( spaceName, space ) { var cache = space.cache; each( space.props, function( key, prop ) { // if the cache doesn't exist, and we know how to convert if ( !inst[ cache ] && space.to ) { // if the value was null, we don't need to copy it // if the key was alpha, we don't need to copy it either if ( key === "alpha" || red[ key ] == null ) { return; } inst[ cache ] = space.to( inst._rgba ); } // this is the only case where we allow nulls for ALL properties. // call clamp with alwaysAllowEmpty inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true ); }); // everything defined but alpha? if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) { // use the default of 1 inst[ cache ][ 3 ] = 1; if ( space.from ) { inst._rgba = space.from( inst[ cache ] ); } } }); } return this; } }, is: function( compare ) { var is = color( compare ), same = true, inst = this; each( spaces, function( _, space ) { var localCache, isCache = is[ space.cache ]; if (isCache) { localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || []; each( space.props, function( _, prop ) { if ( isCache[ prop.idx ] != null ) { same = ( isCache[ prop.idx ] === localCache[ prop.idx ] ); return same; } }); } return same; }); return same; }, _space: function() { var used = [], inst = this; each( spaces, function( spaceName, space ) { if ( inst[ space.cache ] ) { used.push( spaceName ); } }); return used.pop(); }, transition: function( other, distance ) { var end = color( other ), spaceName = end._space(), space = spaces[ spaceName ], startColor = this.alpha() === 0 ? color( "transparent" ) : this, start = startColor[ space.cache ] || space.to( startColor._rgba ), result = start.slice(); end = end[ space.cache ]; each( space.props, function( key, prop ) { var index = prop.idx, startValue = start[ index ], endValue = end[ index ], type = propTypes[ prop.type ] || {}; // if null, don't override start value if ( endValue === null ) { return; } // if null - use end if ( startValue === null ) { result[ index ] = endValue; } else { if ( type.mod ) { if ( endValue - startValue > type.mod / 2 ) { startValue += type.mod; } else if ( startValue - endValue > type.mod / 2 ) { startValue -= type.mod; } } result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop ); } }); return this[ spaceName ]( result ); }, blend: function( opaque ) { // if we are already opaque - return ourself if ( this._rgba[ 3 ] === 1 ) { return this; } var rgb = this._rgba.slice(), a = rgb.pop(), blend = color( opaque )._rgba; return color( jQuery.map( rgb, function( v, i ) { return ( 1 - a ) * blend[ i ] + a * v; })); }, toRgbaString: function() { var prefix = "rgba(", rgba = jQuery.map( this._rgba, function( v, i ) { return v == null ? ( i > 2 ? 1 : 0 ) : v; }); if ( rgba[ 3 ] === 1 ) { rgba.pop(); prefix = "rgb("; } return prefix + rgba.join() + ")"; }, toHslaString: function() { var prefix = "hsla(", hsla = jQuery.map( this.hsla(), function( v, i ) { if ( v == null ) { v = i > 2 ? 1 : 0; } // catch 1 and 2 if ( i && i < 3 ) { v = Math.round( v * 100 ) + "%"; } return v; }); if ( hsla[ 3 ] === 1 ) { hsla.pop(); prefix = "hsl("; } return prefix + hsla.join() + ")"; }, toHexString: function( includeAlpha ) { var rgba = this._rgba.slice(), alpha = rgba.pop(); if ( includeAlpha ) { rgba.push( ~~( alpha * 255 ) ); } return "#" + jQuery.map( rgba, function( v ) { // default to 0 when nulls exist v = ( v || 0 ).toString( 16 ); return v.length === 1 ? "0" + v : v; }).join(""); }, toString: function() { return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString(); } }); color.fn.parse.prototype = color.fn; // hsla conversions adapted from: // https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021 function hue2rgb( p, q, h ) { h = ( h + 1 ) % 1; if ( h * 6 < 1 ) { return p + ( q - p ) * h * 6; } if ( h * 2 < 1) { return q; } if ( h * 3 < 2 ) { return p + ( q - p ) * ( ( 2 / 3 ) - h ) * 6; } return p; } spaces.hsla.to = function( rgba ) { if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) { return [ null, null, null, rgba[ 3 ] ]; } var r = rgba[ 0 ] / 255, g = rgba[ 1 ] / 255, b = rgba[ 2 ] / 255, a = rgba[ 3 ], max = Math.max( r, g, b ), min = Math.min( r, g, b ), diff = max - min, add = max + min, l = add * 0.5, h, s; if ( min === max ) { h = 0; } else if ( r === max ) { h = ( 60 * ( g - b ) / diff ) + 360; } else if ( g === max ) { h = ( 60 * ( b - r ) / diff ) + 120; } else { h = ( 60 * ( r - g ) / diff ) + 240; } // chroma (diff) == 0 means greyscale which, by definition, saturation = 0% // otherwise, saturation is based on the ratio of chroma (diff) to lightness (add) if ( diff === 0 ) { s = 0; } else if ( l <= 0.5 ) { s = diff / add; } else { s = diff / ( 2 - add ); } return [ Math.round(h) % 360, s, l, a == null ? 1 : a ]; }; spaces.hsla.from = function( hsla ) { if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) { return [ null, null, null, hsla[ 3 ] ]; } var h = hsla[ 0 ] / 360, s = hsla[ 1 ], l = hsla[ 2 ], a = hsla[ 3 ], q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s, p = 2 * l - q; return [ Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ), Math.round( hue2rgb( p, q, h ) * 255 ), Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ), a ]; }; each( spaces, function( spaceName, space ) { var props = space.props, cache = space.cache, to = space.to, from = space.from; // makes rgba() and hsla() color.fn[ spaceName ] = function( value ) { // generate a cache for this space if it doesn't exist if ( to && !this[ cache ] ) { this[ cache ] = to( this._rgba ); } if ( value === undefined ) { return this[ cache ].slice(); } var ret, type = jQuery.type( value ), arr = ( type === "array" || type === "object" ) ? value : arguments, local = this[ cache ].slice(); each( props, function( key, prop ) { var val = arr[ type === "object" ? key : prop.idx ]; if ( val == null ) { val = local[ prop.idx ]; } local[ prop.idx ] = clamp( val, prop ); }); if ( from ) { ret = color( from( local ) ); ret[ cache ] = local; return ret; } else { return color( local ); } }; // makes red() green() blue() alpha() hue() saturation() lightness() each( props, function( key, prop ) { // alpha is included in more than one space if ( color.fn[ key ] ) { return; } color.fn[ key ] = function( value ) { var vtype = jQuery.type( value ), fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ), local = this[ fn ](), cur = local[ prop.idx ], match; if ( vtype === "undefined" ) { return cur; } if ( vtype === "function" ) { value = value.call( this, cur ); vtype = jQuery.type( value ); } if ( value == null && prop.empty ) { return this; } if ( vtype === "string" ) { match = rplusequals.exec( value ); if ( match ) { value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 ); } } local[ prop.idx ] = value; return this[ fn ]( local ); }; }); }); // add cssHook and .fx.step function for each named hook. // accept a space separated string of properties color.hook = function( hook ) { var hooks = hook.split( " " ); each( hooks, function( i, hook ) { jQuery.cssHooks[ hook ] = { set: function( elem, value ) { var parsed, curElem, backgroundColor = ""; if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) { value = color( parsed || value ); if ( !support.rgba && value._rgba[ 3 ] !== 1 ) { curElem = hook === "backgroundColor" ? elem.parentNode : elem; while ( (backgroundColor === "" || backgroundColor === "transparent") && curElem && curElem.style ) { try { backgroundColor = jQuery.css( curElem, "backgroundColor" ); curElem = curElem.parentNode; } catch ( e ) { } } value = value.blend( backgroundColor && backgroundColor !== "transparent" ? backgroundColor : "_default" ); } value = value.toRgbaString(); } try { elem.style[ hook ] = value; } catch ( e ) { // wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit' } } }; jQuery.fx.step[ hook ] = function( fx ) { if ( !fx.colorInit ) { fx.start = color( fx.elem, hook ); fx.end = color( fx.end ); fx.colorInit = true; } jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) ); }; }); }; color.hook( stepHooks ); jQuery.cssHooks.borderColor = { expand: function( value ) { var expanded = {}; each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) { expanded[ "border" + part + "Color" ] = value; }); return expanded; } }; // Basic color names only. // Usage of any of the other color names requires adding yourself or including // jquery.color.svg-names.js. colors = jQuery.Color.names = { // 4.1. Basic color keywords aqua: "#00ffff", black: "#000000", blue: "#0000ff", fuchsia: "#ff00ff", gray: "#808080", green: "#008000", lime: "#00ff00", maroon: "#800000", navy: "#000080", olive: "#808000", purple: "#800080", red: "#ff0000", silver: "#c0c0c0", teal: "#008080", white: "#ffffff", yellow: "#ffff00", // 4.2.3. "transparent" color keyword transparent: [ null, null, null, 0 ], _default: "#ffffff" }; })( jQuery ); /******************************************************************************/ /****************************** CLASS ANIMATIONS ******************************/ /******************************************************************************/ (function() { var classAnimationActions = [ "add", "remove", "toggle" ], shorthandStyles = { border: 1, borderBottom: 1, borderColor: 1, borderLeft: 1, borderRight: 1, borderTop: 1, borderWidth: 1, margin: 1, padding: 1 }; $.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) { $.fx.step[ prop ] = function( fx ) { if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) { jQuery.style( fx.elem, prop, fx.end ); fx.setAttr = true; } }; }); function getElementStyles( elem ) { var key, len, style = elem.ownerDocument.defaultView ? elem.ownerDocument.defaultView.getComputedStyle( elem, null ) : elem.currentStyle, styles = {}; if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) { len = style.length; while ( len-- ) { key = style[ len ]; if ( typeof style[ key ] === "string" ) { styles[ $.camelCase( key ) ] = style[ key ]; } } // support: Opera, IE <9 } else { for ( key in style ) { if ( typeof style[ key ] === "string" ) { styles[ key ] = style[ key ]; } } } return styles; } function styleDifference( oldStyle, newStyle ) { var diff = {}, name, value; for ( name in newStyle ) { value = newStyle[ name ]; if ( oldStyle[ name ] !== value ) { if ( !shorthandStyles[ name ] ) { if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) { diff[ name ] = value; } } } } return diff; } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } $.effects.animateClass = function( value, duration, easing, callback ) { var o = $.speed( duration, easing, callback ); return this.queue( function() { var animated = $( this ), baseClass = animated.attr( "class" ) || "", applyClassChange, allAnimations = o.children ? animated.find( "*" ).addBack() : animated; // map the animated objects to store the original styles. allAnimations = allAnimations.map(function() { var el = $( this ); return { el: el, start: getElementStyles( this ) }; }); // apply class change applyClassChange = function() { $.each( classAnimationActions, function(i, action) { if ( value[ action ] ) { animated[ action + "Class" ]( value[ action ] ); } }); }; applyClassChange(); // map all animated objects again - calculate new styles and diff allAnimations = allAnimations.map(function() { this.end = getElementStyles( this.el[ 0 ] ); this.diff = styleDifference( this.start, this.end ); return this; }); // apply original class animated.attr( "class", baseClass ); // map all animated objects again - this time collecting a promise allAnimations = allAnimations.map(function() { var styleInfo = this, dfd = $.Deferred(), opts = $.extend({}, o, { queue: false, complete: function() { dfd.resolve( styleInfo ); } }); this.el.animate( this.diff, opts ); return dfd.promise(); }); // once all animations have completed: $.when.apply( $, allAnimations.get() ).done(function() { // set the final class applyClassChange(); // for each animated element, // clear all css properties that were animated $.each( arguments, function() { var el = this.el; $.each( this.diff, function(key) { el.css( key, "" ); }); }); // this is guarnteed to be there if you use jQuery.speed() // it also handles dequeuing the next anim... o.complete.call( animated[ 0 ] ); }); }); }; $.fn.extend({ addClass: (function( orig ) { return function( classNames, speed, easing, callback ) { return speed ? $.effects.animateClass.call( this, { add: classNames }, speed, easing, callback ) : orig.apply( this, arguments ); }; })( $.fn.addClass ), removeClass: (function( orig ) { return function( classNames, speed, easing, callback ) { return arguments.length > 1 ? $.effects.animateClass.call( this, { remove: classNames }, speed, easing, callback ) : orig.apply( this, arguments ); }; })( $.fn.removeClass ), toggleClass: (function( orig ) { return function( classNames, force, speed, easing, callback ) { if ( typeof force === "boolean" || force === undefined ) { if ( !speed ) { // without speed parameter return orig.apply( this, arguments ); } else { return $.effects.animateClass.call( this, (force ? { add: classNames } : { remove: classNames }), speed, easing, callback ); } } else { // without force parameter return $.effects.animateClass.call( this, { toggle: classNames }, force, speed, easing ); } }; })( $.fn.toggleClass ), switchClass: function( remove, add, speed, easing, callback) { return $.effects.animateClass.call( this, { add: add, remove: remove }, speed, easing, callback ); } }); })(); /******************************************************************************/ /*********************************** EFFECTS **********************************/ /******************************************************************************/ (function() { $.extend( $.effects, { version: "1.11.3", // Saves a set of properties in a data storage save: function( element, set ) { for ( var i = 0; i < set.length; i++ ) { if ( set[ i ] !== null ) { element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] ); } } }, // Restores a set of previously saved properties from a data storage restore: function( element, set ) { var val, i; for ( i = 0; i < set.length; i++ ) { if ( set[ i ] !== null ) { val = element.data( dataSpace + set[ i ] ); // support: jQuery 1.6.2 // http://bugs.jquery.com/ticket/9917 // jQuery 1.6.2 incorrectly returns undefined for any falsy value. // We can't differentiate between "" and 0 here, so we just assume // empty string since it's likely to be a more common value... if ( val === undefined ) { val = ""; } element.css( set[ i ], val ); } } }, setMode: function( el, mode ) { if (mode === "toggle") { mode = el.is( ":hidden" ) ? "show" : "hide"; } return mode; }, // Translates a [top,left] array into a baseline value // this should be a little more flexible in the future to handle a string & hash getBaseline: function( origin, original ) { var y, x; switch ( origin[ 0 ] ) { case "top": y = 0; break; case "middle": y = 0.5; break; case "bottom": y = 1; break; default: y = origin[ 0 ] / original.height; } switch ( origin[ 1 ] ) { case "left": x = 0; break; case "center": x = 0.5; break; case "right": x = 1; break; default: x = origin[ 1 ] / original.width; } return { x: x, y: y }; }, // Wraps the element around a wrapper that copies position properties createWrapper: function( element ) { // if the element is already wrapped, return it if ( element.parent().is( ".ui-effects-wrapper" )) { return element.parent(); } // wrap the element var props = { width: element.outerWidth(true), height: element.outerHeight(true), "float": element.css( "float" ) }, wrapper = $( "<div></div>" ) .addClass( "ui-effects-wrapper" ) .css({ fontSize: "100%", background: "transparent", border: "none", margin: 0, padding: 0 }), // Store the size in case width/height are defined in % - Fixes #5245 size = { width: element.width(), height: element.height() }, active = document.activeElement; // support: Firefox // Firefox incorrectly exposes anonymous content // https://bugzilla.mozilla.org/show_bug.cgi?id=561664 try { active.id; } catch ( e ) { active = document.body; } element.wrap( wrapper ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).focus(); } wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element // transfer positioning properties to the wrapper if ( element.css( "position" ) === "static" ) { wrapper.css({ position: "relative" }); element.css({ position: "relative" }); } else { $.extend( props, { position: element.css( "position" ), zIndex: element.css( "z-index" ) }); $.each([ "top", "left", "bottom", "right" ], function(i, pos) { props[ pos ] = element.css( pos ); if ( isNaN( parseInt( props[ pos ], 10 ) ) ) { props[ pos ] = "auto"; } }); element.css({ position: "relative", top: 0, left: 0, right: "auto", bottom: "auto" }); } element.css(size); return wrapper.css( props ).show(); }, removeWrapper: function( element ) { var active = document.activeElement; if ( element.parent().is( ".ui-effects-wrapper" ) ) { element.parent().replaceWith( element ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).focus(); } } return element; }, setTransition: function( element, list, factor, value ) { value = value || {}; $.each( list, function( i, x ) { var unit = element.cssUnit( x ); if ( unit[ 0 ] > 0 ) { value[ x ] = unit[ 0 ] * factor + unit[ 1 ]; } }); return value; } }); // return an effect options object for the given parameters: function _normalizeArguments( effect, options, speed, callback ) { // allow passing all options as the first parameter if ( $.isPlainObject( effect ) ) { options = effect; effect = effect.effect; } // convert to an object effect = { effect: effect }; // catch (effect, null, ...) if ( options == null ) { options = {}; } // catch (effect, callback) if ( $.isFunction( options ) ) { callback = options; speed = null; options = {}; } // catch (effect, speed, ?) if ( typeof options === "number" || $.fx.speeds[ options ] ) { callback = speed; speed = options; options = {}; } // catch (effect, options, callback) if ( $.isFunction( speed ) ) { callback = speed; speed = null; } // add options to effect if ( options ) { $.extend( effect, options ); } speed = speed || options.duration; effect.duration = $.fx.off ? 0 : typeof speed === "number" ? speed : speed in $.fx.speeds ? $.fx.speeds[ speed ] : $.fx.speeds._default; effect.complete = callback || options.complete; return effect; } function standardAnimationOption( option ) { // Valid standard speeds (nothing, number, named speed) if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) { return true; } // Invalid strings - treat as "normal" speed if ( typeof option === "string" && !$.effects.effect[ option ] ) { return true; } // Complete callback if ( $.isFunction( option ) ) { return true; } // Options hash (but not naming an effect) if ( typeof option === "object" && !option.effect ) { return true; } // Didn't match any standard API return false; } $.fn.extend({ effect: function( /* effect, options, speed, callback */ ) { var args = _normalizeArguments.apply( this, arguments ), mode = args.mode, queue = args.queue, effectMethod = $.effects.effect[ args.effect ]; if ( $.fx.off || !effectMethod ) { // delegate to the original method (e.g., .show()) if possible if ( mode ) { return this[ mode ]( args.duration, args.complete ); } else { return this.each( function() { if ( args.complete ) { args.complete.call( this ); } }); } } function run( next ) { var elem = $( this ), complete = args.complete, mode = args.mode; function done() { if ( $.isFunction( complete ) ) { complete.call( elem[0] ); } if ( $.isFunction( next ) ) { next(); } } // If the element already has the correct final state, delegate to // the core methods so the internal tracking of "olddisplay" works. if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) { elem[ mode ](); done(); } else { effectMethod.call( elem[0], args, done ); } } return queue === false ? this.each( run ) : this.queue( queue || "fx", run ); }, show: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "show"; return this.effect.call( this, args ); } }; })( $.fn.show ), hide: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "hide"; return this.effect.call( this, args ); } }; })( $.fn.hide ), toggle: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) || typeof option === "boolean" ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "toggle"; return this.effect.call( this, args ); } }; })( $.fn.toggle ), // helper functions cssUnit: function(key) { var style = this.css( key ), val = []; $.each( [ "em", "px", "%", "pt" ], function( i, unit ) { if ( style.indexOf( unit ) > 0 ) { val = [ parseFloat( style ), unit ]; } }); return val; } }); })(); /******************************************************************************/ /*********************************** EASING ***********************************/ /******************************************************************************/ (function() { // based on easing equations from Robert Penner (http://www.robertpenner.com/easing) var baseEasings = {}; $.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) { baseEasings[ name ] = function( p ) { return Math.pow( p, i + 2 ); }; }); $.extend( baseEasings, { Sine: function( p ) { return 1 - Math.cos( p * Math.PI / 2 ); }, Circ: function( p ) { return 1 - Math.sqrt( 1 - p * p ); }, Elastic: function( p ) { return p === 0 || p === 1 ? p : -Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 ); }, Back: function( p ) { return p * p * ( 3 * p - 2 ); }, Bounce: function( p ) { var pow2, bounce = 4; while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {} return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 ); } }); $.each( baseEasings, function( name, easeIn ) { $.easing[ "easeIn" + name ] = easeIn; $.easing[ "easeOut" + name ] = function( p ) { return 1 - easeIn( 1 - p ); }; $.easing[ "easeInOut" + name ] = function( p ) { return p < 0.5 ? easeIn( p * 2 ) / 2 : 1 - easeIn( p * -2 + 2 ) / 2; }; }); })(); return $.effects; }));
/* snapper css snap points carousel */ ;(function( w, $ ){ var pluginName = "snapper"; $.fn[ pluginName ] = function(){ // css snap points feature test. // even if this test passes, several behaviors will still be polyfilled, such as snapping after resize, and animated advancing of slides with anchor links or next/prev links var testProp = "scroll-snap-type"; var snapSupported = w.CSS && w.CSS.supports && ( w.CSS.supports( testProp, "mandatory") || w.CSS.supports("-webkit-" + testProp, "mandatory") || w.CSS.supports("-ms-" + testProp, "mandatory") ); // get the snapper_item elements whose left offsets fall within the scroll pane. Returns a wrapped array. function itemsAtOffset( elem, offset ){ var $childNodes = $( elem ).find( "." + pluginName + "_item" ); var containWidth = $( elem ).width(); var activeItems = []; $childNodes.each(function( i ){ if( this.offsetLeft >= offset - 5 && this.offsetLeft < offset + containWidth - 5 ){ activeItems.push( this ); } }); return $( activeItems ); } function outerWidth( $elem ){ return $elem.width() + parseFloat( $elem.css( "margin-left" ) ) + parseFloat( $elem.css( "margin-right" ) ); } // snapEvent dispatches the "snapper.snap" event. // The snapper_item elements with left offsets that are inside the scroll viewport are listed in an array in the second callback argument's activeSlides property. // use like this: $( ".snapper" ).bind( "snapper.snap", function( event, data ){ console.log( data.activeSlides ); } ); function snapEvent( elem, x ){ var activeSlides = itemsAtOffset( elem, x ); $( elem ).trigger( pluginName + ".snap", { activeSlides: activeSlides } ); } // optional: include overthrow.toss() in your page to get a smooth scroll, otherwise it'll just jump to the slide function goto( elem, x, nothrow ){ snapEvent( elem, x ); if( typeof w.overthrow !== "undefined" && !nothrow ){ w.overthrow.toss( elem, { left: x } ); } else { elem.scrollLeft = x; } } // Loop through snapper elements and enhance/bind events return this.each(function(){ var self = this; var addNextPrev = $( self ).is( "[data-" + pluginName + "-nextprev]" ); var $slider = $( "." + pluginName + "_pane", self ); var enhancedClass = pluginName + "-enhanced"; var $itemsContain = $slider.find( "." + pluginName + "_items" ); var $items = $itemsContain.children(); $items.addClass( pluginName + "_item" ); var numItems = $items.length; var $nav = $( "." + pluginName + "_nav", self ); var navSelectedClass = pluginName + "_nav_item-selected"; // this function updates the widths of the items within the slider, and their container. // It factors in margins and converts those to values that make sense when all items are placed in a long row function updateWidths(){ var itemsContainStyle = $itemsContain.attr( "style" ); $itemsContain.attr( "style", "" ); var itemStyle = $items.eq(0).attr( "style" ); $items.eq(0).attr( "style", "" ); var sliderWidth = $slider.width(); var itemWidth = $items.eq(0).width(); var computed = w.getComputedStyle( $items[ 0 ], null ); var itemLeftMargin = parseFloat( computed.getPropertyValue( "margin-left" ) ); var itemRightMargin = parseFloat( computed.getPropertyValue( "margin-right" ) ); $items.eq(0).attr( "style", itemStyle ); $itemsContain.attr( "style", itemsContainStyle ); var parentWidth = numItems / Math.round(sliderWidth / itemWidth) * 100; var iPercentWidth = itemWidth / sliderWidth * 100; var iPercentRightMargin = itemRightMargin / sliderWidth * 100; var iPercentLeftMargin = itemLeftMargin / sliderWidth * 100; var outerPercentWidth = iPercentWidth + iPercentLeftMargin + iPercentRightMargin; var percentAsWidth = iPercentWidth / outerPercentWidth; var percentAsRightMargin = iPercentRightMargin / outerPercentWidth; var percentAsLeftMargin = iPercentLeftMargin / outerPercentWidth; $itemsContain.css( "width", parentWidth + "%"); $items.css( "width", 100 / numItems * percentAsWidth + "%" ); $items.css( "margin-left", 100 / numItems * percentAsLeftMargin + "%" ); $items.css( "margin-right", 100 / numItems * percentAsRightMargin + "%" ); } updateWidths(); $( self ).addClass( enhancedClass ); // if the nextprev option is set, add the nextprev nav if( addNextPrev ){ var $nextprev = $( '<ul class="snapper_nextprev"><li class="snapper_nextprev_item"><a href="#prev" class="snapper_nextprev_prev">Prev</a></li><li class="snapper_nextprev_item"><a href="#next" class="snapper_nextprev_next">Next</a></li></ul>' ); var $nextprevContain = $( ".snapper_nextprev_contain", self ); if( !$nextprevContain.length ){ $nextprevContain = $( self ); } $nextprev.appendTo( $nextprevContain ); } // This click binding will allow deep-linking to slides without causing the page to scroll to the carousel container // this also supports click handling for generated next/prev links $( "a", this ).bind( "click", function( e ){ var slideID = $( this ).attr( "href" ); if( slideID.indexOf( "#" ) === -1 ){ // only local anchor links return; } e.preventDefault(); if( $( this ).is( ".snapper_nextprev_next" ) ){ return arrowNavigate( true ); } else if( $( this ).is( ".snapper_nextprev_prev" ) ){ return arrowNavigate( false ); } else { var $slide = $( slideID, self ); goto( $slider[ 0 ], $slide[ 0 ].offsetLeft ); if( "replaceState" in w.history ){ w.history.replaceState( {}, document.title, slideID ); } } }); // arrow key bindings for next/prev $( this ) .attr( "tabindex", "0" ) .bind( "keyup", function( e ){ if( e.keyCode === 37 || e.keyCode === 38 ){ e.preventDefault(); arrowNavigate( false ); } if( e.keyCode === 39 || e.keyCode === 40 ){ e.preventDefault(); arrowNavigate( true ); } } ); // snap to nearest slide. Useful after a scroll stops, for polyfilling snap points function snapScroll(){ var currScroll = $slider[ 0 ].scrollLeft; var width = $itemsContain.width(); var itemWidth = $items[ 1 ] ? $items[ 1 ].offsetLeft : outerWidth( $items.eq( 0 ) ); var roundedScroll = Math.round(currScroll/itemWidth)*itemWidth; var maxScroll = width - $slider.width(); if( roundedScroll > maxScroll ){ roundedScroll = maxScroll; } if( currScroll !== roundedScroll ){ if( snapSupported ){ snapEvent( $slider[ 0 ], roundedScroll ); } else { goto( $slider[ 0 ], roundedScroll ); } } } // retain snapping on resize (necessary even in scroll-snap supporting browsers currently, unfortunately) var startSlide; var afterResize; function snapStay(){ var currScroll = $slider[ 0 ].scrollLeft; var numItems = $items.length; var width = $itemsContain.width(); if( startSlide === undefined ){ startSlide = Math.round( currScroll / width * numItems ); } if( afterResize ){ clearTimeout( afterResize ); } afterResize = setTimeout( function(){ updateWidths(); goto( $slider[ 0 ], $items[ startSlide ].offsetLeft, true ); startSlide = afterResize = undefined; }, 50 ); } $( w ).bind( "resize", snapStay ); // next/prev links or arrows should loop back to the other end when an extreme is reached function arrowNavigate( forward ){ var currScroll = $slider[ 0 ].scrollLeft; var width = $itemsContain.width(); var itemWidth = outerWidth( $slider ); var maxScroll = width - itemWidth - 5; if( forward ){ if( currScroll >= maxScroll ){ return first(); } else { return next(); } } else { if( currScroll === 0 ){ return last(); } else { return prev(); } } } // advance slide one full scrollpane's width forward function next(){ goto( $slider[ 0 ], $slider[ 0 ].scrollLeft + ( $itemsContain.width() / numItems ) ); } // advance slide one full scrollpane's width backwards function prev(){ goto( $slider[ 0 ], $slider[ 0 ].scrollLeft - ( $itemsContain.width() / numItems ) ); } // go to first slide function first(){ goto( $slider[ 0 ], 0 ); } // go to last slide function last(){ goto( $slider[ 0 ], $itemsContain.width() - $slider.width() ); } // update thumbnail state on pane scroll if( $nav.length ){ function activeItem(){ var currScroll = $slider[ 0 ].scrollLeft; var width = outerWidth( $itemsContain ); var activeIndex = Math.round( currScroll / width * numItems ); $nav .children().removeClass( navSelectedClass ) .eq( activeIndex ) .addClass( navSelectedClass ); } // set active item on scroll $slider.bind( "scroll", activeItem ); // set active item on init activeItem(); } // apply snapping after scroll, in browsers that don't support CSS scroll-snap var scrollStop; $slider.bind( "scroll", function(e){ if( scrollStop ){ clearTimeout( scrollStop ); } scrollStop = setTimeout( snapScroll, 50 ); }); }); }; // auto-init on enhance $( document ).bind( "enhance", function( e ){ $( "." + pluginName, e.target ).add( e.target ).filter( "." + pluginName )[ pluginName ](); }); }( this, jQuery ));
/** * @author Richard Davey <[email protected]> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Phaser.Color stub. This stub only includes the bare minimum functions that Phaser needs. * * @class Phaser.Color */ Phaser.Color = { /** * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components. * * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`). * * An alpha channel is _not_ supported when specifying a hex string. * * @method Phaser.Color.valueToColor * @static * @param {string|number} value - The color expressed as a recognized string format or a packed integer. * @param {object} [out] - The object to use for the output. If not provided a new object will be created. * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties. */ valueToColor: function (value, out) { if (typeof value === 'string') { if (value.indexOf('rgb') === 0) { return Phaser.Color.webToColor(value, out); } else { // `hexToColor` does not support alpha; match `createColor`. out.a = 1; return Phaser.Color.hexToColor(value, out); } } else if (typeof value === 'number') { // `getRGB` does not take optional object to modify; // alpha is also adjusted to match `createColor`. var tempColor = Phaser.Color.getRGB(value); out.r = tempColor.r; out.g = tempColor.g; out.b = tempColor.b; out.a = tempColor.a / 255; return out; } else { return out; } }, /** * Return the component parts of a color as an Object with the properties alpha, red, green, blue. * * Alpha will only be set if it exist in the given color (0xAARRGGBB) * * @method Phaser.Color.getRGB * @static * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB). * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given. */ getRGB: function (color) { if (color > 16777215) { // The color value has an alpha component return { alpha: color >>> 24, red: color >> 16 & 0xFF, green: color >> 8 & 0xFF, blue: color & 0xFF, a: color >>> 24, r: color >> 16 & 0xFF, g: color >> 8 & 0xFF, b: color & 0xFF }; } else { return { alpha: 255, red: color >> 16 & 0xFF, green: color >> 8 & 0xFF, blue: color & 0xFF, a: 255, r: color >> 16 & 0xFF, g: color >> 8 & 0xFF, b: color & 0xFF }; } }, /** * Converts a CSS 'web' string into a Phaser Color object. * * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. * * @method Phaser.Color.webToColor * @static * @param {string} web - The color string in CSS 'web' format. * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. */ webToColor: function (web, out) { var result = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(web); if (result) { out.r = parseInt(result[1], 10); out.g = parseInt(result[2], 10); out.b = parseInt(result[3], 10); out.a = result[4] !== undefined ? parseFloat(result[4]) : 1; Phaser.Color.updateColor(out); } return out; }, /** * Converts a hex string into a Phaser Color object. * * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. * * An alpha channel is _not_ supported. * * @method Phaser.Color.hexToColor * @static * @param {string} hex - The color string in a hex format. * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created. * @return {object} An object with the red, green and blue values set in the r, g and b properties. */ hexToColor: function (hex, out) { // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); if (result) { var r = parseInt(result[1], 16); var g = parseInt(result[2], 16); var b = parseInt(result[3], 16); out.r = r; out.g = g; out.b = b; } return out; }, /** * Takes a color object and updates the rgba property. * * @method Phaser.Color.updateColor * @static * @param {object} out - The color object to update. * @returns {number} A native color value integer (format: 0xAARRGGBB). */ updateColor: function (out) { out.rgba = 'rgba(' + out.r.toString() + ',' + out.g.toString() + ',' + out.b.toString() + ',' + out.a.toString() + ')'; out.color = Phaser.Color.getColor(out.r, out.g, out.b); out.color32 = Phaser.Color.getColor32(out.a, out.r, out.g, out.b); return out; }, /** * Given an alpha and 3 color values this will return an integer representation of it. * * @method Phaser.Color.getColor32 * @static * @param {number} a - The alpha color component, in the range 0 - 255. * @param {number} r - The red color component, in the range 0 - 255. * @param {number} g - The green color component, in the range 0 - 255. * @param {number} b - The blue color component, in the range 0 - 255. * @returns {number} A native color value integer (format: 0xAARRGGBB). */ getColor32: function (a, r, g, b) { return a << 24 | r << 16 | g << 8 | b; }, /** * Given 3 color values this will return an integer representation of it. * * @method Phaser.Color.getColor * @static * @param {number} r - The red color component, in the range 0 - 255. * @param {number} g - The green color component, in the range 0 - 255. * @param {number} b - The blue color component, in the range 0 - 255. * @returns {number} A native color value integer (format: 0xRRGGBB). */ getColor: function (r, g, b) { return r << 16 | g << 8 | b; } };
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "domenica", "luned\u00ec", "marted\u00ec", "mercoled\u00ec", "gioved\u00ec", "venerd\u00ec", "sabato" ], "MONTH": [ "gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre" ], "SHORTDAY": [ "dom", "lun", "mar", "mer", "gio", "ven", "sab" ], "SHORTMONTH": [ "gen", "feb", "mar", "apr", "mag", "giu", "lug", "ago", "set", "ott", "nov", "dic" ], "fullDate": "EEEE d MMMM y", "longDate": "dd MMMM y", "medium": "dd/MMM/y HH:mm:ss", "mediumDate": "dd/MMM/y", "mediumTime": "HH:mm:ss", "short": "dd/MM/yy HH:mm", "shortDate": "dd/MM/yy", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u20ac", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a0\u00a4", "posPre": "", "posSuf": "\u00a0\u00a4" } ] }, "id": "it-it", "pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
/*
/** * vue-validator v1.3.1 * (c) 2014-2015 kazuya kawaguchi * Released under the MIT License. */ (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["vue-validator"] = factory(); else root["vue-validator"] = 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__) { /** * Import(s) */ var validates = __webpack_require__(1) /** * Export(s) */ module.exports = install /** * Install plugin */ function install (Vue, options) { options = options || {} var componentName = options.component = options.component || '$validator' var directiveName = options.directive = options.directive || 'validate' var path = Vue.parsers.path var utils = Vue.util function getVal (obj, keypath) { var ret = null try { ret = path.get(obj, keypath) } catch (e) { } return ret } Vue.directive(directiveName, { priority: 1024, bind: function () { var vm = this.vm var el = this.el var $validator = vm[componentName] var keypath = this._keypath = this._parseModelAttribute(el.getAttribute(Vue.config.prefix + 'model')) var validator = this.arg ? this.arg : this.expression var arg = this.arg ? this.expression : null var customs = (vm.$options.validator && vm.$options.validator.validates) || {} if (!this._checkDirective(validator, validates, customs)) { utils.warn('specified invalid v-validate directive !! please check v-validator directive !!') this._ignore = true return } if (!$validator) { vm[componentName] = $validator = vm.$addChild({ validator: vm.$options.validator }, Vue.extend(__webpack_require__(2))) } var validation = $validator._getValidationNamespace('validation') var init = el.getAttribute('value') || vm.$get(keypath) var readyEvent = el.getAttribute('wait-for') if (readyEvent && !$validator._isRegistedReadyEvent(keypath)) { $validator._addReadyEvents(keypath, this._checkParam('wait-for')) } this._setupValidator($validator, keypath, validation, validator, arg, init) }, update: function (val, old) { if (this._ignore) { return } var vm = this.vm var keypath = this._keypath var validator = this.arg ? this.arg : this.expression var $validator = vm[componentName] $validator._changeValidator(keypath, validator, val) if (!$validator._isRegistedReadyEvent(keypath)) { // normal $validator._updateDirtyProperty(keypath, $validator.$get(keypath)) $validator._doValidate(keypath, validator, $validator.$get(keypath)) } else { // wait-for vm.$once($validator._getReadyEvents(keypath), function (val) { $validator._setInitialValue(keypath, val) vm.$set(keypath, val) $validator._updateDirtyProperty(keypath, $validator.$get(keypath)) $validator._doValidate(keypath, validator, $validator.$get(keypath)) }) } }, unbind: function () { if (this._ignore) { return } var vm = this.vm var keypath = this._keypath var validator = this.arg ? this.arg : this.expression var $validator = vm[componentName] this._teardownValidator(vm, $validator, keypath, validator) }, _parseModelAttribute: function (attr) { var res = Vue.parsers.directive.parse(attr) return res[0].arg ? res[0].arg : res[0].expression }, _checkDirective: function (validator, validates, customs) { var items = Object.keys(validates).concat(Object.keys(customs)) return items.some(function (item) { return item === validator }) }, _setupValidator: function ($validator, keypath, validation, validator, arg, init) { var vm = this.vm if (!getVal($validator[validation], keypath)) { $validator._defineModelValidationScope(keypath) $validator._setInitialValue(keypath, init) } if (!getVal($validator[validation], [keypath, validator].join('.'))) { $validator._defineValidatorToValidationScope(keypath, validator) $validator._addValidator(keypath, validator, getVal(vm, arg) || arg) } $validator._addManagedValidator(keypath, validator) }, _updateValidator: function () { }, _teardownValidator: function (vm, $validator, keypath, validator) { $validator._deleteManagedValidator(keypath, validator) $validator._undefineValidatorToValidationScope(keypath, validator) $validator._undefineModelValidationScope(keypath) if (!$validator._isManagedValidator()) { $validator.$destroy() vm[componentName] = null delete vm[componentName] } } }) } /***/ }, /* 1 */ /***/ function(module, exports) { /** * Fundamental validate functions */ /** * required * * This function validate whether the value has been filled out. * * @param val * @return {Boolean} */ function required (val) { if (Array.isArray(val)) { return val.length > 0 } else if ((val !== null) && (typeof val === 'object')) { return Object.keys(val).length > 0 } else { return !val ? false : true } } /** * pattern * * This function validate whether the value matches the regex pattern * * @param val * @param {String} pat * @return {Boolean} */ function pattern (val, pat) { if (typeof pat !== 'string') { return false } var match = pat.match(new RegExp('^/(.*?)/([gimy]*)$')) if (!match) { return false } return new RegExp(match[1], match[2]).test(val) } /** * minLength * * This function validate whether the minimum length of the string. * * @param {String} val * @param {String|Number} min * @return {Boolean} */ function minLength (val, min) { return typeof val === 'string' && isInteger(min, 10) && val.length >= parseInt(min, 10) } /** * maxLength * * This function validate whether the maximum length of the string. * * @param {String} val * @param {String|Number} max * @return {Boolean} */ function maxLength (val, max) { return typeof val === 'string' && isInteger(max, 10) && val.length <= parseInt(max, 10) } /** * min * * This function validate whether the minimum value of the numberable value. * * @param {*} val * @param {*} arg minimum * @return {Boolean} */ function min (val, arg) { return !isNaN(+(val)) && !isNaN(+(arg)) && (+(val) >= +(arg)) } /** * max * * This function validate whether the maximum value of the numberable value. * * @param {*} val * @param {*} arg maximum * @return {Boolean} */ function max (val, arg) { return !isNaN(+(val)) && !isNaN(+(arg)) && (+(val) <= +(arg)) } /** * isInteger * * This function check whether the value of the string is integer. * * @param {String} val * @return {Boolean} * @private */ function isInteger (val) { return /^(-?[1-9]\d*|0)$/.test(val) } /** * export(s) */ module.exports = { required: required, pattern: pattern, minLength: minLength, maxLength: maxLength, min: min, max: max } /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /** * Import(s) */ var validates = __webpack_require__(1) /** * Export(s) */ /** * `v-validator` component with mixin */ module.exports = { inherit: true, created: function () { this._initValidationVariables() this._initOptions() this._mixinCustomValidates() this._defineProperties() this._defineValidationScope() }, beforeDestroy: function () { this._undefineProperties() this._undefineValidationScope() }, methods: { _getValidationNamespace: function (key) { return this.$options.validator.namespace[key] }, _initValidationVariables: function () { this._validators = {} this._validates = {} this._initialValues = {} for (var key in validates) { this._validates[key] = validates[key] } this._validatorWatchers = {} this._managedValidator = {} this._readyEvents = {} }, _initOptions: function () { var validator = this.$options.validator = this.$options.validator || {} var namespace = validator.namespace = validator.namespace || {} namespace.validation = namespace.validation || 'validation' namespace.valid = namespace.valid || 'valid' namespace.invalid = namespace.invalid || 'invalid' namespace.dirty = namespace.dirty || 'dirty' }, _mixinCustomValidates: function () { var customs = this.$options.validator.validates for (var key in customs) { this._validates[key] = customs[key] } }, _defineValidProperty: function (target, getter) { Object.defineProperty(target, this._getValidationNamespace('valid'), { enumerable: true, configurable: true, get: getter }) }, _undefineValidProperty: function (target) { delete target[this._getValidationNamespace('valid')] }, _defineInvalidProperty: function (target) { var self = this Object.defineProperty(target, this._getValidationNamespace('invalid'), { enumerable: true, configurable: true, get: function () { return !target[self._getValidationNamespace('valid')] } }) }, _undefineInvalidProperty: function (target) { delete target[this._getValidationNamespace('invalid')] }, _defineDirtyProperty: function (target, getter) { Object.defineProperty(target, this._getValidationNamespace('dirty'), { enumerable: true, configurable: true, get: getter }) }, _undefineDirtyProperty: function (target) { delete target[this._getValidationNamespace('dirty')] }, _defineProperties: function () { var self = this var walk = function (obj, propName, namespaces) { var ret = false var keys = Object.keys(obj) var i = keys.length var key, last while (i--) { key = keys[i] last = obj[key] if (!(key in namespaces) && typeof last === 'object') { ret = walk(last, propName, namespaces) if ((propName === self._getValidationNamespace('valid') && !ret) || (propName === self._getValidationNamespace('dirty') && ret)) { break } } else if (key === propName && typeof last !== 'object') { ret = last if ((key === self._getValidationNamespace('valid') && !ret) || (key === self._getValidationNamespace('dirty') && ret)) { break } } } return ret } this._defineValidProperty(this.$parent, function () { var validationName = self._getValidationNamespace('validation') var validName = self._getValidationNamespace('valid') var namespaces = self.$options.validator.namespace return walk(this[validationName], validName, namespaces) }) this._defineInvalidProperty(this.$parent) this._defineDirtyProperty(this.$parent, function () { var validationName = self._getValidationNamespace('validation') var dirtyName = self._getValidationNamespace('dirty') var namespaces = self.$options.validator.namespace return walk(this[validationName], dirtyName, namespaces) }) }, _undefineProperties: function () { this._undefineDirtyProperty(this.$parent) this._undefineInvalidProperty(this.$parent) this._undefineValidProperty(this.$parent) }, _defineValidationScope: function () { this.$parent.$add(this._getValidationNamespace('validation'), {}) }, _undefineValidationScope: function () { this.$parent.$delete(this._getValidationNamespace('validation')) }, _defineModelValidationScope: function (keypath) { var self = this var validationName = this._getValidationNamespace('validation') var dirtyName = this._getValidationNamespace('dirty') var keys = keypath.split('.') var last = this[validationName] var obj, key for (var i = 0; i < keys.length; i++) { key = keys[i] obj = last[key] if (!obj) { obj = {} last.$add(key, obj) } last = obj } last.$add(dirtyName, false) this._defineValidProperty(last, function () { var ret = true var validators = self._validators[keypath] var i = validators.length var validator while (i--) { validator = validators[i] if (last[validator.name]) { ret = false break } } return ret }) this._defineInvalidProperty(last) this._validators[keypath] = [] this._watchModel(keypath, function (val, old) { self._updateDirtyProperty(keypath, val) self._validators[keypath].forEach(function (validator) { self._doValidate(keypath, validator.name, val) }) }) }, _undefineModelValidationScope: function (keypath) { if (this.$parent) { var targetPath = [this._getValidationNamespace('validation'), keypath].join('.') var target = this.$parent.$get(targetPath) if (target) { this._unwatchModel(keypath) this._undefineDirtyProperty(target) this._undefineInvalidProperty(target) this._undefineValidProperty(target) var validation = this.$parent.$get(this._getValidationNamespace('validation')) validation.$delete(keypath) } } }, _defineValidatorToValidationScope: function (keypath, validator) { var target = getTarget(this[this._getValidationNamespace('validation')], keypath) target.$add(validator, null) }, _undefineValidatorToValidationScope: function (keypath, validator) { var validationName = this._getValidationNamespace('validation') if (this.$parent) { var targetPath = [validationName, keypath].join('.') var target = this.$parent.$get(targetPath) if (target) { target.$delete(validator) } } }, _getInitialValue: function (keypath) { return this._initialValues[keypath] }, _setInitialValue: function (keypath, val) { this._initialValues[keypath] = val }, _addValidator: function (keypath, validator, arg) { this._validators[keypath].push({ name: validator, arg: arg }) }, _changeValidator: function (keypath, validator, arg) { var validators = this._validators[keypath] var i = validators.length while (i--) { if (validators[i].name === validator) { validators[i].arg = arg break } } }, _findValidator: function (keypath, validator) { var found = null var validators = this._validators[keypath] var i = validators.length while (i--) { if (validators[i].name === validator) { found = validators[i] break } } return found }, _watchModel: function (keypath, fn) { this._validatorWatchers[keypath] = this.$watch(keypath, fn, { deep: false, immediate: true }) }, _unwatchModel: function (keypath) { var unwatch = this._validatorWatchers[keypath] if (unwatch) { unwatch() delete this._validatorWatchers[keypath] } }, _addManagedValidator: function (keypath, validator) { this._managedValidator[[keypath, validator].join('.')] = true }, _deleteManagedValidator: function (keypath, validator) { var key = [keypath, validator].join('.') this._managedValidator[key] = null delete this._managedValidator[key] }, _isManagedValidator: function () { return Object.keys(this._managedValidator).length !== 0 }, _addReadyEvents: function (id, event) { this._readyEvents[id] = event }, _getReadyEvents: function (id) { return this._readyEvents[id] }, _isRegistedReadyEvent: function (id) { return id in this._readyEvents }, _updateDirtyProperty: function (keypath, val) { var validationName = this._getValidationNamespace('validation') var dirtyName = this._getValidationNamespace('dirty') var target = getTarget(this[validationName], keypath) target.$set(dirtyName, this._getInitialValue(keypath) !== val) }, _doValidate: function (keypath, validateName, val) { var validationName = this._getValidationNamespace('validation') var target = getTarget(this[validationName], keypath) var validator = this._findValidator(keypath, validateName) if (validator) { target.$set( validateName, !this._validates[validateName].call(this, val, validator.arg) ) } } } } /** * Get target validatable object * * @param {Object} validation * @param {String} keypath * @return {Object} validatable object */ function getTarget (validation, keypath) { var last = validation var keys = keypath.split('.') var key, obj for (var i = 0; i < keys.length; i++) { key = keys[i] obj = last[key] last = obj } return last } /***/ } /******/ ]) }); ;
/* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause * * Based on the Base 64 VLQ implementation in Closure Compiler: * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java * * Copyright 2011 The Closure Compiler Authors. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ { var base64 = require('./base64'); // A single base 64 digit can contain 6 bits of data. For the base 64 variable // length quantities we use in the source map spec, the first bit is the sign, // the next four bits are the actual value, and the 6th bit is the // continuation bit. The continuation bit tells us whether there are more // digits in this value following this digit. // // Continuation // | Sign // | | // V V // 101011 var VLQ_BASE_SHIFT = 5; // binary: 100000 var VLQ_BASE = 1 << VLQ_BASE_SHIFT; // binary: 011111 var VLQ_BASE_MASK = VLQ_BASE - 1; // binary: 100000 var VLQ_CONTINUATION_BIT = VLQ_BASE; /** * Converts from a two-complement value to a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ function toVLQSigned(aValue) { return aValue < 0 ? ((-aValue) << 1) + 1 : (aValue << 1) + 0; } /** * Converts to a two-complement value from a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 */ function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } /** * Returns the base 64 VLQ encoded value. */ exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { // There are still more digits in this value, so we must make sure the // continuation bit is marked. digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; /** * Decodes the next base 64 VLQ value from the given string and returns the * value and the rest of the string via the out parameter. */ exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (aIndex >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charCodeAt(aIndex++)); if (digit === -1) { throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); } continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); aOutParam.value = fromVLQSigned(result); aOutParam.rest = aIndex; }; }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (factory) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } // Because of build optimizers if (typeof define === 'function' && define.amd) { define(['rx'], function (Rx, exports) { return factory(root, exports, Rx); }); } else if (typeof module === 'object' && module && module.exports === freeExports) { module.exports = factory(root, module.exports, require('./rx')); } else { root.Rx = factory(root, {}, root.Rx); } }.call(this, function (root, exp, Rx, undefined) { var Observable = Rx.Observable, observableProto = Observable.prototype, AnonymousObservable = Rx.AnonymousObservable, Subject = Rx.Subject, AsyncSubject = Rx.AsyncSubject, Observer = Rx.Observer, ScheduledObserver = Rx.internals.ScheduledObserver, disposableCreate = Rx.Disposable.create, disposableEmpty = Rx.Disposable.empty, CompositeDisposable = Rx.CompositeDisposable, currentThreadScheduler = Rx.Scheduler.currentThread, isFunction = Rx.helpers.isFunction, inherits = Rx.internals.inherits, addProperties = Rx.internals.addProperties, checkDisposed = Rx.Disposable.checkDisposed; // Utilities function cloneArray(arr) { var len = arr.length, a = new Array(len); for(var i = 0; i < len; i++) { a[i] = arr[i]; } return a; } /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }, source) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, window, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.hasError = false; } addProperties(BehaviorSubject.prototype, Observer, { /** * Gets the current value or throws an exception. * Value is frozen after onCompleted is called. * After onError is called Value always throws the specified exception. * An exception is always thrown after dispose is called. * @returns {Mixed} The initial value passed to the constructor until OnNext is called; after which, the last value passed to OnNext. */ getValue: function () { checkDisposed(this); if (this.hasError) { throw this.error; } return this.value; }, /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = createRemovableDisposable(this, so); checkDisposed(this); this._trim(this.scheduler.now()); this.observers.push(so); for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { so.onError(this.error); } else if (this.isStopped) { so.onCompleted(); } so.ensureActive(); return subscription; } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onError(error); observer.ensureActive(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onCompleted(); observer.ensureActive(); } this.observers.length = 0; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, function (o) { return subject.subscribe(o); }); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); return Rx; }));
/** * @license AngularJS v1.1.2 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) { 'use strict'; /** * @ngdoc overview * @name ngResource * @description */ /** * @ngdoc object * @name ngResource.$resource * @requires $http * * @description * A factory which creates a resource object that lets you interact with * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources. * * The returned resource object has action methods which provide high-level behaviors without * the need to interact with the low level {@link ng.$http $http} service. * * @param {string} url A parameterized URL template with parameters prefixed by `:` as in * `/user/:username`. If you are using a URL with a port number (e.g. * `http://example.com:8080/api`), you'll need to escape the colon character before the port * number, like this: `$resource('http://example.com\\:8080/api')`. * * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in * `actions` methods. If any of the parameter value is a function, it will be executed every time * when a param value needs to be obtained for a request (unless the param was overriden). * * Each key value in the parameter object is first bound to url template if present and then any * excess keys are appended to the url search query after the `?`. * * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in * URL `/path/greet?salutation=Hello`. * * If the parameter value is prefixed with `@` then the value of that parameter is extracted from * the data object (useful for non-GET operations). * * @param {Object.<Object>=} actions Hash with declaration of custom action that should extend the * default set of resource actions. The declaration should be created in the format of {@link * ng.$http#Parameters $http.config}: * * {action1: {method:?, params:?, isArray:?, headers:?, ...}, * action2: {method:?, params:?, isArray:?, headers:?, ...}, * ...} * * Where: * * - **`action`** – {string} – The name of action. This name becomes the name of the method on your * resource object. * - **`method`** – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`, * and `JSONP`. * - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of the * parameter value is a function, it will be executed every time when a param value needs to be * obtained for a request (unless the param was overriden). * - **`isArray`** – {boolean=} – If true then the returned object for this action is an array, see * `returns` section. * - **`transformRequest`** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. * - **`transformResponse`** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * response body and headers and returns its transformed (typically deserialized) version. * - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the * GET request, otherwise if a cache instance built with * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for * caching. * - **`timeout`** – `{number}` – timeout in milliseconds. * - **`withCredentials`** - `{boolean}` - whether to to set the `withCredentials` flag on the * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5 * requests with credentials} for more information. * - **`responseType`** - `{string}` - see {@link * https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}. * * @returns {Object} A resource "class" object with methods for the default set of resource actions * optionally extended with custom `actions`. The default set contains these actions: * * { 'get': {method:'GET'}, * 'save': {method:'POST'}, * 'query': {method:'GET', isArray:true}, * 'remove': {method:'DELETE'}, * 'delete': {method:'DELETE'} }; * * Calling these methods invoke an {@link ng.$http} with the specified http method, * destination and parameters. When the data is returned from the server then the object is an * instance of the resource class `save`, `remove` and `delete` actions are available on it as * methods with the `$` prefix. This allows you to easily perform CRUD operations (create, read, * update, delete) on server-side data like this: * <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function() { user.abc = true; user.$save(); }); </pre> * * It is important to realize that invoking a $resource object method immediately returns an * empty reference (object or array depending on `isArray`). Once the data is returned from the * server the existing reference is populated with the actual data. This is a useful trick since * usually the resource is assigned to a model which is then rendered by the view. Having an empty * object results in no rendering, once the data arrives from the server then the object is * populated with the data and the view automatically re-renders itself showing the new data. This * means that in most case one never has to write a callback function for the action methods. * * The action methods on the class object or instance object can be invoked with the following * parameters: * * - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])` * - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])` * - non-GET instance actions: `instance.$action([parameters], [success], [error])` * * * @example * * # Credit card resource * * <pre> // Define CreditCard class var CreditCard = $resource('/user/:userId/card/:cardId', {userId:123, cardId:'@id'}, { charge: {method:'POST', params:{charge:true}} }); // We can retrieve a collection from the server var cards = CreditCard.query(function() { // GET: /user/123/card // server returns: [ {id:456, number:'1234', name:'Smith'} ]; var card = cards[0]; // each item is an instance of CreditCard expect(card instanceof CreditCard).toEqual(true); card.name = "J. Smith"; // non GET methods are mapped onto the instances card.$save(); // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'}; // our custom method is mapped as well. card.$charge({amount:9.99}); // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'} }); // we can create an instance as well var newCard = new CreditCard({number:'0123'}); newCard.name = "Mike Smith"; newCard.$save(); // POST: /user/123/card {number:'0123', name:'Mike Smith'} // server returns: {id:789, number:'01234', name: 'Mike Smith'}; expect(newCard.id).toEqual(789); * </pre> * * The object returned from this function execution is a resource "class" which has "static" method * for each action in the definition. * * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and `headers`. * When the data is returned from the server then the object is an instance of the resource type and * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD * operations (create, read, update, delete) on server-side data. <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function() { user.abc = true; user.$save(); }); </pre> * * It's worth noting that the success callback for `get`, `query` and other method gets passed * in the response that came from the server as well as $http header getter function, so one * could rewrite the above example and get access to http headers as: * <pre> var User = $resource('/user/:userId', {userId:'@id'}); User.get({userId:123}, function(u, getResponseHeaders){ u.abc = true; u.$save(function(u, putResponseHeaders) { //u => saved user object //putResponseHeaders => $http header getter }); }); </pre> * # Buzz client Let's look at what a buzz client created with the `$resource` service looks like: <doc:example> <doc:source jsfiddle="false"> <script> function BuzzController($resource) { this.userId = 'googlebuzz'; this.Activity = $resource( 'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments', {alt:'json', callback:'JSON_CALLBACK'}, {get:{method:'JSONP', params:{visibility:'@self'}}, replies: {method:'JSONP', params:{visibility:'@self', comments:'@comments'}}} ); } BuzzController.prototype = { fetch: function() { this.activities = this.Activity.get({userId:this.userId}); }, expandReplies: function(activity) { activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id}); } }; BuzzController.$inject = ['$resource']; </script> <div ng-controller="BuzzController"> <input ng-model="userId"/> <button ng-click="fetch()">fetch</button> <hr/> <div ng-repeat="item in activities.data.items"> <h1 style="font-size: 15px;"> <img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a> <a href ng-click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a> </h1> {{item.object.content | html}} <div ng-repeat="reply in item.replies.data.items" style="margin-left: 20px;"> <img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}} </div> </div> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angular.module('ngResource', ['ng']). factory('$resource', ['$http', '$parse', function($http, $parse) { var DEFAULT_ACTIONS = { 'get': {method:'GET'}, 'save': {method:'POST'}, 'query': {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} }; var noop = angular.noop, forEach = angular.forEach, extend = angular.extend, copy = angular.copy, isFunction = angular.isFunction, getter = function(obj, path) { return $parse(path)(obj); }; /** * We need our custom method because encodeURIComponent is too aggressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace((pctEncodeSpaces ? null : /%20/g), '+'); } function Route(template, defaults) { this.template = template = template + '#'; this.defaults = defaults || {}; var urlParams = this.urlParams = {}; forEach(template.split(/\W/), function(param){ if (param && template.match(new RegExp("[^\\\\]:" + param + "\\W"))) { urlParams[param] = true; } }); this.template = template.replace(/\\:/g, ':'); } Route.prototype = { url: function(params) { var self = this, url = this.template, val, encodedVal; params = params || {}; forEach(this.urlParams, function(_, urlParam){ val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam]; if (angular.isDefined(val) && val !== null) { encodedVal = encodeUriSegment(val); url = url.replace(new RegExp(":" + urlParam + "(\\W)", "g"), encodedVal + "$1"); } else { url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W)", "g"), function(match, leadingSlashes, tail) { if (tail.charAt(0) == '/') { return tail; } else { return leadingSlashes + tail; } }); } }); url = url.replace(/\/?#$/, ''); var query = []; forEach(params, function(value, key){ if (!self.urlParams[key]) { query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value)); } }); query.sort(); url = url.replace(/\/*$/, ''); return url + (query.length ? '?' + query.join('&') : ''); } }; function ResourceFactory(url, paramDefaults, actions) { var route = new Route(url); actions = extend({}, DEFAULT_ACTIONS, actions); function extractParams(data, actionParams){ var ids = {}; actionParams = extend({}, paramDefaults, actionParams); forEach(actionParams, function(value, key){ if (isFunction(value)) { value = value(); } ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value; }); return ids; } function Resource(value){ copy(value || {}, this); } forEach(actions, function(action, name) { action.method = angular.uppercase(action.method); var hasBody = action.method == 'POST' || action.method == 'PUT' || action.method == 'PATCH'; Resource[name] = function(a1, a2, a3, a4) { var params = {}; var data; var success = noop; var error = null; switch(arguments.length) { case 4: error = a4; success = a3; //fallthrough case 3: case 2: if (isFunction(a2)) { if (isFunction(a1)) { success = a1; error = a2; break; } success = a2; error = a3; //fallthrough } else { params = a1; data = a2; success = a3; break; } case 1: if (isFunction(a1)) success = a1; else if (hasBody) data = a1; else params = a1; break; case 0: break; default: throw "Expected between 0-4 arguments [params, data, success, error], got " + arguments.length + " arguments."; } var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data)); var httpConfig = {}; forEach(action, function(value, key) { if (key != 'params' && key != 'isArray' ) { httpConfig[key] = copy(value); } }); httpConfig.data = data; httpConfig.url = route.url(extend({}, extractParams(data, action.params || {}), params)) $http(httpConfig).then(function(response) { var data = response.data; if (data) { if (action.isArray) { value.length = 0; forEach(data, function(item) { value.push(new Resource(item)); }); } else { copy(data, value); } } (success||noop)(value, response.headers); }, error); return value; }; Resource.prototype['$' + name] = function(a1, a2, a3) { var params = extractParams(this), success = noop, error; switch(arguments.length) { case 3: params = a1; success = a2; error = a3; break; case 2: case 1: if (isFunction(a1)) { success = a1; error = a2; } else { params = a1; success = a2 || noop; } case 0: break; default: throw "Expected between 1-3 arguments [params, success, error], got " + arguments.length + " arguments."; } var data = hasBody ? this : undefined; Resource[name].call(this, params, data, success, error); }; }); Resource.bind = function(additionalParamDefaults){ return ResourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); }; return Resource; } return ResourceFactory; }]); })(window, window.angular);
import { null as nil } from "bar"
define(function (require) { var echarts = require('echarts'); function BMapCoordSys(bmap, api) { this._bmap = bmap; this.dimensions = ['lng', 'lat']; this._mapOffset = [0, 0]; this._api = api; } BMapCoordSys.prototype.dimensions = ['lng', 'lat']; BMapCoordSys.prototype.setMapOffset = function (mapOffset) { this._mapOffset = mapOffset; }; BMapCoordSys.prototype.getBMap = function () { return this._bmap; }; BMapCoordSys.prototype.dataToPoint = function (data) { var point = new BMap.Point(data[0], data[1]); var px = this._bmap.pointToOverlayPixel(point); var mapOffset = this._mapOffset; return [px.x - mapOffset[0], px.y - mapOffset[1]]; }; BMapCoordSys.prototype.pointToData = function (pt) { var mapOffset = this._mapOffset; var pt = this._bmap.overlayPixelToPoint({ x: pt[0] + mapOffset[0], y: pt[1] + mapOffset[1] }); return [pt.lng, pt.lat]; }; BMapCoordSys.prototype.getViewRect = function () { var api = this._api; return new echarts.graphic.BoundingRect(0, 0, api.getWidth(), api.getHeight()); }; BMapCoordSys.prototype.getRoamTransform = function () { return echarts.matrix.create(); }; var Overlay; // For deciding which dimensions to use when creating list data BMapCoordSys.dimensions = BMapCoordSys.prototype.dimensions; function createOverlayCtor() { function Overlay(root) { this._root = root; } Overlay.prototype = new BMap.Overlay(); /** * 初始化 * * @param {BMap.Map} map * @override */ Overlay.prototype.initialize = function (map) { map.getPanes().labelPane.appendChild(this._root); return this._root; }; /** * @override */ Overlay.prototype.draw = function () {}; return Overlay; } BMapCoordSys.create = function (ecModel, api) { var bmapCoordSys; var root = api.getDom(); // TODO Dispose ecModel.eachComponent('bmap', function (bmapModel) { var viewportRoot = api.getZr().painter.getViewportRoot(); if (typeof BMap === 'undefined') { throw new Error('BMap api is not loaded'); } Overlay = Overlay || createOverlayCtor(); if (bmapCoordSys) { throw new Error('Only one bmap component can exist'); } if (!bmapModel.__bmap) { // Not support IE8 var bmapRoot = root.querySelector('.ec-extension-bmap'); if (bmapRoot) { // Reset viewport left and top, which will be changed // in moving handler in BMapView viewportRoot.style.left = '0px'; viewportRoot.style.top = '0px'; root.removeChild(bmapRoot); } bmapRoot = document.createElement('div'); bmapRoot.style.cssText = 'width:100%;height:100%'; // Not support IE8 bmapRoot.classList.add('ec-extension-bmap'); root.appendChild(bmapRoot); var bmap = bmapModel.__bmap = new BMap.Map(bmapRoot); var overlay = new Overlay(viewportRoot); bmap.addOverlay(overlay); } var bmap = bmapModel.__bmap; // Set bmap options // centerAndZoom before layout and render var center = bmapModel.get('center'); var zoom = bmapModel.get('zoom'); if (center && zoom) { var pt = new BMap.Point(center[0], center[1]); bmap.centerAndZoom(pt, zoom); } bmapCoordSys = new BMapCoordSys(bmap, api); bmapCoordSys.setMapOffset(bmapModel.__mapOffset || [0, 0]); bmapModel.coordinateSystem = bmapCoordSys; }); ecModel.eachSeries(function (seriesModel) { if (seriesModel.get('coordinateSystem') === 'bmap') { seriesModel.coordinateSystem = bmapCoordSys; } }); }; return BMapCoordSys; });
/** * @module echarts/coord/polar/Polar */ define(function(require) { 'use strict'; var RadiusAxis = require('./RadiusAxis'); var AngleAxis = require('./AngleAxis'); /** * @alias {module:echarts/coord/polar/Polar} * @constructor * @param {string} name */ var Polar = function (name) { /** * @type {string} */ this.name = name || ''; /** * x of polar center * @type {number} */ this.cx = 0; /** * y of polar center * @type {number} */ this.cy = 0; /** * @type {module:echarts/coord/polar/RadiusAxis} * @private */ this._radiusAxis = new RadiusAxis(); /** * @type {module:echarts/coord/polar/AngleAxis} * @private */ this._angleAxis = new AngleAxis(); }; Polar.prototype = { constructor: Polar, type: 'polar', /** * @param {Array.<string>} * @readOnly */ dimensions: ['radius', 'angle'], /** * If contain coord * @param {Array.<number>} point * @return {boolean} */ containPoint: function (point) { var coord = this.pointToCoord(point); return this._radiusAxis.contain(coord[0]) && this._angleAxis.contain(coord[1]); }, /** * If contain data * @param {Array.<number>} data * @return {boolean} */ containData: function (data) { return this._radiusAxis.containData(data[0]) && this._angleAxis.containData(data[1]); }, /** * @param {string} axisType * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis} */ getAxis: function (axisType) { return this['_' + axisType + 'Axis']; }, /** * Get axes by type of scale * @param {string} scaleType * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis} */ getAxesByScale: function (scaleType) { var axes = []; var angleAxis = this._angleAxis; var radiusAxis = this._radiusAxis; angleAxis.scale.type === scaleType && axes.push(angleAxis); radiusAxis.scale.type === scaleType && axes.push(radiusAxis); return axes; }, /** * @return {module:echarts/coord/polar/AngleAxis} */ getAngleAxis: function () { return this._angleAxis; }, /** * @return {module:echarts/coord/polar/RadiusAxis} */ getRadiusAxis: function () { return this._radiusAxis; }, /** * @param {module:echarts/coord/polar/Axis} * @return {module:echarts/coord/polar/Axis} */ getOtherAxis: function (axis) { var angleAxis = this._angleAxis; return axis === angleAxis ? this._radiusAxis : angleAxis; }, /** * Base axis will be used on stacking. * * @return {module:echarts/coord/polar/Axis} */ getBaseAxis: function () { return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAngleAxis(); }, /** * Convert series data to a list of (x, y) points * @param {module:echarts/data/List} data * @return {Array} * Return list of coordinates. For example: * `[[10, 10], [20, 20], [30, 30]]` */ dataToPoints: function (data) { return data.mapArray(this.dimensions, function (radius, angle) { return this.dataToPoint([radius, angle]); }, this); }, /** * Convert a single data item to (x, y) point. * Parameter data is an array which the first element is radius and the second is angle * @param {Array.<number>} data * @param {boolean} [clamp=false] * @return {Array.<number>} */ dataToPoint: function (data, clamp) { return this.coordToPoint([ this._radiusAxis.dataToRadius(data[0], clamp), this._angleAxis.dataToAngle(data[1], clamp) ]); }, /** * Convert a (x, y) point to data * @param {Array.<number>} point * @param {boolean} [clamp=false] * @return {Array.<number>} */ pointToData: function (point, clamp) { var coord = this.pointToCoord(point); return [ this._radiusAxis.radiusToData(coord[0], clamp), this._angleAxis.angleToData(coord[1], clamp) ]; }, /** * Convert a (x, y) point to (radius, angle) coord * @param {Array.<number>} point * @return {Array.<number>} */ pointToCoord: function (point) { var dx = point[0] - this.cx; var dy = point[1] - this.cy; var angleAxis = this.getAngleAxis(); var extent = angleAxis.getExtent(); var minAngle = Math.min(extent[0], extent[1]); var maxAngle = Math.max(extent[0], extent[1]); // Fix fixed extent in polarCreator // FIXME angleAxis.inverse ? (minAngle = maxAngle - 360) : (maxAngle = minAngle + 360); var radius = Math.sqrt(dx * dx + dy * dy); dx /= radius; dy /= radius; var radian = Math.atan2(-dy, dx) / Math.PI * 180; // move to angleExtent var dir = radian < minAngle ? 1 : -1; while (radian < minAngle || radian > maxAngle) { radian += dir * 360; } return [radius, radian]; }, /** * Convert a (radius, angle) coord to (x, y) point * @param {Array.<number>} coord * @return {Array.<number>} */ coordToPoint: function (coord) { var radius = coord[0]; var radian = coord[1] / 180 * Math.PI; var x = Math.cos(radian) * radius + this.cx; // Inverse the y var y = -Math.sin(radian) * radius + this.cy; return [x, y]; } }; return Polar; });
YUI.add("lang/datatype-date-format_es-MX",function(e){e.Intl.add("datatype-date-format","es-MX",{a:["dom","lun","mar","mié","jue","vie","sáb"],A:["domingo","lunes","martes","miércoles","jueves","viernes","sábado"],b:["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],B:["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"],c:"%a, %d %b %Y %H:%M:%S %Z",p:["A.M.","P.M."],P:["a.m.","p.m."],x:"%d/%m/%y",X:"%H:%M:%S"})},"@VERSION@")
/* * /MathJax/jax/output/SVG/fonts/TeX/AMS/Regular/LatinExtendedA.js * * Copyright (c) 2012 Design Science, Inc. * * Part of the MathJax library. * See http://www.mathjax.org for details. * * Licensed under the Apache License, Version 2.0; * you may not use this file except in compliance with the License. * * http://www.apache.org/licenses/LICENSE-2.0 */ MathJax.Hub.Insert(MathJax.OutputJax.SVG.FONTDATA.FONTS.MathJax_AMS,{295:[695,13,540,42,562,"182 599Q182 611 174 615T133 619Q118 619 114 621T109 630Q109 636 114 656T122 681Q125 685 202 688Q272 695 286 695Q304 695 304 684Q304 682 295 644T282 597Q282 592 360 592H399Q430 592 445 587T460 563Q460 552 451 541L442 535H266L251 468Q247 453 243 436T236 409T233 399Q233 395 244 404Q295 441 357 441Q405 441 445 417T485 333Q485 284 449 178T412 58T426 44Q447 44 466 68Q485 87 500 130L509 152H531H543Q562 152 562 144Q562 128 546 93T494 23T415 -13Q385 -13 359 3T322 44Q318 52 318 77Q318 99 352 196T386 337Q386 386 346 386Q318 386 286 370Q267 361 245 338T211 292Q207 287 193 235T162 113T138 21Q128 7 122 4Q105 -12 83 -12Q66 -12 54 -2T42 26L166 530Q166 534 161 534T129 535Q127 535 122 535T112 534Q74 534 74 562Q74 570 77 576T84 585T96 589T109 591T124 592T138 592L182 595V599"]});MathJax.Ajax.loadComplete(MathJax.OutputJax.SVG.fontDir+"/AMS/Regular/LatinExtendedA.js");
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("widget","fa",{move:"کلیک و کشیدن برای جابجایی"});
"use strict" var ReadPreference = require('../topologies/read_preference'); var getReadPreference = function(cmd, options) { // Default to command version of the readPreference var readPreference = cmd.readPreference || new ReadPreference('primary'); // If we have an option readPreference override the command one if(options.readPreference) { readPreference = options.readPreference; } if(typeof readPreference == 'string') { readPreference = new ReadPreference(readPreference); } if(!(readPreference instanceof ReadPreference)) { throw new MongoError('readPreference must be a ReadPreference instance'); } return readPreference; } module.exports = { getReadPreference: getReadPreference }
export const ADD_TODO = 'ADD_TODO'; export const DELETE_TODO = 'DELETE_TODO'; export const EDIT_TODO = 'EDIT_TODO'; export const COMPLETE_TODO = 'COMPLETE_TODO'; export const COMPLETE_ALL = 'COMPLETE_ALL'; export const CLEAR_COMPLETED = 'CLEAR_COMPLETED';
OpenLayers.Pixel=OpenLayers.Class({x:0,y:0,initialize:function(e,t){this.x=parseFloat(e),this.y=parseFloat(t)},toString:function(){return"x="+this.x+",y="+this.y},clone:function(){return new OpenLayers.Pixel(this.x,this.y)},equals:function(e){var t=!1;return null!=e&&(t=this.x==e.x&&this.y==e.y||isNaN(this.x)&&isNaN(this.y)&&isNaN(e.x)&&isNaN(e.y)),t},distanceTo:function(e){return Math.sqrt(Math.pow(this.x-e.x,2)+Math.pow(this.y-e.y,2))},add:function(e,t){if(null==e||null==t){var i=OpenLayers.i18n("pixelAddError");return OpenLayers.Console.error(i),null}return new OpenLayers.Pixel(this.x+e,this.y+t)},offset:function(e){var t=this.clone();return e&&(t=this.add(e.x,e.y)),t},CLASS_NAME:"OpenLayers.Pixel"});