code
stringlengths
2
1.05M
/** * @author qiao / https://github.com/qiao * @fileoverview This is a convex hull generator using the incremental method. * The complexity is O(n^2) where n is the number of vertices. * O(nlogn) algorithms do exist, but they are much more complicated. * * Benchmark: * * Platform: CPU: P7350 @2.00GHz Engine: V8 * * Num Vertices Time(ms) * * 10 1 * 20 3 * 30 19 * 40 48 * 50 107 */ THREE.ConvexGeometry = function( vertices ) { THREE.Geometry.call( this ); var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ]; for ( var i = 3; i < vertices.length; i++ ) { addPoint( i ); } function addPoint( vertexId ) { var vertex = vertices[ vertexId ].clone(); var mag = vertex.length(); vertex.x += mag * randomOffset(); vertex.y += mag * randomOffset(); vertex.z += mag * randomOffset(); var hole = []; for ( var f = 0; f < faces.length; ) { var face = faces[ f ]; // for each face, if the vertex can see it, // then we try to add the face's edges into the hole. if ( visible( face, vertex ) ) { for ( var e = 0; e < 3; e++ ) { var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ]; var boundary = true; // remove duplicated edges. for ( var h = 0; h < hole.length; h++ ) { if ( equalEdge( hole[ h ], edge ) ) { hole[ h ] = hole[ hole.length - 1 ]; hole.pop(); boundary = false; break; } } if ( boundary ) { hole.push( edge ); } } // remove faces[ f ] faces[ f ] = faces[ faces.length - 1 ]; faces.pop(); } else { // not visible f++; } } // construct the new faces formed by the edges of the hole and the vertex for ( var h = 0; h < hole.length; h++ ) { faces.push( [ hole[ h ][ 0 ], hole[ h ][ 1 ], vertexId ] ); } } /** * Whether the face is visible from the vertex */ function visible( face, vertex ) { var va = vertices[ face[ 0 ] ]; var vb = vertices[ face[ 1 ] ]; var vc = vertices[ face[ 2 ] ]; var n = normal( va, vb, vc ); // distance from face to origin var dist = n.dot( va ); return n.dot( vertex ) >= dist; } /** * Face normal */ function normal( va, vb, vc ) { var cb = new THREE.Vector3(); var ab = new THREE.Vector3(); cb.subVectors( vc, vb ); ab.subVectors( va, vb ); cb.cross( ab ); cb.normalize(); return cb; } /** * Detect whether two edges are equal. * Note that when constructing the convex hull, two same edges can only * be of the negative direction. */ function equalEdge( ea, eb ) { return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ]; } /** * Create a random offset between -1e-6 and 1e-6. */ function randomOffset() { return ( Math.random() - 0.5 ) * 2 * 1e-6; } /** * XXX: Not sure if this is the correct approach. Need someone to review. */ function vertexUv( vertex ) { var mag = vertex.length(); return new THREE.Vector2( vertex.x / mag, vertex.y / mag ); } // Push vertices into `this.vertices`, skipping those inside the hull var id = 0; var newId = new Array( vertices.length ); // map from old vertex id to new id for ( var i = 0; i < faces.length; i++ ) { var face = faces[ i ]; for ( var j = 0; j < 3; j++ ) { if ( newId[ face[ j ] ] === undefined ) { newId[ face[ j ] ] = id++; this.vertices.push( vertices[ face[ j ] ] ); } face[ j ] = newId[ face[ j ] ]; } } // Convert faces into instances of THREE.Face3 for ( var i = 0; i < faces.length; i++ ) { this.faces.push( new THREE.Face3( faces[ i ][ 0 ], faces[ i ][ 1 ], faces[ i ][ 2 ] ) ); } // Compute UVs for ( var i = 0; i < this.faces.length; i++ ) { var face = this.faces[ i ]; this.faceVertexUvs[ 0 ].push( [ vertexUv( this.vertices[ face.a ] ), vertexUv( this.vertices[ face.b ] ), vertexUv( this.vertices[ face.c ]) ] ); } this.computeCentroids(); this.computeFaceNormals(); this.computeVertexNormals(); }; THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
he.js
/* eslint-disable */ ;(function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD define(['../core'], factory); } else if (typeof exports === 'object') { // Node.js module.exports = factory(require('../core')); } else { // Browser root.Blockly.Msg = factory(root.Blockly); } }(this, function(Blockly) { var Blockly = {};Blockly.Msg={};// This file was automatically generated. Do not modify. 'use strict'; Blockly.Msg["ADD_COMMENT"] = "تبصرہ کرو"; Blockly.Msg["CANNOT_DELETE_VARIABLE_PROCEDURE"] = "Can't delete the variable '%1' because it's part of the definition of the function '%2'"; // untranslated Blockly.Msg["CHANGE_VALUE_TITLE"] = "ویلیو تبدیل کرو:"; Blockly.Msg["CLEAN_UP"] = "بلاک صاف کرو"; Blockly.Msg["COLLAPSED_WARNINGS_WARNING"] = "Collapsed blocks contain warnings."; // untranslated Blockly.Msg["COLLAPSE_ALL"] = "بلاک کٹھے کرو"; Blockly.Msg["COLLAPSE_BLOCK"] = "بلا ک کٹھے کرو"; Blockly.Msg["COLOUR_BLEND_COLOUR1"] = "رنگ 1"; Blockly.Msg["COLOUR_BLEND_COLOUR2"] = "رنگ 2"; Blockly.Msg["COLOUR_BLEND_HELPURL"] = "https://meyerweb.com/eric/tools/color-blend/#:::rgbp"; // untranslated Blockly.Msg["COLOUR_BLEND_RATIO"] = "نسبت"; Blockly.Msg["COLOUR_BLEND_TITLE"] = "مرکب"; Blockly.Msg["COLOUR_BLEND_TOOLTIP"] = "Blends two colours together with a given ratio (0.0 - 1.0)."; // untranslated Blockly.Msg["COLOUR_PICKER_HELPURL"] = "https://en.wikipedia.org/wiki/Color"; Blockly.Msg["COLOUR_PICKER_TOOLTIP"] = "Choose a colour from the palette."; // untranslated Blockly.Msg["COLOUR_RANDOM_HELPURL"] = "http://randomcolour.com"; // untranslated Blockly.Msg["COLOUR_RANDOM_TITLE"] = "بنا ترتيب رنگ"; Blockly.Msg["COLOUR_RANDOM_TOOLTIP"] = "Choose a colour at random."; // untranslated Blockly.Msg["COLOUR_RGB_BLUE"] = "نیلا"; Blockly.Msg["COLOUR_RGB_GREEN"] = "ساوا"; Blockly.Msg["COLOUR_RGB_HELPURL"] = "https://www.december.com/html/spec/colorpercompact.html"; // untranslated Blockly.Msg["COLOUR_RGB_RED"] = "رتا"; Blockly.Msg["COLOUR_RGB_TITLE"] = "نال رن٘گ"; Blockly.Msg["COLOUR_RGB_TOOLTIP"] = "Create a colour with the specified amount of red, green, and blue. All values must be between 0 and 100."; // untranslated Blockly.Msg["CONTROLS_FLOW_STATEMENTS_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#loop-termination-blocks"; // untranslated Blockly.Msg["CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK"] = "گھیرے کنوں ٻاہر نکلݨ"; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE"] = "continue with next iteration of loop"; // untranslated Blockly.Msg["CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK"] = "Break out of the containing loop."; // untranslated Blockly.Msg["CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE"] = "Skip the rest of this loop, and continue with the next iteration."; // untranslated Blockly.Msg["CONTROLS_FLOW_STATEMENTS_WARNING"] = "Warning: This block may only be used within a loop."; // untranslated Blockly.Msg["CONTROLS_FOREACH_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#for-each"; // untranslated Blockly.Msg["CONTROLS_FOREACH_TITLE"] = "for each item %1 in list %2"; // untranslated Blockly.Msg["CONTROLS_FOREACH_TOOLTIP"] = "For each item in a list, set the variable '%1' to the item, and then do some statements."; // untranslated Blockly.Msg["CONTROLS_FOR_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#count-with"; // untranslated Blockly.Msg["CONTROLS_FOR_TITLE"] = "count with %1 from %2 to %3 by %4"; // untranslated Blockly.Msg["CONTROLS_FOR_TOOLTIP"] = "Have the variable '%1' take on the values from the start number to the end number, counting by the specified interval, and do the specified blocks."; // untranslated Blockly.Msg["CONTROLS_IF_ELSEIF_TOOLTIP"] = "Add a condition to the if block."; // untranslated Blockly.Msg["CONTROLS_IF_ELSE_TOOLTIP"] = "Add a final, catch-all condition to the if block."; // untranslated Blockly.Msg["CONTROLS_IF_HELPURL"] = "https://github.com/google/blockly/wiki/IfElse"; // untranslated Blockly.Msg["CONTROLS_IF_IF_TOOLTIP"] = "Add, remove, or reorder sections to reconfigure this if block."; // untranslated Blockly.Msg["CONTROLS_IF_MSG_ELSE"] = "وکھرا"; Blockly.Msg["CONTROLS_IF_MSG_ELSEIF"] = "ٻیا اگر"; Blockly.Msg["CONTROLS_IF_MSG_IF"] = "جے"; Blockly.Msg["CONTROLS_IF_TOOLTIP_1"] = "If a value is true, then do some statements."; // untranslated Blockly.Msg["CONTROLS_IF_TOOLTIP_2"] = "If a value is true, then do the first block of statements. Otherwise, do the second block of statements."; // untranslated Blockly.Msg["CONTROLS_IF_TOOLTIP_3"] = "If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements."; // untranslated Blockly.Msg["CONTROLS_IF_TOOLTIP_4"] = "If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements. If none of the values are true, do the last block of statements."; // untranslated Blockly.Msg["CONTROLS_REPEAT_HELPURL"] = "https://en.wikipedia.org/wiki/For_loop"; // untranslated Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"] = "کرو"; Blockly.Msg["CONTROLS_REPEAT_TITLE"] = "repeat %1 times"; // untranslated Blockly.Msg["CONTROLS_REPEAT_TOOLTIP"] = "Do some statements several times."; // untranslated Blockly.Msg["CONTROLS_WHILEUNTIL_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#repeat"; // untranslated Blockly.Msg["CONTROLS_WHILEUNTIL_OPERATOR_UNTIL"] = "تائیں دہرائے"; Blockly.Msg["CONTROLS_WHILEUNTIL_OPERATOR_WHILE"] = "repeat while"; // untranslated Blockly.Msg["CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL"] = "While a value is false, then do some statements."; // untranslated Blockly.Msg["CONTROLS_WHILEUNTIL_TOOLTIP_WHILE"] = "While a value is true, then do some statements."; // untranslated Blockly.Msg["DELETE_ALL_BLOCKS"] = "بھلا %1 بلاکاں کوں مٹاؤں؟"; Blockly.Msg["DELETE_BLOCK"] = "بلاک مٹاؤ"; Blockly.Msg["DELETE_VARIABLE"] = "Delete the '%1' variable"; // untranslated Blockly.Msg["DELETE_VARIABLE_CONFIRMATION"] = "Delete %1 uses of the '%2' variable?"; // untranslated Blockly.Msg["DELETE_X_BLOCKS"] = "%1 بلاکاں کوں مٹاؤ"; Blockly.Msg["DIALOG_CANCEL"] = "منسوخ"; Blockly.Msg["DIALOG_OK"] = "ٹھیک ہے"; Blockly.Msg["DISABLE_BLOCK"] = "بلاک ہٹاؤ"; Blockly.Msg["DUPLICATE_BLOCK"] = "ڈپلیکیٹ"; Blockly.Msg["DUPLICATE_COMMENT"] = "Duplicate Comment"; // untranslated Blockly.Msg["ENABLE_BLOCK"] = "بلاک فعال کرو"; Blockly.Msg["EXPAND_ALL"] = "بلاکوں کوں کھنڈاؤ"; Blockly.Msg["EXPAND_BLOCK"] = "بلاک کھنڈاؤ"; Blockly.Msg["EXTERNAL_INPUTS"] = "باہرلے انپٹ"; Blockly.Msg["HELP"] = "مدد"; Blockly.Msg["INLINE_INPUTS"] = "ان لائن ان پٹ"; Blockly.Msg["LISTS_CREATE_EMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-empty-list"; // untranslated Blockly.Msg["LISTS_CREATE_EMPTY_TITLE"] = "خالی تندیر بݨاؤ"; Blockly.Msg["LISTS_CREATE_EMPTY_TOOLTIP"] = "Returns a list, of length 0, containing no data records"; // untranslated Blockly.Msg["LISTS_CREATE_WITH_CONTAINER_TITLE_ADD"] = "فہرست"; Blockly.Msg["LISTS_CREATE_WITH_CONTAINER_TOOLTIP"] = "Add, remove, or reorder sections to reconfigure this list block."; // untranslated Blockly.Msg["LISTS_CREATE_WITH_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated Blockly.Msg["LISTS_CREATE_WITH_INPUT_WITH"] = "create list with"; // untranslated Blockly.Msg["LISTS_CREATE_WITH_ITEM_TOOLTIP"] = "Add an item to the list."; // untranslated Blockly.Msg["LISTS_CREATE_WITH_TOOLTIP"] = "Create a list with any number of items."; // untranslated Blockly.Msg["LISTS_GET_INDEX_FIRST"] = "پہلا"; Blockly.Msg["LISTS_GET_INDEX_FROM_END"] = "# چھیکڑ کنوں"; Blockly.Msg["LISTS_GET_INDEX_FROM_START"] = "#"; // untranslated Blockly.Msg["LISTS_GET_INDEX_GET"] = "گھنو"; Blockly.Msg["LISTS_GET_INDEX_GET_REMOVE"] = "گھنو تے ہٹاؤ"; Blockly.Msg["LISTS_GET_INDEX_LAST"] = "چھیکڑی"; Blockly.Msg["LISTS_GET_INDEX_RANDOM"] = "قُݨے نال"; Blockly.Msg["LISTS_GET_INDEX_REMOVE"] = "ہٹاؤ"; Blockly.Msg["LISTS_GET_INDEX_TAIL"] = ""; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_FIRST"] = "Returns the first item in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_FROM"] = "Returns the item at the specified position in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_LAST"] = "Returns the last item in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_RANDOM"] = "Returns a random item in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST"] = "Removes and returns the first item in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM"] = "Removes and returns the item at the specified position in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST"] = "Removes and returns the last item in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM"] = "Removes and returns a random item in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST"] = "Removes the first item in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM"] = "Removes the item at the specified position in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST"] = "Removes the last item in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM"] = "Removes a random item in a list."; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_END_FROM_END"] = "to # from end"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_END_FROM_START"] = "to #"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_END_LAST"] = "to last"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_START_FIRST"] = "get sub-list from first"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_START_FROM_END"] = "get sub-list from # from end"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_START_FROM_START"] = "get sub-list from #"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_TAIL"] = ""; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_TOOLTIP"] = "Creates a copy of the specified portion of a list."; // untranslated Blockly.Msg["LISTS_INDEX_FROM_END_TOOLTIP"] = "%1 is the last item."; // untranslated Blockly.Msg["LISTS_INDEX_FROM_START_TOOLTIP"] = "%1 is the first item."; // untranslated Blockly.Msg["LISTS_INDEX_OF_FIRST"] = "find first occurrence of item"; // untranslated Blockly.Msg["LISTS_INDEX_OF_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list"; // untranslated Blockly.Msg["LISTS_INDEX_OF_LAST"] = "find last occurrence of item"; // untranslated Blockly.Msg["LISTS_INDEX_OF_TOOLTIP"] = "Returns the index of the first/last occurrence of the item in the list. Returns %1 if item is not found."; // untranslated Blockly.Msg["LISTS_INLIST"] = "فہرست وچ"; Blockly.Msg["LISTS_ISEMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#is-empty"; // untranslated Blockly.Msg["LISTS_ISEMPTY_TITLE"] = "%1 خالی ہے"; Blockly.Msg["LISTS_ISEMPTY_TOOLTIP"] = "Returns true if the list is empty."; // untranslated Blockly.Msg["LISTS_LENGTH_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#length-of"; // untranslated Blockly.Msg["LISTS_LENGTH_TITLE"] = "length of %1"; // untranslated Blockly.Msg["LISTS_LENGTH_TOOLTIP"] = "Returns the length of a list."; // untranslated Blockly.Msg["LISTS_REPEAT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated Blockly.Msg["LISTS_REPEAT_TITLE"] = "create list with item %1 repeated %2 times"; // untranslated Blockly.Msg["LISTS_REPEAT_TOOLTIP"] = "Creates a list consisting of the given value repeated the specified number of times."; // untranslated Blockly.Msg["LISTS_REVERSE_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#reversing-a-list"; // untranslated Blockly.Msg["LISTS_REVERSE_MESSAGE0"] = "reverse %1"; // untranslated Blockly.Msg["LISTS_REVERSE_TOOLTIP"] = "Reverse a copy of a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#in-list--set"; // untranslated Blockly.Msg["LISTS_SET_INDEX_INPUT_TO"] = "بطور"; Blockly.Msg["LISTS_SET_INDEX_INSERT"] = "تے درج کرو"; Blockly.Msg["LISTS_SET_INDEX_SET"] = "سیٹ"; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST"] = "Inserts the item at the start of a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_FROM"] = "Inserts the item at the specified position in a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_LAST"] = "Append the item to the end of a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM"] = "Inserts the item randomly in a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_FIRST"] = "Sets the first item in a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_FROM"] = "Sets the item at the specified position in a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_LAST"] = "Sets the last item in a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_RANDOM"] = "Sets a random item in a list."; // untranslated Blockly.Msg["LISTS_SORT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#sorting-a-list"; // untranslated Blockly.Msg["LISTS_SORT_ORDER_ASCENDING"] = "چڑھدا ہویا"; Blockly.Msg["LISTS_SORT_ORDER_DESCENDING"] = "لہندا ہویا"; Blockly.Msg["LISTS_SORT_TITLE"] = "سارٹ کرو%1%2%3"; Blockly.Msg["LISTS_SORT_TOOLTIP"] = "Sort a copy of a list."; // untranslated Blockly.Msg["LISTS_SORT_TYPE_IGNORECASE"] = "alphabetic, ignore case"; // untranslated Blockly.Msg["LISTS_SORT_TYPE_NUMERIC"] = "عددی"; Blockly.Msg["LISTS_SORT_TYPE_TEXT"] = "الف بے دی"; Blockly.Msg["LISTS_SPLIT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists"; // untranslated Blockly.Msg["LISTS_SPLIT_LIST_FROM_TEXT"] = "make list from text"; // untranslated Blockly.Msg["LISTS_SPLIT_TEXT_FROM_LIST"] = "make text from list"; // untranslated Blockly.Msg["LISTS_SPLIT_TOOLTIP_JOIN"] = "Join a list of texts into one text, separated by a delimiter."; // untranslated Blockly.Msg["LISTS_SPLIT_TOOLTIP_SPLIT"] = "Split text into a list of texts, breaking at each delimiter."; // untranslated Blockly.Msg["LISTS_SPLIT_WITH_DELIMITER"] = "with delimiter"; // untranslated Blockly.Msg["LOGIC_BOOLEAN_FALSE"] = "غلط"; Blockly.Msg["LOGIC_BOOLEAN_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#values"; // untranslated Blockly.Msg["LOGIC_BOOLEAN_TOOLTIP"] = "Returns either true or false."; // untranslated Blockly.Msg["LOGIC_BOOLEAN_TRUE"] = "سچ"; Blockly.Msg["LOGIC_COMPARE_HELPURL"] = "https://en.wikipedia.org/wiki/Inequality_(mathematics)"; // untranslated Blockly.Msg["LOGIC_COMPARE_TOOLTIP_EQ"] = "Return true if both inputs equal each other."; // untranslated Blockly.Msg["LOGIC_COMPARE_TOOLTIP_GT"] = "Return true if the first input is greater than the second input."; // untranslated Blockly.Msg["LOGIC_COMPARE_TOOLTIP_GTE"] = "Return true if the first input is greater than or equal to the second input."; // untranslated Blockly.Msg["LOGIC_COMPARE_TOOLTIP_LT"] = "Return true if the first input is smaller than the second input."; // untranslated Blockly.Msg["LOGIC_COMPARE_TOOLTIP_LTE"] = "Return true if the first input is smaller than or equal to the second input."; // untranslated Blockly.Msg["LOGIC_COMPARE_TOOLTIP_NEQ"] = "Return true if both inputs are not equal to each other."; // untranslated Blockly.Msg["LOGIC_NEGATE_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#not"; // untranslated Blockly.Msg["LOGIC_NEGATE_TITLE"] = "%1 کائنی"; Blockly.Msg["LOGIC_NEGATE_TOOLTIP"] = "Returns true if the input is false. Returns false if the input is true."; // untranslated Blockly.Msg["LOGIC_NULL"] = "کوئی وی کائنی"; Blockly.Msg["LOGIC_NULL_HELPURL"] = "https://en.wikipedia.org/wiki/Nullable_type"; // untranslated Blockly.Msg["LOGIC_NULL_TOOLTIP"] = "Returns null."; // untranslated Blockly.Msg["LOGIC_OPERATION_AND"] = "اتے"; Blockly.Msg["LOGIC_OPERATION_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#logical-operations"; // untranslated Blockly.Msg["LOGIC_OPERATION_OR"] = "یا"; Blockly.Msg["LOGIC_OPERATION_TOOLTIP_AND"] = "Return true if both inputs are true."; // untranslated Blockly.Msg["LOGIC_OPERATION_TOOLTIP_OR"] = "Return true if at least one of the inputs is true."; // untranslated Blockly.Msg["LOGIC_TERNARY_CONDITION"] = "ٹیسٹ"; Blockly.Msg["LOGIC_TERNARY_HELPURL"] = "https://en.wikipedia.org/wiki/%3F:"; // untranslated Blockly.Msg["LOGIC_TERNARY_IF_FALSE"] = "اگر کوڑ ہے"; Blockly.Msg["LOGIC_TERNARY_IF_TRUE"] = "اگر سچ ہے"; Blockly.Msg["LOGIC_TERNARY_TOOLTIP"] = "Check the condition in 'test'. If the condition is true, returns the 'if true' value; otherwise returns the 'if false' value."; // untranslated Blockly.Msg["MATH_ADDITION_SYMBOL"] = "+"; // untranslated Blockly.Msg["MATH_ARITHMETIC_HELPURL"] = "https://en.wikipedia.org/wiki/Arithmetic"; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_ADD"] = "Return the sum of the two numbers."; // untranslated Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_DIVIDE"] = "Return the quotient of the two numbers."; // untranslated Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_MINUS"] = "Return the difference of the two numbers."; // untranslated Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_MULTIPLY"] = "Return the product of the two numbers."; // untranslated Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_POWER"] = "Return the first number raised to the power of the second number."; // untranslated Blockly.Msg["MATH_ATAN2_HELPURL"] = "https://en.wikipedia.org/wiki/Atan2"; // untranslated Blockly.Msg["MATH_ATAN2_TITLE"] = "atan2 of X:%1 Y:%2"; // untranslated Blockly.Msg["MATH_ATAN2_TOOLTIP"] = "Return the arctangent of point (X, Y) in degrees from -180 to 180."; // untranslated Blockly.Msg["MATH_CHANGE_HELPURL"] = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter"; // untranslated Blockly.Msg["MATH_CHANGE_TITLE"] = "change %1 by %2"; // untranslated Blockly.Msg["MATH_CHANGE_TOOLTIP"] = "Add a number to variable '%1'."; // untranslated Blockly.Msg["MATH_CONSTANT_HELPURL"] = "https://en.wikipedia.org/wiki/Mathematical_constant"; // untranslated Blockly.Msg["MATH_CONSTANT_TOOLTIP"] = "Return one of the common constants: π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), or ∞ (infinity)."; // untranslated Blockly.Msg["MATH_CONSTRAIN_HELPURL"] = "https://en.wikipedia.org/wiki/Clamping_(graphics)"; // untranslated Blockly.Msg["MATH_CONSTRAIN_TITLE"] = "constrain %1 low %2 high %3"; // untranslated Blockly.Msg["MATH_CONSTRAIN_TOOLTIP"] = "Constrain a number to be between the specified limits (inclusive)."; // untranslated Blockly.Msg["MATH_DIVISION_SYMBOL"] = "÷"; // untranslated Blockly.Msg["MATH_IS_DIVISIBLE_BY"] = "is divisible by"; // untranslated Blockly.Msg["MATH_IS_EVEN"] = "جفت ہے"; Blockly.Msg["MATH_IS_NEGATIVE"] = "منفی ہے"; Blockly.Msg["MATH_IS_ODD"] = "طاق ہے"; Blockly.Msg["MATH_IS_POSITIVE"] = "مثبت ہے"; Blockly.Msg["MATH_IS_PRIME"] = "مفرد ہے"; Blockly.Msg["MATH_IS_TOOLTIP"] = "Check if a number is an even, odd, prime, whole, positive, negative, or if it is divisible by certain number. Returns true or false."; // untranslated Blockly.Msg["MATH_IS_WHOLE"] = "مکمل ہے"; Blockly.Msg["MATH_MODULO_HELPURL"] = "https://en.wikipedia.org/wiki/Modulo_operation"; // untranslated Blockly.Msg["MATH_MODULO_TITLE"] = "remainder of %1 ÷ %2"; // untranslated Blockly.Msg["MATH_MODULO_TOOLTIP"] = "Return the remainder from dividing the two numbers."; // untranslated Blockly.Msg["MATH_MULTIPLICATION_SYMBOL"] = "×"; // untranslated Blockly.Msg["MATH_NUMBER_HELPURL"] = "https://en.wikipedia.org/wiki/Number"; // untranslated Blockly.Msg["MATH_NUMBER_TOOLTIP"] = "ہک عدد"; Blockly.Msg["MATH_ONLIST_HELPURL"] = ""; // untranslated Blockly.Msg["MATH_ONLIST_OPERATOR_AVERAGE"] = "فہرست دی اوسط"; Blockly.Msg["MATH_ONLIST_OPERATOR_MAX"] = "لسٹ وچوں سب توں ودھ"; Blockly.Msg["MATH_ONLIST_OPERATOR_MEDIAN"] = "median of list"; // untranslated Blockly.Msg["MATH_ONLIST_OPERATOR_MIN"] = "لسٹ وچوں سب توں گھٹ"; Blockly.Msg["MATH_ONLIST_OPERATOR_MODE"] = "modes of list"; // untranslated Blockly.Msg["MATH_ONLIST_OPERATOR_RANDOM"] = "random item of list"; // untranslated Blockly.Msg["MATH_ONLIST_OPERATOR_STD_DEV"] = "standard deviation of list"; // untranslated Blockly.Msg["MATH_ONLIST_OPERATOR_SUM"] = "لسٹ دا مجموعہ"; Blockly.Msg["MATH_ONLIST_TOOLTIP_AVERAGE"] = "Return the average (arithmetic mean) of the numeric values in the list."; // untranslated Blockly.Msg["MATH_ONLIST_TOOLTIP_MAX"] = "Return the largest number in the list."; // untranslated Blockly.Msg["MATH_ONLIST_TOOLTIP_MEDIAN"] = "Return the median number in the list."; // untranslated Blockly.Msg["MATH_ONLIST_TOOLTIP_MIN"] = "Return the smallest number in the list."; // untranslated Blockly.Msg["MATH_ONLIST_TOOLTIP_MODE"] = "Return a list of the most common item(s) in the list."; // untranslated Blockly.Msg["MATH_ONLIST_TOOLTIP_RANDOM"] = "Return a random element from the list."; // untranslated Blockly.Msg["MATH_ONLIST_TOOLTIP_STD_DEV"] = "Return the standard deviation of the list."; // untranslated Blockly.Msg["MATH_ONLIST_TOOLTIP_SUM"] = "Return the sum of all the numbers in the list."; // untranslated Blockly.Msg["MATH_POWER_SYMBOL"] = "^"; // untranslated Blockly.Msg["MATH_RANDOM_FLOAT_HELPURL"] = "https://en.wikipedia.org/wiki/Random_number_generation"; // untranslated Blockly.Msg["MATH_RANDOM_FLOAT_TITLE_RANDOM"] = "random fraction"; // untranslated Blockly.Msg["MATH_RANDOM_FLOAT_TOOLTIP"] = "Return a random fraction between 0.0 (inclusive) and 1.0 (exclusive)."; // untranslated Blockly.Msg["MATH_RANDOM_INT_HELPURL"] = "https://en.wikipedia.org/wiki/Random_number_generation"; // untranslated Blockly.Msg["MATH_RANDOM_INT_TITLE"] = "random integer from %1 to %2"; // untranslated Blockly.Msg["MATH_RANDOM_INT_TOOLTIP"] = "Return a random integer between the two specified limits, inclusive."; // untranslated Blockly.Msg["MATH_ROUND_HELPURL"] = "https://en.wikipedia.org/wiki/Rounding"; // untranslated Blockly.Msg["MATH_ROUND_OPERATOR_ROUND"] = "round"; // untranslated Blockly.Msg["MATH_ROUND_OPERATOR_ROUNDDOWN"] = "round down"; // untranslated Blockly.Msg["MATH_ROUND_OPERATOR_ROUNDUP"] = "round up"; // untranslated Blockly.Msg["MATH_ROUND_TOOLTIP"] = "Round a number up or down."; // untranslated Blockly.Msg["MATH_SINGLE_HELPURL"] = "https://en.wikipedia.org/wiki/Square_root"; // untranslated Blockly.Msg["MATH_SINGLE_OP_ABSOLUTE"] = "مطلق"; Blockly.Msg["MATH_SINGLE_OP_ROOT"] = "مربعی جذر"; Blockly.Msg["MATH_SINGLE_TOOLTIP_ABS"] = "Return the absolute value of a number."; // untranslated Blockly.Msg["MATH_SINGLE_TOOLTIP_EXP"] = "Return e to the power of a number."; // untranslated Blockly.Msg["MATH_SINGLE_TOOLTIP_LN"] = "Return the natural logarithm of a number."; // untranslated Blockly.Msg["MATH_SINGLE_TOOLTIP_LOG10"] = "Return the base 10 logarithm of a number."; // untranslated Blockly.Msg["MATH_SINGLE_TOOLTIP_NEG"] = "Return the negation of a number."; // untranslated Blockly.Msg["MATH_SINGLE_TOOLTIP_POW10"] = "Return 10 to the power of a number."; // untranslated Blockly.Msg["MATH_SINGLE_TOOLTIP_ROOT"] = "Return the square root of a number."; // untranslated Blockly.Msg["MATH_SUBTRACTION_SYMBOL"] = "-"; // untranslated Blockly.Msg["MATH_TRIG_ACOS"] = "acos"; // untranslated Blockly.Msg["MATH_TRIG_ASIN"] = "asin"; // untranslated Blockly.Msg["MATH_TRIG_ATAN"] = "atan"; // untranslated Blockly.Msg["MATH_TRIG_COS"] = "cos"; // untranslated Blockly.Msg["MATH_TRIG_HELPURL"] = "https://en.wikipedia.org/wiki/Trigonometric_functions"; // untranslated Blockly.Msg["MATH_TRIG_SIN"] = "sin"; // untranslated Blockly.Msg["MATH_TRIG_TAN"] = "tan"; // untranslated Blockly.Msg["MATH_TRIG_TOOLTIP_ACOS"] = "Return the arccosine of a number."; // untranslated Blockly.Msg["MATH_TRIG_TOOLTIP_ASIN"] = "Return the arcsine of a number."; // untranslated Blockly.Msg["MATH_TRIG_TOOLTIP_ATAN"] = "Return the arctangent of a number."; // untranslated Blockly.Msg["MATH_TRIG_TOOLTIP_COS"] = "Return the cosine of a degree (not radian)."; // untranslated Blockly.Msg["MATH_TRIG_TOOLTIP_SIN"] = "Return the sine of a degree (not radian)."; // untranslated Blockly.Msg["MATH_TRIG_TOOLTIP_TAN"] = "Return the tangent of a degree (not radian)."; // untranslated Blockly.Msg["NEW_COLOUR_VARIABLE"] = "Create colour variable..."; // untranslated Blockly.Msg["NEW_NUMBER_VARIABLE"] = "Create number variable..."; // untranslated Blockly.Msg["NEW_STRING_VARIABLE"] = "Create string variable..."; // untranslated Blockly.Msg["NEW_VARIABLE"] = "متغیر بݨاؤ۔۔۔"; Blockly.Msg["NEW_VARIABLE_TITLE"] = "نواں متغیر ناں:"; Blockly.Msg["NEW_VARIABLE_TYPE_TITLE"] = "New variable type:"; // untranslated Blockly.Msg["ORDINAL_NUMBER_SUFFIX"] = ""; // untranslated Blockly.Msg["PROCEDURES_ALLOW_STATEMENTS"] = "allow statements"; // untranslated Blockly.Msg["PROCEDURES_BEFORE_PARAMS"] = "نال:"; Blockly.Msg["PROCEDURES_CALLNORETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated Blockly.Msg["PROCEDURES_CALLNORETURN_TOOLTIP"] = "Run the user-defined function '%1'."; // untranslated Blockly.Msg["PROCEDURES_CALLRETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated Blockly.Msg["PROCEDURES_CALLRETURN_TOOLTIP"] = "Run the user-defined function '%1' and use its output."; // untranslated Blockly.Msg["PROCEDURES_CALL_BEFORE_PARAMS"] = "نال:"; Blockly.Msg["PROCEDURES_CREATE_DO"] = "Create '%1'"; // untranslated Blockly.Msg["PROCEDURES_DEFNORETURN_COMMENT"] = "Describe this function..."; // untranslated Blockly.Msg["PROCEDURES_DEFNORETURN_DO"] = ""; // untranslated Blockly.Msg["PROCEDURES_DEFNORETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated Blockly.Msg["PROCEDURES_DEFNORETURN_PROCEDURE"] = "do something"; // untranslated Blockly.Msg["PROCEDURES_DEFNORETURN_TITLE"] = "کوں"; Blockly.Msg["PROCEDURES_DEFNORETURN_TOOLTIP"] = "Creates a function with no output."; // untranslated Blockly.Msg["PROCEDURES_DEFRETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated Blockly.Msg["PROCEDURES_DEFRETURN_RETURN"] = "واپس آ ونڄو"; Blockly.Msg["PROCEDURES_DEFRETURN_TOOLTIP"] = "Creates a function with an output."; // untranslated Blockly.Msg["PROCEDURES_DEF_DUPLICATE_WARNING"] = "Warning: This function has duplicate parameters."; // untranslated Blockly.Msg["PROCEDURES_HIGHLIGHT_DEF"] = "Highlight function definition"; // untranslated Blockly.Msg["PROCEDURES_IFRETURN_HELPURL"] = "http://c2.com/cgi/wiki?GuardClause"; // untranslated Blockly.Msg["PROCEDURES_IFRETURN_TOOLTIP"] = "If a value is true, then return a second value."; // untranslated Blockly.Msg["PROCEDURES_IFRETURN_WARNING"] = "Warning: This block may be used only within a function definition."; // untranslated Blockly.Msg["PROCEDURES_MUTATORARG_TITLE"] = "ان پُٹ ناں:"; Blockly.Msg["PROCEDURES_MUTATORARG_TOOLTIP"] = "Add an input to the function."; // untranslated Blockly.Msg["PROCEDURES_MUTATORCONTAINER_TITLE"] = "inputs"; // untranslated Blockly.Msg["PROCEDURES_MUTATORCONTAINER_TOOLTIP"] = "Add, remove, or reorder inputs to this function."; // untranslated Blockly.Msg["REDO"] = "ولدا کرو"; Blockly.Msg["REMOVE_COMMENT"] = "رائے مٹاؤ"; Blockly.Msg["RENAME_VARIABLE"] = "متغیر دا ولدا ناں رکھو۔۔۔"; Blockly.Msg["RENAME_VARIABLE_TITLE"] = "Rename all '%1' variables to:"; // untranslated Blockly.Msg["TEXT_APPEND_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated Blockly.Msg["TEXT_APPEND_TITLE"] = "to %1 append text %2"; // untranslated Blockly.Msg["TEXT_APPEND_TOOLTIP"] = "Append some text to variable '%1'."; // untranslated Blockly.Msg["TEXT_CHANGECASE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; // untranslated Blockly.Msg["TEXT_CHANGECASE_OPERATOR_LOWERCASE"] = "to lower case"; // untranslated Blockly.Msg["TEXT_CHANGECASE_OPERATOR_TITLECASE"] = "to Title Case"; // untranslated Blockly.Msg["TEXT_CHANGECASE_OPERATOR_UPPERCASE"] = "to UPPER CASE"; // untranslated Blockly.Msg["TEXT_CHANGECASE_TOOLTIP"] = "Return a copy of the text in a different case."; // untranslated Blockly.Msg["TEXT_CHARAT_FIRST"] = "پہلا حرف گھنو"; Blockly.Msg["TEXT_CHARAT_FROM_END"] = "get letter # from end"; // untranslated Blockly.Msg["TEXT_CHARAT_FROM_START"] = "# حرف گھنو"; Blockly.Msg["TEXT_CHARAT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#extracting-text"; // untranslated Blockly.Msg["TEXT_CHARAT_LAST"] = "چھیکڑی حرف گھنو"; Blockly.Msg["TEXT_CHARAT_RANDOM"] = "get random letter"; // untranslated Blockly.Msg["TEXT_CHARAT_TAIL"] = ""; // untranslated Blockly.Msg["TEXT_CHARAT_TITLE"] = "in text %1 %2"; // untranslated Blockly.Msg["TEXT_CHARAT_TOOLTIP"] = "Returns the letter at the specified position."; // untranslated Blockly.Msg["TEXT_COUNT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#counting-substrings"; // untranslated Blockly.Msg["TEXT_COUNT_MESSAGE0"] = "count %1 in %2"; // untranslated Blockly.Msg["TEXT_COUNT_TOOLTIP"] = "Count how many times some text occurs within some other text."; // untranslated Blockly.Msg["TEXT_CREATE_JOIN_ITEM_TOOLTIP"] = "Add an item to the text."; // untranslated Blockly.Msg["TEXT_CREATE_JOIN_TITLE_JOIN"] = "شامل تھیوو"; Blockly.Msg["TEXT_CREATE_JOIN_TOOLTIP"] = "Add, remove, or reorder sections to reconfigure this text block."; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_END_FROM_END"] = "to letter # from end"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_END_FROM_START"] = "to letter #"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_END_LAST"] = "to last letter"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_HELPURL"] = "https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_INPUT_IN_TEXT"] = "ٹیکسٹ وچ"; Blockly.Msg["TEXT_GET_SUBSTRING_START_FIRST"] = "get substring from first letter"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_START_FROM_END"] = "get substring from letter # from end"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_START_FROM_START"] = "get substring from letter #"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_TAIL"] = ""; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_TOOLTIP"] = "Returns a specified portion of the text."; // untranslated Blockly.Msg["TEXT_INDEXOF_HELPURL"] = "https://github.com/google/blockly/wiki/Text#finding-text"; // untranslated Blockly.Msg["TEXT_INDEXOF_OPERATOR_FIRST"] = "find first occurrence of text"; // untranslated Blockly.Msg["TEXT_INDEXOF_OPERATOR_LAST"] = "find last occurrence of text"; // untranslated Blockly.Msg["TEXT_INDEXOF_TITLE"] = "in text %1 %2 %3"; // untranslated Blockly.Msg["TEXT_INDEXOF_TOOLTIP"] = "Returns the index of the first/last occurrence of the first text in the second text. Returns %1 if text is not found."; // untranslated Blockly.Msg["TEXT_ISEMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; // untranslated Blockly.Msg["TEXT_ISEMPTY_TITLE"] = "%1 خالی ہے"; Blockly.Msg["TEXT_ISEMPTY_TOOLTIP"] = "Returns true if the provided text is empty."; // untranslated Blockly.Msg["TEXT_JOIN_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-creation"; // untranslated Blockly.Msg["TEXT_JOIN_TITLE_CREATEWITH"] = "create text with"; // untranslated Blockly.Msg["TEXT_JOIN_TOOLTIP"] = "Create a piece of text by joining together any number of items."; // untranslated Blockly.Msg["TEXT_LENGTH_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated Blockly.Msg["TEXT_LENGTH_TITLE"] = "%1 دی لمباݨ"; Blockly.Msg["TEXT_LENGTH_TOOLTIP"] = "Returns the number of letters (including spaces) in the provided text."; // untranslated Blockly.Msg["TEXT_PRINT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#printing-text"; // untranslated Blockly.Msg["TEXT_PRINT_TITLE"] = "%1 چھاپو"; Blockly.Msg["TEXT_PRINT_TOOLTIP"] = "Print the specified text, number or other value."; // untranslated Blockly.Msg["TEXT_PROMPT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; // untranslated Blockly.Msg["TEXT_PROMPT_TOOLTIP_NUMBER"] = "Prompt for user for a number."; // untranslated Blockly.Msg["TEXT_PROMPT_TOOLTIP_TEXT"] = "Prompt for user for some text."; // untranslated Blockly.Msg["TEXT_PROMPT_TYPE_NUMBER"] = "prompt for number with message"; // untranslated Blockly.Msg["TEXT_PROMPT_TYPE_TEXT"] = "prompt for text with message"; // untranslated Blockly.Msg["TEXT_REPLACE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#replacing-substrings"; // untranslated Blockly.Msg["TEXT_REPLACE_MESSAGE0"] = "replace %1 with %2 in %3"; // untranslated Blockly.Msg["TEXT_REPLACE_TOOLTIP"] = "Replace all occurances of some text within some other text."; // untranslated Blockly.Msg["TEXT_REVERSE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#reversing-text"; // untranslated Blockly.Msg["TEXT_REVERSE_MESSAGE0"] = "reverse %1"; // untranslated Blockly.Msg["TEXT_REVERSE_TOOLTIP"] = "Reverses the order of the characters in the text."; // untranslated Blockly.Msg["TEXT_TEXT_HELPURL"] = "https://en.wikipedia.org/wiki/String_(computer_science)"; // untranslated Blockly.Msg["TEXT_TEXT_TOOLTIP"] = "A letter, word, or line of text."; // untranslated Blockly.Msg["TEXT_TRIM_HELPURL"] = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; // untranslated Blockly.Msg["TEXT_TRIM_OPERATOR_BOTH"] = "trim spaces from both sides of"; // untranslated Blockly.Msg["TEXT_TRIM_OPERATOR_LEFT"] = "trim spaces from left side of"; // untranslated Blockly.Msg["TEXT_TRIM_OPERATOR_RIGHT"] = "trim spaces from right side of"; // untranslated Blockly.Msg["TEXT_TRIM_TOOLTIP"] = "Return a copy of the text with spaces removed from one or both ends."; // untranslated Blockly.Msg["TODAY"] = "اڄ"; Blockly.Msg["UNDO"] = "واپس"; Blockly.Msg["UNNAMED_KEY"] = "unnamed"; // untranslated Blockly.Msg["VARIABLES_DEFAULT_NAME"] = "آئٹم"; Blockly.Msg["VARIABLES_GET_CREATE_SET"] = "Create 'set %1'"; // untranslated Blockly.Msg["VARIABLES_GET_HELPURL"] = "https://github.com/google/blockly/wiki/Variables#get"; // untranslated Blockly.Msg["VARIABLES_GET_TOOLTIP"] = "Returns the value of this variable."; // untranslated Blockly.Msg["VARIABLES_SET"] = "set %1 to %2"; // untranslated Blockly.Msg["VARIABLES_SET_CREATE_GET"] = "Create 'get %1'"; // untranslated Blockly.Msg["VARIABLES_SET_HELPURL"] = "https://github.com/google/blockly/wiki/Variables#set"; // untranslated Blockly.Msg["VARIABLES_SET_TOOLTIP"] = "Sets this variable to be equal to the input."; // untranslated Blockly.Msg["VARIABLE_ALREADY_EXISTS"] = "'%1' نامی متغیر پہلے موجود ہے۔"; Blockly.Msg["VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE"] = "A variable named '%1' already exists for another type: '%2'."; // untranslated Blockly.Msg["WORKSPACE_ARIA_LABEL"] = "Blockly Workspace"; // untranslated Blockly.Msg["WORKSPACE_COMMENT_DEFAULT_TEXT"] = "Say something..."; // untranslated Blockly.Msg["CONTROLS_FOREACH_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["CONTROLS_FOR_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["CONTROLS_IF_ELSEIF_TITLE_ELSEIF"] = Blockly.Msg["CONTROLS_IF_MSG_ELSEIF"]; Blockly.Msg["CONTROLS_IF_ELSE_TITLE_ELSE"] = Blockly.Msg["CONTROLS_IF_MSG_ELSE"]; Blockly.Msg["CONTROLS_IF_IF_TITLE_IF"] = Blockly.Msg["CONTROLS_IF_MSG_IF"]; Blockly.Msg["CONTROLS_IF_MSG_THEN"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["CONTROLS_WHILEUNTIL_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["LISTS_CREATE_WITH_ITEM_TITLE"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["LISTS_GET_INDEX_HELPURL"] = Blockly.Msg["LISTS_INDEX_OF_HELPURL"]; Blockly.Msg["LISTS_GET_INDEX_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["LISTS_GET_SUBLIST_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["LISTS_INDEX_OF_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["LISTS_SET_INDEX_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["MATH_CHANGE_TITLE_ITEM"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["PROCEDURES_DEFRETURN_COMMENT"] = Blockly.Msg["PROCEDURES_DEFNORETURN_COMMENT"]; Blockly.Msg["PROCEDURES_DEFRETURN_DO"] = Blockly.Msg["PROCEDURES_DEFNORETURN_DO"]; Blockly.Msg["PROCEDURES_DEFRETURN_PROCEDURE"] = Blockly.Msg["PROCEDURES_DEFNORETURN_PROCEDURE"]; Blockly.Msg["PROCEDURES_DEFRETURN_TITLE"] = Blockly.Msg["PROCEDURES_DEFNORETURN_TITLE"]; Blockly.Msg["TEXT_APPEND_VARIABLE"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["TEXT_CREATE_JOIN_ITEM_TITLE_ITEM"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["MATH_HUE"] = "230"; Blockly.Msg["LOOPS_HUE"] = "120"; Blockly.Msg["LISTS_HUE"] = "260"; Blockly.Msg["LOGIC_HUE"] = "210"; Blockly.Msg["VARIABLES_HUE"] = "330"; Blockly.Msg["TEXTS_HUE"] = "160"; Blockly.Msg["PROCEDURES_HUE"] = "290"; Blockly.Msg["COLOUR_HUE"] = "20"; Blockly.Msg["VARIABLES_DYNAMIC_HUE"] = "310"; return Blockly.Msg; }));
"use strict";function easeInOutSin(n){return(1+Math.sin(Math.PI*n-Math.PI/2))/2}function animate(t,i,a){var n=3<arguments.length&&void 0!==arguments[3]?arguments[3]:{},r=4<arguments.length&&void 0!==arguments[4]?arguments[4]:function(){},e=n.ease,o=void 0===e?easeInOutSin:e,e=n.duration,u=void 0===e?300:e,l=null,s=i[t],m=!1,n=function(){m=!0},e=function n(e){m?r(new Error("Animation cancelled")):(null===l&&(l=e),e=Math.min(1,(e-l)/u),i[t]=o(e)*(a-s)+s,1<=e?requestAnimationFrame(function(){r(null)}):requestAnimationFrame(n))};return s===a?r(new Error("Element already at target position")):requestAnimationFrame(e),n}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=animate;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var turnOrder=require("./turn-order-9099d084.js");require("immer"),require("lodash.isplainobject");const PlayerView={STRIP_SECRETS:(e,r,t)=>{const s={...e};return void 0!==s.secret&&delete s.secret,s.players&&(s.players=t?{[t]:s.players[t]}:{}),s}};exports.ActivePlayers=turnOrder.ActivePlayers,Object.defineProperty(exports,"GameMethod",{enumerable:!0,get:function(){return turnOrder.GameMethod}}),exports.INVALID_MOVE=turnOrder.INVALID_MOVE,exports.Stage=turnOrder.Stage,exports.TurnOrder=turnOrder.TurnOrder,exports.PlayerView=PlayerView;
define("ace/snippets/ruby",["require","exports","module"], function(require, exports, module) { "use strict"; exports.snippetText = "########################################\n\ # Ruby snippets - for Rails, see below #\n\ ########################################\n\ \n\ # encoding for Ruby 1.9\n\ snippet enc\n\ # encoding: utf-8\n\ \n\ # #!/usr/bin/env ruby\n\ snippet #!\n\ #!/usr/bin/env ruby\n\ # encoding: utf-8\n\ \n\ # New Block\n\ snippet =b\n\ =begin rdoc\n\ ${1}\n\ =end\n\ snippet y\n\ :yields: ${1:arguments}\n\ snippet rb\n\ #!/usr/bin/env ruby -wKU\n\ snippet beg\n\ begin\n\ ${3}\n\ rescue ${1:Exception} => ${2:e}\n\ end\n\ \n\ snippet req require\n\ require \"${1}\"${2}\n\ snippet #\n\ # =>\n\ snippet end\n\ __END__\n\ snippet case\n\ case ${1:object}\n\ when ${2:condition}\n\ ${3}\n\ end\n\ snippet when\n\ when ${1:condition}\n\ ${2}\n\ snippet def\n\ def ${1:method_name}\n\ ${2}\n\ end\n\ snippet deft\n\ def test_${1:case_name}\n\ ${2}\n\ end\n\ snippet if\n\ if ${1:condition}\n\ ${2}\n\ end\n\ snippet ife\n\ if ${1:condition}\n\ ${2}\n\ else\n\ ${3}\n\ end\n\ snippet elsif\n\ elsif ${1:condition}\n\ ${2}\n\ snippet unless\n\ unless ${1:condition}\n\ ${2}\n\ end\n\ snippet while\n\ while ${1:condition}\n\ ${2}\n\ end\n\ snippet for\n\ for ${1:e} in ${2:c}\n\ ${3}\n\ end\n\ snippet until\n\ until ${1:condition}\n\ ${2}\n\ end\n\ snippet cla class .. end\n\ class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`}\n\ ${2}\n\ end\n\ snippet cla class .. initialize .. end\n\ class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`}\n\ def initialize(${2:args})\n\ ${3}\n\ end\n\ end\n\ snippet cla class .. < ParentClass .. initialize .. end\n\ class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`} < ${2:ParentClass}\n\ def initialize(${3:args})\n\ ${4}\n\ end\n\ end\n\ snippet cla ClassName = Struct .. do .. end\n\ ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`} = Struct.new(:${2:attr_names}) do\n\ def ${3:method_name}\n\ ${4}\n\ end\n\ end\n\ snippet cla class BlankSlate .. initialize .. end\n\ class ${1:BlankSlate}\n\ instance_methods.each { |meth| undef_method(meth) unless meth =~ /\\A__/ }\n\ end\n\ snippet cla class << self .. end\n\ class << ${1:self}\n\ ${2}\n\ end\n\ # class .. < DelegateClass .. initialize .. end\n\ snippet cla-\n\ class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`} < DelegateClass(${2:ParentClass})\n\ def initialize(${3:args})\n\ super(${4:del_obj})\n\ \n\ ${5}\n\ end\n\ end\n\ snippet mod module .. end\n\ module ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`}\n\ ${2}\n\ end\n\ snippet mod module .. module_function .. end\n\ module ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`}\n\ module_function\n\ \n\ ${2}\n\ end\n\ snippet mod module .. ClassMethods .. end\n\ module ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`}\n\ module ClassMethods\n\ ${2}\n\ end\n\ \n\ module InstanceMethods\n\ \n\ end\n\ \n\ def self.included(receiver)\n\ receiver.extend ClassMethods\n\ receiver.send :include, InstanceMethods\n\ end\n\ end\n\ # attr_reader\n\ snippet r\n\ attr_reader :${1:attr_names}\n\ # attr_writer\n\ snippet w\n\ attr_writer :${1:attr_names}\n\ # attr_accessor\n\ snippet rw\n\ attr_accessor :${1:attr_names}\n\ snippet atp\n\ attr_protected :${1:attr_names}\n\ snippet ata\n\ attr_accessible :${1:attr_names}\n\ # include Enumerable\n\ snippet Enum\n\ include Enumerable\n\ \n\ def each(&block)\n\ ${1}\n\ end\n\ # include Comparable\n\ snippet Comp\n\ include Comparable\n\ \n\ def <=>(other)\n\ ${1}\n\ end\n\ # extend Forwardable\n\ snippet Forw-\n\ extend Forwardable\n\ # def self\n\ snippet defs\n\ def self.${1:class_method_name}\n\ ${2}\n\ end\n\ # def method_missing\n\ snippet defmm\n\ def method_missing(meth, *args, &blk)\n\ ${1}\n\ end\n\ snippet defd\n\ def_delegator :${1:@del_obj}, :${2:del_meth}, :${3:new_name}\n\ snippet defds\n\ def_delegators :${1:@del_obj}, :${2:del_methods}\n\ snippet am\n\ alias_method :${1:new_name}, :${2:old_name}\n\ snippet app\n\ if __FILE__ == $PROGRAM_NAME\n\ ${1}\n\ end\n\ # usage_if()\n\ snippet usai\n\ if ARGV.${1}\n\ abort \"Usage: #{$PROGRAM_NAME} ${2:ARGS_GO_HERE}\"${3}\n\ end\n\ # usage_unless()\n\ snippet usau\n\ unless ARGV.${1}\n\ abort \"Usage: #{$PROGRAM_NAME} ${2:ARGS_GO_HERE}\"${3}\n\ end\n\ snippet array\n\ Array.new(${1:10}) { |${2:i}| ${3} }\n\ snippet hash\n\ Hash.new { |${1:hash}, ${2:key}| $1[$2] = ${3} }\n\ snippet file File.foreach() { |line| .. }\n\ File.foreach(${1:\"path/to/file\"}) { |${2:line}| ${3} }\n\ snippet file File.read()\n\ File.read(${1:\"path/to/file\"})${2}\n\ snippet Dir Dir.global() { |file| .. }\n\ Dir.glob(${1:\"dir/glob/*\"}) { |${2:file}| ${3} }\n\ snippet Dir Dir[\"..\"]\n\ Dir[${1:\"glob/**/*.rb\"}]${2}\n\ snippet dir\n\ Filename.dirname(__FILE__)\n\ snippet deli\n\ delete_if { |${1:e}| ${2} }\n\ snippet fil\n\ fill(${1:range}) { |${2:i}| ${3} }\n\ # flatten_once()\n\ snippet flao\n\ inject(Array.new) { |${1:arr}, ${2:a}| $1.push(*$2)}${3}\n\ snippet zip\n\ zip(${1:enums}) { |${2:row}| ${3} }\n\ # downto(0) { |n| .. }\n\ snippet dow\n\ downto(${1:0}) { |${2:n}| ${3} }\n\ snippet ste\n\ step(${1:2}) { |${2:n}| ${3} }\n\ snippet tim\n\ times { |${1:n}| ${2} }\n\ snippet upt\n\ upto(${1:1.0/0.0}) { |${2:n}| ${3} }\n\ snippet loo\n\ loop { ${1} }\n\ snippet ea\n\ each { |${1:e}| ${2} }\n\ snippet ead\n\ each do |${1:e}|\n\ ${2}\n\ end\n\ snippet eab\n\ each_byte { |${1:byte}| ${2} }\n\ snippet eac- each_char { |chr| .. }\n\ each_char { |${1:chr}| ${2} }\n\ snippet eac- each_cons(..) { |group| .. }\n\ each_cons(${1:2}) { |${2:group}| ${3} }\n\ snippet eai\n\ each_index { |${1:i}| ${2} }\n\ snippet eaid\n\ each_index do |${1:i}|\n\ ${2}\n\ end\n\ snippet eak\n\ each_key { |${1:key}| ${2} }\n\ snippet eakd\n\ each_key do |${1:key}|\n\ ${2}\n\ end\n\ snippet eal\n\ each_line { |${1:line}| ${2} }\n\ snippet eald\n\ each_line do |${1:line}|\n\ ${2}\n\ end\n\ snippet eap\n\ each_pair { |${1:name}, ${2:val}| ${3} }\n\ snippet eapd\n\ each_pair do |${1:name}, ${2:val}|\n\ ${3}\n\ end\n\ snippet eas-\n\ each_slice(${1:2}) { |${2:group}| ${3} }\n\ snippet easd-\n\ each_slice(${1:2}) do |${2:group}|\n\ ${3}\n\ end\n\ snippet eav\n\ each_value { |${1:val}| ${2} }\n\ snippet eavd\n\ each_value do |${1:val}|\n\ ${2}\n\ end\n\ snippet eawi\n\ each_with_index { |${1:e}, ${2:i}| ${3} }\n\ snippet eawid\n\ each_with_index do |${1:e},${2:i}|\n\ ${3}\n\ end\n\ snippet reve\n\ reverse_each { |${1:e}| ${2} }\n\ snippet reved\n\ reverse_each do |${1:e}|\n\ ${2}\n\ end\n\ snippet inj\n\ inject(${1:init}) { |${2:mem}, ${3:var}| ${4} }\n\ snippet injd\n\ inject(${1:init}) do |${2:mem}, ${3:var}|\n\ ${4}\n\ end\n\ snippet map\n\ map { |${1:e}| ${2} }\n\ snippet mapd\n\ map do |${1:e}|\n\ ${2}\n\ end\n\ snippet mapwi-\n\ enum_with_index.map { |${1:e}, ${2:i}| ${3} }\n\ snippet sor\n\ sort { |a, b| ${1} }\n\ snippet sorb\n\ sort_by { |${1:e}| ${2} }\n\ snippet ran\n\ sort_by { rand }\n\ snippet all\n\ all? { |${1:e}| ${2} }\n\ snippet any\n\ any? { |${1:e}| ${2} }\n\ snippet cl\n\ classify { |${1:e}| ${2} }\n\ snippet col\n\ collect { |${1:e}| ${2} }\n\ snippet cold\n\ collect do |${1:e}|\n\ ${2}\n\ end\n\ snippet det\n\ detect { |${1:e}| ${2} }\n\ snippet detd\n\ detect do |${1:e}|\n\ ${2}\n\ end\n\ snippet fet\n\ fetch(${1:name}) { |${2:key}| ${3} }\n\ snippet fin\n\ find { |${1:e}| ${2} }\n\ snippet find\n\ find do |${1:e}|\n\ ${2}\n\ end\n\ snippet fina\n\ find_all { |${1:e}| ${2} }\n\ snippet finad\n\ find_all do |${1:e}|\n\ ${2}\n\ end\n\ snippet gre\n\ grep(${1:/pattern/}) { |${2:match}| ${3} }\n\ snippet sub\n\ ${1:g}sub(${2:/pattern/}) { |${3:match}| ${4} }\n\ snippet sca\n\ scan(${1:/pattern/}) { |${2:match}| ${3} }\n\ snippet scad\n\ scan(${1:/pattern/}) do |${2:match}|\n\ ${3}\n\ end\n\ snippet max\n\ max { |a, b| ${1} }\n\ snippet min\n\ min { |a, b| ${1} }\n\ snippet par\n\ partition { |${1:e}| ${2} }\n\ snippet pard\n\ partition do |${1:e}|\n\ ${2}\n\ end\n\ snippet rej\n\ reject { |${1:e}| ${2} }\n\ snippet rejd\n\ reject do |${1:e}|\n\ ${2}\n\ end\n\ snippet sel\n\ select { |${1:e}| ${2} }\n\ snippet seld\n\ select do |${1:e}|\n\ ${2}\n\ end\n\ snippet lam\n\ lambda { |${1:args}| ${2} }\n\ snippet doo\n\ do\n\ ${1}\n\ end\n\ snippet dov\n\ do |${1:variable}|\n\ ${2}\n\ end\n\ snippet :\n\ :${1:key} => ${2:\"value\"}${3}\n\ snippet ope\n\ open(${1:\"path/or/url/or/pipe\"}, \"${2:w}\") { |${3:io}| ${4} }\n\ # path_from_here()\n\ snippet fpath\n\ File.join(File.dirname(__FILE__), *%2[${1:rel path here}])${2}\n\ # unix_filter {}\n\ snippet unif\n\ ARGF.each_line${1} do |${2:line}|\n\ ${3}\n\ end\n\ # option_parse {}\n\ snippet optp\n\ require \"optparse\"\n\ \n\ options = {${1:default => \"args\"}}\n\ \n\ ARGV.options do |opts|\n\ opts.banner = \"Usage: #{File.basename($PROGRAM_NAME)}\n\ snippet opt\n\ opts.on( \"-${1:o}\", \"--${2:long-option-name}\", ${3:String},\n\ \"${4:Option description.}\") do |${5:opt}|\n\ ${6}\n\ end\n\ snippet tc\n\ require \"test/unit\"\n\ \n\ require \"${1:library_file_name}\"\n\ \n\ class Test${2:$1} < Test::Unit::TestCase\n\ def test_${3:case_name}\n\ ${4}\n\ end\n\ end\n\ snippet ts\n\ require \"test/unit\"\n\ \n\ require \"tc_${1:test_case_file}\"\n\ require \"tc_${2:test_case_file}\"${3}\n\ snippet as\n\ assert ${1:test}, \"${2:Failure message.}\"${3}\n\ snippet ase\n\ assert_equal ${1:expected}, ${2:actual}${3}\n\ snippet asne\n\ assert_not_equal ${1:unexpected}, ${2:actual}${3}\n\ snippet asid\n\ assert_in_delta ${1:expected_float}, ${2:actual_float}, ${3:2 ** -20}${4}\n\ snippet asio\n\ assert_instance_of ${1:ExpectedClass}, ${2:actual_instance}${3}\n\ snippet asko\n\ assert_kind_of ${1:ExpectedKind}, ${2:actual_instance}${3}\n\ snippet asn\n\ assert_nil ${1:instance}${2}\n\ snippet asnn\n\ assert_not_nil ${1:instance}${2}\n\ snippet asm\n\ assert_match /${1:expected_pattern}/, ${2:actual_string}${3}\n\ snippet asnm\n\ assert_no_match /${1:unexpected_pattern}/, ${2:actual_string}${3}\n\ snippet aso\n\ assert_operator ${1:left}, :${2:operator}, ${3:right}${4}\n\ snippet asr\n\ assert_raise ${1:Exception} { ${2} }\n\ snippet asrd\n\ assert_raise ${1:Exception} do\n\ ${2}\n\ end\n\ snippet asnr\n\ assert_nothing_raised ${1:Exception} { ${2} }\n\ snippet asnrd\n\ assert_nothing_raised ${1:Exception} do\n\ ${2}\n\ end\n\ snippet asrt\n\ assert_respond_to ${1:object}, :${2:method}${3}\n\ snippet ass assert_same(..)\n\ assert_same ${1:expected}, ${2:actual}${3}\n\ snippet ass assert_send(..)\n\ assert_send [${1:object}, :${2:message}, ${3:args}]${4}\n\ snippet asns\n\ assert_not_same ${1:unexpected}, ${2:actual}${3}\n\ snippet ast\n\ assert_throws :${1:expected} { ${2} }\n\ snippet astd\n\ assert_throws :${1:expected} do\n\ ${2}\n\ end\n\ snippet asnt\n\ assert_nothing_thrown { ${1} }\n\ snippet asntd\n\ assert_nothing_thrown do\n\ ${1}\n\ end\n\ snippet fl\n\ flunk \"${1:Failure message.}\"${2}\n\ # Benchmark.bmbm do .. end\n\ snippet bm-\n\ TESTS = ${1:10_000}\n\ Benchmark.bmbm do |results|\n\ ${2}\n\ end\n\ snippet rep\n\ results.report(\"${1:name}:\") { TESTS.times { ${2} }}\n\ # Marshal.dump(.., file)\n\ snippet Md\n\ File.open(${1:\"path/to/file.dump\"}, \"wb\") { |${2:file}| Marshal.dump(${3:obj}, $2) }${4}\n\ # Mashal.load(obj)\n\ snippet Ml\n\ File.open(${1:\"path/to/file.dump\"}, \"rb\") { |${2:file}| Marshal.load($2) }${3}\n\ # deep_copy(..)\n\ snippet deec\n\ Marshal.load(Marshal.dump(${1:obj_to_copy}))${2}\n\ snippet Pn-\n\ PStore.new(${1:\"file_name.pstore\"})${2}\n\ snippet tra\n\ transaction(${1:true}) { ${2} }\n\ # xmlread(..)\n\ snippet xml-\n\ REXML::Document.new(File.read(${1:\"path/to/file\"}))${2}\n\ # xpath(..) { .. }\n\ snippet xpa\n\ elements.each(${1:\"//Xpath\"}) do |${2:node}|\n\ ${3}\n\ end\n\ # class_from_name()\n\ snippet clafn\n\ split(\"::\").inject(Object) { |par, const| par.const_get(const) }\n\ # singleton_class()\n\ snippet sinc\n\ class << self; self end\n\ snippet nam\n\ namespace :${1:`Filename()`} do\n\ ${2}\n\ end\n\ snippet tas\n\ desc \"${1:Task description}\"\n\ task :${2:task_name => [:dependent, :tasks]} do\n\ ${3}\n\ end\n\ # block\n\ snippet b\n\ { |${1:var}| ${2} }\n\ snippet begin\n\ begin\n\ raise 'A test exception.'\n\ rescue Exception => e\n\ puts e.message\n\ puts e.backtrace.inspect\n\ else\n\ # other exception\n\ ensure\n\ # always executed\n\ end\n\ \n\ #debugging\n\ snippet debug\n\ require 'ruby-debug'; debugger; true;\n\ snippet pry\n\ require 'pry'; binding.pry\n\ \n\ #############################################\n\ # Rails snippets - for pure Ruby, see above #\n\ #############################################\n\ snippet art\n\ assert_redirected_to ${1::action => \"${2:index}\"}\n\ snippet artnp\n\ assert_redirected_to ${1:parent}_${2:child}_path(${3:@$1}, ${4:@$2})\n\ snippet artnpp\n\ assert_redirected_to ${1:parent}_${2:child}_path(${3:@$1})\n\ snippet artp\n\ assert_redirected_to ${1:model}_path(${2:@$1})\n\ snippet artpp\n\ assert_redirected_to ${1:model}s_path\n\ snippet asd\n\ assert_difference \"${1:Model}.${2:count}\", $1 do\n\ ${3}\n\ end\n\ snippet asnd\n\ assert_no_difference \"${1:Model}.${2:count}\" do\n\ ${3}\n\ end\n\ snippet asre\n\ assert_response :${1:success}, @response.body${2}\n\ snippet asrj\n\ assert_rjs :${1:replace}, \"${2:dom id}\"\n\ snippet ass assert_select(..)\n\ assert_select '${1:path}', :${2:text} => '${3:inner_html' ${4:do}\n\ snippet bf\n\ before_filter :${1:method}\n\ snippet bt\n\ belongs_to :${1:association}\n\ snippet crw\n\ cattr_accessor :${1:attr_names}\n\ snippet defcreate\n\ def create\n\ @${1:model_class_name} = ${2:ModelClassName}.new(params[:$1])\n\ \n\ respond_to do |wants|\n\ if @$1.save\n\ flash[:notice] = '$2 was successfully created.'\n\ wants.html { redirect_to(@$1) }\n\ wants.xml { render :xml => @$1, :status => :created, :location => @$1 }\n\ else\n\ wants.html { render :action => \"new\" }\n\ wants.xml { render :xml => @$1.errors, :status => :unprocessable_entity }\n\ end\n\ end\n\ end${3}\n\ snippet defdestroy\n\ def destroy\n\ @${1:model_class_name} = ${2:ModelClassName}.find(params[:id])\n\ @$1.destroy\n\ \n\ respond_to do |wants|\n\ wants.html { redirect_to($1s_url) }\n\ wants.xml { head :ok }\n\ end\n\ end${3}\n\ snippet defedit\n\ def edit\n\ @${1:model_class_name} = ${2:ModelClassName}.find(params[:id])\n\ end\n\ snippet defindex\n\ def index\n\ @${1:model_class_name} = ${2:ModelClassName}.all\n\ \n\ respond_to do |wants|\n\ wants.html # index.html.erb\n\ wants.xml { render :xml => @$1s }\n\ end\n\ end${3}\n\ snippet defnew\n\ def new\n\ @${1:model_class_name} = ${2:ModelClassName}.new\n\ \n\ respond_to do |wants|\n\ wants.html # new.html.erb\n\ wants.xml { render :xml => @$1 }\n\ end\n\ end${3}\n\ snippet defshow\n\ def show\n\ @${1:model_class_name} = ${2:ModelClassName}.find(params[:id])\n\ \n\ respond_to do |wants|\n\ wants.html # show.html.erb\n\ wants.xml { render :xml => @$1 }\n\ end\n\ end${3}\n\ snippet defupdate\n\ def update\n\ @${1:model_class_name} = ${2:ModelClassName}.find(params[:id])\n\ \n\ respond_to do |wants|\n\ if @$1.update_attributes(params[:$1])\n\ flash[:notice] = '$2 was successfully updated.'\n\ wants.html { redirect_to(@$1) }\n\ wants.xml { head :ok }\n\ else\n\ wants.html { render :action => \"edit\" }\n\ wants.xml { render :xml => @$1.errors, :status => :unprocessable_entity }\n\ end\n\ end\n\ end${3}\n\ snippet flash\n\ flash[:${1:notice}] = \"${2}\"\n\ snippet habtm\n\ has_and_belongs_to_many :${1:object}, :join_table => \"${2:table_name}\", :foreign_key => \"${3}_id\"${4}\n\ snippet hm\n\ has_many :${1:object}\n\ snippet hmd\n\ has_many :${1:other}s, :class_name => \"${2:$1}\", :foreign_key => \"${3:$1}_id\", :dependent => :destroy${4}\n\ snippet hmt\n\ has_many :${1:object}, :through => :${2:object}\n\ snippet ho\n\ has_one :${1:object}\n\ snippet i18\n\ I18n.t('${1:type.key}')${2}\n\ snippet ist\n\ <%= image_submit_tag(\"${1:agree.png}\", :id => \"${2:id}\"${3} %>\n\ snippet log\n\ Rails.logger.${1:debug} ${2}\n\ snippet log2\n\ RAILS_DEFAULT_LOGGER.${1:debug} ${2}\n\ snippet logd\n\ logger.debug { \"${1:message}\" }${2}\n\ snippet loge\n\ logger.error { \"${1:message}\" }${2}\n\ snippet logf\n\ logger.fatal { \"${1:message}\" }${2}\n\ snippet logi\n\ logger.info { \"${1:message}\" }${2}\n\ snippet logw\n\ logger.warn { \"${1:message}\" }${2}\n\ snippet mapc\n\ ${1:map}.${2:connect} '${3:controller/:action/:id}'\n\ snippet mapca\n\ ${1:map}.catch_all \"*${2:anything}\", :controller => \"${3:default}\", :action => \"${4:error}\"${5}\n\ snippet mapr\n\ ${1:map}.resource :${2:resource}\n\ snippet maprs\n\ ${1:map}.resources :${2:resource}\n\ snippet mapwo\n\ ${1:map}.with_options :${2:controller} => '${3:thing}' do |$3|\n\ ${4}\n\ end\n\ snippet mbs\n\ before_save :${1:method}\n\ snippet mcht\n\ change_table :${1:table_name} do |t|\n\ ${2}\n\ end\n\ snippet mp\n\ map(&:${1:id})\n\ snippet mrw\n\ mattr_accessor :${1:attr_names}\n\ snippet oa\n\ order(\"${1:field}\")\n\ snippet od\n\ order(\"${1:field} DESC\")\n\ snippet pa\n\ params[:${1:id}]${2}\n\ snippet ra\n\ render :action => \"${1:action}\"\n\ snippet ral\n\ render :action => \"${1:action}\", :layout => \"${2:layoutname}\"\n\ snippet rest\n\ respond_to do |wants|\n\ wants.${1:html} { ${2} }\n\ end\n\ snippet rf\n\ render :file => \"${1:filepath}\"\n\ snippet rfu\n\ render :file => \"${1:filepath}\", :use_full_path => ${2:false}\n\ snippet ri\n\ render :inline => \"${1:<%= 'hello' %>}\"\n\ snippet ril\n\ render :inline => \"${1:<%= 'hello' %>}\", :locals => { ${2::name} => \"${3:value}\"${4} }\n\ snippet rit\n\ render :inline => \"${1:<%= 'hello' %>}\", :type => ${2::rxml}\n\ snippet rjson\n\ render :json => ${1:text to render}\n\ snippet rl\n\ render :layout => \"${1:layoutname}\"\n\ snippet rn\n\ render :nothing => ${1:true}\n\ snippet rns\n\ render :nothing => ${1:true}, :status => ${2:401}\n\ snippet rp\n\ render :partial => \"${1:item}\"\n\ snippet rpc\n\ render :partial => \"${1:item}\", :collection => ${2:@$1s}\n\ snippet rpl\n\ render :partial => \"${1:item}\", :locals => { :${2:$1} => ${3:@$1}\n\ snippet rpo\n\ render :partial => \"${1:item}\", :object => ${2:@$1}\n\ snippet rps\n\ render :partial => \"${1:item}\", :status => ${2:500}\n\ snippet rt\n\ render :text => \"${1:text to render}\"\n\ snippet rtl\n\ render :text => \"${1:text to render}\", :layout => \"${2:layoutname}\"\n\ snippet rtlt\n\ render :text => \"${1:text to render}\", :layout => ${2:true}\n\ snippet rts\n\ render :text => \"${1:text to render}\", :status => ${2:401}\n\ snippet ru\n\ render :update do |${1:page}|\n\ $1.${2}\n\ end\n\ snippet rxml\n\ render :xml => ${1:text to render}\n\ snippet sc\n\ scope :${1:name}, :where(:@${2:field} => ${3:value})\n\ snippet sl\n\ scope :${1:name}, lambda do |${2:value}|\n\ where(\"${3:field = ?}\", ${4:bind var})\n\ end\n\ snippet sha1\n\ Digest::SHA1.hexdigest(${1:string})\n\ snippet sweeper\n\ class ${1:ModelClassName}Sweeper < ActionController::Caching::Sweeper\n\ observe $1\n\ \n\ def after_save(${2:model_class_name})\n\ expire_cache($2)\n\ end\n\ \n\ def after_destroy($2)\n\ expire_cache($2)\n\ end\n\ \n\ def expire_cache($2)\n\ expire_page\n\ end\n\ end\n\ snippet tcb\n\ t.boolean :${1:title}\n\ ${2}\n\ snippet tcbi\n\ t.binary :${1:title}, :limit => ${2:2}.megabytes\n\ ${3}\n\ snippet tcd\n\ t.decimal :${1:title}, :precision => ${2:10}, :scale => ${3:2}\n\ ${4}\n\ snippet tcda\n\ t.date :${1:title}\n\ ${2}\n\ snippet tcdt\n\ t.datetime :${1:title}\n\ ${2}\n\ snippet tcf\n\ t.float :${1:title}\n\ ${2}\n\ snippet tch\n\ t.change :${1:name}, :${2:string}, :${3:limit} => ${4:80}\n\ ${5}\n\ snippet tci\n\ t.integer :${1:title}\n\ ${2}\n\ snippet tcl\n\ t.integer :lock_version, :null => false, :default => 0\n\ ${1}\n\ snippet tcr\n\ t.references :${1:taggable}, :polymorphic => { :default => '${2:Photo}' }\n\ ${3}\n\ snippet tcs\n\ t.string :${1:title}\n\ ${2}\n\ snippet tct\n\ t.text :${1:title}\n\ ${2}\n\ snippet tcti\n\ t.time :${1:title}\n\ ${2}\n\ snippet tcts\n\ t.timestamp :${1:title}\n\ ${2}\n\ snippet tctss\n\ t.timestamps\n\ ${1}\n\ snippet va\n\ validates_associated :${1:attribute}\n\ snippet vao\n\ validates_acceptance_of :${1:terms}\n\ snippet vc\n\ validates_confirmation_of :${1:attribute}\n\ snippet ve\n\ validates_exclusion_of :${1:attribute}, :in => ${2:%w( mov avi )}\n\ snippet vf\n\ validates_format_of :${1:attribute}, :with => /${2:regex}/\n\ snippet vi\n\ validates_inclusion_of :${1:attribute}, :in => %w(${2: mov avi })\n\ snippet vl\n\ validates_length_of :${1:attribute}, :within => ${2:3}..${3:20}\n\ snippet vn\n\ validates_numericality_of :${1:attribute}\n\ snippet vpo\n\ validates_presence_of :${1:attribute}\n\ snippet vu\n\ validates_uniqueness_of :${1:attribute}\n\ snippet wants\n\ wants.${1:js|xml|html} { ${2} }\n\ snippet wc\n\ where(${1:\"conditions\"}${2:, bind_var})\n\ snippet wh\n\ where(${1:field} => ${2:value})\n\ snippet xdelete\n\ xhr :delete, :${1:destroy}, :id => ${2:1}${3}\n\ snippet xget\n\ xhr :get, :${1:show}, :id => ${2:1}${3}\n\ snippet xpost\n\ xhr :post, :${1:create}, :${2:object} => { ${3} }\n\ snippet xput\n\ xhr :put, :${1:update}, :id => ${2:1}, :${3:object} => { ${4} }${5}\n\ snippet test\n\ test \"should ${1:do something}\" do\n\ ${2}\n\ end\n\ #migrations\n\ snippet mac\n\ add_column :${1:table_name}, :${2:column_name}, :${3:data_type}\n\ snippet mrc\n\ remove_column :${1:table_name}, :${2:column_name}\n\ snippet mrnc\n\ rename_column :${1:table_name}, :${2:old_column_name}, :${3:new_column_name}\n\ snippet mcc\n\ change_column :${1:table}, :${2:column}, :${3:type}\n\ snippet mccc\n\ t.column :${1:title}, :${2:string}\n\ snippet mct\n\ create_table :${1:table_name} do |t|\n\ t.column :${2:name}, :${3:type}\n\ end\n\ snippet migration\n\ class ${1:class_name} < ActiveRecord::Migration\n\ def self.up\n\ ${2}\n\ end\n\ \n\ def self.down\n\ end\n\ end\n\ \n\ snippet trc\n\ t.remove :${1:column}\n\ snippet tre\n\ t.rename :${1:old_column_name}, :${2:new_column_name}\n\ ${3}\n\ snippet tref\n\ t.references :${1:model}\n\ \n\ #rspec\n\ snippet it\n\ it \"${1:spec_name}\" do\n\ ${2}\n\ end\n\ snippet itp\n\ it \"${1:spec_name}\"\n\ ${2}\n\ snippet desc\n\ describe ${1:class_name} do\n\ ${2}\n\ end\n\ snippet cont\n\ context \"${1:message}\" do\n\ ${2}\n\ end\n\ snippet bef\n\ before :${1:each} do\n\ ${2}\n\ end\n\ snippet aft\n\ after :${1:each} do\n\ ${2}\n\ end\n\ "; exports.scope = "ruby"; }); (function() { window.require(["ace/snippets/ruby"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
/** @module ember @submodule ember-runtime */ import { Mixin, get, set } from 'ember-metal'; import { deprecate } from 'ember-debug'; /** The `Ember.Freezable` mixin implements some basic methods for marking an object as frozen. Once an object is frozen it should be read only. No changes may be made the internal state of the object. ## Enforcement To fully support freezing in your subclass, you must include this mixin and override any method that might alter any property on the object to instead raise an exception. You can check the state of an object by checking the `isFrozen` property. Although future versions of JavaScript may support language-level freezing object objects, that is not the case today. Even if an object is freezable, it is still technically possible to modify the object, even though it could break other parts of your application that do not expect a frozen object to change. It is, therefore, very important that you always respect the `isFrozen` property on all freezable objects. ## Example Usage The example below shows a simple object that implement the `Ember.Freezable` protocol. ```javascript Contact = Ember.Object.extend(Ember.Freezable, { firstName: null, lastName: null, // swaps the names swapNames: function() { if (this.get('isFrozen')) throw Ember.FROZEN_ERROR; var tmp = this.get('firstName'); this.set('firstName', this.get('lastName')); this.set('lastName', tmp); return this; } }); c = Contact.create({ firstName: "John", lastName: "Doe" }); c.swapNames(); // returns c c.freeze(); c.swapNames(); // EXCEPTION ``` ## Copying Usually the `Ember.Freezable` protocol is implemented in cooperation with the `Ember.Copyable` protocol, which defines a `frozenCopy()` method that will return a frozen object, if the object implements this method as well. @class Freezable @namespace Ember @since Ember 0.9 @deprecated Use `Object.freeze` instead. @private */ export const Freezable = Mixin.create({ init() { deprecate( '`Ember.Freezable` is deprecated, use `Object.freeze` instead.', false, { id: 'ember-runtime.freezable-init', until: '3.0.0' } ); this._super(...arguments); }, /** Set to `true` when the object is frozen. Use this property to detect whether your object is frozen or not. @property isFrozen @type Boolean @private */ isFrozen: false, /** Freezes the object. Once this method has been called the object should no longer allow any properties to be edited. @method freeze @return {Object} receiver @private */ freeze() { if (get(this, 'isFrozen')) { return this; } set(this, 'isFrozen', true); return this; } }); export const FROZEN_ERROR = 'Frozen object cannot be modified.';
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _simpleAssign = require('simple-assign'); var _simpleAssign2 = _interopRequireDefault(_simpleAssign); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _transitions = require('../styles/transitions'); var _transitions2 = _interopRequireDefault(_transitions); var _colorManipulator = require('../utils/colorManipulator'); var _EnhancedButton = require('../internal/EnhancedButton'); var _EnhancedButton2 = _interopRequireDefault(_EnhancedButton); var _FontIcon = require('../FontIcon'); var _FontIcon2 = _interopRequireDefault(_FontIcon); var _Paper = require('../Paper'); var _Paper2 = _interopRequireDefault(_Paper); var _childUtils = require('../utils/childUtils'); var _warning = require('warning'); var _warning2 = _interopRequireDefault(_warning); var _propTypes = require('../utils/propTypes'); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function getStyles(props, context) { var floatingActionButton = context.muiTheme.floatingActionButton; var backgroundColor = props.backgroundColor || floatingActionButton.color; var iconColor = floatingActionButton.iconColor; if (props.disabled) { backgroundColor = props.disabledColor || floatingActionButton.disabledColor; iconColor = floatingActionButton.disabledTextColor; } else if (props.secondary) { backgroundColor = floatingActionButton.secondaryColor; iconColor = floatingActionButton.secondaryIconColor; } return { root: { transition: _transitions2.default.easeOut(), display: 'inline-block' }, container: { backgroundColor: backgroundColor, transition: _transitions2.default.easeOut(), position: 'relative', height: floatingActionButton.buttonSize, width: floatingActionButton.buttonSize, padding: 0, overflow: 'hidden', borderRadius: '50%', textAlign: 'center', verticalAlign: 'bottom' }, containerWhenMini: { height: floatingActionButton.miniSize, width: floatingActionButton.miniSize }, overlay: { transition: _transitions2.default.easeOut(), top: 0 }, overlayWhenHovered: { backgroundColor: (0, _colorManipulator.fade)(iconColor, 0.4) }, icon: { height: floatingActionButton.buttonSize, lineHeight: floatingActionButton.buttonSize + 'px', fill: iconColor, color: iconColor }, iconWhenMini: { height: floatingActionButton.miniSize, lineHeight: floatingActionButton.miniSize + 'px' } }; } var FloatingActionButton = function (_Component) { _inherits(FloatingActionButton, _Component); function FloatingActionButton() { var _Object$getPrototypeO; var _temp, _this, _ret; _classCallCheck(this, FloatingActionButton); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(FloatingActionButton)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = { hovered: false, touch: false, zDepth: undefined }, _this.handleMouseDown = function (event) { // only listen to left clicks if (event.button === 0) { _this.setState({ zDepth: _this.props.zDepth + 1 }); } if (_this.props.onMouseDown) _this.props.onMouseDown(event); }, _this.handleMouseUp = function (event) { _this.setState({ zDepth: _this.props.zDepth }); if (_this.props.onMouseUp) { _this.props.onMouseUp(event); } }, _this.handleMouseLeave = function (event) { if (!_this.refs.container.isKeyboardFocused()) { _this.setState({ zDepth: _this.props.zDepth, hovered: false }); } if (_this.props.onMouseLeave) { _this.props.onMouseLeave(event); } }, _this.handleMouseEnter = function (event) { if (!_this.refs.container.isKeyboardFocused() && !_this.state.touch) { _this.setState({ hovered: true }); } if (_this.props.onMouseEnter) { _this.props.onMouseEnter(event); } }, _this.handleTouchStart = function (event) { _this.setState({ touch: true, zDepth: _this.props.zDepth + 1 }); if (_this.props.onTouchStart) { _this.props.onTouchStart(event); } }, _this.handleTouchEnd = function (event) { _this.setState({ zDepth: _this.props.zDepth }); if (_this.props.onTouchEnd) { _this.props.onTouchEnd(event); } }, _this.handleKeyboardFocus = function (event, keyboardFocused) { if (keyboardFocused && !_this.props.disabled) { _this.setState({ zDepth: _this.props.zDepth + 1 }); _this.refs.overlay.style.backgroundColor = (0, _colorManipulator.fade)(getStyles(_this.props, _this.context).icon.color, 0.4); } else if (!_this.state.hovered) { _this.setState({ zDepth: _this.props.zDepth }); _this.refs.overlay.style.backgroundColor = 'transparent'; } }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(FloatingActionButton, [{ key: 'componentWillMount', value: function componentWillMount() { this.setState({ zDepth: this.props.disabled ? 0 : this.props.zDepth }); } }, { key: 'componentDidMount', value: function componentDidMount() { process.env.NODE_ENV !== "production" ? (0, _warning2.default)(!this.props.iconClassName || !this.props.children, 'You have set both an iconClassName and a child icon. ' + 'It is recommended you use only one method when adding ' + 'icons to FloatingActionButtons.') : void 0; } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (nextProps.disabled !== this.props.disabled) { this.setState({ zDepth: nextProps.disabled ? 0 : this.props.zDepth }); } } }, { key: 'render', value: function render() { var _props = this.props; var backgroundColor = _props.backgroundColor; var className = _props.className; var disabled = _props.disabled; var mini = _props.mini; var secondary = _props.secondary; var iconStyle = _props.iconStyle; var iconClassName = _props.iconClassName; var zDepth = _props.zDepth; var other = _objectWithoutProperties(_props, ['backgroundColor', 'className', 'disabled', 'mini', 'secondary', 'iconStyle', 'iconClassName', 'zDepth']); var prepareStyles = this.context.muiTheme.prepareStyles; var styles = getStyles(this.props, this.context); var iconElement = void 0; if (iconClassName) { iconElement = _react2.default.createElement(_FontIcon2.default, { className: iconClassName, style: (0, _simpleAssign2.default)({}, styles.icon, mini && styles.iconWhenMini, iconStyle) }); } var children = (0, _childUtils.extendChildren)(this.props.children, { style: (0, _simpleAssign2.default)({}, styles.icon, mini && styles.iconWhenMini, iconStyle) }); var buttonEventHandlers = disabled ? null : { onMouseDown: this.handleMouseDown, onMouseUp: this.handleMouseUp, onMouseLeave: this.handleMouseLeave, onMouseEnter: this.handleMouseEnter, onTouchStart: this.handleTouchStart, onTouchEnd: this.handleTouchEnd, onKeyboardFocus: this.handleKeyboardFocus }; return _react2.default.createElement( _Paper2.default, { className: className, style: (0, _simpleAssign2.default)(styles.root, this.props.style), zDepth: this.state.zDepth, circle: true }, _react2.default.createElement( _EnhancedButton2.default, _extends({}, other, buttonEventHandlers, { ref: 'container', disabled: disabled, style: (0, _simpleAssign2.default)(styles.container, this.props.mini && styles.containerWhenMini, iconStyle), focusRippleColor: styles.icon.color, touchRippleColor: styles.icon.color }), _react2.default.createElement( 'div', { ref: 'overlay', style: prepareStyles((0, _simpleAssign2.default)(styles.overlay, this.state.hovered && !this.props.disabled && styles.overlayWhenHovered)) }, iconElement, children ) ) ); } }]); return FloatingActionButton; }(_react.Component); FloatingActionButton.propTypes = { /** * This value will override the default background color for the button. * However it will not override the default disabled background color. * This has to be set separately using the disabledColor attribute. */ backgroundColor: _react.PropTypes.string, /** * This is what displayed inside the floating action button; for example, a SVG Icon. */ children: _react.PropTypes.node, /** * The css class name of the root element. */ className: _react.PropTypes.string, /** * Disables the button if set to true. */ disabled: _react.PropTypes.bool, /** * This value will override the default background color for the button when it is disabled. */ disabledColor: _react.PropTypes.string, /** * The URL to link to when the button is clicked. */ href: _react.PropTypes.string, /** * The icon within the FloatingActionButton is a FontIcon component. * This property is the classname of the icon to be displayed inside the button. * An alternative to adding an iconClassName would be to manually insert a * FontIcon component or custom SvgIcon component or as a child of FloatingActionButton. */ iconClassName: _react.PropTypes.string, /** * This is the equivalent to iconClassName except that it is used for * overriding the inline-styles of the FontIcon component. */ iconStyle: _react.PropTypes.object, /** * If true, the button will be a small floating action button. */ mini: _react.PropTypes.bool, /** @ignore */ onMouseDown: _react.PropTypes.func, /** @ignore */ onMouseEnter: _react.PropTypes.func, /** @ignore */ onMouseLeave: _react.PropTypes.func, /** @ignore */ onMouseUp: _react.PropTypes.func, /** @ignore */ onTouchEnd: _react.PropTypes.func, /** @ignore */ onTouchStart: _react.PropTypes.func, /** * If true, the button will use the secondary button colors. */ secondary: _react.PropTypes.bool, /** * Override the inline-styles of the root element. */ style: _react.PropTypes.object, /** * The zDepth of the underlying `Paper` component. */ zDepth: _propTypes2.default.zDepth }; FloatingActionButton.defaultProps = { disabled: false, mini: false, secondary: false, zDepth: 2 }; FloatingActionButton.contextTypes = { muiTheme: _react.PropTypes.object.isRequired }; exports.default = FloatingActionButton;
// Generated by CoffeeScript 1.7.1 var ReadableTrackingBuffer, WritableTrackingBuffer; ReadableTrackingBuffer = require('./readable-tracking-buffer'); WritableTrackingBuffer = require('./writable-tracking-buffer'); module.exports.ReadableTrackingBuffer = ReadableTrackingBuffer; module.exports.WritableTrackingBuffer = WritableTrackingBuffer;
module.exports = [ { entry: { "widgets": "./app/widgets", "edit": "./app/views/edit", "index": "./app/views/index" }, output: { filename: "./app/bundle/[name].js" }, module: { loaders: [ { test: /\.html$/, loader: "html" }, { test: /\.vue$/, loader: "vue" } ] } } ];
/*! x509-1.1.6.js (c) 2012-2015 Kenji Urushima | kjur.github.com/jsrsasign/license */ /* * x509.js - X509 class to read subject public key from certificate. * * Copyright (c) 2010-2015 Kenji Urushima (kenji.urushima@gmail.com) * * This software is licensed under the terms of the MIT License. * http://kjur.github.com/jsrsasign/license * * The above copyright and license notice shall be * included in all copies or substantial portions of the Software. */ /** * @fileOverview * @name x509-1.1.js * @author Kenji Urushima kenji.urushima@gmail.com * @version x509 1.1.6 (2015-May-20) * @since jsrsasign 1.x.x * @license <a href="http://kjur.github.io/jsrsasign/license/">MIT License</a> */ /* * Depends: * base64.js * rsa.js * asn1hex.js */ /** * X.509 certificate class.<br/> * @class X.509 certificate class * @property {RSAKey} subjectPublicKeyRSA Tom Wu's RSAKey object * @property {String} subjectPublicKeyRSA_hN hexadecimal string for modulus of RSA public key * @property {String} subjectPublicKeyRSA_hE hexadecimal string for public exponent of RSA public key * @property {String} hex hexacedimal string for X.509 certificate. * @author Kenji Urushima * @version 1.0.1 (08 May 2012) * @see <a href="http://kjur.github.com/jsrsasigns/">'jwrsasign'(RSA Sign JavaScript Library) home page http://kjur.github.com/jsrsasign/</a> */ function X509() { this.subjectPublicKeyRSA = null; this.subjectPublicKeyRSA_hN = null; this.subjectPublicKeyRSA_hE = null; this.hex = null; // ===== get basic fields from hex ===================================== /** * get hexadecimal string of serialNumber field of certificate.<br/> * @name getSerialNumberHex * @memberOf X509# * @function */ this.getSerialNumberHex = function() { return ASN1HEX.getDecendantHexVByNthList(this.hex, 0, [0, 1]); }; /** * get hexadecimal string of issuer field TLV of certificate.<br/> * @name getIssuerHex * @memberOf X509# * @function */ this.getIssuerHex = function() { return ASN1HEX.getDecendantHexTLVByNthList(this.hex, 0, [0, 3]); }; /** * get string of issuer field of certificate.<br/> * @name getIssuerString * @memberOf X509# * @function */ this.getIssuerString = function() { return X509.hex2dn(ASN1HEX.getDecendantHexTLVByNthList(this.hex, 0, [0, 3])); }; /** * get hexadecimal string of subject field of certificate.<br/> * @name getSubjectHex * @memberOf X509# * @function */ this.getSubjectHex = function() { return ASN1HEX.getDecendantHexTLVByNthList(this.hex, 0, [0, 5]); }; /** * get string of subject field of certificate.<br/> * @name getSubjectString * @memberOf X509# * @function */ this.getSubjectString = function() { return X509.hex2dn(ASN1HEX.getDecendantHexTLVByNthList(this.hex, 0, [0, 5])); }; /** * get notBefore field string of certificate.<br/> * @name getNotBefore * @memberOf X509# * @function */ this.getNotBefore = function() { var s = ASN1HEX.getDecendantHexVByNthList(this.hex, 0, [0, 4, 0]); s = s.replace(/(..)/g, "%$1"); s = decodeURIComponent(s); return s; }; /** * get notAfter field string of certificate.<br/> * @name getNotAfter * @memberOf X509# * @function */ this.getNotAfter = function() { var s = ASN1HEX.getDecendantHexVByNthList(this.hex, 0, [0, 4, 1]); s = s.replace(/(..)/g, "%$1"); s = decodeURIComponent(s); return s; }; // ===== read certificate public key ========================== // ===== read certificate ===================================== /** * read PEM formatted X.509 certificate from string.<br/> * @name readCertPEM * @memberOf X509# * @function * @param {String} sCertPEM string for PEM formatted X.509 certificate */ this.readCertPEM = function(sCertPEM) { var hCert = X509.pemToHex(sCertPEM); var a = X509.getPublicKeyHexArrayFromCertHex(hCert); var rsa = new RSAKey(); rsa.setPublic(a[0], a[1]); this.subjectPublicKeyRSA = rsa; this.subjectPublicKeyRSA_hN = a[0]; this.subjectPublicKeyRSA_hE = a[1]; this.hex = hCert; }; this.readCertPEMWithoutRSAInit = function(sCertPEM) { var hCert = X509.pemToHex(sCertPEM); var a = X509.getPublicKeyHexArrayFromCertHex(hCert); this.subjectPublicKeyRSA.setPublic(a[0], a[1]); this.subjectPublicKeyRSA_hN = a[0]; this.subjectPublicKeyRSA_hE = a[1]; this.hex = hCert; }; }; X509.pemToBase64 = function(sCertPEM) { var s = sCertPEM; s = s.replace("-----BEGIN CERTIFICATE-----", ""); s = s.replace("-----END CERTIFICATE-----", ""); s = s.replace(/[ \n]+/g, ""); return s; }; X509.pemToHex = function(sCertPEM) { var b64Cert = X509.pemToBase64(sCertPEM); var hCert = b64tohex(b64Cert); return hCert; }; // NOTE: Without BITSTRING encapsulation. X509.getSubjectPublicKeyPosFromCertHex = function(hCert) { var pInfo = X509.getSubjectPublicKeyInfoPosFromCertHex(hCert); if (pInfo == -1) return -1; var a = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, pInfo); if (a.length != 2) return -1; var pBitString = a[1]; if (hCert.substring(pBitString, pBitString + 2) != '03') return -1; var pBitStringV = ASN1HEX.getStartPosOfV_AtObj(hCert, pBitString); if (hCert.substring(pBitStringV, pBitStringV + 2) != '00') return -1; return pBitStringV + 2; }; // NOTE: privateKeyUsagePeriod field of X509v2 not supported. // NOTE: v1 and v3 supported X509.getSubjectPublicKeyInfoPosFromCertHex = function(hCert) { var pTbsCert = ASN1HEX.getStartPosOfV_AtObj(hCert, 0); var a = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, pTbsCert); if (a.length < 1) return -1; if (hCert.substring(a[0], a[0] + 10) == "a003020102") { // v3 if (a.length < 6) return -1; return a[6]; } else { if (a.length < 5) return -1; return a[5]; } }; X509.getPublicKeyHexArrayFromCertHex = function(hCert) { var p = X509.getSubjectPublicKeyPosFromCertHex(hCert); var a = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, p); if (a.length != 2) return []; var hN = ASN1HEX.getHexOfV_AtObj(hCert, a[0]); var hE = ASN1HEX.getHexOfV_AtObj(hCert, a[1]); if (hN != null && hE != null) { return [hN, hE]; } else { return []; } }; X509.getHexTbsCertificateFromCert = function(hCert) { var pTbsCert = ASN1HEX.getStartPosOfV_AtObj(hCert, 0); return pTbsCert; }; X509.getPublicKeyHexArrayFromCertPEM = function(sCertPEM) { var hCert = X509.pemToHex(sCertPEM); var a = X509.getPublicKeyHexArrayFromCertHex(hCert); return a; }; X509.hex2dn = function(hDN) { var s = ""; var a = ASN1HEX.getPosArrayOfChildren_AtObj(hDN, 0); for (var i = 0; i < a.length; i++) { var hRDN = ASN1HEX.getHexOfTLV_AtObj(hDN, a[i]); s = s + "/" + X509.hex2rdn(hRDN); } return s; }; X509.hex2rdn = function(hRDN) { var hType = ASN1HEX.getDecendantHexTLVByNthList(hRDN, 0, [0, 0]); var hValue = ASN1HEX.getDecendantHexVByNthList(hRDN, 0, [0, 1]); var type = ""; try { type = X509.DN_ATTRHEX[hType]; } catch (ex) { type = hType; } hValue = hValue.replace(/(..)/g, "%$1"); var value = decodeURIComponent(hValue); return type + "=" + value; }; X509.DN_ATTRHEX = { "0603550406": "C", "060355040a": "O", "060355040b": "OU", "0603550403": "CN", "0603550405": "SN", "0603550408": "ST", "0603550407": "L", }; /** * get RSAKey/ECDSA public key object from PEM certificate string * @name getPublicKeyFromCertPEM * @memberOf X509 * @function * @param {String} sCertPEM PEM formatted RSA/ECDSA/DSA X.509 certificate * @return returns RSAKey/KJUR.crypto.{ECDSA,DSA} object of public key * @since x509 1.1.1 * @description * NOTE: DSA is also supported since x509 1.1.2. */ X509.getPublicKeyFromCertPEM = function(sCertPEM) { var info = X509.getPublicKeyInfoPropOfCertPEM(sCertPEM); if (info.algoid == "2a864886f70d010101") { // RSA var aRSA = KEYUTIL.parsePublicRawRSAKeyHex(info.keyhex); var key = new RSAKey(); key.setPublic(aRSA.n, aRSA.e); return key; } else if (info.algoid == "2a8648ce3d0201") { // ECC var curveName = KJUR.crypto.OID.oidhex2name[info.algparam]; var key = new KJUR.crypto.ECDSA({'curve': curveName, 'info': info.keyhex}); key.setPublicKeyHex(info.keyhex); return key; } else if (info.algoid == "2a8648ce380401") { // DSA 1.2.840.10040.4.1 var p = ASN1HEX.getVbyList(info.algparam, 0, [0], "02"); var q = ASN1HEX.getVbyList(info.algparam, 0, [1], "02"); var g = ASN1HEX.getVbyList(info.algparam, 0, [2], "02"); var y = ASN1HEX.getHexOfV_AtObj(info.keyhex, 0); y = y.substr(2); var key = new KJUR.crypto.DSA(); key.setPublic(new BigInteger(p, 16), new BigInteger(q, 16), new BigInteger(g, 16), new BigInteger(y, 16)); return key; } else { throw "unsupported key"; } }; /** * get public key information from PEM certificate * @name getPublicKeyInfoPropOfCertPEM * @memberOf X509 * @function * @param {String} sCertPEM string of PEM formatted certificate * @return {Hash} hash of information for public key * @since x509 1.1.1 * @description * Resulted associative array has following properties: * <ul> * <li>algoid - hexadecimal string of OID of asymmetric key algorithm</li> * <li>algparam - hexadecimal string of OID of ECC curve name or null</li> * <li>keyhex - hexadecimal string of key in the certificate</li> * </ul> * @since x509 1.1.1 */ X509.getPublicKeyInfoPropOfCertPEM = function(sCertPEM) { var result = {}; result.algparam = null; var hCert = X509.pemToHex(sCertPEM); // 1. Certificate ASN.1 var a1 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, 0); if (a1.length != 3) throw "malformed X.509 certificate PEM (code:001)"; // not 3 item of seq Cert // 2. tbsCertificate if (hCert.substr(a1[0], 2) != "30") throw "malformed X.509 certificate PEM (code:002)"; // tbsCert not seq var a2 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, a1[0]); // 3. subjectPublicKeyInfo if (a2.length < 7) throw "malformed X.509 certificate PEM (code:003)"; // no subjPubKeyInfo var a3 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, a2[6]); if (a3.length != 2) throw "malformed X.509 certificate PEM (code:004)"; // not AlgId and PubKey // 4. AlgId var a4 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, a3[0]); if (a4.length != 2) throw "malformed X.509 certificate PEM (code:005)"; // not 2 item in AlgId result.algoid = ASN1HEX.getHexOfV_AtObj(hCert, a4[0]); if (hCert.substr(a4[1], 2) == "06") { // EC result.algparam = ASN1HEX.getHexOfV_AtObj(hCert, a4[1]); } else if (hCert.substr(a4[1], 2) == "30") { // DSA result.algparam = ASN1HEX.getHexOfTLV_AtObj(hCert, a4[1]); } // 5. Public Key Hex if (hCert.substr(a3[1], 2) != "03") throw "malformed X.509 certificate PEM (code:006)"; // not bitstring var unusedBitAndKeyHex = ASN1HEX.getHexOfV_AtObj(hCert, a3[1]); result.keyhex = unusedBitAndKeyHex.substr(2); return result; }; /** * get position of subjectPublicKeyInfo field from HEX certificate * @name getPublicKeyInfoPosOfCertHEX * @memberOf X509 * @function * @param {String} hCert hexadecimal string of certificate * @return {Integer} position in hexadecimal string * @since x509 1.1.4 * @description * get position for SubjectPublicKeyInfo field in the hexadecimal string of * certificate. */ X509.getPublicKeyInfoPosOfCertHEX = function(hCert) { // 1. Certificate ASN.1 var a1 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, 0); if (a1.length != 3) throw "malformed X.509 certificate PEM (code:001)"; // not 3 item of seq Cert // 2. tbsCertificate if (hCert.substr(a1[0], 2) != "30") throw "malformed X.509 certificate PEM (code:002)"; // tbsCert not seq var a2 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, a1[0]); // 3. subjectPublicKeyInfo if (a2.length < 7) throw "malformed X.509 certificate PEM (code:003)"; // no subjPubKeyInfo return a2[6]; }; /** * get array of X.509 V3 extension value information in hex string of certificate * @name getV3ExtInfoListOfCertHex * @memberOf X509 * @function * @param {String} hCert hexadecimal string of X.509 certificate binary * @return {Array} array of result object by {@link X509.getV3ExtInfoListOfCertHex} * @since x509 1.1.5 * @description * This method will get all extension information of a X.509 certificate. * Items of resulting array has following properties: * <ul> * <li>posTLV - index of ASN.1 TLV for the extension. same as 'pos' argument.</li> * <li>oid - dot noted string of extension oid (ex. 2.5.29.14)</li> * <li>critical - critical flag value for this extension</li> * <li>posV - index of ASN.1 TLV for the extension value. * This is a position of a content of ENCAPSULATED OCTET STRING.</li> * </ul> * @example * hCert = X509.pemToHex(certGithubPEM); * a = X509.getV3ExtInfoListOfCertHex(hCert); * // Then a will be an array of like following: * [{posTLV: 1952, oid: "2.5.29.35", critical: false, posV: 1968}, * {posTLV: 1974, oid: "2.5.29.19", critical: true, posV: 1986}, ...] */ X509.getV3ExtInfoListOfCertHex = function(hCert) { // 1. Certificate ASN.1 var a1 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, 0); if (a1.length != 3) throw "malformed X.509 certificate PEM (code:001)"; // not 3 item of seq Cert // 2. tbsCertificate if (hCert.substr(a1[0], 2) != "30") throw "malformed X.509 certificate PEM (code:002)"; // tbsCert not seq var a2 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, a1[0]); // 3. v3Extension EXPLICIT Tag [3] // ver, seri, alg, iss, validity, subj, spki, (iui,) (sui,) ext if (a2.length < 8) throw "malformed X.509 certificate PEM (code:003)"; // tbsCert num field too short if (hCert.substr(a2[7], 2) != "a3") throw "malformed X.509 certificate PEM (code:004)"; // not [3] tag var a3 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, a2[7]); if (a3.length != 1) throw "malformed X.509 certificate PEM (code:005)"; // [3]tag numChild!=1 // 4. v3Extension SEQUENCE if (hCert.substr(a3[0], 2) != "30") throw "malformed X.509 certificate PEM (code:006)"; // not SEQ var a4 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, a3[0]); // 5. v3Extension item position var numExt = a4.length; var aInfo = new Array(numExt); for (var i = 0; i < numExt; i++) { aInfo[i] = X509.getV3ExtItemInfo_AtObj(hCert, a4[i]); } return aInfo; }; /** * get X.509 V3 extension value information at the specified position * @name getV3ExtItemInfo_AtObj * @memberOf X509 * @function * @param {String} hCert hexadecimal string of X.509 certificate binary * @param {Integer} pos index of hexadecimal string for the extension * @return {Object} properties for the extension * @since x509 1.1.5 * @description * This method will get some information of a X.509 V extension * which is referred by an index of hexadecimal string of X.509 * certificate. * Resulting object has following properties: * <ul> * <li>posTLV - index of ASN.1 TLV for the extension. same as 'pos' argument.</li> * <li>oid - dot noted string of extension oid (ex. 2.5.29.14)</li> * <li>critical - critical flag value for this extension</li> * <li>posV - index of ASN.1 TLV for the extension value. * This is a position of a content of ENCAPSULATED OCTET STRING.</li> * </ul> * This method is used by {@link X509.getV3ExtInfoListOfCertHex} internally. */ X509.getV3ExtItemInfo_AtObj = function(hCert, pos) { var info = {}; // posTLV - extension TLV info.posTLV = pos; var a = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, pos); if (a.length != 2 && a.length != 3) throw "malformed X.509v3 Ext (code:001)"; // oid,(critical,)val // oid - extension OID if (hCert.substr(a[0], 2) != "06") throw "malformed X.509v3 Ext (code:002)"; // not OID "06" var valueHex = ASN1HEX.getHexOfV_AtObj(hCert, a[0]); info.oid = ASN1HEX.hextooidstr(valueHex); // critical - extension critical flag info.critical = false; // critical false by default if (a.length == 3) info.critical = true; // posV - content TLV position of encapsulated // octet string of V3 extension value. var posExtV = a[a.length - 1]; if (hCert.substr(posExtV, 2) != "04") throw "malformed X.509v3 Ext (code:003)"; // not EncapOctet "04" info.posV = ASN1HEX.getStartPosOfV_AtObj(hCert, posExtV); return info; }; /** * get X.509 V3 extension value ASN.1 TLV for specified oid or name * @name getHexOfTLV_V3ExtValue * @memberOf X509 * @function * @param {String} hCert hexadecimal string of X.509 certificate binary * @param {String} oidOrName oid or name for extension (ex. 'keyUsage' or '2.5.29.15') * @return {String} hexadecimal string of extension ASN.1 TLV * @since x509 1.1.6 * @description * This method will get X.509v3 extension value of ASN.1 TLV * which is specifyed by extension name or oid. * @example * hExtValue = X509.getHexOfTLV_V3ExtValue(hCert, "keyUsage"); * // hExtValue will be such like '030205a0'. */ X509.getHexOfTLV_V3ExtValue = function(hCert, oidOrName) { var pos = X509.getPosOfTLV_V3ExtValue(hCert, oidOrName); if (pos == -1) return ''; return ASN1HEX.getHexOfTLV_AtObj(hCert, pos); }; /** * get X.509 V3 extension value ASN.1 V for specified oid or name * @name getHexOfV_V3ExtValue * @memberOf X509 * @function * @param {String} hCert hexadecimal string of X.509 certificate binary * @param {String} oidOrName oid or name for extension (ex. 'keyUsage' or '2.5.29.15') * @return {String} hexadecimal string of extension ASN.1 TLV * @since x509 1.1.6 * @description * This method will get X.509v3 extension value of ASN.1 value * which is specifyed by extension name or oid. * If there is no such extension in the certificate, * it returns empty string (i.e. ''). * Available extension names and oids are defined * in the {@link KJUR.asn1.x509.OID} class. * @example * hExtValue = X509.getHexOfV_V3ExtValue(hCert, "keyUsage"); * // hExtValue will be such like '05a0'. */ X509.getHexOfV_V3ExtValue = function(hCert, oidOrName) { var pos = X509.getPosOfTLV_V3ExtValue(hCert, oidOrName); if (pos == -1) return ''; return ASN1HEX.getHexOfV_AtObj(hCert, pos); }; /** * get index in the certificate hexa string for specified oid or name specified extension * @name getPosOfTLV_V3ExtValue * @memberOf X509 * @function * @param {String} hCert hexadecimal string of X.509 certificate binary * @param {String} oidOrName oid or name for extension (ex. 'keyUsage' or '2.5.29.15') * @return {Integer} index in the hexadecimal string of certficate for specified extension * @since x509 1.1.6 * @description * This method will get X.509v3 extension value of ASN.1 V(value) * which is specifyed by extension name or oid. * If there is no such extension in the certificate, * it returns empty string (i.e. ''). * Available extension names and oids are defined * in the {@link KJUR.asn1.x509.OID} class. * @example * idx = X509.getPosOfV_V3ExtValue(hCert, "keyUsage"); * // The 'idx' will be index in the string for keyUsage value ASN.1 TLV. */ X509.getPosOfTLV_V3ExtValue = function(hCert, oidOrName) { var oid = oidOrName; if (! oidOrName.match(/^[0-9.]+$/)) oid = KJUR.asn1.x509.OID.name2oid(oidOrName); if (oid == '') return -1; var infoList = X509.getV3ExtInfoListOfCertHex(hCert); for (var i = 0; i < infoList.length; i++) { var info = infoList[i]; if (info.oid == oid) return info.posV; } return -1; }; X509.KEYUSAGE_NAME = [ "digitalSignature", "nonRepudiation", "keyEncipherment", "dataEncipherment", "keyAgreement", "keyCertSign", "cRLSign", "encipherOnly", "decipherOnly" ]; /** * get KeyUsage extension value as binary string in the certificate * @name getExtKeyUsageBin * @memberOf X509 * @function * @param {String} hCert hexadecimal string of X.509 certificate binary * @return {String} binary string of key usage bits (ex. '101') * @since x509 1.1.6 * @description * This method will get key usage extension value * as binary string such like '101'. * Key usage bits definition is in the RFC 5280. * If there is no key usage extension in the certificate, * it returns empty string (i.e. ''). * @example * bKeyUsage = X509.getExtKeyUsageBin(hCert); * // bKeyUsage will be such like '101'. * // 1 - digitalSignature * // 0 - nonRepudiation * // 1 - keyEncipherment */ X509.getExtKeyUsageBin = function(hCert) { var hKeyUsage = X509.getHexOfV_V3ExtValue(hCert, "keyUsage"); if (hKeyUsage == '') return ''; if (hKeyUsage.length % 2 != 0 || hKeyUsage.length <= 2) throw "malformed key usage value"; var unusedBits = parseInt(hKeyUsage.substr(0, 2)); var bKeyUsage = parseInt(hKeyUsage.substr(2), 16).toString(2); return bKeyUsage.substr(0, bKeyUsage.length - unusedBits); }; /** * get KeyUsage extension value as names in the certificate * @name getExtKeyUsageString * @memberOf X509 * @function * @param {String} hCert hexadecimal string of X.509 certificate binary * @return {String} comma separated string of key usage * @since x509 1.1.6 * @description * This method will get key usage extension value * as comma separated string of usage names. * If there is no key usage extension in the certificate, * it returns empty string (i.e. ''). * @example * sKeyUsage = X509.getExtKeyUsageString(hCert); * // sKeyUsage will be such like 'digitalSignature,keyEncipherment'. */ X509.getExtKeyUsageString = function(hCert) { var bKeyUsage = X509.getExtKeyUsageBin(hCert); var a = new Array(); for (var i = 0; i < bKeyUsage.length; i++) { if (bKeyUsage.substr(i, 1) == "1") a.push(X509.KEYUSAGE_NAME[i]); } return a.join(","); }; /** * get AuthorityInfoAccess extension value in the certificate as associative array * @name getExtAIAInfo * @memberOf X509 * @function * @param {String} hCert hexadecimal string of X.509 certificate binary * @return {Object} associative array of AIA extension properties * @since x509 1.1.6 * @description * This method will get authority info access value * as associate array which has following properties: * <ul> * <li>ocsp - array of string for OCSP responder URL</li> * <li>caissuer - array of string for caIssuer value (i.e. CA certificates URL)</li> * </ul> * If there is no key usage extension in the certificate, * it returns null; * @example * oAIA = X509.getExtAIAInfo(hCert); * // result will be such like: * // oAIA.ocsp = ["http://ocsp.foo.com"]; * // oAIA.caissuer = ["http://rep.foo.com/aaa.p8m"]; */ X509.getExtAIAInfo = function(hCert) { var result = {}; result.ocsp = []; result.caissuer = []; var pos1 = X509.getPosOfTLV_V3ExtValue(hCert, "authorityInfoAccess"); if (pos1 == -1) return null; if (hCert.substr(pos1, 2) != "30") // extnValue SEQUENCE throw "malformed AIA Extn Value"; var posAccDescList = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, pos1); for (var i = 0; i < posAccDescList.length; i++) { var p = posAccDescList[i]; var posAccDescChild = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, p); if (posAccDescChild.length != 2) throw "malformed AccessDescription of AIA Extn"; var pOID = posAccDescChild[0]; var pName = posAccDescChild[1]; if (ASN1HEX.getHexOfV_AtObj(hCert, pOID) == "2b06010505073001") { if (hCert.substr(pName, 2) == "86") { result.ocsp.push(hextoutf8(ASN1HEX.getHexOfV_AtObj(hCert, pName))); } } if (ASN1HEX.getHexOfV_AtObj(hCert, pOID) == "2b06010505073002") { if (hCert.substr(pName, 2) == "86") { result.caissuer.push(hextoutf8(ASN1HEX.getHexOfV_AtObj(hCert, pName))); } } } return result; }; /* X509.prototype.readCertPEM = _x509_readCertPEM; X509.prototype.readCertPEMWithoutRSAInit = _x509_readCertPEMWithoutRSAInit; X509.prototype.getSerialNumberHex = _x509_getSerialNumberHex; X509.prototype.getIssuerHex = _x509_getIssuerHex; X509.prototype.getSubjectHex = _x509_getSubjectHex; X509.prototype.getIssuerString = _x509_getIssuerString; X509.prototype.getSubjectString = _x509_getSubjectString; X509.prototype.getNotBefore = _x509_getNotBefore; X509.prototype.getNotAfter = _x509_getNotAfter; */
/** * A processor that can run arbitrary checking rules against properties of documents * The configuration for the processor is via the `docTypeRules`. * This is a hash of docTypes to rulesets. * Each rules set is a hash of properties to rule functions. * * The processor will run each rule function against each matching property of each matching doc. * * An example rule might look like: * * ``` * function noMarkdownHeadings(doc, prop, value) { * const match = /^\s?#+\s+.*$/m.exec(value); * if (match) { * return `Headings not allowed in "${prop}" property. Found "${match[0]}"`; * } * } * ``` * */ module.exports = function checkContentRules(log, createDocMessage) { return { /** * { * [docType]: { * [property]: Array<(doc: Document, property: string, value: any) => string|undefined> * } * } */ docTypeRules: {}, failOnContentErrors: false, $runAfter: ['tags-extracted'], $runBefore: [], $process(docs) { const logMessage = this.failOnContentErrors ? log.error.bind(log) : log.warn.bind(log); const errors = []; docs.forEach(doc => { const docErrors = []; const rules = this.docTypeRules[doc.docType] || {}; if (rules) { Object.keys(rules).forEach(property => { const ruleFns = rules[property]; ruleFns.forEach(ruleFn => { const error = ruleFn(doc, property, doc[property]); if (error) { docErrors.push(error); } }); }); } if (docErrors.length) { errors.push({ doc, errors: docErrors }); } }); if (errors.length) { logMessage('Content contains errors'); errors.forEach(docError => { const errors = docError.errors.join('\n '); logMessage(createDocMessage(errors + '\n ', docError.doc)); }); if (this.failOnContentErrors) { throw new Error('Stopping due to content errors.'); } } } }; };
/*! * Vue.js v2.5.6 * (c) 2014-2017 Evan You * Released under the MIT License. */ /* */ var emptyObject = Object.freeze({}); // these helpers produces better vm code in JS engines due to their // explicitness and function inlining function isUndef (v) { return v === undefined || v === null } function isDef (v) { return v !== undefined && v !== null } function isTrue (v) { return v === true } function isFalse (v) { return v === false } /** * Check if value is primitive */ function isPrimitive (value) { return ( typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ) } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ function isObject (obj) { return obj !== null && typeof obj === 'object' } /** * Get the raw type string of a value e.g. [object Object] */ var _toString = Object.prototype.toString; function toRawType (value) { return _toString.call(value).slice(8, -1) } /** * Strict object type check. Only returns true * for plain JavaScript objects. */ function isPlainObject (obj) { return _toString.call(obj) === '[object Object]' } function isRegExp (v) { return _toString.call(v) === '[object RegExp]' } /** * Check if val is a valid array index. */ function isValidArrayIndex (val) { var n = parseFloat(String(val)); return n >= 0 && Math.floor(n) === n && isFinite(val) } /** * Convert a value to a string that is actually rendered. */ function toString (val) { return val == null ? '' : typeof val === 'object' ? JSON.stringify(val, null, 2) : String(val) } /** * Convert a input value to a number for persistence. * If the conversion fails, return original string. */ function toNumber (val) { var n = parseFloat(val); return isNaN(n) ? val : n } /** * Make a map and return a function for checking if a key * is in that map. */ function makeMap ( str, expectsLowerCase ) { var map = Object.create(null); var list = str.split(','); for (var i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; } } /** * Check if a tag is a built-in tag. */ var isBuiltInTag = makeMap('slot,component', true); /** * Check if a attribute is a reserved attribute. */ var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is'); /** * Remove an item from an array */ function remove (arr, item) { if (arr.length) { var index = arr.indexOf(item); if (index > -1) { return arr.splice(index, 1) } } } /** * Check whether the object has the property. */ var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) { return hasOwnProperty.call(obj, key) } /** * Create a cached version of a pure function. */ function cached (fn) { var cache = Object.create(null); return (function cachedFn (str) { var hit = cache[str]; return hit || (cache[str] = fn(str)) }) } /** * Camelize a hyphen-delimited string. */ var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) }); /** * Capitalize a string. */ var capitalize = cached(function (str) { return str.charAt(0).toUpperCase() + str.slice(1) }); /** * Hyphenate a camelCase string. */ var hyphenateRE = /\B([A-Z])/g; var hyphenate = cached(function (str) { return str.replace(hyphenateRE, '-$1').toLowerCase() }); /** * Simple bind, faster than native */ function bind (fn, ctx) { function boundFn (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } // record original fn length boundFn._length = fn.length; return boundFn } /** * Convert an Array-like object to a real Array. */ function toArray (list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret } /** * Mix properties into target object. */ function extend (to, _from) { for (var key in _from) { to[key] = _from[key]; } return to } /** * Merge an Array of Objects into a single Object. */ function toObject (arr) { var res = {}; for (var i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res } /** * Perform no operation. * Stubbing args to make Flow happy without leaving useless transpiled code * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/) */ function noop (a, b, c) {} /** * Always return false. */ var no = function (a, b, c) { return false; }; /** * Return same value */ var identity = function (_) { return _; }; /** * Generate a static keys string from compiler modules. */ function genStaticKeys (modules) { return modules.reduce(function (keys, m) { return keys.concat(m.staticKeys || []) }, []).join(',') } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ function looseEqual (a, b) { if (a === b) { return true } var isObjectA = isObject(a); var isObjectB = isObject(b); if (isObjectA && isObjectB) { try { var isArrayA = Array.isArray(a); var isArrayB = Array.isArray(b); if (isArrayA && isArrayB) { return a.length === b.length && a.every(function (e, i) { return looseEqual(e, b[i]) }) } else if (!isArrayA && !isArrayB) { var keysA = Object.keys(a); var keysB = Object.keys(b); return keysA.length === keysB.length && keysA.every(function (key) { return looseEqual(a[key], b[key]) }) } else { /* istanbul ignore next */ return false } } catch (e) { /* istanbul ignore next */ return false } } else if (!isObjectA && !isObjectB) { return String(a) === String(b) } else { return false } } function looseIndexOf (arr, val) { for (var i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) { return i } } return -1 } /** * Ensure a function is called only once. */ function once (fn) { var called = false; return function () { if (!called) { called = true; fn.apply(this, arguments); } } } var SSR_ATTR = 'data-server-rendered'; var ASSET_TYPES = [ 'component', 'directive', 'filter' ]; var LIFECYCLE_HOOKS = [ 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed', 'activated', 'deactivated', 'errorCaptured' ]; /* */ var config = ({ /** * Option merge strategies (used in core/util/options) */ optionMergeStrategies: Object.create(null), /** * Whether to suppress warnings. */ silent: false, /** * Show production mode tip message on boot? */ productionTip: process.env.NODE_ENV !== 'production', /** * Whether to enable devtools */ devtools: process.env.NODE_ENV !== 'production', /** * Whether to record perf */ performance: false, /** * Error handler for watcher errors */ errorHandler: null, /** * Warn handler for watcher warns */ warnHandler: null, /** * Ignore certain custom elements */ ignoredElements: [], /** * Custom user key aliases for v-on */ keyCodes: Object.create(null), /** * Check if a tag is reserved so that it cannot be registered as a * component. This is platform-dependent and may be overwritten. */ isReservedTag: no, /** * Check if an attribute is reserved so that it cannot be used as a component * prop. This is platform-dependent and may be overwritten. */ isReservedAttr: no, /** * Check if a tag is an unknown element. * Platform-dependent. */ isUnknownElement: no, /** * Get the namespace of an element */ getTagNamespace: noop, /** * Parse the real tag name for the specific platform. */ parsePlatformTagName: identity, /** * Check if an attribute must be bound using property, e.g. value * Platform-dependent. */ mustUseProp: no, /** * Exposed for legacy reasons */ _lifecycleHooks: LIFECYCLE_HOOKS }); /* */ /** * Check if a string starts with $ or _ */ function isReserved (str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F } /** * Define a property. */ function def (obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Parse simple path. */ var bailRE = /[^\w.$]/; function parsePath (path) { if (bailRE.test(path)) { return } var segments = path.split('.'); return function (obj) { for (var i = 0; i < segments.length; i++) { if (!obj) { return } obj = obj[segments[i]]; } return obj } } /* */ // can we use __proto__? var hasProto = '__proto__' in {}; // Browser environment sniffing var inBrowser = typeof window !== 'undefined'; var inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform; var weexPlatform = inWeex && WXEnvironment.platform.toLowerCase(); var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isEdge = UA && UA.indexOf('edge/') > 0; var isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android'); var isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios'); var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge; // Firefox has a "watch" function on Object.prototype... var nativeWatch = ({}).watch; var supportsPassive = false; if (inBrowser) { try { var opts = {}; Object.defineProperty(opts, 'passive', ({ get: function get () { /* istanbul ignore next */ supportsPassive = true; } })); // https://github.com/facebook/flow/issues/285 window.addEventListener('test-passive', null, opts); } catch (e) {} } // this needs to be lazy-evaled because vue may be required before // vue-server-renderer can set VUE_ENV var _isServer; var isServerRendering = function () { if (_isServer === undefined) { /* istanbul ignore if */ if (!inBrowser && typeof global !== 'undefined') { // detect presence of vue-server-renderer and avoid // Webpack shimming the process _isServer = global['process'].env.VUE_ENV === 'server'; } else { _isServer = false; } } return _isServer }; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ function isNative (Ctor) { return typeof Ctor === 'function' && /native code/.test(Ctor.toString()) } var hasSymbol = typeof Symbol !== 'undefined' && isNative(Symbol) && typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys); var _Set; /* istanbul ignore if */ // $flow-disable-line if (typeof Set !== 'undefined' && isNative(Set)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = (function () { function Set () { this.set = Object.create(null); } Set.prototype.has = function has (key) { return this.set[key] === true }; Set.prototype.add = function add (key) { this.set[key] = true; }; Set.prototype.clear = function clear () { this.set = Object.create(null); }; return Set; }()); } /* */ var warn = noop; var tip = noop; var generateComponentTrace = (noop); // work around flow check var formatComponentName = (noop); if (process.env.NODE_ENV !== 'production') { var hasConsole = typeof console !== 'undefined'; var classifyRE = /(?:^|[-_])(\w)/g; var classify = function (str) { return str .replace(classifyRE, function (c) { return c.toUpperCase(); }) .replace(/[-_]/g, ''); }; warn = function (msg, vm) { var trace = vm ? generateComponentTrace(vm) : ''; if (config.warnHandler) { config.warnHandler.call(null, msg, vm, trace); } else if (hasConsole && (!config.silent)) { console.error(("[Vue warn]: " + msg + trace)); } }; tip = function (msg, vm) { if (hasConsole && (!config.silent)) { console.warn("[Vue tip]: " + msg + ( vm ? generateComponentTrace(vm) : '' )); } }; formatComponentName = function (vm, includeFile) { if (vm.$root === vm) { return '<Root>' } var options = typeof vm === 'function' && vm.cid != null ? vm.options : vm._isVue ? vm.$options || vm.constructor.options : vm || {}; var name = options.name || options._componentTag; var file = options.__file; if (!name && file) { var match = file.match(/([^/\\]+)\.vue$/); name = match && match[1]; } return ( (name ? ("<" + (classify(name)) + ">") : "<Anonymous>") + (file && includeFile !== false ? (" at " + file) : '') ) }; var repeat = function (str, n) { var res = ''; while (n) { if (n % 2 === 1) { res += str; } if (n > 1) { str += str; } n >>= 1; } return res }; generateComponentTrace = function (vm) { if (vm._isVue && vm.$parent) { var tree = []; var currentRecursiveSequence = 0; while (vm) { if (tree.length > 0) { var last = tree[tree.length - 1]; if (last.constructor === vm.constructor) { currentRecursiveSequence++; vm = vm.$parent; continue } else if (currentRecursiveSequence > 0) { tree[tree.length - 1] = [last, currentRecursiveSequence]; currentRecursiveSequence = 0; } } tree.push(vm); vm = vm.$parent; } return '\n\nfound in\n\n' + tree .map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm) ? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)") : formatComponentName(vm))); }) .join('\n') } else { return ("\n\n(found in " + (formatComponentName(vm)) + ")") } }; } /* */ var uid = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ var Dep = function Dep () { this.id = uid++; this.subs = []; }; Dep.prototype.addSub = function addSub (sub) { this.subs.push(sub); }; Dep.prototype.removeSub = function removeSub (sub) { remove(this.subs, sub); }; Dep.prototype.depend = function depend () { if (Dep.target) { Dep.target.addDep(this); } }; Dep.prototype.notify = function notify () { // stabilize the subscriber list first var subs = this.subs.slice(); for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; // the current target watcher being evaluated. // this is globally unique because there could be only one // watcher being evaluated at any time. Dep.target = null; var targetStack = []; function pushTarget (_target) { if (Dep.target) { targetStack.push(Dep.target); } Dep.target = _target; } function popTarget () { Dep.target = targetStack.pop(); } /* */ var VNode = function VNode ( tag, data, children, text, elm, context, componentOptions, asyncFactory ) { this.tag = tag; this.data = data; this.children = children; this.text = text; this.elm = elm; this.ns = undefined; this.context = context; this.functionalContext = undefined; this.functionalOptions = undefined; this.functionalScopeId = undefined; this.key = data && data.key; this.componentOptions = componentOptions; this.componentInstance = undefined; this.parent = undefined; this.raw = false; this.isStatic = false; this.isRootInsert = true; this.isComment = false; this.isCloned = false; this.isOnce = false; this.asyncFactory = asyncFactory; this.asyncMeta = undefined; this.isAsyncPlaceholder = false; }; var prototypeAccessors = { child: { configurable: true } }; // DEPRECATED: alias for componentInstance for backwards compat. /* istanbul ignore next */ prototypeAccessors.child.get = function () { return this.componentInstance }; Object.defineProperties( VNode.prototype, prototypeAccessors ); var createEmptyVNode = function (text) { if ( text === void 0 ) text = ''; var node = new VNode(); node.text = text; node.isComment = true; return node }; function createTextVNode (val) { return new VNode(undefined, undefined, undefined, String(val)) } // optimized shallow clone // used for static nodes and slot nodes because they may be reused across // multiple renders, cloning them avoids errors when DOM manipulations rely // on their elm reference. function cloneVNode (vnode, deep) { var componentOptions = vnode.componentOptions; var cloned = new VNode( vnode.tag, vnode.data, vnode.children, vnode.text, vnode.elm, vnode.context, componentOptions, vnode.asyncFactory ); cloned.ns = vnode.ns; cloned.isStatic = vnode.isStatic; cloned.key = vnode.key; cloned.isComment = vnode.isComment; cloned.isCloned = true; if (deep) { if (vnode.children) { cloned.children = cloneVNodes(vnode.children, true); } if (componentOptions && componentOptions.children) { componentOptions.children = cloneVNodes(componentOptions.children, true); } } return cloned } function cloneVNodes (vnodes, deep) { var len = vnodes.length; var res = new Array(len); for (var i = 0; i < len; i++) { res[i] = cloneVNode(vnodes[i], deep); } return res } /* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto);[ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ] .forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var result = original.apply(this, args); var ob = this.__ob__; var inserted; switch (method) { case 'push': case 'unshift': inserted = args; break case 'splice': inserted = args.slice(2); break } if (inserted) { ob.observeArray(inserted); } // notify change ob.dep.notify(); return result }); }); /* */ var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * By default, when a reactive property is set, the new value is * also converted to become reactive. However when passing down props, * we don't want to force conversion because the value may be a nested value * under a frozen data structure. Converting it would defeat the optimization. */ var observerState = { shouldConvert: true }; /** * Observer class that are attached to each observed * object. Once attached, the observer converts target * object's property keys into getter/setters that * collect dependencies and dispatches updates. */ var Observer = function Observer (value) { this.value = value; this.dep = new Dep(); this.vmCount = 0; def(value, '__ob__', this); if (Array.isArray(value)) { var augment = hasProto ? protoAugment : copyAugment; augment(value, arrayMethods, arrayKeys); this.observeArray(value); } else { this.walk(value); } }; /** * Walk through each property and convert them into * getter/setters. This method should only be called when * value type is Object. */ Observer.prototype.walk = function walk (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { defineReactive(obj, keys[i], obj[keys[i]]); } }; /** * Observe a list of Array items. */ Observer.prototype.observeArray = function observeArray (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; // helpers /** * Augment an target Object or Array by intercepting * the prototype chain using __proto__ */ function protoAugment (target, src, keys) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * Augment an target Object or Array by defining * hidden properties. */ /* istanbul ignore next */ function copyAugment (target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ function observe (value, asRootData) { if (!isObject(value) || value instanceof VNode) { return } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ( observerState.shouldConvert && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value); } if (asRootData && ob) { ob.vmCount++; } return ob } /** * Define a reactive property on an Object. */ function defineReactive ( obj, key, val, customSetter, shallow ) { var dep = new Dep(); var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return } // cater for pre-defined getter/setters var getter = property && property.get; var setter = property && property.set; var childOb = !shallow && observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); if (Array.isArray(value)) { dependArray(value); } } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (process.env.NODE_ENV !== 'production' && customSetter) { customSetter(); } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = !shallow && observe(newVal); dep.notify(); } }); } /** * Set a property on an object. Adds the new property and * triggers change notification if the property doesn't * already exist. */ function set (target, key, val) { if (Array.isArray(target) && isValidArrayIndex(key)) { target.length = Math.max(target.length, key); target.splice(key, 1, val); return val } if (key in target && !(key in Object.prototype)) { target[key] = val; return val } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ); return val } if (!ob) { target[key] = val; return val } defineReactive(ob.value, key, val); ob.dep.notify(); return val } /** * Delete a property and trigger change if necessary. */ function del (target, key) { if (Array.isArray(target) && isValidArrayIndex(key)) { target.splice(key, 1); return } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid deleting properties on a Vue instance or its root $data ' + '- just set it to null.' ); return } if (!hasOwn(target, key)) { return } delete target[key]; if (!ob) { return } ob.dep.notify(); } /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ function dependArray (value) { for (var e = (void 0), i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); if (Array.isArray(e)) { dependArray(e); } } } /* */ /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. */ var strats = config.optionMergeStrategies; /** * Options with restrictions */ if (process.env.NODE_ENV !== 'production') { strats.el = strats.propsData = function (parent, child, vm, key) { if (!vm) { warn( "option \"" + key + "\" can only be used during instance " + 'creation with the `new` keyword.' ); } return defaultStrat(parent, child) }; } /** * Helper that recursively merges two data objects together. */ function mergeData (to, from) { if (!from) { return to } var key, toVal, fromVal; var keys = Object.keys(from); for (var i = 0; i < keys.length; i++) { key = keys[i]; toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set(to, key, fromVal); } else if (isPlainObject(toVal) && isPlainObject(fromVal)) { mergeData(toVal, fromVal); } } return to } /** * Data */ function mergeDataOrFn ( parentVal, childVal, vm ) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal } if (!parentVal) { return childVal } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn () { return mergeData( typeof childVal === 'function' ? childVal.call(this) : childVal, typeof parentVal === 'function' ? parentVal.call(this) : parentVal ) } } else { return function mergedInstanceDataFn () { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm) : childVal; var defaultData = typeof parentVal === 'function' ? parentVal.call(vm) : parentVal; if (instanceData) { return mergeData(instanceData, defaultData) } else { return defaultData } } } } strats.data = function ( parentVal, childVal, vm ) { if (!vm) { if (childVal && typeof childVal !== 'function') { process.env.NODE_ENV !== 'production' && warn( 'The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm ); return parentVal } return mergeDataOrFn(parentVal, childVal) } return mergeDataOrFn(parentVal, childVal, vm) }; /** * Hooks and props are merged as arrays. */ function mergeHook ( parentVal, childVal ) { return childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [childVal] : parentVal } LIFECYCLE_HOOKS.forEach(function (hook) { strats[hook] = mergeHook; }); /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets ( parentVal, childVal, vm, key ) { var res = Object.create(parentVal || null); if (childVal) { process.env.NODE_ENV !== 'production' && assertObjectType(key, childVal, vm); return extend(res, childVal) } else { return res } } ASSET_TYPES.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Watchers. * * Watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = function ( parentVal, childVal, vm, key ) { // work around Firefox's Object.prototype.watch... if (parentVal === nativeWatch) { parentVal = undefined; } if (childVal === nativeWatch) { childVal = undefined; } /* istanbul ignore if */ if (!childVal) { return Object.create(parentVal || null) } if (process.env.NODE_ENV !== 'production') { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = {}; extend(ret, parentVal); for (var key$1 in childVal) { var parent = ret[key$1]; var child = childVal[key$1]; if (parent && !Array.isArray(parent)) { parent = [parent]; } ret[key$1] = parent ? parent.concat(child) : Array.isArray(child) ? child : [child]; } return ret }; /** * Other object hashes. */ strats.props = strats.methods = strats.inject = strats.computed = function ( parentVal, childVal, vm, key ) { if (childVal && process.env.NODE_ENV !== 'production') { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = Object.create(null); extend(ret, parentVal); if (childVal) { extend(ret, childVal); } return ret }; strats.provide = mergeDataOrFn; /** * Default strategy. */ var defaultStrat = function (parentVal, childVal) { return childVal === undefined ? parentVal : childVal }; /** * Validate component names */ function checkComponents (options) { for (var key in options.components) { var lower = key.toLowerCase(); if (isBuiltInTag(lower) || config.isReservedTag(lower)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + key ); } } } /** * Ensure all props option syntax are normalized into the * Object-based format. */ function normalizeProps (options, vm) { var props = options.props; if (!props) { return } var res = {}; var i, val, name; if (Array.isArray(props)) { i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { name = camelize(val); res[name] = { type: null }; } else if (process.env.NODE_ENV !== 'production') { warn('props must be strings when using array syntax.'); } } } else if (isPlainObject(props)) { for (var key in props) { val = props[key]; name = camelize(key); res[name] = isPlainObject(val) ? val : { type: val }; } } else if (process.env.NODE_ENV !== 'production') { warn( "Invalid value for option \"props\": expected an Array or an Object, " + "but got " + (toRawType(props)) + ".", vm ); } options.props = res; } /** * Normalize all injections into Object-based format */ function normalizeInject (options, vm) { var inject = options.inject; var normalized = options.inject = {}; if (Array.isArray(inject)) { for (var i = 0; i < inject.length; i++) { normalized[inject[i]] = { from: inject[i] }; } } else if (isPlainObject(inject)) { for (var key in inject) { var val = inject[key]; normalized[key] = isPlainObject(val) ? extend({ from: key }, val) : { from: val }; } } else if (process.env.NODE_ENV !== 'production' && inject) { warn( "Invalid value for option \"inject\": expected an Array or an Object, " + "but got " + (toRawType(inject)) + ".", vm ); } } /** * Normalize raw function directives into object format. */ function normalizeDirectives (options) { var dirs = options.directives; if (dirs) { for (var key in dirs) { var def = dirs[key]; if (typeof def === 'function') { dirs[key] = { bind: def, update: def }; } } } } function assertObjectType (name, value, vm) { if (!isPlainObject(value)) { warn( "Invalid value for option \"" + name + "\": expected an Object, " + "but got " + (toRawType(value)) + ".", vm ); } } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. */ function mergeOptions ( parent, child, vm ) { if (process.env.NODE_ENV !== 'production') { checkComponents(child); } if (typeof child === 'function') { child = child.options; } normalizeProps(child, vm); normalizeInject(child, vm); normalizeDirectives(child); var extendsFrom = child.extends; if (extendsFrom) { parent = mergeOptions(parent, extendsFrom, vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = mergeOptions(parent, child.mixins[i], vm); } } var options = {}; var key; for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField (key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. */ function resolveAsset ( options, type, id, warnMissing ) { /* istanbul ignore if */ if (typeof id !== 'string') { return } var assets = options[type]; // check local registration variations first if (hasOwn(assets, id)) { return assets[id] } var camelizedId = camelize(id); if (hasOwn(assets, camelizedId)) { return assets[camelizedId] } var PascalCaseId = capitalize(camelizedId); if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] } // fallback to prototype chain var res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; if (process.env.NODE_ENV !== 'production' && warnMissing && !res) { warn( 'Failed to resolve ' + type.slice(0, -1) + ': ' + id, options ); } return res } /* */ function validateProp ( key, propOptions, propsData, vm ) { var prop = propOptions[key]; var absent = !hasOwn(propsData, key); var value = propsData[key]; // handle boolean props if (isType(Boolean, prop.type)) { if (absent && !hasOwn(prop, 'default')) { value = false; } else if (!isType(String, prop.type) && (value === '' || value === hyphenate(key))) { value = true; } } // check default value if (value === undefined) { value = getPropDefaultValue(vm, prop, key); // since the default value is a fresh copy, // make sure to observe it. var prevShouldConvert = observerState.shouldConvert; observerState.shouldConvert = true; observe(value); observerState.shouldConvert = prevShouldConvert; } if (process.env.NODE_ENV !== 'production') { assertProp(prop, key, value, vm, absent); } return value } /** * Get the default value of a prop. */ function getPropDefaultValue (vm, prop, key) { // no default, return undefined if (!hasOwn(prop, 'default')) { return undefined } var def = prop.default; // warn against non-factory defaults for Object & Array if (process.env.NODE_ENV !== 'production' && isObject(def)) { warn( 'Invalid default value for prop "' + key + '": ' + 'Props with type Object/Array must use a factory function ' + 'to return the default value.', vm ); } // the raw prop value was also undefined from previous render, // return previous default value to avoid unnecessary watcher trigger if (vm && vm.$options.propsData && vm.$options.propsData[key] === undefined && vm._props[key] !== undefined ) { return vm._props[key] } // call factory function for non-Function types // a value is Function if its prototype is function even across different execution context return typeof def === 'function' && getType(prop.type) !== 'Function' ? def.call(vm) : def } /** * Assert whether a prop is valid. */ function assertProp ( prop, name, value, vm, absent ) { if (prop.required && absent) { warn( 'Missing required prop: "' + name + '"', vm ); return } if (value == null && !prop.required) { return } var type = prop.type; var valid = !type || type === true; var expectedTypes = []; if (type) { if (!Array.isArray(type)) { type = [type]; } for (var i = 0; i < type.length && !valid; i++) { var assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType || ''); valid = assertedType.valid; } } if (!valid) { warn( "Invalid prop: type check failed for prop \"" + name + "\"." + " Expected " + (expectedTypes.map(capitalize).join(', ')) + ", got " + (toRawType(value)) + ".", vm ); return } var validator = prop.validator; if (validator) { if (!validator(value)) { warn( 'Invalid prop: custom validator check failed for prop "' + name + '".', vm ); } } } var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/; function assertType (value, type) { var valid; var expectedType = getType(type); if (simpleCheckRE.test(expectedType)) { var t = typeof value; valid = t === expectedType.toLowerCase(); // for primitive wrapper objects if (!valid && t === 'object') { valid = value instanceof type; } } else if (expectedType === 'Object') { valid = isPlainObject(value); } else if (expectedType === 'Array') { valid = Array.isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType } } /** * Use function string name to check built-in types, * because a simple equality check will fail when running * across different vms / iframes. */ function getType (fn) { var match = fn && fn.toString().match(/^\s*function (\w+)/); return match ? match[1] : '' } function isType (type, fn) { if (!Array.isArray(fn)) { return getType(fn) === getType(type) } for (var i = 0, len = fn.length; i < len; i++) { if (getType(fn[i]) === getType(type)) { return true } } /* istanbul ignore next */ return false } /* */ function handleError (err, vm, info) { if (vm) { var cur = vm; while ((cur = cur.$parent)) { var hooks = cur.$options.errorCaptured; if (hooks) { for (var i = 0; i < hooks.length; i++) { try { var capture = hooks[i].call(cur, err, vm, info) === false; if (capture) { return } } catch (e) { globalHandleError(e, cur, 'errorCaptured hook'); } } } } } globalHandleError(err, vm, info); } function globalHandleError (err, vm, info) { if (config.errorHandler) { try { return config.errorHandler.call(null, err, vm, info) } catch (e) { logError(e, null, 'config.errorHandler'); } } logError(err, vm, info); } function logError (err, vm, info) { if (process.env.NODE_ENV !== 'production') { warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm); } /* istanbul ignore else */ if ((inBrowser || inWeex) && typeof console !== 'undefined') { console.error(err); } else { throw err } } /* */ /* globals MessageChannel */ var callbacks = []; var pending = false; function flushCallbacks () { pending = false; var copies = callbacks.slice(0); callbacks.length = 0; for (var i = 0; i < copies.length; i++) { copies[i](); } } // Here we have async deferring wrappers using both micro and macro tasks. // In < 2.4 we used micro tasks everywhere, but there are some scenarios where // micro tasks have too high a priority and fires in between supposedly // sequential events (e.g. #4521, #6690) or even between bubbling of the same // event (#6566). However, using macro tasks everywhere also has subtle problems // when state is changed right before repaint (e.g. #6813, out-in transitions). // Here we use micro task by default, but expose a way to force macro task when // needed (e.g. in event handlers attached by v-on). var microTimerFunc; var macroTimerFunc; var useMacroTask = false; // Determine (macro) Task defer implementation. // Technically setImmediate should be the ideal choice, but it's only available // in IE. The only polyfill that consistently queues the callback after all DOM // events triggered in the same loop is by using MessageChannel. /* istanbul ignore if */ if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) { macroTimerFunc = function () { setImmediate(flushCallbacks); }; } else if (typeof MessageChannel !== 'undefined' && ( isNative(MessageChannel) || // PhantomJS MessageChannel.toString() === '[object MessageChannelConstructor]' )) { var channel = new MessageChannel(); var port = channel.port2; channel.port1.onmessage = flushCallbacks; macroTimerFunc = function () { port.postMessage(1); }; } else { /* istanbul ignore next */ macroTimerFunc = function () { setTimeout(flushCallbacks, 0); }; } // Determine MicroTask defer implementation. /* istanbul ignore next, $flow-disable-line */ if (typeof Promise !== 'undefined' && isNative(Promise)) { var p = Promise.resolve(); microTimerFunc = function () { p.then(flushCallbacks); // in problematic UIWebViews, Promise.then doesn't completely break, but // it can get stuck in a weird state where callbacks are pushed into the // microtask queue but the queue isn't being flushed, until the browser // needs to do some other work, e.g. handle a timer. Therefore we can // "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) { setTimeout(noop); } }; } else { // fallback to macro microTimerFunc = macroTimerFunc; } /** * Wrap a function so that if any code inside triggers state change, * the changes are queued using a Task instead of a MicroTask. */ function withMacroTask (fn) { return fn._withTask || (fn._withTask = function () { useMacroTask = true; var res = fn.apply(null, arguments); useMacroTask = false; return res }) } function nextTick (cb, ctx) { var _resolve; callbacks.push(function () { if (cb) { try { cb.call(ctx); } catch (e) { handleError(e, ctx, 'nextTick'); } } else if (_resolve) { _resolve(ctx); } }); if (!pending) { pending = true; if (useMacroTask) { macroTimerFunc(); } else { microTimerFunc(); } } // $flow-disable-line if (!cb && typeof Promise !== 'undefined') { return new Promise(function (resolve) { _resolve = resolve; }) } } /* */ var mark; var measure; if (process.env.NODE_ENV !== 'production') { var perf = inBrowser && window.performance; /* istanbul ignore if */ if ( perf && perf.mark && perf.measure && perf.clearMarks && perf.clearMeasures ) { mark = function (tag) { return perf.mark(tag); }; measure = function (name, startTag, endTag) { perf.measure(name, startTag, endTag); perf.clearMarks(startTag); perf.clearMarks(endTag); perf.clearMeasures(name); }; } } /* not type checking this file because flow doesn't play well with Proxy */ var initProxy; if (process.env.NODE_ENV !== 'production') { var allowedGlobals = makeMap( 'Infinity,undefined,NaN,isFinite,isNaN,' + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' + 'require' // for Webpack/Browserify ); var warnNonPresent = function (target, key) { warn( "Property or method \"" + key + "\" is not defined on the instance but " + 'referenced during render. Make sure that this property is reactive, ' + 'either in the data option, or for class-based components, by ' + 'initializing the property. ' + 'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.', target ); }; var hasProxy = typeof Proxy !== 'undefined' && Proxy.toString().match(/native code/); if (hasProxy) { var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact'); config.keyCodes = new Proxy(config.keyCodes, { set: function set (target, key, value) { if (isBuiltInModifier(key)) { warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key)); return false } else { target[key] = value; return true } } }); } var hasHandler = { has: function has (target, key) { var has = key in target; var isAllowed = allowedGlobals(key) || key.charAt(0) === '_'; if (!has && !isAllowed) { warnNonPresent(target, key); } return has || !isAllowed } }; var getHandler = { get: function get (target, key) { if (typeof key === 'string' && !(key in target)) { warnNonPresent(target, key); } return target[key] } }; initProxy = function initProxy (vm) { if (hasProxy) { // determine which proxy handler to use var options = vm.$options; var handlers = options.render && options.render._withStripped ? getHandler : hasHandler; vm._renderProxy = new Proxy(vm, handlers); } else { vm._renderProxy = vm; } }; } /* */ var seenObjects = new _Set(); /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. */ function traverse (val) { _traverse(val, seenObjects); seenObjects.clear(); } function _traverse (val, seen) { var i, keys; var isA = Array.isArray(val); if ((!isA && !isObject(val)) || !Object.isExtensible(val)) { return } if (val.__ob__) { var depId = val.__ob__.dep.id; if (seen.has(depId)) { return } seen.add(depId); } if (isA) { i = val.length; while (i--) { _traverse(val[i], seen); } } else { keys = Object.keys(val); i = keys.length; while (i--) { _traverse(val[keys[i]], seen); } } } /* */ var normalizeEvent = cached(function (name) { var passive = name.charAt(0) === '&'; name = passive ? name.slice(1) : name; var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first name = once$$1 ? name.slice(1) : name; var capture = name.charAt(0) === '!'; name = capture ? name.slice(1) : name; return { name: name, once: once$$1, capture: capture, passive: passive } }); function createFnInvoker (fns) { function invoker () { var arguments$1 = arguments; var fns = invoker.fns; if (Array.isArray(fns)) { var cloned = fns.slice(); for (var i = 0; i < cloned.length; i++) { cloned[i].apply(null, arguments$1); } } else { // return handler return value for single handlers return fns.apply(null, arguments) } } invoker.fns = fns; return invoker } function updateListeners ( on, oldOn, add, remove$$1, vm ) { var name, cur, old, event; for (name in on) { cur = on[name]; old = oldOn[name]; event = normalizeEvent(name); if (isUndef(cur)) { process.env.NODE_ENV !== 'production' && warn( "Invalid handler for event \"" + (event.name) + "\": got " + String(cur), vm ); } else if (isUndef(old)) { if (isUndef(cur.fns)) { cur = on[name] = createFnInvoker(cur); } add(event.name, cur, event.once, event.capture, event.passive); } else if (cur !== old) { old.fns = cur; on[name] = old; } } for (name in oldOn) { if (isUndef(on[name])) { event = normalizeEvent(name); remove$$1(event.name, oldOn[name], event.capture); } } } /* */ function mergeVNodeHook (def, hookKey, hook) { if (def instanceof VNode) { def = def.data.hook || (def.data.hook = {}); } var invoker; var oldHook = def[hookKey]; function wrappedHook () { hook.apply(this, arguments); // important: remove merged hook to ensure it's called only once // and prevent memory leak remove(invoker.fns, wrappedHook); } if (isUndef(oldHook)) { // no existing hook invoker = createFnInvoker([wrappedHook]); } else { /* istanbul ignore if */ if (isDef(oldHook.fns) && isTrue(oldHook.merged)) { // already a merged invoker invoker = oldHook; invoker.fns.push(wrappedHook); } else { // existing plain hook invoker = createFnInvoker([oldHook, wrappedHook]); } } invoker.merged = true; def[hookKey] = invoker; } /* */ function extractPropsFromVNodeData ( data, Ctor, tag ) { // we are only extracting raw values here. // validation and default values are handled in the child // component itself. var propOptions = Ctor.options.props; if (isUndef(propOptions)) { return } var res = {}; var attrs = data.attrs; var props = data.props; if (isDef(attrs) || isDef(props)) { for (var key in propOptions) { var altKey = hyphenate(key); if (process.env.NODE_ENV !== 'production') { var keyInLowerCase = key.toLowerCase(); if ( key !== keyInLowerCase && attrs && hasOwn(attrs, keyInLowerCase) ) { tip( "Prop \"" + keyInLowerCase + "\" is passed to component " + (formatComponentName(tag || Ctor)) + ", but the declared prop name is" + " \"" + key + "\". " + "Note that HTML attributes are case-insensitive and camelCased " + "props need to use their kebab-case equivalents when using in-DOM " + "templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"." ); } } checkProp(res, props, key, altKey, true) || checkProp(res, attrs, key, altKey, false); } } return res } function checkProp ( res, hash, key, altKey, preserve ) { if (isDef(hash)) { if (hasOwn(hash, key)) { res[key] = hash[key]; if (!preserve) { delete hash[key]; } return true } else if (hasOwn(hash, altKey)) { res[key] = hash[altKey]; if (!preserve) { delete hash[altKey]; } return true } } return false } /* */ // The template compiler attempts to minimize the need for normalization by // statically analyzing the template at compile time. // // For plain HTML markup, normalization can be completely skipped because the // generated render function is guaranteed to return Array<VNode>. There are // two cases where extra normalization is needed: // 1. When the children contains components - because a functional component // may return an Array instead of a single root. In this case, just a simple // normalization is needed - if any child is an Array, we flatten the whole // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep // because functional components already normalize their own children. function simpleNormalizeChildren (children) { for (var i = 0; i < children.length; i++) { if (Array.isArray(children[i])) { return Array.prototype.concat.apply([], children) } } return children } // 2. When the children contains constructs that always generated nested Arrays, // e.g. <template>, <slot>, v-for, or when the children is provided by user // with hand-written render functions / JSX. In such cases a full normalization // is needed to cater to all possible types of children values. function normalizeChildren (children) { return isPrimitive(children) ? [createTextVNode(children)] : Array.isArray(children) ? normalizeArrayChildren(children) : undefined } function isTextNode (node) { return isDef(node) && isDef(node.text) && isFalse(node.isComment) } function normalizeArrayChildren (children, nestedIndex) { var res = []; var i, c, lastIndex, last; for (i = 0; i < children.length; i++) { c = children[i]; if (isUndef(c) || typeof c === 'boolean') { continue } lastIndex = res.length - 1; last = res[lastIndex]; // nested if (Array.isArray(c)) { if (c.length > 0) { c = normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i)); // merge adjacent text nodes if (isTextNode(c[0]) && isTextNode(last)) { res[lastIndex] = createTextVNode(last.text + (c[0]).text); c.shift(); } res.push.apply(res, c); } } else if (isPrimitive(c)) { if (isTextNode(last)) { // merge adjacent text nodes // this is necessary for SSR hydration because text nodes are // essentially merged when rendered to HTML strings res[lastIndex] = createTextVNode(last.text + c); } else if (c !== '') { // convert primitive to vnode res.push(createTextVNode(c)); } } else { if (isTextNode(c) && isTextNode(last)) { // merge adjacent text nodes res[lastIndex] = createTextVNode(last.text + c.text); } else { // default key for nested array children (likely generated by v-for) if (isTrue(children._isVList) && isDef(c.tag) && isUndef(c.key) && isDef(nestedIndex)) { c.key = "__vlist" + nestedIndex + "_" + i + "__"; } res.push(c); } } } return res } /* */ function ensureCtor (comp, base) { if ( comp.__esModule || (hasSymbol && comp[Symbol.toStringTag] === 'Module') ) { comp = comp.default; } return isObject(comp) ? base.extend(comp) : comp } function createAsyncPlaceholder ( factory, data, context, children, tag ) { var node = createEmptyVNode(); node.asyncFactory = factory; node.asyncMeta = { data: data, context: context, children: children, tag: tag }; return node } function resolveAsyncComponent ( factory, baseCtor, context ) { if (isTrue(factory.error) && isDef(factory.errorComp)) { return factory.errorComp } if (isDef(factory.resolved)) { return factory.resolved } if (isTrue(factory.loading) && isDef(factory.loadingComp)) { return factory.loadingComp } if (isDef(factory.contexts)) { // already pending factory.contexts.push(context); } else { var contexts = factory.contexts = [context]; var sync = true; var forceRender = function () { for (var i = 0, l = contexts.length; i < l; i++) { contexts[i].$forceUpdate(); } }; var resolve = once(function (res) { // cache resolved factory.resolved = ensureCtor(res, baseCtor); // invoke callbacks only if this is not a synchronous resolve // (async resolves are shimmed as synchronous during SSR) if (!sync) { forceRender(); } }); var reject = once(function (reason) { process.env.NODE_ENV !== 'production' && warn( "Failed to resolve async component: " + (String(factory)) + (reason ? ("\nReason: " + reason) : '') ); if (isDef(factory.errorComp)) { factory.error = true; forceRender(); } }); var res = factory(resolve, reject); if (isObject(res)) { if (typeof res.then === 'function') { // () => Promise if (isUndef(factory.resolved)) { res.then(resolve, reject); } } else if (isDef(res.component) && typeof res.component.then === 'function') { res.component.then(resolve, reject); if (isDef(res.error)) { factory.errorComp = ensureCtor(res.error, baseCtor); } if (isDef(res.loading)) { factory.loadingComp = ensureCtor(res.loading, baseCtor); if (res.delay === 0) { factory.loading = true; } else { setTimeout(function () { if (isUndef(factory.resolved) && isUndef(factory.error)) { factory.loading = true; forceRender(); } }, res.delay || 200); } } if (isDef(res.timeout)) { setTimeout(function () { if (isUndef(factory.resolved)) { reject( process.env.NODE_ENV !== 'production' ? ("timeout (" + (res.timeout) + "ms)") : null ); } }, res.timeout); } } } sync = false; // return in case resolved synchronously return factory.loading ? factory.loadingComp : factory.resolved } } /* */ function isAsyncPlaceholder (node) { return node.isComment && node.asyncFactory } /* */ function getFirstComponentChild (children) { if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var c = children[i]; if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) { return c } } } } /* */ /* */ function initEvents (vm) { vm._events = Object.create(null); vm._hasHookEvent = false; // init parent attached events var listeners = vm.$options._parentListeners; if (listeners) { updateComponentListeners(vm, listeners); } } var target; function add (event, fn, once) { if (once) { target.$once(event, fn); } else { target.$on(event, fn); } } function remove$1 (event, fn) { target.$off(event, fn); } function updateComponentListeners ( vm, listeners, oldListeners ) { target = vm; updateListeners(listeners, oldListeners || {}, add, remove$1, vm); target = undefined; } function eventsMixin (Vue) { var hookRE = /^hook:/; Vue.prototype.$on = function (event, fn) { var this$1 = this; var vm = this; if (Array.isArray(event)) { for (var i = 0, l = event.length; i < l; i++) { this$1.$on(event[i], fn); } } else { (vm._events[event] || (vm._events[event] = [])).push(fn); // optimize hook:event cost by using a boolean flag marked at registration // instead of a hash lookup if (hookRE.test(event)) { vm._hasHookEvent = true; } } return vm }; Vue.prototype.$once = function (event, fn) { var vm = this; function on () { vm.$off(event, on); fn.apply(vm, arguments); } on.fn = fn; vm.$on(event, on); return vm }; Vue.prototype.$off = function (event, fn) { var this$1 = this; var vm = this; // all if (!arguments.length) { vm._events = Object.create(null); return vm } // array of events if (Array.isArray(event)) { for (var i = 0, l = event.length; i < l; i++) { this$1.$off(event[i], fn); } return vm } // specific event var cbs = vm._events[event]; if (!cbs) { return vm } if (!fn) { vm._events[event] = null; return vm } if (fn) { // specific handler var cb; var i$1 = cbs.length; while (i$1--) { cb = cbs[i$1]; if (cb === fn || cb.fn === fn) { cbs.splice(i$1, 1); break } } } return vm }; Vue.prototype.$emit = function (event) { var vm = this; if (process.env.NODE_ENV !== 'production') { var lowerCaseEvent = event.toLowerCase(); if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) { tip( "Event \"" + lowerCaseEvent + "\" is emitted in component " + (formatComponentName(vm)) + " but the handler is registered for \"" + event + "\". " + "Note that HTML attributes are case-insensitive and you cannot use " + "v-on to listen to camelCase events when using in-DOM templates. " + "You should probably use \"" + (hyphenate(event)) + "\" instead of \"" + event + "\"." ); } } var cbs = vm._events[event]; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; var args = toArray(arguments, 1); for (var i = 0, l = cbs.length; i < l; i++) { try { cbs[i].apply(vm, args); } catch (e) { handleError(e, vm, ("event handler for \"" + event + "\"")); } } } return vm }; } /* */ /** * Runtime helper for resolving raw children VNodes into a slot object. */ function resolveSlots ( children, context ) { var slots = {}; if (!children) { return slots } for (var i = 0, l = children.length; i < l; i++) { var child = children[i]; var data = child.data; // remove slot attribute if the node is resolved as a Vue slot node if (data && data.attrs && data.attrs.slot) { delete data.attrs.slot; } // named slots should only be respected if the vnode was rendered in the // same context. if ((child.context === context || child.functionalContext === context) && data && data.slot != null ) { var name = child.data.slot; var slot = (slots[name] || (slots[name] = [])); if (child.tag === 'template') { slot.push.apply(slot, child.children); } else { slot.push(child); } } else { (slots.default || (slots.default = [])).push(child); } } // ignore slots that contains only whitespace for (var name$1 in slots) { if (slots[name$1].every(isWhitespace)) { delete slots[name$1]; } } return slots } function isWhitespace (node) { return (node.isComment && !node.asyncFactory) || node.text === ' ' } function resolveScopedSlots ( fns, // see flow/vnode res ) { res = res || {}; for (var i = 0; i < fns.length; i++) { if (Array.isArray(fns[i])) { resolveScopedSlots(fns[i], res); } else { res[fns[i].key] = fns[i].fn; } } return res } /* */ var activeInstance = null; var isUpdatingChildComponent = false; function initLifecycle (vm) { var options = vm.$options; // locate first non-abstract parent var parent = options.parent; if (parent && !options.abstract) { while (parent.$options.abstract && parent.$parent) { parent = parent.$parent; } parent.$children.push(vm); } vm.$parent = parent; vm.$root = parent ? parent.$root : vm; vm.$children = []; vm.$refs = {}; vm._watcher = null; vm._inactive = null; vm._directInactive = false; vm._isMounted = false; vm._isDestroyed = false; vm._isBeingDestroyed = false; } function lifecycleMixin (Vue) { Vue.prototype._update = function (vnode, hydrating) { var vm = this; if (vm._isMounted) { callHook(vm, 'beforeUpdate'); } var prevEl = vm.$el; var prevVnode = vm._vnode; var prevActiveInstance = activeInstance; activeInstance = vm; vm._vnode = vnode; // Vue.prototype.__patch__ is injected in entry points // based on the rendering backend used. if (!prevVnode) { // initial render vm.$el = vm.__patch__( vm.$el, vnode, hydrating, false /* removeOnly */, vm.$options._parentElm, vm.$options._refElm ); // no need for the ref nodes after initial patch // this prevents keeping a detached DOM tree in memory (#5851) vm.$options._parentElm = vm.$options._refElm = null; } else { // updates vm.$el = vm.__patch__(prevVnode, vnode); } activeInstance = prevActiveInstance; // update __vue__ reference if (prevEl) { prevEl.__vue__ = null; } if (vm.$el) { vm.$el.__vue__ = vm; } // if parent is an HOC, update its $el as well if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) { vm.$parent.$el = vm.$el; } // updated hook is called by the scheduler to ensure that children are // updated in a parent's updated hook. }; Vue.prototype.$forceUpdate = function () { var vm = this; if (vm._watcher) { vm._watcher.update(); } }; Vue.prototype.$destroy = function () { var vm = this; if (vm._isBeingDestroyed) { return } callHook(vm, 'beforeDestroy'); vm._isBeingDestroyed = true; // remove self from parent var parent = vm.$parent; if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) { remove(parent.$children, vm); } // teardown watchers if (vm._watcher) { vm._watcher.teardown(); } var i = vm._watchers.length; while (i--) { vm._watchers[i].teardown(); } // remove reference from data ob // frozen object may not have observer. if (vm._data.__ob__) { vm._data.__ob__.vmCount--; } // call the last hook... vm._isDestroyed = true; // invoke destroy hooks on current rendered tree vm.__patch__(vm._vnode, null); // fire destroyed hook callHook(vm, 'destroyed'); // turn off all instance listeners. vm.$off(); // remove __vue__ reference if (vm.$el) { vm.$el.__vue__ = null; } // release circular reference (#6759) if (vm.$vnode) { vm.$vnode.parent = null; } }; } function mountComponent ( vm, el, hydrating ) { vm.$el = el; if (!vm.$options.render) { vm.$options.render = createEmptyVNode; if (process.env.NODE_ENV !== 'production') { /* istanbul ignore if */ if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') || vm.$options.el || el) { warn( 'You are using the runtime-only build of Vue where the template ' + 'compiler is not available. Either pre-compile the templates into ' + 'render functions, or use the compiler-included build.', vm ); } else { warn( 'Failed to mount component: template or render function not defined.', vm ); } } } callHook(vm, 'beforeMount'); var updateComponent; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { updateComponent = function () { var name = vm._name; var id = vm._uid; var startTag = "vue-perf-start:" + id; var endTag = "vue-perf-end:" + id; mark(startTag); var vnode = vm._render(); mark(endTag); measure(("vue " + name + " render"), startTag, endTag); mark(startTag); vm._update(vnode, hydrating); mark(endTag); measure(("vue " + name + " patch"), startTag, endTag); }; } else { updateComponent = function () { vm._update(vm._render(), hydrating); }; } vm._watcher = new Watcher(vm, updateComponent, noop); hydrating = false; // manually mounted instance, call mounted on self // mounted is called for render-created child components in its inserted hook if (vm.$vnode == null) { vm._isMounted = true; callHook(vm, 'mounted'); } return vm } function updateChildComponent ( vm, propsData, listeners, parentVnode, renderChildren ) { if (process.env.NODE_ENV !== 'production') { isUpdatingChildComponent = true; } // determine whether component has slot children // we need to do this before overwriting $options._renderChildren var hasChildren = !!( renderChildren || // has new static slots vm.$options._renderChildren || // has old static slots parentVnode.data.scopedSlots || // has new scoped slots vm.$scopedSlots !== emptyObject // has old scoped slots ); vm.$options._parentVnode = parentVnode; vm.$vnode = parentVnode; // update vm's placeholder node without re-render if (vm._vnode) { // update child tree's parent vm._vnode.parent = parentVnode; } vm.$options._renderChildren = renderChildren; // update $attrs and $listeners hash // these are also reactive so they may trigger child update if the child // used them during render vm.$attrs = (parentVnode.data && parentVnode.data.attrs) || emptyObject; vm.$listeners = listeners || emptyObject; // update props if (propsData && vm.$options.props) { observerState.shouldConvert = false; var props = vm._props; var propKeys = vm.$options._propKeys || []; for (var i = 0; i < propKeys.length; i++) { var key = propKeys[i]; props[key] = validateProp(key, vm.$options.props, propsData, vm); } observerState.shouldConvert = true; // keep a copy of raw propsData vm.$options.propsData = propsData; } // update listeners if (listeners) { var oldListeners = vm.$options._parentListeners; vm.$options._parentListeners = listeners; updateComponentListeners(vm, listeners, oldListeners); } // resolve slots + force update if has children if (hasChildren) { vm.$slots = resolveSlots(renderChildren, parentVnode.context); vm.$forceUpdate(); } if (process.env.NODE_ENV !== 'production') { isUpdatingChildComponent = false; } } function isInInactiveTree (vm) { while (vm && (vm = vm.$parent)) { if (vm._inactive) { return true } } return false } function activateChildComponent (vm, direct) { if (direct) { vm._directInactive = false; if (isInInactiveTree(vm)) { return } } else if (vm._directInactive) { return } if (vm._inactive || vm._inactive === null) { vm._inactive = false; for (var i = 0; i < vm.$children.length; i++) { activateChildComponent(vm.$children[i]); } callHook(vm, 'activated'); } } function deactivateChildComponent (vm, direct) { if (direct) { vm._directInactive = true; if (isInInactiveTree(vm)) { return } } if (!vm._inactive) { vm._inactive = true; for (var i = 0; i < vm.$children.length; i++) { deactivateChildComponent(vm.$children[i]); } callHook(vm, 'deactivated'); } } function callHook (vm, hook) { var handlers = vm.$options[hook]; if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { try { handlers[i].call(vm); } catch (e) { handleError(e, vm, (hook + " hook")); } } } if (vm._hasHookEvent) { vm.$emit('hook:' + hook); } } /* */ var MAX_UPDATE_COUNT = 100; var queue = []; var activatedChildren = []; var has = {}; var circular = {}; var waiting = false; var flushing = false; var index = 0; /** * Reset the scheduler's state. */ function resetSchedulerState () { index = queue.length = activatedChildren.length = 0; has = {}; if (process.env.NODE_ENV !== 'production') { circular = {}; } waiting = flushing = false; } /** * Flush both queues and run the watchers. */ function flushSchedulerQueue () { flushing = true; var watcher, id; // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child) // 2. A component's user watchers are run before its render watcher (because // user watchers are created before the render watcher) // 3. If a component is destroyed during a parent component's watcher run, // its watchers can be skipped. queue.sort(function (a, b) { return a.id - b.id; }); // do not cache length because more watchers might be pushed // as we run existing watchers for (index = 0; index < queue.length; index++) { watcher = queue[index]; id = watcher.id; has[id] = null; watcher.run(); // in dev build, check and stop circular updates. if (process.env.NODE_ENV !== 'production' && has[id] != null) { circular[id] = (circular[id] || 0) + 1; if (circular[id] > MAX_UPDATE_COUNT) { warn( 'You may have an infinite update loop ' + ( watcher.user ? ("in watcher with expression \"" + (watcher.expression) + "\"") : "in a component render function." ), watcher.vm ); break } } } // keep copies of post queues before resetting state var activatedQueue = activatedChildren.slice(); var updatedQueue = queue.slice(); resetSchedulerState(); // call component updated and activated hooks callActivatedHooks(activatedQueue); callUpdatedHooks(updatedQueue); // devtool hook /* istanbul ignore if */ if (devtools && config.devtools) { devtools.emit('flush'); } } function callUpdatedHooks (queue) { var i = queue.length; while (i--) { var watcher = queue[i]; var vm = watcher.vm; if (vm._watcher === watcher && vm._isMounted) { callHook(vm, 'updated'); } } } /** * Queue a kept-alive component that was activated during patch. * The queue will be processed after the entire tree has been patched. */ function queueActivatedComponent (vm) { // setting _inactive to false here so that a render function can // rely on checking whether it's in an inactive tree (e.g. router-view) vm._inactive = false; activatedChildren.push(vm); } function callActivatedHooks (queue) { for (var i = 0; i < queue.length; i++) { queue[i]._inactive = true; activateChildComponent(queue[i], true /* true */); } } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. */ function queueWatcher (watcher) { var id = watcher.id; if (has[id] == null) { has[id] = true; if (!flushing) { queue.push(watcher); } else { // if already flushing, splice the watcher based on its id // if already past its id, it will be run next immediately. var i = queue.length - 1; while (i > index && queue[i].id > watcher.id) { i--; } queue.splice(i + 1, 0, watcher); } // queue the flush if (!waiting) { waiting = true; nextTick(flushSchedulerQueue); } } } /* */ var uid$2 = 0; /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. */ var Watcher = function Watcher ( vm, expOrFn, cb, options ) { this.vm = vm; vm._watchers.push(this); // options if (options) { this.deep = !!options.deep; this.user = !!options.user; this.lazy = !!options.lazy; this.sync = !!options.sync; } else { this.deep = this.user = this.lazy = this.sync = false; } this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = new _Set(); this.newDepIds = new _Set(); this.expression = process.env.NODE_ENV !== 'production' ? expOrFn.toString() : ''; // parse expression for getter if (typeof expOrFn === 'function') { this.getter = expOrFn; } else { this.getter = parsePath(expOrFn); if (!this.getter) { this.getter = function () {}; process.env.NODE_ENV !== 'production' && warn( "Failed watching path: \"" + expOrFn + "\" " + 'Watcher only accepts simple dot-delimited paths. ' + 'For full control, use a function instead.', vm ); } } this.value = this.lazy ? undefined : this.get(); }; /** * Evaluate the getter, and re-collect dependencies. */ Watcher.prototype.get = function get () { pushTarget(this); var value; var vm = this.vm; try { value = this.getter.call(vm, vm); } catch (e) { if (this.user) { handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\"")); } else { throw e } } finally { // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } popTarget(); this.cleanupDeps(); } return value }; /** * Add a dependency to this directive. */ Watcher.prototype.addDep = function addDep (dep) { var id = dep.id; if (!this.newDepIds.has(id)) { this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.cleanupDeps = function cleanupDeps () { var this$1 = this; var i = this.deps.length; while (i--) { var dep = this$1.deps[i]; if (!this$1.newDepIds.has(dep.id)) { dep.removeSub(this$1); } } var tmp = this.depIds; this.depIds = this.newDepIds; this.newDepIds = tmp; this.newDepIds.clear(); tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; this.newDeps.length = 0; }; /** * Subscriber interface. * Will be called when a dependency changes. */ Watcher.prototype.update = function update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true; } else if (this.sync) { this.run(); } else { queueWatcher(this); } }; /** * Scheduler job interface. * Will be called by the scheduler. */ Watcher.prototype.run = function run () { if (this.active) { var value = this.get(); if ( value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep ) { // set new value var oldValue = this.value; this.value = value; if (this.user) { try { this.cb.call(this.vm, value, oldValue); } catch (e) { handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\"")); } } else { this.cb.call(this.vm, value, oldValue); } } } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function evaluate () { this.value = this.get(); this.dirty = false; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function depend () { var this$1 = this; var i = this.deps.length; while (i--) { this$1.deps[i].depend(); } }; /** * Remove self from all dependencies' subscriber list. */ Watcher.prototype.teardown = function teardown () { var this$1 = this; if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed. if (!this.vm._isBeingDestroyed) { remove(this.vm._watchers, this); } var i = this.deps.length; while (i--) { this$1.deps[i].removeSub(this$1); } this.active = false; } }; /* */ var sharedPropertyDefinition = { enumerable: true, configurable: true, get: noop, set: noop }; function proxy (target, sourceKey, key) { sharedPropertyDefinition.get = function proxyGetter () { return this[sourceKey][key] }; sharedPropertyDefinition.set = function proxySetter (val) { this[sourceKey][key] = val; }; Object.defineProperty(target, key, sharedPropertyDefinition); } function initState (vm) { vm._watchers = []; var opts = vm.$options; if (opts.props) { initProps(vm, opts.props); } if (opts.methods) { initMethods(vm, opts.methods); } if (opts.data) { initData(vm); } else { observe(vm._data = {}, true /* asRootData */); } if (opts.computed) { initComputed(vm, opts.computed); } if (opts.watch && opts.watch !== nativeWatch) { initWatch(vm, opts.watch); } } function initProps (vm, propsOptions) { var propsData = vm.$options.propsData || {}; var props = vm._props = {}; // cache prop keys so that future props updates can iterate using Array // instead of dynamic object key enumeration. var keys = vm.$options._propKeys = []; var isRoot = !vm.$parent; // root instance props should be converted observerState.shouldConvert = isRoot; var loop = function ( key ) { keys.push(key); var value = validateProp(key, propsOptions, propsData, vm); /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { var hyphenatedKey = hyphenate(key); if (isReservedAttribute(hyphenatedKey) || config.isReservedAttr(hyphenatedKey)) { warn( ("\"" + hyphenatedKey + "\" is a reserved attribute and cannot be used as component prop."), vm ); } defineReactive(props, key, value, function () { if (vm.$parent && !isUpdatingChildComponent) { warn( "Avoid mutating a prop directly since the value will be " + "overwritten whenever the parent component re-renders. " + "Instead, use a data or computed property based on the prop's " + "value. Prop being mutated: \"" + key + "\"", vm ); } }); } else { defineReactive(props, key, value); } // static props are already proxied on the component's prototype // during Vue.extend(). We only need to proxy props defined at // instantiation here. if (!(key in vm)) { proxy(vm, "_props", key); } }; for (var key in propsOptions) loop( key ); observerState.shouldConvert = true; } function initData (vm) { var data = vm.$options.data; data = vm._data = typeof data === 'function' ? getData(data, vm) : data || {}; if (!isPlainObject(data)) { data = {}; process.env.NODE_ENV !== 'production' && warn( 'data functions should return an object:\n' + 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function', vm ); } // proxy data on instance var keys = Object.keys(data); var props = vm.$options.props; var methods = vm.$options.methods; var i = keys.length; while (i--) { var key = keys[i]; if (process.env.NODE_ENV !== 'production') { if (methods && hasOwn(methods, key)) { warn( ("Method \"" + key + "\" has already been defined as a data property."), vm ); } } if (props && hasOwn(props, key)) { process.env.NODE_ENV !== 'production' && warn( "The data property \"" + key + "\" is already declared as a prop. " + "Use prop default value instead.", vm ); } else if (!isReserved(key)) { proxy(vm, "_data", key); } } // observe data observe(data, true /* asRootData */); } function getData (data, vm) { try { return data.call(vm, vm) } catch (e) { handleError(e, vm, "data()"); return {} } } var computedWatcherOptions = { lazy: true }; function initComputed (vm, computed) { var watchers = vm._computedWatchers = Object.create(null); // computed properties are just getters during SSR var isSSR = isServerRendering(); for (var key in computed) { var userDef = computed[key]; var getter = typeof userDef === 'function' ? userDef : userDef.get; if (process.env.NODE_ENV !== 'production' && getter == null) { warn( ("Getter is missing for computed property \"" + key + "\"."), vm ); } if (!isSSR) { // create internal watcher for the computed property. watchers[key] = new Watcher( vm, getter || noop, noop, computedWatcherOptions ); } // component-defined computed properties are already defined on the // component prototype. We only need to define computed properties defined // at instantiation here. if (!(key in vm)) { defineComputed(vm, key, userDef); } else if (process.env.NODE_ENV !== 'production') { if (key in vm.$data) { warn(("The computed property \"" + key + "\" is already defined in data."), vm); } else if (vm.$options.props && key in vm.$options.props) { warn(("The computed property \"" + key + "\" is already defined as a prop."), vm); } } } } function defineComputed ( target, key, userDef ) { var shouldCache = !isServerRendering(); if (typeof userDef === 'function') { sharedPropertyDefinition.get = shouldCache ? createComputedGetter(key) : userDef; sharedPropertyDefinition.set = noop; } else { sharedPropertyDefinition.get = userDef.get ? shouldCache && userDef.cache !== false ? createComputedGetter(key) : userDef.get : noop; sharedPropertyDefinition.set = userDef.set ? userDef.set : noop; } if (process.env.NODE_ENV !== 'production' && sharedPropertyDefinition.set === noop) { sharedPropertyDefinition.set = function () { warn( ("Computed property \"" + key + "\" was assigned to but it has no setter."), this ); }; } Object.defineProperty(target, key, sharedPropertyDefinition); } function createComputedGetter (key) { return function computedGetter () { var watcher = this._computedWatchers && this._computedWatchers[key]; if (watcher) { if (watcher.dirty) { watcher.evaluate(); } if (Dep.target) { watcher.depend(); } return watcher.value } } } function initMethods (vm, methods) { var props = vm.$options.props; for (var key in methods) { if (process.env.NODE_ENV !== 'production') { if (methods[key] == null) { warn( "Method \"" + key + "\" has an undefined value in the component definition. " + "Did you reference the function correctly?", vm ); } if (props && hasOwn(props, key)) { warn( ("Method \"" + key + "\" has already been defined as a prop."), vm ); } if ((key in vm) && isReserved(key)) { warn( "Method \"" + key + "\" conflicts with an existing Vue instance method. " + "Avoid defining component methods that start with _ or $." ); } } vm[key] = methods[key] == null ? noop : bind(methods[key], vm); } } function initWatch (vm, watch) { for (var key in watch) { var handler = watch[key]; if (Array.isArray(handler)) { for (var i = 0; i < handler.length; i++) { createWatcher(vm, key, handler[i]); } } else { createWatcher(vm, key, handler); } } } function createWatcher ( vm, keyOrFn, handler, options ) { if (isPlainObject(handler)) { options = handler; handler = handler.handler; } if (typeof handler === 'string') { handler = vm[handler]; } return vm.$watch(keyOrFn, handler, options) } function stateMixin (Vue) { // flow somehow has problems with directly declared definition object // when using Object.defineProperty, so we have to procedurally build up // the object here. var dataDef = {}; dataDef.get = function () { return this._data }; var propsDef = {}; propsDef.get = function () { return this._props }; if (process.env.NODE_ENV !== 'production') { dataDef.set = function (newData) { warn( 'Avoid replacing instance root $data. ' + 'Use nested data properties instead.', this ); }; propsDef.set = function () { warn("$props is readonly.", this); }; } Object.defineProperty(Vue.prototype, '$data', dataDef); Object.defineProperty(Vue.prototype, '$props', propsDef); Vue.prototype.$set = set; Vue.prototype.$delete = del; Vue.prototype.$watch = function ( expOrFn, cb, options ) { var vm = this; if (isPlainObject(cb)) { return createWatcher(vm, expOrFn, cb, options) } options = options || {}; options.user = true; var watcher = new Watcher(vm, expOrFn, cb, options); if (options.immediate) { cb.call(vm, watcher.value); } return function unwatchFn () { watcher.teardown(); } }; } /* */ function initProvide (vm) { var provide = vm.$options.provide; if (provide) { vm._provided = typeof provide === 'function' ? provide.call(vm) : provide; } } function initInjections (vm) { var result = resolveInject(vm.$options.inject, vm); if (result) { observerState.shouldConvert = false; Object.keys(result).forEach(function (key) { /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { defineReactive(vm, key, result[key], function () { warn( "Avoid mutating an injected value directly since the changes will be " + "overwritten whenever the provided component re-renders. " + "injection being mutated: \"" + key + "\"", vm ); }); } else { defineReactive(vm, key, result[key]); } }); observerState.shouldConvert = true; } } function resolveInject (inject, vm) { if (inject) { // inject is :any because flow is not smart enough to figure out cached var result = Object.create(null); var keys = hasSymbol ? Reflect.ownKeys(inject).filter(function (key) { /* istanbul ignore next */ return Object.getOwnPropertyDescriptor(inject, key).enumerable }) : Object.keys(inject); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var provideKey = inject[key].from; var source = vm; while (source) { if (source._provided && provideKey in source._provided) { result[key] = source._provided[provideKey]; break } source = source.$parent; } if (!source) { if ('default' in inject[key]) { var provideDefault = inject[key].default; result[key] = typeof provideDefault === 'function' ? provideDefault.call(vm) : provideDefault; } else if (process.env.NODE_ENV !== 'production') { warn(("Injection \"" + key + "\" not found"), vm); } } } return result } } /* */ /** * Runtime helper for rendering v-for lists. */ function renderList ( val, render ) { var ret, i, l, keys, key; if (Array.isArray(val) || typeof val === 'string') { ret = new Array(val.length); for (i = 0, l = val.length; i < l; i++) { ret[i] = render(val[i], i); } } else if (typeof val === 'number') { ret = new Array(val); for (i = 0; i < val; i++) { ret[i] = render(i + 1, i); } } else if (isObject(val)) { keys = Object.keys(val); ret = new Array(keys.length); for (i = 0, l = keys.length; i < l; i++) { key = keys[i]; ret[i] = render(val[key], key, i); } } if (isDef(ret)) { (ret)._isVList = true; } return ret } /* */ /** * Runtime helper for rendering <slot> */ function renderSlot ( name, fallback, props, bindObject ) { var scopedSlotFn = this.$scopedSlots[name]; var nodes; if (scopedSlotFn) { // scoped slot props = props || {}; if (bindObject) { if (process.env.NODE_ENV !== 'production' && !isObject(bindObject)) { warn( 'slot v-bind without argument expects an Object', this ); } props = extend(extend({}, bindObject), props); } nodes = scopedSlotFn(props) || fallback; } else { var slotNodes = this.$slots[name]; // warn duplicate slot usage if (slotNodes) { if (process.env.NODE_ENV !== 'production' && slotNodes._rendered) { warn( "Duplicate presence of slot \"" + name + "\" found in the same render tree " + "- this will likely cause render errors.", this ); } slotNodes._rendered = true; } nodes = slotNodes || fallback; } var target = props && props.slot; if (target) { return this.$createElement('template', { slot: target }, nodes) } else { return nodes } } /* */ /** * Runtime helper for resolving filters */ function resolveFilter (id) { return resolveAsset(this.$options, 'filters', id, true) || identity } /* */ /** * Runtime helper for checking keyCodes from config. * exposed as Vue.prototype._k * passing in eventKeyName as last argument separately for backwards compat */ function checkKeyCodes ( eventKeyCode, key, builtInAlias, eventKeyName ) { var keyCodes = config.keyCodes[key] || builtInAlias; if (keyCodes) { if (Array.isArray(keyCodes)) { return keyCodes.indexOf(eventKeyCode) === -1 } else { return keyCodes !== eventKeyCode } } else if (eventKeyName) { return hyphenate(eventKeyName) !== key } } /* */ /** * Runtime helper for merging v-bind="object" into a VNode's data. */ function bindObjectProps ( data, tag, value, asProp, isSync ) { if (value) { if (!isObject(value)) { process.env.NODE_ENV !== 'production' && warn( 'v-bind without argument expects an Object or Array value', this ); } else { if (Array.isArray(value)) { value = toObject(value); } var hash; var loop = function ( key ) { if ( key === 'class' || key === 'style' || isReservedAttribute(key) ) { hash = data; } else { var type = data.attrs && data.attrs.type; hash = asProp || config.mustUseProp(tag, type, key) ? data.domProps || (data.domProps = {}) : data.attrs || (data.attrs = {}); } if (!(key in hash)) { hash[key] = value[key]; if (isSync) { var on = data.on || (data.on = {}); on[("update:" + key)] = function ($event) { value[key] = $event; }; } } }; for (var key in value) loop( key ); } } return data } /* */ /** * Runtime helper for rendering static trees. */ function renderStatic ( index, isInFor, isOnce ) { // render fns generated by compiler < 2.5.4 does not provide v-once // information to runtime so be conservative var isOldVersion = arguments.length < 3; // if a static tree is generated by v-once, it is cached on the instance; // otherwise it is purely static and can be cached on the shared options // across all instances. var renderFns = this.$options.staticRenderFns; var cached = isOldVersion || isOnce ? (this._staticTrees || (this._staticTrees = [])) : (renderFns.cached || (renderFns.cached = [])); var tree = cached[index]; // if has already-rendered static tree and not inside v-for, // we can reuse the same tree by doing a shallow clone. if (tree && !isInFor) { return Array.isArray(tree) ? cloneVNodes(tree) : cloneVNode(tree) } // otherwise, render a fresh tree. tree = cached[index] = renderFns[index].call(this._renderProxy, null, this); markStatic(tree, ("__static__" + index), false); return tree } /** * Runtime helper for v-once. * Effectively it means marking the node as static with a unique key. */ function markOnce ( tree, index, key ) { markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true); return tree } function markStatic ( tree, key, isOnce ) { if (Array.isArray(tree)) { for (var i = 0; i < tree.length; i++) { if (tree[i] && typeof tree[i] !== 'string') { markStaticNode(tree[i], (key + "_" + i), isOnce); } } } else { markStaticNode(tree, key, isOnce); } } function markStaticNode (node, key, isOnce) { node.isStatic = true; node.key = key; node.isOnce = isOnce; } /* */ function bindObjectListeners (data, value) { if (value) { if (!isPlainObject(value)) { process.env.NODE_ENV !== 'production' && warn( 'v-on without argument expects an Object value', this ); } else { var on = data.on = data.on ? extend({}, data.on) : {}; for (var key in value) { var existing = on[key]; var ours = value[key]; on[key] = existing ? [].concat(existing, ours) : ours; } } } return data } /* */ function installRenderHelpers (target) { target._o = markOnce; target._n = toNumber; target._s = toString; target._l = renderList; target._t = renderSlot; target._q = looseEqual; target._i = looseIndexOf; target._m = renderStatic; target._f = resolveFilter; target._k = checkKeyCodes; target._b = bindObjectProps; target._v = createTextVNode; target._e = createEmptyVNode; target._u = resolveScopedSlots; target._g = bindObjectListeners; } /* */ function FunctionalRenderContext ( data, props, children, parent, Ctor ) { var options = Ctor.options; this.data = data; this.props = props; this.children = children; this.parent = parent; this.listeners = data.on || emptyObject; this.injections = resolveInject(options.inject, parent); this.slots = function () { return resolveSlots(children, parent); }; // ensure the createElement function in functional components // gets a unique context - this is necessary for correct named slot check var contextVm = Object.create(parent); var isCompiled = isTrue(options._compiled); var needNormalization = !isCompiled; // support for compiled functional template if (isCompiled) { // exposing $options for renderStatic() this.$options = options; // pre-resolve slots for renderSlot() this.$slots = this.slots(); this.$scopedSlots = data.scopedSlots || emptyObject; } if (options._scopeId) { this._c = function (a, b, c, d) { var vnode = createElement(contextVm, a, b, c, d, needNormalization); if (vnode) { vnode.functionalScopeId = options._scopeId; vnode.functionalContext = parent; } return vnode }; } else { this._c = function (a, b, c, d) { return createElement(contextVm, a, b, c, d, needNormalization); }; } } installRenderHelpers(FunctionalRenderContext.prototype); function createFunctionalComponent ( Ctor, propsData, data, contextVm, children ) { var options = Ctor.options; var props = {}; var propOptions = options.props; if (isDef(propOptions)) { for (var key in propOptions) { props[key] = validateProp(key, propOptions, propsData || emptyObject); } } else { if (isDef(data.attrs)) { mergeProps(props, data.attrs); } if (isDef(data.props)) { mergeProps(props, data.props); } } var renderContext = new FunctionalRenderContext( data, props, children, contextVm, Ctor ); var vnode = options.render.call(null, renderContext._c, renderContext); if (vnode instanceof VNode) { vnode.functionalContext = contextVm; vnode.functionalOptions = options; if (data.slot) { (vnode.data || (vnode.data = {})).slot = data.slot; } } return vnode } function mergeProps (to, from) { for (var key in from) { to[camelize(key)] = from[key]; } } /* */ // hooks to be invoked on component VNodes during patch var componentVNodeHooks = { init: function init ( vnode, hydrating, parentElm, refElm ) { if (!vnode.componentInstance || vnode.componentInstance._isDestroyed) { var child = vnode.componentInstance = createComponentInstanceForVnode( vnode, activeInstance, parentElm, refElm ); child.$mount(hydrating ? vnode.elm : undefined, hydrating); } else if (vnode.data.keepAlive) { // kept-alive components, treat as a patch var mountedNode = vnode; // work around flow componentVNodeHooks.prepatch(mountedNode, mountedNode); } }, prepatch: function prepatch (oldVnode, vnode) { var options = vnode.componentOptions; var child = vnode.componentInstance = oldVnode.componentInstance; updateChildComponent( child, options.propsData, // updated props options.listeners, // updated listeners vnode, // new parent vnode options.children // new children ); }, insert: function insert (vnode) { var context = vnode.context; var componentInstance = vnode.componentInstance; if (!componentInstance._isMounted) { componentInstance._isMounted = true; callHook(componentInstance, 'mounted'); } if (vnode.data.keepAlive) { if (context._isMounted) { // vue-router#1212 // During updates, a kept-alive component's child components may // change, so directly walking the tree here may call activated hooks // on incorrect children. Instead we push them into a queue which will // be processed after the whole patch process ended. queueActivatedComponent(componentInstance); } else { activateChildComponent(componentInstance, true /* direct */); } } }, destroy: function destroy (vnode) { var componentInstance = vnode.componentInstance; if (!componentInstance._isDestroyed) { if (!vnode.data.keepAlive) { componentInstance.$destroy(); } else { deactivateChildComponent(componentInstance, true /* direct */); } } } }; var hooksToMerge = Object.keys(componentVNodeHooks); function createComponent ( Ctor, data, context, children, tag ) { if (isUndef(Ctor)) { return } var baseCtor = context.$options._base; // plain options object: turn it into a constructor if (isObject(Ctor)) { Ctor = baseCtor.extend(Ctor); } // if at this stage it's not a constructor or an async component factory, // reject. if (typeof Ctor !== 'function') { if (process.env.NODE_ENV !== 'production') { warn(("Invalid Component definition: " + (String(Ctor))), context); } return } // async component var asyncFactory; if (isUndef(Ctor.cid)) { asyncFactory = Ctor; Ctor = resolveAsyncComponent(asyncFactory, baseCtor, context); if (Ctor === undefined) { // return a placeholder node for async component, which is rendered // as a comment node but preserves all the raw information for the node. // the information will be used for async server-rendering and hydration. return createAsyncPlaceholder( asyncFactory, data, context, children, tag ) } } data = data || {}; // resolve constructor options in case global mixins are applied after // component constructor creation resolveConstructorOptions(Ctor); // transform component v-model data into props & events if (isDef(data.model)) { transformModel(Ctor.options, data); } // extract props var propsData = extractPropsFromVNodeData(data, Ctor, tag); // functional component if (isTrue(Ctor.options.functional)) { return createFunctionalComponent(Ctor, propsData, data, context, children) } // extract listeners, since these needs to be treated as // child component listeners instead of DOM listeners var listeners = data.on; // replace with listeners with .native modifier // so it gets processed during parent component patch. data.on = data.nativeOn; if (isTrue(Ctor.options.abstract)) { // abstract components do not keep anything // other than props & listeners & slot // work around flow var slot = data.slot; data = {}; if (slot) { data.slot = slot; } } // merge component management hooks onto the placeholder node mergeHooks(data); // return a placeholder vnode var name = Ctor.options.name || tag; var vnode = new VNode( ("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')), data, undefined, undefined, undefined, context, { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }, asyncFactory ); return vnode } function createComponentInstanceForVnode ( vnode, // we know it's MountedComponentVNode but flow doesn't parent, // activeInstance in lifecycle state parentElm, refElm ) { var vnodeComponentOptions = vnode.componentOptions; var options = { _isComponent: true, parent: parent, propsData: vnodeComponentOptions.propsData, _componentTag: vnodeComponentOptions.tag, _parentVnode: vnode, _parentListeners: vnodeComponentOptions.listeners, _renderChildren: vnodeComponentOptions.children, _parentElm: parentElm || null, _refElm: refElm || null }; // check inline-template render functions var inlineTemplate = vnode.data.inlineTemplate; if (isDef(inlineTemplate)) { options.render = inlineTemplate.render; options.staticRenderFns = inlineTemplate.staticRenderFns; } return new vnodeComponentOptions.Ctor(options) } function mergeHooks (data) { if (!data.hook) { data.hook = {}; } for (var i = 0; i < hooksToMerge.length; i++) { var key = hooksToMerge[i]; var fromParent = data.hook[key]; var ours = componentVNodeHooks[key]; data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours; } } function mergeHook$1 (one, two) { return function (a, b, c, d) { one(a, b, c, d); two(a, b, c, d); } } // transform component v-model info (value and callback) into // prop and event handler respectively. function transformModel (options, data) { var prop = (options.model && options.model.prop) || 'value'; var event = (options.model && options.model.event) || 'input';(data.props || (data.props = {}))[prop] = data.model.value; var on = data.on || (data.on = {}); if (isDef(on[event])) { on[event] = [data.model.callback].concat(on[event]); } else { on[event] = data.model.callback; } } /* */ var SIMPLE_NORMALIZE = 1; var ALWAYS_NORMALIZE = 2; // wrapper function for providing a more flexible interface // without getting yelled at by flow function createElement ( context, tag, data, children, normalizationType, alwaysNormalize ) { if (Array.isArray(data) || isPrimitive(data)) { normalizationType = children; children = data; data = undefined; } if (isTrue(alwaysNormalize)) { normalizationType = ALWAYS_NORMALIZE; } return _createElement(context, tag, data, children, normalizationType) } function _createElement ( context, tag, data, children, normalizationType ) { if (isDef(data) && isDef((data).__ob__)) { process.env.NODE_ENV !== 'production' && warn( "Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" + 'Always create fresh vnode data objects in each render!', context ); return createEmptyVNode() } // object syntax in v-bind if (isDef(data) && isDef(data.is)) { tag = data.is; } if (!tag) { // in case of component :is set to falsy value return createEmptyVNode() } // warn against non-primitive key if (process.env.NODE_ENV !== 'production' && isDef(data) && isDef(data.key) && !isPrimitive(data.key) ) { warn( 'Avoid using non-primitive value as key, ' + 'use string/number value instead.', context ); } // support single function children as default scoped slot if (Array.isArray(children) && typeof children[0] === 'function' ) { data = data || {}; data.scopedSlots = { default: children[0] }; children.length = 0; } if (normalizationType === ALWAYS_NORMALIZE) { children = normalizeChildren(children); } else if (normalizationType === SIMPLE_NORMALIZE) { children = simpleNormalizeChildren(children); } var vnode, ns; if (typeof tag === 'string') { var Ctor; ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag); if (config.isReservedTag(tag)) { // platform built-in elements vnode = new VNode( config.parsePlatformTagName(tag), data, children, undefined, undefined, context ); } else if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) { // component vnode = createComponent(Ctor, data, context, children, tag); } else { // unknown or unlisted namespaced elements // check at runtime because it may get assigned a namespace when its // parent normalizes children vnode = new VNode( tag, data, children, undefined, undefined, context ); } } else { // direct component options / constructor vnode = createComponent(tag, data, context, children); } if (isDef(vnode)) { if (ns) { applyNS(vnode, ns); } return vnode } else { return createEmptyVNode() } } function applyNS (vnode, ns, force) { vnode.ns = ns; if (vnode.tag === 'foreignObject') { // use default namespace inside foreignObject ns = undefined; force = true; } if (isDef(vnode.children)) { for (var i = 0, l = vnode.children.length; i < l; i++) { var child = vnode.children[i]; if (isDef(child.tag) && (isUndef(child.ns) || isTrue(force))) { applyNS(child, ns, force); } } } } /* */ function initRender (vm) { vm._vnode = null; // the root of the child tree vm._staticTrees = null; // v-once cached trees var options = vm.$options; var parentVnode = vm.$vnode = options._parentVnode; // the placeholder node in parent tree var renderContext = parentVnode && parentVnode.context; vm.$slots = resolveSlots(options._renderChildren, renderContext); vm.$scopedSlots = emptyObject; // bind the createElement fn to this instance // so that we get proper render context inside it. // args order: tag, data, children, normalizationType, alwaysNormalize // internal version is used by render functions compiled from templates vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); }; // normalization is always applied for the public version, used in // user-written render functions. vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); }; // $attrs & $listeners are exposed for easier HOC creation. // they need to be reactive so that HOCs using them are always updated var parentData = parentVnode && parentVnode.data; /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, function () { !isUpdatingChildComponent && warn("$attrs is readonly.", vm); }, true); defineReactive(vm, '$listeners', options._parentListeners || emptyObject, function () { !isUpdatingChildComponent && warn("$listeners is readonly.", vm); }, true); } else { defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, null, true); defineReactive(vm, '$listeners', options._parentListeners || emptyObject, null, true); } } function renderMixin (Vue) { // install runtime convenience helpers installRenderHelpers(Vue.prototype); Vue.prototype.$nextTick = function (fn) { return nextTick(fn, this) }; Vue.prototype._render = function () { var vm = this; var ref = vm.$options; var render = ref.render; var _parentVnode = ref._parentVnode; if (vm._isMounted) { // if the parent didn't update, the slot nodes will be the ones from // last render. They need to be cloned to ensure "freshness" for this render. for (var key in vm.$slots) { var slot = vm.$slots[key]; // _rendered is a flag added by renderSlot, but may not be present // if the slot is passed from manually written render functions if (slot._rendered || (slot[0] && slot[0].elm)) { vm.$slots[key] = cloneVNodes(slot, true /* deep */); } } } vm.$scopedSlots = (_parentVnode && _parentVnode.data.scopedSlots) || emptyObject; // set parent vnode. this allows render functions to have access // to the data on the placeholder node. vm.$vnode = _parentVnode; // render self var vnode; try { vnode = render.call(vm._renderProxy, vm.$createElement); } catch (e) { handleError(e, vm, "render"); // return error render result, // or previous vnode to prevent render error causing blank component /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { if (vm.$options.renderError) { try { vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e); } catch (e) { handleError(e, vm, "renderError"); vnode = vm._vnode; } } else { vnode = vm._vnode; } } else { vnode = vm._vnode; } } // return empty vnode in case the render function errored out if (!(vnode instanceof VNode)) { if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) { warn( 'Multiple root nodes returned from render function. Render function ' + 'should return a single root node.', vm ); } vnode = createEmptyVNode(); } // set parent vnode.parent = _parentVnode; return vnode }; } /* */ var uid$1 = 0; function initMixin (Vue) { Vue.prototype._init = function (options) { var vm = this; // a uid vm._uid = uid$1++; var startTag, endTag; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { startTag = "vue-perf-start:" + (vm._uid); endTag = "vue-perf-end:" + (vm._uid); mark(startTag); } // a flag to avoid this being observed vm._isVue = true; // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options); } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ); } /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { initProxy(vm); } else { vm._renderProxy = vm; } // expose real self vm._self = vm; initLifecycle(vm); initEvents(vm); initRender(vm); callHook(vm, 'beforeCreate'); initInjections(vm); // resolve injections before data/props initState(vm); initProvide(vm); // resolve provide after data/props callHook(vm, 'created'); /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { vm._name = formatComponentName(vm, false); mark(endTag); measure(("vue " + (vm._name) + " init"), startTag, endTag); } if (vm.$options.el) { vm.$mount(vm.$options.el); } }; } function initInternalComponent (vm, options) { var opts = vm.$options = Object.create(vm.constructor.options); // doing this because it's faster than dynamic enumeration. opts.parent = options.parent; opts.propsData = options.propsData; opts._parentVnode = options._parentVnode; opts._parentListeners = options._parentListeners; opts._renderChildren = options._renderChildren; opts._componentTag = options._componentTag; opts._parentElm = options._parentElm; opts._refElm = options._refElm; if (options.render) { opts.render = options.render; opts.staticRenderFns = options.staticRenderFns; } } function resolveConstructorOptions (Ctor) { var options = Ctor.options; if (Ctor.super) { var superOptions = resolveConstructorOptions(Ctor.super); var cachedSuperOptions = Ctor.superOptions; if (superOptions !== cachedSuperOptions) { // super option changed, // need to resolve new options. Ctor.superOptions = superOptions; // check if there are any late-modified/attached options (#4976) var modifiedOptions = resolveModifiedOptions(Ctor); // update base extend options if (modifiedOptions) { extend(Ctor.extendOptions, modifiedOptions); } options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions); if (options.name) { options.components[options.name] = Ctor; } } } return options } function resolveModifiedOptions (Ctor) { var modified; var latest = Ctor.options; var extended = Ctor.extendOptions; var sealed = Ctor.sealedOptions; for (var key in latest) { if (latest[key] !== sealed[key]) { if (!modified) { modified = {}; } modified[key] = dedupe(latest[key], extended[key], sealed[key]); } } return modified } function dedupe (latest, extended, sealed) { // compare latest and sealed to ensure lifecycle hooks won't be duplicated // between merges if (Array.isArray(latest)) { var res = []; sealed = Array.isArray(sealed) ? sealed : [sealed]; extended = Array.isArray(extended) ? extended : [extended]; for (var i = 0; i < latest.length; i++) { // push original options and not sealed options to exclude duplicated options if (extended.indexOf(latest[i]) >= 0 || sealed.indexOf(latest[i]) < 0) { res.push(latest[i]); } } return res } else { return latest } } function Vue$3 (options) { if (process.env.NODE_ENV !== 'production' && !(this instanceof Vue$3) ) { warn('Vue is a constructor and should be called with the `new` keyword'); } this._init(options); } initMixin(Vue$3); stateMixin(Vue$3); eventsMixin(Vue$3); lifecycleMixin(Vue$3); renderMixin(Vue$3); /* */ function initUse (Vue) { Vue.use = function (plugin) { var installedPlugins = (this._installedPlugins || (this._installedPlugins = [])); if (installedPlugins.indexOf(plugin) > -1) { return this } // additional parameters var args = toArray(arguments, 1); args.unshift(this); if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args); } else if (typeof plugin === 'function') { plugin.apply(null, args); } installedPlugins.push(plugin); return this }; } /* */ function initMixin$1 (Vue) { Vue.mixin = function (mixin) { this.options = mergeOptions(this.options, mixin); return this }; } /* */ function initExtend (Vue) { /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ Vue.cid = 0; var cid = 1; /** * Class inheritance */ Vue.extend = function (extendOptions) { extendOptions = extendOptions || {}; var Super = this; var SuperId = Super.cid; var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {}); if (cachedCtors[SuperId]) { return cachedCtors[SuperId] } var name = extendOptions.name || Super.options.name; if (process.env.NODE_ENV !== 'production') { if (!/^[a-zA-Z][\w-]*$/.test(name)) { warn( 'Invalid component name: "' + name + '". Component names ' + 'can only contain alphanumeric characters and the hyphen, ' + 'and must start with a letter.' ); } } var Sub = function VueComponent (options) { this._init(options); }; Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; Sub.cid = cid++; Sub.options = mergeOptions( Super.options, extendOptions ); Sub['super'] = Super; // For props and computed properties, we define the proxy getters on // the Vue instances at extension time, on the extended prototype. This // avoids Object.defineProperty calls for each instance created. if (Sub.options.props) { initProps$1(Sub); } if (Sub.options.computed) { initComputed$1(Sub); } // allow further extension/mixin/plugin usage Sub.extend = Super.extend; Sub.mixin = Super.mixin; Sub.use = Super.use; // create asset registers, so extended classes // can have their private assets too. ASSET_TYPES.forEach(function (type) { Sub[type] = Super[type]; }); // enable recursive self-lookup if (name) { Sub.options.components[name] = Sub; } // keep a reference to the super options at extension time. // later at instantiation we can check if Super's options have // been updated. Sub.superOptions = Super.options; Sub.extendOptions = extendOptions; Sub.sealedOptions = extend({}, Sub.options); // cache constructor cachedCtors[SuperId] = Sub; return Sub }; } function initProps$1 (Comp) { var props = Comp.options.props; for (var key in props) { proxy(Comp.prototype, "_props", key); } } function initComputed$1 (Comp) { var computed = Comp.options.computed; for (var key in computed) { defineComputed(Comp.prototype, key, computed[key]); } } /* */ function initAssetRegisters (Vue) { /** * Create asset registration methods. */ ASSET_TYPES.forEach(function (type) { Vue[type] = function ( id, definition ) { if (!definition) { return this.options[type + 's'][id] } else { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { if (type === 'component' && config.isReservedTag(id)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + id ); } } if (type === 'component' && isPlainObject(definition)) { definition.name = definition.name || id; definition = this.options._base.extend(definition); } if (type === 'directive' && typeof definition === 'function') { definition = { bind: definition, update: definition }; } this.options[type + 's'][id] = definition; return definition } }; }); } /* */ function getComponentName (opts) { return opts && (opts.Ctor.options.name || opts.tag) } function matches (pattern, name) { if (Array.isArray(pattern)) { return pattern.indexOf(name) > -1 } else if (typeof pattern === 'string') { return pattern.split(',').indexOf(name) > -1 } else if (isRegExp(pattern)) { return pattern.test(name) } /* istanbul ignore next */ return false } function pruneCache (keepAliveInstance, filter) { var cache = keepAliveInstance.cache; var keys = keepAliveInstance.keys; var _vnode = keepAliveInstance._vnode; for (var key in cache) { var cachedNode = cache[key]; if (cachedNode) { var name = getComponentName(cachedNode.componentOptions); if (name && !filter(name)) { pruneCacheEntry(cache, key, keys, _vnode); } } } } function pruneCacheEntry ( cache, key, keys, current ) { var cached$$1 = cache[key]; if (cached$$1 && cached$$1 !== current) { cached$$1.componentInstance.$destroy(); } cache[key] = null; remove(keys, key); } var patternTypes = [String, RegExp, Array]; var KeepAlive = { name: 'keep-alive', abstract: true, props: { include: patternTypes, exclude: patternTypes, max: [String, Number] }, created: function created () { this.cache = Object.create(null); this.keys = []; }, destroyed: function destroyed () { var this$1 = this; for (var key in this$1.cache) { pruneCacheEntry(this$1.cache, key, this$1.keys); } }, watch: { include: function include (val) { pruneCache(this, function (name) { return matches(val, name); }); }, exclude: function exclude (val) { pruneCache(this, function (name) { return !matches(val, name); }); } }, render: function render () { var slot = this.$slots.default; var vnode = getFirstComponentChild(slot); var componentOptions = vnode && vnode.componentOptions; if (componentOptions) { // check pattern var name = getComponentName(componentOptions); if (!name || ( (this.exclude && matches(this.exclude, name)) || (this.include && !matches(this.include, name)) )) { return vnode } var ref = this; var cache = ref.cache; var keys = ref.keys; var key = vnode.key == null // same constructor may get registered as different local components // so cid alone is not enough (#3269) ? componentOptions.Ctor.cid + (componentOptions.tag ? ("::" + (componentOptions.tag)) : '') : vnode.key; if (cache[key]) { vnode.componentInstance = cache[key].componentInstance; // make current key freshest remove(keys, key); keys.push(key); } else { cache[key] = vnode; keys.push(key); // prune oldest entry if (this.max && keys.length > parseInt(this.max)) { pruneCacheEntry(cache, keys[0], keys, this._vnode); } } vnode.data.keepAlive = true; } return vnode || (slot && slot[0]) } }; var builtInComponents = { KeepAlive: KeepAlive }; /* */ function initGlobalAPI (Vue) { // config var configDef = {}; configDef.get = function () { return config; }; if (process.env.NODE_ENV !== 'production') { configDef.set = function () { warn( 'Do not replace the Vue.config object, set individual fields instead.' ); }; } Object.defineProperty(Vue, 'config', configDef); // exposed util methods. // NOTE: these are not considered part of the public API - avoid relying on // them unless you are aware of the risk. Vue.util = { warn: warn, extend: extend, mergeOptions: mergeOptions, defineReactive: defineReactive }; Vue.set = set; Vue.delete = del; Vue.nextTick = nextTick; Vue.options = Object.create(null); ASSET_TYPES.forEach(function (type) { Vue.options[type + 's'] = Object.create(null); }); // this is used to identify the "base" constructor to extend all plain-object // components with in Weex's multi-instance scenarios. Vue.options._base = Vue; extend(Vue.options.components, builtInComponents); initUse(Vue); initMixin$1(Vue); initExtend(Vue); initAssetRegisters(Vue); } initGlobalAPI(Vue$3); Object.defineProperty(Vue$3.prototype, '$isServer', { get: isServerRendering }); Object.defineProperty(Vue$3.prototype, '$ssrContext', { get: function get () { /* istanbul ignore next */ return this.$vnode && this.$vnode.ssrContext } }); Vue$3.version = '2.5.6'; /* */ // these are reserved for web because they are directly compiled away // during template compilation var isReservedAttr = makeMap('style,class'); // attributes that should be using props for binding var acceptValue = makeMap('input,textarea,option,select,progress'); var mustUseProp = function (tag, type, attr) { return ( (attr === 'value' && acceptValue(tag)) && type !== 'button' || (attr === 'selected' && tag === 'option') || (attr === 'checked' && tag === 'input') || (attr === 'muted' && tag === 'video') ) }; var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck'); var isBooleanAttr = makeMap( 'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' + 'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' + 'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' + 'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' + 'required,reversed,scoped,seamless,selected,sortable,translate,' + 'truespeed,typemustmatch,visible' ); var xlinkNS = 'http://www.w3.org/1999/xlink'; var isXlink = function (name) { return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink' }; var getXlinkProp = function (name) { return isXlink(name) ? name.slice(6, name.length) : '' }; var isFalsyAttrValue = function (val) { return val == null || val === false }; /* */ function genClassForVnode (vnode) { var data = vnode.data; var parentNode = vnode; var childNode = vnode; while (isDef(childNode.componentInstance)) { childNode = childNode.componentInstance._vnode; if (childNode.data) { data = mergeClassData(childNode.data, data); } } while (isDef(parentNode = parentNode.parent)) { if (parentNode.data) { data = mergeClassData(data, parentNode.data); } } return renderClass(data.staticClass, data.class) } function mergeClassData (child, parent) { return { staticClass: concat(child.staticClass, parent.staticClass), class: isDef(child.class) ? [child.class, parent.class] : parent.class } } function renderClass ( staticClass, dynamicClass ) { if (isDef(staticClass) || isDef(dynamicClass)) { return concat(staticClass, stringifyClass(dynamicClass)) } /* istanbul ignore next */ return '' } function concat (a, b) { return a ? b ? (a + ' ' + b) : a : (b || '') } function stringifyClass (value) { if (Array.isArray(value)) { return stringifyArray(value) } if (isObject(value)) { return stringifyObject(value) } if (typeof value === 'string') { return value } /* istanbul ignore next */ return '' } function stringifyArray (value) { var res = ''; var stringified; for (var i = 0, l = value.length; i < l; i++) { if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') { if (res) { res += ' '; } res += stringified; } } return res } function stringifyObject (value) { var res = ''; for (var key in value) { if (value[key]) { if (res) { res += ' '; } res += key; } } return res } /* */ var namespaceMap = { svg: 'http://www.w3.org/2000/svg', math: 'http://www.w3.org/1998/Math/MathML' }; var isHTMLTag = makeMap( 'html,body,base,head,link,meta,style,title,' + 'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' + 'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' + 'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' + 's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' + 'embed,object,param,source,canvas,script,noscript,del,ins,' + 'caption,col,colgroup,table,thead,tbody,td,th,tr,' + 'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' + 'output,progress,select,textarea,' + 'details,dialog,menu,menuitem,summary,' + 'content,element,shadow,template,blockquote,iframe,tfoot' ); // this map is intentionally selective, only covering SVG elements that may // contain child elements. var isSVG = makeMap( 'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' + 'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' + 'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view', true ); var isPreTag = function (tag) { return tag === 'pre'; }; var isReservedTag = function (tag) { return isHTMLTag(tag) || isSVG(tag) }; function getTagNamespace (tag) { if (isSVG(tag)) { return 'svg' } // basic support for MathML // note it doesn't support other MathML elements being component roots if (tag === 'math') { return 'math' } } var unknownElementCache = Object.create(null); function isUnknownElement (tag) { /* istanbul ignore if */ if (!inBrowser) { return true } if (isReservedTag(tag)) { return false } tag = tag.toLowerCase(); /* istanbul ignore if */ if (unknownElementCache[tag] != null) { return unknownElementCache[tag] } var el = document.createElement(tag); if (tag.indexOf('-') > -1) { // http://stackoverflow.com/a/28210364/1070244 return (unknownElementCache[tag] = ( el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement )) } else { return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString())) } } var isTextInputType = makeMap('text,number,password,search,email,tel,url'); /* */ /** * Query an element selector if it's not an element already. */ function query (el) { if (typeof el === 'string') { var selected = document.querySelector(el); if (!selected) { process.env.NODE_ENV !== 'production' && warn( 'Cannot find element: ' + el ); return document.createElement('div') } return selected } else { return el } } /* */ function createElement$1 (tagName, vnode) { var elm = document.createElement(tagName); if (tagName !== 'select') { return elm } // false or null will remove the attribute but undefined will not if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) { elm.setAttribute('multiple', 'multiple'); } return elm } function createElementNS (namespace, tagName) { return document.createElementNS(namespaceMap[namespace], tagName) } function createTextNode (text) { return document.createTextNode(text) } function createComment (text) { return document.createComment(text) } function insertBefore (parentNode, newNode, referenceNode) { parentNode.insertBefore(newNode, referenceNode); } function removeChild (node, child) { node.removeChild(child); } function appendChild (node, child) { node.appendChild(child); } function parentNode (node) { return node.parentNode } function nextSibling (node) { return node.nextSibling } function tagName (node) { return node.tagName } function setTextContent (node, text) { node.textContent = text; } function setAttribute (node, key, val) { node.setAttribute(key, val); } var nodeOps = Object.freeze({ createElement: createElement$1, createElementNS: createElementNS, createTextNode: createTextNode, createComment: createComment, insertBefore: insertBefore, removeChild: removeChild, appendChild: appendChild, parentNode: parentNode, nextSibling: nextSibling, tagName: tagName, setTextContent: setTextContent, setAttribute: setAttribute }); /* */ var ref = { create: function create (_, vnode) { registerRef(vnode); }, update: function update (oldVnode, vnode) { if (oldVnode.data.ref !== vnode.data.ref) { registerRef(oldVnode, true); registerRef(vnode); } }, destroy: function destroy (vnode) { registerRef(vnode, true); } }; function registerRef (vnode, isRemoval) { var key = vnode.data.ref; if (!key) { return } var vm = vnode.context; var ref = vnode.componentInstance || vnode.elm; var refs = vm.$refs; if (isRemoval) { if (Array.isArray(refs[key])) { remove(refs[key], ref); } else if (refs[key] === ref) { refs[key] = undefined; } } else { if (vnode.data.refInFor) { if (!Array.isArray(refs[key])) { refs[key] = [ref]; } else if (refs[key].indexOf(ref) < 0) { // $flow-disable-line refs[key].push(ref); } } else { refs[key] = ref; } } } /** * Virtual DOM patching algorithm based on Snabbdom by * Simon Friis Vindum (@paldepind) * Licensed under the MIT License * https://github.com/paldepind/snabbdom/blob/master/LICENSE * * modified by Evan You (@yyx990803) * * Not type-checking this because this file is perf-critical and the cost * of making flow understand it is not worth it. */ var emptyNode = new VNode('', {}, []); var hooks = ['create', 'activate', 'update', 'remove', 'destroy']; function sameVnode (a, b) { return ( a.key === b.key && ( ( a.tag === b.tag && a.isComment === b.isComment && isDef(a.data) === isDef(b.data) && sameInputType(a, b) ) || ( isTrue(a.isAsyncPlaceholder) && a.asyncFactory === b.asyncFactory && isUndef(b.asyncFactory.error) ) ) ) } function sameInputType (a, b) { if (a.tag !== 'input') { return true } var i; var typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type; var typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type; return typeA === typeB || isTextInputType(typeA) && isTextInputType(typeB) } function createKeyToOldIdx (children, beginIdx, endIdx) { var i, key; var map = {}; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (isDef(key)) { map[key] = i; } } return map } function createPatchFunction (backend) { var i, j; var cbs = {}; var modules = backend.modules; var nodeOps = backend.nodeOps; for (i = 0; i < hooks.length; ++i) { cbs[hooks[i]] = []; for (j = 0; j < modules.length; ++j) { if (isDef(modules[j][hooks[i]])) { cbs[hooks[i]].push(modules[j][hooks[i]]); } } } function emptyNodeAt (elm) { return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm) } function createRmCb (childElm, listeners) { function remove () { if (--remove.listeners === 0) { removeNode(childElm); } } remove.listeners = listeners; return remove } function removeNode (el) { var parent = nodeOps.parentNode(el); // element may have already been removed due to v-html / v-text if (isDef(parent)) { nodeOps.removeChild(parent, el); } } function isUnknownElement$$1 (vnode, inVPre) { return ( !inVPre && !vnode.ns && !( config.ignoredElements.length && config.ignoredElements.some(function (ignore) { return isRegExp(ignore) ? ignore.test(vnode.tag) : ignore === vnode.tag }) ) && config.isUnknownElement(vnode.tag) ) } var creatingElmInVPre = 0; function createElm (vnode, insertedVnodeQueue, parentElm, refElm, nested) { vnode.isRootInsert = !nested; // for transition enter check if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) { return } var data = vnode.data; var children = vnode.children; var tag = vnode.tag; if (isDef(tag)) { if (process.env.NODE_ENV !== 'production') { if (data && data.pre) { creatingElmInVPre++; } if (isUnknownElement$$1(vnode, creatingElmInVPre)) { warn( 'Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.', vnode.context ); } } vnode.elm = vnode.ns ? nodeOps.createElementNS(vnode.ns, tag) : nodeOps.createElement(tag, vnode); setScope(vnode); /* istanbul ignore if */ { createChildren(vnode, children, insertedVnodeQueue); if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue); } insert(parentElm, vnode.elm, refElm); } if (process.env.NODE_ENV !== 'production' && data && data.pre) { creatingElmInVPre--; } } else if (isTrue(vnode.isComment)) { vnode.elm = nodeOps.createComment(vnode.text); insert(parentElm, vnode.elm, refElm); } else { vnode.elm = nodeOps.createTextNode(vnode.text); insert(parentElm, vnode.elm, refElm); } } function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i = vnode.data; if (isDef(i)) { var isReactivated = isDef(vnode.componentInstance) && i.keepAlive; if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */, parentElm, refElm); } // after calling the init hook, if the vnode is a child component // it should've created a child instance and mounted it. the child // component also has set the placeholder vnode's elm. // in that case we can just return the element and be done. if (isDef(vnode.componentInstance)) { initComponent(vnode, insertedVnodeQueue); if (isTrue(isReactivated)) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm); } return true } } } function initComponent (vnode, insertedVnodeQueue) { if (isDef(vnode.data.pendingInsert)) { insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert); vnode.data.pendingInsert = null; } vnode.elm = vnode.componentInstance.$el; if (isPatchable(vnode)) { invokeCreateHooks(vnode, insertedVnodeQueue); setScope(vnode); } else { // empty component root. // skip all element-related modules except for ref (#3455) registerRef(vnode); // make sure to invoke the insert hook insertedVnodeQueue.push(vnode); } } function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i; // hack for #4339: a reactivated component with inner transition // does not trigger because the inner node's created hooks are not called // again. It's not ideal to involve module-specific logic in here but // there doesn't seem to be a better way to do it. var innerNode = vnode; while (innerNode.componentInstance) { innerNode = innerNode.componentInstance._vnode; if (isDef(i = innerNode.data) && isDef(i = i.transition)) { for (i = 0; i < cbs.activate.length; ++i) { cbs.activate[i](emptyNode, innerNode); } insertedVnodeQueue.push(innerNode); break } } // unlike a newly created component, // a reactivated keep-alive component doesn't insert itself insert(parentElm, vnode.elm, refElm); } function insert (parent, elm, ref$$1) { if (isDef(parent)) { if (isDef(ref$$1)) { if (ref$$1.parentNode === parent) { nodeOps.insertBefore(parent, elm, ref$$1); } } else { nodeOps.appendChild(parent, elm); } } } function createChildren (vnode, children, insertedVnodeQueue) { if (Array.isArray(children)) { for (var i = 0; i < children.length; ++i) { createElm(children[i], insertedVnodeQueue, vnode.elm, null, true); } } else if (isPrimitive(vnode.text)) { nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(vnode.text)); } } function isPatchable (vnode) { while (vnode.componentInstance) { vnode = vnode.componentInstance._vnode; } return isDef(vnode.tag) } function invokeCreateHooks (vnode, insertedVnodeQueue) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, vnode); } i = vnode.data.hook; // Reuse variable if (isDef(i)) { if (isDef(i.create)) { i.create(emptyNode, vnode); } if (isDef(i.insert)) { insertedVnodeQueue.push(vnode); } } } // set scope id attribute for scoped CSS. // this is implemented as a special case to avoid the overhead // of going through the normal attribute patching process. function setScope (vnode) { var i; if (isDef(i = vnode.functionalScopeId)) { nodeOps.setAttribute(vnode.elm, i, ''); } else { var ancestor = vnode; while (ancestor) { if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) { nodeOps.setAttribute(vnode.elm, i, ''); } ancestor = ancestor.parent; } } // for slot content they should also get the scopeId from the host instance. if (isDef(i = activeInstance) && i !== vnode.context && i !== vnode.functionalContext && isDef(i = i.$options._scopeId) ) { nodeOps.setAttribute(vnode.elm, i, ''); } } function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) { for (; startIdx <= endIdx; ++startIdx) { createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm); } } function invokeDestroyHook (vnode) { var i, j; var data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); } for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); } } if (isDef(i = vnode.children)) { for (j = 0; j < vnode.children.length; ++j) { invokeDestroyHook(vnode.children[j]); } } } function removeVnodes (parentElm, vnodes, startIdx, endIdx) { for (; startIdx <= endIdx; ++startIdx) { var ch = vnodes[startIdx]; if (isDef(ch)) { if (isDef(ch.tag)) { removeAndInvokeRemoveHook(ch); invokeDestroyHook(ch); } else { // Text node removeNode(ch.elm); } } } } function removeAndInvokeRemoveHook (vnode, rm) { if (isDef(rm) || isDef(vnode.data)) { var i; var listeners = cbs.remove.length + 1; if (isDef(rm)) { // we have a recursively passed down rm callback // increase the listeners count rm.listeners += listeners; } else { // directly removing rm = createRmCb(vnode.elm, listeners); } // recursively invoke hooks on child component root node if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) { removeAndInvokeRemoveHook(i, rm); } for (i = 0; i < cbs.remove.length; ++i) { cbs.remove[i](vnode, rm); } if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) { i(vnode, rm); } else { rm(); } } else { removeNode(vnode.elm); } } function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) { var oldStartIdx = 0; var newStartIdx = 0; var oldEndIdx = oldCh.length - 1; var oldStartVnode = oldCh[0]; var oldEndVnode = oldCh[oldEndIdx]; var newEndIdx = newCh.length - 1; var newStartVnode = newCh[0]; var newEndVnode = newCh[newEndIdx]; var oldKeyToIdx, idxInOld, vnodeToMove, refElm; // removeOnly is a special flag used only by <transition-group> // to ensure removed elements stay in correct relative positions // during leaving transitions var canMove = !removeOnly; while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx]; } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue); oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue); oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm)); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); } idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx); if (isUndef(idxInOld)) { // New element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm); } else { vnodeToMove = oldCh[idxInOld]; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && !vnodeToMove) { warn( 'It seems there are duplicate keys that is causing an update error. ' + 'Make sure each v-for item has a unique key.' ); } if (sameVnode(vnodeToMove, newStartVnode)) { patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue); oldCh[idxInOld] = undefined; canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm); } else { // same key but different element. treat as new element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm); } } newStartVnode = newCh[++newStartIdx]; } } if (oldStartIdx > oldEndIdx) { refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm; addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue); } else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx); } } function findIdxInOld (node, oldCh, start, end) { for (var i = start; i < end; i++) { var c = oldCh[i]; if (isDef(c) && sameVnode(node, c)) { return i } } } function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) { if (oldVnode === vnode) { return } var elm = vnode.elm = oldVnode.elm; if (isTrue(oldVnode.isAsyncPlaceholder)) { if (isDef(vnode.asyncFactory.resolved)) { hydrate(oldVnode.elm, vnode, insertedVnodeQueue); } else { vnode.isAsyncPlaceholder = true; } return } // reuse element for static trees. // note we only do this if the vnode is cloned - // if the new node is not cloned it means the render functions have been // reset by the hot-reload-api and we need to do a proper re-render. if (isTrue(vnode.isStatic) && isTrue(oldVnode.isStatic) && vnode.key === oldVnode.key && (isTrue(vnode.isCloned) || isTrue(vnode.isOnce)) ) { vnode.componentInstance = oldVnode.componentInstance; return } var i; var data = vnode.data; if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) { i(oldVnode, vnode); } var oldCh = oldVnode.children; var ch = vnode.children; if (isDef(data) && isPatchable(vnode)) { for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); } if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); } } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); } } else if (isDef(ch)) { if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue); } else if (isDef(oldCh)) { removeVnodes(elm, oldCh, 0, oldCh.length - 1); } else if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } } else if (oldVnode.text !== vnode.text) { nodeOps.setTextContent(elm, vnode.text); } if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); } } } function invokeInsertHook (vnode, queue, initial) { // delay insert hooks for component root nodes, invoke them after the // element is really inserted if (isTrue(initial) && isDef(vnode.parent)) { vnode.parent.data.pendingInsert = queue; } else { for (var i = 0; i < queue.length; ++i) { queue[i].data.hook.insert(queue[i]); } } } var hydrationBailed = false; // list of modules that can skip create hook during hydration because they // are already rendered on the client or has no need for initialization // Note: style is excluded because it relies on initial clone for future // deep updates (#7063). var isRenderedModule = makeMap('attrs,class,staticClass,staticStyle,key'); // Note: this is a browser-only function so we can assume elms are DOM nodes. function hydrate (elm, vnode, insertedVnodeQueue, inVPre) { var i; var tag = vnode.tag; var data = vnode.data; var children = vnode.children; inVPre = inVPre || (data && data.pre); vnode.elm = elm; if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) { vnode.isAsyncPlaceholder = true; return true } // assert node match if (process.env.NODE_ENV !== 'production') { if (!assertNodeMatch(elm, vnode, inVPre)) { return false } } if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); } if (isDef(i = vnode.componentInstance)) { // child component. it should have hydrated its own tree. initComponent(vnode, insertedVnodeQueue); return true } } if (isDef(tag)) { if (isDef(children)) { // empty element, allow client to pick up and populate children if (!elm.hasChildNodes()) { createChildren(vnode, children, insertedVnodeQueue); } else { // v-html and domProps: innerHTML if (isDef(i = data) && isDef(i = i.domProps) && isDef(i = i.innerHTML)) { if (i !== elm.innerHTML) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined' && !hydrationBailed ) { hydrationBailed = true; console.warn('Parent: ', elm); console.warn('server innerHTML: ', i); console.warn('client innerHTML: ', elm.innerHTML); } return false } } else { // iterate and compare children lists var childrenMatch = true; var childNode = elm.firstChild; for (var i$1 = 0; i$1 < children.length; i$1++) { if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue, inVPre)) { childrenMatch = false; break } childNode = childNode.nextSibling; } // if childNode is not null, it means the actual childNodes list is // longer than the virtual children list. if (!childrenMatch || childNode) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined' && !hydrationBailed ) { hydrationBailed = true; console.warn('Parent: ', elm); console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children); } return false } } } } if (isDef(data)) { var fullInvoke = false; for (var key in data) { if (!isRenderedModule(key)) { fullInvoke = true; invokeCreateHooks(vnode, insertedVnodeQueue); break } } if (!fullInvoke && data['class']) { // ensure collecting deps for deep class bindings for future updates traverse(data['class']); } } } else if (elm.data !== vnode.text) { elm.data = vnode.text; } return true } function assertNodeMatch (node, vnode, inVPre) { if (isDef(vnode.tag)) { return vnode.tag.indexOf('vue-component') === 0 || ( !isUnknownElement$$1(vnode, inVPre) && vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase()) ) } else { return node.nodeType === (vnode.isComment ? 8 : 3) } } return function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) { if (isUndef(vnode)) { if (isDef(oldVnode)) { invokeDestroyHook(oldVnode); } return } var isInitialPatch = false; var insertedVnodeQueue = []; if (isUndef(oldVnode)) { // empty mount (likely as component), create new root element isInitialPatch = true; createElm(vnode, insertedVnodeQueue, parentElm, refElm); } else { var isRealElement = isDef(oldVnode.nodeType); if (!isRealElement && sameVnode(oldVnode, vnode)) { // patch existing root node patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly); } else { if (isRealElement) { // mounting to a real element // check if this is server-rendered content and if we can perform // a successful hydration. if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) { oldVnode.removeAttribute(SSR_ATTR); hydrating = true; } if (isTrue(hydrating)) { if (hydrate(oldVnode, vnode, insertedVnodeQueue)) { invokeInsertHook(vnode, insertedVnodeQueue, true); return oldVnode } else if (process.env.NODE_ENV !== 'production') { warn( 'The client-side rendered virtual DOM tree is not matching ' + 'server-rendered content. This is likely caused by incorrect ' + 'HTML markup, for example nesting block-level elements inside ' + '<p>, or missing <tbody>. Bailing hydration and performing ' + 'full client-side render.' ); } } // either not server-rendered, or hydration failed. // create an empty node and replace it oldVnode = emptyNodeAt(oldVnode); } // replacing existing element var oldElm = oldVnode.elm; var parentElm$1 = nodeOps.parentNode(oldElm); // create new node createElm( vnode, insertedVnodeQueue, // extremely rare edge case: do not insert if old element is in a // leaving transition. Only happens when combining transition + // keep-alive + HOCs. (#4590) oldElm._leaveCb ? null : parentElm$1, nodeOps.nextSibling(oldElm) ); // update parent placeholder node element, recursively if (isDef(vnode.parent)) { var ancestor = vnode.parent; var patchable = isPatchable(vnode); while (ancestor) { for (var i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](ancestor); } ancestor.elm = vnode.elm; if (patchable) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, ancestor); } // #6513 // invoke insert hooks that may have been merged by create hooks. // e.g. for directives that uses the "inserted" hook. var insert = ancestor.data.hook.insert; if (insert.merged) { // start at index 1 to avoid re-invoking component mounted hook for (var i$2 = 1; i$2 < insert.fns.length; i$2++) { insert.fns[i$2](); } } } else { registerRef(ancestor); } ancestor = ancestor.parent; } } // destroy old node if (isDef(parentElm$1)) { removeVnodes(parentElm$1, [oldVnode], 0, 0); } else if (isDef(oldVnode.tag)) { invokeDestroyHook(oldVnode); } } } invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch); return vnode.elm } } /* */ var directives = { create: updateDirectives, update: updateDirectives, destroy: function unbindDirectives (vnode) { updateDirectives(vnode, emptyNode); } }; function updateDirectives (oldVnode, vnode) { if (oldVnode.data.directives || vnode.data.directives) { _update(oldVnode, vnode); } } function _update (oldVnode, vnode) { var isCreate = oldVnode === emptyNode; var isDestroy = vnode === emptyNode; var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context); var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context); var dirsWithInsert = []; var dirsWithPostpatch = []; var key, oldDir, dir; for (key in newDirs) { oldDir = oldDirs[key]; dir = newDirs[key]; if (!oldDir) { // new directive, bind callHook$1(dir, 'bind', vnode, oldVnode); if (dir.def && dir.def.inserted) { dirsWithInsert.push(dir); } } else { // existing directive, update dir.oldValue = oldDir.value; callHook$1(dir, 'update', vnode, oldVnode); if (dir.def && dir.def.componentUpdated) { dirsWithPostpatch.push(dir); } } } if (dirsWithInsert.length) { var callInsert = function () { for (var i = 0; i < dirsWithInsert.length; i++) { callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode); } }; if (isCreate) { mergeVNodeHook(vnode, 'insert', callInsert); } else { callInsert(); } } if (dirsWithPostpatch.length) { mergeVNodeHook(vnode, 'postpatch', function () { for (var i = 0; i < dirsWithPostpatch.length; i++) { callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode); } }); } if (!isCreate) { for (key in oldDirs) { if (!newDirs[key]) { // no longer present, unbind callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy); } } } } var emptyModifiers = Object.create(null); function normalizeDirectives$1 ( dirs, vm ) { var res = Object.create(null); if (!dirs) { return res } var i, dir; for (i = 0; i < dirs.length; i++) { dir = dirs[i]; if (!dir.modifiers) { dir.modifiers = emptyModifiers; } res[getRawDirName(dir)] = dir; dir.def = resolveAsset(vm.$options, 'directives', dir.name, true); } return res } function getRawDirName (dir) { return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.'))) } function callHook$1 (dir, hook, vnode, oldVnode, isDestroy) { var fn = dir.def && dir.def[hook]; if (fn) { try { fn(vnode.elm, dir, vnode, oldVnode, isDestroy); } catch (e) { handleError(e, vnode.context, ("directive " + (dir.name) + " " + hook + " hook")); } } } var baseModules = [ ref, directives ]; /* */ function updateAttrs (oldVnode, vnode) { var opts = vnode.componentOptions; if (isDef(opts) && opts.Ctor.options.inheritAttrs === false) { return } if (isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs)) { return } var key, cur, old; var elm = vnode.elm; var oldAttrs = oldVnode.data.attrs || {}; var attrs = vnode.data.attrs || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(attrs.__ob__)) { attrs = vnode.data.attrs = extend({}, attrs); } for (key in attrs) { cur = attrs[key]; old = oldAttrs[key]; if (old !== cur) { setAttr(elm, key, cur); } } // #4391: in IE9, setting type can reset value for input[type=radio] // #6666: IE/Edge forces progress value down to 1 before setting a max /* istanbul ignore if */ if ((isIE9 || isEdge) && attrs.value !== oldAttrs.value) { setAttr(elm, 'value', attrs.value); } for (key in oldAttrs) { if (isUndef(attrs[key])) { if (isXlink(key)) { elm.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else if (!isEnumeratedAttr(key)) { elm.removeAttribute(key); } } } } function setAttr (el, key, value) { if (isBooleanAttr(key)) { // set attribute for blank value // e.g. <option disabled>Select one</option> if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { // technically allowfullscreen is a boolean attribute for <iframe>, // but Flash expects a value of "true" when used on <embed> tag value = key === 'allowfullscreen' && el.tagName === 'EMBED' ? 'true' : key; el.setAttribute(key, value); } } else if (isEnumeratedAttr(key)) { el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true'); } else if (isXlink(key)) { if (isFalsyAttrValue(value)) { el.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else { el.setAttributeNS(xlinkNS, key, value); } } else { if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { el.setAttribute(key, value); } } } var attrs = { create: updateAttrs, update: updateAttrs }; /* */ function updateClass (oldVnode, vnode) { var el = vnode.elm; var data = vnode.data; var oldData = oldVnode.data; if ( isUndef(data.staticClass) && isUndef(data.class) && ( isUndef(oldData) || ( isUndef(oldData.staticClass) && isUndef(oldData.class) ) ) ) { return } var cls = genClassForVnode(vnode); // handle transition classes var transitionClass = el._transitionClasses; if (isDef(transitionClass)) { cls = concat(cls, stringifyClass(transitionClass)); } // set the class if (cls !== el._prevClass) { el.setAttribute('class', cls); el._prevClass = cls; } } var klass = { create: updateClass, update: updateClass }; /* */ var validDivisionCharRE = /[\w).+\-_$\]]/; function parseFilters (exp) { var inSingle = false; var inDouble = false; var inTemplateString = false; var inRegex = false; var curly = 0; var square = 0; var paren = 0; var lastFilterIndex = 0; var c, prev, i, expression, filters; for (i = 0; i < exp.length; i++) { prev = c; c = exp.charCodeAt(i); if (inSingle) { if (c === 0x27 && prev !== 0x5C) { inSingle = false; } } else if (inDouble) { if (c === 0x22 && prev !== 0x5C) { inDouble = false; } } else if (inTemplateString) { if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; } } else if (inRegex) { if (c === 0x2f && prev !== 0x5C) { inRegex = false; } } else if ( c === 0x7C && // pipe exp.charCodeAt(i + 1) !== 0x7C && exp.charCodeAt(i - 1) !== 0x7C && !curly && !square && !paren ) { if (expression === undefined) { // first filter, end of expression lastFilterIndex = i + 1; expression = exp.slice(0, i).trim(); } else { pushFilter(); } } else { switch (c) { case 0x22: inDouble = true; break // " case 0x27: inSingle = true; break // ' case 0x60: inTemplateString = true; break // ` case 0x28: paren++; break // ( case 0x29: paren--; break // ) case 0x5B: square++; break // [ case 0x5D: square--; break // ] case 0x7B: curly++; break // { case 0x7D: curly--; break // } } if (c === 0x2f) { // / var j = i - 1; var p = (void 0); // find first non-whitespace prev char for (; j >= 0; j--) { p = exp.charAt(j); if (p !== ' ') { break } } if (!p || !validDivisionCharRE.test(p)) { inRegex = true; } } } } if (expression === undefined) { expression = exp.slice(0, i).trim(); } else if (lastFilterIndex !== 0) { pushFilter(); } function pushFilter () { (filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim()); lastFilterIndex = i + 1; } if (filters) { for (i = 0; i < filters.length; i++) { expression = wrapFilter(expression, filters[i]); } } return expression } function wrapFilter (exp, filter) { var i = filter.indexOf('('); if (i < 0) { // _f: resolveFilter return ("_f(\"" + filter + "\")(" + exp + ")") } else { var name = filter.slice(0, i); var args = filter.slice(i + 1); return ("_f(\"" + name + "\")(" + exp + "," + args) } } /* */ function baseWarn (msg) { console.error(("[Vue compiler]: " + msg)); } function pluckModuleFunction ( modules, key ) { return modules ? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; }) : [] } function addProp (el, name, value) { (el.props || (el.props = [])).push({ name: name, value: value }); } function addAttr (el, name, value) { (el.attrs || (el.attrs = [])).push({ name: name, value: value }); } function addDirective ( el, name, rawName, value, arg, modifiers ) { (el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers }); } function addHandler ( el, name, value, modifiers, important, warn ) { modifiers = modifiers || emptyObject; // warn prevent and passive modifier /* istanbul ignore if */ if ( process.env.NODE_ENV !== 'production' && warn && modifiers.prevent && modifiers.passive ) { warn( 'passive and prevent can\'t be used together. ' + 'Passive handler can\'t prevent default event.' ); } // check capture modifier if (modifiers.capture) { delete modifiers.capture; name = '!' + name; // mark the event as captured } if (modifiers.once) { delete modifiers.once; name = '~' + name; // mark the event as once } /* istanbul ignore if */ if (modifiers.passive) { delete modifiers.passive; name = '&' + name; // mark the event as passive } // normalize click.right and click.middle since they don't actually fire // this is technically browser-specific, but at least for now browsers are // the only target envs that have right/middle clicks. if (name === 'click') { if (modifiers.right) { name = 'contextmenu'; delete modifiers.right; } else if (modifiers.middle) { name = 'mouseup'; } } var events; if (modifiers.native) { delete modifiers.native; events = el.nativeEvents || (el.nativeEvents = {}); } else { events = el.events || (el.events = {}); } var newHandler = { value: value }; if (modifiers !== emptyObject) { newHandler.modifiers = modifiers; } var handlers = events[name]; /* istanbul ignore if */ if (Array.isArray(handlers)) { important ? handlers.unshift(newHandler) : handlers.push(newHandler); } else if (handlers) { events[name] = important ? [newHandler, handlers] : [handlers, newHandler]; } else { events[name] = newHandler; } } function getBindingAttr ( el, name, getStatic ) { var dynamicValue = getAndRemoveAttr(el, ':' + name) || getAndRemoveAttr(el, 'v-bind:' + name); if (dynamicValue != null) { return parseFilters(dynamicValue) } else if (getStatic !== false) { var staticValue = getAndRemoveAttr(el, name); if (staticValue != null) { return JSON.stringify(staticValue) } } } // note: this only removes the attr from the Array (attrsList) so that it // doesn't get processed by processAttrs. // By default it does NOT remove it from the map (attrsMap) because the map is // needed during codegen. function getAndRemoveAttr ( el, name, removeFromMap ) { var val; if ((val = el.attrsMap[name]) != null) { var list = el.attrsList; for (var i = 0, l = list.length; i < l; i++) { if (list[i].name === name) { list.splice(i, 1); break } } } if (removeFromMap) { delete el.attrsMap[name]; } return val } /* */ /** * Cross-platform code generation for component v-model */ function genComponentModel ( el, value, modifiers ) { var ref = modifiers || {}; var number = ref.number; var trim = ref.trim; var baseValueExpression = '$$v'; var valueExpression = baseValueExpression; if (trim) { valueExpression = "(typeof " + baseValueExpression + " === 'string'" + "? " + baseValueExpression + ".trim()" + ": " + baseValueExpression + ")"; } if (number) { valueExpression = "_n(" + valueExpression + ")"; } var assignment = genAssignmentCode(value, valueExpression); el.model = { value: ("(" + value + ")"), expression: ("\"" + value + "\""), callback: ("function (" + baseValueExpression + ") {" + assignment + "}") }; } /** * Cross-platform codegen helper for generating v-model value assignment code. */ function genAssignmentCode ( value, assignment ) { var res = parseModel(value); if (res.key === null) { return (value + "=" + assignment) } else { return ("$set(" + (res.exp) + ", " + (res.key) + ", " + assignment + ")") } } /** * Parse a v-model expression into a base path and a final key segment. * Handles both dot-path and possible square brackets. * * Possible cases: * * - test * - test[key] * - test[test1[key]] * - test["a"][key] * - xxx.test[a[a].test1[key]] * - test.xxx.a["asa"][test1[key]] * */ var len; var str; var chr; var index$1; var expressionPos; var expressionEndPos; function parseModel (val) { len = val.length; if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) { index$1 = val.lastIndexOf('.'); if (index$1 > -1) { return { exp: val.slice(0, index$1), key: '"' + val.slice(index$1 + 1) + '"' } } else { return { exp: val, key: null } } } str = val; index$1 = expressionPos = expressionEndPos = 0; while (!eof()) { chr = next(); /* istanbul ignore if */ if (isStringStart(chr)) { parseString(chr); } else if (chr === 0x5B) { parseBracket(chr); } } return { exp: val.slice(0, expressionPos), key: val.slice(expressionPos + 1, expressionEndPos) } } function next () { return str.charCodeAt(++index$1) } function eof () { return index$1 >= len } function isStringStart (chr) { return chr === 0x22 || chr === 0x27 } function parseBracket (chr) { var inBracket = 1; expressionPos = index$1; while (!eof()) { chr = next(); if (isStringStart(chr)) { parseString(chr); continue } if (chr === 0x5B) { inBracket++; } if (chr === 0x5D) { inBracket--; } if (inBracket === 0) { expressionEndPos = index$1; break } } } function parseString (chr) { var stringQuote = chr; while (!eof()) { chr = next(); if (chr === stringQuote) { break } } } /* */ var warn$1; // in some cases, the event used has to be determined at runtime // so we used some reserved tokens during compile. var RANGE_TOKEN = '__r'; var CHECKBOX_RADIO_TOKEN = '__c'; function model ( el, dir, _warn ) { warn$1 = _warn; var value = dir.value; var modifiers = dir.modifiers; var tag = el.tag; var type = el.attrsMap.type; if (process.env.NODE_ENV !== 'production') { // inputs with type="file" are read only and setting the input's // value will throw an error. if (tag === 'input' && type === 'file') { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\" type=\"file\">:\n" + "File inputs are read only. Use a v-on:change listener instead." ); } } if (el.component) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false } else if (tag === 'select') { genSelect(el, value, modifiers); } else if (tag === 'input' && type === 'checkbox') { genCheckboxModel(el, value, modifiers); } else if (tag === 'input' && type === 'radio') { genRadioModel(el, value, modifiers); } else if (tag === 'input' || tag === 'textarea') { genDefaultModel(el, value, modifiers); } else if (!config.isReservedTag(tag)) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false } else if (process.env.NODE_ENV !== 'production') { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "v-model is not supported on this element type. " + 'If you are working with contenteditable, it\'s recommended to ' + 'wrap a library dedicated for that purpose inside a custom component.' ); } // ensure runtime directive metadata return true } function genCheckboxModel ( el, value, modifiers ) { var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; var trueValueBinding = getBindingAttr(el, 'true-value') || 'true'; var falseValueBinding = getBindingAttr(el, 'false-value') || 'false'; addProp(el, 'checked', "Array.isArray(" + value + ")" + "?_i(" + value + "," + valueBinding + ")>-1" + ( trueValueBinding === 'true' ? (":(" + value + ")") : (":_q(" + value + "," + trueValueBinding + ")") ) ); addHandler(el, 'change', "var $$a=" + value + "," + '$$el=$event.target,' + "$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");" + 'if(Array.isArray($$a)){' + "var $$v=" + (number ? '_n(' + valueBinding + ')' : valueBinding) + "," + '$$i=_i($$a,$$v);' + "if($$el.checked){$$i<0&&(" + value + "=$$a.concat([$$v]))}" + "else{$$i>-1&&(" + value + "=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}" + "}else{" + (genAssignmentCode(value, '$$c')) + "}", null, true ); } function genRadioModel ( el, value, modifiers ) { var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; valueBinding = number ? ("_n(" + valueBinding + ")") : valueBinding; addProp(el, 'checked', ("_q(" + value + "," + valueBinding + ")")); addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true); } function genSelect ( el, value, modifiers ) { var number = modifiers && modifiers.number; var selectedVal = "Array.prototype.filter" + ".call($event.target.options,function(o){return o.selected})" + ".map(function(o){var val = \"_value\" in o ? o._value : o.value;" + "return " + (number ? '_n(val)' : 'val') + "})"; var assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]'; var code = "var $$selectedVal = " + selectedVal + ";"; code = code + " " + (genAssignmentCode(value, assignment)); addHandler(el, 'change', code, null, true); } function genDefaultModel ( el, value, modifiers ) { var type = el.attrsMap.type; // warn if v-bind:value conflicts with v-model if (process.env.NODE_ENV !== 'production') { var value$1 = el.attrsMap['v-bind:value'] || el.attrsMap[':value']; if (value$1) { var binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value'; warn$1( binding + "=\"" + value$1 + "\" conflicts with v-model on the same element " + 'because the latter already expands to a value binding internally' ); } } var ref = modifiers || {}; var lazy = ref.lazy; var number = ref.number; var trim = ref.trim; var needCompositionGuard = !lazy && type !== 'range'; var event = lazy ? 'change' : type === 'range' ? RANGE_TOKEN : 'input'; var valueExpression = '$event.target.value'; if (trim) { valueExpression = "$event.target.value.trim()"; } if (number) { valueExpression = "_n(" + valueExpression + ")"; } var code = genAssignmentCode(value, valueExpression); if (needCompositionGuard) { code = "if($event.target.composing)return;" + code; } addProp(el, 'value', ("(" + value + ")")); addHandler(el, event, code, null, true); if (trim || number) { addHandler(el, 'blur', '$forceUpdate()'); } } /* */ // normalize v-model event tokens that can only be determined at runtime. // it's important to place the event as the first in the array because // the whole point is ensuring the v-model callback gets called before // user-attached handlers. function normalizeEvents (on) { /* istanbul ignore if */ if (isDef(on[RANGE_TOKEN])) { // IE input[type=range] only supports `change` event var event = isIE ? 'change' : 'input'; on[event] = [].concat(on[RANGE_TOKEN], on[event] || []); delete on[RANGE_TOKEN]; } // This was originally intended to fix #4521 but no longer necessary // after 2.5. Keeping it for backwards compat with generated code from < 2.4 /* istanbul ignore if */ if (isDef(on[CHECKBOX_RADIO_TOKEN])) { on.change = [].concat(on[CHECKBOX_RADIO_TOKEN], on.change || []); delete on[CHECKBOX_RADIO_TOKEN]; } } var target$1; function createOnceHandler (handler, event, capture) { var _target = target$1; // save current target element in closure return function onceHandler () { var res = handler.apply(null, arguments); if (res !== null) { remove$2(event, onceHandler, capture, _target); } } } function add$1 ( event, handler, once$$1, capture, passive ) { handler = withMacroTask(handler); if (once$$1) { handler = createOnceHandler(handler, event, capture); } target$1.addEventListener( event, handler, supportsPassive ? { capture: capture, passive: passive } : capture ); } function remove$2 ( event, handler, capture, _target ) { (_target || target$1).removeEventListener( event, handler._withTask || handler, capture ); } function updateDOMListeners (oldVnode, vnode) { if (isUndef(oldVnode.data.on) && isUndef(vnode.data.on)) { return } var on = vnode.data.on || {}; var oldOn = oldVnode.data.on || {}; target$1 = vnode.elm; normalizeEvents(on); updateListeners(on, oldOn, add$1, remove$2, vnode.context); target$1 = undefined; } var events = { create: updateDOMListeners, update: updateDOMListeners }; /* */ function updateDOMProps (oldVnode, vnode) { if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) { return } var key, cur; var elm = vnode.elm; var oldProps = oldVnode.data.domProps || {}; var props = vnode.data.domProps || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(props.__ob__)) { props = vnode.data.domProps = extend({}, props); } for (key in oldProps) { if (isUndef(props[key])) { elm[key] = ''; } } for (key in props) { cur = props[key]; // ignore children if the node has textContent or innerHTML, // as these will throw away existing DOM nodes and cause removal errors // on subsequent patches (#3360) if (key === 'textContent' || key === 'innerHTML') { if (vnode.children) { vnode.children.length = 0; } if (cur === oldProps[key]) { continue } // #6601 work around Chrome version <= 55 bug where single textNode // replaced by innerHTML/textContent retains its parentNode property if (elm.childNodes.length === 1) { elm.removeChild(elm.childNodes[0]); } } if (key === 'value') { // store value as _value as well since // non-string values will be stringified elm._value = cur; // avoid resetting cursor position when value is the same var strCur = isUndef(cur) ? '' : String(cur); if (shouldUpdateValue(elm, strCur)) { elm.value = strCur; } } else { elm[key] = cur; } } } // check platforms/web/util/attrs.js acceptValue function shouldUpdateValue (elm, checkVal) { return (!elm.composing && ( elm.tagName === 'OPTION' || isDirty(elm, checkVal) || isInputChanged(elm, checkVal) )) } function isDirty (elm, checkVal) { // return true when textbox (.number and .trim) loses focus and its value is // not equal to the updated value var notInFocus = true; // #6157 // work around IE bug when accessing document.activeElement in an iframe try { notInFocus = document.activeElement !== elm; } catch (e) {} return notInFocus && elm.value !== checkVal } function isInputChanged (elm, newVal) { var value = elm.value; var modifiers = elm._vModifiers; // injected by v-model runtime if (isDef(modifiers) && modifiers.number) { return toNumber(value) !== toNumber(newVal) } if (isDef(modifiers) && modifiers.trim) { return value.trim() !== newVal.trim() } return value !== newVal } var domProps = { create: updateDOMProps, update: updateDOMProps }; /* */ var parseStyleText = cached(function (cssText) { var res = {}; var listDelimiter = /;(?![^(]*\))/g; var propertyDelimiter = /:(.+)/; cssText.split(listDelimiter).forEach(function (item) { if (item) { var tmp = item.split(propertyDelimiter); tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim()); } }); return res }); // merge static and dynamic style data on the same vnode function normalizeStyleData (data) { var style = normalizeStyleBinding(data.style); // static style is pre-processed into an object during compilation // and is always a fresh object, so it's safe to merge into it return data.staticStyle ? extend(data.staticStyle, style) : style } // normalize possible array / string values into Object function normalizeStyleBinding (bindingStyle) { if (Array.isArray(bindingStyle)) { return toObject(bindingStyle) } if (typeof bindingStyle === 'string') { return parseStyleText(bindingStyle) } return bindingStyle } /** * parent component style should be after child's * so that parent component's style could override it */ function getStyle (vnode, checkChild) { var res = {}; var styleData; if (checkChild) { var childNode = vnode; while (childNode.componentInstance) { childNode = childNode.componentInstance._vnode; if (childNode.data && (styleData = normalizeStyleData(childNode.data))) { extend(res, styleData); } } } if ((styleData = normalizeStyleData(vnode.data))) { extend(res, styleData); } var parentNode = vnode; while ((parentNode = parentNode.parent)) { if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) { extend(res, styleData); } } return res } /* */ var cssVarRE = /^--/; var importantRE = /\s*!important$/; var setProp = function (el, name, val) { /* istanbul ignore if */ if (cssVarRE.test(name)) { el.style.setProperty(name, val); } else if (importantRE.test(val)) { el.style.setProperty(name, val.replace(importantRE, ''), 'important'); } else { var normalizedName = normalize(name); if (Array.isArray(val)) { // Support values array created by autoprefixer, e.g. // {display: ["-webkit-box", "-ms-flexbox", "flex"]} // Set them one by one, and the browser will only set those it can recognize for (var i = 0, len = val.length; i < len; i++) { el.style[normalizedName] = val[i]; } } else { el.style[normalizedName] = val; } } }; var vendorNames = ['Webkit', 'Moz', 'ms']; var emptyStyle; var normalize = cached(function (prop) { emptyStyle = emptyStyle || document.createElement('div').style; prop = camelize(prop); if (prop !== 'filter' && (prop in emptyStyle)) { return prop } var capName = prop.charAt(0).toUpperCase() + prop.slice(1); for (var i = 0; i < vendorNames.length; i++) { var name = vendorNames[i] + capName; if (name in emptyStyle) { return name } } }); function updateStyle (oldVnode, vnode) { var data = vnode.data; var oldData = oldVnode.data; if (isUndef(data.staticStyle) && isUndef(data.style) && isUndef(oldData.staticStyle) && isUndef(oldData.style) ) { return } var cur, name; var el = vnode.elm; var oldStaticStyle = oldData.staticStyle; var oldStyleBinding = oldData.normalizedStyle || oldData.style || {}; // if static style exists, stylebinding already merged into it when doing normalizeStyleData var oldStyle = oldStaticStyle || oldStyleBinding; var style = normalizeStyleBinding(vnode.data.style) || {}; // store normalized style under a different key for next diff // make sure to clone it if it's reactive, since the user likely wants // to mutate it. vnode.data.normalizedStyle = isDef(style.__ob__) ? extend({}, style) : style; var newStyle = getStyle(vnode, true); for (name in oldStyle) { if (isUndef(newStyle[name])) { setProp(el, name, ''); } } for (name in newStyle) { cur = newStyle[name]; if (cur !== oldStyle[name]) { // ie9 setting to null has no effect, must use empty string setProp(el, name, cur == null ? '' : cur); } } } var style = { create: updateStyle, update: updateStyle }; /* */ /** * Add class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function addClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function (c) { return el.classList.add(c); }); } else { el.classList.add(cls); } } else { var cur = " " + (el.getAttribute('class') || '') + " "; if (cur.indexOf(' ' + cls + ' ') < 0) { el.setAttribute('class', (cur + cls).trim()); } } } /** * Remove class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function removeClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function (c) { return el.classList.remove(c); }); } else { el.classList.remove(cls); } if (!el.classList.length) { el.removeAttribute('class'); } } else { var cur = " " + (el.getAttribute('class') || '') + " "; var tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } cur = cur.trim(); if (cur) { el.setAttribute('class', cur); } else { el.removeAttribute('class'); } } } /* */ function resolveTransition (def) { if (!def) { return } /* istanbul ignore else */ if (typeof def === 'object') { var res = {}; if (def.css !== false) { extend(res, autoCssTransition(def.name || 'v')); } extend(res, def); return res } else if (typeof def === 'string') { return autoCssTransition(def) } } var autoCssTransition = cached(function (name) { return { enterClass: (name + "-enter"), enterToClass: (name + "-enter-to"), enterActiveClass: (name + "-enter-active"), leaveClass: (name + "-leave"), leaveToClass: (name + "-leave-to"), leaveActiveClass: (name + "-leave-active") } }); var hasTransition = inBrowser && !isIE9; var TRANSITION = 'transition'; var ANIMATION = 'animation'; // Transition property/event sniffing var transitionProp = 'transition'; var transitionEndEvent = 'transitionend'; var animationProp = 'animation'; var animationEndEvent = 'animationend'; if (hasTransition) { /* istanbul ignore if */ if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined ) { transitionProp = 'WebkitTransition'; transitionEndEvent = 'webkitTransitionEnd'; } if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined ) { animationProp = 'WebkitAnimation'; animationEndEvent = 'webkitAnimationEnd'; } } // binding to window is necessary to make hot reload work in IE in strict mode var raf = inBrowser ? window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : setTimeout : /* istanbul ignore next */ function (fn) { return fn(); }; function nextFrame (fn) { raf(function () { raf(fn); }); } function addTransitionClass (el, cls) { var transitionClasses = el._transitionClasses || (el._transitionClasses = []); if (transitionClasses.indexOf(cls) < 0) { transitionClasses.push(cls); addClass(el, cls); } } function removeTransitionClass (el, cls) { if (el._transitionClasses) { remove(el._transitionClasses, cls); } removeClass(el, cls); } function whenTransitionEnds ( el, expectedType, cb ) { var ref = getTransitionInfo(el, expectedType); var type = ref.type; var timeout = ref.timeout; var propCount = ref.propCount; if (!type) { return cb() } var event = type === TRANSITION ? transitionEndEvent : animationEndEvent; var ended = 0; var end = function () { el.removeEventListener(event, onEnd); cb(); }; var onEnd = function (e) { if (e.target === el) { if (++ended >= propCount) { end(); } } }; setTimeout(function () { if (ended < propCount) { end(); } }, timeout + 1); el.addEventListener(event, onEnd); } var transformRE = /\b(transform|all)(,|$)/; function getTransitionInfo (el, expectedType) { var styles = window.getComputedStyle(el); var transitionDelays = styles[transitionProp + 'Delay'].split(', '); var transitionDurations = styles[transitionProp + 'Duration'].split(', '); var transitionTimeout = getTimeout(transitionDelays, transitionDurations); var animationDelays = styles[animationProp + 'Delay'].split(', '); var animationDurations = styles[animationProp + 'Duration'].split(', '); var animationTimeout = getTimeout(animationDelays, animationDurations); var type; var timeout = 0; var propCount = 0; /* istanbul ignore if */ if (expectedType === TRANSITION) { if (transitionTimeout > 0) { type = TRANSITION; timeout = transitionTimeout; propCount = transitionDurations.length; } } else if (expectedType === ANIMATION) { if (animationTimeout > 0) { type = ANIMATION; timeout = animationTimeout; propCount = animationDurations.length; } } else { timeout = Math.max(transitionTimeout, animationTimeout); type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null; propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0; } var hasTransform = type === TRANSITION && transformRE.test(styles[transitionProp + 'Property']); return { type: type, timeout: timeout, propCount: propCount, hasTransform: hasTransform } } function getTimeout (delays, durations) { /* istanbul ignore next */ while (delays.length < durations.length) { delays = delays.concat(delays); } return Math.max.apply(null, durations.map(function (d, i) { return toMs(d) + toMs(delays[i]) })) } function toMs (s) { return Number(s.slice(0, -1)) * 1000 } /* */ function enter (vnode, toggleDisplay) { var el = vnode.elm; // call leave callback now if (isDef(el._leaveCb)) { el._leaveCb.cancelled = true; el._leaveCb(); } var data = resolveTransition(vnode.data.transition); if (isUndef(data)) { return } /* istanbul ignore if */ if (isDef(el._enterCb) || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var enterClass = data.enterClass; var enterToClass = data.enterToClass; var enterActiveClass = data.enterActiveClass; var appearClass = data.appearClass; var appearToClass = data.appearToClass; var appearActiveClass = data.appearActiveClass; var beforeEnter = data.beforeEnter; var enter = data.enter; var afterEnter = data.afterEnter; var enterCancelled = data.enterCancelled; var beforeAppear = data.beforeAppear; var appear = data.appear; var afterAppear = data.afterAppear; var appearCancelled = data.appearCancelled; var duration = data.duration; // activeInstance will always be the <transition> component managing this // transition. One edge case to check is when the <transition> is placed // as the root node of a child component. In that case we need to check // <transition>'s parent for appear check. var context = activeInstance; var transitionNode = activeInstance.$vnode; while (transitionNode && transitionNode.parent) { transitionNode = transitionNode.parent; context = transitionNode.context; } var isAppear = !context._isMounted || !vnode.isRootInsert; if (isAppear && !appear && appear !== '') { return } var startClass = isAppear && appearClass ? appearClass : enterClass; var activeClass = isAppear && appearActiveClass ? appearActiveClass : enterActiveClass; var toClass = isAppear && appearToClass ? appearToClass : enterToClass; var beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter; var enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter; var afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter; var enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled; var explicitEnterDuration = toNumber( isObject(duration) ? duration.enter : duration ); if (process.env.NODE_ENV !== 'production' && explicitEnterDuration != null) { checkDuration(explicitEnterDuration, 'enter', vnode); } var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(enterHook); var cb = el._enterCb = once(function () { if (expectsCSS) { removeTransitionClass(el, toClass); removeTransitionClass(el, activeClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, startClass); } enterCancelledHook && enterCancelledHook(el); } else { afterEnterHook && afterEnterHook(el); } el._enterCb = null; }); if (!vnode.data.show) { // remove pending leave element on enter by injecting an insert hook mergeVNodeHook(vnode, 'insert', function () { var parent = el.parentNode; var pendingNode = parent && parent._pending && parent._pending[vnode.key]; if (pendingNode && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb ) { pendingNode.elm._leaveCb(); } enterHook && enterHook(el, cb); }); } // start enter transition beforeEnterHook && beforeEnterHook(el); if (expectsCSS) { addTransitionClass(el, startClass); addTransitionClass(el, activeClass); nextFrame(function () { addTransitionClass(el, toClass); removeTransitionClass(el, startClass); if (!cb.cancelled && !userWantsControl) { if (isValidDuration(explicitEnterDuration)) { setTimeout(cb, explicitEnterDuration); } else { whenTransitionEnds(el, type, cb); } } }); } if (vnode.data.show) { toggleDisplay && toggleDisplay(); enterHook && enterHook(el, cb); } if (!expectsCSS && !userWantsControl) { cb(); } } function leave (vnode, rm) { var el = vnode.elm; // call enter callback now if (isDef(el._enterCb)) { el._enterCb.cancelled = true; el._enterCb(); } var data = resolveTransition(vnode.data.transition); if (isUndef(data) || el.nodeType !== 1) { return rm() } /* istanbul ignore if */ if (isDef(el._leaveCb)) { return } var css = data.css; var type = data.type; var leaveClass = data.leaveClass; var leaveToClass = data.leaveToClass; var leaveActiveClass = data.leaveActiveClass; var beforeLeave = data.beforeLeave; var leave = data.leave; var afterLeave = data.afterLeave; var leaveCancelled = data.leaveCancelled; var delayLeave = data.delayLeave; var duration = data.duration; var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(leave); var explicitLeaveDuration = toNumber( isObject(duration) ? duration.leave : duration ); if (process.env.NODE_ENV !== 'production' && isDef(explicitLeaveDuration)) { checkDuration(explicitLeaveDuration, 'leave', vnode); } var cb = el._leaveCb = once(function () { if (el.parentNode && el.parentNode._pending) { el.parentNode._pending[vnode.key] = null; } if (expectsCSS) { removeTransitionClass(el, leaveToClass); removeTransitionClass(el, leaveActiveClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, leaveClass); } leaveCancelled && leaveCancelled(el); } else { rm(); afterLeave && afterLeave(el); } el._leaveCb = null; }); if (delayLeave) { delayLeave(performLeave); } else { performLeave(); } function performLeave () { // the delayed leave may have already been cancelled if (cb.cancelled) { return } // record leaving element if (!vnode.data.show) { (el.parentNode._pending || (el.parentNode._pending = {}))[(vnode.key)] = vnode; } beforeLeave && beforeLeave(el); if (expectsCSS) { addTransitionClass(el, leaveClass); addTransitionClass(el, leaveActiveClass); nextFrame(function () { addTransitionClass(el, leaveToClass); removeTransitionClass(el, leaveClass); if (!cb.cancelled && !userWantsControl) { if (isValidDuration(explicitLeaveDuration)) { setTimeout(cb, explicitLeaveDuration); } else { whenTransitionEnds(el, type, cb); } } }); } leave && leave(el, cb); if (!expectsCSS && !userWantsControl) { cb(); } } } // only used in dev mode function checkDuration (val, name, vnode) { if (typeof val !== 'number') { warn( "<transition> explicit " + name + " duration is not a valid number - " + "got " + (JSON.stringify(val)) + ".", vnode.context ); } else if (isNaN(val)) { warn( "<transition> explicit " + name + " duration is NaN - " + 'the duration expression might be incorrect.', vnode.context ); } } function isValidDuration (val) { return typeof val === 'number' && !isNaN(val) } /** * Normalize a transition hook's argument length. The hook may be: * - a merged hook (invoker) with the original in .fns * - a wrapped component method (check ._length) * - a plain function (.length) */ function getHookArgumentsLength (fn) { if (isUndef(fn)) { return false } var invokerFns = fn.fns; if (isDef(invokerFns)) { // invoker return getHookArgumentsLength( Array.isArray(invokerFns) ? invokerFns[0] : invokerFns ) } else { return (fn._length || fn.length) > 1 } } function _enter (_, vnode) { if (vnode.data.show !== true) { enter(vnode); } } var transition = inBrowser ? { create: _enter, activate: _enter, remove: function remove$$1 (vnode, rm) { /* istanbul ignore else */ if (vnode.data.show !== true) { leave(vnode, rm); } else { rm(); } } } : {}; var platformModules = [ attrs, klass, events, domProps, style, transition ]; /* */ // the directive module should be applied last, after all // built-in modules have been applied. var modules = platformModules.concat(baseModules); var patch = createPatchFunction({ nodeOps: nodeOps, modules: modules }); /** * Not type checking this file because flow doesn't like attaching * properties to Elements. */ /* istanbul ignore if */ if (isIE9) { // http://www.matts411.com/post/internet-explorer-9-oninput/ document.addEventListener('selectionchange', function () { var el = document.activeElement; if (el && el.vmodel) { trigger(el, 'input'); } }); } var directive = { inserted: function inserted (el, binding, vnode, oldVnode) { if (vnode.tag === 'select') { // #6903 if (oldVnode.elm && !oldVnode.elm._vOptions) { mergeVNodeHook(vnode, 'postpatch', function () { directive.componentUpdated(el, binding, vnode); }); } else { setSelected(el, binding, vnode.context); } el._vOptions = [].map.call(el.options, getValue); } else if (vnode.tag === 'textarea' || isTextInputType(el.type)) { el._vModifiers = binding.modifiers; if (!binding.modifiers.lazy) { // Safari < 10.2 & UIWebView doesn't fire compositionend when // switching focus before confirming composition choice // this also fixes the issue where some browsers e.g. iOS Chrome // fires "change" instead of "input" on autocomplete. el.addEventListener('change', onCompositionEnd); if (!isAndroid) { el.addEventListener('compositionstart', onCompositionStart); el.addEventListener('compositionend', onCompositionEnd); } /* istanbul ignore if */ if (isIE9) { el.vmodel = true; } } } }, componentUpdated: function componentUpdated (el, binding, vnode) { if (vnode.tag === 'select') { setSelected(el, binding, vnode.context); // in case the options rendered by v-for have changed, // it's possible that the value is out-of-sync with the rendered options. // detect such cases and filter out values that no longer has a matching // option in the DOM. var prevOptions = el._vOptions; var curOptions = el._vOptions = [].map.call(el.options, getValue); if (curOptions.some(function (o, i) { return !looseEqual(o, prevOptions[i]); })) { // trigger change event if // no matching option found for at least one value var needReset = el.multiple ? binding.value.some(function (v) { return hasNoMatchingOption(v, curOptions); }) : binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, curOptions); if (needReset) { trigger(el, 'change'); } } } } }; function setSelected (el, binding, vm) { actuallySetSelected(el, binding, vm); /* istanbul ignore if */ if (isIE || isEdge) { setTimeout(function () { actuallySetSelected(el, binding, vm); }, 0); } } function actuallySetSelected (el, binding, vm) { var value = binding.value; var isMultiple = el.multiple; if (isMultiple && !Array.isArray(value)) { process.env.NODE_ENV !== 'production' && warn( "<select multiple v-model=\"" + (binding.expression) + "\"> " + "expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)), vm ); return } var selected, option; for (var i = 0, l = el.options.length; i < l; i++) { option = el.options[i]; if (isMultiple) { selected = looseIndexOf(value, getValue(option)) > -1; if (option.selected !== selected) { option.selected = selected; } } else { if (looseEqual(getValue(option), value)) { if (el.selectedIndex !== i) { el.selectedIndex = i; } return } } } if (!isMultiple) { el.selectedIndex = -1; } } function hasNoMatchingOption (value, options) { return options.every(function (o) { return !looseEqual(o, value); }) } function getValue (option) { return '_value' in option ? option._value : option.value } function onCompositionStart (e) { e.target.composing = true; } function onCompositionEnd (e) { // prevent triggering an input event for no reason if (!e.target.composing) { return } e.target.composing = false; trigger(e.target, 'input'); } function trigger (el, type) { var e = document.createEvent('HTMLEvents'); e.initEvent(type, true, true); el.dispatchEvent(e); } /* */ // recursively search for possible transition defined inside the component root function locateNode (vnode) { return vnode.componentInstance && (!vnode.data || !vnode.data.transition) ? locateNode(vnode.componentInstance._vnode) : vnode } var show = { bind: function bind (el, ref, vnode) { var value = ref.value; vnode = locateNode(vnode); var transition$$1 = vnode.data && vnode.data.transition; var originalDisplay = el.__vOriginalDisplay = el.style.display === 'none' ? '' : el.style.display; if (value && transition$$1) { vnode.data.show = true; enter(vnode, function () { el.style.display = originalDisplay; }); } else { el.style.display = value ? originalDisplay : 'none'; } }, update: function update (el, ref, vnode) { var value = ref.value; var oldValue = ref.oldValue; /* istanbul ignore if */ if (value === oldValue) { return } vnode = locateNode(vnode); var transition$$1 = vnode.data && vnode.data.transition; if (transition$$1) { vnode.data.show = true; if (value) { enter(vnode, function () { el.style.display = el.__vOriginalDisplay; }); } else { leave(vnode, function () { el.style.display = 'none'; }); } } else { el.style.display = value ? el.__vOriginalDisplay : 'none'; } }, unbind: function unbind ( el, binding, vnode, oldVnode, isDestroy ) { if (!isDestroy) { el.style.display = el.__vOriginalDisplay; } } }; var platformDirectives = { model: directive, show: show }; /* */ // Provides transition support for a single element/component. // supports transition mode (out-in / in-out) var transitionProps = { name: String, appear: Boolean, css: Boolean, mode: String, type: String, enterClass: String, leaveClass: String, enterToClass: String, leaveToClass: String, enterActiveClass: String, leaveActiveClass: String, appearClass: String, appearActiveClass: String, appearToClass: String, duration: [Number, String, Object] }; // in case the child is also an abstract component, e.g. <keep-alive> // we want to recursively retrieve the real component to be rendered function getRealChild (vnode) { var compOptions = vnode && vnode.componentOptions; if (compOptions && compOptions.Ctor.options.abstract) { return getRealChild(getFirstComponentChild(compOptions.children)) } else { return vnode } } function extractTransitionData (comp) { var data = {}; var options = comp.$options; // props for (var key in options.propsData) { data[key] = comp[key]; } // events. // extract listeners and pass them directly to the transition methods var listeners = options._parentListeners; for (var key$1 in listeners) { data[camelize(key$1)] = listeners[key$1]; } return data } function placeholder (h, rawChild) { if (/\d-keep-alive$/.test(rawChild.tag)) { return h('keep-alive', { props: rawChild.componentOptions.propsData }) } } function hasParentTransition (vnode) { while ((vnode = vnode.parent)) { if (vnode.data.transition) { return true } } } function isSameChild (child, oldChild) { return oldChild.key === child.key && oldChild.tag === child.tag } var Transition = { name: 'transition', props: transitionProps, abstract: true, render: function render (h) { var this$1 = this; var children = this.$slots.default; if (!children) { return } // filter out text nodes (possible whitespaces) children = children.filter(function (c) { return c.tag || isAsyncPlaceholder(c); }); /* istanbul ignore if */ if (!children.length) { return } // warn multiple elements if (process.env.NODE_ENV !== 'production' && children.length > 1) { warn( '<transition> can only be used on a single element. Use ' + '<transition-group> for lists.', this.$parent ); } var mode = this.mode; // warn invalid mode if (process.env.NODE_ENV !== 'production' && mode && mode !== 'in-out' && mode !== 'out-in' ) { warn( 'invalid <transition> mode: ' + mode, this.$parent ); } var rawChild = children[0]; // if this is a component root node and the component's // parent container node also has transition, skip. if (hasParentTransition(this.$vnode)) { return rawChild } // apply transition data to child // use getRealChild() to ignore abstract components e.g. keep-alive var child = getRealChild(rawChild); /* istanbul ignore if */ if (!child) { return rawChild } if (this._leaving) { return placeholder(h, rawChild) } // ensure a key that is unique to the vnode type and to this transition // component instance. This key will be used to remove pending leaving nodes // during entering. var id = "__transition-" + (this._uid) + "-"; child.key = child.key == null ? child.isComment ? id + 'comment' : id + child.tag : isPrimitive(child.key) ? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key) : child.key; var data = (child.data || (child.data = {})).transition = extractTransitionData(this); var oldRawChild = this._vnode; var oldChild = getRealChild(oldRawChild); // mark v-show // so that the transition module can hand over the control to the directive if (child.data.directives && child.data.directives.some(function (d) { return d.name === 'show'; })) { child.data.show = true; } if ( oldChild && oldChild.data && !isSameChild(child, oldChild) && !isAsyncPlaceholder(oldChild) && // #6687 component root is a comment node !(oldChild.componentInstance && oldChild.componentInstance._vnode.isComment) ) { // replace old child transition data with fresh one // important for dynamic transitions! var oldData = oldChild.data.transition = extend({}, data); // handle transition mode if (mode === 'out-in') { // return placeholder node and queue update when leave finishes this._leaving = true; mergeVNodeHook(oldData, 'afterLeave', function () { this$1._leaving = false; this$1.$forceUpdate(); }); return placeholder(h, rawChild) } else if (mode === 'in-out') { if (isAsyncPlaceholder(child)) { return oldRawChild } var delayedLeave; var performLeave = function () { delayedLeave(); }; mergeVNodeHook(data, 'afterEnter', performLeave); mergeVNodeHook(data, 'enterCancelled', performLeave); mergeVNodeHook(oldData, 'delayLeave', function (leave) { delayedLeave = leave; }); } } return rawChild } }; /* */ // Provides transition support for list items. // supports move transitions using the FLIP technique. // Because the vdom's children update algorithm is "unstable" - i.e. // it doesn't guarantee the relative positioning of removed elements, // we force transition-group to update its children into two passes: // in the first pass, we remove all nodes that need to be removed, // triggering their leaving transition; in the second pass, we insert/move // into the final desired state. This way in the second pass removed // nodes will remain where they should be. var props = extend({ tag: String, moveClass: String }, transitionProps); delete props.mode; var TransitionGroup = { props: props, render: function render (h) { var tag = this.tag || this.$vnode.data.tag || 'span'; var map = Object.create(null); var prevChildren = this.prevChildren = this.children; var rawChildren = this.$slots.default || []; var children = this.children = []; var transitionData = extractTransitionData(this); for (var i = 0; i < rawChildren.length; i++) { var c = rawChildren[i]; if (c.tag) { if (c.key != null && String(c.key).indexOf('__vlist') !== 0) { children.push(c); map[c.key] = c ;(c.data || (c.data = {})).transition = transitionData; } else if (process.env.NODE_ENV !== 'production') { var opts = c.componentOptions; var name = opts ? (opts.Ctor.options.name || opts.tag || '') : c.tag; warn(("<transition-group> children must be keyed: <" + name + ">")); } } } if (prevChildren) { var kept = []; var removed = []; for (var i$1 = 0; i$1 < prevChildren.length; i$1++) { var c$1 = prevChildren[i$1]; c$1.data.transition = transitionData; c$1.data.pos = c$1.elm.getBoundingClientRect(); if (map[c$1.key]) { kept.push(c$1); } else { removed.push(c$1); } } this.kept = h(tag, null, kept); this.removed = removed; } return h(tag, null, children) }, beforeUpdate: function beforeUpdate () { // force removing pass this.__patch__( this._vnode, this.kept, false, // hydrating true // removeOnly (!important, avoids unnecessary moves) ); this._vnode = this.kept; }, updated: function updated () { var children = this.prevChildren; var moveClass = this.moveClass || ((this.name || 'v') + '-move'); if (!children.length || !this.hasMove(children[0].elm, moveClass)) { return } // we divide the work into three loops to avoid mixing DOM reads and writes // in each iteration - which helps prevent layout thrashing. children.forEach(callPendingCbs); children.forEach(recordPosition); children.forEach(applyTranslation); // force reflow to put everything in position // assign to this to avoid being removed in tree-shaking // $flow-disable-line this._reflow = document.body.offsetHeight; children.forEach(function (c) { if (c.data.moved) { var el = c.elm; var s = el.style; addTransitionClass(el, moveClass); s.transform = s.WebkitTransform = s.transitionDuration = ''; el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) { if (!e || /transform$/.test(e.propertyName)) { el.removeEventListener(transitionEndEvent, cb); el._moveCb = null; removeTransitionClass(el, moveClass); } }); } }); }, methods: { hasMove: function hasMove (el, moveClass) { /* istanbul ignore if */ if (!hasTransition) { return false } /* istanbul ignore if */ if (this._hasMove) { return this._hasMove } // Detect whether an element with the move class applied has // CSS transitions. Since the element may be inside an entering // transition at this very moment, we make a clone of it and remove // all other transition classes applied to ensure only the move class // is applied. var clone = el.cloneNode(); if (el._transitionClasses) { el._transitionClasses.forEach(function (cls) { removeClass(clone, cls); }); } addClass(clone, moveClass); clone.style.display = 'none'; this.$el.appendChild(clone); var info = getTransitionInfo(clone); this.$el.removeChild(clone); return (this._hasMove = info.hasTransform) } } }; function callPendingCbs (c) { /* istanbul ignore if */ if (c.elm._moveCb) { c.elm._moveCb(); } /* istanbul ignore if */ if (c.elm._enterCb) { c.elm._enterCb(); } } function recordPosition (c) { c.data.newPos = c.elm.getBoundingClientRect(); } function applyTranslation (c) { var oldPos = c.data.pos; var newPos = c.data.newPos; var dx = oldPos.left - newPos.left; var dy = oldPos.top - newPos.top; if (dx || dy) { c.data.moved = true; var s = c.elm.style; s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)"; s.transitionDuration = '0s'; } } var platformComponents = { Transition: Transition, TransitionGroup: TransitionGroup }; /* */ // install platform specific utils Vue$3.config.mustUseProp = mustUseProp; Vue$3.config.isReservedTag = isReservedTag; Vue$3.config.isReservedAttr = isReservedAttr; Vue$3.config.getTagNamespace = getTagNamespace; Vue$3.config.isUnknownElement = isUnknownElement; // install platform runtime directives & components extend(Vue$3.options.directives, platformDirectives); extend(Vue$3.options.components, platformComponents); // install platform patch function Vue$3.prototype.__patch__ = inBrowser ? patch : noop; // public mount method Vue$3.prototype.$mount = function ( el, hydrating ) { el = el && inBrowser ? query(el) : undefined; return mountComponent(this, el, hydrating) }; // devtools global hook /* istanbul ignore next */ Vue$3.nextTick(function () { if (config.devtools) { if (devtools) { devtools.emit('init', Vue$3); } else if (process.env.NODE_ENV !== 'production' && isChrome) { console[console.info ? 'info' : 'log']( 'Download the Vue Devtools extension for a better development experience:\n' + 'https://github.com/vuejs/vue-devtools' ); } } if (process.env.NODE_ENV !== 'production' && config.productionTip !== false && inBrowser && typeof console !== 'undefined' ) { console[console.info ? 'info' : 'log']( "You are running Vue in development mode.\n" + "Make sure to turn on production mode when deploying for production.\n" + "See more tips at https://vuejs.org/guide/deployment.html" ); } }, 0); /* */ var defaultTagRE = /\{\{((?:.|\n)+?)\}\}/g; var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g; var buildRegex = cached(function (delimiters) { var open = delimiters[0].replace(regexEscapeRE, '\\$&'); var close = delimiters[1].replace(regexEscapeRE, '\\$&'); return new RegExp(open + '((?:.|\\n)+?)' + close, 'g') }); function parseText ( text, delimiters ) { var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE; if (!tagRE.test(text)) { return } var tokens = []; var lastIndex = tagRE.lastIndex = 0; var match, index; while ((match = tagRE.exec(text))) { index = match.index; // push text token if (index > lastIndex) { tokens.push(JSON.stringify(text.slice(lastIndex, index))); } // tag token var exp = parseFilters(match[1].trim()); tokens.push(("_s(" + exp + ")")); lastIndex = index + match[0].length; } if (lastIndex < text.length) { tokens.push(JSON.stringify(text.slice(lastIndex))); } return tokens.join('+') } /* */ function transformNode (el, options) { var warn = options.warn || baseWarn; var staticClass = getAndRemoveAttr(el, 'class'); if (process.env.NODE_ENV !== 'production' && staticClass) { var expression = parseText(staticClass, options.delimiters); if (expression) { warn( "class=\"" + staticClass + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div class="{{ val }}">, use <div :class="val">.' ); } } if (staticClass) { el.staticClass = JSON.stringify(staticClass); } var classBinding = getBindingAttr(el, 'class', false /* getStatic */); if (classBinding) { el.classBinding = classBinding; } } function genData (el) { var data = ''; if (el.staticClass) { data += "staticClass:" + (el.staticClass) + ","; } if (el.classBinding) { data += "class:" + (el.classBinding) + ","; } return data } var klass$1 = { staticKeys: ['staticClass'], transformNode: transformNode, genData: genData }; /* */ function transformNode$1 (el, options) { var warn = options.warn || baseWarn; var staticStyle = getAndRemoveAttr(el, 'style'); if (staticStyle) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { var expression = parseText(staticStyle, options.delimiters); if (expression) { warn( "style=\"" + staticStyle + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div style="{{ val }}">, use <div :style="val">.' ); } } el.staticStyle = JSON.stringify(parseStyleText(staticStyle)); } var styleBinding = getBindingAttr(el, 'style', false /* getStatic */); if (styleBinding) { el.styleBinding = styleBinding; } } function genData$1 (el) { var data = ''; if (el.staticStyle) { data += "staticStyle:" + (el.staticStyle) + ","; } if (el.styleBinding) { data += "style:(" + (el.styleBinding) + "),"; } return data } var style$1 = { staticKeys: ['staticStyle'], transformNode: transformNode$1, genData: genData$1 }; /* */ var decoder; var he = { decode: function decode (html) { decoder = decoder || document.createElement('div'); decoder.innerHTML = html; return decoder.textContent } }; /* */ var isUnaryTag = makeMap( 'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' + 'link,meta,param,source,track,wbr' ); // Elements that you can, intentionally, leave open // (and which close themselves) var canBeLeftOpenTag = makeMap( 'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source' ); // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content var isNonPhrasingTag = makeMap( 'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' + 'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' + 'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' + 'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' + 'title,tr,track' ); /** * Not type-checking this file because it's mostly vendor code. */ /*! * HTML Parser By John Resig (ejohn.org) * Modified by Juriy "kangax" Zaytsev * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js */ // Regular Expressions for parsing tags and attributes var attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/; // could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName // but for Vue templates we can enforce a simple charset var ncname = '[a-zA-Z_][\\w\\-\\.]*'; var qnameCapture = "((?:" + ncname + "\\:)?" + ncname + ")"; var startTagOpen = new RegExp(("^<" + qnameCapture)); var startTagClose = /^\s*(\/?)>/; var endTag = new RegExp(("^<\\/" + qnameCapture + "[^>]*>")); var doctype = /^<!DOCTYPE [^>]+>/i; var comment = /^<!--/; var conditionalComment = /^<!\[/; var IS_REGEX_CAPTURING_BROKEN = false; 'x'.replace(/x(.)?/g, function (m, g) { IS_REGEX_CAPTURING_BROKEN = g === ''; }); // Special Elements (can contain anything) var isPlainTextElement = makeMap('script,style,textarea', true); var reCache = {}; var decodingMap = { '&lt;': '<', '&gt;': '>', '&quot;': '"', '&amp;': '&', '&#10;': '\n', '&#9;': '\t' }; var encodedAttr = /&(?:lt|gt|quot|amp);/g; var encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10|#9);/g; // #5992 var isIgnoreNewlineTag = makeMap('pre,textarea', true); var shouldIgnoreFirstNewline = function (tag, html) { return tag && isIgnoreNewlineTag(tag) && html[0] === '\n'; }; function decodeAttr (value, shouldDecodeNewlines) { var re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr; return value.replace(re, function (match) { return decodingMap[match]; }) } function parseHTML (html, options) { var stack = []; var expectHTML = options.expectHTML; var isUnaryTag$$1 = options.isUnaryTag || no; var canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no; var index = 0; var last, lastTag; while (html) { last = html; // Make sure we're not in a plaintext content element like script/style if (!lastTag || !isPlainTextElement(lastTag)) { var textEnd = html.indexOf('<'); if (textEnd === 0) { // Comment: if (comment.test(html)) { var commentEnd = html.indexOf('-->'); if (commentEnd >= 0) { if (options.shouldKeepComment) { options.comment(html.substring(4, commentEnd)); } advance(commentEnd + 3); continue } } // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment if (conditionalComment.test(html)) { var conditionalEnd = html.indexOf(']>'); if (conditionalEnd >= 0) { advance(conditionalEnd + 2); continue } } // Doctype: var doctypeMatch = html.match(doctype); if (doctypeMatch) { advance(doctypeMatch[0].length); continue } // End tag: var endTagMatch = html.match(endTag); if (endTagMatch) { var curIndex = index; advance(endTagMatch[0].length); parseEndTag(endTagMatch[1], curIndex, index); continue } // Start tag: var startTagMatch = parseStartTag(); if (startTagMatch) { handleStartTag(startTagMatch); if (shouldIgnoreFirstNewline(lastTag, html)) { advance(1); } continue } } var text = (void 0), rest = (void 0), next = (void 0); if (textEnd >= 0) { rest = html.slice(textEnd); while ( !endTag.test(rest) && !startTagOpen.test(rest) && !comment.test(rest) && !conditionalComment.test(rest) ) { // < in plain text, be forgiving and treat it as text next = rest.indexOf('<', 1); if (next < 0) { break } textEnd += next; rest = html.slice(textEnd); } text = html.substring(0, textEnd); advance(textEnd); } if (textEnd < 0) { text = html; html = ''; } if (options.chars && text) { options.chars(text); } } else { var endTagLength = 0; var stackedTag = lastTag.toLowerCase(); var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i')); var rest$1 = html.replace(reStackedTag, function (all, text, endTag) { endTagLength = endTag.length; if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') { text = text .replace(/<!--([\s\S]*?)-->/g, '$1') .replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1'); } if (shouldIgnoreFirstNewline(stackedTag, text)) { text = text.slice(1); } if (options.chars) { options.chars(text); } return '' }); index += html.length - rest$1.length; html = rest$1; parseEndTag(stackedTag, index - endTagLength, index); } if (html === last) { options.chars && options.chars(html); if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) { options.warn(("Mal-formatted tag at end of template: \"" + html + "\"")); } break } } // Clean up any remaining tags parseEndTag(); function advance (n) { index += n; html = html.substring(n); } function parseStartTag () { var start = html.match(startTagOpen); if (start) { var match = { tagName: start[1], attrs: [], start: index }; advance(start[0].length); var end, attr; while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) { advance(attr[0].length); match.attrs.push(attr); } if (end) { match.unarySlash = end[1]; advance(end[0].length); match.end = index; return match } } } function handleStartTag (match) { var tagName = match.tagName; var unarySlash = match.unarySlash; if (expectHTML) { if (lastTag === 'p' && isNonPhrasingTag(tagName)) { parseEndTag(lastTag); } if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) { parseEndTag(tagName); } } var unary = isUnaryTag$$1(tagName) || !!unarySlash; var l = match.attrs.length; var attrs = new Array(l); for (var i = 0; i < l; i++) { var args = match.attrs[i]; // hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778 if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) { if (args[3] === '') { delete args[3]; } if (args[4] === '') { delete args[4]; } if (args[5] === '') { delete args[5]; } } var value = args[3] || args[4] || args[5] || ''; var shouldDecodeNewlines = tagName === 'a' && args[1] === 'href' ? options.shouldDecodeNewlinesForHref : options.shouldDecodeNewlines; attrs[i] = { name: args[1], value: decodeAttr(value, shouldDecodeNewlines) }; } if (!unary) { stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs }); lastTag = tagName; } if (options.start) { options.start(tagName, attrs, unary, match.start, match.end); } } function parseEndTag (tagName, start, end) { var pos, lowerCasedTagName; if (start == null) { start = index; } if (end == null) { end = index; } if (tagName) { lowerCasedTagName = tagName.toLowerCase(); } // Find the closest opened tag of the same type if (tagName) { for (pos = stack.length - 1; pos >= 0; pos--) { if (stack[pos].lowerCasedTag === lowerCasedTagName) { break } } } else { // If no tag name is provided, clean shop pos = 0; } if (pos >= 0) { // Close all the open elements, up the stack for (var i = stack.length - 1; i >= pos; i--) { if (process.env.NODE_ENV !== 'production' && (i > pos || !tagName) && options.warn ) { options.warn( ("tag <" + (stack[i].tag) + "> has no matching end tag.") ); } if (options.end) { options.end(stack[i].tag, start, end); } } // Remove the open elements from the stack stack.length = pos; lastTag = pos && stack[pos - 1].tag; } else if (lowerCasedTagName === 'br') { if (options.start) { options.start(tagName, [], true, start, end); } } else if (lowerCasedTagName === 'p') { if (options.start) { options.start(tagName, [], false, start, end); } if (options.end) { options.end(tagName, start, end); } } } } /* */ var onRE = /^@|^v-on:/; var dirRE = /^v-|^@|^:/; var forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/; var forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/; var argRE = /:(.*)$/; var bindRE = /^:|^v-bind:/; var modifierRE = /\.[^.]+/g; var decodeHTMLCached = cached(he.decode); // configurable state var warn$2; var delimiters; var transforms; var preTransforms; var postTransforms; var platformIsPreTag; var platformMustUseProp; var platformGetTagNamespace; function createASTElement ( tag, attrs, parent ) { return { type: 1, tag: tag, attrsList: attrs, attrsMap: makeAttrsMap(attrs), parent: parent, children: [] } } /** * Convert HTML string to AST. */ function parse ( template, options ) { warn$2 = options.warn || baseWarn; platformIsPreTag = options.isPreTag || no; platformMustUseProp = options.mustUseProp || no; platformGetTagNamespace = options.getTagNamespace || no; transforms = pluckModuleFunction(options.modules, 'transformNode'); preTransforms = pluckModuleFunction(options.modules, 'preTransformNode'); postTransforms = pluckModuleFunction(options.modules, 'postTransformNode'); delimiters = options.delimiters; var stack = []; var preserveWhitespace = options.preserveWhitespace !== false; var root; var currentParent; var inVPre = false; var inPre = false; var warned = false; function warnOnce (msg) { if (!warned) { warned = true; warn$2(msg); } } function endPre (element) { // check pre state if (element.pre) { inVPre = false; } if (platformIsPreTag(element.tag)) { inPre = false; } } parseHTML(template, { warn: warn$2, expectHTML: options.expectHTML, isUnaryTag: options.isUnaryTag, canBeLeftOpenTag: options.canBeLeftOpenTag, shouldDecodeNewlines: options.shouldDecodeNewlines, shouldDecodeNewlinesForHref: options.shouldDecodeNewlinesForHref, shouldKeepComment: options.comments, start: function start (tag, attrs, unary) { // check namespace. // inherit parent ns if there is one var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag); // handle IE svg bug /* istanbul ignore if */ if (isIE && ns === 'svg') { attrs = guardIESVGBug(attrs); } var element = createASTElement(tag, attrs, currentParent); if (ns) { element.ns = ns; } if (isForbiddenTag(element) && !isServerRendering()) { element.forbidden = true; process.env.NODE_ENV !== 'production' && warn$2( 'Templates should only be responsible for mapping the state to the ' + 'UI. Avoid placing tags with side-effects in your templates, such as ' + "<" + tag + ">" + ', as they will not be parsed.' ); } // apply pre-transforms for (var i = 0; i < preTransforms.length; i++) { element = preTransforms[i](element, options) || element; } if (!inVPre) { processPre(element); if (element.pre) { inVPre = true; } } if (platformIsPreTag(element.tag)) { inPre = true; } if (inVPre) { processRawAttrs(element); } else if (!element.processed) { // structural directives processFor(element); processIf(element); processOnce(element); // element-scope stuff processElement(element, options); } function checkRootConstraints (el) { if (process.env.NODE_ENV !== 'production') { if (el.tag === 'slot' || el.tag === 'template') { warnOnce( "Cannot use <" + (el.tag) + "> as component root element because it may " + 'contain multiple nodes.' ); } if (el.attrsMap.hasOwnProperty('v-for')) { warnOnce( 'Cannot use v-for on stateful component root element because ' + 'it renders multiple elements.' ); } } } // tree management if (!root) { root = element; checkRootConstraints(root); } else if (!stack.length) { // allow root elements with v-if, v-else-if and v-else if (root.if && (element.elseif || element.else)) { checkRootConstraints(element); addIfCondition(root, { exp: element.elseif, block: element }); } else if (process.env.NODE_ENV !== 'production') { warnOnce( "Component template should contain exactly one root element. " + "If you are using v-if on multiple elements, " + "use v-else-if to chain them instead." ); } } if (currentParent && !element.forbidden) { if (element.elseif || element.else) { processIfConditions(element, currentParent); } else if (element.slotScope) { // scoped slot currentParent.plain = false; var name = element.slotTarget || '"default"';(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element; } else { currentParent.children.push(element); element.parent = currentParent; } } if (!unary) { currentParent = element; stack.push(element); } else { endPre(element); } // apply post-transforms for (var i$1 = 0; i$1 < postTransforms.length; i$1++) { postTransforms[i$1](element, options); } }, end: function end () { // remove trailing whitespace var element = stack[stack.length - 1]; var lastNode = element.children[element.children.length - 1]; if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) { element.children.pop(); } // pop stack stack.length -= 1; currentParent = stack[stack.length - 1]; endPre(element); }, chars: function chars (text) { if (!currentParent) { if (process.env.NODE_ENV !== 'production') { if (text === template) { warnOnce( 'Component template requires a root element, rather than just text.' ); } else if ((text = text.trim())) { warnOnce( ("text \"" + text + "\" outside root element will be ignored.") ); } } return } // IE textarea placeholder bug /* istanbul ignore if */ if (isIE && currentParent.tag === 'textarea' && currentParent.attrsMap.placeholder === text ) { return } var children = currentParent.children; text = inPre || text.trim() ? isTextTag(currentParent) ? text : decodeHTMLCached(text) // only preserve whitespace if its not right after a starting tag : preserveWhitespace && children.length ? ' ' : ''; if (text) { var expression; if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) { children.push({ type: 2, expression: expression, text: text }); } else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') { children.push({ type: 3, text: text }); } } }, comment: function comment (text) { currentParent.children.push({ type: 3, text: text, isComment: true }); } }); return root } function processPre (el) { if (getAndRemoveAttr(el, 'v-pre') != null) { el.pre = true; } } function processRawAttrs (el) { var l = el.attrsList.length; if (l) { var attrs = el.attrs = new Array(l); for (var i = 0; i < l; i++) { attrs[i] = { name: el.attrsList[i].name, value: JSON.stringify(el.attrsList[i].value) }; } } else if (!el.pre) { // non root node in pre blocks with no attributes el.plain = true; } } function processElement (element, options) { processKey(element); // determine whether this is a plain element after // removing structural attributes element.plain = !element.key && !element.attrsList.length; processRef(element); processSlot(element); processComponent(element); for (var i = 0; i < transforms.length; i++) { element = transforms[i](element, options) || element; } processAttrs(element); } function processKey (el) { var exp = getBindingAttr(el, 'key'); if (exp) { if (process.env.NODE_ENV !== 'production' && el.tag === 'template') { warn$2("<template> cannot be keyed. Place the key on real elements instead."); } el.key = exp; } } function processRef (el) { var ref = getBindingAttr(el, 'ref'); if (ref) { el.ref = ref; el.refInFor = checkInFor(el); } } function processFor (el) { var exp; if ((exp = getAndRemoveAttr(el, 'v-for'))) { var inMatch = exp.match(forAliasRE); if (!inMatch) { process.env.NODE_ENV !== 'production' && warn$2( ("Invalid v-for expression: " + exp) ); return } el.for = inMatch[2].trim(); var alias = inMatch[1].trim(); var iteratorMatch = alias.match(forIteratorRE); if (iteratorMatch) { el.alias = iteratorMatch[1].trim(); el.iterator1 = iteratorMatch[2].trim(); if (iteratorMatch[3]) { el.iterator2 = iteratorMatch[3].trim(); } } else { el.alias = alias; } } } function processIf (el) { var exp = getAndRemoveAttr(el, 'v-if'); if (exp) { el.if = exp; addIfCondition(el, { exp: exp, block: el }); } else { if (getAndRemoveAttr(el, 'v-else') != null) { el.else = true; } var elseif = getAndRemoveAttr(el, 'v-else-if'); if (elseif) { el.elseif = elseif; } } } function processIfConditions (el, parent) { var prev = findPrevElement(parent.children); if (prev && prev.if) { addIfCondition(prev, { exp: el.elseif, block: el }); } else if (process.env.NODE_ENV !== 'production') { warn$2( "v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " + "used on element <" + (el.tag) + "> without corresponding v-if." ); } } function findPrevElement (children) { var i = children.length; while (i--) { if (children[i].type === 1) { return children[i] } else { if (process.env.NODE_ENV !== 'production' && children[i].text !== ' ') { warn$2( "text \"" + (children[i].text.trim()) + "\" between v-if and v-else(-if) " + "will be ignored." ); } children.pop(); } } } function addIfCondition (el, condition) { if (!el.ifConditions) { el.ifConditions = []; } el.ifConditions.push(condition); } function processOnce (el) { var once$$1 = getAndRemoveAttr(el, 'v-once'); if (once$$1 != null) { el.once = true; } } function processSlot (el) { if (el.tag === 'slot') { el.slotName = getBindingAttr(el, 'name'); if (process.env.NODE_ENV !== 'production' && el.key) { warn$2( "`key` does not work on <slot> because slots are abstract outlets " + "and can possibly expand into multiple elements. " + "Use the key on a wrapping element instead." ); } } else { var slotScope; if (el.tag === 'template') { slotScope = getAndRemoveAttr(el, 'scope'); /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && slotScope) { warn$2( "the \"scope\" attribute for scoped slots have been deprecated and " + "replaced by \"slot-scope\" since 2.5. The new \"slot-scope\" attribute " + "can also be used on plain elements in addition to <template> to " + "denote scoped slots.", true ); } el.slotScope = slotScope || getAndRemoveAttr(el, 'slot-scope'); } else if ((slotScope = getAndRemoveAttr(el, 'slot-scope'))) { el.slotScope = slotScope; } var slotTarget = getBindingAttr(el, 'slot'); if (slotTarget) { el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget; // preserve slot as an attribute for native shadow DOM compat // only for non-scoped slots. if (el.tag !== 'template' && !el.slotScope) { addAttr(el, 'slot', slotTarget); } } } } function processComponent (el) { var binding; if ((binding = getBindingAttr(el, 'is'))) { el.component = binding; } if (getAndRemoveAttr(el, 'inline-template') != null) { el.inlineTemplate = true; } } function processAttrs (el) { var list = el.attrsList; var i, l, name, rawName, value, modifiers, isProp; for (i = 0, l = list.length; i < l; i++) { name = rawName = list[i].name; value = list[i].value; if (dirRE.test(name)) { // mark element as dynamic el.hasBindings = true; // modifiers modifiers = parseModifiers(name); if (modifiers) { name = name.replace(modifierRE, ''); } if (bindRE.test(name)) { // v-bind name = name.replace(bindRE, ''); value = parseFilters(value); isProp = false; if (modifiers) { if (modifiers.prop) { isProp = true; name = camelize(name); if (name === 'innerHtml') { name = 'innerHTML'; } } if (modifiers.camel) { name = camelize(name); } if (modifiers.sync) { addHandler( el, ("update:" + (camelize(name))), genAssignmentCode(value, "$event") ); } } if (isProp || ( !el.component && platformMustUseProp(el.tag, el.attrsMap.type, name) )) { addProp(el, name, value); } else { addAttr(el, name, value); } } else if (onRE.test(name)) { // v-on name = name.replace(onRE, ''); addHandler(el, name, value, modifiers, false, warn$2); } else { // normal directives name = name.replace(dirRE, ''); // parse arg var argMatch = name.match(argRE); var arg = argMatch && argMatch[1]; if (arg) { name = name.slice(0, -(arg.length + 1)); } addDirective(el, name, rawName, value, arg, modifiers); if (process.env.NODE_ENV !== 'production' && name === 'model') { checkForAliasModel(el, value); } } } else { // literal attribute if (process.env.NODE_ENV !== 'production') { var expression = parseText(value, delimiters); if (expression) { warn$2( name + "=\"" + value + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div id="{{ val }}">, use <div :id="val">.' ); } } addAttr(el, name, JSON.stringify(value)); // #6887 firefox doesn't update muted state if set via attribute // even immediately after element creation if (!el.component && name === 'muted' && platformMustUseProp(el.tag, el.attrsMap.type, name)) { addProp(el, name, 'true'); } } } } function checkInFor (el) { var parent = el; while (parent) { if (parent.for !== undefined) { return true } parent = parent.parent; } return false } function parseModifiers (name) { var match = name.match(modifierRE); if (match) { var ret = {}; match.forEach(function (m) { ret[m.slice(1)] = true; }); return ret } } function makeAttrsMap (attrs) { var map = {}; for (var i = 0, l = attrs.length; i < l; i++) { if ( process.env.NODE_ENV !== 'production' && map[attrs[i].name] && !isIE && !isEdge ) { warn$2('duplicate attribute: ' + attrs[i].name); } map[attrs[i].name] = attrs[i].value; } return map } // for script (e.g. type="x/template") or style, do not decode content function isTextTag (el) { return el.tag === 'script' || el.tag === 'style' } function isForbiddenTag (el) { return ( el.tag === 'style' || (el.tag === 'script' && ( !el.attrsMap.type || el.attrsMap.type === 'text/javascript' )) ) } var ieNSBug = /^xmlns:NS\d+/; var ieNSPrefix = /^NS\d+:/; /* istanbul ignore next */ function guardIESVGBug (attrs) { var res = []; for (var i = 0; i < attrs.length; i++) { var attr = attrs[i]; if (!ieNSBug.test(attr.name)) { attr.name = attr.name.replace(ieNSPrefix, ''); res.push(attr); } } return res } function checkForAliasModel (el, value) { var _el = el; while (_el) { if (_el.for && _el.alias === value) { warn$2( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "You are binding v-model directly to a v-for iteration alias. " + "This will not be able to modify the v-for source array because " + "writing to the alias is like modifying a function local variable. " + "Consider using an array of objects and use v-model on an object property instead." ); } _el = _el.parent; } } /* */ /** * Expand input[v-model] with dyanmic type bindings into v-if-else chains * Turn this: * <input v-model="data[type]" :type="type"> * into this: * <input v-if="type === 'checkbox'" type="checkbox" v-model="data[type]"> * <input v-else-if="type === 'radio'" type="radio" v-model="data[type]"> * <input v-else :type="type" v-model="data[type]"> */ function preTransformNode (el, options) { if (el.tag === 'input') { var map = el.attrsMap; if (map['v-model'] && (map['v-bind:type'] || map[':type'])) { var typeBinding = getBindingAttr(el, 'type'); var ifCondition = getAndRemoveAttr(el, 'v-if', true); var ifConditionExtra = ifCondition ? ("&&(" + ifCondition + ")") : ""; var hasElse = getAndRemoveAttr(el, 'v-else', true) != null; var elseIfCondition = getAndRemoveAttr(el, 'v-else-if', true); // 1. checkbox var branch0 = cloneASTElement(el); // process for on the main node processFor(branch0); addRawAttr(branch0, 'type', 'checkbox'); processElement(branch0, options); branch0.processed = true; // prevent it from double-processed branch0.if = "(" + typeBinding + ")==='checkbox'" + ifConditionExtra; addIfCondition(branch0, { exp: branch0.if, block: branch0 }); // 2. add radio else-if condition var branch1 = cloneASTElement(el); getAndRemoveAttr(branch1, 'v-for', true); addRawAttr(branch1, 'type', 'radio'); processElement(branch1, options); addIfCondition(branch0, { exp: "(" + typeBinding + ")==='radio'" + ifConditionExtra, block: branch1 }); // 3. other var branch2 = cloneASTElement(el); getAndRemoveAttr(branch2, 'v-for', true); addRawAttr(branch2, ':type', typeBinding); processElement(branch2, options); addIfCondition(branch0, { exp: ifCondition, block: branch2 }); if (hasElse) { branch0.else = true; } else if (elseIfCondition) { branch0.elseif = elseIfCondition; } return branch0 } } } function cloneASTElement (el) { return createASTElement(el.tag, el.attrsList.slice(), el.parent) } function addRawAttr (el, name, value) { el.attrsMap[name] = value; el.attrsList.push({ name: name, value: value }); } var model$2 = { preTransformNode: preTransformNode }; var modules$1 = [ klass$1, style$1, model$2 ]; /* */ function text (el, dir) { if (dir.value) { addProp(el, 'textContent', ("_s(" + (dir.value) + ")")); } } /* */ function html (el, dir) { if (dir.value) { addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")")); } } var directives$1 = { model: model, text: text, html: html }; /* */ var baseOptions = { expectHTML: true, modules: modules$1, directives: directives$1, isPreTag: isPreTag, isUnaryTag: isUnaryTag, mustUseProp: mustUseProp, canBeLeftOpenTag: canBeLeftOpenTag, isReservedTag: isReservedTag, getTagNamespace: getTagNamespace, staticKeys: genStaticKeys(modules$1) }; /* */ var isStaticKey; var isPlatformReservedTag; var genStaticKeysCached = cached(genStaticKeys$1); /** * Goal of the optimizer: walk the generated template AST tree * and detect sub-trees that are purely static, i.e. parts of * the DOM that never needs to change. * * Once we detect these sub-trees, we can: * * 1. Hoist them into constants, so that we no longer need to * create fresh nodes for them on each re-render; * 2. Completely skip them in the patching process. */ function optimize (root, options) { if (!root) { return } isStaticKey = genStaticKeysCached(options.staticKeys || ''); isPlatformReservedTag = options.isReservedTag || no; // first pass: mark all non-static nodes. markStatic$1(root); // second pass: mark static roots. markStaticRoots(root, false); } function genStaticKeys$1 (keys) { return makeMap( 'type,tag,attrsList,attrsMap,plain,parent,children,attrs' + (keys ? ',' + keys : '') ) } function markStatic$1 (node) { node.static = isStatic(node); if (node.type === 1) { // do not make component slot content static. this avoids // 1. components not able to mutate slot nodes // 2. static slot content fails for hot-reloading if ( !isPlatformReservedTag(node.tag) && node.tag !== 'slot' && node.attrsMap['inline-template'] == null ) { return } for (var i = 0, l = node.children.length; i < l; i++) { var child = node.children[i]; markStatic$1(child); if (!child.static) { node.static = false; } } if (node.ifConditions) { for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) { var block = node.ifConditions[i$1].block; markStatic$1(block); if (!block.static) { node.static = false; } } } } } function markStaticRoots (node, isInFor) { if (node.type === 1) { if (node.static || node.once) { node.staticInFor = isInFor; } // For a node to qualify as a static root, it should have children that // are not just static text. Otherwise the cost of hoisting out will // outweigh the benefits and it's better off to just always render it fresh. if (node.static && node.children.length && !( node.children.length === 1 && node.children[0].type === 3 )) { node.staticRoot = true; return } else { node.staticRoot = false; } if (node.children) { for (var i = 0, l = node.children.length; i < l; i++) { markStaticRoots(node.children[i], isInFor || !!node.for); } } if (node.ifConditions) { for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) { markStaticRoots(node.ifConditions[i$1].block, isInFor); } } } } function isStatic (node) { if (node.type === 2) { // expression return false } if (node.type === 3) { // text return true } return !!(node.pre || ( !node.hasBindings && // no dynamic bindings !node.if && !node.for && // not v-if or v-for or v-else !isBuiltInTag(node.tag) && // not a built-in isPlatformReservedTag(node.tag) && // not a component !isDirectChildOfTemplateFor(node) && Object.keys(node).every(isStaticKey) )) } function isDirectChildOfTemplateFor (node) { while (node.parent) { node = node.parent; if (node.tag !== 'template') { return false } if (node.for) { return true } } return false } /* */ var fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/; var simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/; // keyCode aliases var keyCodes = { esc: 27, tab: 9, enter: 13, space: 32, up: 38, left: 37, right: 39, down: 40, 'delete': [8, 46] }; // #4868: modifiers that prevent the execution of the listener // need to explicitly return null so that we can determine whether to remove // the listener for .once var genGuard = function (condition) { return ("if(" + condition + ")return null;"); }; var modifierCode = { stop: '$event.stopPropagation();', prevent: '$event.preventDefault();', self: genGuard("$event.target !== $event.currentTarget"), ctrl: genGuard("!$event.ctrlKey"), shift: genGuard("!$event.shiftKey"), alt: genGuard("!$event.altKey"), meta: genGuard("!$event.metaKey"), left: genGuard("'button' in $event && $event.button !== 0"), middle: genGuard("'button' in $event && $event.button !== 1"), right: genGuard("'button' in $event && $event.button !== 2") }; function genHandlers ( events, isNative, warn ) { var res = isNative ? 'nativeOn:{' : 'on:{'; for (var name in events) { res += "\"" + name + "\":" + (genHandler(name, events[name])) + ","; } return res.slice(0, -1) + '}' } function genHandler ( name, handler ) { if (!handler) { return 'function(){}' } if (Array.isArray(handler)) { return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]") } var isMethodPath = simplePathRE.test(handler.value); var isFunctionExpression = fnExpRE.test(handler.value); if (!handler.modifiers) { return isMethodPath || isFunctionExpression ? handler.value : ("function($event){" + (handler.value) + "}") // inline statement } else { var code = ''; var genModifierCode = ''; var keys = []; for (var key in handler.modifiers) { if (modifierCode[key]) { genModifierCode += modifierCode[key]; // left/right if (keyCodes[key]) { keys.push(key); } } else if (key === 'exact') { var modifiers = (handler.modifiers); genModifierCode += genGuard( ['ctrl', 'shift', 'alt', 'meta'] .filter(function (keyModifier) { return !modifiers[keyModifier]; }) .map(function (keyModifier) { return ("$event." + keyModifier + "Key"); }) .join('||') ); } else { keys.push(key); } } if (keys.length) { code += genKeyFilter(keys); } // Make sure modifiers like prevent and stop get executed after key filtering if (genModifierCode) { code += genModifierCode; } var handlerCode = isMethodPath ? handler.value + '($event)' : isFunctionExpression ? ("(" + (handler.value) + ")($event)") : handler.value; return ("function($event){" + code + handlerCode + "}") } } function genKeyFilter (keys) { return ("if(!('button' in $event)&&" + (keys.map(genFilterCode).join('&&')) + ")return null;") } function genFilterCode (key) { var keyVal = parseInt(key, 10); if (keyVal) { return ("$event.keyCode!==" + keyVal) } var code = keyCodes[key]; return ( "_k($event.keyCode," + (JSON.stringify(key)) + "," + (JSON.stringify(code)) + "," + "$event.key)" ) } /* */ function on (el, dir) { if (process.env.NODE_ENV !== 'production' && dir.modifiers) { warn("v-on without argument does not support modifiers."); } el.wrapListeners = function (code) { return ("_g(" + code + "," + (dir.value) + ")"); }; } /* */ function bind$1 (el, dir) { el.wrapData = function (code) { return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + "," + (dir.modifiers && dir.modifiers.prop ? 'true' : 'false') + (dir.modifiers && dir.modifiers.sync ? ',true' : '') + ")") }; } /* */ var baseDirectives = { on: on, bind: bind$1, cloak: noop }; /* */ var CodegenState = function CodegenState (options) { this.options = options; this.warn = options.warn || baseWarn; this.transforms = pluckModuleFunction(options.modules, 'transformCode'); this.dataGenFns = pluckModuleFunction(options.modules, 'genData'); this.directives = extend(extend({}, baseDirectives), options.directives); var isReservedTag = options.isReservedTag || no; this.maybeComponent = function (el) { return !isReservedTag(el.tag); }; this.onceId = 0; this.staticRenderFns = []; }; function generate ( ast, options ) { var state = new CodegenState(options); var code = ast ? genElement(ast, state) : '_c("div")'; return { render: ("with(this){return " + code + "}"), staticRenderFns: state.staticRenderFns } } function genElement (el, state) { if (el.staticRoot && !el.staticProcessed) { return genStatic(el, state) } else if (el.once && !el.onceProcessed) { return genOnce(el, state) } else if (el.for && !el.forProcessed) { return genFor(el, state) } else if (el.if && !el.ifProcessed) { return genIf(el, state) } else if (el.tag === 'template' && !el.slotTarget) { return genChildren(el, state) || 'void 0' } else if (el.tag === 'slot') { return genSlot(el, state) } else { // component or element var code; if (el.component) { code = genComponent(el.component, el, state); } else { var data = el.plain ? undefined : genData$2(el, state); var children = el.inlineTemplate ? null : genChildren(el, state, true); code = "_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")"; } // module transforms for (var i = 0; i < state.transforms.length; i++) { code = state.transforms[i](el, code); } return code } } // hoist static sub-trees out function genStatic (el, state, once$$1) { el.staticProcessed = true; state.staticRenderFns.push(("with(this){return " + (genElement(el, state)) + "}")); return ("_m(" + (state.staticRenderFns.length - 1) + "," + (el.staticInFor ? 'true' : 'false') + "," + (once$$1 ? 'true' : 'false') + ")") } // v-once function genOnce (el, state) { el.onceProcessed = true; if (el.if && !el.ifProcessed) { return genIf(el, state) } else if (el.staticInFor) { var key = ''; var parent = el.parent; while (parent) { if (parent.for) { key = parent.key; break } parent = parent.parent; } if (!key) { process.env.NODE_ENV !== 'production' && state.warn( "v-once can only be used inside v-for that is keyed. " ); return genElement(el, state) } return ("_o(" + (genElement(el, state)) + "," + (state.onceId++) + "," + key + ")") } else { return genStatic(el, state, true) } } function genIf ( el, state, altGen, altEmpty ) { el.ifProcessed = true; // avoid recursion return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty) } function genIfConditions ( conditions, state, altGen, altEmpty ) { if (!conditions.length) { return altEmpty || '_e()' } var condition = conditions.shift(); if (condition.exp) { return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions, state, altGen, altEmpty))) } else { return ("" + (genTernaryExp(condition.block))) } // v-if with v-once should generate code like (a)?_m(0):_m(1) function genTernaryExp (el) { return altGen ? altGen(el, state) : el.once ? genOnce(el, state) : genElement(el, state) } } function genFor ( el, state, altGen, altHelper ) { var exp = el.for; var alias = el.alias; var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : ''; var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : ''; if (process.env.NODE_ENV !== 'production' && state.maybeComponent(el) && el.tag !== 'slot' && el.tag !== 'template' && !el.key ) { state.warn( "<" + (el.tag) + " v-for=\"" + alias + " in " + exp + "\">: component lists rendered with " + "v-for should have explicit keys. " + "See https://vuejs.org/guide/list.html#key for more info.", true /* tip */ ); } el.forProcessed = true; // avoid recursion return (altHelper || '_l') + "((" + exp + ")," + "function(" + alias + iterator1 + iterator2 + "){" + "return " + ((altGen || genElement)(el, state)) + '})' } function genData$2 (el, state) { var data = '{'; // directives first. // directives may mutate the el's other properties before they are generated. var dirs = genDirectives(el, state); if (dirs) { data += dirs + ','; } // key if (el.key) { data += "key:" + (el.key) + ","; } // ref if (el.ref) { data += "ref:" + (el.ref) + ","; } if (el.refInFor) { data += "refInFor:true,"; } // pre if (el.pre) { data += "pre:true,"; } // record original tag name for components using "is" attribute if (el.component) { data += "tag:\"" + (el.tag) + "\","; } // module data generation functions for (var i = 0; i < state.dataGenFns.length; i++) { data += state.dataGenFns[i](el); } // attributes if (el.attrs) { data += "attrs:{" + (genProps(el.attrs)) + "},"; } // DOM props if (el.props) { data += "domProps:{" + (genProps(el.props)) + "},"; } // event handlers if (el.events) { data += (genHandlers(el.events, false, state.warn)) + ","; } if (el.nativeEvents) { data += (genHandlers(el.nativeEvents, true, state.warn)) + ","; } // slot target // only for non-scoped slots if (el.slotTarget && !el.slotScope) { data += "slot:" + (el.slotTarget) + ","; } // scoped slots if (el.scopedSlots) { data += (genScopedSlots(el.scopedSlots, state)) + ","; } // component v-model if (el.model) { data += "model:{value:" + (el.model.value) + ",callback:" + (el.model.callback) + ",expression:" + (el.model.expression) + "},"; } // inline-template if (el.inlineTemplate) { var inlineTemplate = genInlineTemplate(el, state); if (inlineTemplate) { data += inlineTemplate + ","; } } data = data.replace(/,$/, '') + '}'; // v-bind data wrap if (el.wrapData) { data = el.wrapData(data); } // v-on data wrap if (el.wrapListeners) { data = el.wrapListeners(data); } return data } function genDirectives (el, state) { var dirs = el.directives; if (!dirs) { return } var res = 'directives:['; var hasRuntime = false; var i, l, dir, needRuntime; for (i = 0, l = dirs.length; i < l; i++) { dir = dirs[i]; needRuntime = true; var gen = state.directives[dir.name]; if (gen) { // compile-time directive that manipulates AST. // returns true if it also needs a runtime counterpart. needRuntime = !!gen(el, dir, state.warn); } if (needRuntime) { hasRuntime = true; res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:\"" + (dir.arg) + "\"") : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},"; } } if (hasRuntime) { return res.slice(0, -1) + ']' } } function genInlineTemplate (el, state) { var ast = el.children[0]; if (process.env.NODE_ENV !== 'production' && ( el.children.length !== 1 || ast.type !== 1 )) { state.warn('Inline-template components must have exactly one child element.'); } if (ast.type === 1) { var inlineRenderFns = generate(ast, state.options); return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}") } } function genScopedSlots ( slots, state ) { return ("scopedSlots:_u([" + (Object.keys(slots).map(function (key) { return genScopedSlot(key, slots[key], state) }).join(',')) + "])") } function genScopedSlot ( key, el, state ) { if (el.for && !el.forProcessed) { return genForScopedSlot(key, el, state) } var fn = "function(" + (String(el.slotScope)) + "){" + "return " + (el.tag === 'template' ? el.if ? ((el.if) + "?" + (genChildren(el, state) || 'undefined') + ":undefined") : genChildren(el, state) || 'undefined' : genElement(el, state)) + "}"; return ("{key:" + key + ",fn:" + fn + "}") } function genForScopedSlot ( key, el, state ) { var exp = el.for; var alias = el.alias; var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : ''; var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : ''; el.forProcessed = true; // avoid recursion return "_l((" + exp + ")," + "function(" + alias + iterator1 + iterator2 + "){" + "return " + (genScopedSlot(key, el, state)) + '})' } function genChildren ( el, state, checkSkip, altGenElement, altGenNode ) { var children = el.children; if (children.length) { var el$1 = children[0]; // optimize single v-for if (children.length === 1 && el$1.for && el$1.tag !== 'template' && el$1.tag !== 'slot' ) { return (altGenElement || genElement)(el$1, state) } var normalizationType = checkSkip ? getNormalizationType(children, state.maybeComponent) : 0; var gen = altGenNode || genNode; return ("[" + (children.map(function (c) { return gen(c, state); }).join(',')) + "]" + (normalizationType ? ("," + normalizationType) : '')) } } // determine the normalization needed for the children array. // 0: no normalization needed // 1: simple normalization needed (possible 1-level deep nested array) // 2: full normalization needed function getNormalizationType ( children, maybeComponent ) { var res = 0; for (var i = 0; i < children.length; i++) { var el = children[i]; if (el.type !== 1) { continue } if (needsNormalization(el) || (el.ifConditions && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) { res = 2; break } if (maybeComponent(el) || (el.ifConditions && el.ifConditions.some(function (c) { return maybeComponent(c.block); }))) { res = 1; } } return res } function needsNormalization (el) { return el.for !== undefined || el.tag === 'template' || el.tag === 'slot' } function genNode (node, state) { if (node.type === 1) { return genElement(node, state) } if (node.type === 3 && node.isComment) { return genComment(node) } else { return genText(node) } } function genText (text) { return ("_v(" + (text.type === 2 ? text.expression // no need for () because already wrapped in _s() : transformSpecialNewlines(JSON.stringify(text.text))) + ")") } function genComment (comment) { return ("_e(" + (JSON.stringify(comment.text)) + ")") } function genSlot (el, state) { var slotName = el.slotName || '"default"'; var children = genChildren(el, state); var res = "_t(" + slotName + (children ? ("," + children) : ''); var attrs = el.attrs && ("{" + (el.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}"); var bind$$1 = el.attrsMap['v-bind']; if ((attrs || bind$$1) && !children) { res += ",null"; } if (attrs) { res += "," + attrs; } if (bind$$1) { res += (attrs ? '' : ',null') + "," + bind$$1; } return res + ')' } // componentName is el.component, take it as argument to shun flow's pessimistic refinement function genComponent ( componentName, el, state ) { var children = el.inlineTemplate ? null : genChildren(el, state, true); return ("_c(" + componentName + "," + (genData$2(el, state)) + (children ? ("," + children) : '') + ")") } function genProps (props) { var res = ''; for (var i = 0; i < props.length; i++) { var prop = props[i]; res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ","; } return res.slice(0, -1) } // #3895, #4268 function transformSpecialNewlines (text) { return text .replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029') } /* */ // these keywords should not appear inside expressions, but operators like // typeof, instanceof and in are allowed var prohibitedKeywordRE = new RegExp('\\b' + ( 'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' + 'super,throw,while,yield,delete,export,import,return,switch,default,' + 'extends,finally,continue,debugger,function,arguments' ).split(',').join('\\b|\\b') + '\\b'); // these unary operators should not be used as property/method names var unaryOperatorsRE = new RegExp('\\b' + ( 'delete,typeof,void' ).split(',').join('\\s*\\([^\\)]*\\)|\\b') + '\\s*\\([^\\)]*\\)'); // check valid identifier for v-for var identRE = /[A-Za-z_$][\w$]*/; // strip strings in expressions var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g; // detect problematic expressions in a template function detectErrors (ast) { var errors = []; if (ast) { checkNode(ast, errors); } return errors } function checkNode (node, errors) { if (node.type === 1) { for (var name in node.attrsMap) { if (dirRE.test(name)) { var value = node.attrsMap[name]; if (value) { if (name === 'v-for') { checkFor(node, ("v-for=\"" + value + "\""), errors); } else if (onRE.test(name)) { checkEvent(value, (name + "=\"" + value + "\""), errors); } else { checkExpression(value, (name + "=\"" + value + "\""), errors); } } } } if (node.children) { for (var i = 0; i < node.children.length; i++) { checkNode(node.children[i], errors); } } } else if (node.type === 2) { checkExpression(node.expression, node.text, errors); } } function checkEvent (exp, text, errors) { var stipped = exp.replace(stripStringRE, ''); var keywordMatch = stipped.match(unaryOperatorsRE); if (keywordMatch && stipped.charAt(keywordMatch.index - 1) !== '$') { errors.push( "avoid using JavaScript unary operator as property name: " + "\"" + (keywordMatch[0]) + "\" in expression " + (text.trim()) ); } checkExpression(exp, text, errors); } function checkFor (node, text, errors) { checkExpression(node.for || '', text, errors); checkIdentifier(node.alias, 'v-for alias', text, errors); checkIdentifier(node.iterator1, 'v-for iterator', text, errors); checkIdentifier(node.iterator2, 'v-for iterator', text, errors); } function checkIdentifier (ident, type, text, errors) { if (typeof ident === 'string' && !identRE.test(ident)) { errors.push(("invalid " + type + " \"" + ident + "\" in expression: " + (text.trim()))); } } function checkExpression (exp, text, errors) { try { new Function(("return " + exp)); } catch (e) { var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE); if (keywordMatch) { errors.push( "avoid using JavaScript keyword as property name: " + "\"" + (keywordMatch[0]) + "\"\n Raw expression: " + (text.trim()) ); } else { errors.push( "invalid expression: " + (e.message) + " in\n\n" + " " + exp + "\n\n" + " Raw expression: " + (text.trim()) + "\n" ); } } } /* */ function createFunction (code, errors) { try { return new Function(code) } catch (err) { errors.push({ err: err, code: code }); return noop } } function createCompileToFunctionFn (compile) { var cache = Object.create(null); return function compileToFunctions ( template, options, vm ) { options = extend({}, options); var warn$$1 = options.warn || warn; delete options.warn; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { // detect possible CSP restriction try { new Function('return 1'); } catch (e) { if (e.toString().match(/unsafe-eval|CSP/)) { warn$$1( 'It seems you are using the standalone build of Vue.js in an ' + 'environment with Content Security Policy that prohibits unsafe-eval. ' + 'The template compiler cannot work in this environment. Consider ' + 'relaxing the policy to allow unsafe-eval or pre-compiling your ' + 'templates into render functions.' ); } } } // check cache var key = options.delimiters ? String(options.delimiters) + template : template; if (cache[key]) { return cache[key] } // compile var compiled = compile(template, options); // check compilation errors/tips if (process.env.NODE_ENV !== 'production') { if (compiled.errors && compiled.errors.length) { warn$$1( "Error compiling template:\n\n" + template + "\n\n" + compiled.errors.map(function (e) { return ("- " + e); }).join('\n') + '\n', vm ); } if (compiled.tips && compiled.tips.length) { compiled.tips.forEach(function (msg) { return tip(msg, vm); }); } } // turn code into functions var res = {}; var fnGenErrors = []; res.render = createFunction(compiled.render, fnGenErrors); res.staticRenderFns = compiled.staticRenderFns.map(function (code) { return createFunction(code, fnGenErrors) }); // check function generation errors. // this should only happen if there is a bug in the compiler itself. // mostly for codegen development use /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) { warn$$1( "Failed to generate render function:\n\n" + fnGenErrors.map(function (ref) { var err = ref.err; var code = ref.code; return ((err.toString()) + " in\n\n" + code + "\n"); }).join('\n'), vm ); } } return (cache[key] = res) } } /* */ function createCompilerCreator (baseCompile) { return function createCompiler (baseOptions) { function compile ( template, options ) { var finalOptions = Object.create(baseOptions); var errors = []; var tips = []; finalOptions.warn = function (msg, tip) { (tip ? tips : errors).push(msg); }; if (options) { // merge custom modules if (options.modules) { finalOptions.modules = (baseOptions.modules || []).concat(options.modules); } // merge custom directives if (options.directives) { finalOptions.directives = extend( Object.create(baseOptions.directives), options.directives ); } // copy other options for (var key in options) { if (key !== 'modules' && key !== 'directives') { finalOptions[key] = options[key]; } } } var compiled = baseCompile(template, finalOptions); if (process.env.NODE_ENV !== 'production') { errors.push.apply(errors, detectErrors(compiled.ast)); } compiled.errors = errors; compiled.tips = tips; return compiled } return { compile: compile, compileToFunctions: createCompileToFunctionFn(compile) } } } /* */ // `createCompilerCreator` allows creating compilers that use alternative // parser/optimizer/codegen, e.g the SSR optimizing compiler. // Here we just export a default compiler using the default parts. var createCompiler = createCompilerCreator(function baseCompile ( template, options ) { var ast = parse(template.trim(), options); optimize(ast, options); var code = generate(ast, options); return { ast: ast, render: code.render, staticRenderFns: code.staticRenderFns } }); /* */ var ref$1 = createCompiler(baseOptions); var compileToFunctions = ref$1.compileToFunctions; /* */ // check whether current browser encodes a char inside attribute values var div; function getShouldDecode (href) { div = div || document.createElement('div'); div.innerHTML = href ? "<a href=\"\n\"/>" : "<div a=\"\n\"/>"; return div.innerHTML.indexOf('&#10;') > 0 } // #3663: IE encodes newlines inside attribute values while other browsers don't var shouldDecodeNewlines = inBrowser ? getShouldDecode(false) : false; // #6828: chrome encodes content in a[href] var shouldDecodeNewlinesForHref = inBrowser ? getShouldDecode(true) : false; /* */ var idToTemplate = cached(function (id) { var el = query(id); return el && el.innerHTML }); var mount = Vue$3.prototype.$mount; Vue$3.prototype.$mount = function ( el, hydrating ) { el = el && query(el); /* istanbul ignore if */ if (el === document.body || el === document.documentElement) { process.env.NODE_ENV !== 'production' && warn( "Do not mount Vue to <html> or <body> - mount to normal elements instead." ); return this } var options = this.$options; // resolve template/el and convert to render function if (!options.render) { var template = options.template; if (template) { if (typeof template === 'string') { if (template.charAt(0) === '#') { template = idToTemplate(template); /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && !template) { warn( ("Template element not found or is empty: " + (options.template)), this ); } } } else if (template.nodeType) { template = template.innerHTML; } else { if (process.env.NODE_ENV !== 'production') { warn('invalid template option:' + template, this); } return this } } else if (el) { template = getOuterHTML(el); } if (template) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { mark('compile'); } var ref = compileToFunctions(template, { shouldDecodeNewlines: shouldDecodeNewlines, shouldDecodeNewlinesForHref: shouldDecodeNewlinesForHref, delimiters: options.delimiters, comments: options.comments }, this); var render = ref.render; var staticRenderFns = ref.staticRenderFns; options.render = render; options.staticRenderFns = staticRenderFns; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { mark('compile end'); measure(("vue " + (this._name) + " compile"), 'compile', 'compile end'); } } } return mount.call(this, el, hydrating) }; /** * Get outerHTML of elements, taking care * of SVG elements in IE as well. */ function getOuterHTML (el) { if (el.outerHTML) { return el.outerHTML } else { var container = document.createElement('div'); container.appendChild(el.cloneNode(true)); return container.innerHTML } } Vue$3.compile = compileToFunctions; export default Vue$3;
/** @license React v16.1.0 * react-dom-unstable-native-dependencies.production.min.js * * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';var h=require("react-dom"),k=require("object-assign"),l=require("fbjs/lib/emptyFunction"); function n(a){for(var b=arguments.length-1,c="Minified React error #"+a+"; visit http://facebook.github.io/react/docs/error-decoder.html?invariant\x3d"+a,f=0;f<b;f++)c+="\x26args[]\x3d"+encodeURIComponent(arguments[f+1]);b=Error(c+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.");b.name="Invariant Violation";b.framesToPop=1;throw b;}var p=null,q=null,t=null; function u(a){return"topMouseUp"===a||"topTouchEnd"===a||"topTouchCancel"===a}function v(a){return"topMouseMove"===a||"topTouchMove"===a}function w(a){return"topMouseDown"===a||"topTouchStart"===a}function x(a){var b=a._dispatchListeners,c=a._dispatchInstances;Array.isArray(b)?n("103"):void 0;a.currentTarget=b?t(c):null;b=b?b(a):null;a.currentTarget=null;a._dispatchListeners=null;a._dispatchInstances=null;return b}function y(a){do a=a["return"];while(a&&5!==a.tag);return a?a:null} function z(a,b,c){for(var f=[];a;)f.push(a),a=y(a);for(a=f.length;0<a--;)b(f[a],"captured",c);for(a=0;a<f.length;a++)b(f[a],"bubbled",c)}function A(a,b){null==b?n("30"):void 0;if(null==a)return b;if(Array.isArray(a)){if(Array.isArray(b))return a.push.apply(a,b),a;a.push(b);return a}return Array.isArray(b)?[a].concat(b):[a,b]}function B(a,b,c){Array.isArray(a)?a.forEach(b,c):a&&b.call(c,a)} function C(a,b){var c=a.stateNode;if(!c)return null;var f=p(c);if(!f)return null;c=f[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":(f=!f.disabled)||(a=a.type,f=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!f;break a;default:a=!1}if(a)return null;c&&"function"!==typeof c?n("231",b,typeof c):void 0; return c}function D(a,b,c){if(b=C(a,c.dispatchConfig.phasedRegistrationNames[b]))c._dispatchListeners=A(c._dispatchListeners,b),c._dispatchInstances=A(c._dispatchInstances,a)}function E(a){a&&a.dispatchConfig.phasedRegistrationNames&&z(a._targetInst,D,a)}function aa(a){if(a&&a.dispatchConfig.phasedRegistrationNames){var b=a._targetInst;b=b?y(b):null;z(b,D,a)}} function F(a){if(a&&a.dispatchConfig.registrationName){var b=a._targetInst;if(b&&a&&a.dispatchConfig.registrationName){var c=C(b,a.dispatchConfig.registrationName);c&&(a._dispatchListeners=A(a._dispatchListeners,c),a._dispatchInstances=A(a._dispatchInstances,b))}}} var G="dispatchConfig _targetInst nativeEvent isDefaultPrevented isPropagationStopped _dispatchListeners _dispatchInstances".split(" "),ba={type:null,target:null,currentTarget:l.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null}; function H(a,b,c,f){this.dispatchConfig=a;this._targetInst=b;this.nativeEvent=c;a=this.constructor.Interface;for(var d in a)a.hasOwnProperty(d)&&((b=a[d])?this[d]=b(c):"target"===d?this.target=f:this[d]=c[d]);this.isDefaultPrevented=(null!=c.defaultPrevented?c.defaultPrevented:!1===c.returnValue)?l.thatReturnsTrue:l.thatReturnsFalse;this.isPropagationStopped=l.thatReturnsFalse;return this} k(H.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&(a.returnValue=!1),this.isDefaultPrevented=l.thatReturnsTrue)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=l.thatReturnsTrue)},persist:function(){this.isPersistent=l.thatReturnsTrue},isPersistent:l.thatReturnsFalse, destructor:function(){var a=this.constructor.Interface,b;for(b in a)this[b]=null;for(a=0;a<G.length;a++)this[G[a]]=null}});H.Interface=ba;H.augmentClass=function(a,b){function c(){}c.prototype=this.prototype;var f=new c;k(f,a.prototype);a.prototype=f;a.prototype.constructor=a;a.Interface=k({},this.Interface,b);a.augmentClass=this.augmentClass;I(a)};I(H);function ca(a,b,c,f){if(this.eventPool.length){var d=this.eventPool.pop();this.call(d,a,b,c,f);return d}return new this(a,b,c,f)} function da(a){a instanceof this?void 0:n("223");a.destructor();10>this.eventPool.length&&this.eventPool.push(a)}function I(a){a.eventPool=[];a.getPooled=ca;a.release=da}function J(a,b,c,f){return H.call(this,a,b,c,f)}H.augmentClass(J,{touchHistory:function(){return null}});var L=[],M={touchBank:L,numberActiveTouches:0,indexOfSingleActiveTouch:-1,mostRecentTimeStamp:0};function N(a){return a.timeStamp||a.timestamp}function O(a){a=a.identifier;null==a?n("138"):void 0;return a} function ea(a){var b=O(a),c=L[b];c?(c.touchActive=!0,c.startPageX=a.pageX,c.startPageY=a.pageY,c.startTimeStamp=N(a),c.currentPageX=a.pageX,c.currentPageY=a.pageY,c.currentTimeStamp=N(a),c.previousPageX=a.pageX,c.previousPageY=a.pageY,c.previousTimeStamp=N(a)):(c={touchActive:!0,startPageX:a.pageX,startPageY:a.pageY,startTimeStamp:N(a),currentPageX:a.pageX,currentPageY:a.pageY,currentTimeStamp:N(a),previousPageX:a.pageX,previousPageY:a.pageY,previousTimeStamp:N(a)},L[b]=c);M.mostRecentTimeStamp=N(a)} function fa(a){var b=L[O(a)];b?(b.touchActive=!0,b.previousPageX=b.currentPageX,b.previousPageY=b.currentPageY,b.previousTimeStamp=b.currentTimeStamp,b.currentPageX=a.pageX,b.currentPageY=a.pageY,b.currentTimeStamp=N(a),M.mostRecentTimeStamp=N(a)):console.error("Cannot record touch move without a touch start.\nTouch Move: %s\n","Touch Bank: %s",P(a),Q())} function ha(a){var b=L[O(a)];b?(b.touchActive=!1,b.previousPageX=b.currentPageX,b.previousPageY=b.currentPageY,b.previousTimeStamp=b.currentTimeStamp,b.currentPageX=a.pageX,b.currentPageY=a.pageY,b.currentTimeStamp=N(a),M.mostRecentTimeStamp=N(a)):console.error("Cannot record touch end without a touch start.\nTouch End: %s\n","Touch Bank: %s",P(a),Q())}function P(a){return JSON.stringify({identifier:a.identifier,pageX:a.pageX,pageY:a.pageY,timestamp:N(a)})} function Q(){var a=JSON.stringify(L.slice(0,20));20<L.length&&(a+=" (original size: "+L.length+")");return a} var R={recordTouchTrack:function(a,b){if(v(a))b.changedTouches.forEach(fa);else if(w(a))b.changedTouches.forEach(ea),M.numberActiveTouches=b.touches.length,1===M.numberActiveTouches&&(M.indexOfSingleActiveTouch=b.touches[0].identifier);else if(u(a)&&(b.changedTouches.forEach(ha),M.numberActiveTouches=b.touches.length,1===M.numberActiveTouches))for(a=0;a<L.length;a++)if(b=L[a],null!=b&&b.touchActive){M.indexOfSingleActiveTouch=a;break}},touchHistory:M}; function S(a,b){null==b?n("29"):void 0;return null==a?b:Array.isArray(a)?a.concat(b):Array.isArray(b)?[a].concat(b):[a,b]}var T=null,U=0,V=0;function W(a,b){var c=T;T=a;if(null!==X.GlobalResponderHandler)X.GlobalResponderHandler.onChange(c,a,b)} var Y={startShouldSetResponder:{phasedRegistrationNames:{bubbled:"onStartShouldSetResponder",captured:"onStartShouldSetResponderCapture"}},scrollShouldSetResponder:{phasedRegistrationNames:{bubbled:"onScrollShouldSetResponder",captured:"onScrollShouldSetResponderCapture"}},selectionChangeShouldSetResponder:{phasedRegistrationNames:{bubbled:"onSelectionChangeShouldSetResponder",captured:"onSelectionChangeShouldSetResponderCapture"}},moveShouldSetResponder:{phasedRegistrationNames:{bubbled:"onMoveShouldSetResponder", captured:"onMoveShouldSetResponderCapture"}},responderStart:{registrationName:"onResponderStart"},responderMove:{registrationName:"onResponderMove"},responderEnd:{registrationName:"onResponderEnd"},responderRelease:{registrationName:"onResponderRelease"},responderTerminationRequest:{registrationName:"onResponderTerminationRequest"},responderGrant:{registrationName:"onResponderGrant"},responderReject:{registrationName:"onResponderReject"},responderTerminate:{registrationName:"onResponderTerminate"}}, X={_getResponder:function(){return T},eventTypes:Y,extractEvents:function(a,b,c,f){if(w(a))U+=1;else if(u(a))if(0<=U)--U;else return console.error("Ended a touch event which was not counted in `trackedTouchCount`."),null;R.recordTouchTrack(a,c);if(b&&("topScroll"===a&&!c.responderIgnoreScroll||0<U&&"topSelectionChange"===a||w(a)||v(a))){var d=w(a)?Y.startShouldSetResponder:v(a)?Y.moveShouldSetResponder:"topSelectionChange"===a?Y.selectionChangeShouldSetResponder:Y.scrollShouldSetResponder;if(T)b:{var e= T;for(var g=0,r=e;r;r=y(r))g++;r=0;for(var K=b;K;K=y(K))r++;for(;0<g-r;)e=y(e),g--;for(;0<r-g;)b=y(b),r--;for(;g--;){if(e===b||e===b.alternate)break b;e=y(e);b=y(b)}e=null}else e=b;b=e===T;e=J.getPooled(d,e,c,f);e.touchHistory=R.touchHistory;b?B(e,aa):B(e,E);b:{d=e._dispatchListeners;b=e._dispatchInstances;if(Array.isArray(d))for(g=0;g<d.length&&!e.isPropagationStopped();g++){if(d[g](e,b[g])){d=b[g];break b}}else if(d&&d(e,b)){d=b;break b}d=null}e._dispatchInstances=null;e._dispatchListeners=null; e.isPersistent()||e.constructor.release(e);if(d&&d!==T)if(e=J.getPooled(Y.responderGrant,d,c,f),e.touchHistory=R.touchHistory,B(e,F),b=!0===x(e),T)if(g=J.getPooled(Y.responderTerminationRequest,T,c,f),g.touchHistory=R.touchHistory,B(g,F),r=!g._dispatchListeners||x(g),g.isPersistent()||g.constructor.release(g),r){g=J.getPooled(Y.responderTerminate,T,c,f);g.touchHistory=R.touchHistory;B(g,F);var m=S(m,[e,g]);W(d,b)}else d=J.getPooled(Y.responderReject,d,c,f),d.touchHistory=R.touchHistory,B(d,F),m=S(m, d);else m=S(m,e),W(d,b);else m=null}else m=null;d=T&&w(a);e=T&&v(a);b=T&&u(a);if(d=d?Y.responderStart:e?Y.responderMove:b?Y.responderEnd:null)d=J.getPooled(d,T,c,f),d.touchHistory=R.touchHistory,B(d,F),m=S(m,d);d=T&&"topTouchCancel"===a;if(a=T&&!d&&u(a))a:{if((a=c.touches)&&0!==a.length)for(e=0;e<a.length;e++)if(b=a[e].target,null!==b&&void 0!==b&&0!==b){g=q(b);b:{for(b=T;g;){if(b===g||b===g.alternate){b=!0;break b}g=y(g)}b=!1}if(b){a=!1;break a}}a=!0}if(a=d?Y.responderTerminate:a?Y.responderRelease: null)c=J.getPooled(a,T,c,f),c.touchHistory=R.touchHistory,B(c,F),m=S(m,c),W(null);c=R.touchHistory.numberActiveTouches;if(X.GlobalInteractionHandler&&c!==V)X.GlobalInteractionHandler.onChange(c);V=c;return m},GlobalResponderHandler:null,GlobalInteractionHandler:null,injection:{injectGlobalResponderHandler:function(a){X.GlobalResponderHandler=a},injectGlobalInteractionHandler:function(a){X.GlobalInteractionHandler=a}}}; function Z(a){p=a.getFiberCurrentPropsFromNode;q=a.getInstanceFromNode;t=a.getNodeFromInstance}Z(h.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactDOMComponentTree);var ia=Object.freeze({injectComponentTree:Z,ResponderEventPlugin:X,ResponderTouchHistoryStore:R});module.exports=ia;
/** * Copyright JS Foundation and other contributors, http://js.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. **/ module.exports = function(RED) { "use strict"; function StatusNode(n) { RED.nodes.createNode(this,n); var node = this; this.scope = n.scope; this.on("input", function(msg) { this.send(msg); }); } RED.nodes.registerType("status",StatusNode); }
/* angular-moment.js / v1.2.0 / (c) 2013, 2014, 2015, 2016, 2017 Uri Shaked / MIT Licence */ 'format amd'; /* global define */ (function () { 'use strict'; function isUndefinedOrNull(val) { return angular.isUndefined(val) || val === null; } function requireMoment() { try { return require('moment'); // Using nw.js or browserify? } catch (e) { throw new Error('Please install moment via npm. Please reference to: https://github.com/urish/angular-moment'); // Add wiki/troubleshooting section? } } function angularMoment(angular, moment) { if(typeof moment === 'undefined') { if(typeof require === 'function') { moment = requireMoment(); }else{ throw new Error('Moment cannot be found by angular-moment! Please reference to: https://github.com/urish/angular-moment'); // Add wiki/troubleshooting section? } } /** * @ngdoc overview * @name angularMoment * * @description * angularMoment module provides moment.js functionality for angular.js apps. */ angular.module('angularMoment', []) /** * @ngdoc object * @name angularMoment.config:angularMomentConfig * * @description * Common configuration of the angularMoment module */ .constant('angularMomentConfig', { /** * @ngdoc property * @name angularMoment.config.angularMomentConfig#preprocess * @propertyOf angularMoment.config:angularMomentConfig * @returns {function} A preprocessor function that will be applied on all incoming dates * * @description * Defines a preprocessor function to apply on all input dates (e.g. the input of `am-time-ago`, * `amCalendar`, etc.). The function must return a `moment` object. * * @example * // Causes angular-moment to always treat the input values as unix timestamps * angularMomentConfig.preprocess = function(value) { * return moment.unix(value); * } */ preprocess: null, /** * @ngdoc property * @name angularMoment.config.angularMomentConfig#timezone * @propertyOf angularMoment.config:angularMomentConfig * @returns {string} The default timezone * * @description * The default timezone (e.g. 'Europe/London'). Empty string by default (does not apply * any timezone shift). * * NOTE: This option requires moment-timezone >= 0.3.0. */ timezone: null, /** * @ngdoc property * @name angularMoment.config.angularMomentConfig#format * @propertyOf angularMoment.config:angularMomentConfig * @returns {string} The pre-conversion format of the date * * @description * Specify the format of the input date. Essentially it's a * default and saves you from specifying a format in every * element. Overridden by element attr. Null by default. */ format: null, /** * @ngdoc property * @name angularMoment.config.angularMomentConfig#statefulFilters * @propertyOf angularMoment.config:angularMomentConfig * @returns {boolean} Whether angular-moment filters should be stateless (or not) * * @description * Specifies whether the filters included with angular-moment are stateful. * Stateful filters will automatically re-evaluate whenever you change the timezone * or locale settings, but may negatively impact performance. true by default. */ statefulFilters: true }) /** * @ngdoc object * @name angularMoment.object:moment * * @description * moment global (as provided by the moment.js library) */ .constant('moment', moment) /** * @ngdoc object * @name angularMoment.config:amTimeAgoConfig * @module angularMoment * * @description * configuration specific to the amTimeAgo directive */ .constant('amTimeAgoConfig', { /** * @ngdoc property * @name angularMoment.config.amTimeAgoConfig#withoutSuffix * @propertyOf angularMoment.config:amTimeAgoConfig * @returns {boolean} Whether to include a suffix in am-time-ago directive * * @description * Defaults to false. */ withoutSuffix: false, /** * @ngdoc property * @name angularMoment.config.amTimeAgoConfig#serverTime * @propertyOf angularMoment.config:amTimeAgoConfig * @returns {number} Server time in milliseconds since the epoch * * @description * If set, time ago will be calculated relative to the given value. * If null, local time will be used. Defaults to null. */ serverTime: null, /** * @ngdoc property * @name angularMoment.config.amTimeAgoConfig#titleFormat * @propertyOf angularMoment.config:amTimeAgoConfig * @returns {string} The format of the date to be displayed in the title of the element. If null, * the directive set the title of the element. * * @description * The format of the date used for the title of the element. null by default. */ titleFormat: null, /** * @ngdoc property * @name angularMoment.config.amTimeAgoConfig#fullDateThreshold * @propertyOf angularMoment.config:amTimeAgoConfig * @returns {number} The minimum number of days for showing a full date instead of relative time * * @description * The threshold for displaying a full date. The default is null, which means the date will always * be relative, and full date will never be displayed. */ fullDateThreshold: null, /** * @ngdoc property * @name angularMoment.config.amTimeAgoConfig#fullDateFormat * @propertyOf angularMoment.config:amTimeAgoConfig * @returns {string} The format to use when displaying a full date. * * @description * Specify the format of the date when displayed as full date. null by default. */ fullDateFormat: null, fullDateThresholdUnit: 'day' }) /** * @ngdoc directive * @name angularMoment.directive:amTimeAgo * @module angularMoment * * @restrict A */ .directive('amTimeAgo', ['$window', 'moment', 'amMoment', 'amTimeAgoConfig', function ($window, moment, amMoment, amTimeAgoConfig) { return function (scope, element, attr) { var activeTimeout = null; var currentValue; var withoutSuffix = amTimeAgoConfig.withoutSuffix; var titleFormat = amTimeAgoConfig.titleFormat; var fullDateThreshold = amTimeAgoConfig.fullDateThreshold; var fullDateFormat = amTimeAgoConfig.fullDateFormat; var fullDateThresholdUnit = amTimeAgoConfig.fullDateThresholdUnit; var localDate = new Date().getTime(); var modelName = attr.amTimeAgo; var currentFrom; var isTimeElement = ('TIME' === element[0].nodeName.toUpperCase()); var setTitleTime = !element.attr('title'); function getNow() { var now; if (currentFrom) { now = currentFrom; } else if (amTimeAgoConfig.serverTime) { var localNow = new Date().getTime(); var nowMillis = localNow - localDate + amTimeAgoConfig.serverTime; now = moment(nowMillis); } else { now = moment(); } return now; } function cancelTimer() { if (activeTimeout) { $window.clearTimeout(activeTimeout); activeTimeout = null; } } function updateTime(momentInstance) { var timeAgo = getNow().diff(momentInstance, fullDateThresholdUnit); var showFullDate = fullDateThreshold && timeAgo >= fullDateThreshold; if (showFullDate) { element.text(momentInstance.format(fullDateFormat)); } else { element.text(momentInstance.from(getNow(), withoutSuffix)); } if (titleFormat && setTitleTime) { element.attr('title', momentInstance.format(titleFormat)); } if (!showFullDate) { var howOld = Math.abs(getNow().diff(momentInstance, 'minute')); var secondsUntilUpdate = 3600; if (howOld < 1) { secondsUntilUpdate = 1; } else if (howOld < 60) { secondsUntilUpdate = 30; } else if (howOld < 180) { secondsUntilUpdate = 300; } activeTimeout = $window.setTimeout(function () { updateTime(momentInstance); }, secondsUntilUpdate * 1000); } } function updateDateTimeAttr(value) { if (isTimeElement) { element.attr('datetime', value); } } function updateMoment() { cancelTimer(); if (currentValue) { var momentValue = amMoment.preprocessDate(currentValue); updateTime(momentValue); updateDateTimeAttr(momentValue.toISOString()); } } scope.$watch(modelName, function (value) { if (isUndefinedOrNull(value) || (value === '')) { cancelTimer(); if (currentValue) { element.text(''); updateDateTimeAttr(''); currentValue = null; } return; } currentValue = value; updateMoment(); }); if (angular.isDefined(attr.amFrom)) { scope.$watch(attr.amFrom, function (value) { if (isUndefinedOrNull(value) || (value === '')) { currentFrom = null; } else { currentFrom = moment(value); } updateMoment(); }); } if (angular.isDefined(attr.amWithoutSuffix)) { scope.$watch(attr.amWithoutSuffix, function (value) { if (typeof value === 'boolean') { withoutSuffix = value; updateMoment(); } else { withoutSuffix = amTimeAgoConfig.withoutSuffix; } }); } attr.$observe('amFullDateThreshold', function (newValue) { fullDateThreshold = newValue; updateMoment(); }); attr.$observe('amFullDateFormat', function (newValue) { fullDateFormat = newValue; updateMoment(); }); attr.$observe('amFullDateThresholdUnit', function (newValue) { fullDateThresholdUnit = newValue; updateMoment(); }); scope.$on('$destroy', function () { cancelTimer(); }); scope.$on('amMoment:localeChanged', function () { updateMoment(); }); }; }]) /** * @ngdoc service * @name angularMoment.service.amMoment * @module angularMoment */ .service('amMoment', ['moment', '$rootScope', '$log', 'angularMomentConfig', function (moment, $rootScope, $log, angularMomentConfig) { var defaultTimezone = null; /** * @ngdoc function * @name angularMoment.service.amMoment#changeLocale * @methodOf angularMoment.service.amMoment * * @description * Changes the locale for moment.js and updates all the am-time-ago directive instances * with the new locale. Also broadcasts an `amMoment:localeChanged` event on $rootScope. * * @param {string} locale Locale code (e.g. en, es, ru, pt-br, etc.) * @param {object} customization object of locale strings to override */ this.changeLocale = function (locale, customization) { var result = moment.locale(locale, customization); if (angular.isDefined(locale)) { $rootScope.$broadcast('amMoment:localeChanged'); } return result; }; /** * @ngdoc function * @name angularMoment.service.amMoment#changeTimezone * @methodOf angularMoment.service.amMoment * * @description * Changes the default timezone for amCalendar, amDateFormat and amTimeAgo. Also broadcasts an * `amMoment:timezoneChanged` event on $rootScope. * * Note: this method works only if moment-timezone > 0.3.0 is loaded * * @param {string} timezone Timezone name (e.g. UTC) */ this.changeTimezone = function (timezone) { if (moment.tz && moment.tz.setDefault) { moment.tz.setDefault(timezone); $rootScope.$broadcast('amMoment:timezoneChanged'); } else { $log.warn('angular-moment: changeTimezone() works only with moment-timezone.js v0.3.0 or greater.'); } angularMomentConfig.timezone = timezone; defaultTimezone = timezone; }; /** * @ngdoc function * @name angularMoment.service.amMoment#preprocessDate * @methodOf angularMoment.service.amMoment * * @description * Preprocess a given value and convert it into a Moment instance appropriate for use in the * am-time-ago directive and the filters. The behavior of this function can be overriden by * setting `angularMomentConfig.preprocess`. * * @param {*} value The value to be preprocessed * @return {Moment} A `moment` object */ this.preprocessDate = function (value) { // Configure the default timezone if needed if (defaultTimezone !== angularMomentConfig.timezone) { this.changeTimezone(angularMomentConfig.timezone); } if (angularMomentConfig.preprocess) { return angularMomentConfig.preprocess(value); } if (!isNaN(parseFloat(value)) && isFinite(value)) { // Milliseconds since the epoch return moment(parseInt(value, 10)); } // else just returns the value as-is. return moment(value); }; }]) /** * @ngdoc filter * @name angularMoment.filter:amParse * @module angularMoment */ .filter('amParse', ['moment', function (moment) { return function (value, format) { return moment(value, format); }; }]) /** * @ngdoc filter * @name angularMoment.filter:amFromUnix * @module angularMoment */ .filter('amFromUnix', ['moment', function (moment) { return function (value) { return moment.unix(value); }; }]) /** * @ngdoc filter * @name angularMoment.filter:amUtc * @module angularMoment */ .filter('amUtc', ['moment', function (moment) { return function (value) { return moment.utc(value); }; }]) /** * @ngdoc filter * @name angularMoment.filter:amUtcOffset * @module angularMoment * * @description * Adds a UTC offset to the given timezone object. The offset can be a number of minutes, or a string such as * '+0300', '-0300' or 'Z'. */ .filter('amUtcOffset', ['amMoment', function (amMoment) { function amUtcOffset(value, offset) { return amMoment.preprocessDate(value).utcOffset(offset); } return amUtcOffset; }]) /** * @ngdoc filter * @name angularMoment.filter:amLocal * @module angularMoment */ .filter('amLocal', ['moment', function (moment) { return function (value) { return moment.isMoment(value) ? value.local() : null; }; }]) /** * @ngdoc filter * @name angularMoment.filter:amTimezone * @module angularMoment * * @description * Apply a timezone onto a given moment object, e.g. 'America/Phoenix'). * * You need to include moment-timezone.js for timezone support. */ .filter('amTimezone', ['amMoment', 'angularMomentConfig', '$log', function (amMoment, angularMomentConfig, $log) { function amTimezone(value, timezone) { var aMoment = amMoment.preprocessDate(value); if (!timezone) { return aMoment; } if (aMoment.tz) { return aMoment.tz(timezone); } else { $log.warn('angular-moment: named timezone specified but moment.tz() is undefined. Did you forget to include moment-timezone.js ?'); return aMoment; } } return amTimezone; }]) /** * @ngdoc filter * @name angularMoment.filter:amCalendar * @module angularMoment */ .filter('amCalendar', ['moment', 'amMoment', 'angularMomentConfig', function (moment, amMoment, angularMomentConfig) { function amCalendarFilter(value, referenceTime, formats) { if (isUndefinedOrNull(value)) { return ''; } var date = amMoment.preprocessDate(value); return date.isValid() ? date.calendar(referenceTime, formats) : ''; } // Since AngularJS 1.3, filters have to explicitly define being stateful // (this is no longer the default). amCalendarFilter.$stateful = angularMomentConfig.statefulFilters; return amCalendarFilter; }]) /** * @ngdoc filter * @name angularMoment.filter:amDifference * @module angularMoment */ .filter('amDifference', ['moment', 'amMoment', 'angularMomentConfig', function (moment, amMoment, angularMomentConfig) { function amDifferenceFilter(value, otherValue, unit, usePrecision) { if (isUndefinedOrNull(value)) { return ''; } var date = amMoment.preprocessDate(value); var date2 = !isUndefinedOrNull(otherValue) ? amMoment.preprocessDate(otherValue) : moment(); if (!date.isValid() || !date2.isValid()) { return ''; } return date.diff(date2, unit, usePrecision); } amDifferenceFilter.$stateful = angularMomentConfig.statefulFilters; return amDifferenceFilter; }]) /** * @ngdoc filter * @name angularMoment.filter:amDateFormat * @module angularMoment * @function */ .filter('amDateFormat', ['moment', 'amMoment', 'angularMomentConfig', function (moment, amMoment, angularMomentConfig) { function amDateFormatFilter(value, format) { if (isUndefinedOrNull(value)) { return ''; } var date = amMoment.preprocessDate(value); if (!date.isValid()) { return ''; } return date.format(format); } amDateFormatFilter.$stateful = angularMomentConfig.statefulFilters; return amDateFormatFilter; }]) /** * @ngdoc filter * @name angularMoment.filter:amDurationFormat * @module angularMoment * @function */ .filter('amDurationFormat', ['moment', 'angularMomentConfig', function (moment, angularMomentConfig) { function amDurationFormatFilter(value, format, suffix) { if (isUndefinedOrNull(value)) { return ''; } return moment.duration(value, format).humanize(suffix); } amDurationFormatFilter.$stateful = angularMomentConfig.statefulFilters; return amDurationFormatFilter; }]) /** * @ngdoc filter * @name angularMoment.filter:amTimeAgo * @module angularMoment * @function */ .filter('amTimeAgo', ['moment', 'amMoment', 'angularMomentConfig', function (moment, amMoment, angularMomentConfig) { function amTimeAgoFilter(value, suffix, from) { var date, dateFrom; if (isUndefinedOrNull(value)) { return ''; } value = amMoment.preprocessDate(value); date = moment(value); if (!date.isValid()) { return ''; } dateFrom = moment(from); if (!isUndefinedOrNull(from) && dateFrom.isValid()) { return date.from(dateFrom, suffix); } return date.fromNow(suffix); } amTimeAgoFilter.$stateful = angularMomentConfig.statefulFilters; return amTimeAgoFilter; }]) /** * @ngdoc filter * @name angularMoment.filter:amSubtract * @module angularMoment * @function */ .filter('amSubtract', ['moment', 'angularMomentConfig', function (moment, angularMomentConfig) { function amSubtractFilter(value, amount, type) { if (isUndefinedOrNull(value)) { return ''; } return moment(value).subtract(parseInt(amount, 10), type); } amSubtractFilter.$stateful = angularMomentConfig.statefulFilters; return amSubtractFilter; }]) /** * @ngdoc filter * @name angularMoment.filter:amAdd * @module angularMoment * @function */ .filter('amAdd', ['moment', 'angularMomentConfig', function (moment, angularMomentConfig) { function amAddFilter(value, amount, type) { if (isUndefinedOrNull(value)) { return ''; } return moment(value).add(parseInt(amount, 10), type); } amAddFilter.$stateful = angularMomentConfig.statefulFilters; return amAddFilter; }]) /** * @ngdoc filter * @name angularMoment.filter:amStartOf * @module angularMoment * @function */ .filter('amStartOf', ['moment', 'angularMomentConfig', function (moment, angularMomentConfig) { function amStartOfFilter(value, type) { if (isUndefinedOrNull(value)) { return ''; } return moment(value).startOf(type); } amStartOfFilter.$stateful = angularMomentConfig.statefulFilters; return amStartOfFilter; }]) /** * @ngdoc filter * @name angularMoment.filter:amEndOf * @module angularMoment * @function */ .filter('amEndOf', ['moment', 'angularMomentConfig', function (moment, angularMomentConfig) { function amEndOfFilter(value, type) { if (isUndefinedOrNull(value)) { return ''; } return moment(value).endOf(type); } amEndOfFilter.$stateful = angularMomentConfig.statefulFilters; return amEndOfFilter; }]); return 'angularMoment'; } var isElectron = window && window.process && window.process.type; if (typeof define === 'function' && define.amd) { define(['angular', 'moment'], angularMoment); } else if (typeof module !== 'undefined' && module && module.exports && (typeof require === 'function') && !isElectron) { module.exports = angularMoment(require('angular'), require('moment')); } else { angularMoment(angular, (typeof global !== 'undefined' && typeof global.moment !== 'undefined' ? global : window).moment); } })();
React.createElement(Component, babelHelpers.extends({}, x, { y: 2, z: true }));
class Properties { get<T>() {} }
version https://git-lfs.github.com/spec/v1 oid sha256:87a62b163c0cf979432b1fea40389e1e2307cd9a4531e64a403ccb5d8e2259bc size 650
po.drag = function() { var drag = {}, map, container, dragging; function mousedown(e) { if (e.shiftKey) return; dragging = { x: e.clientX, y: e.clientY }; map.focusableParent().focus(); e.preventDefault(); document.body.style.setProperty("cursor", "move", null); } function mousemove(e) { if (!dragging) return; map.panBy({x: e.clientX - dragging.x, y: e.clientY - dragging.y}); dragging.x = e.clientX; dragging.y = e.clientY; } function mouseup(e) { if (!dragging) return; mousemove(e); dragging = null; document.body.style.removeProperty("cursor"); } drag.map = function(x) { if (!arguments.length) return map; if (map) { container.removeEventListener("mousedown", mousedown, false); container = null; } if (map = x) { container = map.container(); container.addEventListener("mousedown", mousedown, false); } return drag; }; window.addEventListener("mousemove", mousemove, false); window.addEventListener("mouseup", mouseup, false); return drag; };
import Model from 'ember-cli-mirage/orm/model'; import {module, test} from 'qunit'; module('mirage:model'); test('it can be instantiated', function(assert) { var model = new Model({}, 'user'); assert.ok(model); }); test('it cannot be instantiated without a schema', function(assert) { assert.throws(function() { new Model(); }, /requires a schema/); }); test('it cannot be instantiated without a type', function(assert) { assert.throws(function() { new Model({}); }, /requires a type/); });
import path from 'path'; import DocBuilder from './DocBuilder.js'; /** * Search index of identifier builder class. */ export default class SearchIndexBuilder extends DocBuilder { /** * execute building output. * @param {function(javascript: string, filePath: string)} callback - is called with output. */ exec(callback) { let searchIndex = []; let docs = this._find({}); for (let doc of docs) { let indexText, url, displayText; if (doc.importPath) { displayText = `<span>${doc.name}</span> <span class="search-result-import-path">${doc.importPath}</span>`; indexText = `${doc.importPath}~${doc.name}`.toLowerCase(); url = this._getURL(doc); } else if (doc.kind === 'testDescribe' || doc.kind === 'testIt') { displayText = doc.testFullDescription; indexText = [...(doc.testTargets || []), ...(doc._custom_test_targets || [])].join(' ').toLowerCase(); let filePath = doc.longname.split('~')[0]; let fileDoc = this._find({kind: 'testFile', longname: filePath})[0]; url = `${this._getURL(fileDoc)}#lineNumber${doc.lineNumber}`; } else { displayText = doc.longname; indexText = displayText.toLowerCase(); url = this._getURL(doc); } let kind = doc.kind; switch (kind) { case 'constructor': kind = 'method'; break; case 'get': case 'set': kind = 'member'; break; case 'testDescribe': case 'testIt': kind = 'test'; break; } searchIndex.push([indexText, url, displayText, kind]); } searchIndex.sort((a, b)=>{ if (a[2] === b[2]) { return 0; } else if (a[2] < b[2]) { return -1; } else { return 1; } }); let javascript = 'window.esdocSearchIndex = ' + JSON.stringify(searchIndex, null, 2); callback(javascript, 'script/search_index.js'); } }
// gl-matrix 1.2.4 - https://github.com/toji/gl-matrix/blob/master/LICENSE.md (function(a){a.glMatrixArrayType=a.MatrixArray=null;a.vec3={};a.mat3={};a.mat4={};a.quat4={};a.setMatrixArrayType=function(a){return glMatrixArrayType=MatrixArray=a};a.determineMatrixArrayType=function(){return setMatrixArrayType("undefined"!==typeof Float32Array?Float32Array:Array)};determineMatrixArrayType()})("undefined"!=typeof exports?global:this);vec3.create=function(a){var b=new MatrixArray(3);a?(b[0]=a[0],b[1]=a[1],b[2]=a[2]):b[0]=b[1]=b[2]=0;return b}; vec3.set=function(a,b){b[0]=a[0];b[1]=a[1];b[2]=a[2];return b};vec3.add=function(a,b,c){if(!c||a===c)return a[0]+=b[0],a[1]+=b[1],a[2]+=b[2],a;c[0]=a[0]+b[0];c[1]=a[1]+b[1];c[2]=a[2]+b[2];return c};vec3.subtract=function(a,b,c){if(!c||a===c)return a[0]-=b[0],a[1]-=b[1],a[2]-=b[2],a;c[0]=a[0]-b[0];c[1]=a[1]-b[1];c[2]=a[2]-b[2];return c};vec3.multiply=function(a,b,c){if(!c||a===c)return a[0]*=b[0],a[1]*=b[1],a[2]*=b[2],a;c[0]=a[0]*b[0];c[1]=a[1]*b[1];c[2]=a[2]*b[2];return c}; vec3.negate=function(a,b){b||(b=a);b[0]=-a[0];b[1]=-a[1];b[2]=-a[2];return b};vec3.scale=function(a,b,c){if(!c||a===c)return a[0]*=b,a[1]*=b,a[2]*=b,a;c[0]=a[0]*b;c[1]=a[1]*b;c[2]=a[2]*b;return c};vec3.normalize=function(a,b){b||(b=a);var c=a[0],d=a[1],e=a[2],g=Math.sqrt(c*c+d*d+e*e);if(g){if(1===g)return b[0]=c,b[1]=d,b[2]=e,b}else return b[0]=0,b[1]=0,b[2]=0,b;g=1/g;b[0]=c*g;b[1]=d*g;b[2]=e*g;return b}; vec3.cross=function(a,b,c){c||(c=a);var d=a[0],e=a[1],a=a[2],g=b[0],f=b[1],b=b[2];c[0]=e*b-a*f;c[1]=a*g-d*b;c[2]=d*f-e*g;return c};vec3.length=function(a){var b=a[0],c=a[1],a=a[2];return Math.sqrt(b*b+c*c+a*a)};vec3.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]};vec3.direction=function(a,b,c){c||(c=a);var d=a[0]-b[0],e=a[1]-b[1],a=a[2]-b[2],b=Math.sqrt(d*d+e*e+a*a);if(!b)return c[0]=0,c[1]=0,c[2]=0,c;b=1/b;c[0]=d*b;c[1]=e*b;c[2]=a*b;return c}; vec3.lerp=function(a,b,c,d){d||(d=a);d[0]=a[0]+c*(b[0]-a[0]);d[1]=a[1]+c*(b[1]-a[1]);d[2]=a[2]+c*(b[2]-a[2]);return d};vec3.dist=function(a,b){var c=b[0]-a[0],d=b[1]-a[1],e=b[2]-a[2];return Math.sqrt(c*c+d*d+e*e)}; vec3.unproject=function(a,b,c,d,e){e||(e=a);var g=mat4.create(),f=new MatrixArray(4);f[0]=2*(a[0]-d[0])/d[2]-1;f[1]=2*(a[1]-d[1])/d[3]-1;f[2]=2*a[2]-1;f[3]=1;mat4.multiply(c,b,g);if(!mat4.inverse(g))return null;mat4.multiplyVec4(g,f);if(0===f[3])return null;e[0]=f[0]/f[3];e[1]=f[1]/f[3];e[2]=f[2]/f[3];return e};vec3.str=function(a){return"["+a[0]+", "+a[1]+", "+a[2]+"]"}; mat3.create=function(a){var b=new MatrixArray(9);a&&(b[0]=a[0],b[1]=a[1],b[2]=a[2],b[3]=a[3],b[4]=a[4],b[5]=a[5],b[6]=a[6],b[7]=a[7],b[8]=a[8]);return b};mat3.set=function(a,b){b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];return b};mat3.identity=function(a){a||(a=mat3.create());a[0]=1;a[1]=0;a[2]=0;a[3]=0;a[4]=1;a[5]=0;a[6]=0;a[7]=0;a[8]=1;return a}; mat3.transpose=function(a,b){if(!b||a===b){var c=a[1],d=a[2],e=a[5];a[1]=a[3];a[2]=a[6];a[3]=c;a[5]=a[7];a[6]=d;a[7]=e;return a}b[0]=a[0];b[1]=a[3];b[2]=a[6];b[3]=a[1];b[4]=a[4];b[5]=a[7];b[6]=a[2];b[7]=a[5];b[8]=a[8];return b};mat3.toMat4=function(a,b){b||(b=mat4.create());b[15]=1;b[14]=0;b[13]=0;b[12]=0;b[11]=0;b[10]=a[8];b[9]=a[7];b[8]=a[6];b[7]=0;b[6]=a[5];b[5]=a[4];b[4]=a[3];b[3]=0;b[2]=a[2];b[1]=a[1];b[0]=a[0];return b}; mat3.str=function(a){return"["+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+", "+a[8]+"]"};mat4.create=function(a){var b=new MatrixArray(16);a&&(b[0]=a[0],b[1]=a[1],b[2]=a[2],b[3]=a[3],b[4]=a[4],b[5]=a[5],b[6]=a[6],b[7]=a[7],b[8]=a[8],b[9]=a[9],b[10]=a[10],b[11]=a[11],b[12]=a[12],b[13]=a[13],b[14]=a[14],b[15]=a[15]);return b}; mat4.set=function(a,b){b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10];b[11]=a[11];b[12]=a[12];b[13]=a[13];b[14]=a[14];b[15]=a[15];return b};mat4.identity=function(a){a||(a=mat4.create());a[0]=1;a[1]=0;a[2]=0;a[3]=0;a[4]=0;a[5]=1;a[6]=0;a[7]=0;a[8]=0;a[9]=0;a[10]=1;a[11]=0;a[12]=0;a[13]=0;a[14]=0;a[15]=1;return a}; mat4.transpose=function(a,b){if(!b||a===b){var c=a[1],d=a[2],e=a[3],g=a[6],f=a[7],h=a[11];a[1]=a[4];a[2]=a[8];a[3]=a[12];a[4]=c;a[6]=a[9];a[7]=a[13];a[8]=d;a[9]=g;a[11]=a[14];a[12]=e;a[13]=f;a[14]=h;return a}b[0]=a[0];b[1]=a[4];b[2]=a[8];b[3]=a[12];b[4]=a[1];b[5]=a[5];b[6]=a[9];b[7]=a[13];b[8]=a[2];b[9]=a[6];b[10]=a[10];b[11]=a[14];b[12]=a[3];b[13]=a[7];b[14]=a[11];b[15]=a[15];return b}; mat4.determinant=function(a){var b=a[0],c=a[1],d=a[2],e=a[3],g=a[4],f=a[5],h=a[6],i=a[7],j=a[8],k=a[9],l=a[10],n=a[11],o=a[12],m=a[13],p=a[14],a=a[15];return o*k*h*e-j*m*h*e-o*f*l*e+g*m*l*e+j*f*p*e-g*k*p*e-o*k*d*i+j*m*d*i+o*c*l*i-b*m*l*i-j*c*p*i+b*k*p*i+o*f*d*n-g*m*d*n-o*c*h*n+b*m*h*n+g*c*p*n-b*f*p*n-j*f*d*a+g*k*d*a+j*c*h*a-b*k*h*a-g*c*l*a+b*f*l*a}; mat4.inverse=function(a,b){b||(b=a);var c=a[0],d=a[1],e=a[2],g=a[3],f=a[4],h=a[5],i=a[6],j=a[7],k=a[8],l=a[9],n=a[10],o=a[11],m=a[12],p=a[13],r=a[14],s=a[15],A=c*h-d*f,B=c*i-e*f,t=c*j-g*f,u=d*i-e*h,v=d*j-g*h,w=e*j-g*i,x=k*p-l*m,y=k*r-n*m,z=k*s-o*m,C=l*r-n*p,D=l*s-o*p,E=n*s-o*r,q=A*E-B*D+t*C+u*z-v*y+w*x;if(!q)return null;q=1/q;b[0]=(h*E-i*D+j*C)*q;b[1]=(-d*E+e*D-g*C)*q;b[2]=(p*w-r*v+s*u)*q;b[3]=(-l*w+n*v-o*u)*q;b[4]=(-f*E+i*z-j*y)*q;b[5]=(c*E-e*z+g*y)*q;b[6]=(-m*w+r*t-s*B)*q;b[7]=(k*w-n*t+o*B)*q;b[8]= (f*D-h*z+j*x)*q;b[9]=(-c*D+d*z-g*x)*q;b[10]=(m*v-p*t+s*A)*q;b[11]=(-k*v+l*t-o*A)*q;b[12]=(-f*C+h*y-i*x)*q;b[13]=(c*C-d*y+e*x)*q;b[14]=(-m*u+p*B-r*A)*q;b[15]=(k*u-l*B+n*A)*q;return b};mat4.toRotationMat=function(a,b){b||(b=mat4.create());b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10];b[11]=a[11];b[12]=0;b[13]=0;b[14]=0;b[15]=1;return b}; mat4.toMat3=function(a,b){b||(b=mat3.create());b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[4];b[4]=a[5];b[5]=a[6];b[6]=a[8];b[7]=a[9];b[8]=a[10];return b};mat4.toInverseMat3=function(a,b){var c=a[0],d=a[1],e=a[2],g=a[4],f=a[5],h=a[6],i=a[8],j=a[9],k=a[10],l=k*f-h*j,n=-k*g+h*i,o=j*g-f*i,m=c*l+d*n+e*o;if(!m)return null;m=1/m;b||(b=mat3.create());b[0]=l*m;b[1]=(-k*d+e*j)*m;b[2]=(h*d-e*f)*m;b[3]=n*m;b[4]=(k*c-e*i)*m;b[5]=(-h*c+e*g)*m;b[6]=o*m;b[7]=(-j*c+d*i)*m;b[8]=(f*c-d*g)*m;return b}; mat4.multiply=function(a,b,c){c||(c=a);var d=a[0],e=a[1],g=a[2],f=a[3],h=a[4],i=a[5],j=a[6],k=a[7],l=a[8],n=a[9],o=a[10],m=a[11],p=a[12],r=a[13],s=a[14],a=a[15],A=b[0],B=b[1],t=b[2],u=b[3],v=b[4],w=b[5],x=b[6],y=b[7],z=b[8],C=b[9],D=b[10],E=b[11],q=b[12],F=b[13],G=b[14],b=b[15];c[0]=A*d+B*h+t*l+u*p;c[1]=A*e+B*i+t*n+u*r;c[2]=A*g+B*j+t*o+u*s;c[3]=A*f+B*k+t*m+u*a;c[4]=v*d+w*h+x*l+y*p;c[5]=v*e+w*i+x*n+y*r;c[6]=v*g+w*j+x*o+y*s;c[7]=v*f+w*k+x*m+y*a;c[8]=z*d+C*h+D*l+E*p;c[9]=z*e+C*i+D*n+E*r;c[10]=z*g+C* j+D*o+E*s;c[11]=z*f+C*k+D*m+E*a;c[12]=q*d+F*h+G*l+b*p;c[13]=q*e+F*i+G*n+b*r;c[14]=q*g+F*j+G*o+b*s;c[15]=q*f+F*k+G*m+b*a;return c};mat4.multiplyVec3=function(a,b,c){c||(c=b);var d=b[0],e=b[1],b=b[2];c[0]=a[0]*d+a[4]*e+a[8]*b+a[12];c[1]=a[1]*d+a[5]*e+a[9]*b+a[13];c[2]=a[2]*d+a[6]*e+a[10]*b+a[14];return c}; mat4.multiplyVec4=function(a,b,c){c||(c=b);var d=b[0],e=b[1],g=b[2],b=b[3];c[0]=a[0]*d+a[4]*e+a[8]*g+a[12]*b;c[1]=a[1]*d+a[5]*e+a[9]*g+a[13]*b;c[2]=a[2]*d+a[6]*e+a[10]*g+a[14]*b;c[3]=a[3]*d+a[7]*e+a[11]*g+a[15]*b;return c}; mat4.translate=function(a,b,c){var d=b[0],e=b[1],b=b[2],g,f,h,i,j,k,l,n,o,m,p,r;if(!c||a===c)return a[12]=a[0]*d+a[4]*e+a[8]*b+a[12],a[13]=a[1]*d+a[5]*e+a[9]*b+a[13],a[14]=a[2]*d+a[6]*e+a[10]*b+a[14],a[15]=a[3]*d+a[7]*e+a[11]*b+a[15],a;g=a[0];f=a[1];h=a[2];i=a[3];j=a[4];k=a[5];l=a[6];n=a[7];o=a[8];m=a[9];p=a[10];r=a[11];c[0]=g;c[1]=f;c[2]=h;c[3]=i;c[4]=j;c[5]=k;c[6]=l;c[7]=n;c[8]=o;c[9]=m;c[10]=p;c[11]=r;c[12]=g*d+j*e+o*b+a[12];c[13]=f*d+k*e+m*b+a[13];c[14]=h*d+l*e+p*b+a[14];c[15]=i*d+n*e+r*b+a[15]; return c};mat4.scale=function(a,b,c){var d=b[0],e=b[1],b=b[2];if(!c||a===c)return a[0]*=d,a[1]*=d,a[2]*=d,a[3]*=d,a[4]*=e,a[5]*=e,a[6]*=e,a[7]*=e,a[8]*=b,a[9]*=b,a[10]*=b,a[11]*=b,a;c[0]=a[0]*d;c[1]=a[1]*d;c[2]=a[2]*d;c[3]=a[3]*d;c[4]=a[4]*e;c[5]=a[5]*e;c[6]=a[6]*e;c[7]=a[7]*e;c[8]=a[8]*b;c[9]=a[9]*b;c[10]=a[10]*b;c[11]=a[11]*b;c[12]=a[12];c[13]=a[13];c[14]=a[14];c[15]=a[15];return c}; mat4.rotate=function(a,b,c,d){var e=c[0],g=c[1],c=c[2],f=Math.sqrt(e*e+g*g+c*c),h,i,j,k,l,n,o,m,p,r,s,A,B,t,u,v,w,x,y,z;if(!f)return null;1!==f&&(f=1/f,e*=f,g*=f,c*=f);h=Math.sin(b);i=Math.cos(b);j=1-i;b=a[0];f=a[1];k=a[2];l=a[3];n=a[4];o=a[5];m=a[6];p=a[7];r=a[8];s=a[9];A=a[10];B=a[11];t=e*e*j+i;u=g*e*j+c*h;v=c*e*j-g*h;w=e*g*j-c*h;x=g*g*j+i;y=c*g*j+e*h;z=e*c*j+g*h;e=g*c*j-e*h;g=c*c*j+i;d?a!==d&&(d[12]=a[12],d[13]=a[13],d[14]=a[14],d[15]=a[15]):d=a;d[0]=b*t+n*u+r*v;d[1]=f*t+o*u+s*v;d[2]=k*t+m*u+A* v;d[3]=l*t+p*u+B*v;d[4]=b*w+n*x+r*y;d[5]=f*w+o*x+s*y;d[6]=k*w+m*x+A*y;d[7]=l*w+p*x+B*y;d[8]=b*z+n*e+r*g;d[9]=f*z+o*e+s*g;d[10]=k*z+m*e+A*g;d[11]=l*z+p*e+B*g;return d};mat4.rotateX=function(a,b,c){var d=Math.sin(b),b=Math.cos(b),e=a[4],g=a[5],f=a[6],h=a[7],i=a[8],j=a[9],k=a[10],l=a[11];c?a!==c&&(c[0]=a[0],c[1]=a[1],c[2]=a[2],c[3]=a[3],c[12]=a[12],c[13]=a[13],c[14]=a[14],c[15]=a[15]):c=a;c[4]=e*b+i*d;c[5]=g*b+j*d;c[6]=f*b+k*d;c[7]=h*b+l*d;c[8]=e*-d+i*b;c[9]=g*-d+j*b;c[10]=f*-d+k*b;c[11]=h*-d+l*b;return c}; mat4.rotateY=function(a,b,c){var d=Math.sin(b),b=Math.cos(b),e=a[0],g=a[1],f=a[2],h=a[3],i=a[8],j=a[9],k=a[10],l=a[11];c?a!==c&&(c[4]=a[4],c[5]=a[5],c[6]=a[6],c[7]=a[7],c[12]=a[12],c[13]=a[13],c[14]=a[14],c[15]=a[15]):c=a;c[0]=e*b+i*-d;c[1]=g*b+j*-d;c[2]=f*b+k*-d;c[3]=h*b+l*-d;c[8]=e*d+i*b;c[9]=g*d+j*b;c[10]=f*d+k*b;c[11]=h*d+l*b;return c}; mat4.rotateZ=function(a,b,c){var d=Math.sin(b),b=Math.cos(b),e=a[0],g=a[1],f=a[2],h=a[3],i=a[4],j=a[5],k=a[6],l=a[7];c?a!==c&&(c[8]=a[8],c[9]=a[9],c[10]=a[10],c[11]=a[11],c[12]=a[12],c[13]=a[13],c[14]=a[14],c[15]=a[15]):c=a;c[0]=e*b+i*d;c[1]=g*b+j*d;c[2]=f*b+k*d;c[3]=h*b+l*d;c[4]=e*-d+i*b;c[5]=g*-d+j*b;c[6]=f*-d+k*b;c[7]=h*-d+l*b;return c}; mat4.frustum=function(a,b,c,d,e,g,f){f||(f=mat4.create());var h=b-a,i=d-c,j=g-e;f[0]=2*e/h;f[1]=0;f[2]=0;f[3]=0;f[4]=0;f[5]=2*e/i;f[6]=0;f[7]=0;f[8]=(b+a)/h;f[9]=(d+c)/i;f[10]=-(g+e)/j;f[11]=-1;f[12]=0;f[13]=0;f[14]=-(2*g*e)/j;f[15]=0;return f};mat4.perspective=function(a,b,c,d,e){a=c*Math.tan(a*Math.PI/360);b*=a;return mat4.frustum(-b,b,-a,a,c,d,e)}; mat4.ortho=function(a,b,c,d,e,g,f){f||(f=mat4.create());var h=b-a,i=d-c,j=g-e;f[0]=2/h;f[1]=0;f[2]=0;f[3]=0;f[4]=0;f[5]=2/i;f[6]=0;f[7]=0;f[8]=0;f[9]=0;f[10]=-2/j;f[11]=0;f[12]=-(a+b)/h;f[13]=-(d+c)/i;f[14]=-(g+e)/j;f[15]=1;return f}; mat4.lookAt=function(a,b,c,d){d||(d=mat4.create());var e,g,f,h,i,j,k,l,n=a[0],o=a[1],a=a[2];f=c[0];h=c[1];g=c[2];k=b[0];c=b[1];e=b[2];if(n===k&&o===c&&a===e)return mat4.identity(d);b=n-k;c=o-c;k=a-e;l=1/Math.sqrt(b*b+c*c+k*k);b*=l;c*=l;k*=l;e=h*k-g*c;g=g*b-f*k;f=f*c-h*b;(l=Math.sqrt(e*e+g*g+f*f))?(l=1/l,e*=l,g*=l,f*=l):f=g=e=0;h=c*f-k*g;i=k*e-b*f;j=b*g-c*e;(l=Math.sqrt(h*h+i*i+j*j))?(l=1/l,h*=l,i*=l,j*=l):j=i=h=0;d[0]=e;d[1]=h;d[2]=b;d[3]=0;d[4]=g;d[5]=i;d[6]=c;d[7]=0;d[8]=f;d[9]=j;d[10]=k;d[11]= 0;d[12]=-(e*n+g*o+f*a);d[13]=-(h*n+i*o+j*a);d[14]=-(b*n+c*o+k*a);d[15]=1;return d};mat4.fromRotationTranslation=function(a,b,c){c||(c=mat4.create());var d=a[0],e=a[1],g=a[2],f=a[3],h=d+d,i=e+e,j=g+g,a=d*h,k=d*i,d=d*j,l=e*i,e=e*j,g=g*j,h=f*h,i=f*i,f=f*j;c[0]=1-(l+g);c[1]=k+f;c[2]=d-i;c[3]=0;c[4]=k-f;c[5]=1-(a+g);c[6]=e+h;c[7]=0;c[8]=d+i;c[9]=e-h;c[10]=1-(a+l);c[11]=0;c[12]=b[0];c[13]=b[1];c[14]=b[2];c[15]=1;return c}; mat4.str=function(a){return"["+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+", "+a[8]+", "+a[9]+", "+a[10]+", "+a[11]+", "+a[12]+", "+a[13]+", "+a[14]+", "+a[15]+"]"};quat4.create=function(a){var b=new MatrixArray(4);a&&(b[0]=a[0],b[1]=a[1],b[2]=a[2],b[3]=a[3]);return b};quat4.set=function(a,b){b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];return b}; quat4.calculateW=function(a,b){var c=a[0],d=a[1],e=a[2];if(!b||a===b)return a[3]=-Math.sqrt(Math.abs(1-c*c-d*d-e*e)),a;b[0]=c;b[1]=d;b[2]=e;b[3]=-Math.sqrt(Math.abs(1-c*c-d*d-e*e));return b};quat4.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]};quat4.inverse=function(a,b){var c=a[0],d=a[1],e=a[2],g=a[3],c=(c=c*c+d*d+e*e+g*g)?1/c:0;if(!b||a===b)return a[0]*=-c,a[1]*=-c,a[2]*=-c,a[3]*=c,a;b[0]=-a[0]*c;b[1]=-a[1]*c;b[2]=-a[2]*c;b[3]=a[3]*c;return b}; quat4.conjugate=function(a,b){if(!b||a===b)return a[0]*=-1,a[1]*=-1,a[2]*=-1,a;b[0]=-a[0];b[1]=-a[1];b[2]=-a[2];b[3]=a[3];return b};quat4.length=function(a){var b=a[0],c=a[1],d=a[2],a=a[3];return Math.sqrt(b*b+c*c+d*d+a*a)};quat4.normalize=function(a,b){b||(b=a);var c=a[0],d=a[1],e=a[2],g=a[3],f=Math.sqrt(c*c+d*d+e*e+g*g);if(0===f)return b[0]=0,b[1]=0,b[2]=0,b[3]=0,b;f=1/f;b[0]=c*f;b[1]=d*f;b[2]=e*f;b[3]=g*f;return b}; quat4.multiply=function(a,b,c){c||(c=a);var d=a[0],e=a[1],g=a[2],a=a[3],f=b[0],h=b[1],i=b[2],b=b[3];c[0]=d*b+a*f+e*i-g*h;c[1]=e*b+a*h+g*f-d*i;c[2]=g*b+a*i+d*h-e*f;c[3]=a*b-d*f-e*h-g*i;return c};quat4.multiplyVec3=function(a,b,c){c||(c=b);var d=b[0],e=b[1],g=b[2],b=a[0],f=a[1],h=a[2],a=a[3],i=a*d+f*g-h*e,j=a*e+h*d-b*g,k=a*g+b*e-f*d,d=-b*d-f*e-h*g;c[0]=i*a+d*-b+j*-h-k*-f;c[1]=j*a+d*-f+k*-b-i*-h;c[2]=k*a+d*-h+i*-f-j*-b;return c}; quat4.toMat3=function(a,b){b||(b=mat3.create());var c=a[0],d=a[1],e=a[2],g=a[3],f=c+c,h=d+d,i=e+e,j=c*f,k=c*h,c=c*i,l=d*h,d=d*i,e=e*i,f=g*f,h=g*h,g=g*i;b[0]=1-(l+e);b[1]=k+g;b[2]=c-h;b[3]=k-g;b[4]=1-(j+e);b[5]=d+f;b[6]=c+h;b[7]=d-f;b[8]=1-(j+l);return b}; quat4.toMat4=function(a,b){b||(b=mat4.create());var c=a[0],d=a[1],e=a[2],g=a[3],f=c+c,h=d+d,i=e+e,j=c*f,k=c*h,c=c*i,l=d*h,d=d*i,e=e*i,f=g*f,h=g*h,g=g*i;b[0]=1-(l+e);b[1]=k+g;b[2]=c-h;b[3]=0;b[4]=k-g;b[5]=1-(j+e);b[6]=d+f;b[7]=0;b[8]=c+h;b[9]=d-f;b[10]=1-(j+l);b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return b}; quat4.slerp=function(a,b,c,d){d||(d=a);var e=a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],g,f;if(1<=Math.abs(e))return d!==a&&(d[0]=a[0],d[1]=a[1],d[2]=a[2],d[3]=a[3]),d;g=Math.acos(e);f=Math.sqrt(1-e*e);if(0.001>Math.abs(f))return d[0]=0.5*a[0]+0.5*b[0],d[1]=0.5*a[1]+0.5*b[1],d[2]=0.5*a[2]+0.5*b[2],d[3]=0.5*a[3]+0.5*b[3],d;e=Math.sin((1-c)*g)/f;c=Math.sin(c*g)/f;d[0]=a[0]*e+b[0]*c;d[1]=a[1]*e+b[1]*c;d[2]=a[2]*e+b[2]*c;d[3]=a[3]*e+b[3]*c;return d}; quat4.str=function(a){return"["+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+"]"};
version https://git-lfs.github.com/spec/v1 oid sha256:af70d1465cbe870a7f22f60bc612a1e91fa6c85ae675cca03cb8f93b2e0f2414 size 2295
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.cellx = factory()); }(this, (function () { 'use strict'; var ErrorLogger = { _handler: null, /** * @typesign (handler: (...msg)); */ setHandler: function setHandler(handler) { this._handler = handler; }, /** * @typesign (...msg); */ log: function log() { this._handler.apply(this, arguments); } }; var uidCounter = 0; /** * @typesign () -> string; */ function nextUID() { return String(++uidCounter); } var Symbol = Function('return this;')().Symbol; if (!Symbol) { Symbol = function Symbol(key) { return '__' + key + '_' + Math.floor(Math.random() * 1e9) + '_' + nextUID() + '__'; }; Symbol.iterator = Symbol('Symbol.iterator'); } var Symbol$1 = Symbol; var UID = Symbol$1('cellx.uid'); var CELLS = Symbol$1('cellx.cells'); var global$1 = Function('return this;')(); var hasOwn$1 = Object.prototype.hasOwnProperty; var Map = global$1.Map; if (!Map || Map.toString().indexOf('[native code]') == -1 || !new Map([[1, 1]]).size) { var entryStub = { value: undefined }; Map = function Map(entries) { this._entries = Object.create(null); this._objectStamps = {}; this._first = null; this._last = null; this.size = 0; if (entries) { for (var i = 0, l = entries.length; i < l; i++) { this.set(entries[i][0], entries[i][1]); } } }; Map.prototype = { constructor: Map, has: function has(key) { return !!this._entries[this._getValueStamp(key)]; }, get: function get(key) { return (this._entries[this._getValueStamp(key)] || entryStub).value; }, set: function set(key, value) { var entries = this._entries; var keyStamp = this._getValueStamp(key); if (entries[keyStamp]) { entries[keyStamp].value = value; } else { var entry = entries[keyStamp] = { key: key, keyStamp: keyStamp, value: value, prev: this._last, next: null }; if (this.size++) { this._last.next = entry; } else { this._first = entry; } this._last = entry; } return this; }, delete: function delete_(key) { var keyStamp = this._getValueStamp(key); var entry = this._entries[keyStamp]; if (!entry) { return false; } if (--this.size) { var prev = entry.prev; var next = entry.next; if (prev) { prev.next = next; } else { this._first = next; } if (next) { next.prev = prev; } else { this._last = prev; } } else { this._first = null; this._last = null; } delete this._entries[keyStamp]; delete this._objectStamps[keyStamp]; return true; }, clear: function clear() { var entries = this._entries; for (var stamp in entries) { delete entries[stamp]; } this._objectStamps = {}; this._first = null; this._last = null; this.size = 0; }, _getValueStamp: function _getValueStamp(value) { switch (typeof value) { case 'undefined': { return 'undefined'; } case 'object': { if (value === null) { return 'null'; } break; } case 'boolean': { return '?' + value; } case 'number': { return '+' + value; } case 'string': { return ',' + value; } } return this._getObjectStamp(value); }, _getObjectStamp: function _getObjectStamp(obj) { if (!hasOwn$1.call(obj, UID)) { if (!Object.isExtensible(obj)) { var stamps = this._objectStamps; var stamp; for (stamp in stamps) { if (hasOwn$1.call(stamps, stamp) && stamps[stamp] == obj) { return stamp; } } stamp = nextUID(); stamps[stamp] = obj; return stamp; } Object.defineProperty(obj, UID, { value: nextUID() }); } return obj[UID]; }, forEach: function forEach(callback, context) { var entry = this._first; while (entry) { callback.call(context, entry.value, entry.key, this); do { entry = entry.next; } while (entry && !this._entries[entry.keyStamp]); } }, toString: function toString() { return '[object Map]'; } }; [['keys', function keys(entry) { return entry.key; }], ['values', function values(entry) { return entry.value; }], ['entries', function entries(entry) { return [entry.key, entry.value]; }]].forEach((function (settings) { var getStepValue = settings[1]; Map.prototype[settings[0]] = function () { var entries = this._entries; var entry; var done = false; var map = this; return { next: function () { if (!done) { if (entry) { do { entry = entry.next; } while (entry && !entries[entry.keyStamp]); } else { entry = map._first; } if (entry) { return { value: getStepValue(entry), done: false }; } done = true; } return { value: undefined, done: true }; } }; }; })); } if (!Map.prototype[Symbol$1.iterator]) { Map.prototype[Symbol$1.iterator] = Map.prototype.entries; } var Map$1 = Map; var IS_EVENT = {}; /** * @typedef {{ * listener: (evt: cellx~Event) -> ?boolean, * context * }} cellx~EmitterEvent */ /** * @typedef {{ * target?: Object, * type: string, * bubbles?: boolean, * isPropagationStopped?: boolean * }} cellx~Event */ /** * @class cellx.EventEmitter * @extends {Object} * @typesign new EventEmitter() -> cellx.EventEmitter; */ function EventEmitter() { /** * @type {{ [type: string]: cellx~EmitterEvent | Array<cellx~EmitterEvent> }} */ this._events = new Map$1(); } EventEmitter.currentlySubscribing = false; EventEmitter.prototype = { constructor: EventEmitter, /** * @typesign () -> { [type: string]: Array<cellx~EmitterEvent> }; * @typesign (type: string) -> Array<cellx~EmitterEvent>; */ getEvents: function getEvents(type) { var events; if (type) { events = this._events.get(type); if (!events) { return []; } return events._isEvent === IS_EVENT ? [events] : events; } events = Object.create(null); this._events.forEach((function (typeEvents, type) { events[type] = typeEvents._isEvent === IS_EVENT ? [typeEvents] : typeEvents; })); return events; }, /** * @typesign ( * type: string, * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.EventEmitter; * * @typesign ( * listeners: { [type: string]: (evt: cellx~Event) -> ?boolean }, * context? * ) -> cellx.EventEmitter; */ on: function on(type, listener, context) { if (typeof type == 'object') { context = listener !== undefined ? listener : this; var listeners = type; for (type in listeners) { this._on(type, listeners[type], context); } } else { this._on(type, listener, context !== undefined ? context : this); } return this; }, /** * @typesign ( * type: string, * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.EventEmitter; * * @typesign ( * listeners: { [type: string]: (evt: cellx~Event) -> ?boolean }, * context? * ) -> cellx.EventEmitter; * * @typesign () -> cellx.EventEmitter; */ off: function off(type, listener, context) { if (type) { if (typeof type == 'object') { context = listener !== undefined ? listener : this; var listeners = type; for (type in listeners) { this._off(type, listeners[type], context); } } else { this._off(type, listener, context !== undefined ? context : this); } } else { this._events.clear(); } return this; }, /** * @typesign ( * type: string, * listener: (evt: cellx~Event) -> ?boolean, * context * ); */ _on: function _on(type, listener, context) { var index = type.indexOf(':'); if (index != -1) { var propName = type.slice(index + 1); EventEmitter.currentlySubscribing = true; (this[propName + 'Cell'] || (this[propName], this[propName + 'Cell'])).on(type.slice(0, index), listener, context); EventEmitter.currentlySubscribing = false; } else { var events = this._events.get(type); var evt = { _isEvent: IS_EVENT, listener: listener, context: context }; if (!events) { this._events.set(type, evt); } else if (events._isEvent === IS_EVENT) { this._events.set(type, [events, evt]); } else { events.push(evt); } } }, /** * @typesign ( * type: string, * listener: (evt: cellx~Event) -> ?boolean, * context * ); */ _off: function _off(type, listener, context) { var index = type.indexOf(':'); if (index != -1) { var propName = type.slice(index + 1); (this[propName + 'Cell'] || (this[propName], this[propName + 'Cell'])).off(type.slice(0, index), listener, context); } else { var events = this._events.get(type); if (!events) { return; } var isEvent = events._isEvent === IS_EVENT; var evt; if (isEvent || events.length == 1) { evt = isEvent ? events : events[0]; if (evt.listener == listener && evt.context === context) { this._events.delete(type); } } else { for (var i = events.length; i;) { evt = events[--i]; if (evt.listener == listener && evt.context === context) { events.splice(i, 1); break; } } } } }, /** * @typesign ( * type: string, * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> (evt: cellx~Event) -> ?boolean; */ once: function once(type, listener, context) { if (context === undefined) { context = this; } function wrapper(evt) { this._off(type, wrapper, context); return listener.call(this, evt); } this._on(type, wrapper, context); return wrapper; }, /** * @typesign (evt: cellx~Event) -> cellx~Event; * @typesign (type: string) -> cellx~Event; */ emit: function emit(evt) { if (typeof evt == 'string') { evt = { target: this, type: evt }; } else if (!evt.target) { evt.target = this; } else if (evt.target != this) { throw new TypeError('Event cannot be emitted on this object'); } this._handleEvent(evt); return evt; }, /** * @typesign (evt: cellx~Event); * * For override: * @example * function View(el) { * this.element = el; * el._view = this; * } * * View.prototype = { * __proto__: EventEmitter.prototype, * constructor: View, * * getParent: function() { * var node = this.element; * * while (node = node.parentNode) { * if (node._view) { * return node._view; * } * } * * return null; * }, * * _handleEvent: function(evt) { * EventEmitter.prototype._handleEvent.call(this, evt); * * if (evt.bubbles !== false && !evt.isPropagationStopped) { * var parent = this.getParent(); * * if (parent) { * parent._handleEvent(evt); * } * } * } * }; */ _handleEvent: function _handleEvent(evt) { var events = this._events.get(evt.type); if (!events) { return; } if (events._isEvent === IS_EVENT) { if (this._tryEventListener(events, evt) === false) { evt.isPropagationStopped = true; } } else { var eventCount = events.length; if (eventCount == 1) { if (this._tryEventListener(events[0], evt) === false) { evt.isPropagationStopped = true; } } else { events = events.slice(); for (var i = 0; i < eventCount; i++) { if (this._tryEventListener(events[i], evt) === false) { evt.isPropagationStopped = true; } } } } }, /** * @typesign (emEvt: cellx~EmitterEvent, evt: cellx~Event); */ _tryEventListener: function _tryEventListener(emEvt, evt) { try { return emEvt.listener.call(emEvt.context, evt); } catch (err) { this._logError(err); } }, /** * @typesign (...msg); */ _logError: function _logError() { ErrorLogger.log.apply(ErrorLogger, arguments); } }; /** * @typesign (a, b) -> boolean; */ var is = Object.is || function is(a, b) { if (a === 0 && b === 0) { return 1 / a == 1 / b; } return a === b || a != a && b != b; }; /** * @typesign (target: Object, ...sources: Array<Object>) -> Object; */ function mixin(target, source) { var names = Object.getOwnPropertyNames(source); for (var i = 0, l = names.length; i < l; i++) { var name = names[i]; Object.defineProperty(target, name, Object.getOwnPropertyDescriptor(source, name)); } if (arguments.length > 2) { var i = 2; do { mixin(target, arguments[i]); } while (++i < arguments.length); } return target; } /** * @typesign (callback: ()); */ var nextTick; /* istanbul ignore next */ if (global$1.process && process.toString() == '[object process]' && process.nextTick) { nextTick = process.nextTick; } else if (global$1.setImmediate) { nextTick = function nextTick(callback) { setImmediate(callback); }; } else if (global$1.Promise && Promise.toString().indexOf('[native code]') != -1) { var prm = Promise.resolve(); nextTick = function nextTick(callback) { prm.then((function () { callback(); })); }; } else { var queue; global$1.addEventListener('message', (function () { if (queue) { var track = queue; queue = null; for (var i = 0, l = track.length; i < l; i++) { try { track[i](); } catch (err) { ErrorLogger.log(err); } } } })); nextTick = function nextTick(callback) { if (queue) { queue.push(callback); } else { queue = [callback]; postMessage('__tic__', '*'); } }; } var nextTick$1 = nextTick; function noop() {} var slice$1 = Array.prototype.slice; var EventEmitterProto = EventEmitter.prototype; var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 0x1fffffffffffff; var KEY_WRAPPERS = Symbol$1('wrappers'); var errorIndexCounter = 0; var pushingIndexCounter = 0; var releasePlan = new Map$1(); var releasePlanIndex = MAX_SAFE_INTEGER; var releasePlanToIndex = -1; var releasePlanned = false; var currentlyRelease = false; var currentCell = null; var error = { original: null }; var releaseVersion = 1; var transactionLevel = 0; var transactionFailure = false; var pendingReactions = []; var afterReleaseCallbacks; var STATE_INITED = 128; var STATE_CURRENTLY_PULLING = 64; var STATE_ACTIVE = 32; var STATE_HAS_FOLLOWERS = 16; var STATE_PENDING = 8; var STATE_FULFILLED = 4; var STATE_REJECTED = 2; var STATE_CAN_CANCEL_CHANGE = 1; function release() { if (!releasePlanned) { return; } releasePlanned = false; currentlyRelease = true; var queue = releasePlan.get(releasePlanIndex); for (;;) { var cell = queue && queue.shift(); if (!cell) { if (releasePlanIndex == releasePlanToIndex) { break; } queue = releasePlan.get(++releasePlanIndex); continue; } var level = cell._level; var changeEvent = cell._changeEvent; if (!changeEvent) { if (level > releasePlanIndex || cell._levelInRelease == -1) { if (!queue.length) { if (releasePlanIndex == releasePlanToIndex) { break; } queue = releasePlan.get(++releasePlanIndex); } continue; } cell.pull(); level = cell._level; if (level > releasePlanIndex) { if (!queue.length) { queue = releasePlan.get(++releasePlanIndex); } continue; } changeEvent = cell._changeEvent; } cell._levelInRelease = -1; if (changeEvent) { var oldReleasePlanIndex = releasePlanIndex; cell._fixedValue = cell._value; cell._changeEvent = null; cell._handleEvent(changeEvent); var pushingIndex = cell._pushingIndex; var slaves = cell._slaves; for (var i = 0, l = slaves.length; i < l; i++) { var slave = slaves[i]; if (slave._level <= level) { slave._level = level + 1; } if (pushingIndex >= slave._pushingIndex) { slave._pushingIndex = pushingIndex; slave._changeEvent = null; slave._addToRelease(); } } if (releasePlanIndex != oldReleasePlanIndex) { queue = releasePlan.get(releasePlanIndex); continue; } } if (!queue.length) { if (releasePlanIndex == releasePlanToIndex) { break; } queue = releasePlan.get(++releasePlanIndex); } } releasePlanIndex = MAX_SAFE_INTEGER; releasePlanToIndex = -1; currentlyRelease = false; releaseVersion++; if (afterReleaseCallbacks) { var callbacks = afterReleaseCallbacks; afterReleaseCallbacks = null; for (var j = 0, m = callbacks.length; j < m; j++) { callbacks[j](); } } } /** * @typesign (cell: Cell, value); */ function defaultPut(cell, value) { cell.push(value); } var config = { asynchronous: true }; /** * @class cellx.Cell * @extends {cellx.EventEmitter} * * @example * var a = new Cell(1); * var b = new Cell(2); * var c = new Cell(function() { * return a.get() + b.get(); * }); * * c.on('change', function() { * console.log('c = ' + c.get()); * }); * * console.log(c.get()); * // => 3 * * a.set(5); * b.set(10); * // => 'c = 15' * * @typesign new Cell(value?, opts?: { * debugKey?: string, * owner?: Object, * get?: (value) -> *, * validate?: (value, oldValue), * merge: (value, oldValue) -> *, * put?: (cell: Cell, value, oldValue), * reap?: (), * onChange?: (evt: cellx~Event) -> ?boolean, * onError?: (evt: cellx~Event) -> ?boolean * }) -> cellx.Cell; * * @typesign new Cell(pull: (cell: Cell, next) -> *, opts?: { * debugKey?: string, * owner?: Object, * get?: (value) -> *, * validate?: (value, oldValue), * merge: (value, oldValue) -> *, * put?: (cell: Cell, value, oldValue), * reap?: (), * onChange?: (evt: cellx~Event) -> ?boolean, * onError?: (evt: cellx~Event) -> ?boolean * }) -> cellx.Cell; */ function Cell(value, opts) { EventEmitter.call(this); this.debugKey = opts && opts.debugKey; this.owner = opts && opts.owner || this; this._pull = typeof value == 'function' ? value : null; this._get = opts && opts.get || null; this._validate = opts && opts.validate || null; this._merge = opts && opts.merge || null; this._put = opts && opts.put || defaultPut; this._onFulfilled = this._onRejected = null; this._reap = opts && opts.reap || null; if (this._pull) { this._fixedValue = this._value = undefined; } else { if (this._validate) { this._validate(value, undefined); } if (this._merge) { value = this._merge(value, undefined); } this._fixedValue = this._value = value; if (value instanceof EventEmitter) { value.on('change', this._onValueChange, this); } } this._error = null; this._selfErrorCell = null; this._errorCell = null; this._errorIndex = 0; this._pushingIndex = 0; this._version = 0; /** * Ведущие ячейки. * @type {?Array<cellx.Cell>} */ this._masters = undefined; /** * Ведомые ячейки. * @type {Array<cellx.Cell>} */ this._slaves = []; this._level = 0; this._levelInRelease = -1; this._selfPendingStatusCell = null; this._pendingStatusCell = null; this._status = null; this._changeEvent = null; this._lastErrorEvent = null; this._state = STATE_CAN_CANCEL_CHANGE; if (opts) { if (opts.onChange) { this.on('change', opts.onChange); } if (opts.onError) { this.on('error', opts.onError); } } } mixin(Cell, { /** * @typesign (cnfg: { asynchronous?: boolean }); */ configure: function configure(cnfg) { if (cnfg.asynchronous !== undefined) { if (releasePlanned) { release(); } config.asynchronous = cnfg.asynchronous; } }, /** * @type {boolean} */ get currentlyPulling() { return !!currentCell; }, /** * @typesign (callback: (), context?) -> (); */ autorun: function autorun(callback, context) { var disposer; new Cell(function () { var cell = this; if (!disposer) { disposer = function disposer() { cell.dispose(); }; } if (transactionLevel) { var index = pendingReactions.indexOf(this); if (index != -1) { pendingReactions.splice(index, 1); } pendingReactions.push(this); } else { callback.call(context, disposer); } }, { onChange: noop }); return disposer; }, /** * @typesign (); */ forceRelease: function forceRelease() { if (releasePlanned) { release(); } }, /** * @typesign (callback: ()); */ transaction: function transaction(callback) { if (!transactionLevel++ && releasePlanned) { release(); } try { callback(); } catch (err) { ErrorLogger.log(err); transactionFailure = true; } if (transactionFailure) { for (var iterator = releasePlan.values(), step; !(step = iterator.next()).done;) { var queue = step.value; for (var i = queue.length; i;) { var cell = queue[--i]; cell._value = cell._fixedValue; cell._levelInRelease = -1; cell._changeEvent = null; } } releasePlan.clear(); releasePlanIndex = MAX_SAFE_INTEGER; releasePlanToIndex = -1; releasePlanned = false; pendingReactions.length = 0; } if (! --transactionLevel && !transactionFailure) { for (var i = 0, l = pendingReactions.length; i < l; i++) { var reaction = pendingReactions[i]; if (reaction instanceof Cell) { reaction.pull(); } else { EventEmitterProto._handleEvent.call(reaction[1], reaction[0]); } } transactionFailure = false; pendingReactions.length = 0; if (releasePlanned) { release(); } } }, /** * @typesign (callback: ()); */ afterRelease: function afterRelease(callback) { (afterReleaseCallbacks || (afterReleaseCallbacks = [])).push(callback); } }); Cell.prototype = { __proto__: EventEmitter.prototype, constructor: Cell, _handleEvent: function _handleEvent(evt) { if (transactionLevel) { pendingReactions.push([evt, this]); } else { EventEmitterProto._handleEvent.call(this, evt); } }, /** * @override */ on: function on(type, listener, context) { if (releasePlanned) { release(); } this._activate(); if (typeof type == 'object') { EventEmitterProto.on.call(this, type, listener !== undefined ? listener : this.owner); } else { EventEmitterProto.on.call(this, type, listener, context !== undefined ? context : this.owner); } this._state |= STATE_HAS_FOLLOWERS; return this; }, /** * @override */ off: function off(type, listener, context) { if (releasePlanned) { release(); } if (type) { if (typeof type == 'object') { EventEmitterProto.off.call(this, type, listener !== undefined ? listener : this.owner); } else { EventEmitterProto.off.call(this, type, listener, context !== undefined ? context : this.owner); } } else { EventEmitterProto.off.call(this); } if (!this._slaves.length && !this._events.has('change') && !this._events.has('error') && this._state & STATE_HAS_FOLLOWERS) { this._state ^= STATE_HAS_FOLLOWERS; this._deactivate(); if (this._reap) { this._reap.call(this.owner); } } return this; }, /** * @typesign ( * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ addChangeListener: function addChangeListener(listener, context) { return this.on('change', listener, context !== undefined ? context : this.owner); }, /** * @typesign ( * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ removeChangeListener: function removeChangeListener(listener, context) { return this.off('change', listener, context !== undefined ? context : this.owner); }, /** * @typesign ( * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ addErrorListener: function addErrorListener(listener, context) { return this.on('error', listener, context !== undefined ? context : this.owner); }, /** * @typesign ( * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ removeErrorListener: function removeErrorListener(listener, context) { return this.off('error', listener, context !== undefined ? context : this.owner); }, /** * @typesign ( * listener: (err: ?Error, evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ subscribe: function subscribe(listener, context) { var wrappers = listener[KEY_WRAPPERS]; if (wrappers && wrappers.has(listener)) { return this; } function wrapper(evt) { return listener.call(this, evt.error || null, evt); } (wrappers || (listener[KEY_WRAPPERS] = new Map$1())).set(this, wrapper); if (context === undefined) { context = this.owner; } return this.on('change', wrapper, context).on('error', wrapper, context); }, /** * @typesign ( * listener: (err: ?Error, evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ unsubscribe: function unsubscribe(listener, context) { var wrappers = listener[KEY_WRAPPERS]; var wrapper = wrappers && wrappers.get(this); if (!wrapper) { return this; } wrappers.delete(this); if (context === undefined) { context = this.owner; } return this.off('change', wrapper, context).off('error', wrapper, context); }, /** * @typesign (slave: cellx.Cell); */ _registerSlave: function _registerSlave(slave) { this._activate(); this._slaves.push(slave); this._state |= STATE_HAS_FOLLOWERS; }, /** * @typesign (slave: cellx.Cell); */ _unregisterSlave: function _unregisterSlave(slave) { this._slaves.splice(this._slaves.indexOf(slave), 1); if (!this._slaves.length && !this._events.has('change') && !this._events.has('error')) { this._state ^= STATE_HAS_FOLLOWERS; this._deactivate(); if (this._reap) { this._reap.call(this.owner); } } }, /** * @typesign (); */ _activate: function _activate() { if (!this._pull || this._state & STATE_ACTIVE || this._masters === null) { return; } var masters = this._masters; if (this._version < releaseVersion) { var value = this._tryPull(); if (masters || this._masters || !(this._state & STATE_INITED)) { if (value === error) { this._fail(error.original, false); } else { this._push(value, false, false); } } masters = this._masters; } if (masters) { var i = masters.length; do { masters[--i]._registerSlave(this); } while (i); this._state |= STATE_ACTIVE; } }, /** * @typesign (); */ _deactivate: function _deactivate() { if (!(this._state & STATE_ACTIVE)) { return; } var masters = this._masters; var i = masters.length; do { masters[--i]._unregisterSlave(this); } while (i); if (this._levelInRelease != -1 && !this._changeEvent) { this._levelInRelease = -1; } this._state ^= STATE_ACTIVE; }, /** * @typesign (); */ _addToRelease: function _addToRelease() { var level = this._level; if (level <= this._levelInRelease) { return; } var queue; (releasePlan.get(level) || (releasePlan.set(level, queue = []), queue)).push(this); if (releasePlanIndex > level) { releasePlanIndex = level; } if (releasePlanToIndex < level) { releasePlanToIndex = level; } this._levelInRelease = level; if (!releasePlanned && !currentlyRelease) { releasePlanned = true; if (!transactionLevel && !config.asynchronous) { release(); } else { nextTick$1(release); } } }, /** * @typesign (evt: cellx~Event); */ _onValueChange: function _onValueChange(evt) { this._pushingIndex = ++pushingIndexCounter; if (this._changeEvent) { evt.prev = this._changeEvent; this._changeEvent = evt; if (this._value === this._fixedValue) { this._state &= ~STATE_CAN_CANCEL_CHANGE; } } else { evt.prev = null; this._changeEvent = evt; this._state &= ~STATE_CAN_CANCEL_CHANGE; this._addToRelease(); } }, /** * @typesign () -> *; */ get: function get() { if (releasePlanned && this._pull) { release(); } if (this._pull && !(this._state & STATE_ACTIVE) && this._version < releaseVersion && this._masters !== null) { var oldMasters = this._masters; var value = this._tryPull(); var masters = this._masters; if (oldMasters || masters || !(this._state & STATE_INITED)) { if (masters && this._state & STATE_HAS_FOLLOWERS) { var i = masters.length; do { masters[--i]._registerSlave(this); } while (i); this._state |= STATE_ACTIVE; } if (value === error) { this._fail(error.original, false); } else { this._push(value, false, false); } } } if (currentCell) { var currentCellMasters = currentCell._masters; var level = this._level; if (currentCellMasters) { if (currentCellMasters.indexOf(this) == -1) { currentCellMasters.push(this); if (currentCell._level <= level) { currentCell._level = level + 1; } } } else { currentCell._masters = [this]; currentCell._level = level + 1; } } return this._get ? this._get(this._value) : this._value; }, /** * @typesign () -> boolean; */ pull: function pull() { if (!this._pull) { return false; } if (releasePlanned) { release(); } var hasFollowers = this._state & STATE_HAS_FOLLOWERS; var oldMasters; var oldLevel; if (hasFollowers) { oldMasters = this._masters; oldLevel = this._level; } var value = this._tryPull(); if (hasFollowers) { var masters = this._masters; var newMasterCount = 0; if (masters) { var i = masters.length; do { var master = masters[--i]; if (!oldMasters || oldMasters.indexOf(master) == -1) { master._registerSlave(this); newMasterCount++; } } while (i); } if (oldMasters && (masters ? masters.length - newMasterCount : 0) < oldMasters.length) { for (var j = oldMasters.length; j;) { var oldMaster = oldMasters[--j]; if (!masters || masters.indexOf(oldMaster) == -1) { oldMaster._unregisterSlave(this); } } } if (masters && masters.length) { this._state |= STATE_ACTIVE; } else { this._state &= ~STATE_ACTIVE; } if (currentlyRelease && this._level > oldLevel) { this._addToRelease(); return false; } } if (value === error) { this._fail(error.original, false); return true; } return this._push(value, false, true); }, /** * @typesign () -> *; */ _tryPull: function _tryPull() { if (this._state & STATE_CURRENTLY_PULLING) { throw new TypeError('Circular pulling detected'); } var pull = this._pull; if (pull.length) { this._state |= STATE_PENDING; if (this._selfPendingStatusCell) { this._selfPendingStatusCell.set(true); } this._state &= ~(STATE_FULFILLED | STATE_REJECTED); } var prevCell = currentCell; currentCell = this; this._state |= STATE_CURRENTLY_PULLING; this._masters = null; this._level = 0; try { return pull.length ? pull.call(this.owner, this, this._value) : pull.call(this.owner); } catch (err) { error.original = err; return error; } finally { currentCell = prevCell; this._version = releaseVersion + currentlyRelease; var pendingStatusCell = this._pendingStatusCell; if (pendingStatusCell && pendingStatusCell._state & STATE_ACTIVE) { pendingStatusCell.pull(); } var errorCell = this._errorCell; if (errorCell && errorCell._state & STATE_ACTIVE) { errorCell.pull(); } this._state ^= STATE_CURRENTLY_PULLING; } }, /** * @typesign () -> ?Error; */ getError: function getError() { var errorCell = this._errorCell; if (!errorCell) { var debugKey = this.debugKey; this._selfErrorCell = new Cell(this._error, debugKey ? { debugKey: debugKey + '._selfErrorCell' } : null); errorCell = this._errorCell = new Cell(function () { this.get(); var err = this._selfErrorCell.get(); var index; if (err) { index = this._errorIndex; if (index == errorIndexCounter) { return err; } } var masters = this._masters; if (masters) { var i = masters.length; do { var master = masters[--i]; var masterError = master.getError(); if (masterError) { var masterErrorIndex = master._errorIndex; if (masterErrorIndex == errorIndexCounter) { return masterError; } if (!err || index < masterErrorIndex) { err = masterError; index = masterErrorIndex; } } } while (i); } return err; }, debugKey ? { debugKey: debugKey + '._errorCell', owner: this } : { owner: this }); } return errorCell.get(); }, /** * @typesign () -> boolean; */ isPending: function isPending() { var pendingStatusCell = this._pendingStatusCell; if (!pendingStatusCell) { var debugKey = this.debugKey; this._selfPendingStatusCell = new Cell(!!(this._state & STATE_PENDING), debugKey ? { debugKey: debugKey + '._selfPendingStatusCell' } : null); pendingStatusCell = this._pendingStatusCell = new Cell(function () { if (this._selfPendingStatusCell.get()) { return true; } this.get(); var masters = this._masters; if (masters) { var i = masters.length; do { if (masters[--i].isPending()) { return true; } } while (i); } return false; }, debugKey ? { debugKey: debugKey + '._pendingStatusCell', owner: this } : { owner: this }); } return pendingStatusCell.get(); }, getStatus: function getStatus() { var status = this._status; if (!status) { var cell = this; status = this._status = { get success() { return !cell.getError(); }, get pending() { return cell.isPending(); } }; } return status; }, /** * @typesign (value) -> cellx.Cell; */ set: function set(value) { if (this._validate) { this._validate(value, this._value); } if (this._merge) { value = this._merge(value, this._value); } this._state |= STATE_PENDING; if (this._selfPendingStatusCell) { this._selfPendingStatusCell.set(true); } this._state &= ~(STATE_FULFILLED | STATE_REJECTED); if (this._put.length >= 3) { this._put.call(this.owner, this, value, this._value); } else { this._put.call(this.owner, this, value); } return this; }, /** * @typesign (value) -> cellx.Cell; */ push: function push(value) { this._push(value, true, false); return this; }, /** * @typesign (value, external: boolean, pulling: boolean) -> boolean; */ _push: function _push(value, external, pulling) { this._state |= STATE_INITED; var oldValue = this._value; if (external && currentlyRelease && this._state & STATE_HAS_FOLLOWERS) { if (is(value, oldValue)) { this._setError(null); this._fulfill(value); return false; } var cell = this; (afterReleaseCallbacks || (afterReleaseCallbacks = [])).push((function () { cell._push(value, true, false); })); return true; } if (external || !currentlyRelease && pulling) { this._pushingIndex = ++pushingIndexCounter; } this._setError(null); if (is(value, oldValue)) { if (external || currentlyRelease && pulling) { this._fulfill(value); } return false; } this._value = value; if (oldValue instanceof EventEmitter) { oldValue.off('change', this._onValueChange, this); } if (value instanceof EventEmitter) { value.on('change', this._onValueChange, this); } if (this._state & STATE_HAS_FOLLOWERS || transactionLevel) { if (this._changeEvent) { if (is(value, this._fixedValue) && this._state & STATE_CAN_CANCEL_CHANGE) { this._levelInRelease = -1; this._changeEvent = null; } else { this._changeEvent = { target: this, type: 'change', oldValue: oldValue, value: value, prev: this._changeEvent }; } } else { this._changeEvent = { target: this, type: 'change', oldValue: oldValue, value: value, prev: null }; this._state |= STATE_CAN_CANCEL_CHANGE; this._addToRelease(); } } else { if (external || !currentlyRelease && pulling) { releaseVersion++; } this._fixedValue = value; this._version = releaseVersion + currentlyRelease; } if (external || currentlyRelease && pulling) { this._fulfill(value); } return true; }, /** * @typesign (value); */ _fulfill: function _fulfill(value) { this._resolvePending(); if (!(this._state & STATE_FULFILLED)) { this._state |= STATE_FULFILLED; if (this._onFulfilled) { this._onFulfilled(value); } } }, /** * @typesign (err) -> cellx.Cell; */ fail: function fail(err) { this._fail(err, true); return this; }, /** * @typesign (err, external: boolean); */ _fail: function _fail(err, external) { if (transactionLevel) { transactionFailure = true; } this._logError(err); if (!(err instanceof Error)) { err = new Error(String(err)); } this._setError(err); if (external) { this._reject(err); } }, /** * @typesign (err: ?Error); */ _setError: function _setError(err) { if (!err && !this._error) { return; } this._error = err; if (this._selfErrorCell) { this._selfErrorCell.set(err); } if (err) { this._errorIndex = ++errorIndexCounter; this._handleErrorEvent({ type: 'error', error: err }); } }, /** * @typesign (evt: cellx~Event{ error: Error }); */ _handleErrorEvent: function _handleErrorEvent(evt) { if (this._lastErrorEvent === evt) { return; } this._lastErrorEvent = evt; this._handleEvent(evt); var slaves = this._slaves; for (var i = 0, l = slaves.length; i < l; i++) { slaves[i]._handleErrorEvent(evt); } }, /** * @typesign (err: Error); */ _reject: function _reject(err) { this._resolvePending(); if (!(this._state & STATE_REJECTED)) { this._state |= STATE_REJECTED; if (this._onRejected) { this._onRejected(err); } } }, /** * @typesign (); */ _resolvePending: function _resolvePending() { if (this._state & STATE_PENDING) { this._state ^= STATE_PENDING; if (this._selfPendingStatusCell) { this._selfPendingStatusCell.set(false); } } }, /** * @typesign (onFulfilled: ?(value) -> *, onRejected?: (err) -> *) -> Promise; */ then: function then(onFulfilled, onRejected) { if (releasePlanned) { release(); } if (!this._pull || this._state & STATE_FULFILLED) { return Promise.resolve(this._get ? this._get(this._value) : this._value).then(onFulfilled); } if (this._state & STATE_REJECTED) { return Promise.reject(this._error).catch(onRejected); } var cell = this; var promise = new Promise(function (resolve, reject) { cell._onFulfilled = function onFulfilled(value) { cell._onFulfilled = cell._onRejected = null; resolve(cell._get ? cell._get(value) : value); }; cell._onRejected = function onRejected(err) { cell._onFulfilled = cell._onRejected = null; reject(err); }; }).then(onFulfilled, onRejected); if (!(this._state & STATE_PENDING)) { this.pull(); } if (cell.isPending()) { cell._pendingStatusCell.on('change', (function onPendingStatusCellChange() { cell._pendingStatusCell.off('change', onPendingStatusCellChange); if (!(cell._state & STATE_FULFILLED) && !(cell._state & STATE_REJECTED)) { var err = cell.getError(); if (err) { cell._reject(err); } else { cell._fulfill(cell._get ? cell._get(cell._value) : cell._value); } } })); } return promise; }, /** * @typesign (onRejected: (err) -> *) -> Promise; */ catch: function catch_(onRejected) { return this.then(null, onRejected); }, /** * @override */ _logError: function _logError() { var msg = slice$1.call(arguments); if (this.debugKey) { msg.unshift('[' + this.debugKey + ']'); } EventEmitterProto._logError.apply(this, msg); }, /** * @typesign () -> cellx.Cell; */ reap: function reap() { var slaves = this._slaves; for (var i = 0, l = slaves.length; i < l; i++) { slaves[i].reap(); } return this.off(); }, /** * @typesign () -> cellx.Cell; */ dispose: function dispose() { return this.reap(); } }; Cell.prototype[Symbol$1.iterator] = function () { return this._value[Symbol$1.iterator](); }; function ObservableCollectionMixin() { /** * @type {Map<*, uint>} */ this._valueCounts = new Map$1(); } ObservableCollectionMixin.prototype = { /** * @typesign (evt: cellx~Event); */ _onItemChange: function _onItemChange(evt) { this._handleEvent(evt); }, /** * @typesign (value); */ _registerValue: function _registerValue(value) { var valueCounts = this._valueCounts; var valueCount = valueCounts.get(value); if (valueCount) { valueCounts.set(value, valueCount + 1); } else { valueCounts.set(value, 1); if (this.adoptsValueChanges && value instanceof EventEmitter) { value.on('change', this._onItemChange, this); } } }, /** * @typesign (value); */ _unregisterValue: function _unregisterValue(value) { var valueCounts = this._valueCounts; var valueCount = valueCounts.get(value); if (valueCount > 1) { valueCounts.set(value, valueCount - 1); } else { valueCounts.delete(value); if (this.adoptsValueChanges && value instanceof EventEmitter) { value.off('change', this._onItemChange, this); } } } }; var push = Array.prototype.push; var splice = Array.prototype.splice; /** * @typesign (a, b) -> -1 | 1 | 0; */ function defaultComparator(a, b) { return a < b ? -1 : a > b ? 1 : 0; } /** * @class cellx.ObservableList * @extends {cellx.EventEmitter} * @implements {cellx.ObservableCollectionMixin} * * @typesign new ObservableList(items?: Array | cellx.ObservableList, opts?: { * adoptsValueChanges?: boolean, * comparator?: (a, b) -> int, * sorted?: boolean * }) -> cellx.ObservableList; * * @typesign new ObservableList( * items?: Array | cellx.ObservableList, * adoptsValueChanges?: boolean * ) -> cellx.ObservableList; */ function ObservableList(items, opts) { EventEmitter.call(this); ObservableCollectionMixin.call(this); if (typeof opts == 'boolean') { opts = { adoptsValueChanges: opts }; } this._items = []; this.length = 0; /** * @type {boolean} */ this.adoptsValueChanges = !!(opts && opts.adoptsValueChanges); /** * @type {?(a, b) -> int} */ this.comparator = null; this.sorted = false; if (opts && (opts.sorted || opts.comparator && opts.sorted !== false)) { this.comparator = opts.comparator || defaultComparator; this.sorted = true; } if (items) { this._addRange(items); } } ObservableList.prototype = mixin({ __proto__: EventEmitter.prototype }, ObservableCollectionMixin.prototype, { constructor: ObservableList, /** * @typesign (index: ?int, allowEndIndex?: boolean) -> ?uint; */ _validateIndex: function _validateIndex(index, allowEndIndex) { if (index === undefined) { return index; } if (index < 0) { index += this.length; if (index < 0) { throw new RangeError('Index out of valid range'); } } else if (index >= this.length + (allowEndIndex ? 1 : 0)) { throw new RangeError('Index out of valid range'); } return index; }, /** * @typesign (value) -> boolean; */ contains: function contains(value) { return this._valueCounts.has(value); }, /** * @typesign (value, fromIndex?: int) -> int; */ indexOf: function indexOf(value, fromIndex) { return this._items.indexOf(value, this._validateIndex(fromIndex, true)); }, /** * @typesign (value, fromIndex?: int) -> int; */ lastIndexOf: function lastIndexOf(value, fromIndex) { return this._items.lastIndexOf(value, fromIndex === undefined ? -1 : this._validateIndex(fromIndex, true)); }, /** * @typesign (index: int) -> *; */ get: function get(index) { return this._items[this._validateIndex(index, true)]; }, /** * @typesign (index: int, count?: uint) -> Array; */ getRange: function getRange(index, count) { index = this._validateIndex(index, true); var items = this._items; if (count === undefined) { return items.slice(index); } if (index + count > items.length) { throw new RangeError('Sum of "index" and "count" out of valid range'); } return items.slice(index, index + count); }, /** * @typesign (index: int, value) -> cellx.ObservableList; */ set: function set(index, value) { if (this.sorted) { throw new TypeError('Cannot set to sorted list'); } index = this._validateIndex(index, true); var items = this._items; if (is(value, items[index])) { return this; } this._unregisterValue(items[index]); this._registerValue(value); items[index] = value; this.emit('change'); return this; }, /** * @typesign (index: int, values: Array | cellx.ObservableList) -> cellx.ObservableList; */ setRange: function setRange(index, values) { if (this.sorted) { throw new TypeError('Cannot set to sorted list'); } index = this._validateIndex(index, true); if (values instanceof ObservableList) { values = values._items; } var valueCount = values.length; if (!valueCount) { return this; } if (index + valueCount > this.length) { throw new RangeError('Sum of "index" and "values.length" out of valid range'); } var items = this._items; var changed = false; for (var i = index + valueCount; i > index;) { var value = values[--i - index]; if (!is(value, items[i])) { this._unregisterValue(items[i]); this._registerValue(value); items[i] = value; changed = true; } } if (changed) { this.emit('change'); } return this; }, /** * @typesign (value) -> cellx.ObservableList; */ add: function add(value) { if (this.sorted) { this._insertValue(value); } else { this._registerValue(value); this._items.push(value); } this.length++; this.emit('change'); return this; }, /** * @typesign (values: Array | cellx.ObservableList) -> cellx.ObservableList; */ addRange: function addRange(values) { if (values.length) { this._addRange(values); this.emit('change'); } return this; }, /** * @typesign (values: Array | cellx.ObservableList); */ _addRange: function _addRange(values) { if (values instanceof ObservableList) { values = values._items; } if (this.sorted) { for (var i = 0, l = values.length; i < l; i++) { this._insertValue(values[i]); } this.length += values.length; } else { for (var j = values.length; j;) { this._registerValue(values[--j]); } this.length = push.apply(this._items, values); } }, /** * @typesign (value); */ _insertValue: function _insertValue(value) { this._registerValue(value); var items = this._items; var comparator = this.comparator; var low = 0; var high = items.length; while (low != high) { var mid = low + high >> 1; if (comparator(value, items[mid]) < 0) { high = mid; } else { low = mid + 1; } } items.splice(low, 0, value); }, /** * @typesign (index: int, value) -> cellx.ObservableList; */ insert: function insert(index, value) { if (this.sorted) { throw new TypeError('Cannot insert to sorted list'); } index = this._validateIndex(index, true); this._registerValue(value); this._items.splice(index, 0, value); this.length++; this.emit('change'); return this; }, /** * @typesign (index: int, values: Array | cellx.ObservableList) -> cellx.ObservableList; */ insertRange: function insertRange(index, values) { if (this.sorted) { throw new TypeError('Cannot insert to sorted list'); } index = this._validateIndex(index, true); if (values instanceof ObservableList) { values = values._items; } var valueCount = values.length; if (!valueCount) { return this; } for (var i = valueCount; i;) { this._registerValue(values[--i]); } splice.apply(this._items, [index, 0].concat(values)); this.length += valueCount; this.emit('change'); return this; }, /** * @typesign (value, fromIndex?: int) -> boolean; */ remove: function remove(value, fromIndex) { var index = this._items.indexOf(value, this._validateIndex(fromIndex, true)); if (index == -1) { return false; } this._unregisterValue(value); this._items.splice(index, 1); this.length--; this.emit('change'); return true; }, /** * @typesign (value, fromIndex?: int) -> boolean; */ removeAll: function removeAll(value, fromIndex) { var index = this._validateIndex(fromIndex, true); var items = this._items; var changed = false; while ((index = items.indexOf(value, index)) != -1) { this._unregisterValue(value); items.splice(index, 1); changed = true; } if (changed) { this.length = items.length; this.emit('change'); } return changed; }, /** * @typesign (values: Array | cellx.ObservableList, fromIndex?: int) -> boolean; */ removeEach: function removeEach(values, fromIndex) { fromIndex = this._validateIndex(fromIndex, true); if (values instanceof ObservableList) { values = values._items; } var items = this._items; var changed = false; for (var i = 0, l = values.length; i < l; i++) { var value = values[i]; var index = items.indexOf(value, fromIndex); if (index != -1) { this._unregisterValue(value); items.splice(index, 1); changed = true; } } if (changed) { this.length = items.length; this.emit('change'); } return changed; }, /** * @typesign (values: Array | cellx.ObservableList, fromIndex?: int) -> boolean; */ removeAllEach: function removeAllEach(values, fromIndex) { fromIndex = this._validateIndex(fromIndex, true); if (values instanceof ObservableList) { values = values._items; } var items = this._items; var changed = false; for (var i = 0, l = values.length; i < l; i++) { var value = values[i]; for (var index = fromIndex; (index = items.indexOf(value, index)) != -1;) { this._unregisterValue(value); items.splice(index, 1); changed = true; } } if (changed) { this.length = items.length; this.emit('change'); } return changed; }, /** * @typesign (index: int) -> *; */ removeAt: function removeAt(index) { var value = this._items.splice(this._validateIndex(index), 1)[0]; this._unregisterValue(value); this.length--; this.emit('change'); return value; }, /** * @typesign (index: int, count?: uint) -> Array; */ removeRange: function removeRange(index, count) { index = this._validateIndex(index, true); var items = this._items; if (count === undefined) { count = items.length - index; } else if (index + count > items.length) { throw new RangeError('Sum of "index" and "count" out of valid range'); } if (!count) { return []; } for (var i = index + count; i > index;) { this._unregisterValue(items[--i]); } var values = items.splice(index, count); this.length -= count; this.emit('change'); return values; }, /** * @typesign () -> cellx.ObservableList; */ clear: function clear() { if (!this.length) { return this; } if (this.adoptsValueChanges) { this._valueCounts.forEach((function (value) { if (value instanceof EventEmitter) { value.off('change', this._onItemChange, this); } }), this); } this._items.length = 0; this._valueCounts.clear(); this.length = 0; this.emit({ type: 'change', subtype: 'clear' }); return this; }, /** * @typesign (separator?: string) -> string; */ join: function join(separator) { return this._items.join(separator); }, /** * @typesign ( * callback: (item, index: uint, list: cellx.ObservableList), * context? * ); */ forEach: null, /** * @typesign ( * callback: (item, index: uint, list: cellx.ObservableList) -> *, * context? * ) -> Array; */ map: null, /** * @typesign ( * callback: (item, index: uint, list: cellx.ObservableList) -> ?boolean, * context? * ) -> Array; */ filter: null, /** * @typesign ( * callback: (item, index: uint, list: cellx.ObservableList) -> ?boolean, * context? * ) -> *; */ find: function (callback, context) { var items = this._items; for (var i = 0, l = items.length; i < l; i++) { var item = items[i]; if (callback.call(context, item, i, this)) { return item; } } }, /** * @typesign ( * callback: (item, index: uint, list: cellx.ObservableList) -> ?boolean, * context? * ) -> int; */ findIndex: function (callback, context) { var items = this._items; for (var i = 0, l = items.length; i < l; i++) { if (callback.call(context, items[i], i, this)) { return i; } } return -1; }, /** * @typesign ( * callback: (item, index: uint, list: cellx.ObservableList) -> ?boolean, * context? * ) -> boolean; */ every: null, /** * @typesign ( * callback: (item, index: uint, list: cellx.ObservableList) -> ?boolean, * context? * ) -> boolean; */ some: null, /** * @typesign ( * callback: (accumulator, item, index: uint, list: cellx.ObservableList) -> *, * initialValue? * ) -> *; */ reduce: null, /** * @typesign ( * callback: (accumulator, item, index: uint, list: cellx.ObservableList) -> *, * initialValue? * ) -> *; */ reduceRight: null, /** * @typesign () -> cellx.ObservableList; */ clone: function clone() { return new this.constructor(this, { adoptsValueChanges: this.adoptsValueChanges, comparator: this.comparator, sorted: this.sorted }); }, /** * @typesign () -> Array; */ toArray: function toArray() { return this._items.slice(); }, /** * @typesign () -> string; */ toString: function toString() { return this._items.join(); } }); ['forEach', 'map', 'filter', 'every', 'some'].forEach((function (name) { ObservableList.prototype[name] = function (callback, context) { return this._items[name]((function (item, index) { return callback.call(context, item, index, this); }), this); }; })); ['reduce', 'reduceRight'].forEach((function (name) { ObservableList.prototype[name] = function (callback, initialValue) { var items = this._items; var list = this; function wrapper(accumulator, item, index) { return callback(accumulator, item, index, list); } return arguments.length >= 2 ? items[name](wrapper, initialValue) : items[name](wrapper); }; })); [['keys', function keys(index) { return index; }], ['values', function values(index, item) { return item; }], ['entries', function entries(index, item) { return [index, item]; }]].forEach((function (settings) { var getStepValue = settings[1]; ObservableList.prototype[settings[0]] = function () { var items = this._items; var index = 0; var done = false; return { next: function () { if (!done) { if (index < items.length) { return { value: getStepValue(index, items[index++]), done: false }; } done = true; } return { value: undefined, done: true }; } }; }; })); ObservableList.prototype[Symbol$1.iterator] = ObservableList.prototype.values; /** * @class cellx.ObservableMap * @extends {cellx.EventEmitter} * @implements {cellx.ObservableCollectionMixin} * * @typesign new ObservableMap(entries?: Object | cellx.ObservableMap | Map | Array<{ 0, 1 }>, opts?: { * adoptsValueChanges?: boolean * }) -> cellx.ObservableMap; * * @typesign new ObservableMap( * entries?: Object | cellx.ObservableMap | Map | Array<{ 0, 1 }>, * adoptsValueChanges?: boolean * ) -> cellx.ObservableMap; */ function ObservableMap(entries, opts) { EventEmitter.call(this); ObservableCollectionMixin.call(this); if (typeof opts == 'boolean') { opts = { adoptsValueChanges: opts }; } this._entries = new Map$1(); this.size = 0; /** * @type {boolean} */ this.adoptsValueChanges = !!(opts && opts.adoptsValueChanges); if (entries) { var mapEntries = this._entries; if (entries instanceof ObservableMap || entries instanceof Map$1) { entries._entries.forEach((function (value, key) { this._registerValue(value); mapEntries.set(key, value); }), this); } else if (Array.isArray(entries)) { for (var i = 0, l = entries.length; i < l; i++) { var entry = entries[i]; this._registerValue(entry[1]); mapEntries.set(entry[0], entry[1]); } } else { for (var key in entries) { this._registerValue(entries[key]); mapEntries.set(key, entries[key]); } } this.size = mapEntries.size; } } ObservableMap.prototype = mixin({ __proto__: EventEmitter.prototype }, ObservableCollectionMixin.prototype, { constructor: ObservableMap, /** * @typesign (key) -> boolean; */ has: function has(key) { return this._entries.has(key); }, /** * @typesign (value) -> boolean; */ contains: function contains(value) { return this._valueCounts.has(value); }, /** * @typesign (key) -> *; */ get: function get(key) { return this._entries.get(key); }, /** * @typesign (key, value) -> cellx.ObservableMap; */ set: function set(key, value) { var entries = this._entries; var hasKey = entries.has(key); var oldValue; if (hasKey) { oldValue = entries.get(key); if (is(value, oldValue)) { return this; } this._unregisterValue(oldValue); } this._registerValue(value); entries.set(key, value); if (!hasKey) { this.size++; } this.emit({ type: 'change', subtype: hasKey ? 'update' : 'add', key: key, oldValue: oldValue, value: value }); return this; }, /** * @typesign (key) -> boolean; */ delete: function delete_(key) { var entries = this._entries; if (!entries.has(key)) { return false; } var value = entries.get(key); this._unregisterValue(value); entries.delete(key); this.size--; this.emit({ type: 'change', subtype: 'delete', key: key, oldValue: value, value: undefined }); return true; }, /** * @typesign () -> cellx.ObservableMap; */ clear: function clear() { if (!this.size) { return this; } if (this.adoptsValueChanges) { this._valueCounts.forEach((function (value) { if (value instanceof EventEmitter) { value.off('change', this._onItemChange, this); } }), this); } this._entries.clear(); this._valueCounts.clear(); this.size = 0; this.emit({ type: 'change', subtype: 'clear' }); return this; }, /** * @typesign ( * callback: (value, key, map: cellx.ObservableMap), * context? * ); */ forEach: function forEach(callback, context) { this._entries.forEach((function (value, key) { callback.call(context, value, key, this); }), this); }, /** * @typesign () -> { next: () -> { value, done: boolean } }; */ keys: function keys() { return this._entries.keys(); }, /** * @typesign () -> { next: () -> { value, done: boolean } }; */ values: function values() { return this._entries.values(); }, /** * @typesign () -> { next: () -> { value: { 0, 1 }, done: boolean } }; */ entries: function entries() { return this._entries.entries(); }, /** * @typesign () -> cellx.ObservableMap; */ clone: function clone() { return new this.constructor(this, { adoptsValueChanges: this.adoptsValueChanges }); } }); ObservableMap.prototype[Symbol$1.iterator] = ObservableMap.prototype.entries; var map$1 = Array.prototype.map; /** * @typesign (...msg); */ function logError() { var console = global$1.console; (console && console.error || noop).call(console || global$1, map$1.call(arguments, (function (arg) { return arg === Object(arg) && arg.stack || arg; })).join(' ')); } var hasOwn = Object.prototype.hasOwnProperty; var slice = Array.prototype.slice; ErrorLogger.setHandler(logError); var assign = Object.assign || function (target, source) { for (var name in source) { target[name] = source[name]; } return target; }; /** * @typesign (value?, opts?: { * debugKey?: string, * owner?: Object, * validate?: (value, oldValue), * merge: (value, oldValue) -> *, * put?: (cell: Cell, value, oldValue), * reap?: (), * onChange?: (evt: cellx~Event) -> ?boolean, * onError?: (evt: cellx~Event) -> ?boolean * }) -> cellx; * * @typesign (pull: (cell: Cell, next) -> *, opts?: { * debugKey?: string, * owner?: Object, * validate?: (value, oldValue), * merge: (value, oldValue) -> *, * put?: (cell: Cell, value, oldValue), * reap?: (), * onChange?: (evt: cellx~Event) -> ?boolean, * onError?: (evt: cellx~Event) -> ?boolean * }) -> cellx; */ function cellx(value, opts) { if (!opts) { opts = {}; } var initialValue = value; function cx(value) { var owner = this; if (!owner || owner == global$1) { owner = cx; } if (!hasOwn.call(owner, CELLS)) { Object.defineProperty(owner, CELLS, { value: new Map$1() }); } var cell = owner[CELLS].get(cx); if (!cell) { if (value === 'dispose' && arguments.length >= 2) { return; } cell = new Cell(initialValue, assign({ owner: owner }, opts)); owner[CELLS].set(cx, cell); } switch (arguments.length) { case 0: { return cell.get(); } case 1: { cell.set(value); return value; } default: { var method = value; switch (method) { case 'bind': { cx = cx.bind(owner); cx.constructor = cellx; return cx; } case 'unwrap': { return cell; } default: { var result = Cell.prototype[method].apply(cell, slice.call(arguments, 1)); return result === cell ? cx : result; } } } } } cx.constructor = cellx; if (opts.onChange || opts.onError) { cx.call(opts.owner || global$1); } return cx; } cellx.configure = function (config) { Cell.configure(config); }; cellx.ErrorLogger = ErrorLogger; cellx.EventEmitter = EventEmitter; cellx.ObservableCollectionMixin = ObservableCollectionMixin; cellx.ObservableMap = ObservableMap; cellx.ObservableList = ObservableList; cellx.Cell = Cell; cellx.autorun = Cell.autorun; cellx.transact = cellx.transaction = Cell.transaction; cellx.KEY_UID = UID; cellx.KEY_CELLS = CELLS; /** * @typesign ( * entries?: Object | Array<{ 0, 1 }> | cellx.ObservableMap, * opts?: { adoptsValueChanges?: boolean } * ) -> cellx.ObservableMap; * * @typesign ( * entries?: Object | Array<{ 0, 1 }> | cellx.ObservableMap, * adoptsValueChanges?: boolean * ) -> cellx.ObservableMap; */ function map(entries, opts) { return new ObservableMap(entries, opts); } cellx.map = map; /** * @typesign (items?: Array | cellx.ObservableList, opts?: { * adoptsValueChanges?: boolean, * comparator?: (a, b) -> int, * sorted?: boolean * }) -> cellx.ObservableList; * * @typesign (items?: Array | cellx.ObservableList, adoptsValueChanges?: boolean) -> cellx.ObservableList; */ function list(items, opts) { return new ObservableList(items, opts); } cellx.list = list; /** * @typesign (obj: cellx.EventEmitter, name: string, value) -> cellx.EventEmitter; */ function defineObservableProperty(obj, name, value) { var cellName = name + 'Cell'; obj[cellName] = value instanceof Cell ? value : new Cell(value, { owner: obj }); Object.defineProperty(obj, name, { configurable: true, enumerable: true, get: function () { return this[cellName].get(); }, set: function (value) { this[cellName].set(value); } }); return obj; } cellx.defineObservableProperty = defineObservableProperty; /** * @typesign (obj: cellx.EventEmitter, props: Object) -> cellx.EventEmitter; */ function defineObservableProperties(obj, props) { Object.keys(props).forEach((function (name) { defineObservableProperty(obj, name, props[name]); })); return obj; } cellx.defineObservableProperties = defineObservableProperties; /** * @typesign (obj: cellx.EventEmitter, name: string, value) -> cellx.EventEmitter; * @typesign (obj: cellx.EventEmitter, props: Object) -> cellx.EventEmitter; */ function define(obj, name, value) { if (typeof name == 'string') { defineObservableProperty(obj, name, value); } else { defineObservableProperties(obj, name); } return obj; } cellx.define = define; cellx.JS = { is: is, Symbol: Symbol$1, Map: Map$1 }; cellx.Utils = { logError: logError, nextUID: nextUID, mixin: mixin, nextTick: nextTick$1, noop: noop }; cellx.cellx = cellx; cellx.__esModule = true; cellx.default = cellx; return cellx; })));
/* Magic Mirror * Node Helper: Calendar * * By Michael Teeuw http://michaelteeuw.nl * MIT Licensed. */ var NodeHelper = require("node_helper"); var validUrl = require("valid-url"); var CalendarFetcher = require("./calendarfetcher.js"); module.exports = NodeHelper.create({ // Override start method. start: function() { var self = this; var events = []; this.fetchers = []; console.log("Starting node helper for: " + this.name); }, // Override socketNotificationReceived method. socketNotificationReceived: function(notification, payload) { if (notification === "ADD_CALENDAR") { //console.log('ADD_CALENDAR: '); this.createFetcher(payload.url, payload.fetchInterval, payload.maximumEntries, payload.maximumNumberOfDays, payload.user, payload.pass); } }, /* createFetcher(url, reloadInterval) * Creates a fetcher for a new url if it doesn't exist yet. * Otherwise it reuses the existing one. * * attribute url string - URL of the news feed. * attribute reloadInterval number - Reload interval in milliseconds. */ createFetcher: function(url, fetchInterval, maximumEntries, maximumNumberOfDays, user, pass) { var self = this; if (!validUrl.isUri(url)) { self.sendSocketNotification("INCORRECT_URL", {url: url}); return; } var fetcher; if (typeof self.fetchers[url] === "undefined") { console.log("Create new calendar fetcher for url: " + url + " - Interval: " + fetchInterval); fetcher = new CalendarFetcher(url, fetchInterval, maximumEntries, maximumNumberOfDays, user, pass); fetcher.onReceive(function(fetcher) { //console.log('Broadcast events.'); //console.log(fetcher.events()); self.sendSocketNotification("CALENDAR_EVENTS", { url: fetcher.url(), events: fetcher.events() }); }); fetcher.onError(function(fetcher, error) { self.sendSocketNotification("FETCH_ERROR", { url: fetcher.url(), error: error }); }); self.fetchers[url] = fetcher; } else { //console.log('Use existing news fetcher for url: ' + url); fetcher = self.fetchers[url]; fetcher.broadcastEvents(); } fetcher.startFetch(); } });
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } (function (global, factory) { if (typeof define === "function" && define.amd) { define(["exports"], factory); } else if (typeof exports !== "undefined") { factory(exports); } else { var mod = { exports: {} }; factory(mod.exports); global.createComponent = mod.exports; } })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_exports) { "use strict"; Object.defineProperty(_exports, "__esModule", { value: true }); _exports.default = _default; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } /** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ function _default(ToMix) { var CreateComponent = /*#__PURE__*/function (_ToMix) { _inherits(CreateComponent, _ToMix); var _super = _createSuper(CreateComponent); /** * The component instances managed by this component. * Releasing this component also releases the components in `this.children`. * @type {Component[]} */ /** * Mix-in class to manage lifecycle of component. * The constructor sets up this component's effective options, * and registers this component's instance associated to an element. * @implements Handle * @param {HTMLElement} element The element working as this component. * @param {object} [options] The component options. */ function CreateComponent(element) { var _this; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck(this, CreateComponent); _this = _super.call(this, element, options); _this.children = []; if (!element || element.nodeType !== Node.ELEMENT_NODE) { throw new TypeError('DOM element should be given to initialize this widget.'); } /** * The element the component is of. * @type {Element} */ _this.element = element; /** * The component options. * @type {object} */ _this.options = Object.assign(Object.create(_this.constructor.options), options); _this.constructor.components.set(_this.element, _assertThisInitialized(_this)); return _this; } /** * Instantiates this component of the given element. * @param {HTMLElement} element The element. */ _createClass(CreateComponent, [{ key: "release", value: /** * Releases this component's instance from the associated element. */ function release() { for (var child = this.children.pop(); child; child = this.children.pop()) { child.release(); } this.constructor.components.delete(this.element); return null; } }], [{ key: "create", value: function create(element, options) { return this.components.get(element) || new this(element, options); } }]); return CreateComponent; }(ToMix); return CreateComponent; } });
Meteor.startup(function() { RocketChat.settings.add('GoogleNaturalLanguage_Enabled', false, { type: 'boolean', group: 'Message', section: 'Google Natural Language', public: true, i18nLabel: 'Enabled' }); RocketChat.settings.add('GoogleNaturalLanguage_ServiceAccount', '', { type: 'string', group: 'Message', section: 'Google Natural Language', multiline: true, enableQuery: { _id: 'GoogleNaturalLanguage_Enabled', value: true }, i18nLabel: 'Service_account_key' }); });
'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; ;(function (window, linkify) { var linkifyElement = function (linkify) { 'use strict'; var tokenize = linkify.tokenize; var options = linkify.options; var HTML_NODE = 1; var TXT_NODE = 3; /** Given a parent element and child node that the parent contains, replaces that child with the given array of new children */ function replaceChildWithChildren(parent, oldChild, newChildren) { var lastNewChild = newChildren[newChildren.length - 1]; parent.replaceChild(lastNewChild, oldChild); for (var i = newChildren.length - 2; i >= 0; i--) { parent.insertBefore(newChildren[i], lastNewChild); lastNewChild = newChildren[i]; } } /** Given an array of MultiTokens, return an array of Nodes that are either (a) Plain Text nodes (node type 3) (b) Anchor tag nodes (usually, unless tag name is overridden in the options) Takes the same options as linkifyElement and an optional doc element (this should be passed in by linkifyElement) */ function tokensToNodes(tokens, opts, doc) { var result = []; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; var validated = token.isLink && options.resolve(opts.validate, token.toString(), token.type); if (token.isLink && validated) { var href = token.toHref(opts.defaultProtocol), formatted = options.resolve(opts.format, token.toString(), token.type), formattedHref = options.resolve(opts.formatHref, href, token.type), attributesHash = options.resolve(opts.attributes, href, token.type), tagName = options.resolve(opts.tagName, href, token.type), linkClass = options.resolve(opts.linkClass, href, token.type), target = options.resolve(opts.target, href, token.type), events = options.resolve(opts.events, href, token.type); // Build the link var link = doc.createElement(tagName); link.setAttribute('href', formattedHref); link.setAttribute('class', linkClass); if (target) { link.setAttribute('target', target); } // Build up additional attributes if (attributesHash) { for (var attr in attributesHash) { link.setAttribute(attr, attributesHash[attr]); } } if (events) { for (var event in events) { if (link.addEventListener) { link.addEventListener(event, events[event]); } else if (link.attachEvent) { link.attachEvent('on' + event, events[event]); } } } link.appendChild(doc.createTextNode(formatted)); result.push(link); } else if (token.type === 'nl' && opts.nl2br) { result.push(doc.createElement('br')); } else { result.push(doc.createTextNode(token.toString())); } } return result; } // Requires document.createElement function linkifyElementHelper(element, opts, doc) { // Can the element be linkified? if (!element || (typeof element === 'undefined' ? 'undefined' : _typeof(element)) !== 'object' || element.nodeType !== HTML_NODE) { throw new Error('Cannot linkify ' + element + ' - Invalid DOM Node type'); } var ignoreTags = opts.ignoreTags; // Is this element already a link? if (element.tagName === 'A' || options.contains(ignoreTags, element.tagName)) { // No need to linkify return element; } var childElement = element.firstChild; while (childElement) { switch (childElement.nodeType) { case HTML_NODE: linkifyElementHelper(childElement, opts, doc); break; case TXT_NODE: var str = childElement.nodeValue, tokens = tokenize(str), nodes = tokensToNodes(tokens, opts, doc); // Swap out the current child for the set of nodes replaceChildWithChildren(element, childElement, nodes); // so that the correct sibling is selected childElement = nodes[nodes.length - 1]; break; } childElement = childElement.nextSibling; } return element; } function linkifyElement(element, opts) { var doc = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; try { doc = doc || window && window.document || global && global.document; } catch (e) {/* do nothing for now */} if (!doc) { throw new Error('Cannot find document implementation. ' + 'If you are in a non-browser environment like Node.js, ' + 'pass the document implementation as the third argument to linkifyElement.'); } opts = options.normalize(opts); return linkifyElementHelper(element, opts, doc); } // Maintain reference to the recursive helper to cache option-normalization linkifyElement.helper = linkifyElementHelper; linkifyElement.normalize = options.normalize; return linkifyElement; }(linkify); window.linkifyElement = linkifyElement; })(window, linkify);
// Generated by CoffeeScript 1.9.3 (function() { module.exports = require('./2.x'); }).call(this);
/*! * Flickity PACKAGED v2.0.10 * Touch, responsive, flickable carousels * * Licensed GPLv3 for open source use * or Flickity Commercial License for commercial use * * http://flickity.metafizzy.co * Copyright 2017 Metafizzy */ /** * Bridget makes jQuery widgets * v2.0.1 * MIT license */ /* jshint browser: true, strict: true, undef: true, unused: true */ ( function( window, factory ) { // universal module definition /*jshint strict: false */ /* globals define, module, require */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'jquery-bridget/jquery-bridget',[ 'jquery' ], function( jQuery ) { return factory( window, jQuery ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( window, require('jquery') ); } else { // browser global window.jQueryBridget = factory( window, window.jQuery ); } }( window, function factory( window, jQuery ) { 'use strict'; // ----- utils ----- // var arraySlice = Array.prototype.slice; // helper function for logging errors // $.error breaks jQuery chaining var console = window.console; var logError = typeof console == 'undefined' ? function() {} : function( message ) { console.error( message ); }; // ----- jQueryBridget ----- // function jQueryBridget( namespace, PluginClass, $ ) { $ = $ || jQuery || window.jQuery; if ( !$ ) { return; } // add option method -> $().plugin('option', {...}) if ( !PluginClass.prototype.option ) { // option setter PluginClass.prototype.option = function( opts ) { // bail out if not an object if ( !$.isPlainObject( opts ) ){ return; } this.options = $.extend( true, this.options, opts ); }; } // make jQuery plugin $.fn[ namespace ] = function( arg0 /*, arg1 */ ) { if ( typeof arg0 == 'string' ) { // method call $().plugin( 'methodName', { options } ) // shift arguments by 1 var args = arraySlice.call( arguments, 1 ); return methodCall( this, arg0, args ); } // just $().plugin({ options }) plainCall( this, arg0 ); return this; }; // $().plugin('methodName') function methodCall( $elems, methodName, args ) { var returnValue; var pluginMethodStr = '$().' + namespace + '("' + methodName + '")'; $elems.each( function( i, elem ) { // get instance var instance = $.data( elem, namespace ); if ( !instance ) { logError( namespace + ' not initialized. Cannot call methods, i.e. ' + pluginMethodStr ); return; } var method = instance[ methodName ]; if ( !method || methodName.charAt(0) == '_' ) { logError( pluginMethodStr + ' is not a valid method' ); return; } // apply method, get return value var value = method.apply( instance, args ); // set return value if value is returned, use only first value returnValue = returnValue === undefined ? value : returnValue; }); return returnValue !== undefined ? returnValue : $elems; } function plainCall( $elems, options ) { $elems.each( function( i, elem ) { var instance = $.data( elem, namespace ); if ( instance ) { // set options & init instance.option( options ); instance._init(); } else { // initialize new instance instance = new PluginClass( elem, options ); $.data( elem, namespace, instance ); } }); } updateJQuery( $ ); } // ----- updateJQuery ----- // // set $.bridget for v1 backwards compatibility function updateJQuery( $ ) { if ( !$ || ( $ && $.bridget ) ) { return; } $.bridget = jQueryBridget; } updateJQuery( jQuery || window.jQuery ); // ----- ----- // return jQueryBridget; })); /** * EvEmitter v1.1.0 * Lil' event emitter * MIT License */ /* jshint unused: true, undef: true, strict: true */ ( function( global, factory ) { // universal module definition /* jshint strict: false */ /* globals define, module, window */ if ( typeof define == 'function' && define.amd ) { // AMD - RequireJS define( 'ev-emitter/ev-emitter',factory ); } else if ( typeof module == 'object' && module.exports ) { // CommonJS - Browserify, Webpack module.exports = factory(); } else { // Browser globals global.EvEmitter = factory(); } }( typeof window != 'undefined' ? window : this, function() { function EvEmitter() {} var proto = EvEmitter.prototype; proto.on = function( eventName, listener ) { if ( !eventName || !listener ) { return; } // set events hash var events = this._events = this._events || {}; // set listeners array var listeners = events[ eventName ] = events[ eventName ] || []; // only add once if ( listeners.indexOf( listener ) == -1 ) { listeners.push( listener ); } return this; }; proto.once = function( eventName, listener ) { if ( !eventName || !listener ) { return; } // add event this.on( eventName, listener ); // set once flag // set onceEvents hash var onceEvents = this._onceEvents = this._onceEvents || {}; // set onceListeners object var onceListeners = onceEvents[ eventName ] = onceEvents[ eventName ] || {}; // set flag onceListeners[ listener ] = true; return this; }; proto.off = function( eventName, listener ) { var listeners = this._events && this._events[ eventName ]; if ( !listeners || !listeners.length ) { return; } var index = listeners.indexOf( listener ); if ( index != -1 ) { listeners.splice( index, 1 ); } return this; }; proto.emitEvent = function( eventName, args ) { var listeners = this._events && this._events[ eventName ]; if ( !listeners || !listeners.length ) { return; } // copy over to avoid interference if .off() in listener listeners = listeners.slice(0); args = args || []; // once stuff var onceListeners = this._onceEvents && this._onceEvents[ eventName ]; for ( var i=0; i < listeners.length; i++ ) { var listener = listeners[i] var isOnce = onceListeners && onceListeners[ listener ]; if ( isOnce ) { // remove listener // remove before trigger to prevent recursion this.off( eventName, listener ); // unset once flag delete onceListeners[ listener ]; } // trigger listener listener.apply( this, args ); } return this; }; proto.allOff = function() { delete this._events; delete this._onceEvents; }; return EvEmitter; })); /*! * getSize v2.0.2 * measure size of elements * MIT license */ /*jshint browser: true, strict: true, undef: true, unused: true */ /*global define: false, module: false, console: false */ ( function( window, factory ) { 'use strict'; if ( typeof define == 'function' && define.amd ) { // AMD define( 'get-size/get-size',[],function() { return factory(); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory(); } else { // browser global window.getSize = factory(); } })( window, function factory() { 'use strict'; // -------------------------- helpers -------------------------- // // get a number from a string, not a percentage function getStyleSize( value ) { var num = parseFloat( value ); // not a percent like '100%', and a number var isValid = value.indexOf('%') == -1 && !isNaN( num ); return isValid && num; } function noop() {} var logError = typeof console == 'undefined' ? noop : function( message ) { console.error( message ); }; // -------------------------- measurements -------------------------- // var measurements = [ 'paddingLeft', 'paddingRight', 'paddingTop', 'paddingBottom', 'marginLeft', 'marginRight', 'marginTop', 'marginBottom', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth', 'borderBottomWidth' ]; var measurementsLength = measurements.length; function getZeroSize() { var size = { width: 0, height: 0, innerWidth: 0, innerHeight: 0, outerWidth: 0, outerHeight: 0 }; for ( var i=0; i < measurementsLength; i++ ) { var measurement = measurements[i]; size[ measurement ] = 0; } return size; } // -------------------------- getStyle -------------------------- // /** * getStyle, get style of element, check for Firefox bug * https://bugzilla.mozilla.org/show_bug.cgi?id=548397 */ function getStyle( elem ) { var style = getComputedStyle( elem ); if ( !style ) { logError( 'Style returned ' + style + '. Are you running this code in a hidden iframe on Firefox? ' + 'See http://bit.ly/getsizebug1' ); } return style; } // -------------------------- setup -------------------------- // var isSetup = false; var isBoxSizeOuter; /** * setup * check isBoxSizerOuter * do on first getSize() rather than on page load for Firefox bug */ function setup() { // setup once if ( isSetup ) { return; } isSetup = true; // -------------------------- box sizing -------------------------- // /** * WebKit measures the outer-width on style.width on border-box elems * IE & Firefox<29 measures the inner-width */ var div = document.createElement('div'); div.style.width = '200px'; div.style.padding = '1px 2px 3px 4px'; div.style.borderStyle = 'solid'; div.style.borderWidth = '1px 2px 3px 4px'; div.style.boxSizing = 'border-box'; var body = document.body || document.documentElement; body.appendChild( div ); var style = getStyle( div ); getSize.isBoxSizeOuter = isBoxSizeOuter = getStyleSize( style.width ) == 200; body.removeChild( div ); } // -------------------------- getSize -------------------------- // function getSize( elem ) { setup(); // use querySeletor if elem is string if ( typeof elem == 'string' ) { elem = document.querySelector( elem ); } // do not proceed on non-objects if ( !elem || typeof elem != 'object' || !elem.nodeType ) { return; } var style = getStyle( elem ); // if hidden, everything is 0 if ( style.display == 'none' ) { return getZeroSize(); } var size = {}; size.width = elem.offsetWidth; size.height = elem.offsetHeight; var isBorderBox = size.isBorderBox = style.boxSizing == 'border-box'; // get all measurements for ( var i=0; i < measurementsLength; i++ ) { var measurement = measurements[i]; var value = style[ measurement ]; var num = parseFloat( value ); // any 'auto', 'medium' value will be 0 size[ measurement ] = !isNaN( num ) ? num : 0; } var paddingWidth = size.paddingLeft + size.paddingRight; var paddingHeight = size.paddingTop + size.paddingBottom; var marginWidth = size.marginLeft + size.marginRight; var marginHeight = size.marginTop + size.marginBottom; var borderWidth = size.borderLeftWidth + size.borderRightWidth; var borderHeight = size.borderTopWidth + size.borderBottomWidth; var isBorderBoxSizeOuter = isBorderBox && isBoxSizeOuter; // overwrite width and height if we can get it from style var styleWidth = getStyleSize( style.width ); if ( styleWidth !== false ) { size.width = styleWidth + // add padding and border unless it's already including it ( isBorderBoxSizeOuter ? 0 : paddingWidth + borderWidth ); } var styleHeight = getStyleSize( style.height ); if ( styleHeight !== false ) { size.height = styleHeight + // add padding and border unless it's already including it ( isBorderBoxSizeOuter ? 0 : paddingHeight + borderHeight ); } size.innerWidth = size.width - ( paddingWidth + borderWidth ); size.innerHeight = size.height - ( paddingHeight + borderHeight ); size.outerWidth = size.width + marginWidth; size.outerHeight = size.height + marginHeight; return size; } return getSize; }); /** * matchesSelector v2.0.2 * matchesSelector( element, '.selector' ) * MIT license */ /*jshint browser: true, strict: true, undef: true, unused: true */ ( function( window, factory ) { /*global define: false, module: false */ 'use strict'; // universal module definition if ( typeof define == 'function' && define.amd ) { // AMD define( 'desandro-matches-selector/matches-selector',factory ); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory(); } else { // browser global window.matchesSelector = factory(); } }( window, function factory() { 'use strict'; var matchesMethod = ( function() { var ElemProto = window.Element.prototype; // check for the standard method name first if ( ElemProto.matches ) { return 'matches'; } // check un-prefixed if ( ElemProto.matchesSelector ) { return 'matchesSelector'; } // check vendor prefixes var prefixes = [ 'webkit', 'moz', 'ms', 'o' ]; for ( var i=0; i < prefixes.length; i++ ) { var prefix = prefixes[i]; var method = prefix + 'MatchesSelector'; if ( ElemProto[ method ] ) { return method; } } })(); return function matchesSelector( elem, selector ) { return elem[ matchesMethod ]( selector ); }; })); /** * Fizzy UI utils v2.0.5 * MIT license */ /*jshint browser: true, undef: true, unused: true, strict: true */ ( function( window, factory ) { // universal module definition /*jshint strict: false */ /*globals define, module, require */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'fizzy-ui-utils/utils',[ 'desandro-matches-selector/matches-selector' ], function( matchesSelector ) { return factory( window, matchesSelector ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( window, require('desandro-matches-selector') ); } else { // browser global window.fizzyUIUtils = factory( window, window.matchesSelector ); } }( window, function factory( window, matchesSelector ) { var utils = {}; // ----- extend ----- // // extends objects utils.extend = function( a, b ) { for ( var prop in b ) { a[ prop ] = b[ prop ]; } return a; }; // ----- modulo ----- // utils.modulo = function( num, div ) { return ( ( num % div ) + div ) % div; }; // ----- makeArray ----- // // turn element or nodeList into an array utils.makeArray = function( obj ) { var ary = []; if ( Array.isArray( obj ) ) { // use object if already an array ary = obj; } else if ( obj && typeof obj == 'object' && typeof obj.length == 'number' ) { // convert nodeList to array for ( var i=0; i < obj.length; i++ ) { ary.push( obj[i] ); } } else { // array of single index ary.push( obj ); } return ary; }; // ----- removeFrom ----- // utils.removeFrom = function( ary, obj ) { var index = ary.indexOf( obj ); if ( index != -1 ) { ary.splice( index, 1 ); } }; // ----- getParent ----- // utils.getParent = function( elem, selector ) { while ( elem.parentNode && elem != document.body ) { elem = elem.parentNode; if ( matchesSelector( elem, selector ) ) { return elem; } } }; // ----- getQueryElement ----- // // use element as selector string utils.getQueryElement = function( elem ) { if ( typeof elem == 'string' ) { return document.querySelector( elem ); } return elem; }; // ----- handleEvent ----- // // enable .ontype to trigger from .addEventListener( elem, 'type' ) utils.handleEvent = function( event ) { var method = 'on' + event.type; if ( this[ method ] ) { this[ method ]( event ); } }; // ----- filterFindElements ----- // utils.filterFindElements = function( elems, selector ) { // make array of elems elems = utils.makeArray( elems ); var ffElems = []; elems.forEach( function( elem ) { // check that elem is an actual element if ( !( elem instanceof HTMLElement ) ) { return; } // add elem if no selector if ( !selector ) { ffElems.push( elem ); return; } // filter & find items if we have a selector // filter if ( matchesSelector( elem, selector ) ) { ffElems.push( elem ); } // find children var childElems = elem.querySelectorAll( selector ); // concat childElems to filterFound array for ( var i=0; i < childElems.length; i++ ) { ffElems.push( childElems[i] ); } }); return ffElems; }; // ----- debounceMethod ----- // utils.debounceMethod = function( _class, methodName, threshold ) { // original method var method = _class.prototype[ methodName ]; var timeoutName = methodName + 'Timeout'; _class.prototype[ methodName ] = function() { var timeout = this[ timeoutName ]; if ( timeout ) { clearTimeout( timeout ); } var args = arguments; var _this = this; this[ timeoutName ] = setTimeout( function() { method.apply( _this, args ); delete _this[ timeoutName ]; }, threshold || 100 ); }; }; // ----- docReady ----- // utils.docReady = function( callback ) { var readyState = document.readyState; if ( readyState == 'complete' || readyState == 'interactive' ) { // do async to allow for other scripts to run. metafizzy/flickity#441 setTimeout( callback ); } else { document.addEventListener( 'DOMContentLoaded', callback ); } }; // ----- htmlInit ----- // // http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/ utils.toDashed = function( str ) { return str.replace( /(.)([A-Z])/g, function( match, $1, $2 ) { return $1 + '-' + $2; }).toLowerCase(); }; var console = window.console; /** * allow user to initialize classes via [data-namespace] or .js-namespace class * htmlInit( Widget, 'widgetName' ) * options are parsed from data-namespace-options */ utils.htmlInit = function( WidgetClass, namespace ) { utils.docReady( function() { var dashedNamespace = utils.toDashed( namespace ); var dataAttr = 'data-' + dashedNamespace; var dataAttrElems = document.querySelectorAll( '[' + dataAttr + ']' ); var jsDashElems = document.querySelectorAll( '.js-' + dashedNamespace ); var elems = utils.makeArray( dataAttrElems ) .concat( utils.makeArray( jsDashElems ) ); var dataOptionsAttr = dataAttr + '-options'; var jQuery = window.jQuery; elems.forEach( function( elem ) { var attr = elem.getAttribute( dataAttr ) || elem.getAttribute( dataOptionsAttr ); var options; try { options = attr && JSON.parse( attr ); } catch ( error ) { // log error, do not initialize if ( console ) { console.error( 'Error parsing ' + dataAttr + ' on ' + elem.className + ': ' + error ); } return; } // initialize var instance = new WidgetClass( elem, options ); // make available via $().data('namespace') if ( jQuery ) { jQuery.data( elem, namespace, instance ); } }); }); }; // ----- ----- // return utils; })); // Flickity.Cell ( function( window, factory ) { // universal module definition /* jshint strict: false */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'flickity/js/cell',[ 'get-size/get-size' ], function( getSize ) { return factory( window, getSize ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( window, require('get-size') ); } else { // browser global window.Flickity = window.Flickity || {}; window.Flickity.Cell = factory( window, window.getSize ); } }( window, function factory( window, getSize ) { function Cell( elem, parent ) { this.element = elem; this.parent = parent; this.create(); } var proto = Cell.prototype; proto.create = function() { this.element.style.position = 'absolute'; this.x = 0; this.shift = 0; }; proto.destroy = function() { // reset style this.element.style.position = ''; var side = this.parent.originSide; this.element.style[ side ] = ''; }; proto.getSize = function() { this.size = getSize( this.element ); }; proto.setPosition = function( x ) { this.x = x; this.updateTarget(); this.renderPosition( x ); }; // setDefaultTarget v1 method, backwards compatibility, remove in v3 proto.updateTarget = proto.setDefaultTarget = function() { var marginProperty = this.parent.originSide == 'left' ? 'marginLeft' : 'marginRight'; this.target = this.x + this.size[ marginProperty ] + this.size.width * this.parent.cellAlign; }; proto.renderPosition = function( x ) { // render position of cell with in slider var side = this.parent.originSide; this.element.style[ side ] = this.parent.getPositionValue( x ); }; /** * @param {Integer} factor - 0, 1, or -1 **/ proto.wrapShift = function( shift ) { this.shift = shift; this.renderPosition( this.x + this.parent.slideableWidth * shift ); }; proto.remove = function() { this.element.parentNode.removeChild( this.element ); }; return Cell; })); // slide ( function( window, factory ) { // universal module definition /* jshint strict: false */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'flickity/js/slide',factory ); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory(); } else { // browser global window.Flickity = window.Flickity || {}; window.Flickity.Slide = factory(); } }( window, function factory() { 'use strict'; function Slide( parent ) { this.parent = parent; this.isOriginLeft = parent.originSide == 'left'; this.cells = []; this.outerWidth = 0; this.height = 0; } var proto = Slide.prototype; proto.addCell = function( cell ) { this.cells.push( cell ); this.outerWidth += cell.size.outerWidth; this.height = Math.max( cell.size.outerHeight, this.height ); // first cell stuff if ( this.cells.length == 1 ) { this.x = cell.x; // x comes from first cell var beginMargin = this.isOriginLeft ? 'marginLeft' : 'marginRight'; this.firstMargin = cell.size[ beginMargin ]; } }; proto.updateTarget = function() { var endMargin = this.isOriginLeft ? 'marginRight' : 'marginLeft'; var lastCell = this.getLastCell(); var lastMargin = lastCell ? lastCell.size[ endMargin ] : 0; var slideWidth = this.outerWidth - ( this.firstMargin + lastMargin ); this.target = this.x + this.firstMargin + slideWidth * this.parent.cellAlign; }; proto.getLastCell = function() { return this.cells[ this.cells.length - 1 ]; }; proto.select = function() { this.changeSelectedClass('add'); }; proto.unselect = function() { this.changeSelectedClass('remove'); }; proto.changeSelectedClass = function( method ) { this.cells.forEach( function( cell ) { cell.element.classList[ method ]('is-selected'); }); }; proto.getCellElements = function() { return this.cells.map( function( cell ) { return cell.element; }); }; return Slide; })); // animate ( function( window, factory ) { // universal module definition /* jshint strict: false */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'flickity/js/animate',[ 'fizzy-ui-utils/utils' ], function( utils ) { return factory( window, utils ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( window, require('fizzy-ui-utils') ); } else { // browser global window.Flickity = window.Flickity || {}; window.Flickity.animatePrototype = factory( window, window.fizzyUIUtils ); } }( window, function factory( window, utils ) { // -------------------------- requestAnimationFrame -------------------------- // // get rAF, prefixed, if present var requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame; // fallback to setTimeout var lastTime = 0; if ( !requestAnimationFrame ) { requestAnimationFrame = function( callback ) { var currTime = new Date().getTime(); var timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) ); var id = setTimeout( callback, timeToCall ); lastTime = currTime + timeToCall; return id; }; } // -------------------------- animate -------------------------- // var proto = {}; proto.startAnimation = function() { if ( this.isAnimating ) { return; } this.isAnimating = true; this.restingFrames = 0; this.animate(); }; proto.animate = function() { this.applyDragForce(); this.applySelectedAttraction(); var previousX = this.x; this.integratePhysics(); this.positionSlider(); this.settle( previousX ); // animate next frame if ( this.isAnimating ) { var _this = this; requestAnimationFrame( function animateFrame() { _this.animate(); }); } }; var transformProperty = ( function () { var style = document.documentElement.style; if ( typeof style.transform == 'string' ) { return 'transform'; } return 'WebkitTransform'; })(); proto.positionSlider = function() { var x = this.x; // wrap position around if ( this.options.wrapAround && this.cells.length > 1 ) { x = utils.modulo( x, this.slideableWidth ); x = x - this.slideableWidth; this.shiftWrapCells( x ); } x = x + this.cursorPosition; // reverse if right-to-left and using transform x = this.options.rightToLeft && transformProperty ? -x : x; var value = this.getPositionValue( x ); // use 3D tranforms for hardware acceleration on iOS // but use 2D when settled, for better font-rendering this.slider.style[ transformProperty ] = this.isAnimating ? 'translate3d(' + value + ',0,0)' : 'translateX(' + value + ')'; // scroll event var firstSlide = this.slides[0]; if ( firstSlide ) { var positionX = -this.x - firstSlide.target; var progress = positionX / this.slidesWidth; this.dispatchEvent( 'scroll', null, [ progress, positionX ] ); } }; proto.positionSliderAtSelected = function() { if ( !this.cells.length ) { return; } this.x = -this.selectedSlide.target; this.positionSlider(); }; proto.getPositionValue = function( position ) { if ( this.options.percentPosition ) { // percent position, round to 2 digits, like 12.34% return ( Math.round( ( position / this.size.innerWidth ) * 10000 ) * 0.01 )+ '%'; } else { // pixel positioning return Math.round( position ) + 'px'; } }; proto.settle = function( previousX ) { // keep track of frames where x hasn't moved if ( !this.isPointerDown && Math.round( this.x * 100 ) == Math.round( previousX * 100 ) ) { this.restingFrames++; } // stop animating if resting for 3 or more frames if ( this.restingFrames > 2 ) { this.isAnimating = false; delete this.isFreeScrolling; // render position with translateX when settled this.positionSlider(); this.dispatchEvent('settle'); } }; proto.shiftWrapCells = function( x ) { // shift before cells var beforeGap = this.cursorPosition + x; this._shiftCells( this.beforeShiftCells, beforeGap, -1 ); // shift after cells var afterGap = this.size.innerWidth - ( x + this.slideableWidth + this.cursorPosition ); this._shiftCells( this.afterShiftCells, afterGap, 1 ); }; proto._shiftCells = function( cells, gap, shift ) { for ( var i=0; i < cells.length; i++ ) { var cell = cells[i]; var cellShift = gap > 0 ? shift : 0; cell.wrapShift( cellShift ); gap -= cell.size.outerWidth; } }; proto._unshiftCells = function( cells ) { if ( !cells || !cells.length ) { return; } for ( var i=0; i < cells.length; i++ ) { cells[i].wrapShift( 0 ); } }; // -------------------------- physics -------------------------- // proto.integratePhysics = function() { this.x += this.velocity; this.velocity *= this.getFrictionFactor(); }; proto.applyForce = function( force ) { this.velocity += force; }; proto.getFrictionFactor = function() { return 1 - this.options[ this.isFreeScrolling ? 'freeScrollFriction' : 'friction' ]; }; proto.getRestingPosition = function() { // my thanks to Steven Wittens, who simplified this math greatly return this.x + this.velocity / ( 1 - this.getFrictionFactor() ); }; proto.applyDragForce = function() { if ( !this.isPointerDown ) { return; } // change the position to drag position by applying force var dragVelocity = this.dragX - this.x; var dragForce = dragVelocity - this.velocity; this.applyForce( dragForce ); }; proto.applySelectedAttraction = function() { // do not attract if pointer down or no cells if ( this.isPointerDown || this.isFreeScrolling || !this.cells.length ) { return; } var distance = this.selectedSlide.target * -1 - this.x; var force = distance * this.options.selectedAttraction; this.applyForce( force ); }; return proto; })); // Flickity main ( function( window, factory ) { // universal module definition /* jshint strict: false */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'flickity/js/flickity',[ 'ev-emitter/ev-emitter', 'get-size/get-size', 'fizzy-ui-utils/utils', './cell', './slide', './animate' ], function( EvEmitter, getSize, utils, Cell, Slide, animatePrototype ) { return factory( window, EvEmitter, getSize, utils, Cell, Slide, animatePrototype ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( window, require('ev-emitter'), require('get-size'), require('fizzy-ui-utils'), require('./cell'), require('./slide'), require('./animate') ); } else { // browser global var _Flickity = window.Flickity; window.Flickity = factory( window, window.EvEmitter, window.getSize, window.fizzyUIUtils, _Flickity.Cell, _Flickity.Slide, _Flickity.animatePrototype ); } }( window, function factory( window, EvEmitter, getSize, utils, Cell, Slide, animatePrototype ) { // vars var jQuery = window.jQuery; var getComputedStyle = window.getComputedStyle; var console = window.console; function moveElements( elems, toElem ) { elems = utils.makeArray( elems ); while ( elems.length ) { toElem.appendChild( elems.shift() ); } } // -------------------------- Flickity -------------------------- // // globally unique identifiers var GUID = 0; // internal store of all Flickity intances var instances = {}; function Flickity( element, options ) { var queryElement = utils.getQueryElement( element ); if ( !queryElement ) { if ( console ) { console.error( 'Bad element for Flickity: ' + ( queryElement || element ) ); } return; } this.element = queryElement; // do not initialize twice on same element if ( this.element.flickityGUID ) { var instance = instances[ this.element.flickityGUID ]; instance.option( options ); return instance; } // add jQuery if ( jQuery ) { this.$element = jQuery( this.element ); } // options this.options = utils.extend( {}, this.constructor.defaults ); this.option( options ); // kick things off this._create(); } Flickity.defaults = { accessibility: true, // adaptiveHeight: false, cellAlign: 'center', // cellSelector: undefined, // contain: false, freeScrollFriction: 0.075, // friction when free-scrolling friction: 0.28, // friction when selecting namespaceJQueryEvents: true, // initialIndex: 0, percentPosition: true, resize: true, selectedAttraction: 0.025, setGallerySize: true // watchCSS: false, // wrapAround: false }; // hash of methods triggered on _create() Flickity.createMethods = []; var proto = Flickity.prototype; // inherit EventEmitter utils.extend( proto, EvEmitter.prototype ); proto._create = function() { // add id for Flickity.data var id = this.guid = ++GUID; this.element.flickityGUID = id; // expando instances[ id ] = this; // associate via id // initial properties this.selectedIndex = 0; // how many frames slider has been in same position this.restingFrames = 0; // initial physics properties this.x = 0; this.velocity = 0; this.originSide = this.options.rightToLeft ? 'right' : 'left'; // create viewport & slider this.viewport = document.createElement('div'); this.viewport.className = 'flickity-viewport'; this._createSlider(); if ( this.options.resize || this.options.watchCSS ) { window.addEventListener( 'resize', this ); } Flickity.createMethods.forEach( function( method ) { this[ method ](); }, this ); if ( this.options.watchCSS ) { this.watchCSS(); } else { this.activate(); } }; /** * set options * @param {Object} opts */ proto.option = function( opts ) { utils.extend( this.options, opts ); }; proto.activate = function() { if ( this.isActive ) { return; } this.isActive = true; this.element.classList.add('flickity-enabled'); if ( this.options.rightToLeft ) { this.element.classList.add('flickity-rtl'); } this.getSize(); // move initial cell elements so they can be loaded as cells var cellElems = this._filterFindCellElements( this.element.children ); moveElements( cellElems, this.slider ); this.viewport.appendChild( this.slider ); this.element.appendChild( this.viewport ); // get cells from children this.reloadCells(); if ( this.options.accessibility ) { // allow element to focusable this.element.tabIndex = 0; // listen for key presses this.element.addEventListener( 'keydown', this ); } this.emitEvent('activate'); var index; var initialIndex = this.options.initialIndex; if ( this.isInitActivated ) { index = this.selectedIndex; } else if ( initialIndex !== undefined ) { index = this.cells[ initialIndex ] ? initialIndex : 0; } else { index = 0; } // select instantly this.select( index, false, true ); // flag for initial activation, for using initialIndex this.isInitActivated = true; }; // slider positions the cells proto._createSlider = function() { // slider element does all the positioning var slider = document.createElement('div'); slider.className = 'flickity-slider'; slider.style[ this.originSide ] = 0; this.slider = slider; }; proto._filterFindCellElements = function( elems ) { return utils.filterFindElements( elems, this.options.cellSelector ); }; // goes through all children proto.reloadCells = function() { // collection of item elements this.cells = this._makeCells( this.slider.children ); this.positionCells(); this._getWrapShiftCells(); this.setGallerySize(); }; /** * turn elements into Flickity.Cells * @param {Array or NodeList or HTMLElement} elems * @returns {Array} items - collection of new Flickity Cells */ proto._makeCells = function( elems ) { var cellElems = this._filterFindCellElements( elems ); // create new Flickity for collection var cells = cellElems.map( function( cellElem ) { return new Cell( cellElem, this ); }, this ); return cells; }; proto.getLastCell = function() { return this.cells[ this.cells.length - 1 ]; }; proto.getLastSlide = function() { return this.slides[ this.slides.length - 1 ]; }; // positions all cells proto.positionCells = function() { // size all cells this._sizeCells( this.cells ); // position all cells this._positionCells( 0 ); }; /** * position certain cells * @param {Integer} index - which cell to start with */ proto._positionCells = function( index ) { index = index || 0; // also measure maxCellHeight // start 0 if positioning all cells this.maxCellHeight = index ? this.maxCellHeight || 0 : 0; var cellX = 0; // get cellX if ( index > 0 ) { var startCell = this.cells[ index - 1 ]; cellX = startCell.x + startCell.size.outerWidth; } var len = this.cells.length; for ( var i=index; i < len; i++ ) { var cell = this.cells[i]; cell.setPosition( cellX ); cellX += cell.size.outerWidth; this.maxCellHeight = Math.max( cell.size.outerHeight, this.maxCellHeight ); } // keep track of cellX for wrap-around this.slideableWidth = cellX; // slides this.updateSlides(); // contain slides target this._containSlides(); // update slidesWidth this.slidesWidth = len ? this.getLastSlide().target - this.slides[0].target : 0; }; /** * cell.getSize() on multiple cells * @param {Array} cells */ proto._sizeCells = function( cells ) { cells.forEach( function( cell ) { cell.getSize(); }); }; // -------------------------- -------------------------- // proto.updateSlides = function() { this.slides = []; if ( !this.cells.length ) { return; } var slide = new Slide( this ); this.slides.push( slide ); var isOriginLeft = this.originSide == 'left'; var nextMargin = isOriginLeft ? 'marginRight' : 'marginLeft'; var canCellFit = this._getCanCellFit(); this.cells.forEach( function( cell, i ) { // just add cell if first cell in slide if ( !slide.cells.length ) { slide.addCell( cell ); return; } var slideWidth = ( slide.outerWidth - slide.firstMargin ) + ( cell.size.outerWidth - cell.size[ nextMargin ] ); if ( canCellFit.call( this, i, slideWidth ) ) { slide.addCell( cell ); } else { // doesn't fit, new slide slide.updateTarget(); slide = new Slide( this ); this.slides.push( slide ); slide.addCell( cell ); } }, this ); // last slide slide.updateTarget(); // update .selectedSlide this.updateSelectedSlide(); }; proto._getCanCellFit = function() { var groupCells = this.options.groupCells; if ( !groupCells ) { return function() { return false; }; } else if ( typeof groupCells == 'number' ) { // group by number. 3 -> [0,1,2], [3,4,5], ... var number = parseInt( groupCells, 10 ); return function( i ) { return ( i % number ) !== 0; }; } // default, group by width of slide // parse '75% var percentMatch = typeof groupCells == 'string' && groupCells.match(/^(\d+)%$/); var percent = percentMatch ? parseInt( percentMatch[1], 10 ) / 100 : 1; return function( i, slideWidth ) { return slideWidth <= ( this.size.innerWidth + 1 ) * percent; }; }; // alias _init for jQuery plugin .flickity() proto._init = proto.reposition = function() { this.positionCells(); this.positionSliderAtSelected(); }; proto.getSize = function() { this.size = getSize( this.element ); this.setCellAlign(); this.cursorPosition = this.size.innerWidth * this.cellAlign; }; var cellAlignShorthands = { // cell align, then based on origin side center: { left: 0.5, right: 0.5 }, left: { left: 0, right: 1 }, right: { right: 0, left: 1 } }; proto.setCellAlign = function() { var shorthand = cellAlignShorthands[ this.options.cellAlign ]; this.cellAlign = shorthand ? shorthand[ this.originSide ] : this.options.cellAlign; }; proto.setGallerySize = function() { if ( this.options.setGallerySize ) { var height = this.options.adaptiveHeight && this.selectedSlide ? this.selectedSlide.height : this.maxCellHeight; this.viewport.style.height = height + 'px'; } }; proto._getWrapShiftCells = function() { // only for wrap-around if ( !this.options.wrapAround ) { return; } // unshift previous cells this._unshiftCells( this.beforeShiftCells ); this._unshiftCells( this.afterShiftCells ); // get before cells // initial gap var gapX = this.cursorPosition; var cellIndex = this.cells.length - 1; this.beforeShiftCells = this._getGapCells( gapX, cellIndex, -1 ); // get after cells // ending gap between last cell and end of gallery viewport gapX = this.size.innerWidth - this.cursorPosition; // start cloning at first cell, working forwards this.afterShiftCells = this._getGapCells( gapX, 0, 1 ); }; proto._getGapCells = function( gapX, cellIndex, increment ) { // keep adding cells until the cover the initial gap var cells = []; while ( gapX > 0 ) { var cell = this.cells[ cellIndex ]; if ( !cell ) { break; } cells.push( cell ); cellIndex += increment; gapX -= cell.size.outerWidth; } return cells; }; // ----- contain ----- // // contain cell targets so no excess sliding proto._containSlides = function() { if ( !this.options.contain || this.options.wrapAround || !this.cells.length ) { return; } var isRightToLeft = this.options.rightToLeft; var beginMargin = isRightToLeft ? 'marginRight' : 'marginLeft'; var endMargin = isRightToLeft ? 'marginLeft' : 'marginRight'; var contentWidth = this.slideableWidth - this.getLastCell().size[ endMargin ]; // content is less than gallery size var isContentSmaller = contentWidth < this.size.innerWidth; // bounds var beginBound = this.cursorPosition + this.cells[0].size[ beginMargin ]; var endBound = contentWidth - this.size.innerWidth * ( 1 - this.cellAlign ); // contain each cell target this.slides.forEach( function( slide ) { if ( isContentSmaller ) { // all cells fit inside gallery slide.target = contentWidth * this.cellAlign; } else { // contain to bounds slide.target = Math.max( slide.target, beginBound ); slide.target = Math.min( slide.target, endBound ); } }, this ); }; // ----- ----- // /** * emits events via eventEmitter and jQuery events * @param {String} type - name of event * @param {Event} event - original event * @param {Array} args - extra arguments */ proto.dispatchEvent = function( type, event, args ) { var emitArgs = event ? [ event ].concat( args ) : args; this.emitEvent( type, emitArgs ); if ( jQuery && this.$element ) { // default trigger with type if no event type += this.options.namespaceJQueryEvents ? '.flickity' : ''; var $event = type; if ( event ) { // create jQuery event var jQEvent = jQuery.Event( event ); jQEvent.type = type; $event = jQEvent; } this.$element.trigger( $event, args ); } }; // -------------------------- select -------------------------- // /** * @param {Integer} index - index of the slide * @param {Boolean} isWrap - will wrap-around to last/first if at the end * @param {Boolean} isInstant - will immediately set position at selected cell */ proto.select = function( index, isWrap, isInstant ) { if ( !this.isActive ) { return; } index = parseInt( index, 10 ); this._wrapSelect( index ); if ( this.options.wrapAround || isWrap ) { index = utils.modulo( index, this.slides.length ); } // bail if invalid index if ( !this.slides[ index ] ) { return; } this.selectedIndex = index; this.updateSelectedSlide(); if ( isInstant ) { this.positionSliderAtSelected(); } else { this.startAnimation(); } if ( this.options.adaptiveHeight ) { this.setGallerySize(); } this.dispatchEvent('select'); // old v1 event name, remove in v3 this.dispatchEvent('cellSelect'); }; // wraps position for wrapAround, to move to closest slide. #113 proto._wrapSelect = function( index ) { var len = this.slides.length; var isWrapping = this.options.wrapAround && len > 1; if ( !isWrapping ) { return index; } var wrapIndex = utils.modulo( index, len ); // go to shortest var delta = Math.abs( wrapIndex - this.selectedIndex ); var backWrapDelta = Math.abs( ( wrapIndex + len ) - this.selectedIndex ); var forewardWrapDelta = Math.abs( ( wrapIndex - len ) - this.selectedIndex ); if ( !this.isDragSelect && backWrapDelta < delta ) { index += len; } else if ( !this.isDragSelect && forewardWrapDelta < delta ) { index -= len; } // wrap position so slider is within normal area if ( index < 0 ) { this.x -= this.slideableWidth; } else if ( index >= len ) { this.x += this.slideableWidth; } }; proto.previous = function( isWrap, isInstant ) { this.select( this.selectedIndex - 1, isWrap, isInstant ); }; proto.next = function( isWrap, isInstant ) { this.select( this.selectedIndex + 1, isWrap, isInstant ); }; proto.updateSelectedSlide = function() { var slide = this.slides[ this.selectedIndex ]; // selectedIndex could be outside of slides, if triggered before resize() if ( !slide ) { return; } // unselect previous selected slide this.unselectSelectedSlide(); // update new selected slide this.selectedSlide = slide; slide.select(); this.selectedCells = slide.cells; this.selectedElements = slide.getCellElements(); // HACK: selectedCell & selectedElement is first cell in slide, backwards compatibility // Remove in v3? this.selectedCell = slide.cells[0]; this.selectedElement = this.selectedElements[0]; }; proto.unselectSelectedSlide = function() { if ( this.selectedSlide ) { this.selectedSlide.unselect(); } }; /** * select slide from number or cell element * @param {Element or Number} elem */ proto.selectCell = function( value, isWrap, isInstant ) { // get cell var cell; if ( typeof value == 'number' ) { cell = this.cells[ value ]; } else { // use string as selector if ( typeof value == 'string' ) { value = this.element.querySelector( value ); } // get cell from element cell = this.getCell( value ); } // select slide that has cell for ( var i=0; cell && i < this.slides.length; i++ ) { var slide = this.slides[i]; var index = slide.cells.indexOf( cell ); if ( index != -1 ) { this.select( i, isWrap, isInstant ); return; } } }; // -------------------------- get cells -------------------------- // /** * get Flickity.Cell, given an Element * @param {Element} elem * @returns {Flickity.Cell} item */ proto.getCell = function( elem ) { // loop through cells to get the one that matches for ( var i=0; i < this.cells.length; i++ ) { var cell = this.cells[i]; if ( cell.element == elem ) { return cell; } } }; /** * get collection of Flickity.Cells, given Elements * @param {Element, Array, NodeList} elems * @returns {Array} cells - Flickity.Cells */ proto.getCells = function( elems ) { elems = utils.makeArray( elems ); var cells = []; elems.forEach( function( elem ) { var cell = this.getCell( elem ); if ( cell ) { cells.push( cell ); } }, this ); return cells; }; /** * get cell elements * @returns {Array} cellElems */ proto.getCellElements = function() { return this.cells.map( function( cell ) { return cell.element; }); }; /** * get parent cell from an element * @param {Element} elem * @returns {Flickit.Cell} cell */ proto.getParentCell = function( elem ) { // first check if elem is cell var cell = this.getCell( elem ); if ( cell ) { return cell; } // try to get parent cell elem elem = utils.getParent( elem, '.flickity-slider > *' ); return this.getCell( elem ); }; /** * get cells adjacent to a slide * @param {Integer} adjCount - number of adjacent slides * @param {Integer} index - index of slide to start * @returns {Array} cells - array of Flickity.Cells */ proto.getAdjacentCellElements = function( adjCount, index ) { if ( !adjCount ) { return this.selectedSlide.getCellElements(); } index = index === undefined ? this.selectedIndex : index; var len = this.slides.length; if ( 1 + ( adjCount * 2 ) >= len ) { return this.getCellElements(); } var cellElems = []; for ( var i = index - adjCount; i <= index + adjCount ; i++ ) { var slideIndex = this.options.wrapAround ? utils.modulo( i, len ) : i; var slide = this.slides[ slideIndex ]; if ( slide ) { cellElems = cellElems.concat( slide.getCellElements() ); } } return cellElems; }; // -------------------------- events -------------------------- // proto.uiChange = function() { this.emitEvent('uiChange'); }; proto.childUIPointerDown = function( event ) { this.emitEvent( 'childUIPointerDown', [ event ] ); }; // ----- resize ----- // proto.onresize = function() { this.watchCSS(); this.resize(); }; utils.debounceMethod( Flickity, 'onresize', 150 ); proto.resize = function() { if ( !this.isActive ) { return; } this.getSize(); // wrap values if ( this.options.wrapAround ) { this.x = utils.modulo( this.x, this.slideableWidth ); } this.positionCells(); this._getWrapShiftCells(); this.setGallerySize(); this.emitEvent('resize'); // update selected index for group slides, instant // TODO: position can be lost between groups of various numbers var selectedElement = this.selectedElements && this.selectedElements[0]; this.selectCell( selectedElement, false, true ); }; // watches the :after property, activates/deactivates proto.watchCSS = function() { var watchOption = this.options.watchCSS; if ( !watchOption ) { return; } var afterContent = getComputedStyle( this.element, ':after' ).content; // activate if :after { content: 'flickity' } if ( afterContent.indexOf('flickity') != -1 ) { this.activate(); } else { this.deactivate(); } }; // ----- keydown ----- // // go previous/next if left/right keys pressed proto.onkeydown = function( event ) { // only work if element is in focus if ( !this.options.accessibility || ( document.activeElement && document.activeElement != this.element ) ) { return; } if ( event.keyCode == 37 ) { // go left var leftMethod = this.options.rightToLeft ? 'next' : 'previous'; this.uiChange(); this[ leftMethod ](); } else if ( event.keyCode == 39 ) { // go right var rightMethod = this.options.rightToLeft ? 'previous' : 'next'; this.uiChange(); this[ rightMethod ](); } }; // -------------------------- destroy -------------------------- // // deactivate all Flickity functionality, but keep stuff available proto.deactivate = function() { if ( !this.isActive ) { return; } this.element.classList.remove('flickity-enabled'); this.element.classList.remove('flickity-rtl'); // destroy cells this.cells.forEach( function( cell ) { cell.destroy(); }); this.unselectSelectedSlide(); this.element.removeChild( this.viewport ); // move child elements back into element moveElements( this.slider.children, this.element ); if ( this.options.accessibility ) { this.element.removeAttribute('tabIndex'); this.element.removeEventListener( 'keydown', this ); } // set flags this.isActive = false; this.emitEvent('deactivate'); }; proto.destroy = function() { this.deactivate(); window.removeEventListener( 'resize', this ); this.emitEvent('destroy'); if ( jQuery && this.$element ) { jQuery.removeData( this.element, 'flickity' ); } delete this.element.flickityGUID; delete instances[ this.guid ]; }; // -------------------------- prototype -------------------------- // utils.extend( proto, animatePrototype ); // -------------------------- extras -------------------------- // /** * get Flickity instance from element * @param {Element} elem * @returns {Flickity} */ Flickity.data = function( elem ) { elem = utils.getQueryElement( elem ); var id = elem && elem.flickityGUID; return id && instances[ id ]; }; utils.htmlInit( Flickity, 'flickity' ); if ( jQuery && jQuery.bridget ) { jQuery.bridget( 'flickity', Flickity ); } // set internal jQuery, for Webpack + jQuery v3, #478 Flickity.setJQuery = function( jq ) { jQuery = jq; }; Flickity.Cell = Cell; return Flickity; })); /*! * Unipointer v2.2.0 * base class for doing one thing with pointer event * MIT license */ /*jshint browser: true, undef: true, unused: true, strict: true */ ( function( window, factory ) { // universal module definition /* jshint strict: false */ /*global define, module, require */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'unipointer/unipointer',[ 'ev-emitter/ev-emitter' ], function( EvEmitter ) { return factory( window, EvEmitter ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( window, require('ev-emitter') ); } else { // browser global window.Unipointer = factory( window, window.EvEmitter ); } }( window, function factory( window, EvEmitter ) { function noop() {} function Unipointer() {} // inherit EvEmitter var proto = Unipointer.prototype = Object.create( EvEmitter.prototype ); proto.bindStartEvent = function( elem ) { this._bindStartEvent( elem, true ); }; proto.unbindStartEvent = function( elem ) { this._bindStartEvent( elem, false ); }; /** * works as unbinder, as you can ._bindStart( false ) to unbind * @param {Boolean} isBind - will unbind if falsey */ proto._bindStartEvent = function( elem, isBind ) { // munge isBind, default to true isBind = isBind === undefined ? true : !!isBind; var bindMethod = isBind ? 'addEventListener' : 'removeEventListener'; if ( window.PointerEvent ) { // Pointer Events. Chrome 55, IE11, Edge 14 elem[ bindMethod ]( 'pointerdown', this ); } else { // listen for both, for devices like Chrome Pixel elem[ bindMethod ]( 'mousedown', this ); elem[ bindMethod ]( 'touchstart', this ); } }; // trigger handler methods for events proto.handleEvent = function( event ) { var method = 'on' + event.type; if ( this[ method ] ) { this[ method ]( event ); } }; // returns the touch that we're keeping track of proto.getTouch = function( touches ) { for ( var i=0; i < touches.length; i++ ) { var touch = touches[i]; if ( touch.identifier == this.pointerIdentifier ) { return touch; } } }; // ----- start event ----- // proto.onmousedown = function( event ) { // dismiss clicks from right or middle buttons var button = event.button; if ( button && ( button !== 0 && button !== 1 ) ) { return; } this._pointerDown( event, event ); }; proto.ontouchstart = function( event ) { this._pointerDown( event, event.changedTouches[0] ); }; proto.onpointerdown = function( event ) { this._pointerDown( event, event ); }; /** * pointer start * @param {Event} event * @param {Event or Touch} pointer */ proto._pointerDown = function( event, pointer ) { // dismiss other pointers if ( this.isPointerDown ) { return; } this.isPointerDown = true; // save pointer identifier to match up touch events this.pointerIdentifier = pointer.pointerId !== undefined ? // pointerId for pointer events, touch.indentifier for touch events pointer.pointerId : pointer.identifier; this.pointerDown( event, pointer ); }; proto.pointerDown = function( event, pointer ) { this._bindPostStartEvents( event ); this.emitEvent( 'pointerDown', [ event, pointer ] ); }; // hash of events to be bound after start event var postStartEvents = { mousedown: [ 'mousemove', 'mouseup' ], touchstart: [ 'touchmove', 'touchend', 'touchcancel' ], pointerdown: [ 'pointermove', 'pointerup', 'pointercancel' ], }; proto._bindPostStartEvents = function( event ) { if ( !event ) { return; } // get proper events to match start event var events = postStartEvents[ event.type ]; // bind events to node events.forEach( function( eventName ) { window.addEventListener( eventName, this ); }, this ); // save these arguments this._boundPointerEvents = events; }; proto._unbindPostStartEvents = function() { // check for _boundEvents, in case dragEnd triggered twice (old IE8 bug) if ( !this._boundPointerEvents ) { return; } this._boundPointerEvents.forEach( function( eventName ) { window.removeEventListener( eventName, this ); }, this ); delete this._boundPointerEvents; }; // ----- move event ----- // proto.onmousemove = function( event ) { this._pointerMove( event, event ); }; proto.onpointermove = function( event ) { if ( event.pointerId == this.pointerIdentifier ) { this._pointerMove( event, event ); } }; proto.ontouchmove = function( event ) { var touch = this.getTouch( event.changedTouches ); if ( touch ) { this._pointerMove( event, touch ); } }; /** * pointer move * @param {Event} event * @param {Event or Touch} pointer * @private */ proto._pointerMove = function( event, pointer ) { this.pointerMove( event, pointer ); }; // public proto.pointerMove = function( event, pointer ) { this.emitEvent( 'pointerMove', [ event, pointer ] ); }; // ----- end event ----- // proto.onmouseup = function( event ) { this._pointerUp( event, event ); }; proto.onpointerup = function( event ) { if ( event.pointerId == this.pointerIdentifier ) { this._pointerUp( event, event ); } }; proto.ontouchend = function( event ) { var touch = this.getTouch( event.changedTouches ); if ( touch ) { this._pointerUp( event, touch ); } }; /** * pointer up * @param {Event} event * @param {Event or Touch} pointer * @private */ proto._pointerUp = function( event, pointer ) { this._pointerDone(); this.pointerUp( event, pointer ); }; // public proto.pointerUp = function( event, pointer ) { this.emitEvent( 'pointerUp', [ event, pointer ] ); }; // ----- pointer done ----- // // triggered on pointer up & pointer cancel proto._pointerDone = function() { // reset properties this.isPointerDown = false; delete this.pointerIdentifier; // remove events this._unbindPostStartEvents(); this.pointerDone(); }; proto.pointerDone = noop; // ----- pointer cancel ----- // proto.onpointercancel = function( event ) { if ( event.pointerId == this.pointerIdentifier ) { this._pointerCancel( event, event ); } }; proto.ontouchcancel = function( event ) { var touch = this.getTouch( event.changedTouches ); if ( touch ) { this._pointerCancel( event, touch ); } }; /** * pointer cancel * @param {Event} event * @param {Event or Touch} pointer * @private */ proto._pointerCancel = function( event, pointer ) { this._pointerDone(); this.pointerCancel( event, pointer ); }; // public proto.pointerCancel = function( event, pointer ) { this.emitEvent( 'pointerCancel', [ event, pointer ] ); }; // ----- ----- // // utility function for getting x/y coords from event Unipointer.getPointerPoint = function( pointer ) { return { x: pointer.pageX, y: pointer.pageY }; }; // ----- ----- // return Unipointer; })); /*! * Unidragger v2.2.3 * Draggable base class * MIT license */ /*jshint browser: true, unused: true, undef: true, strict: true */ ( function( window, factory ) { // universal module definition /*jshint strict: false */ /*globals define, module, require */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'unidragger/unidragger',[ 'unipointer/unipointer' ], function( Unipointer ) { return factory( window, Unipointer ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( window, require('unipointer') ); } else { // browser global window.Unidragger = factory( window, window.Unipointer ); } }( window, function factory( window, Unipointer ) { // -------------------------- Unidragger -------------------------- // function Unidragger() {} // inherit Unipointer & EvEmitter var proto = Unidragger.prototype = Object.create( Unipointer.prototype ); // ----- bind start ----- // proto.bindHandles = function() { this._bindHandles( true ); }; proto.unbindHandles = function() { this._bindHandles( false ); }; /** * works as unbinder, as you can .bindHandles( false ) to unbind * @param {Boolean} isBind - will unbind if falsey */ proto._bindHandles = function( isBind ) { // munge isBind, default to true isBind = isBind === undefined ? true : !!isBind; // bind each handle var bindMethod = isBind ? 'addEventListener' : 'removeEventListener'; for ( var i=0; i < this.handles.length; i++ ) { var handle = this.handles[i]; this._bindStartEvent( handle, isBind ); handle[ bindMethod ]( 'click', this ); // touch-action: none to override browser touch gestures // metafizzy/flickity#540 if ( window.PointerEvent ) { handle.style.touchAction = isBind ? this._touchActionValue : ''; } } }; // prototype so it can be overwriteable by Flickity proto._touchActionValue = 'none'; // ----- start event ----- // /** * pointer start * @param {Event} event * @param {Event or Touch} pointer */ proto.pointerDown = function( event, pointer ) { // dismiss range sliders if ( event.target.nodeName == 'INPUT' && event.target.type == 'range' ) { // reset pointerDown logic this.isPointerDown = false; delete this.pointerIdentifier; return; } this._dragPointerDown( event, pointer ); // kludge to blur focused inputs in dragger var focused = document.activeElement; if ( focused && focused.blur ) { focused.blur(); } // bind move and end events this._bindPostStartEvents( event ); this.emitEvent( 'pointerDown', [ event, pointer ] ); }; // base pointer down logic proto._dragPointerDown = function( event, pointer ) { // track to see when dragging starts this.pointerDownPoint = Unipointer.getPointerPoint( pointer ); var canPreventDefault = this.canPreventDefaultOnPointerDown( event, pointer ); if ( canPreventDefault ) { event.preventDefault(); } }; // overwriteable method so Flickity can prevent for scrolling proto.canPreventDefaultOnPointerDown = function( event ) { // prevent default, unless touchstart or <select> return event.target.nodeName != 'SELECT'; }; // ----- move event ----- // /** * drag move * @param {Event} event * @param {Event or Touch} pointer */ proto.pointerMove = function( event, pointer ) { var moveVector = this._dragPointerMove( event, pointer ); this.emitEvent( 'pointerMove', [ event, pointer, moveVector ] ); this._dragMove( event, pointer, moveVector ); }; // base pointer move logic proto._dragPointerMove = function( event, pointer ) { var movePoint = Unipointer.getPointerPoint( pointer ); var moveVector = { x: movePoint.x - this.pointerDownPoint.x, y: movePoint.y - this.pointerDownPoint.y }; // start drag if pointer has moved far enough to start drag if ( !this.isDragging && this.hasDragStarted( moveVector ) ) { this._dragStart( event, pointer ); } return moveVector; }; // condition if pointer has moved far enough to start drag proto.hasDragStarted = function( moveVector ) { return Math.abs( moveVector.x ) > 3 || Math.abs( moveVector.y ) > 3; }; // ----- end event ----- // /** * pointer up * @param {Event} event * @param {Event or Touch} pointer */ proto.pointerUp = function( event, pointer ) { this.emitEvent( 'pointerUp', [ event, pointer ] ); this._dragPointerUp( event, pointer ); }; proto._dragPointerUp = function( event, pointer ) { if ( this.isDragging ) { this._dragEnd( event, pointer ); } else { // pointer didn't move enough for drag to start this._staticClick( event, pointer ); } }; // -------------------------- drag -------------------------- // // dragStart proto._dragStart = function( event, pointer ) { this.isDragging = true; this.dragStartPoint = Unipointer.getPointerPoint( pointer ); // prevent clicks this.isPreventingClicks = true; this.dragStart( event, pointer ); }; proto.dragStart = function( event, pointer ) { this.emitEvent( 'dragStart', [ event, pointer ] ); }; // dragMove proto._dragMove = function( event, pointer, moveVector ) { // do not drag if not dragging yet if ( !this.isDragging ) { return; } this.dragMove( event, pointer, moveVector ); }; proto.dragMove = function( event, pointer, moveVector ) { event.preventDefault(); this.emitEvent( 'dragMove', [ event, pointer, moveVector ] ); }; // dragEnd proto._dragEnd = function( event, pointer ) { // set flags this.isDragging = false; // re-enable clicking async setTimeout( function() { delete this.isPreventingClicks; }.bind( this ) ); this.dragEnd( event, pointer ); }; proto.dragEnd = function( event, pointer ) { this.emitEvent( 'dragEnd', [ event, pointer ] ); }; // ----- onclick ----- // // handle all clicks and prevent clicks when dragging proto.onclick = function( event ) { if ( this.isPreventingClicks ) { event.preventDefault(); } }; // ----- staticClick ----- // // triggered after pointer down & up with no/tiny movement proto._staticClick = function( event, pointer ) { // ignore emulated mouse up clicks if ( this.isIgnoringMouseUp && event.type == 'mouseup' ) { return; } // allow click in <input>s and <textarea>s var nodeName = event.target.nodeName; if ( nodeName == 'INPUT' || nodeName == 'TEXTAREA' ) { event.target.focus(); } this.staticClick( event, pointer ); // set flag for emulated clicks 300ms after touchend if ( event.type != 'mouseup' ) { this.isIgnoringMouseUp = true; // reset flag after 300ms setTimeout( function() { delete this.isIgnoringMouseUp; }.bind( this ), 400 ); } }; proto.staticClick = function( event, pointer ) { this.emitEvent( 'staticClick', [ event, pointer ] ); }; // ----- utils ----- // Unidragger.getPointerPoint = Unipointer.getPointerPoint; // ----- ----- // return Unidragger; })); // drag ( function( window, factory ) { // universal module definition /* jshint strict: false */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'flickity/js/drag',[ './flickity', 'unidragger/unidragger', 'fizzy-ui-utils/utils' ], function( Flickity, Unidragger, utils ) { return factory( window, Flickity, Unidragger, utils ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( window, require('./flickity'), require('unidragger'), require('fizzy-ui-utils') ); } else { // browser global window.Flickity = factory( window, window.Flickity, window.Unidragger, window.fizzyUIUtils ); } }( window, function factory( window, Flickity, Unidragger, utils ) { // ----- defaults ----- // utils.extend( Flickity.defaults, { draggable: true, dragThreshold: 3, }); // ----- create ----- // Flickity.createMethods.push('_createDrag'); // -------------------------- drag prototype -------------------------- // var proto = Flickity.prototype; utils.extend( proto, Unidragger.prototype ); proto._touchActionValue = 'pan-y'; // -------------------------- -------------------------- // var isTouch = 'createTouch' in document; var isTouchmoveScrollCanceled = false; proto._createDrag = function() { this.on( 'activate', this.bindDrag ); this.on( 'uiChange', this._uiChangeDrag ); this.on( 'childUIPointerDown', this._childUIPointerDownDrag ); this.on( 'deactivate', this.unbindDrag ); // HACK - add seemingly innocuous handler to fix iOS 10 scroll behavior // #457, RubaXa/Sortable#973 if ( isTouch && !isTouchmoveScrollCanceled ) { window.addEventListener( 'touchmove', function() {}); isTouchmoveScrollCanceled = true; } }; proto.bindDrag = function() { if ( !this.options.draggable || this.isDragBound ) { return; } this.element.classList.add('is-draggable'); this.handles = [ this.viewport ]; this.bindHandles(); this.isDragBound = true; }; proto.unbindDrag = function() { if ( !this.isDragBound ) { return; } this.element.classList.remove('is-draggable'); this.unbindHandles(); delete this.isDragBound; }; proto._uiChangeDrag = function() { delete this.isFreeScrolling; }; proto._childUIPointerDownDrag = function( event ) { event.preventDefault(); this.pointerDownFocus( event ); }; // -------------------------- pointer events -------------------------- // // nodes that have text fields var cursorNodes = { TEXTAREA: true, INPUT: true, OPTION: true, }; // input types that do not have text fields var clickTypes = { radio: true, checkbox: true, button: true, submit: true, image: true, file: true, }; proto.pointerDown = function( event, pointer ) { // dismiss inputs with text fields. #403, #404 var isCursorInput = cursorNodes[ event.target.nodeName ] && !clickTypes[ event.target.type ]; if ( isCursorInput ) { // reset pointerDown logic this.isPointerDown = false; delete this.pointerIdentifier; return; } this._dragPointerDown( event, pointer ); // kludge to blur focused inputs in dragger var focused = document.activeElement; if ( focused && focused.blur && focused != this.element && // do not blur body for IE9 & 10, #117 focused != document.body ) { focused.blur(); } this.pointerDownFocus( event ); // stop if it was moving this.dragX = this.x; this.viewport.classList.add('is-pointer-down'); // bind move and end events this._bindPostStartEvents( event ); // track scrolling this.pointerDownScroll = getScrollPosition(); window.addEventListener( 'scroll', this ); this.dispatchEvent( 'pointerDown', event, [ pointer ] ); }; proto.pointerDownFocus = function( event ) { // focus element, if not touch, and its not an input or select var canPointerDown = getCanPointerDown( event ); if ( !this.options.accessibility || canPointerDown ) { return; } var prevScrollY = window.pageYOffset; this.element.focus(); // hack to fix scroll jump after focus, #76 if ( window.pageYOffset != prevScrollY ) { window.scrollTo( window.pageXOffset, prevScrollY ); } }; var focusNodes = { INPUT: true, SELECT: true, }; function getCanPointerDown( event ) { var isTouchStart = event.type == 'touchstart'; var isTouchPointer = event.pointerType == 'touch'; var isFocusNode = focusNodes[ event.target.nodeName ]; return isTouchStart || isTouchPointer || isFocusNode; } proto.canPreventDefaultOnPointerDown = function( event ) { // prevent default, unless touchstart or input var canPointerDown = getCanPointerDown( event ); return !canPointerDown; }; // ----- move ----- // proto.hasDragStarted = function( moveVector ) { return Math.abs( moveVector.x ) > this.options.dragThreshold; }; // ----- up ----- // proto.pointerUp = function( event, pointer ) { delete this.isTouchScrolling; this.viewport.classList.remove('is-pointer-down'); this.dispatchEvent( 'pointerUp', event, [ pointer ] ); this._dragPointerUp( event, pointer ); }; proto.pointerDone = function() { window.removeEventListener( 'scroll', this ); delete this.pointerDownScroll; }; // -------------------------- dragging -------------------------- // proto.dragStart = function( event, pointer ) { this.dragStartPosition = this.x; this.startAnimation(); window.removeEventListener( 'scroll', this ); this.dispatchEvent( 'dragStart', event, [ pointer ] ); }; proto.pointerMove = function( event, pointer ) { var moveVector = this._dragPointerMove( event, pointer ); this.dispatchEvent( 'pointerMove', event, [ pointer, moveVector ] ); this._dragMove( event, pointer, moveVector ); }; proto.dragMove = function( event, pointer, moveVector ) { event.preventDefault(); this.previousDragX = this.dragX; // reverse if right-to-left var direction = this.options.rightToLeft ? -1 : 1; var dragX = this.dragStartPosition + moveVector.x * direction; if ( !this.options.wrapAround && this.slides.length ) { // slow drag var originBound = Math.max( -this.slides[0].target, this.dragStartPosition ); dragX = dragX > originBound ? ( dragX + originBound ) * 0.5 : dragX; var endBound = Math.min( -this.getLastSlide().target, this.dragStartPosition ); dragX = dragX < endBound ? ( dragX + endBound ) * 0.5 : dragX; } this.dragX = dragX; this.dragMoveTime = new Date(); this.dispatchEvent( 'dragMove', event, [ pointer, moveVector ] ); }; proto.dragEnd = function( event, pointer ) { if ( this.options.freeScroll ) { this.isFreeScrolling = true; } // set selectedIndex based on where flick will end up var index = this.dragEndRestingSelect(); if ( this.options.freeScroll && !this.options.wrapAround ) { // if free-scroll & not wrap around // do not free-scroll if going outside of bounding slides // so bounding slides can attract slider, and keep it in bounds var restingX = this.getRestingPosition(); this.isFreeScrolling = -restingX > this.slides[0].target && -restingX < this.getLastSlide().target; } else if ( !this.options.freeScroll && index == this.selectedIndex ) { // boost selection if selected index has not changed index += this.dragEndBoostSelect(); } delete this.previousDragX; // apply selection // TODO refactor this, selecting here feels weird // HACK, set flag so dragging stays in correct direction this.isDragSelect = this.options.wrapAround; this.select( index ); delete this.isDragSelect; this.dispatchEvent( 'dragEnd', event, [ pointer ] ); }; proto.dragEndRestingSelect = function() { var restingX = this.getRestingPosition(); // how far away from selected slide var distance = Math.abs( this.getSlideDistance( -restingX, this.selectedIndex ) ); // get closet resting going up and going down var positiveResting = this._getClosestResting( restingX, distance, 1 ); var negativeResting = this._getClosestResting( restingX, distance, -1 ); // use closer resting for wrap-around var index = positiveResting.distance < negativeResting.distance ? positiveResting.index : negativeResting.index; return index; }; /** * given resting X and distance to selected cell * get the distance and index of the closest cell * @param {Number} restingX - estimated post-flick resting position * @param {Number} distance - distance to selected cell * @param {Integer} increment - +1 or -1, going up or down * @returns {Object} - { distance: {Number}, index: {Integer} } */ proto._getClosestResting = function( restingX, distance, increment ) { var index = this.selectedIndex; var minDistance = Infinity; var condition = this.options.contain && !this.options.wrapAround ? // if contain, keep going if distance is equal to minDistance function( d, md ) { return d <= md; } : function( d, md ) { return d < md; }; while ( condition( distance, minDistance ) ) { // measure distance to next cell index += increment; minDistance = distance; distance = this.getSlideDistance( -restingX, index ); if ( distance === null ) { break; } distance = Math.abs( distance ); } return { distance: minDistance, // selected was previous index index: index - increment }; }; /** * measure distance between x and a slide target * @param {Number} x * @param {Integer} index - slide index */ proto.getSlideDistance = function( x, index ) { var len = this.slides.length; // wrap around if at least 2 slides var isWrapAround = this.options.wrapAround && len > 1; var slideIndex = isWrapAround ? utils.modulo( index, len ) : index; var slide = this.slides[ slideIndex ]; if ( !slide ) { return null; } // add distance for wrap-around slides var wrap = isWrapAround ? this.slideableWidth * Math.floor( index / len ) : 0; return x - ( slide.target + wrap ); }; proto.dragEndBoostSelect = function() { // do not boost if no previousDragX or dragMoveTime if ( this.previousDragX === undefined || !this.dragMoveTime || // or if drag was held for 100 ms new Date() - this.dragMoveTime > 100 ) { return 0; } var distance = this.getSlideDistance( -this.dragX, this.selectedIndex ); var delta = this.previousDragX - this.dragX; if ( distance > 0 && delta > 0 ) { // boost to next if moving towards the right, and positive velocity return 1; } else if ( distance < 0 && delta < 0 ) { // boost to previous if moving towards the left, and negative velocity return -1; } return 0; }; // ----- staticClick ----- // proto.staticClick = function( event, pointer ) { // get clickedCell, if cell was clicked var clickedCell = this.getParentCell( event.target ); var cellElem = clickedCell && clickedCell.element; var cellIndex = clickedCell && this.cells.indexOf( clickedCell ); this.dispatchEvent( 'staticClick', event, [ pointer, cellElem, cellIndex ] ); }; // ----- scroll ----- // proto.onscroll = function() { var scroll = getScrollPosition(); var scrollMoveX = this.pointerDownScroll.x - scroll.x; var scrollMoveY = this.pointerDownScroll.y - scroll.y; // cancel click/tap if scroll is too much if ( Math.abs( scrollMoveX ) > 3 || Math.abs( scrollMoveY ) > 3 ) { this._pointerDone(); } }; // ----- utils ----- // function getScrollPosition() { return { x: window.pageXOffset, y: window.pageYOffset }; } // ----- ----- // return Flickity; })); /*! * Tap listener v2.0.0 * listens to taps * MIT license */ /*jshint browser: true, unused: true, undef: true, strict: true */ ( function( window, factory ) { // universal module definition /*jshint strict: false*/ /*globals define, module, require */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'tap-listener/tap-listener',[ 'unipointer/unipointer' ], function( Unipointer ) { return factory( window, Unipointer ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( window, require('unipointer') ); } else { // browser global window.TapListener = factory( window, window.Unipointer ); } }( window, function factory( window, Unipointer ) { // -------------------------- TapListener -------------------------- // function TapListener( elem ) { this.bindTap( elem ); } // inherit Unipointer & EventEmitter var proto = TapListener.prototype = Object.create( Unipointer.prototype ); /** * bind tap event to element * @param {Element} elem */ proto.bindTap = function( elem ) { if ( !elem ) { return; } this.unbindTap(); this.tapElement = elem; this._bindStartEvent( elem, true ); }; proto.unbindTap = function() { if ( !this.tapElement ) { return; } this._bindStartEvent( this.tapElement, true ); delete this.tapElement; }; /** * pointer up * @param {Event} event * @param {Event or Touch} pointer */ proto.pointerUp = function( event, pointer ) { // ignore emulated mouse up clicks if ( this.isIgnoringMouseUp && event.type == 'mouseup' ) { return; } var pointerPoint = Unipointer.getPointerPoint( pointer ); var boundingRect = this.tapElement.getBoundingClientRect(); var scrollX = window.pageXOffset; var scrollY = window.pageYOffset; // calculate if pointer is inside tapElement var isInside = pointerPoint.x >= boundingRect.left + scrollX && pointerPoint.x <= boundingRect.right + scrollX && pointerPoint.y >= boundingRect.top + scrollY && pointerPoint.y <= boundingRect.bottom + scrollY; // trigger callback if pointer is inside element if ( isInside ) { this.emitEvent( 'tap', [ event, pointer ] ); } // set flag for emulated clicks 300ms after touchend if ( event.type != 'mouseup' ) { this.isIgnoringMouseUp = true; // reset flag after 300ms var _this = this; setTimeout( function() { delete _this.isIgnoringMouseUp; }, 400 ); } }; proto.destroy = function() { this.pointerDone(); this.unbindTap(); }; // ----- ----- // return TapListener; })); // prev/next buttons ( function( window, factory ) { // universal module definition /* jshint strict: false */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'flickity/js/prev-next-button',[ './flickity', 'tap-listener/tap-listener', 'fizzy-ui-utils/utils' ], function( Flickity, TapListener, utils ) { return factory( window, Flickity, TapListener, utils ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( window, require('./flickity'), require('tap-listener'), require('fizzy-ui-utils') ); } else { // browser global factory( window, window.Flickity, window.TapListener, window.fizzyUIUtils ); } }( window, function factory( window, Flickity, TapListener, utils ) { 'use strict'; var svgURI = 'http://www.w3.org/2000/svg'; // -------------------------- PrevNextButton -------------------------- // function PrevNextButton( direction, parent ) { this.direction = direction; this.parent = parent; this._create(); } PrevNextButton.prototype = new TapListener(); PrevNextButton.prototype._create = function() { // properties this.isEnabled = true; this.isPrevious = this.direction == -1; var leftDirection = this.parent.options.rightToLeft ? 1 : -1; this.isLeft = this.direction == leftDirection; var element = this.element = document.createElement('button'); element.className = 'flickity-prev-next-button'; element.className += this.isPrevious ? ' previous' : ' next'; // prevent button from submitting form http://stackoverflow.com/a/10836076/182183 element.setAttribute( 'type', 'button' ); // init as disabled this.disable(); element.setAttribute( 'aria-label', this.isPrevious ? 'previous' : 'next' ); // create arrow var svg = this.createSVG(); element.appendChild( svg ); // events this.on( 'tap', this.onTap ); this.parent.on( 'select', this.update.bind( this ) ); this.on( 'pointerDown', this.parent.childUIPointerDown.bind( this.parent ) ); }; PrevNextButton.prototype.activate = function() { this.bindTap( this.element ); // click events from keyboard this.element.addEventListener( 'click', this ); // add to DOM this.parent.element.appendChild( this.element ); }; PrevNextButton.prototype.deactivate = function() { // remove from DOM this.parent.element.removeChild( this.element ); // do regular TapListener destroy TapListener.prototype.destroy.call( this ); // click events from keyboard this.element.removeEventListener( 'click', this ); }; PrevNextButton.prototype.createSVG = function() { var svg = document.createElementNS( svgURI, 'svg'); svg.setAttribute( 'viewBox', '0 0 100 100' ); var path = document.createElementNS( svgURI, 'path'); var pathMovements = getArrowMovements( this.parent.options.arrowShape ); path.setAttribute( 'd', pathMovements ); path.setAttribute( 'class', 'arrow' ); // rotate arrow if ( !this.isLeft ) { path.setAttribute( 'transform', 'translate(100, 100) rotate(180) ' ); } svg.appendChild( path ); return svg; }; // get SVG path movmement function getArrowMovements( shape ) { // use shape as movement if string if ( typeof shape == 'string' ) { return shape; } // create movement string return 'M ' + shape.x0 + ',50' + ' L ' + shape.x1 + ',' + ( shape.y1 + 50 ) + ' L ' + shape.x2 + ',' + ( shape.y2 + 50 ) + ' L ' + shape.x3 + ',50 ' + ' L ' + shape.x2 + ',' + ( 50 - shape.y2 ) + ' L ' + shape.x1 + ',' + ( 50 - shape.y1 ) + ' Z'; } PrevNextButton.prototype.onTap = function() { if ( !this.isEnabled ) { return; } this.parent.uiChange(); var method = this.isPrevious ? 'previous' : 'next'; this.parent[ method ](); }; PrevNextButton.prototype.handleEvent = utils.handleEvent; PrevNextButton.prototype.onclick = function() { // only allow clicks from keyboard var focused = document.activeElement; if ( focused && focused == this.element ) { this.onTap(); } }; // ----- ----- // PrevNextButton.prototype.enable = function() { if ( this.isEnabled ) { return; } this.element.disabled = false; this.isEnabled = true; }; PrevNextButton.prototype.disable = function() { if ( !this.isEnabled ) { return; } this.element.disabled = true; this.isEnabled = false; }; PrevNextButton.prototype.update = function() { // index of first or last slide, if previous or next var slides = this.parent.slides; // enable is wrapAround and at least 2 slides if ( this.parent.options.wrapAround && slides.length > 1 ) { this.enable(); return; } var lastIndex = slides.length ? slides.length - 1 : 0; var boundIndex = this.isPrevious ? 0 : lastIndex; var method = this.parent.selectedIndex == boundIndex ? 'disable' : 'enable'; this[ method ](); }; PrevNextButton.prototype.destroy = function() { this.deactivate(); }; // -------------------------- Flickity prototype -------------------------- // utils.extend( Flickity.defaults, { prevNextButtons: true, arrowShape: { x0: 10, x1: 60, y1: 50, x2: 70, y2: 40, x3: 30 } }); Flickity.createMethods.push('_createPrevNextButtons'); var proto = Flickity.prototype; proto._createPrevNextButtons = function() { if ( !this.options.prevNextButtons ) { return; } this.prevButton = new PrevNextButton( -1, this ); this.nextButton = new PrevNextButton( 1, this ); this.on( 'activate', this.activatePrevNextButtons ); }; proto.activatePrevNextButtons = function() { this.prevButton.activate(); this.nextButton.activate(); this.on( 'deactivate', this.deactivatePrevNextButtons ); }; proto.deactivatePrevNextButtons = function() { this.prevButton.deactivate(); this.nextButton.deactivate(); this.off( 'deactivate', this.deactivatePrevNextButtons ); }; // -------------------------- -------------------------- // Flickity.PrevNextButton = PrevNextButton; return Flickity; })); // page dots ( function( window, factory ) { // universal module definition /* jshint strict: false */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'flickity/js/page-dots',[ './flickity', 'tap-listener/tap-listener', 'fizzy-ui-utils/utils' ], function( Flickity, TapListener, utils ) { return factory( window, Flickity, TapListener, utils ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( window, require('./flickity'), require('tap-listener'), require('fizzy-ui-utils') ); } else { // browser global factory( window, window.Flickity, window.TapListener, window.fizzyUIUtils ); } }( window, function factory( window, Flickity, TapListener, utils ) { // -------------------------- PageDots -------------------------- // function PageDots( parent ) { this.parent = parent; this._create(); } PageDots.prototype = new TapListener(); PageDots.prototype._create = function() { // create holder element this.holder = document.createElement('ol'); this.holder.className = 'flickity-page-dots'; // create dots, array of elements this.dots = []; // events this.on( 'tap', this.onTap ); this.on( 'pointerDown', this.parent.childUIPointerDown.bind( this.parent ) ); }; PageDots.prototype.activate = function() { this.setDots(); this.bindTap( this.holder ); // add to DOM this.parent.element.appendChild( this.holder ); }; PageDots.prototype.deactivate = function() { // remove from DOM this.parent.element.removeChild( this.holder ); TapListener.prototype.destroy.call( this ); }; PageDots.prototype.setDots = function() { // get difference between number of slides and number of dots var delta = this.parent.slides.length - this.dots.length; if ( delta > 0 ) { this.addDots( delta ); } else if ( delta < 0 ) { this.removeDots( -delta ); } }; PageDots.prototype.addDots = function( count ) { var fragment = document.createDocumentFragment(); var newDots = []; while ( count ) { var dot = document.createElement('li'); dot.className = 'dot'; fragment.appendChild( dot ); newDots.push( dot ); count--; } this.holder.appendChild( fragment ); this.dots = this.dots.concat( newDots ); }; PageDots.prototype.removeDots = function( count ) { // remove from this.dots collection var removeDots = this.dots.splice( this.dots.length - count, count ); // remove from DOM removeDots.forEach( function( dot ) { this.holder.removeChild( dot ); }, this ); }; PageDots.prototype.updateSelected = function() { // remove selected class on previous if ( this.selectedDot ) { this.selectedDot.className = 'dot'; } // don't proceed if no dots if ( !this.dots.length ) { return; } this.selectedDot = this.dots[ this.parent.selectedIndex ]; this.selectedDot.className = 'dot is-selected'; }; PageDots.prototype.onTap = function( event ) { var target = event.target; // only care about dot clicks if ( target.nodeName != 'LI' ) { return; } this.parent.uiChange(); var index = this.dots.indexOf( target ); this.parent.select( index ); }; PageDots.prototype.destroy = function() { this.deactivate(); }; Flickity.PageDots = PageDots; // -------------------------- Flickity -------------------------- // utils.extend( Flickity.defaults, { pageDots: true }); Flickity.createMethods.push('_createPageDots'); var proto = Flickity.prototype; proto._createPageDots = function() { if ( !this.options.pageDots ) { return; } this.pageDots = new PageDots( this ); // events this.on( 'activate', this.activatePageDots ); this.on( 'select', this.updateSelectedPageDots ); this.on( 'cellChange', this.updatePageDots ); this.on( 'resize', this.updatePageDots ); this.on( 'deactivate', this.deactivatePageDots ); }; proto.activatePageDots = function() { this.pageDots.activate(); }; proto.updateSelectedPageDots = function() { this.pageDots.updateSelected(); }; proto.updatePageDots = function() { this.pageDots.setDots(); }; proto.deactivatePageDots = function() { this.pageDots.deactivate(); }; // ----- ----- // Flickity.PageDots = PageDots; return Flickity; })); // player & autoPlay ( function( window, factory ) { // universal module definition /* jshint strict: false */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'flickity/js/player',[ 'ev-emitter/ev-emitter', 'fizzy-ui-utils/utils', './flickity' ], function( EvEmitter, utils, Flickity ) { return factory( EvEmitter, utils, Flickity ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( require('ev-emitter'), require('fizzy-ui-utils'), require('./flickity') ); } else { // browser global factory( window.EvEmitter, window.fizzyUIUtils, window.Flickity ); } }( window, function factory( EvEmitter, utils, Flickity ) { // -------------------------- Page Visibility -------------------------- // // https://developer.mozilla.org/en-US/docs/Web/Guide/User_experience/Using_the_Page_Visibility_API var hiddenProperty, visibilityEvent; if ( 'hidden' in document ) { hiddenProperty = 'hidden'; visibilityEvent = 'visibilitychange'; } else if ( 'webkitHidden' in document ) { hiddenProperty = 'webkitHidden'; visibilityEvent = 'webkitvisibilitychange'; } // -------------------------- Player -------------------------- // function Player( parent ) { this.parent = parent; this.state = 'stopped'; // visibility change event handler if ( visibilityEvent ) { this.onVisibilityChange = function() { this.visibilityChange(); }.bind( this ); this.onVisibilityPlay = function() { this.visibilityPlay(); }.bind( this ); } } Player.prototype = Object.create( EvEmitter.prototype ); // start play Player.prototype.play = function() { if ( this.state == 'playing' ) { return; } // do not play if page is hidden, start playing when page is visible var isPageHidden = document[ hiddenProperty ]; if ( visibilityEvent && isPageHidden ) { document.addEventListener( visibilityEvent, this.onVisibilityPlay ); return; } this.state = 'playing'; // listen to visibility change if ( visibilityEvent ) { document.addEventListener( visibilityEvent, this.onVisibilityChange ); } // start ticking this.tick(); }; Player.prototype.tick = function() { // do not tick if not playing if ( this.state != 'playing' ) { return; } var time = this.parent.options.autoPlay; // default to 3 seconds time = typeof time == 'number' ? time : 3000; var _this = this; // HACK: reset ticks if stopped and started within interval this.clear(); this.timeout = setTimeout( function() { _this.parent.next( true ); _this.tick(); }, time ); }; Player.prototype.stop = function() { this.state = 'stopped'; this.clear(); // remove visibility change event if ( visibilityEvent ) { document.removeEventListener( visibilityEvent, this.onVisibilityChange ); } }; Player.prototype.clear = function() { clearTimeout( this.timeout ); }; Player.prototype.pause = function() { if ( this.state == 'playing' ) { this.state = 'paused'; this.clear(); } }; Player.prototype.unpause = function() { // re-start play if paused if ( this.state == 'paused' ) { this.play(); } }; // pause if page visibility is hidden, unpause if visible Player.prototype.visibilityChange = function() { var isPageHidden = document[ hiddenProperty ]; this[ isPageHidden ? 'pause' : 'unpause' ](); }; Player.prototype.visibilityPlay = function() { this.play(); document.removeEventListener( visibilityEvent, this.onVisibilityPlay ); }; // -------------------------- Flickity -------------------------- // utils.extend( Flickity.defaults, { pauseAutoPlayOnHover: true }); Flickity.createMethods.push('_createPlayer'); var proto = Flickity.prototype; proto._createPlayer = function() { this.player = new Player( this ); this.on( 'activate', this.activatePlayer ); this.on( 'uiChange', this.stopPlayer ); this.on( 'pointerDown', this.stopPlayer ); this.on( 'deactivate', this.deactivatePlayer ); }; proto.activatePlayer = function() { if ( !this.options.autoPlay ) { return; } this.player.play(); this.element.addEventListener( 'mouseenter', this ); }; // Player API, don't hate the ... thanks I know where the door is proto.playPlayer = function() { this.player.play(); }; proto.stopPlayer = function() { this.player.stop(); }; proto.pausePlayer = function() { this.player.pause(); }; proto.unpausePlayer = function() { this.player.unpause(); }; proto.deactivatePlayer = function() { this.player.stop(); this.element.removeEventListener( 'mouseenter', this ); }; // ----- mouseenter/leave ----- // // pause auto-play on hover proto.onmouseenter = function() { if ( !this.options.pauseAutoPlayOnHover ) { return; } this.player.pause(); this.element.addEventListener( 'mouseleave', this ); }; // resume auto-play on hover off proto.onmouseleave = function() { this.player.unpause(); this.element.removeEventListener( 'mouseleave', this ); }; // ----- ----- // Flickity.Player = Player; return Flickity; })); // add, remove cell ( function( window, factory ) { // universal module definition /* jshint strict: false */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'flickity/js/add-remove-cell',[ './flickity', 'fizzy-ui-utils/utils' ], function( Flickity, utils ) { return factory( window, Flickity, utils ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( window, require('./flickity'), require('fizzy-ui-utils') ); } else { // browser global factory( window, window.Flickity, window.fizzyUIUtils ); } }( window, function factory( window, Flickity, utils ) { // append cells to a document fragment function getCellsFragment( cells ) { var fragment = document.createDocumentFragment(); cells.forEach( function( cell ) { fragment.appendChild( cell.element ); }); return fragment; } // -------------------------- add/remove cell prototype -------------------------- // var proto = Flickity.prototype; /** * Insert, prepend, or append cells * @param {Element, Array, NodeList} elems * @param {Integer} index */ proto.insert = function( elems, index ) { var cells = this._makeCells( elems ); if ( !cells || !cells.length ) { return; } var len = this.cells.length; // default to append index = index === undefined ? len : index; // add cells with document fragment var fragment = getCellsFragment( cells ); // append to slider var isAppend = index == len; if ( isAppend ) { this.slider.appendChild( fragment ); } else { var insertCellElement = this.cells[ index ].element; this.slider.insertBefore( fragment, insertCellElement ); } // add to this.cells if ( index === 0 ) { // prepend, add to start this.cells = cells.concat( this.cells ); } else if ( isAppend ) { // append, add to end this.cells = this.cells.concat( cells ); } else { // insert in this.cells var endCells = this.cells.splice( index, len - index ); this.cells = this.cells.concat( cells ).concat( endCells ); } this._sizeCells( cells ); var selectedIndexDelta = index > this.selectedIndex ? 0 : cells.length; this._cellAddedRemoved( index, selectedIndexDelta ); }; proto.append = function( elems ) { this.insert( elems, this.cells.length ); }; proto.prepend = function( elems ) { this.insert( elems, 0 ); }; /** * Remove cells * @param {Element, Array, NodeList} elems */ proto.remove = function( elems ) { var cells = this.getCells( elems ); var selectedIndexDelta = 0; var len = cells.length; var i, cell; // calculate selectedIndexDelta, easier if done in seperate loop for ( i=0; i < len; i++ ) { cell = cells[i]; var wasBefore = this.cells.indexOf( cell ) < this.selectedIndex; selectedIndexDelta -= wasBefore ? 1 : 0; } for ( i=0; i < len; i++ ) { cell = cells[i]; cell.remove(); // remove item from collection utils.removeFrom( this.cells, cell ); } if ( cells.length ) { // update stuff this._cellAddedRemoved( 0, selectedIndexDelta ); } }; // updates when cells are added or removed proto._cellAddedRemoved = function( changedCellIndex, selectedIndexDelta ) { // TODO this math isn't perfect with grouped slides selectedIndexDelta = selectedIndexDelta || 0; this.selectedIndex += selectedIndexDelta; this.selectedIndex = Math.max( 0, Math.min( this.slides.length - 1, this.selectedIndex ) ); this.cellChange( changedCellIndex, true ); // backwards compatibility this.emitEvent( 'cellAddedRemoved', [ changedCellIndex, selectedIndexDelta ] ); }; /** * logic to be run after a cell's size changes * @param {Element} elem - cell's element */ proto.cellSizeChange = function( elem ) { var cell = this.getCell( elem ); if ( !cell ) { return; } cell.getSize(); var index = this.cells.indexOf( cell ); this.cellChange( index ); }; /** * logic any time a cell is changed: added, removed, or size changed * @param {Integer} changedCellIndex - index of the changed cell, optional */ proto.cellChange = function( changedCellIndex, isPositioningSlider ) { var prevSlideableWidth = this.slideableWidth; this._positionCells( changedCellIndex ); this._getWrapShiftCells(); this.setGallerySize(); this.emitEvent( 'cellChange', [ changedCellIndex ] ); // position slider if ( this.options.freeScroll ) { // shift x by change in slideableWidth // TODO fix position shifts when prepending w/ freeScroll var deltaX = prevSlideableWidth - this.slideableWidth; this.x += deltaX * this.cellAlign; this.positionSlider(); } else { // do not position slider after lazy load if ( isPositioningSlider ) { this.positionSliderAtSelected(); } this.select( this.selectedIndex ); } }; // ----- ----- // return Flickity; })); // lazyload ( function( window, factory ) { // universal module definition /* jshint strict: false */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'flickity/js/lazyload',[ './flickity', 'fizzy-ui-utils/utils' ], function( Flickity, utils ) { return factory( window, Flickity, utils ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( window, require('./flickity'), require('fizzy-ui-utils') ); } else { // browser global factory( window, window.Flickity, window.fizzyUIUtils ); } }( window, function factory( window, Flickity, utils ) { 'use strict'; Flickity.createMethods.push('_createLazyload'); var proto = Flickity.prototype; proto._createLazyload = function() { this.on( 'select', this.lazyLoad ); }; proto.lazyLoad = function() { var lazyLoad = this.options.lazyLoad; if ( !lazyLoad ) { return; } // get adjacent cells, use lazyLoad option for adjacent count var adjCount = typeof lazyLoad == 'number' ? lazyLoad : 0; var cellElems = this.getAdjacentCellElements( adjCount ); // get lazy images in those cells var lazyImages = []; cellElems.forEach( function( cellElem ) { var lazyCellImages = getCellLazyImages( cellElem ); lazyImages = lazyImages.concat( lazyCellImages ); }); // load lazy images lazyImages.forEach( function( img ) { new LazyLoader( img, this ); }, this ); }; function getCellLazyImages( cellElem ) { // check if cell element is lazy image if ( cellElem.nodeName == 'IMG' && cellElem.getAttribute('data-flickity-lazyload') ) { return [ cellElem ]; } // select lazy images in cell var imgs = cellElem.querySelectorAll('img[data-flickity-lazyload]'); return utils.makeArray( imgs ); } // -------------------------- LazyLoader -------------------------- // /** * class to handle loading images */ function LazyLoader( img, flickity ) { this.img = img; this.flickity = flickity; this.load(); } LazyLoader.prototype.handleEvent = utils.handleEvent; LazyLoader.prototype.load = function() { this.img.addEventListener( 'load', this ); this.img.addEventListener( 'error', this ); // load image this.img.src = this.img.getAttribute('data-flickity-lazyload'); // remove attr this.img.removeAttribute('data-flickity-lazyload'); }; LazyLoader.prototype.onload = function( event ) { this.complete( event, 'flickity-lazyloaded' ); }; LazyLoader.prototype.onerror = function( event ) { this.complete( event, 'flickity-lazyerror' ); }; LazyLoader.prototype.complete = function( event, className ) { // unbind events this.img.removeEventListener( 'load', this ); this.img.removeEventListener( 'error', this ); var cell = this.flickity.getParentCell( this.img ); var cellElem = cell && cell.element; this.flickity.cellSizeChange( cellElem ); this.img.classList.add( className ); this.flickity.dispatchEvent( 'lazyLoad', event, cellElem ); }; // ----- ----- // Flickity.LazyLoader = LazyLoader; return Flickity; })); /*! * Flickity v2.0.10 * Touch, responsive, flickable carousels * * Licensed GPLv3 for open source use * or Flickity Commercial License for commercial use * * http://flickity.metafizzy.co * Copyright 2017 Metafizzy */ ( function( window, factory ) { // universal module definition /* jshint strict: false */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'flickity/js/index',[ './flickity', './drag', './prev-next-button', './page-dots', './player', './add-remove-cell', './lazyload' ], factory ); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( require('./flickity'), require('./drag'), require('./prev-next-button'), require('./page-dots'), require('./player'), require('./add-remove-cell'), require('./lazyload') ); } })( window, function factory( Flickity ) { /*jshint strict: false*/ return Flickity; }); /*! * Flickity asNavFor v2.0.1 * enable asNavFor for Flickity */ /*jshint browser: true, undef: true, unused: true, strict: true*/ ( function( window, factory ) { // universal module definition /*jshint strict: false */ /*globals define, module, require */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'flickity-as-nav-for/as-nav-for',[ 'flickity/js/index', 'fizzy-ui-utils/utils' ], factory ); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( require('flickity'), require('fizzy-ui-utils') ); } else { // browser global window.Flickity = factory( window.Flickity, window.fizzyUIUtils ); } }( window, function factory( Flickity, utils ) { // -------------------------- asNavFor prototype -------------------------- // // Flickity.defaults.asNavFor = null; Flickity.createMethods.push('_createAsNavFor'); var proto = Flickity.prototype; proto._createAsNavFor = function() { this.on( 'activate', this.activateAsNavFor ); this.on( 'deactivate', this.deactivateAsNavFor ); this.on( 'destroy', this.destroyAsNavFor ); var asNavForOption = this.options.asNavFor; if ( !asNavForOption ) { return; } // HACK do async, give time for other flickity to be initalized var _this = this; setTimeout( function initNavCompanion() { _this.setNavCompanion( asNavForOption ); }); }; proto.setNavCompanion = function( elem ) { elem = utils.getQueryElement( elem ); var companion = Flickity.data( elem ); // stop if no companion or companion is self if ( !companion || companion == this ) { return; } this.navCompanion = companion; // companion select var _this = this; this.onNavCompanionSelect = function() { _this.navCompanionSelect(); }; companion.on( 'select', this.onNavCompanionSelect ); // click this.on( 'staticClick', this.onNavStaticClick ); this.navCompanionSelect( true ); }; proto.navCompanionSelect = function( isInstant ) { if ( !this.navCompanion ) { return; } // select slide that matches first cell of slide var selectedCell = this.navCompanion.selectedCells[0]; var firstIndex = this.navCompanion.cells.indexOf( selectedCell ); var lastIndex = firstIndex + this.navCompanion.selectedCells.length - 1; var selectIndex = Math.floor( lerp( firstIndex, lastIndex, this.navCompanion.cellAlign ) ); this.selectCell( selectIndex, false, isInstant ); // set nav selected class this.removeNavSelectedElements(); // stop if companion has more cells than this one if ( selectIndex >= this.cells.length ) { return; } var selectedCells = this.cells.slice( firstIndex, lastIndex + 1 ); this.navSelectedElements = selectedCells.map( function( cell ) { return cell.element; }); this.changeNavSelectedClass('add'); }; function lerp( a, b, t ) { return ( b - a ) * t + a; } proto.changeNavSelectedClass = function( method ) { this.navSelectedElements.forEach( function( navElem ) { navElem.classList[ method ]('is-nav-selected'); }); }; proto.activateAsNavFor = function() { this.navCompanionSelect( true ); }; proto.removeNavSelectedElements = function() { if ( !this.navSelectedElements ) { return; } this.changeNavSelectedClass('remove'); delete this.navSelectedElements; }; proto.onNavStaticClick = function( event, pointer, cellElement, cellIndex ) { if ( typeof cellIndex == 'number' ) { this.navCompanion.selectCell( cellIndex ); } }; proto.deactivateAsNavFor = function() { this.removeNavSelectedElements(); }; proto.destroyAsNavFor = function() { if ( !this.navCompanion ) { return; } this.navCompanion.off( 'select', this.onNavCompanionSelect ); this.off( 'staticClick', this.onNavStaticClick ); delete this.navCompanion; }; // ----- ----- // return Flickity; })); /*! * imagesLoaded v4.1.3 * JavaScript is all like "You images are done yet or what?" * MIT License */ ( function( window, factory ) { 'use strict'; // universal module definition /*global define: false, module: false, require: false */ if ( typeof define == 'function' && define.amd ) { // AMD define( 'imagesloaded/imagesloaded',[ 'ev-emitter/ev-emitter' ], function( EvEmitter ) { return factory( window, EvEmitter ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( window, require('ev-emitter') ); } else { // browser global window.imagesLoaded = factory( window, window.EvEmitter ); } })( typeof window !== 'undefined' ? window : this, // -------------------------- factory -------------------------- // function factory( window, EvEmitter ) { var $ = window.jQuery; var console = window.console; // -------------------------- helpers -------------------------- // // extend objects function extend( a, b ) { for ( var prop in b ) { a[ prop ] = b[ prop ]; } return a; } // turn element or nodeList into an array function makeArray( obj ) { var ary = []; if ( Array.isArray( obj ) ) { // use object if already an array ary = obj; } else if ( typeof obj.length == 'number' ) { // convert nodeList to array for ( var i=0; i < obj.length; i++ ) { ary.push( obj[i] ); } } else { // array of single index ary.push( obj ); } return ary; } // -------------------------- imagesLoaded -------------------------- // /** * @param {Array, Element, NodeList, String} elem * @param {Object or Function} options - if function, use as callback * @param {Function} onAlways - callback function */ function ImagesLoaded( elem, options, onAlways ) { // coerce ImagesLoaded() without new, to be new ImagesLoaded() if ( !( this instanceof ImagesLoaded ) ) { return new ImagesLoaded( elem, options, onAlways ); } // use elem as selector string if ( typeof elem == 'string' ) { elem = document.querySelectorAll( elem ); } this.elements = makeArray( elem ); this.options = extend( {}, this.options ); if ( typeof options == 'function' ) { onAlways = options; } else { extend( this.options, options ); } if ( onAlways ) { this.on( 'always', onAlways ); } this.getImages(); if ( $ ) { // add jQuery Deferred object this.jqDeferred = new $.Deferred(); } // HACK check async to allow time to bind listeners setTimeout( function() { this.check(); }.bind( this )); } ImagesLoaded.prototype = Object.create( EvEmitter.prototype ); ImagesLoaded.prototype.options = {}; ImagesLoaded.prototype.getImages = function() { this.images = []; // filter & find items if we have an item selector this.elements.forEach( this.addElementImages, this ); }; /** * @param {Node} element */ ImagesLoaded.prototype.addElementImages = function( elem ) { // filter siblings if ( elem.nodeName == 'IMG' ) { this.addImage( elem ); } // get background image on element if ( this.options.background === true ) { this.addElementBackgroundImages( elem ); } // find children // no non-element nodes, #143 var nodeType = elem.nodeType; if ( !nodeType || !elementNodeTypes[ nodeType ] ) { return; } var childImgs = elem.querySelectorAll('img'); // concat childElems to filterFound array for ( var i=0; i < childImgs.length; i++ ) { var img = childImgs[i]; this.addImage( img ); } // get child background images if ( typeof this.options.background == 'string' ) { var children = elem.querySelectorAll( this.options.background ); for ( i=0; i < children.length; i++ ) { var child = children[i]; this.addElementBackgroundImages( child ); } } }; var elementNodeTypes = { 1: true, 9: true, 11: true }; ImagesLoaded.prototype.addElementBackgroundImages = function( elem ) { var style = getComputedStyle( elem ); if ( !style ) { // Firefox returns null if in a hidden iframe https://bugzil.la/548397 return; } // get url inside url("...") var reURL = /url\((['"])?(.*?)\1\)/gi; var matches = reURL.exec( style.backgroundImage ); while ( matches !== null ) { var url = matches && matches[2]; if ( url ) { this.addBackground( url, elem ); } matches = reURL.exec( style.backgroundImage ); } }; /** * @param {Image} img */ ImagesLoaded.prototype.addImage = function( img ) { var loadingImage = new LoadingImage( img ); this.images.push( loadingImage ); }; ImagesLoaded.prototype.addBackground = function( url, elem ) { var background = new Background( url, elem ); this.images.push( background ); }; ImagesLoaded.prototype.check = function() { var _this = this; this.progressedCount = 0; this.hasAnyBroken = false; // complete if no images if ( !this.images.length ) { this.complete(); return; } function onProgress( image, elem, message ) { // HACK - Chrome triggers event before object properties have changed. #83 setTimeout( function() { _this.progress( image, elem, message ); }); } this.images.forEach( function( loadingImage ) { loadingImage.once( 'progress', onProgress ); loadingImage.check(); }); }; ImagesLoaded.prototype.progress = function( image, elem, message ) { this.progressedCount++; this.hasAnyBroken = this.hasAnyBroken || !image.isLoaded; // progress event this.emitEvent( 'progress', [ this, image, elem ] ); if ( this.jqDeferred && this.jqDeferred.notify ) { this.jqDeferred.notify( this, image ); } // check if completed if ( this.progressedCount == this.images.length ) { this.complete(); } if ( this.options.debug && console ) { console.log( 'progress: ' + message, image, elem ); } }; ImagesLoaded.prototype.complete = function() { var eventName = this.hasAnyBroken ? 'fail' : 'done'; this.isComplete = true; this.emitEvent( eventName, [ this ] ); this.emitEvent( 'always', [ this ] ); if ( this.jqDeferred ) { var jqMethod = this.hasAnyBroken ? 'reject' : 'resolve'; this.jqDeferred[ jqMethod ]( this ); } }; // -------------------------- -------------------------- // function LoadingImage( img ) { this.img = img; } LoadingImage.prototype = Object.create( EvEmitter.prototype ); LoadingImage.prototype.check = function() { // If complete is true and browser supports natural sizes, // try to check for image status manually. var isComplete = this.getIsImageComplete(); if ( isComplete ) { // report based on naturalWidth this.confirm( this.img.naturalWidth !== 0, 'naturalWidth' ); return; } // If none of the checks above matched, simulate loading on detached element. this.proxyImage = new Image(); this.proxyImage.addEventListener( 'load', this ); this.proxyImage.addEventListener( 'error', this ); // bind to image as well for Firefox. #191 this.img.addEventListener( 'load', this ); this.img.addEventListener( 'error', this ); this.proxyImage.src = this.img.src; }; LoadingImage.prototype.getIsImageComplete = function() { return this.img.complete && this.img.naturalWidth !== undefined; }; LoadingImage.prototype.confirm = function( isLoaded, message ) { this.isLoaded = isLoaded; this.emitEvent( 'progress', [ this, this.img, message ] ); }; // ----- events ----- // // trigger specified handler for event type LoadingImage.prototype.handleEvent = function( event ) { var method = 'on' + event.type; if ( this[ method ] ) { this[ method ]( event ); } }; LoadingImage.prototype.onload = function() { this.confirm( true, 'onload' ); this.unbindEvents(); }; LoadingImage.prototype.onerror = function() { this.confirm( false, 'onerror' ); this.unbindEvents(); }; LoadingImage.prototype.unbindEvents = function() { this.proxyImage.removeEventListener( 'load', this ); this.proxyImage.removeEventListener( 'error', this ); this.img.removeEventListener( 'load', this ); this.img.removeEventListener( 'error', this ); }; // -------------------------- Background -------------------------- // function Background( url, element ) { this.url = url; this.element = element; this.img = new Image(); } // inherit LoadingImage prototype Background.prototype = Object.create( LoadingImage.prototype ); Background.prototype.check = function() { this.img.addEventListener( 'load', this ); this.img.addEventListener( 'error', this ); this.img.src = this.url; // check if image is already complete var isComplete = this.getIsImageComplete(); if ( isComplete ) { this.confirm( this.img.naturalWidth !== 0, 'naturalWidth' ); this.unbindEvents(); } }; Background.prototype.unbindEvents = function() { this.img.removeEventListener( 'load', this ); this.img.removeEventListener( 'error', this ); }; Background.prototype.confirm = function( isLoaded, message ) { this.isLoaded = isLoaded; this.emitEvent( 'progress', [ this, this.element, message ] ); }; // -------------------------- jQuery -------------------------- // ImagesLoaded.makeJQueryPlugin = function( jQuery ) { jQuery = jQuery || window.jQuery; if ( !jQuery ) { return; } // set local variable $ = jQuery; // $().imagesLoaded() $.fn.imagesLoaded = function( options, callback ) { var instance = new ImagesLoaded( this, options, callback ); return instance.jqDeferred.promise( $(this) ); }; }; // try making plugin ImagesLoaded.makeJQueryPlugin(); // -------------------------- -------------------------- // return ImagesLoaded; }); /*! * Flickity imagesLoaded v2.0.0 * enables imagesLoaded option for Flickity */ /*jshint browser: true, strict: true, undef: true, unused: true */ ( function( window, factory ) { // universal module definition /*jshint strict: false */ /*globals define, module, require */ if ( typeof define == 'function' && define.amd ) { // AMD define( [ 'flickity/js/index', 'imagesloaded/imagesloaded' ], function( Flickity, imagesLoaded ) { return factory( window, Flickity, imagesLoaded ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( window, require('flickity'), require('imagesloaded') ); } else { // browser global window.Flickity = factory( window, window.Flickity, window.imagesLoaded ); } }( window, function factory( window, Flickity, imagesLoaded ) { 'use strict'; Flickity.createMethods.push('_createImagesLoaded'); var proto = Flickity.prototype; proto._createImagesLoaded = function() { this.on( 'activate', this.imagesLoaded ); }; proto.imagesLoaded = function() { if ( !this.options.imagesLoaded ) { return; } var _this = this; function onImagesLoadedProgress( instance, image ) { var cell = _this.getParentCell( image.img ); _this.cellSizeChange( cell && cell.element ); if ( !_this.options.freeScroll ) { _this.positionSliderAtSelected(); } } imagesLoaded( this.slider ).on( 'progress', onImagesLoadedProgress ); }; return Flickity; }));
/** * * Creator of typical test AnimationClips / KeyframeTracks * * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ */ THREE.AnimationClipCreator = function() { }; THREE.AnimationClipCreator.CreateRotationAnimation = function( period, axis ) { var times = [ 0, period ], values = [ 0, 360 ]; axis = axis || 'x'; var trackName = '.rotation[' + axis + ']'; var track = new THREE.NumberKeyframeTrack( trackName, times, values ); return new THREE.AnimationClip( null, period, [ track ] ); }; THREE.AnimationClipCreator.CreateScaleAxisAnimation = function( period, axis ) { var times = [ 0, period ], values = [ 0, 1 ]; axis = axis || 'x'; var trackName = '.scale[' + axis + ']'; var track = new THREE.NumberKeyframeTrack( trackName, times, values ); return new THREE.AnimationClip( null, period, [ track ] ); }; THREE.AnimationClipCreator.CreateShakeAnimation = function( duration, shakeScale ) { var times = [], values = [], tmp = new THREE.Vector3(); for( var i = 0; i < duration * 10; i ++ ) { times.push( i / 10 ); tmp.set( Math.random() * 2.0 - 1.0, Math.random() * 2.0 - 1.0, Math.random() * 2.0 - 1.0 ). multiply( shakeScale ). toArray( values, values.length ); } var trackName = '.position'; var track = new THREE.VectorKeyframeTrack( trackName, times, values ); return new THREE.AnimationClip( null, duration, [ track ] ); }; THREE.AnimationClipCreator.CreatePulsationAnimation = function( duration, pulseScale ) { var times = [], values = [], tmp = new THREE.Vector3(); for( var i = 0; i < duration * 10; i ++ ) { times.push( i / 10 ); var scaleFactor = Math.random() * pulseScale; tmp.set( scaleFactor, scaleFactor, scaleFactor ). toArray( values, values.length ); } var trackName = '.scale'; var track = new THREE.VectorKeyframeTrack( trackName, keys ); return new THREE.AnimationClip( null, duration, [ track ] ); }; THREE.AnimationClipCreator.CreateVisibilityAnimation = function( duration ) { var times = [ 0, duration / 2, duration ], values = [ true, false, true ]; var trackName = '.visible'; var track = new THREE.BooleanKeyframeTrack( trackName, times, values ); return new THREE.AnimationClip( null, duration, [ track ] ); }; THREE.AnimationClipCreator.CreateMaterialColorAnimation = function( duration, colors, loop ) { var times = [], values = [], timeStep = duration / colors.length; for( var i = 0; i <= colors.length; i ++ ) { timees.push( i * timeStep ); values.push( colors[ i % colors.length ] ); } var trackName = '.material[0].color'; var track = new THREE.ColorKeyframeTrack( trackName, times, values ); return new THREE.AnimationClip( null, duration, [ track ] ); };
var Key = require('bindings')('KeyModule').Key; var CommonKey = require('./common/Key'); var bignum = require('bignum'); var Point = require('./Point'); var coinUtil = require('../util'); for (var i in CommonKey) { if (CommonKey.hasOwnProperty(i)) Key[i] = CommonKey[i]; } Key.sign = function(hash, priv, k) { if (k) throw new Error('Deterministic k not supported in node'); var key = new Key(); key.private = priv.toBuffer({size: 32}); var sig = key.signSync(hash); var parsed = Key.parseDERsig(sig); return {r: parsed.r, s: parsed.s}; }; Key.signCompressed = function(hash, priv, k) { var sig = Key.sign(hash, priv, k); var r = sig.r; var s = sig.s; var e = bignum.fromBuffer(hash); var G = Point.getG(); var Q = Point.multiply(G, priv.toBuffer({size: 32})); var i = Key.calcPubKeyRecoveryParam(e, r, s, Q); var rbuf = r.toBuffer({size: 32}); var sbuf = s.toBuffer({size: 32}); var ibuf = new Buffer([i]); var buf = Buffer.concat([ibuf, rbuf, sbuf]); return buf; }; Key.verifyCompressed = function(hash, sigbuf, pubkeyhash) { if (sigbuf.length !== 1 + 32 + 32) throw new Error("Invalid length for sigbuf"); var i = sigbuf[0]; if (i < 0 || i > 3) throw new Error("Invalid value for i"); var rbuf = sigbuf.slice(1, 1 + 32); var sbuf = sigbuf.slice(1 + 32, 1 + 32 + 32); var r = bignum.fromBuffer(rbuf); var s = bignum.fromBuffer(sbuf); var sigDER = Key.rs2DER(r, s); var e = bignum.fromBuffer(hash); var key = new Key(); var pub = Key.recoverPubKey(e, r, s, i); var pubbuf = pub.toCompressedPubKey(); key.public = pubbuf; var pubkeyhash2 = coinUtil.sha256ripe160(pubbuf); if (pubkeyhash2.toString('hex') !== pubkeyhash.toString('hex')) { return false; } return key.verifySignatureSync(hash, sigDER); }; module.exports = Key;
/** * @author TristanVALCKE / https://github.com/TristanVALCKE */ //Todo console.warn("Todo: Unit tests of AxisHelper")
define("ace/snippets/crystal",["require","exports","module"],function(e,t,n){"use strict";t.snippetText=undefined,t.scope="crystal"}); (function() { window.require(["ace/snippets/crystal"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
import Component from 'flarum/Component'; import Button from 'flarum/components/Button'; import listItems from 'flarum/helpers/listItems'; import extract from 'flarum/utils/extract'; /** * The `Alert` component represents an alert box, which contains a message, * some controls, and may be dismissible. * * The alert may have the following special props: * * - `type` The type of alert this is. Will be used to give the alert a class * name of `Alert--{type}`. * - `controls` An array of controls to show in the alert. * - `dismissible` Whether or not the alert can be dismissed. * - `ondismiss` A callback to run when the alert is dismissed. * * All other props will be assigned as attributes on the alert element. */ export default class Alert extends Component { view() { const attrs = Object.assign({}, this.props); const type = extract(attrs, 'type'); attrs.className = 'Alert Alert--' + type + ' ' + (attrs.className || ''); const children = extract(attrs, 'children'); const controls = extract(attrs, 'controls') || []; // If the alert is meant to be dismissible (which is the case by default), // then we will create a dismiss button to append as the final control in // the alert. const dismissible = extract(attrs, 'dismissible'); const ondismiss = extract(attrs, 'ondismiss'); const dismissControl = []; if (dismissible || dismissible === undefined) { dismissControl.push( <Button icon="times" className="Button Button--link Button--icon Alert-dismiss" onclick={ondismiss}/> ); } return ( <div {...attrs}> <span className="Alert-body"> {children} </span> <ul className="Alert-controls"> {listItems(controls.concat(dismissControl))} </ul> </div> ); } }
/** * @file Data zoom model */ define(function(require) { var DataZoomModel = require('./DataZoomModel'); var SliderZoomModel = DataZoomModel.extend({ type: 'dataZoom.slider', layoutMode: 'box', /** * @protected */ defaultOption: { show: true, // ph => placeholder. Using placehoder here because // deault value can only be drived in view stage. right: 'ph', // Default align to grid rect. top: 'ph', // Default align to grid rect. width: 'ph', // Default align to grid rect. height: 'ph', // Default align to grid rect. left: null, // Default align to grid rect. bottom: null, // Default align to grid rect. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box, // highest priority, remain for compatibility of // previous version, but not recommended any more. dataBackground: { lineStyle: { color: '#2f4554', width: 0.5, opacity: 0.3 }, areaStyle: { color: 'rgba(47,69,84,0.3)', opacity: 0.3 } }, borderColor: '#ddd', // border color of the box. For compatibility, // if dataBackgroundColor is set, borderColor // is ignored. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle. // handleIcon: 'path://M4.9,17.8c0-1.4,4.5-10.5,5.5-12.4c0-0.1,0.6-1.1,0.9-1.1c0.4,0,0.9,1,0.9,1.1c1.1,2.2,5.4,11,5.4,12.4v17.8c0,1.5-0.6,2.1-1.3,2.1H6.1c-0.7,0-1.3-0.6-1.3-2.1V17.8z', handleIcon: 'M8.2,13.6V3.9H6.3v9.7H3.1v14.9h3.3v9.7h1.8v-9.7h3.3V13.6H8.2z M9.7,24.4H4.8v-1.4h4.9V24.4z M9.7,19.1H4.8v-1.4h4.9V19.1z', // Percent of the slider height handleSize: '100%', handleStyle: { color: '#a7b7cc' }, labelPrecision: null, labelFormatter: null, showDetail: true, showDataShadow: 'auto', // Default auto decision. realtime: true, zoomLock: false, // Whether disable zoom. textStyle: { color: '#333' } } }); return SliderZoomModel; });
/** * Disallows space before `()` or `{}` in function expressions (both [named](#disallowspacesinnamedfunctionexpression) * and [anonymous](#disallowspacesinanonymousfunctionexpression)). * * Type: `Object` * * Values: `"beforeOpeningRoundBrace"` and `"beforeOpeningCurlyBrace"` as child properties. * Child properties must be set to `true`. * * #### Example * * ```js * "disallowSpacesInFunctionExpression": { * "beforeOpeningRoundBrace": true, * "beforeOpeningCurlyBrace": true * } * ``` * * ##### Valid * * ```js * var x = function(){}; * var x = function a(){}; * ``` * * ##### Invalid * * ```js * var x = function () {}; * var x = function a (){}; * ``` */ var assert = require('assert'); module.exports = function() {}; module.exports.prototype = { configure: function(options) { assert( typeof options === 'object', 'disallowSpacesInFunctionExpression option must be the object' ); if ('beforeOpeningRoundBrace' in options) { assert( options.beforeOpeningRoundBrace === true, 'disallowSpacesInFunctionExpression.beforeOpeningRoundBrace ' + 'property requires true value or should be removed' ); } if ('beforeOpeningCurlyBrace' in options) { assert( options.beforeOpeningCurlyBrace === true, 'disallowSpacesInFunctionExpression.beforeOpeningCurlyBrace ' + 'property requires true value or should be removed' ); } assert( options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace, 'disallowSpacesInFunctionExpression must have beforeOpeningCurlyBrace or beforeOpeningRoundBrace property' ); this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace); this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace); }, getOptionName: function() { return 'disallowSpacesInFunctionExpression'; }, check: function(file, errors) { var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace; var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace; var tokens = file.getTokens(); file.iterateNodesByType('FunctionExpression', function(node) { var parent = node.parentNode; // Ignore syntactic sugar for getters and setters. if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) { return; } if (beforeOpeningRoundBrace) { var nodeBeforeRoundBrace = node; // named function if (node.id) { nodeBeforeRoundBrace = node.id; } var functionTokenPos = file.getTokenPosByRangeStart(nodeBeforeRoundBrace.range[0]); var functionToken = tokens[functionTokenPos]; var nextTokenPos = file.getTokenPosByRangeStart(functionToken.range[1]); var nextToken = tokens[nextTokenPos]; if (!nextToken) { errors.add( 'Illegal space before opening round brace', functionToken.loc.start ); } } if (beforeOpeningCurlyBrace) { var tokenBeforeBodyPos = file.getTokenPosByRangeStart(node.body.range[0] - 1); var tokenBeforeBody = tokens[tokenBeforeBodyPos]; if (!tokenBeforeBody) { errors.add( 'Illegal space before opening curly brace', node.body.loc.start ); } } }); } };
if (exports) { var fs = require('fs'); var jsdom = require('jsdom'); var html = fs.readFileSync('./test/index.html', 'utf-8'); window = jsdom.jsdom(html).parentWindow; var Slideout = require('../'); var assert = require('better-assert'); } var doc = window.document; var beforeopenEvent = false; var openEvent = false; var beforecloseEvent = false; var closeEvent = false; var slideout = new Slideout({ 'panel': doc.getElementById('panel'), 'menu': doc.getElementById('menu') }); slideout .on('beforeopen', function() { beforeopenEvent = true; }) .on('open', function() { openEvent = true; }) .on('beforeclose', function() { beforecloseEvent = true; }) .on('close', function() { closeEvent = true; }); describe('Slideout', function () { it('should be defined.', function () { assert(Slideout !== undefined); }); it('should be a function.', function () { assert(typeof Slideout === 'function'); }); it('should return a new instance.', function () { assert(slideout instanceof Slideout); }); describe('should have the following methods:', function () { var methods = [ 'open', 'close', 'toggle', 'isOpen', '_initTouchEvents', '_translateXTo', '_setTransition', 'on', 'once', 'off', 'emit' ]; var i = 0; var len = methods.length; for (i; i < len; i += 1) { (function (i) { it('.' + methods[i] + '()', function (done) { assert(typeof slideout[methods[i]] === 'function'); done() }); }(i)); } }); describe('should define the following properties:', function () { var properties = [ 'panel', 'menu', '_startOffsetX', '_currentOffsetX', '_opening', '_moved', '_opened', '_fx', '_duration', '_tolerance', '_padding', '_touch' ]; var i = 0; var len = properties.length; for (i; i < len; i += 1) { (function (i) { it('.' + properties[i] + '()', function (done) { assert(slideout[properties[i]] !== undefined); done() }); }(i)); } }); it('should add classnames to panel and menu DOM elements.', function () { assert(slideout.panel.className.search('slideout-panel') !== -1); assert(slideout.menu.className.search('slideout-menu') !== -1); }); describe('.open()', function () { it('should add "slideout-open" classname to HTML.', function () { assert(doc.documentElement.className.search('slideout-open') === -1); slideout.open(); assert(doc.documentElement.className.search('slideout-open') !== -1); }); it('should translateX the panel to the given padding.', function () { var translate3d = exports ? 'translate3d(256px, 0, 0)' : 'translate3d(256px, 0px, 0px)'; assert(slideout.panel.style.transform === translate3d); assert(slideout.panel.style.transition.search(/transform 300ms ease/) !== -1); }); it('should set _opened to true.', function () { assert(slideout._opened === true); }); it('should emit "beforeopen" event.', function () { assert(beforeopenEvent === true); }); it('should emit "open" event.', function (done) { setTimeout(function(){ assert(openEvent === true); done(); }, 400); }); }); describe('.isOpen()', function () { it('should return true if the slideout is opened.', function () { assert(slideout.isOpen()); }); }); describe('.close()', function () { it('should remove "slideout-open" classname to HTML.', function (done) { assert(doc.documentElement.className.search('slideout-open') !== -1); slideout.close(); setTimeout(function(){ assert(doc.documentElement.className.search('slideout-open') === -1); done(); }, 350); }); it('should translateX the panel to 0.', function () { assert(slideout.panel.style.transform === ''); assert(slideout.panel.style.transition === ''); }); it('should set _opened to false.', function () { assert(slideout._opened === false); }); it('should emit "beforeclose" event.', function () { assert(beforecloseEvent === true); }); it('should emit "close" event.', function () { assert(closeEvent === true); }); }); describe('.toggle()', function () { it('should show the slideout if it is not opened.', function (done) { assert(doc.documentElement.className.search('slideout-open') === -1); slideout.toggle(); assert(doc.documentElement.className.search('slideout-open') !== -1); slideout.toggle(); setTimeout(function(){ assert(doc.documentElement.className.search('slideout-open') === -1); done() }, 350); }); }); });
'use strict'; /** * @ngdoc filter * @name linky * @kind function * * @description * Finds links in text input and turns them into html links. Supports `http/https/ftp/mailto` and * plain email address links. * * Requires the {@link ngSanitize `ngSanitize`} module to be installed. * * @param {string} text Input text. * @param {string} target Window (`_blank|_self|_parent|_top`) or named frame to open links in. * @param {object|function(url)} [attributes] Add custom attributes to the link element. * * Can be one of: * * - `object`: A map of attributes * - `function`: Takes the url as a parameter and returns a map of attributes * * If the map of attributes contains a value for `target`, it overrides the value of * the target parameter. * * * @returns {string} Html-linkified and {@link $sanitize sanitized} text. * * @usage <span ng-bind-html="linky_expression | linky"></span> * * @example <example module="linkyExample" deps="angular-sanitize.js" name="linky-filter"> <file name="index.html"> <div ng-controller="ExampleController"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <th>Filter</th> <th>Source</th> <th>Rendered</th> </tr> <tr id="linky-filter"> <td>linky filter</td> <td> <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippet | linky"></div> </td> </tr> <tr id="linky-target"> <td>linky target</td> <td> <pre>&lt;div ng-bind-html="snippetWithSingleURL | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippetWithSingleURL | linky:'_blank'"></div> </td> </tr> <tr id="linky-custom-attributes"> <td>linky custom attributes</td> <td> <pre>&lt;div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> </table> </file> <file name="script.js"> angular.module('linkyExample', ['ngSanitize']) .controller('ExampleController', ['$scope', function($scope) { $scope.snippet = 'Pretty text with some links:\n' + 'http://angularjs.org/,\n' + 'mailto:us@somewhere.org,\n' + 'another@somewhere.org,\n' + 'and one more: ftp://127.0.0.1/.'; $scope.snippetWithSingleURL = 'http://angularjs.org/'; }]); </file> <file name="protractor.js" type="protractor"> it('should linkify the snippet with urls', function() { expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#linky-filter a')).count()).toEqual(4); }); it('should not linkify snippet without the linky filter', function() { expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()). toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#escaped-html a')).count()).toEqual(0); }); it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new http://link.'); expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). toBe('new http://link.'); expect(element.all(by.css('#linky-filter a')).count()).toEqual(1); expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()) .toBe('new http://link.'); }); it('should work with the target property', function() { expect(element(by.id('linky-target')). element(by.binding("snippetWithSingleURL | linky:'_blank'")).getText()). toBe('http://angularjs.org/'); expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank'); }); it('should optionally add custom attributes', function() { expect(element(by.id('linky-custom-attributes')). element(by.binding("snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}")).getText()). toBe('http://angularjs.org/'); expect(element(by.css('#linky-custom-attributes a')).getAttribute('rel')).toEqual('nofollow'); }); </file> </example> */ angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) { var LINKY_URL_REGEXP = /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i, MAILTO_REGEXP = /^mailto:/i; var linkyMinErr = angular.$$minErr('linky'); var isDefined = angular.isDefined; var isFunction = angular.isFunction; var isObject = angular.isObject; var isString = angular.isString; return function(text, target, attributes) { if (text == null || text === '') return text; if (!isString(text)) throw linkyMinErr('notstring', 'Expected string but received: {0}', text); var attributesFn = isFunction(attributes) ? attributes : isObject(attributes) ? function getAttributesObject() {return attributes;} : function getEmptyAttributesObject() {return {};}; var match; var raw = text; var html = []; var url; var i; while ((match = raw.match(LINKY_URL_REGEXP))) { // We can not end in these as they are sometimes found at the end of the sentence url = match[0]; // if we did not match ftp/http/www/mailto then assume mailto if (!match[2] && !match[4]) { url = (match[3] ? 'http://' : 'mailto:') + url; } i = match.index; addText(raw.substr(0, i)); addLink(url, match[0].replace(MAILTO_REGEXP, '')); raw = raw.substring(i + match[0].length); } addText(raw); return $sanitize(html.join('')); function addText(text) { if (!text) { return; } html.push(sanitizeText(text)); } function addLink(url, text) { var key, linkAttributes = attributesFn(url); html.push('<a '); for (key in linkAttributes) { html.push(key + '="' + linkAttributes[key] + '" '); } if (isDefined(target) && !('target' in linkAttributes)) { html.push('target="', target, '" '); } html.push('href="', url.replace(/"/g, '&quot;'), '">'); addText(text); html.push('</a>'); } }; }]);
(function(window, document){ var _shimCounter = 0; function Rollbar(parentShim) { this.shimId = ++_shimCounter; this.notifier = null; this.parentShim = parentShim; this.logger = function() {}; if (window.console) { if (window.console.shimId === undefined) { this.logger = window.console.log; } } } function _rollbarWindowOnError(client, old, args) { if (!args[4] && window._rollbarWrappedError) { args[4] = window._rollbarWrappedError; window._rollbarWrappedError = null; } client.uncaughtError.apply(client, args); if (old) { old.apply(window, args); } } Rollbar.init = function(window, config) { var alias = config.globalAlias || 'Rollbar'; if (typeof window[alias] === 'object') { return window[alias]; } // Expose the global shim queue window._rollbarShimQueue = []; window._rollbarWrappedError = null; config = config || {}; var client = new Rollbar(); return (_wrapInternalErr(function() { client.configure(config); if (config.captureUncaught) { // Create the client and set the onerror handler var old = window.onerror; window.onerror = function() { var args = Array.prototype.slice.call(arguments, 0); _rollbarWindowOnError(client, old, args); }; // Adapted from https://github.com/bugsnag/bugsnag-js var globals = ['EventTarget', 'Window', 'Node', 'ApplicationCache', 'AudioTrackList', 'ChannelMergerNode', 'CryptoOperation', 'EventSource', 'FileReader', 'HTMLUnknownElement', 'IDBDatabase', 'IDBRequest', 'IDBTransaction', 'KeyOperation', 'MediaController', 'MessagePort', 'ModalWindow', 'Notification', 'SVGElementInstance', 'Screen', 'TextTrack', 'TextTrackCue', 'TextTrackList', 'WebSocket', 'WebSocketWorker', 'Worker', 'XMLHttpRequest', 'XMLHttpRequestEventTarget', 'XMLHttpRequestUpload']; var i; var global; for (i = 0; i < globals.length; ++i) { global = globals[i]; if (window[global] && window[global].prototype) { _extendListenerPrototype(client, window[global].prototype); } } } // Expose Rollbar globally window[alias] = client; return client; }, client.logger))(); }; Rollbar.prototype.loadFull = function(window, document, immediate, config) { var self = this; // Create the main rollbar script loader var loader = _wrapInternalErr(function() { var s = document.createElement("script"); var f = document.getElementsByTagName("script")[0]; s.src = config.rollbarJsUrl; s.async = !immediate; // NOTE(cory): this may not work for some versions of IE s.onload = handleLoadErr; f.parentNode.insertBefore(s, f); }, this.logger); var handleLoadErr = _wrapInternalErr(function() { if (window._rollbarPayloadQueue === undefined) { // rollbar.js did not load correctly, call any queued callbacks // with an error. var obj; var cb; var args; var i; var err = new Error('rollbar.js did not load'); // Go through each of the shim objects. If one of their args // was a function, treat it as the callback and call it with // err as the first arg. while ((obj = window._rollbarShimQueue.shift())) { args = obj.args; for (i = 0; i < args.length; ++i) { cb = args[i]; if (typeof cb === 'function') { cb(err); break; } } } } }, this.logger); (_wrapInternalErr(function() { if (immediate) { loader(); } else { // Have the window load up the script ASAP if (window.addEventListener) { window.addEventListener("load", loader, false); } else { window.attachEvent("onload", loader); } } }, this.logger))(); }; Rollbar.prototype.wrap = function(f) { try { var _this = this; if (typeof f !== 'function') { return f; } if (f._isWrap) { return f; } if (!f._wrapped) { f._wrapped = function () { try { return f.apply(this, arguments); } catch(e) { window._rollbarWrappedError = e; throw e; } }; f._wrapped._isWrap = true; for (var prop in f) { if (f.hasOwnProperty(prop)) { f._wrapped[prop] = f[prop]; } } } return f._wrapped; } catch (e) { // Try-catch here is to work around issue where wrap() fails when used inside Selenium. // Return the original function if the wrap fails. return f; } }; // Stub out rollbar.js methods function stub(method) { var R = Rollbar; return _wrapInternalErr(function() { if (this.notifier) { return this.notifier[method].apply(this.notifier, arguments); } else { var shim = this; var isScope = method === 'scope'; if (isScope) { shim = new R(this); } var args = Array.prototype.slice.call(arguments, 0); var data = {shim: shim, method: method, args: args, ts: new Date()}; window._rollbarShimQueue.push(data); if (isScope) { return shim; } } }); } function _extendListenerPrototype(client, prototype) { if (prototype.hasOwnProperty && prototype.hasOwnProperty('addEventListener')) { var oldAddEventListener = prototype.addEventListener; prototype.addEventListener = function(event, callback, bubble) { oldAddEventListener.call(this, event, client.wrap(callback), bubble); }; var oldRemoveEventListener = prototype.removeEventListener; prototype.removeEventListener = function(event, callback, bubble) { oldRemoveEventListener.call(this, event, (callback && callback._wrapped) ? callback._wrapped : callback, bubble); }; } } function _wrapInternalErr(f, logger) { logger = logger || this.logger; return function() { try { return f.apply(this, arguments); } catch (e) { logger('Rollbar internal error:', e); } }; } var _methods = 'log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError'.split(','); for (var i = 0; i < _methods.length; ++i) { Rollbar.prototype[_methods[i]] = stub(_methods[i]); } var defaultRollbarJsUrl = '//d37gvrvc0wt4s1.cloudfront.net/js/v1.1/rollbar.min.js'; _rollbarConfig.rollbarJsUrl = _rollbarConfig.rollbarJsUrl || defaultRollbarJsUrl; var r = Rollbar.init(window, _rollbarConfig); r.loadFull(window, document, false, _rollbarConfig); })(window, document);
'use strict'; // Define module using Universal Module Definition pattern // https://github.com/umdjs/umd/blob/master/returnExports.js (function (root, factory) { if (typeof define === 'function' && define.amd) { // Support AMD. Register as an anonymous module. // EDIT: List all dependencies in AMD style define(['d3', 'd3kit', 'labella'], factory); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. // EDIT: Pass dependencies to factory function module.exports = factory(require('d3'), require('d3kit'), require('labella')); } else { // No AMD. Set module as a global variable // EDIT: Pass dependencies to factory function root.d3Kit = factory(root.d3, root.d3Kit, root.labella); } }(this, //EDIT: The dependencies are passed to this function function (d3, d3Kit, labella) { //--------------------------------------------------- // BEGIN code for this module //--------------------------------------------------- var DEFAULT_OPTIONS = { margin: {left: 40, right: 20, top: 20, bottom: 20}, initialWidth: 400, initialHeight: 400, scale: d3.time.scale(), domain: undefined, direction: 'right', dotRadius: 3, layerGap: 60, labella: {}, keyFn: undefined, timeFn: function(d){return d.time;}, textFn: function(d){return d.text;}, dotColor: '#222', labelBgColor: '#222', labelTextColor: '#fff', linkColor: '#222', labelPadding: {left: 4, right: 4, top: 3, bottom: 2}, textYOffset: '0.85em' }; var CUSTOM_EVENTS = [ 'dotClick', 'dotMouseover', 'dotMousemove', 'dotMouseout', 'labelClick', 'labelMouseover', 'labelMousemove', 'labelMouseout' ]; d3Kit.Timeline = d3Kit.factory.createChart(DEFAULT_OPTIONS, CUSTOM_EVENTS, function constructor(skeleton){ // alias var options = skeleton.options(); var dispatch = skeleton.getDispatcher(); var layers = skeleton.getLayerOrganizer(); layers.create(['dummy', {main:['axis', 'link', 'label', 'dot']}]); var force = new labella.Force(options.labella); var axis = d3.svg.axis(); function rectWidth(d){ return d.w; } function rectHeight(d){ return d.h; } function timePos(d){ return options.scale(options.timeFn(d)); } dispatch.on('resize', visualize); dispatch.on('options', visualize); dispatch.on('data', visualize); layers.get('main.axis').classed('axis', true); function visualize(){ if(!skeleton.hasData()) return; var data = skeleton.data(); if(options.domain){ options.scale.domain(options.domain); } else{ options.scale.domain(d3.extent(data, options.timeFn)) .nice(); } options.scale.range([0, (options.direction==='left' || options.direction==='right') ? skeleton.getInnerHeight() : skeleton.getInnerWidth()]); axis.scale(options.scale); var axisTransform; switch(options.direction){ case 'right': axis.orient('left'); axisTransform = 'translate('+(0)+','+(0)+')'; break; case 'left': axis.orient('right'); axisTransform ='translate('+(skeleton.getInnerWidth())+','+(0)+')'; break; case 'up': axis.orient('bottom'); axisTransform ='translate('+(0)+','+(skeleton.getInnerHeight())+')'; break; case 'down': axis.orient('top'); axisTransform = 'translate('+(0)+','+(0)+')'; break; } layers.get('main') .attr('transform', axisTransform); layers.get('main.axis') .call(axis); drawDots(data); var dummyText = layers.get('dummy').append('text') .classed('label-text', true); var nodes = data.map(function(d){ var bbox = dummyText.text(options.textFn(d))[0][0].getBBox(); var w = bbox.width + options.labelPadding.left + options.labelPadding.right; var h = bbox.height + options.labelPadding.top + options.labelPadding.bottom; var node = new labella.Node( timePos(d), (options.direction==='left' || options.direction==='right') ? h : w, d ); node.w = w; node.h = h; return node; }); dummyText.remove(); force.options(options.labella) .nodes(nodes) .compute(); drawLabels(force.nodes()); } function drawDots(data){ var selection = layers.get('main.dot').selectAll('circle.dot') .data(data, options.keyFn); var field = (options.direction==='left' || options.direction==='right') ? 'cy' : 'cx'; selection.enter().append('circle') .classed('dot', true) .on('click', function(d, i){ dispatch.dotClick(d, i); }) .on('mouseover', function(d, i){ dispatch.dotMouseover(d, i); }) .on('mousemove', function(d, i){ dispatch.dotMousemove(d, i); }) .on('mouseout', function(d, i){ dispatch.dotMouseout(d, i); }) .style('fill', options.dotColor) .attr('r', options.dotRadius) .attr(field, timePos); selection.transition() .style('fill', options.dotColor) .attr('r', options.dotRadius) .attr(field, timePos); selection.exit().remove(); } function drawLabels(nodes){ var nodeHeight; if(options.direction==='left' || options.direction==='right'){ nodeHeight = d3.max(nodes, rectWidth); } else{ nodeHeight = d3.max(nodes, rectHeight); } var renderer = new labella.Renderer({ nodeHeight: nodeHeight, layerGap: options.layerGap, direction: options.direction }); renderer.layout(nodes); function nodePos(d){ switch(options.direction){ case 'right': return 'translate('+(d.x)+','+(d.y-d.dy/2)+')'; case 'left': return 'translate('+(d.x + nodeHeight - d.w)+','+(d.y-d.dy/2)+')'; case 'up': return 'translate('+(d.x-d.dx/2)+','+(d.y)+')'; case 'down': return 'translate('+(d.x-d.dx/2)+','+(d.y)+')'; } } var labelBgColor = d3.functor(options.labelBgColor); var labelTextColor = d3.functor(options.labelTextColor); var linkColor = d3.functor(options.linkColor); // Draw label rectangles var selection = layers.get('main.label').selectAll('g.label-g') .data(nodes, options.keyFn ? function(d){return options.keyFn(d.data);} : undefined); var sEnter = selection.enter().append('g') .classed('label-g', true) .on('click', function(d, i){ dispatch.labelClick(d.data, i); }) .on('mouseover', function(d, i){ dispatch.labelMouseover(d.data, i); }) .on('mousemove', function(d, i){ dispatch.labelMousemove(d.data, i); }) .on('mouseout', function(d, i){ dispatch.labelMouseout(d.data, i); }) .attr('transform', nodePos); sEnter .append('rect') .classed('label-bg', true) .attr('rx', 2) .attr('ry', 2) .attr('width', rectWidth) .attr('height', rectHeight) .style('fill', function(d){return labelBgColor(d.data);}); sEnter.append('text') .classed('label-text', true) .attr('dy', options.textYOffset) .attr('x', options.labelPadding.left) .attr('y', options.labelPadding.top) .style('fill', function(d){return labelTextColor(d.data);}) .text(function(d){return options.textFn(d.data);}); var sTrans = selection.transition() .attr('transform', nodePos); sTrans.select('rect') .attr('width', rectWidth) .attr('height', rectHeight) .style('fill', function(d){return labelBgColor(d.data);}); sTrans.select('text.label-text') .attr('dy', options.textYOffset) .attr('x', options.labelPadding.left) .attr('y', options.labelPadding.top) .style('fill', function(d){return labelTextColor(d.data);}) .text(function(d){return options.textFn(d.data);}); selection.exit().remove(); // Draw path from point on the timeline to the label rectangle var paths = layers.get('main.link').selectAll('path.link') .data(nodes, options.keyFn ? function(d){return options.keyFn(d.data);} : undefined); paths.enter().append('path') .classed('link', true) .attr('d', function(d){return renderer.generatePath(d);}) .style('stroke', function(d){return linkColor(d.data);}) .style('fill', 'none'); paths.transition() .style('stroke', function(d){return linkColor(d.data);}) .attr('d', function(d){return renderer.generatePath(d);}); paths.exit().remove(); } return skeleton.mixin({ axis: axis, visualize: visualize }); }); return d3Kit; //--------------------------------------------------- // END code for this module //--------------------------------------------------- }));
import {types as tt} from "./tokentype" import {Parser} from "./state" import {lineBreak, skipWhiteSpace} from "./whitespace" import {isIdentifierStart, isIdentifierChar} from "./identifier" import {DestructuringErrors} from "./parseutil" const pp = Parser.prototype // ### Statement parsing // Parse a program. Initializes the parser, reads any number of // statements, and wraps them in a Program node. Optionally takes a // `program` argument. If present, the statements will be appended // to its body instead of creating a new node. pp.parseTopLevel = function(node) { let first = true if (!node.body) node.body = [] while (this.type !== tt.eof) { let stmt = this.parseStatement(true, true) node.body.push(stmt) if (first) { if (this.isUseStrict(stmt)) this.setStrict(true) first = false } } this.next() if (this.options.ecmaVersion >= 6) { node.sourceType = this.options.sourceType } return this.finishNode(node, "Program") } const loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"} pp.isLet = function() { if (this.type !== tt.name || this.options.ecmaVersion < 6 || this.value != "let") return false skipWhiteSpace.lastIndex = this.pos let skip = skipWhiteSpace.exec(this.input) let next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next) if (nextCh === 91 || nextCh == 123) return true // '{' and '[' if (isIdentifierStart(nextCh, true)) { for (var pos = next + 1; isIdentifierChar(this.input.charCodeAt(pos), true); ++pos) {} let ident = this.input.slice(next, pos) if (!this.isKeyword(ident)) return true } return false } // Parse a single statement. // // If expecting a statement and finding a slash operator, parse a // regular expression literal. This is to handle cases like // `if (foo) /blah/.exec(foo)`, where looking at the previous token // does not help. pp.parseStatement = function(declaration, topLevel) { let starttype = this.type, node = this.startNode(), kind if (this.isLet()) { starttype = tt._var kind = "let" } // Most types of statements are recognized by the keyword they // start with. Many are trivial to parse, some require a bit of // complexity. switch (starttype) { case tt._break: case tt._continue: return this.parseBreakContinueStatement(node, starttype.keyword) case tt._debugger: return this.parseDebuggerStatement(node) case tt._do: return this.parseDoStatement(node) case tt._for: return this.parseForStatement(node) case tt._function: if (!declaration && this.options.ecmaVersion >= 6) this.unexpected() return this.parseFunctionStatement(node) case tt._class: if (!declaration) this.unexpected() return this.parseClass(node, true) case tt._if: return this.parseIfStatement(node) case tt._return: return this.parseReturnStatement(node) case tt._switch: return this.parseSwitchStatement(node) case tt._throw: return this.parseThrowStatement(node) case tt._try: return this.parseTryStatement(node) case tt._const: case tt._var: kind = kind || this.value if (!declaration && kind != "var") this.unexpected() return this.parseVarStatement(node, kind) case tt._while: return this.parseWhileStatement(node) case tt._with: return this.parseWithStatement(node) case tt.braceL: return this.parseBlock() case tt.semi: return this.parseEmptyStatement(node) case tt._export: case tt._import: if (!this.options.allowImportExportEverywhere) { if (!topLevel) this.raise(this.start, "'import' and 'export' may only appear at the top level") if (!this.inModule) this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'") } return starttype === tt._import ? this.parseImport(node) : this.parseExport(node) // If the statement does not start with a statement keyword or a // brace, it's an ExpressionStatement or LabeledStatement. We // simply start parsing an expression, and afterwards, if the // next token is a colon and the expression was a simple // Identifier node, we switch to interpreting it as a label. default: let maybeName = this.value, expr = this.parseExpression() if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon)) return this.parseLabeledStatement(node, maybeName, expr) else return this.parseExpressionStatement(node, expr) } } pp.parseBreakContinueStatement = function(node, keyword) { let isBreak = keyword == "break" this.next() if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null else if (this.type !== tt.name) this.unexpected() else { node.label = this.parseIdent() this.semicolon() } // Verify that there is an actual destination to break or // continue to. for (var i = 0; i < this.labels.length; ++i) { let lab = this.labels[i] if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) break if (node.label && isBreak) break } } if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword) return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") } pp.parseDebuggerStatement = function(node) { this.next() this.semicolon() return this.finishNode(node, "DebuggerStatement") } pp.parseDoStatement = function(node) { this.next() this.labels.push(loopLabel) node.body = this.parseStatement(false) this.labels.pop() this.expect(tt._while) node.test = this.parseParenExpression() if (this.options.ecmaVersion >= 6) this.eat(tt.semi) else this.semicolon() return this.finishNode(node, "DoWhileStatement") } // Disambiguating between a `for` and a `for`/`in` or `for`/`of` // loop is non-trivial. Basically, we have to parse the init `var` // statement or expression, disallowing the `in` operator (see // the second parameter to `parseExpression`), and then check // whether the next token is `in` or `of`. When there is no init // part (semicolon immediately after the opening parenthesis), it // is a regular `for` loop. pp.parseForStatement = function(node) { this.next() this.labels.push(loopLabel) this.expect(tt.parenL) if (this.type === tt.semi) return this.parseFor(node, null) let isLet = this.isLet() if (this.type === tt._var || this.type === tt._const || isLet) { let init = this.startNode(), kind = isLet ? "let" : this.value this.next() this.parseVar(init, true, kind) this.finishNode(init, "VariableDeclaration") if ((this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init.declarations.length === 1 && !(kind !== "var" && init.declarations[0].init)) return this.parseForIn(node, init) return this.parseFor(node, init) } let refDestructuringErrors = new DestructuringErrors let init = this.parseExpression(true, refDestructuringErrors) if (this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) { this.checkPatternErrors(refDestructuringErrors, true) this.toAssignable(init) this.checkLVal(init) return this.parseForIn(node, init) } else { this.checkExpressionErrors(refDestructuringErrors, true) } return this.parseFor(node, init) } pp.parseFunctionStatement = function(node) { this.next() return this.parseFunction(node, true) } pp.parseIfStatement = function(node) { this.next() node.test = this.parseParenExpression() node.consequent = this.parseStatement(false) node.alternate = this.eat(tt._else) ? this.parseStatement(false) : null return this.finishNode(node, "IfStatement") } pp.parseReturnStatement = function(node) { if (!this.inFunction && !this.options.allowReturnOutsideFunction) this.raise(this.start, "'return' outside of function") this.next() // In `return` (and `break`/`continue`), the keywords with // optional arguments, we eagerly look for a semicolon or the // possibility to insert one. if (this.eat(tt.semi) || this.insertSemicolon()) node.argument = null else { node.argument = this.parseExpression(); this.semicolon() } return this.finishNode(node, "ReturnStatement") } pp.parseSwitchStatement = function(node) { this.next() node.discriminant = this.parseParenExpression() node.cases = [] this.expect(tt.braceL) this.labels.push(switchLabel) // Statements under must be grouped (by label) in SwitchCase // nodes. `cur` is used to keep the node that we are currently // adding statements to. for (var cur, sawDefault = false; this.type != tt.braceR;) { if (this.type === tt._case || this.type === tt._default) { let isCase = this.type === tt._case if (cur) this.finishNode(cur, "SwitchCase") node.cases.push(cur = this.startNode()) cur.consequent = [] this.next() if (isCase) { cur.test = this.parseExpression() } else { if (sawDefault) this.raiseRecoverable(this.lastTokStart, "Multiple default clauses") sawDefault = true cur.test = null } this.expect(tt.colon) } else { if (!cur) this.unexpected() cur.consequent.push(this.parseStatement(true)) } } if (cur) this.finishNode(cur, "SwitchCase") this.next() // Closing brace this.labels.pop() return this.finishNode(node, "SwitchStatement") } pp.parseThrowStatement = function(node) { this.next() if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) this.raise(this.lastTokEnd, "Illegal newline after throw") node.argument = this.parseExpression() this.semicolon() return this.finishNode(node, "ThrowStatement") } // Reused empty array added for node fields that are always empty. const empty = [] pp.parseTryStatement = function(node) { this.next() node.block = this.parseBlock() node.handler = null if (this.type === tt._catch) { let clause = this.startNode() this.next() this.expect(tt.parenL) clause.param = this.parseBindingAtom() this.checkLVal(clause.param, true) this.expect(tt.parenR) clause.body = this.parseBlock() node.handler = this.finishNode(clause, "CatchClause") } node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null if (!node.handler && !node.finalizer) this.raise(node.start, "Missing catch or finally clause") return this.finishNode(node, "TryStatement") } pp.parseVarStatement = function(node, kind) { this.next() this.parseVar(node, false, kind) this.semicolon() return this.finishNode(node, "VariableDeclaration") } pp.parseWhileStatement = function(node) { this.next() node.test = this.parseParenExpression() this.labels.push(loopLabel) node.body = this.parseStatement(false) this.labels.pop() return this.finishNode(node, "WhileStatement") } pp.parseWithStatement = function(node) { if (this.strict) this.raise(this.start, "'with' in strict mode") this.next() node.object = this.parseParenExpression() node.body = this.parseStatement(false) return this.finishNode(node, "WithStatement") } pp.parseEmptyStatement = function(node) { this.next() return this.finishNode(node, "EmptyStatement") } pp.parseLabeledStatement = function(node, maybeName, expr) { for (let i = 0; i < this.labels.length; ++i) if (this.labels[i].name === maybeName) this.raise(expr.start, "Label '" + maybeName + "' is already declared") let kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null for (let i = this.labels.length - 1; i >= 0; i--) { let label = this.labels[i] if (label.statementStart == node.start) { label.statementStart = this.start label.kind = kind } else break } this.labels.push({name: maybeName, kind: kind, statementStart: this.start}) node.body = this.parseStatement(true) this.labels.pop() node.label = expr return this.finishNode(node, "LabeledStatement") } pp.parseExpressionStatement = function(node, expr) { node.expression = expr this.semicolon() return this.finishNode(node, "ExpressionStatement") } // Parse a semicolon-enclosed block of statements, handling `"use // strict"` declarations when `allowStrict` is true (used for // function bodies). pp.parseBlock = function(allowStrict) { let node = this.startNode(), first = true, oldStrict node.body = [] this.expect(tt.braceL) while (!this.eat(tt.braceR)) { let stmt = this.parseStatement(true) node.body.push(stmt) if (first && allowStrict && this.isUseStrict(stmt)) { oldStrict = this.strict this.setStrict(this.strict = true) } first = false } if (oldStrict === false) this.setStrict(false) return this.finishNode(node, "BlockStatement") } // Parse a regular `for` loop. The disambiguation code in // `parseStatement` will already have parsed the init statement or // expression. pp.parseFor = function(node, init) { node.init = init this.expect(tt.semi) node.test = this.type === tt.semi ? null : this.parseExpression() this.expect(tt.semi) node.update = this.type === tt.parenR ? null : this.parseExpression() this.expect(tt.parenR) node.body = this.parseStatement(false) this.labels.pop() return this.finishNode(node, "ForStatement") } // Parse a `for`/`in` and `for`/`of` loop, which are almost // same from parser's perspective. pp.parseForIn = function(node, init) { let type = this.type === tt._in ? "ForInStatement" : "ForOfStatement" this.next() node.left = init node.right = this.parseExpression() this.expect(tt.parenR) node.body = this.parseStatement(false) this.labels.pop() return this.finishNode(node, type) } // Parse a list of variable declarations. pp.parseVar = function(node, isFor, kind) { node.declarations = [] node.kind = kind for (;;) { let decl = this.startNode() this.parseVarId(decl) if (this.eat(tt.eq)) { decl.init = this.parseMaybeAssign(isFor) } else if (kind === "const" && !(this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { this.unexpected() } else if (decl.id.type != "Identifier" && !(isFor && (this.type === tt._in || this.isContextual("of")))) { this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value") } else { decl.init = null } node.declarations.push(this.finishNode(decl, "VariableDeclarator")) if (!this.eat(tt.comma)) break } return node } pp.parseVarId = function(decl) { decl.id = this.parseBindingAtom() this.checkLVal(decl.id, true) } // Parse a function declaration or literal (depending on the // `isStatement` parameter). pp.parseFunction = function(node, isStatement, allowExpressionBody) { this.initFunction(node) if (this.options.ecmaVersion >= 6) node.generator = this.eat(tt.star) var oldInGen = this.inGenerator this.inGenerator = node.generator if (isStatement || this.type === tt.name) node.id = this.parseIdent() this.parseFunctionParams(node) this.parseFunctionBody(node, allowExpressionBody) this.inGenerator = oldInGen return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression") } pp.parseFunctionParams = function(node) { this.expect(tt.parenL) node.params = this.parseBindingList(tt.parenR, false, false, true) } // Parse a class declaration or literal (depending on the // `isStatement` parameter). pp.parseClass = function(node, isStatement) { this.next() this.parseClassId(node, isStatement) this.parseClassSuper(node) let classBody = this.startNode() let hadConstructor = false classBody.body = [] this.expect(tt.braceL) while (!this.eat(tt.braceR)) { if (this.eat(tt.semi)) continue let method = this.startNode() let isGenerator = this.eat(tt.star) let isMaybeStatic = this.type === tt.name && this.value === "static" this.parsePropertyName(method) method.static = isMaybeStatic && this.type !== tt.parenL if (method.static) { if (isGenerator) this.unexpected() isGenerator = this.eat(tt.star) this.parsePropertyName(method) } method.kind = "method" let isGetSet = false if (!method.computed) { let {key} = method if (!isGenerator && key.type === "Identifier" && this.type !== tt.parenL && (key.name === "get" || key.name === "set")) { isGetSet = true method.kind = key.name key = this.parsePropertyName(method) } if (!method.static && (key.type === "Identifier" && key.name === "constructor" || key.type === "Literal" && key.value === "constructor")) { if (hadConstructor) this.raise(key.start, "Duplicate constructor in the same class") if (isGetSet) this.raise(key.start, "Constructor can't have get/set modifier") if (isGenerator) this.raise(key.start, "Constructor can't be a generator") method.kind = "constructor" hadConstructor = true } } this.parseClassMethod(classBody, method, isGenerator) if (isGetSet) { let paramCount = method.kind === "get" ? 0 : 1 if (method.value.params.length !== paramCount) { let start = method.value.start if (method.kind === "get") this.raiseRecoverable(start, "getter should have no params") else this.raiseRecoverable(start, "setter should have exactly one param") } if (method.kind === "set" && method.value.params[0].type === "RestElement") this.raise(method.value.params[0].start, "Setter cannot use rest params") } } node.body = this.finishNode(classBody, "ClassBody") return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") } pp.parseClassMethod = function(classBody, method, isGenerator) { method.value = this.parseMethod(isGenerator) classBody.body.push(this.finishNode(method, "MethodDefinition")) } pp.parseClassId = function(node, isStatement) { node.id = this.type === tt.name ? this.parseIdent() : isStatement ? this.unexpected() : null } pp.parseClassSuper = function(node) { node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null } // Parses module export declaration. pp.parseExport = function(node) { this.next() // export * from '...' if (this.eat(tt.star)) { this.expectContextual("from") node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() this.semicolon() return this.finishNode(node, "ExportAllDeclaration") } if (this.eat(tt._default)) { // export default ... let parens = this.type == tt.parenL let expr = this.parseMaybeAssign() let needsSemi = true if (!parens && (expr.type == "FunctionExpression" || expr.type == "ClassExpression")) { needsSemi = false if (expr.id) { expr.type = expr.type == "FunctionExpression" ? "FunctionDeclaration" : "ClassDeclaration" } } node.declaration = expr if (needsSemi) this.semicolon() return this.finishNode(node, "ExportDefaultDeclaration") } // export var|const|let|function|class ... if (this.shouldParseExportStatement()) { node.declaration = this.parseStatement(true) node.specifiers = [] node.source = null } else { // export { x, y as z } [from '...'] node.declaration = null node.specifiers = this.parseExportSpecifiers() if (this.eatContextual("from")) { node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() } else { // check for keywords used as local names for (let i = 0; i < node.specifiers.length; i++) { if (this.keywords.test(node.specifiers[i].local.name) || this.reservedWords.test(node.specifiers[i].local.name)) { this.unexpected(node.specifiers[i].local.start) } } node.source = null } this.semicolon() } return this.finishNode(node, "ExportNamedDeclaration") } pp.shouldParseExportStatement = function() { return this.type.keyword || this.isLet() } // Parses a comma-separated list of module exports. pp.parseExportSpecifiers = function() { let nodes = [], first = true // export { x, y as z } [from '...'] this.expect(tt.braceL) while (!this.eat(tt.braceR)) { if (!first) { this.expect(tt.comma) if (this.afterTrailingComma(tt.braceR)) break } else first = false let node = this.startNode() node.local = this.parseIdent(this.type === tt._default) node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local nodes.push(this.finishNode(node, "ExportSpecifier")) } return nodes } // Parses import declaration. pp.parseImport = function(node) { this.next() // import '...' if (this.type === tt.string) { node.specifiers = empty node.source = this.parseExprAtom() } else { node.specifiers = this.parseImportSpecifiers() this.expectContextual("from") node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() } this.semicolon() return this.finishNode(node, "ImportDeclaration") } // Parses a comma-separated list of module imports. pp.parseImportSpecifiers = function() { let nodes = [], first = true if (this.type === tt.name) { // import defaultObj, { x, y as z } from '...' let node = this.startNode() node.local = this.parseIdent() this.checkLVal(node.local, true) nodes.push(this.finishNode(node, "ImportDefaultSpecifier")) if (!this.eat(tt.comma)) return nodes } if (this.type === tt.star) { let node = this.startNode() this.next() this.expectContextual("as") node.local = this.parseIdent() this.checkLVal(node.local, true) nodes.push(this.finishNode(node, "ImportNamespaceSpecifier")) return nodes } this.expect(tt.braceL) while (!this.eat(tt.braceR)) { if (!first) { this.expect(tt.comma) if (this.afterTrailingComma(tt.braceR)) break } else first = false let node = this.startNode() node.imported = this.parseIdent(true) if (this.eatContextual("as")) { node.local = this.parseIdent() } else { node.local = node.imported if (this.isKeyword(node.local.name)) this.unexpected(node.local.start) if (this.reservedWordsStrict.test(node.local.name)) this.raise(node.local.start, "The keyword '" + node.local.name + "' is reserved") } this.checkLVal(node.local, true) nodes.push(this.finishNode(node, "ImportSpecifier")) } return nodes }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { isBlank } from '../facade/lang'; var _DOM = null; export function getDOM() { return _DOM; } export function setDOM(adapter) { _DOM = adapter; } export function setRootDomAdapter(adapter) { if (isBlank(_DOM)) { _DOM = adapter; } } /* tslint:disable:requireParameterType */ /** * Provides DOM operations in an environment-agnostic way. */ export class DomAdapter { constructor() { this.xhrType = null; } /** @deprecated */ getXHR() { return this.xhrType; } /** * Maps attribute names to their corresponding property names for cases * where attribute name doesn't match property name. */ get attrToPropMap() { return this._attrToPropMap; } ; set attrToPropMap(value) { this._attrToPropMap = value; } ; } //# sourceMappingURL=dom_adapter.js.map
"use strict"; describe("isValidNumber:", function() { beforeEach(function() { intlSetup(true); input = $("<input>"); }); afterEach(function() { input.intlTelInput("destroy"); input = null; }); describe("init plugin and call public method isValidNumber", function() { beforeEach(function() { input.intlTelInput({ // we must disable formatting to test with alpha chars autoFormat: false, }); }); it("returns true for: valid intl number", function() { input.intlTelInput("setNumber", "+44 7733 123456"); expect(input.intlTelInput("isValidNumber")).toBeTruthy(); }); it("returns false for: invalid intl number", function() { input.intlTelInput("setNumber", "+44 7733 123"); expect(input.intlTelInput("isValidNumber")).toBeFalsy(); }); /*it("returns false for: valid intl number containing alpha chars", function() { input.intlTelInput("setNumber", "+44 7733 123 abc"); expect(input.intlTelInput("isValidNumber")).toBeFalsy(); });*/ }); describe("init plugin with nationalMode=true and call public method isValidNumber", function() { beforeEach(function() { input.intlTelInput({ nationalMode: true }); }); it("returns false for: incorrect selected country, valid number", function() { input.intlTelInput("setNumber", "07733 123456"); expect(input.intlTelInput("isValidNumber")).toBeFalsy(); }); it("returns true for: correct selected country, valid number", function() { input.intlTelInput("selectCountry", "gb"); input.intlTelInput("setNumber", "07733 123456"); expect(input.intlTelInput("isValidNumber")).toBeTruthy(); }); it("returns false for: correct selected country, invalid number", function() { input.intlTelInput("selectCountry", "gb"); input.intlTelInput("setNumber", "07733 123"); expect(input.intlTelInput("isValidNumber")).toBeFalsy(); }); }); });
import { generateUtilityClass, generateUtilityClasses } from '@material-ui/unstyled'; export function getPopoverUtilityClass(slot) { return generateUtilityClass('MuiPopover', slot); } const popoverClasses = generateUtilityClasses('MuiPopover', ['root', 'paper']); export default popoverClasses;
/*! jssocials - v1.2.1 - 2016-04-10 * http://js-socials.com * Copyright (c) 2016 Artem Tabalin; Licensed MIT */ (function(window, $, undefined) { var JSSOCIALS = "JSSocials", JSSOCIALS_DATA_KEY = JSSOCIALS; var getOrApply = function(value, context) { if($.isFunction(value)) { return value.apply(context, $.makeArray(arguments).slice(2)); } return value; }; var IMG_SRC_REGEX = /(\.(jpeg|png|gif|bmp)$|^data:image\/(jpeg|png|gif|bmp);base64)/i; var URL_PARAMS_REGEX = /(&?[a-zA-Z0-9]+=)?\{([a-zA-Z0-9]+)\}/g; var MEASURES = { "G": 1000000000, "M": 1000000, "K": 1000 }; var shares = {}; function Socials(element, config) { var $element = $(element); $element.data(JSSOCIALS_DATA_KEY, this); this._$element = $element; this.shares = []; this._init(config); this._render(); } Socials.prototype = { url: "", text: "", shareIn: "blank", showLabel: function(screenWidth) { return (this.showCount === false) ? (screenWidth > this.smallScreenWidth) : (screenWidth >= this.largeScreenWidth); }, showCount: function(screenWidth) { return (screenWidth <= this.smallScreenWidth) ? "inside" : true; }, smallScreenWidth: 640, largeScreenWidth: 1024, resizeTimeout: 200, elementClass: "jssocials", sharesClass: "jssocials-shares", shareClass: "jssocials-share", shareButtonClass: "jssocials-share-button", shareLinkClass: "jssocials-share-link", shareLogoClass: "jssocials-share-logo", shareLabelClass: "jssocials-share-label", shareLinkCountClass: "jssocials-share-link-count", shareCountBoxClass: "jssocials-share-count-box", shareCountClass: "jssocials-share-count", shareZeroCountClass: "jssocials-share-no-count", _init: function(config) { this._initDefaults(); $.extend(this, config); this._initShares(); this._attachWindowResizeCallback(); }, _initDefaults: function() { this.url = window.location.href; this.text = $.trim($("meta[name=description]").attr("content") || $("title").text()); }, _initShares: function() { this.shares = $.map(this.shares, $.proxy(function(shareConfig) { if(typeof shareConfig === "string") { shareConfig = { share: shareConfig }; } var share = (shareConfig.share && shares[shareConfig.share]); if(!share && !shareConfig.renderer) { throw Error("Share '" + shareConfig.share + "' is not found"); } return $.extend({ url: this.url, text: this.text }, share, shareConfig); }, this)); }, _attachWindowResizeCallback: function() { $(window).on("resize", $.proxy(this._windowResizeHandler, this)); }, _detachWindowResizeCallback: function() { $(window).off("resize", this._windowResizeHandler); }, _windowResizeHandler: function() { if($.isFunction(this.showLabel) || $.isFunction(this.showCount)) { window.clearTimeout(this._resizeTimer); this._resizeTimer = setTimeout($.proxy(this.refresh, this), this.resizeTimeout); } }, _render: function() { this._clear(); this._defineOptionsByScreen(); this._$element.addClass(this.elementClass); this._$shares = $("<div>").addClass(this.sharesClass) .appendTo(this._$element); this._renderShares(); }, _defineOptionsByScreen: function() { this._screenWidth = $(window).width(); this._showLabel = getOrApply(this.showLabel, this, this._screenWidth); this._showCount = getOrApply(this.showCount, this, this._screenWidth); }, _renderShares: function() { $.each(this.shares, $.proxy(function(_, share) { this._renderShare(share); }, this)); }, _renderShare: function(share) { var $share; if($.isFunction(share.renderer)) { $share = $(share.renderer()); } else { $share = this._createShare(share); } $share.addClass(this.shareClass) .addClass(share.share ? "jssocials-share-" + share.share : "") .addClass(share.css) .appendTo(this._$shares); }, _createShare: function(share) { var $result = $("<div>"); var $shareLink = this._createShareLink(share).appendTo($result); if(this._showCount) { var isInsideCount = (this._showCount === "inside"); var $countContainer = isInsideCount ? $shareLink : $("<div>").addClass(this.shareCountBoxClass).appendTo($result); $countContainer.addClass(isInsideCount ? this.shareLinkCountClass : this.shareCountBoxClass); this._renderShareCount(share, $countContainer); } return $result; }, _createShareLink: function(share) { var shareStrategy = this._getShareStrategy(share); var $result = shareStrategy.call(share, { shareUrl: this._getShareUrl(share) }); $result.addClass(this.shareLinkClass) .append(this._createShareLogo(share)); if(this._showLabel) { $result.append(this._createShareLabel(share)); } $.each(this.on || {}, function(event, handler) { if($.isFunction(handler)) { $result.on(event, $.proxy(handler, share)); } }); return $result; }, _getShareStrategy: function(share) { var result = shareStrategies[share.shareIn || this.shareIn]; if(!result) throw Error("Share strategy '" + this.shareIn + "' not found"); return result; }, _getShareUrl: function(share) { var shareUrl = getOrApply(share.shareUrl, share); return this._formatShareUrl(shareUrl, share); }, _createShareLogo: function(share) { var logo = share.logo; var $result = IMG_SRC_REGEX.test(logo) ? $("<img>").attr("src", share.logo) : $("<i>").addClass(logo); $result.addClass(this.shareLogoClass); return $result; }, _createShareLabel: function(share) { return $("<span>").addClass(this.shareLabelClass) .text(share.label); }, _renderShareCount: function(share, $container) { var $count = $("<span>").addClass(this.shareCountClass); $container.addClass(this.shareZeroCountClass) .append($count); this._loadCount(share).done($.proxy(function(count) { if(count) { $container.removeClass(this.shareZeroCountClass); $count.text(count); } }, this)); }, _loadCount: function(share) { var deferred = $.Deferred(); var countUrl = this._getCountUrl(share); if(!countUrl) { return deferred.resolve(0).promise(); } var handleSuccess = $.proxy(function(response) { deferred.resolve(this._getCountValue(response, share)); }, this); $.getJSON(countUrl).done(handleSuccess) .fail(function() { $.get(countUrl).done(handleSuccess) .fail(function() { deferred.resolve(0); }); }); return deferred.promise(); }, _getCountUrl: function(share) { var countUrl = getOrApply(share.countUrl, share); return this._formatShareUrl(countUrl, share); }, _getCountValue: function(response, share) { var count = ($.isFunction(share.getCount) ? share.getCount(response) : response) || 0; return (typeof count === "string") ? count : this._formatNumber(count); }, _formatNumber: function(number) { $.each(MEASURES, function(letter, value) { if(number >= value) { number = parseFloat((number / value).toFixed(2)) + letter; return false; } }); return number; }, _formatShareUrl: function(url, share) { return url.replace(URL_PARAMS_REGEX, function(match, key, field) { var value = share[field] || ""; return value ? (key || "") + window.encodeURIComponent(value) : ""; }); }, _clear: function() { window.clearTimeout(this._resizeTimer); this._$element.empty(); }, _passOptionToShares: function(key, value) { var shares = this.shares; $.each(["url", "text"], function(_, optionName) { if(optionName !== key) return; $.each(shares, function(_, share) { share[key] = value; }); }); }, _normalizeShare: function(share) { if($.isNumeric(share)) { return this.shares[share]; } if(typeof share === "string") { return $.grep(this.shares, function(s) { return s.share === share; })[0]; } return share; }, refresh: function() { this._render(); }, destroy: function() { this._clear(); this._detachWindowResizeCallback(); this._$element .removeClass(this.elementClass) .removeData(JSSOCIALS_DATA_KEY); }, option: function(key, value) { if(arguments.length === 1) { return this[key]; } this[key] = value; this._passOptionToShares(key, value); this.refresh(); }, shareOption: function(share, key, value) { share = this._normalizeShare(share); if(arguments.length === 2) { return share[key]; } share[key] = value; this.refresh(); } }; $.fn.jsSocials = function(config) { var args = $.makeArray(arguments), methodArgs = args.slice(1), result = this; this.each(function() { var $element = $(this), instance = $element.data(JSSOCIALS_DATA_KEY), methodResult; if(instance) { if(typeof config === "string") { methodResult = instance[config].apply(instance, methodArgs); if(methodResult !== undefined && methodResult !== instance) { result = methodResult; return false; } } else { instance._detachWindowResizeCallback(); instance._init(config); instance._render(); } } else { new Socials($element, config); } }); return result; }; var setDefaults = function(config) { var component; if($.isPlainObject(config)) { component = Socials.prototype; } else { component = shares[config]; config = arguments[1] || {}; } $.extend(component, config); }; var shareStrategies = { popup: function(args) { return $("<a>").attr("href", "#") .on("click", function() { window.open(args.shareUrl, null, "width=600, height=400, location=0, menubar=0, resizeable=0, scrollbars=0, status=0, titlebar=0, toolbar=0"); return false; }); }, blank: function(args) { return $("<a>").attr({ target: "_blank", href: args.shareUrl }); }, self: function(args) { return $("<a>").attr({ target: "_self", href: args.shareUrl }); } }; window.jsSocials = { Socials: Socials, shares: shares, shareStrategies: shareStrategies, setDefaults: setDefaults }; }(window, jQuery)); (function(window, $, jsSocials, undefined) { $.extend(jsSocials.shares, { email: { label: "E-mail", logo: "fa fa-at", shareUrl: "mailto:{to}?subject={text}&body={url}", countUrl: "", shareIn: "self" }, twitter: { label: "Tweet", logo: "fa fa-twitter", shareUrl: "https://twitter.com/share?url={url}&text={text}&via={via}&hashtags={hashtags}", countUrl: "" }, facebook: { label: "Like", logo: "fa fa-facebook", shareUrl: "https://facebook.com/sharer/sharer.php?u={url}", countUrl: function() { return "https://graph.facebook.com/fql?q=SELECT total_count FROM link_stat WHERE url='" + window.encodeURIComponent(this.url) + "'"; }, getCount: function(data) { return (data.data.length && data.data[0].total_count) || 0; } }, googleplus: { label: "+1", logo: "fa fa-google", shareUrl: "https://plus.google.com/share?url={url}", countUrl: function() { return "https://cors-anywhere.herokuapp.com/https://plusone.google.com/_/+1/fastbutton?url="+ window.encodeURIComponent(this.url); }, getCount: function(data) { return parseFloat((data.match(/\{c: ([.0-9E]+)/) || [])[1]); } }, linkedin: { label: "Share", logo: "fa fa-linkedin", shareUrl: "https://www.linkedin.com/shareArticle?mini=true&url={url}", countUrl: "https://www.linkedin.com/countserv/count/share?format=jsonp&url={url}&callback=?", getCount: function(data) { return data.count; } }, pinterest: { label: "Pin it", logo: "fa fa-pinterest", shareUrl: "https://pinterest.com/pin/create/bookmarklet/?media={media}&url={url}&description={text}", countUrl: "https://api.pinterest.com/v1/urls/count.json?&url={url}&callback=?", getCount: function(data) { return data.count; } }, stumbleupon: { label: "Share", logo: "fa fa-stumbleupon", shareUrl: "http://www.stumbleupon.com/submit?url={url}&title={title}", countUrl: "https://cors-anywhere.herokuapp.com/https://www.stumbleupon.com/services/1.01/badge.getinfo?url={url}", getCount: function(data) { return data.result.views; } }, whatsapp: { label: "WhatsApp", logo: "fa fa-whatsapp", shareUrl: "whatsapp://send?text={url} {text}", countUrl: "", shareIn: "self" }, line: { label: "LINE", logo: "fa fa-comment", shareUrl: "http://line.me/R/msg/text/?{text} {url}", countUrl: "" } }); }(window, jQuery, window.jsSocials));
$(document).ready(function () { $('#saveDefaultsButton').click(function () { var anyQualArray = []; var bestQualArray = []; $('#anyQualities option:selected').each(function (i, d) {anyQualArray.push($(d).val()); }); $('#bestQualities option:selected').each(function (i, d) {bestQualArray.push($(d).val()); }); $.get(sbRoot + '/config/general/saveAddShowDefaults', {defaultStatus: $('#statusSelect').val(), anyQualities: anyQualArray.join(','), bestQualities: bestQualArray.join(','), audio_lang: $('#showLangSelect').val(), subtitles: $('#subtitles').prop('checked'), defaultFlattenFolders: $('#flatten_folders').prop('checked')}); $(this).attr('disabled', true); $.pnotify({ pnotify_title: 'Saved Defaults', pnotify_text: 'Your "add show" defaults have been set to your current selections.', pnotify_shadow: false }); }); $('#statusSelect, #qualityPreset, #flatten_folders, #anyQualities, #bestQualities ,#showLangSelect, #subtitles').change(function () { $('#saveDefaultsButton').attr('disabled', false); }); });
IntlMessageFormat.__addLocaleData({locale:"wae", messageformat:{pluralFunction:function (n) { n=Math.floor(n);if(n===1)return"one";return"other"; }}});
// Generated by CoffeeScript 1.7.1 /* @preserve jQuery.PrettyTextDiff 1.0.4 See https://github.com/arnab/jQuery.PrettyTextDiff/ */ (function() { var $; $ = jQuery; $.fn.extend({ prettyTextDiff: function(options) { var dmp, settings; settings = { originalContainer: ".original", changedContainer: ".changed", diffContainer: ".diff", cleanup: true, debug: false }; settings = $.extend(settings, options); $.fn.prettyTextDiff.debug("Options: ", settings, settings); dmp = new diff_match_patch(); return this.each(function() { var changed, diff_as_html, diffs, original; if (settings.originalContent && settings.changedContent) { original = $('<div />').html(settings.originalContent).text(); changed = $('<div />').html(settings.changedContent).text(); } else { original = $(settings.originalContainer, this).text(); changed = $(settings.changedContainer, this).text(); } $.fn.prettyTextDiff.debug("Original text found: ", original, settings); $.fn.prettyTextDiff.debug("Changed text found: ", changed, settings); diffs = dmp.diff_main(original, changed); if (settings.cleanup) { dmp.diff_cleanupSemantic(diffs); } $.fn.prettyTextDiff.debug("Diffs: ", diffs, settings); diff_as_html = $.map(diffs, function(diff) { return $.fn.prettyTextDiff.createHTML(diff); }); $(settings.diffContainer, this).html(diff_as_html.join('')); return this; }); } }); $.fn.prettyTextDiff.debug = function(message, object, settings) { if (settings.debug) { return console.log(message, object); } }; $.fn.prettyTextDiff.createHTML = function(diff) { var data, html, operation, pattern_amp, pattern_gt, pattern_lt, pattern_para, text; html = []; pattern_amp = /&/g; pattern_lt = /</g; pattern_gt = />/g; pattern_para = /\n/g; operation = diff[0], data = diff[1]; text = data.replace(pattern_amp, '&amp;').replace(pattern_lt, '&lt;').replace(pattern_gt, '&gt;').replace(pattern_para, '<br>'); switch (operation) { case DIFF_INSERT: return '<ins>' + text + '</ins>'; case DIFF_DELETE: return '<del>' + text + '</del>'; case DIFF_EQUAL: return '<span>' + text + '</span>'; } }; }).call(this);
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var users = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', routes); app.use('/users', users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
/*! * smooth-scroll v9.4.1: Animate scrolling to anchor links * (c) 2016 Chris Ferdinandi * MIT License * http://github.com/cferdinandi/smooth-scroll */ (function (root, factory) { if ( typeof define === 'function' && define.amd ) { define([], factory(root)); } else if ( typeof exports === 'object' ) { module.exports = factory(root); } else { root.smoothScroll = factory(root); } })(typeof global !== 'undefined' ? global : this.window || this.global, function (root) { 'use strict'; // // Variables // var smoothScroll = {}; // Object for public APIs var supports = 'querySelector' in document && 'addEventListener' in root; // Feature test var settings, eventTimeout, fixedHeader, headerHeight, animationInterval; // Default settings var defaults = { selector: '[data-scroll]', selectorHeader: '[data-scroll-header]', speed: 500, easing: 'easeInOutCubic', offset: 0, updateURL: true, callback: function () {} }; // // Methods // /** * Merge two or more objects. Returns a new object. * @private * @param {Boolean} deep If true, do a deep (or recursive) merge [optional] * @param {Object} objects The objects to merge together * @returns {Object} Merged values of defaults and options */ var extend = function () { // Variables var extended = {}; var deep = false; var i = 0; var length = arguments.length; // Check if a deep merge if ( Object.prototype.toString.call( arguments[0] ) === '[object Boolean]' ) { deep = arguments[0]; i++; } // Merge the object into the extended object var merge = function (obj) { for ( var prop in obj ) { if ( Object.prototype.hasOwnProperty.call( obj, prop ) ) { // If deep merge and property is an object, merge properties if ( deep && Object.prototype.toString.call(obj[prop]) === '[object Object]' ) { extended[prop] = extend( true, extended[prop], obj[prop] ); } else { extended[prop] = obj[prop]; } } } }; // Loop through each object and conduct a merge for ( ; i < length; i++ ) { var obj = arguments[i]; merge(obj); } return extended; }; /** * Get the height of an element. * @private * @param {Node} elem The element to get the height of * @return {Number} The element's height in pixels */ var getHeight = function ( elem ) { return Math.max( elem.scrollHeight, elem.offsetHeight, elem.clientHeight ); }; /** * Get the closest matching element up the DOM tree. * @private * @param {Element} elem Starting element * @param {String} selector Selector to match against (class, ID, data attribute, or tag) * @return {Boolean|Element} Returns null if not match found */ var getClosest = function ( elem, selector ) { // Variables var firstChar = selector.charAt(0); var supports = 'classList' in document.documentElement; var attribute, value; // If selector is a data attribute, split attribute from value if ( firstChar === '[' ) { selector = selector.substr(1, selector.length - 2); attribute = selector.split( '=' ); if ( attribute.length > 1 ) { value = true; attribute[1] = attribute[1].replace( /"/g, '' ).replace( /'/g, '' ); } } // Get closest match for ( ; elem && elem !== document && elem.nodeType === 1; elem = elem.parentNode ) { // If selector is a class if ( firstChar === '.' ) { if ( supports ) { if ( elem.classList.contains( selector.substr(1) ) ) { return elem; } } else { if ( new RegExp('(^|\\s)' + selector.substr(1) + '(\\s|$)').test( elem.className ) ) { return elem; } } } // If selector is an ID if ( firstChar === '#' ) { if ( elem.id === selector.substr(1) ) { return elem; } } // If selector is a data attribute if ( firstChar === '[' ) { if ( elem.hasAttribute( attribute[0] ) ) { if ( value ) { if ( elem.getAttribute( attribute[0] ) === attribute[1] ) { return elem; } } else { return elem; } } } // If selector is a tag if ( elem.tagName.toLowerCase() === selector ) { return elem; } } return null; }; /** * Escape special characters for use with querySelector * @public * @param {String} id The anchor ID to escape * @author Mathias Bynens * @link https://github.com/mathiasbynens/CSS.escape */ smoothScroll.escapeCharacters = function ( id ) { // Remove leading hash if ( id.charAt(0) === '#' ) { id = id.substr(1); } var string = String(id); var length = string.length; var index = -1; var codeUnit; var result = ''; var firstCodeUnit = string.charCodeAt(0); while (++index < length) { codeUnit = string.charCodeAt(index); // Note: there’s no need to special-case astral symbols, surrogate // pairs, or lone surrogates. // If the character is NULL (U+0000), then throw an // `InvalidCharacterError` exception and terminate these steps. if (codeUnit === 0x0000) { throw new InvalidCharacterError( 'Invalid character: the input contains U+0000.' ); } if ( // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is // U+007F, […] (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || // If the character is the first character and is in the range [0-9] // (U+0030 to U+0039), […] (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || // If the character is the second character and is in the range [0-9] // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] ( index === 1 && codeUnit >= 0x0030 && codeUnit <= 0x0039 && firstCodeUnit === 0x002D ) ) { // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point result += '\\' + codeUnit.toString(16) + ' '; continue; } // If the character is not handled by one of the above rules and is // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to // U+005A), or [a-z] (U+0061 to U+007A), […] if ( codeUnit >= 0x0080 || codeUnit === 0x002D || codeUnit === 0x005F || codeUnit >= 0x0030 && codeUnit <= 0x0039 || codeUnit >= 0x0041 && codeUnit <= 0x005A || codeUnit >= 0x0061 && codeUnit <= 0x007A ) { // the character itself result += string.charAt(index); continue; } // Otherwise, the escaped character. // http://dev.w3.org/csswg/cssom/#escape-a-character result += '\\' + string.charAt(index); } return '#' + result; }; /** * Calculate the easing pattern * @private * @link https://gist.github.com/gre/1650294 * @param {String} type Easing pattern * @param {Number} time Time animation should take to complete * @returns {Number} */ var easingPattern = function ( type, time ) { var pattern; if ( type === 'easeInQuad' ) pattern = time * time; // accelerating from zero velocity if ( type === 'easeOutQuad' ) pattern = time * (2 - time); // decelerating to zero velocity if ( type === 'easeInOutQuad' ) pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration if ( type === 'easeInCubic' ) pattern = time * time * time; // accelerating from zero velocity if ( type === 'easeOutCubic' ) pattern = (--time) * time * time + 1; // decelerating to zero velocity if ( type === 'easeInOutCubic' ) pattern = time < 0.5 ? 4 * time * time * time : (time - 1) * (2 * time - 2) * (2 * time - 2) + 1; // acceleration until halfway, then deceleration if ( type === 'easeInQuart' ) pattern = time * time * time * time; // accelerating from zero velocity if ( type === 'easeOutQuart' ) pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity if ( type === 'easeInOutQuart' ) pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration if ( type === 'easeInQuint' ) pattern = time * time * time * time * time; // accelerating from zero velocity if ( type === 'easeOutQuint' ) pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity if ( type === 'easeInOutQuint' ) pattern = time < 0.5 ? 16 * time * time * time * time * time : 1 + 16 * (--time) * time * time * time * time; // acceleration until halfway, then deceleration return pattern || time; // no easing, no acceleration }; /** * Calculate how far to scroll * @private * @param {Element} anchor The anchor element to scroll to * @param {Number} headerHeight Height of a fixed header, if any * @param {Number} offset Number of pixels by which to offset scroll * @returns {Number} */ var getEndLocation = function ( anchor, headerHeight, offset ) { var location = 0; if (anchor.offsetParent) { do { location += anchor.offsetTop; anchor = anchor.offsetParent; } while (anchor); } location = Math.max(location - headerHeight - offset, 0); return Math.min(location, getDocumentHeight() - getViewportHeight()); }; /** * Determine the viewport's height * @private * @returns {Number} */ var getViewportHeight = function() { return Math.max(document.documentElement.clientHeight, window.innerHeight || 0); }; /** * Determine the document's height * @private * @returns {Number} */ var getDocumentHeight = function () { return Math.max( root.document.body.scrollHeight, root.document.documentElement.scrollHeight, root.document.body.offsetHeight, root.document.documentElement.offsetHeight, root.document.body.clientHeight, root.document.documentElement.clientHeight ); }; /** * Convert data-options attribute into an object of key/value pairs * @private * @param {String} options Link-specific options as a data attribute string * @returns {Object} */ var getDataOptions = function ( options ) { return !options || !(typeof JSON === 'object' && typeof JSON.parse === 'function') ? {} : JSON.parse( options ); }; /** * Update the URL * @private * @param {Element} anchor The element to scroll to * @param {Boolean} url Whether or not to update the URL history */ var updateUrl = function ( anchor, url ) { if ( root.history.pushState && (url || url === 'true') && root.location.protocol !== 'file:' ) { root.history.pushState( null, null, [root.location.protocol, '//', root.location.host, root.location.pathname, root.location.search, anchor].join('') ); } }; var getHeaderHeight = function ( header ) { return header === null ? 0 : ( getHeight( header ) + header.offsetTop ); }; /** * Start/stop the scrolling animation * @public * @param {Element} anchor The element to scroll to * @param {Element} toggle The element that toggled the scroll event * @param {Object} options */ smoothScroll.animateScroll = function ( anchor, toggle, options ) { // Options and overrides var overrides = getDataOptions( toggle ? toggle.getAttribute('data-options') : null ); var animateSettings = extend( settings || defaults, options || {}, overrides ); // Merge user options with defaults // Selectors and variables var isNum = Object.prototype.toString.call( anchor ) === '[object Number]' ? true : false; var hash = smoothScroll.escapeCharacters( anchor ); var anchorElem = isNum ? null : ( hash === '#' ? root.document.documentElement : root.document.querySelector( hash ) ); if ( !isNum && !anchorElem ) return; var startLocation = root.pageYOffset; // Current location on the page if ( !fixedHeader ) { fixedHeader = root.document.querySelector( animateSettings.selectorHeader ); } // Get the fixed header if not already set if ( !headerHeight ) { headerHeight = getHeaderHeight( fixedHeader ); } // Get the height of a fixed header if one exists and not already set var endLocation = isNum ? anchor : getEndLocation( anchorElem, headerHeight, parseInt(animateSettings.offset, 10) ); // Location to scroll to var distance = endLocation - startLocation; // distance to travel var documentHeight = getDocumentHeight(); var timeLapsed = 0; var percentage, position; // Update URL if ( !isNum ) { updateUrl( anchor, animateSettings.updateURL ); } /** * Stop the scroll animation when it reaches its target (or the bottom/top of page) * @private * @param {Number} position Current position on the page * @param {Number} endLocation Scroll to location * @param {Number} animationInterval How much to scroll on this loop */ var stopAnimateScroll = function ( position, endLocation, animationInterval ) { var currentLocation = root.pageYOffset; if ( position == endLocation || currentLocation == endLocation || ( (root.innerHeight + currentLocation) >= documentHeight ) ) { clearInterval(animationInterval); // If scroll target is an anchor, bring it into focus if ( !isNum ) { anchorElem.focus(); if ( document.activeElement.id !== anchorElem.id ) { anchorElem.setAttribute( 'tabindex', '-1' ); anchorElem.focus(); anchorElem.style.outline = 'none'; } } animateSettings.callback( anchor, toggle ); // Run callbacks after animation complete } }; /** * Loop scrolling animation * @private */ var loopAnimateScroll = function () { timeLapsed += 16; percentage = ( timeLapsed / parseInt(animateSettings.speed, 10) ); percentage = ( percentage > 1 ) ? 1 : percentage; position = startLocation + ( distance * easingPattern(animateSettings.easing, percentage) ); root.scrollTo( 0, Math.floor(position) ); stopAnimateScroll(position, endLocation, animationInterval); }; /** * Set interval timer * @private */ var startAnimateScroll = function () { clearInterval(animationInterval); animationInterval = setInterval(loopAnimateScroll, 16); }; /** * Reset position to fix weird iOS bug * @link https://github.com/cferdinandi/smooth-scroll/issues/45 */ if ( root.pageYOffset === 0 ) { root.scrollTo( 0, 0 ); } // Start scrolling animation startAnimateScroll(); }; /** * If smooth scroll element clicked, animate scroll * @private */ var eventHandler = function (event) { // Don't run if right-click or command/control + click if ( event.button !== 0 || event.metaKey || event.ctrlKey ) return; // If a smooth scroll link, animate it var toggle = getClosest( event.target, settings.selector ); if ( toggle && toggle.tagName.toLowerCase() === 'a' ) { // Check that link is an anchor and points to current page if ( toggle.hostname !== root.location.hostname || toggle.pathname !== root.location.pathname || !/#/.test(toggle.href) ) return; event.preventDefault(); // Prevent default click event smoothScroll.animateScroll( toggle.hash, toggle, settings); // Animate scroll } }; /** * On window scroll and resize, only run events at a rate of 15fps for better performance * @private * @param {Function} eventTimeout Timeout function * @param {Object} settings */ var eventThrottler = function (event) { if ( !eventTimeout ) { eventTimeout = setTimeout(function() { eventTimeout = null; // Reset timeout headerHeight = getHeaderHeight( fixedHeader ); // Get the height of a fixed header if one exists }, 66); } }; /** * Destroy the current initialization. * @public */ smoothScroll.destroy = function () { // If plugin isn't already initialized, stop if ( !settings ) return; // Remove event listeners root.document.removeEventListener( 'click', eventHandler, false ); root.removeEventListener( 'resize', eventThrottler, false ); // Reset varaibles settings = null; eventTimeout = null; fixedHeader = null; headerHeight = null; animationInterval = null; }; /** * Initialize Smooth Scroll * @public * @param {Object} options User settings */ smoothScroll.init = function ( options ) { // feature test if ( !supports ) return; // Destroy any existing initializations smoothScroll.destroy(); // Selectors and variables settings = extend( defaults, options || {} ); // Merge user options with defaults fixedHeader = root.document.querySelector( settings.selectorHeader ); // Get the fixed header headerHeight = getHeaderHeight( fixedHeader ); // When a toggle is clicked, run the click handler root.document.addEventListener('click', eventHandler, false ); if ( fixedHeader ) { root.addEventListener( 'resize', eventThrottler, false ); } }; // // Public APIs // return smoothScroll; });
/*! lazysizes - v2.0.2-rc1 */ !function(a){"use strict";var b,c,d,e;a.addEventListener&&(b=a.lazySizes&&lazySizes.cfg||a.lazySizesConfig||{},c=b.lazyClass||"lazyload",d=function(){var b,d;if("string"==typeof c&&(c=document.getElementsByClassName(c)),a.lazySizes)for(b=0,d=c.length;d>b;b++)lazySizes.loader.unveil(c[b])},addEventListener("beforeprint",d,!1),!("onbeforeprint"in a)&&a.matchMedia&&(e=matchMedia("print"))&&e.addListener&&e.addListener(function(){e.matches&&d()}))}(window);
;(function(undefined) { 'use strict'; /** * BottleJS v0.7.2 - 2014-12-26 * A powerful, extensible dependency injection micro container * * Copyright (c) 2014 Stephen Young * Licensed MIT */ /** * Unique id counter; * * @type Number */ var id = 0; /** * Local slice alias * * @type Functions */ var slice = Array.prototype.slice; /** * Map of fullnames by index => name * * @type Array */ var fullnameMap = []; /** * Iterator used to flatten arrays with reduce. * * @param Array a * @param Array b * @return Array */ var concatIterator = function concatIterator(a, b) { return a.concat(b); }; /** * Get a group (middleware, decorator, etc.) for this bottle instance and service name. * * @param Array collection * @param Number id * @param String name * @return Array */ var get = function get(collection, id, name) { var group = collection[id]; if (!group) { group = collection[id] = {}; } if (name && !group[name]) { group[name] = []; } return name ? group[name] : group; }; /** * Will try to get all things from a collection by name, by __global__, and by mapped names. * * @param Array collection * @param Number id * @param String name * @return Array */ var getAllWithMapped = function(collection, id, name) { return get(fullnameMap, id, name) .map(getMapped.bind(null, collection)) .reduce(concatIterator, get(collection, id, name)) .concat(get(collection, id, '__global__')); }; /** * Iterator used to get decorators from a map * * @param Array collection * @param Object data * @return Function */ var getMapped = function getMapped(collection, data) { return get(collection, data.id, data.fullname); }; /** * Iterator used to walk down a nested object. * * @param Object obj * @param String prop * @return mixed */ var getNested = function getNested(obj, prop) { return obj[prop]; }; /** * Get a service stored under a nested key * * @param String fullname * @return Service */ var getNestedService = function getNestedService(fullname) { return fullname.split('.').reduce(getNested, this); }; /** * A helper function for pushing middleware and decorators onto their stacks. * * @param Array collection * @param String name * @param Function func */ var set = function set(collection, id, name, func) { if (typeof name === 'function') { func = name; name = '__global__'; } get(collection, id, name).push(func); }; /** * Register a constant * * @param String name * @param mixed value * @return Bottle */ var constant = function constant(name, value) { var parts = name.split('.'); name = parts.pop(); defineConstant.call(parts.reduce(setValueObject, this.container), name, value); return this; }; var defineConstant = function defineConstant(name, value) { Object.defineProperty(this, name, { configurable : false, enumerable : true, value : value, writable : false }); }; /** * Map of decorator by index => name * * @type Object */ var decorators = []; /** * Register decorator. * * @param String name * @param Function func * @return Bottle */ var decorator = function decorator(name, func) { set(decorators, this.id, name, func); return this; }; /** * Map of deferred functions by id => name * * @type Object */ var deferred = []; /** * Register a function that will be executed when Bottle#resolve is called. * * @param Function func * @return Bottle */ var defer = function defer(func) { set(deferred, this.id, func); return this; }; /** * Immediately instantiates the provided list of services and returns them. * * @param Array services * @return Array Array of instances (in the order they were provided) */ var digest = function digest(services) { return (services || []).map(getNestedService, this.container); }; /** * Register a factory inside a generic provider. * * @param String name * @param Function Factory * @return Bottle */ var factory = function factory(name, Factory) { return provider.call(this, name, function GenericProvider() { this.$get = Factory; }); }; /** * Map of middleware by index => name * * @type Object */ var middles = []; /** * Function used by provider to set up middleware for each request. * * @param Number id * @param String name * @param Object instance * @param Object container * @return void */ var applyMiddleware = function applyMiddleware(id, name, instance, container) { var middleware = getAllWithMapped(middles, id, name); var descriptor = { configurable : true, enumerable : true }; if (middleware.length) { descriptor.get = function getWithMiddlewear() { var index = 0; var next = function nextMiddleware() { if (middleware[index]) { middleware[index++](instance, next); } }; next(); return instance; }; } else { descriptor.value = instance; descriptor.writable = true; } Object.defineProperty(container, name, descriptor); return container[name]; }; /** * Register middleware. * * @param String name * @param Function func * @return Bottle */ var middleware = function middleware(name, func) { set(middles, this.id, name, func); return this; }; /** * Named bottle instances * * @type Object */ var bottles = {}; /** * Get an instance of bottle. * * If a name is provided the instance will be stored in a local hash. Calling Bottle.pop multiple * times with the same name will return the same instance. * * @param String name * @return Bottle */ var pop = function pop(name) { var instance; if (name) { instance = bottles[name]; if (!instance) { bottles[name] = instance = new Bottle(); } return instance; } return new Bottle(); }; /** * Map of nested bottles by index => name * * @type Array */ var nestedBottles = []; /** * Map of provider constructors by index => name * * @type Array */ var providerMap = []; /** * Used to process decorators in the provider * * @param Object instance * @param Function func * @return Mixed */ var reducer = function reducer(instance, func) { return func(instance); }; /** * Register a provider. * * @param String fullname * @param Function Provider * @return Bottle */ var provider = function provider(fullname, Provider) { var parts, providers, name, id, factory; id = this.id; providers = get(providerMap, id); if (providers[fullname]) { return console.error(fullname + ' provider already registered.'); } providers[fullname] = true; parts = fullname.split('.'); name = parts.shift(); factory = parts.length ? createSubProvider : createProvider; return factory.call(this, name, Provider, fullname, parts); }; /** * Create the provider properties on the container * * @param String fullname * @param String name * @param Function Provider * @return Bottle */ var createProvider = function createProvider(name, Provider) { var providerName, properties, container, id; id = this.id; container = this.container; providerName = name + 'Provider'; properties = Object.create(null); properties[providerName] = { configurable : true, enumerable : true, get : function getProvider() { var instance = new Provider(); delete container[providerName]; container[providerName] = instance; return instance; } }; properties[name] = { configurable : true, enumerable : true, get : function getService() { var provider = container[providerName]; var instance; if (provider) { delete container[providerName]; delete container[name]; // filter through decorators instance = getAllWithMapped(decorators, id, name) .reduce(reducer, provider.$get(container)); } return instance ? applyMiddleware(id, name, instance, container) : instance; } }; Object.defineProperties(container, properties); return this; }; /** * Creates a bottle container on the current bottle container, and registers * the provider under the sub container. * * @param String name * @param Function Provider * @param String fullname * @param Array parts * @return Bottle */ var createSubProvider = function createSubProvider(name, Provider, fullname, parts) { var bottle, bottles, subname, id; id = this.id; bottles = get(nestedBottles, id); bottle = bottles[name]; if (!bottle) { this.container[name] = (bottle = bottles[name] = Bottle.pop()).container; } subname = parts.join('.'); bottle.provider(subname, Provider); set(fullnameMap, bottle.id, subname, { fullname : fullname, id : id }); return this; }; /** * Register a service, factory, provider, or value based on properties on the object. * * properties: * * Obj.$name String required ex: `'Thing'` * * Obj.$type String optional 'service', 'factory', 'provider', 'value'. Default: 'service' * * Obj.$inject Mixed optional only useful with $type 'service' name or array of names * * @param Function Obj * @return Bottle */ var register = function register(Obj) { return this[Obj.$type || 'service'].apply(this, [Obj.$name, Obj].concat(Obj.$inject || [])); }; /** * Execute any deferred functions * * @param Mixed data * @return Bottle */ var resolve = function resolve(data) { get(deferred, this.id, '__global__').forEach(function deferredIterator(func) { func(data); }); return this; }; /** * Register a service inside a generic factory. * * @param String name * @param Function Service * @return Bottle */ var service = function service(name, Service) { var deps = arguments.length > 2 ? slice.call(arguments, 2) : null; var bottle = this; return factory.call(this, name, function GenericFactory() { if (deps) { deps = deps.map(getNestedService, bottle.container); deps.unshift(Service); Service = Service.bind.apply(Service, deps); } return new Service(); }); }; /** * Register a value * * @param String name * @param mixed val * @return */ var value = function value(name, val) { var parts; parts = name.split('.'); name = parts.pop(); defineValue.call(parts.reduce(setValueObject, this.container), name, val); return this; }; /** * Iterator for setting a plain object literal via defineValue * * @param Object container * @param string name */ var setValueObject = function setValueObject(container, name) { var newContainer = {}; defineValue.call(container, name, newContainer); return newContainer; }; /** * Define a mutable property on the container. * * @param String name * @param mixed val * @return void * @scope container */ var defineValue = function defineValue(name, val) { Object.defineProperty(this, name, { configurable : true, enumerable : true, value : val, writable : true }); }; /** * Bottle constructor * * @param String name Optional name for functional construction */ var Bottle = function Bottle(name) { if (!(this instanceof Bottle)) { return Bottle.pop(name); } this.id = id++; this.container = { $register : register.bind(this) }; }; /** * Bottle prototype */ Bottle.prototype = { constant : constant, decorator : decorator, defer : defer, digest : digest, factory : factory, middleware : middleware, provider : provider, register : register, resolve : resolve, service : service, value : value }; /** * Bottle static */ Bottle.pop = pop; /** * Exports script adapted from lodash v2.4.1 Modern Build * * @see http://lodash.com/ */ /** * Valid object type map * * @type Object */ var objectTypes = { 'function' : true, 'object' : true }; (function exportBottle(root) { /** * Free variable exports * * @type Function */ var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; /** * Free variable module * * @type Object */ var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; /** * CommonJS module.exports * * @type Function */ var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; /** * Free variable `global` * * @type Object */ var freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } /** * Export */ if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) { root.Bottle = Bottle; define(function() { return Bottle; }); } else if (freeExports && freeModule) { if (moduleExports) { (freeModule.exports = Bottle).Bottle = Bottle; } else { freeExports.Bottle = Bottle; } } else { root.Bottle = Bottle; } }((objectTypes[typeof window] && window) || this)); }.call(this));
var keystone = require('../../../../index.js'); var Types = keystone.Field.Types; var Code = new keystone.List('Code', { autokey: { path: 'key', from: 'name', unique: true, }, track: true, }); Code.add({ name: { type: String, initial: true, required: true, index: true, }, fieldA: { type: Types.Code, initial: true, height: 200, }, fieldB: { type: Types.Code, height: 200, }, }); Code.defaultColumns = 'name, fieldA, fieldB'; Code.register(); module.exports = Code;
var Sites = {}; Sites.getTop = function(callback) { chrome.topSites.get(function(e) { callback(e.map(function(e) { return [e.title, e.url]; })); }); };
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "default", { enumerable: true, get: function get() { return _ListItemSecondaryAction.default; } }); var _ListItemSecondaryAction = _interopRequireDefault(require("./ListItemSecondaryAction"));
/*! * Fine Uploader * * Copyright 2015, Widen Enterprises, Inc. info@fineuploader.com * * Version: 5.3.2 * * Homepage: http://fineuploader.com * * Repository: git://github.com/FineUploader/fine-uploader.git * * Licensed only under the Widen Commercial License (http://fineuploader.com/licensing). */ /*globals window, navigator, document, FormData, File, HTMLInputElement, XMLHttpRequest, Blob, Storage, ActiveXObject */ /* jshint -W079 */ var qq = function(element) { "use strict"; return { hide: function() { element.style.display = "none"; return this; }, /** Returns the function which detaches attached event */ attach: function(type, fn) { if (element.addEventListener) { element.addEventListener(type, fn, false); } else if (element.attachEvent) { element.attachEvent("on" + type, fn); } return function() { qq(element).detach(type, fn); }; }, detach: function(type, fn) { if (element.removeEventListener) { element.removeEventListener(type, fn, false); } else if (element.attachEvent) { element.detachEvent("on" + type, fn); } return this; }, contains: function(descendant) { // The [W3C spec](http://www.w3.org/TR/domcore/#dom-node-contains) // says a `null` (or ostensibly `undefined`) parameter // passed into `Node.contains` should result in a false return value. // IE7 throws an exception if the parameter is `undefined` though. if (!descendant) { return false; } // compareposition returns false in this case if (element === descendant) { return true; } if (element.contains) { return element.contains(descendant); } else { /*jslint bitwise: true*/ return !!(descendant.compareDocumentPosition(element) & 8); } }, /** * Insert this element before elementB. */ insertBefore: function(elementB) { elementB.parentNode.insertBefore(element, elementB); return this; }, remove: function() { element.parentNode.removeChild(element); return this; }, /** * Sets styles for an element. * Fixes opacity in IE6-8. */ css: function(styles) { /*jshint eqnull: true*/ if (element.style == null) { throw new qq.Error("Can't apply style to node as it is not on the HTMLElement prototype chain!"); } /*jshint -W116*/ if (styles.opacity != null) { if (typeof element.style.opacity !== "string" && typeof (element.filters) !== "undefined") { styles.filter = "alpha(opacity=" + Math.round(100 * styles.opacity) + ")"; } } qq.extend(element.style, styles); return this; }, hasClass: function(name, considerParent) { var re = new RegExp("(^| )" + name + "( |$)"); return re.test(element.className) || !!(considerParent && re.test(element.parentNode.className)); }, addClass: function(name) { if (!qq(element).hasClass(name)) { element.className += " " + name; } return this; }, removeClass: function(name) { var re = new RegExp("(^| )" + name + "( |$)"); element.className = element.className.replace(re, " ").replace(/^\s+|\s+$/g, ""); return this; }, getByClass: function(className, first) { var candidates, result = []; if (first && element.querySelector) { return element.querySelector("." + className); } else if (element.querySelectorAll) { return element.querySelectorAll("." + className); } candidates = element.getElementsByTagName("*"); qq.each(candidates, function(idx, val) { if (qq(val).hasClass(className)) { result.push(val); } }); return first ? result[0] : result; }, getFirstByClass: function(className) { return qq(element).getByClass(className, true); }, children: function() { var children = [], child = element.firstChild; while (child) { if (child.nodeType === 1) { children.push(child); } child = child.nextSibling; } return children; }, setText: function(text) { element.innerText = text; element.textContent = text; return this; }, clearText: function() { return qq(element).setText(""); }, // Returns true if the attribute exists on the element // AND the value of the attribute is NOT "false" (case-insensitive) hasAttribute: function(attrName) { var attrVal; if (element.hasAttribute) { if (!element.hasAttribute(attrName)) { return false; } /*jshint -W116*/ return (/^false$/i).exec(element.getAttribute(attrName)) == null; } else { attrVal = element[attrName]; if (attrVal === undefined) { return false; } /*jshint -W116*/ return (/^false$/i).exec(attrVal) == null; } } }; }; (function() { "use strict"; qq.canvasToBlob = function(canvas, mime, quality) { return qq.dataUriToBlob(canvas.toDataURL(mime, quality)); }; qq.dataUriToBlob = function(dataUri) { var arrayBuffer, byteString, createBlob = function(data, mime) { var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder, blobBuilder = BlobBuilder && new BlobBuilder(); if (blobBuilder) { blobBuilder.append(data); return blobBuilder.getBlob(mime); } else { return new Blob([data], {type: mime}); } }, intArray, mimeString; // convert base64 to raw binary data held in a string if (dataUri.split(",")[0].indexOf("base64") >= 0) { byteString = atob(dataUri.split(",")[1]); } else { byteString = decodeURI(dataUri.split(",")[1]); } // extract the MIME mimeString = dataUri.split(",")[0] .split(":")[1] .split(";")[0]; // write the bytes of the binary string to an ArrayBuffer arrayBuffer = new ArrayBuffer(byteString.length); intArray = new Uint8Array(arrayBuffer); qq.each(byteString, function(idx, character) { intArray[idx] = character.charCodeAt(0); }); return createBlob(arrayBuffer, mimeString); }; qq.log = function(message, level) { if (window.console) { if (!level || level === "info") { window.console.log(message); } else { if (window.console[level]) { window.console[level](message); } else { window.console.log("<" + level + "> " + message); } } } }; qq.isObject = function(variable) { return variable && !variable.nodeType && Object.prototype.toString.call(variable) === "[object Object]"; }; qq.isFunction = function(variable) { return typeof (variable) === "function"; }; /** * Check the type of a value. Is it an "array"? * * @param value value to test. * @returns true if the value is an array or associated with an `ArrayBuffer` */ qq.isArray = function(value) { return Object.prototype.toString.call(value) === "[object Array]" || (value && window.ArrayBuffer && value.buffer && value.buffer.constructor === ArrayBuffer); }; // Looks for an object on a `DataTransfer` object that is associated with drop events when utilizing the Filesystem API. qq.isItemList = function(maybeItemList) { return Object.prototype.toString.call(maybeItemList) === "[object DataTransferItemList]"; }; // Looks for an object on a `NodeList` or an `HTMLCollection`|`HTMLFormElement`|`HTMLSelectElement` // object that is associated with collections of Nodes. qq.isNodeList = function(maybeNodeList) { return Object.prototype.toString.call(maybeNodeList) === "[object NodeList]" || // If `HTMLCollection` is the actual type of the object, we must determine this // by checking for expected properties/methods on the object (maybeNodeList.item && maybeNodeList.namedItem); }; qq.isString = function(maybeString) { return Object.prototype.toString.call(maybeString) === "[object String]"; }; qq.trimStr = function(string) { if (String.prototype.trim) { return string.trim(); } return string.replace(/^\s+|\s+$/g, ""); }; /** * @param str String to format. * @returns {string} A string, swapping argument values with the associated occurrence of {} in the passed string. */ qq.format = function(str) { var args = Array.prototype.slice.call(arguments, 1), newStr = str, nextIdxToReplace = newStr.indexOf("{}"); qq.each(args, function(idx, val) { var strBefore = newStr.substring(0, nextIdxToReplace), strAfter = newStr.substring(nextIdxToReplace + 2); newStr = strBefore + val + strAfter; nextIdxToReplace = newStr.indexOf("{}", nextIdxToReplace + val.length); // End the loop if we have run out of tokens (when the arguments exceed the # of tokens) if (nextIdxToReplace < 0) { return false; } }); return newStr; }; qq.isFile = function(maybeFile) { return window.File && Object.prototype.toString.call(maybeFile) === "[object File]"; }; qq.isFileList = function(maybeFileList) { return window.FileList && Object.prototype.toString.call(maybeFileList) === "[object FileList]"; }; qq.isFileOrInput = function(maybeFileOrInput) { return qq.isFile(maybeFileOrInput) || qq.isInput(maybeFileOrInput); }; qq.isInput = function(maybeInput, notFile) { var evaluateType = function(type) { var normalizedType = type.toLowerCase(); if (notFile) { return normalizedType !== "file"; } return normalizedType === "file"; }; if (window.HTMLInputElement) { if (Object.prototype.toString.call(maybeInput) === "[object HTMLInputElement]") { if (maybeInput.type && evaluateType(maybeInput.type)) { return true; } } } if (maybeInput.tagName) { if (maybeInput.tagName.toLowerCase() === "input") { if (maybeInput.type && evaluateType(maybeInput.type)) { return true; } } } return false; }; qq.isBlob = function(maybeBlob) { if (window.Blob && Object.prototype.toString.call(maybeBlob) === "[object Blob]") { return true; } }; qq.isXhrUploadSupported = function() { var input = document.createElement("input"); input.type = "file"; return ( input.multiple !== undefined && typeof File !== "undefined" && typeof FormData !== "undefined" && typeof (qq.createXhrInstance()).upload !== "undefined"); }; // Fall back to ActiveX is native XHR is disabled (possible in any version of IE). qq.createXhrInstance = function() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } try { return new ActiveXObject("MSXML2.XMLHTTP.3.0"); } catch (error) { qq.log("Neither XHR or ActiveX are supported!", "error"); return null; } }; qq.isFolderDropSupported = function(dataTransfer) { return dataTransfer.items && dataTransfer.items.length > 0 && dataTransfer.items[0].webkitGetAsEntry; }; qq.isFileChunkingSupported = function() { return !qq.androidStock() && //Android's stock browser cannot upload Blobs correctly qq.isXhrUploadSupported() && (File.prototype.slice !== undefined || File.prototype.webkitSlice !== undefined || File.prototype.mozSlice !== undefined); }; qq.sliceBlob = function(fileOrBlob, start, end) { var slicer = fileOrBlob.slice || fileOrBlob.mozSlice || fileOrBlob.webkitSlice; return slicer.call(fileOrBlob, start, end); }; qq.arrayBufferToHex = function(buffer) { var bytesAsHex = "", bytes = new Uint8Array(buffer); qq.each(bytes, function(idx, byt) { var byteAsHexStr = byt.toString(16); if (byteAsHexStr.length < 2) { byteAsHexStr = "0" + byteAsHexStr; } bytesAsHex += byteAsHexStr; }); return bytesAsHex; }; qq.readBlobToHex = function(blob, startOffset, length) { var initialBlob = qq.sliceBlob(blob, startOffset, startOffset + length), fileReader = new FileReader(), promise = new qq.Promise(); fileReader.onload = function() { promise.success(qq.arrayBufferToHex(fileReader.result)); }; fileReader.onerror = promise.failure; fileReader.readAsArrayBuffer(initialBlob); return promise; }; qq.extend = function(first, second, extendNested) { qq.each(second, function(prop, val) { if (extendNested && qq.isObject(val)) { if (first[prop] === undefined) { first[prop] = {}; } qq.extend(first[prop], val, true); } else { first[prop] = val; } }); return first; }; /** * Allow properties in one object to override properties in another, * keeping track of the original values from the target object. * * Note that the pre-overriden properties to be overriden by the source will be passed into the `sourceFn` when it is invoked. * * @param target Update properties in this object from some source * @param sourceFn A function that, when invoked, will return properties that will replace properties with the same name in the target. * @returns {object} The target object */ qq.override = function(target, sourceFn) { var super_ = {}, source = sourceFn(super_); qq.each(source, function(srcPropName, srcPropVal) { if (target[srcPropName] !== undefined) { super_[srcPropName] = target[srcPropName]; } target[srcPropName] = srcPropVal; }); return target; }; /** * Searches for a given element (elt) in the array, returns -1 if it is not present. */ qq.indexOf = function(arr, elt, from) { if (arr.indexOf) { return arr.indexOf(elt, from); } from = from || 0; var len = arr.length; if (from < 0) { from += len; } for (; from < len; from += 1) { if (arr.hasOwnProperty(from) && arr[from] === elt) { return from; } } return -1; }; //this is a version 4 UUID qq.getUniqueId = function() { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) { /*jslint eqeq: true, bitwise: true*/ var r = Math.random() * 16 | 0, v = c == "x" ? r : (r & 0x3 | 0x8); return v.toString(16); }); }; // // Browsers and platforms detection qq.ie = function() { return navigator.userAgent.indexOf("MSIE") !== -1 || navigator.userAgent.indexOf("Trident") !== -1; }; qq.ie7 = function() { return navigator.userAgent.indexOf("MSIE 7") !== -1; }; qq.ie8 = function() { return navigator.userAgent.indexOf("MSIE 8") !== -1; }; qq.ie10 = function() { return navigator.userAgent.indexOf("MSIE 10") !== -1; }; qq.ie11 = function() { return qq.ie() && navigator.userAgent.indexOf("rv:11") !== -1; }; qq.safari = function() { return navigator.vendor !== undefined && navigator.vendor.indexOf("Apple") !== -1; }; qq.chrome = function() { return navigator.vendor !== undefined && navigator.vendor.indexOf("Google") !== -1; }; qq.opera = function() { return navigator.vendor !== undefined && navigator.vendor.indexOf("Opera") !== -1; }; qq.firefox = function() { return (!qq.ie11() && navigator.userAgent.indexOf("Mozilla") !== -1 && navigator.vendor !== undefined && navigator.vendor === ""); }; qq.windows = function() { return navigator.platform === "Win32"; }; qq.android = function() { return navigator.userAgent.toLowerCase().indexOf("android") !== -1; }; // We need to identify the Android stock browser via the UA string to work around various bugs in this browser, // such as the one that prevents a `Blob` from being uploaded. qq.androidStock = function() { return qq.android() && navigator.userAgent.toLowerCase().indexOf("chrome") < 0; }; qq.ios6 = function() { return qq.ios() && navigator.userAgent.indexOf(" OS 6_") !== -1; }; qq.ios7 = function() { return qq.ios() && navigator.userAgent.indexOf(" OS 7_") !== -1; }; qq.ios8 = function() { return qq.ios() && navigator.userAgent.indexOf(" OS 8_") !== -1; }; // iOS 8.0.0 qq.ios800 = function() { return qq.ios() && navigator.userAgent.indexOf(" OS 8_0 ") !== -1; }; qq.ios = function() { /*jshint -W014 */ return navigator.userAgent.indexOf("iPad") !== -1 || navigator.userAgent.indexOf("iPod") !== -1 || navigator.userAgent.indexOf("iPhone") !== -1; }; qq.iosChrome = function() { return qq.ios() && navigator.userAgent.indexOf("CriOS") !== -1; }; qq.iosSafari = function() { return qq.ios() && !qq.iosChrome() && navigator.userAgent.indexOf("Safari") !== -1; }; qq.iosSafariWebView = function() { return qq.ios() && !qq.iosChrome() && !qq.iosSafari(); }; // // Events qq.preventDefault = function(e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } }; /** * Creates and returns element from html string * Uses innerHTML to create an element */ qq.toElement = (function() { var div = document.createElement("div"); return function(html) { div.innerHTML = html; var element = div.firstChild; div.removeChild(element); return element; }; }()); //key and value are passed to callback for each entry in the iterable item qq.each = function(iterableItem, callback) { var keyOrIndex, retVal; if (iterableItem) { // Iterate through [`Storage`](http://www.w3.org/TR/webstorage/#the-storage-interface) items if (window.Storage && iterableItem.constructor === window.Storage) { for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) { retVal = callback(iterableItem.key(keyOrIndex), iterableItem.getItem(iterableItem.key(keyOrIndex))); if (retVal === false) { break; } } } // `DataTransferItemList` & `NodeList` objects are array-like and should be treated as arrays // when iterating over items inside the object. else if (qq.isArray(iterableItem) || qq.isItemList(iterableItem) || qq.isNodeList(iterableItem)) { for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) { retVal = callback(keyOrIndex, iterableItem[keyOrIndex]); if (retVal === false) { break; } } } else if (qq.isString(iterableItem)) { for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) { retVal = callback(keyOrIndex, iterableItem.charAt(keyOrIndex)); if (retVal === false) { break; } } } else { for (keyOrIndex in iterableItem) { if (Object.prototype.hasOwnProperty.call(iterableItem, keyOrIndex)) { retVal = callback(keyOrIndex, iterableItem[keyOrIndex]); if (retVal === false) { break; } } } } } }; //include any args that should be passed to the new function after the context arg qq.bind = function(oldFunc, context) { if (qq.isFunction(oldFunc)) { var args = Array.prototype.slice.call(arguments, 2); return function() { var newArgs = qq.extend([], args); if (arguments.length) { newArgs = newArgs.concat(Array.prototype.slice.call(arguments)); } return oldFunc.apply(context, newArgs); }; } throw new Error("first parameter must be a function!"); }; /** * obj2url() takes a json-object as argument and generates * a querystring. pretty much like jQuery.param() * * how to use: * * `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');` * * will result in: * * `http://any.url/upload?otherParam=value&a=b&c=d` * * @param Object JSON-Object * @param String current querystring-part * @return String encoded querystring */ qq.obj2url = function(obj, temp, prefixDone) { /*jshint laxbreak: true*/ var uristrings = [], prefix = "&", add = function(nextObj, i) { var nextTemp = temp ? (/\[\]$/.test(temp)) // prevent double-encoding ? temp : temp + "[" + i + "]" : i; if ((nextTemp !== "undefined") && (i !== "undefined")) { uristrings.push( (typeof nextObj === "object") ? qq.obj2url(nextObj, nextTemp, true) : (Object.prototype.toString.call(nextObj) === "[object Function]") ? encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj()) : encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj) ); } }; if (!prefixDone && temp) { prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? "" : "&" : "?"; uristrings.push(temp); uristrings.push(qq.obj2url(obj)); } else if ((Object.prototype.toString.call(obj) === "[object Array]") && (typeof obj !== "undefined")) { qq.each(obj, function(idx, val) { add(val, idx); }); } else if ((typeof obj !== "undefined") && (obj !== null) && (typeof obj === "object")) { qq.each(obj, function(prop, val) { add(val, prop); }); } else { uristrings.push(encodeURIComponent(temp) + "=" + encodeURIComponent(obj)); } if (temp) { return uristrings.join(prefix); } else { return uristrings.join(prefix) .replace(/^&/, "") .replace(/%20/g, "+"); } }; qq.obj2FormData = function(obj, formData, arrayKeyName) { if (!formData) { formData = new FormData(); } qq.each(obj, function(key, val) { key = arrayKeyName ? arrayKeyName + "[" + key + "]" : key; if (qq.isObject(val)) { qq.obj2FormData(val, formData, key); } else if (qq.isFunction(val)) { formData.append(key, val()); } else { formData.append(key, val); } }); return formData; }; qq.obj2Inputs = function(obj, form) { var input; if (!form) { form = document.createElement("form"); } qq.obj2FormData(obj, { append: function(key, val) { input = document.createElement("input"); input.setAttribute("name", key); input.setAttribute("value", val); form.appendChild(input); } }); return form; }; /** * Not recommended for use outside of Fine Uploader since this falls back to an unchecked eval if JSON.parse is not * implemented. For a more secure JSON.parse polyfill, use Douglas Crockford's json2.js. */ qq.parseJson = function(json) { /*jshint evil: true*/ if (window.JSON && qq.isFunction(JSON.parse)) { return JSON.parse(json); } else { return eval("(" + json + ")"); } }; /** * Retrieve the extension of a file, if it exists. * * @param filename * @returns {string || undefined} */ qq.getExtension = function(filename) { var extIdx = filename.lastIndexOf(".") + 1; if (extIdx > 0) { return filename.substr(extIdx, filename.length - extIdx); } }; qq.getFilename = function(blobOrFileInput) { /*jslint regexp: true*/ if (qq.isInput(blobOrFileInput)) { // get input value and remove path to normalize return blobOrFileInput.value.replace(/.*(\/|\\)/, ""); } else if (qq.isFile(blobOrFileInput)) { if (blobOrFileInput.fileName !== null && blobOrFileInput.fileName !== undefined) { return blobOrFileInput.fileName; } } return blobOrFileInput.name; }; /** * A generic module which supports object disposing in dispose() method. * */ qq.DisposeSupport = function() { var disposers = []; return { /** Run all registered disposers */ dispose: function() { var disposer; do { disposer = disposers.shift(); if (disposer) { disposer(); } } while (disposer); }, /** Attach event handler and register de-attacher as a disposer */ attach: function() { var args = arguments; /*jslint undef:true*/ this.addDisposer(qq(args[0]).attach.apply(this, Array.prototype.slice.call(arguments, 1))); }, /** Add disposer to the collection */ addDisposer: function(disposeFunction) { disposers.push(disposeFunction); } }; }; }()); /* globals qq */ /** * Fine Uploader top-level Error container. Inherits from `Error`. */ (function() { "use strict"; qq.Error = function(message) { this.message = "[Fine Uploader " + qq.version + "] " + message; }; qq.Error.prototype = new Error(); }()); /*global qq */ qq.version = "5.3.2"; /* globals qq */ qq.supportedFeatures = (function() { "use strict"; var supportsUploading, supportsUploadingBlobs, supportsFileDrop, supportsAjaxFileUploading, supportsFolderDrop, supportsChunking, supportsResume, supportsUploadViaPaste, supportsUploadCors, supportsDeleteFileXdr, supportsDeleteFileCorsXhr, supportsDeleteFileCors, supportsFolderSelection, supportsImagePreviews, supportsUploadProgress; function testSupportsFileInputElement() { var supported = true, tempInput; try { tempInput = document.createElement("input"); tempInput.type = "file"; qq(tempInput).hide(); if (tempInput.disabled) { supported = false; } } catch (ex) { supported = false; } return supported; } //only way to test for Filesystem API support since webkit does not expose the DataTransfer interface function isChrome21OrHigher() { return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[2][1-9]|Chrome\/[3-9][0-9]/) !== undefined; } //only way to test for complete Clipboard API support at this time function isChrome14OrHigher() { return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[1][4-9]|Chrome\/[2-9][0-9]/) !== undefined; } //Ensure we can send cross-origin `XMLHttpRequest`s function isCrossOriginXhrSupported() { if (window.XMLHttpRequest) { var xhr = qq.createXhrInstance(); //Commonly accepted test for XHR CORS support. return xhr.withCredentials !== undefined; } return false; } //Test for (terrible) cross-origin ajax transport fallback for IE9 and IE8 function isXdrSupported() { return window.XDomainRequest !== undefined; } // CORS Ajax requests are supported if it is either possible to send credentialed `XMLHttpRequest`s, // or if `XDomainRequest` is an available alternative. function isCrossOriginAjaxSupported() { if (isCrossOriginXhrSupported()) { return true; } return isXdrSupported(); } function isFolderSelectionSupported() { // We know that folder selection is only supported in Chrome via this proprietary attribute for now return document.createElement("input").webkitdirectory !== undefined; } function isLocalStorageSupported() { try { return !!window.localStorage; } catch (error) { // probably caught a security exception, so no localStorage for you return false; } } function isDragAndDropSupported() { var span = document.createElement("span"); return ("draggable" in span || ("ondragstart" in span && "ondrop" in span)) && !qq.android() && !qq.ios(); } supportsUploading = testSupportsFileInputElement(); supportsAjaxFileUploading = supportsUploading && qq.isXhrUploadSupported(); supportsUploadingBlobs = supportsAjaxFileUploading && !qq.androidStock(); supportsFileDrop = supportsAjaxFileUploading && isDragAndDropSupported(); supportsFolderDrop = supportsFileDrop && isChrome21OrHigher(); supportsChunking = supportsAjaxFileUploading && qq.isFileChunkingSupported(); supportsResume = supportsAjaxFileUploading && supportsChunking && isLocalStorageSupported(); supportsUploadViaPaste = supportsAjaxFileUploading && isChrome14OrHigher(); supportsUploadCors = supportsUploading && (window.postMessage !== undefined || supportsAjaxFileUploading); supportsDeleteFileCorsXhr = isCrossOriginXhrSupported(); supportsDeleteFileXdr = isXdrSupported(); supportsDeleteFileCors = isCrossOriginAjaxSupported(); supportsFolderSelection = isFolderSelectionSupported(); supportsImagePreviews = supportsAjaxFileUploading && window.FileReader !== undefined; supportsUploadProgress = (function() { if (supportsAjaxFileUploading) { return !qq.androidStock() && !qq.iosChrome(); } return false; }()); return { ajaxUploading: supportsAjaxFileUploading, blobUploading: supportsUploadingBlobs, canDetermineSize: supportsAjaxFileUploading, chunking: supportsChunking, deleteFileCors: supportsDeleteFileCors, deleteFileCorsXdr: supportsDeleteFileXdr, //NOTE: will also return true in IE10, where XDR is also supported deleteFileCorsXhr: supportsDeleteFileCorsXhr, dialogElement: !!window.HTMLDialogElement, fileDrop: supportsFileDrop, folderDrop: supportsFolderDrop, folderSelection: supportsFolderSelection, imagePreviews: supportsImagePreviews, imageValidation: supportsImagePreviews, itemSizeValidation: supportsAjaxFileUploading, pause: supportsChunking, progressBar: supportsUploadProgress, resume: supportsResume, scaling: supportsImagePreviews && supportsUploadingBlobs, tiffPreviews: qq.safari(), // Not the best solution, but simple and probably accurate enough (for now) unlimitedScaledImageSize: !qq.ios(), // false simply indicates that there is some known limit uploading: supportsUploading, uploadCors: supportsUploadCors, uploadCustomHeaders: supportsAjaxFileUploading, uploadNonMultipart: supportsAjaxFileUploading, uploadViaPaste: supportsUploadViaPaste }; }()); /*globals qq*/ // Is the passed object a promise instance? qq.isGenericPromise = function(maybePromise) { "use strict"; return !!(maybePromise && maybePromise.then && qq.isFunction(maybePromise.then)); }; qq.Promise = function() { "use strict"; var successArgs, failureArgs, successCallbacks = [], failureCallbacks = [], doneCallbacks = [], state = 0; qq.extend(this, { then: function(onSuccess, onFailure) { if (state === 0) { if (onSuccess) { successCallbacks.push(onSuccess); } if (onFailure) { failureCallbacks.push(onFailure); } } else if (state === -1) { onFailure && onFailure.apply(null, failureArgs); } else if (onSuccess) { onSuccess.apply(null, successArgs); } return this; }, done: function(callback) { if (state === 0) { doneCallbacks.push(callback); } else { callback.apply(null, failureArgs === undefined ? successArgs : failureArgs); } return this; }, success: function() { state = 1; successArgs = arguments; if (successCallbacks.length) { qq.each(successCallbacks, function(idx, callback) { callback.apply(null, successArgs); }); } if (doneCallbacks.length) { qq.each(doneCallbacks, function(idx, callback) { callback.apply(null, successArgs); }); } return this; }, failure: function() { state = -1; failureArgs = arguments; if (failureCallbacks.length) { qq.each(failureCallbacks, function(idx, callback) { callback.apply(null, failureArgs); }); } if (doneCallbacks.length) { qq.each(doneCallbacks, function(idx, callback) { callback.apply(null, failureArgs); }); } return this; } }); }; /* globals qq */ /** * Placeholder for a Blob that will be generated on-demand. * * @param referenceBlob Parent of the generated blob * @param onCreate Function to invoke when the blob must be created. Must be promissory. * @constructor */ qq.BlobProxy = function(referenceBlob, onCreate) { "use strict"; qq.extend(this, { referenceBlob: referenceBlob, create: function() { return onCreate(referenceBlob); } }); }; /*globals qq*/ /** * This module represents an upload or "Select File(s)" button. It's job is to embed an opaque `<input type="file">` * element as a child of a provided "container" element. This "container" element (`options.element`) is used to provide * a custom style for the `<input type="file">` element. The ability to change the style of the container element is also * provided here by adding CSS classes to the container on hover/focus. * * TODO Eliminate the mouseover and mouseout event handlers since the :hover CSS pseudo-class should now be * available on all supported browsers. * * @param o Options to override the default values */ qq.UploadButton = function(o) { "use strict"; var self = this, disposeSupport = new qq.DisposeSupport(), options = { // "Container" element element: null, // If true adds `multiple` attribute to `<input type="file">` multiple: false, // Corresponds to the `accept` attribute on the associated `<input type="file">` acceptFiles: null, // A true value allows folders to be selected, if supported by the UA folders: false, // `name` attribute of `<input type="file">` name: "qqfile", // Called when the browser invokes the onchange handler on the `<input type="file">` onChange: function(input) {}, ios8BrowserCrashWorkaround: false, // **This option will be removed** in the future as the :hover CSS pseudo-class is available on all supported browsers hoverClass: "qq-upload-button-hover", focusClass: "qq-upload-button-focus" }, input, buttonId; // Overrides any of the default option values with any option values passed in during construction. qq.extend(options, o); buttonId = qq.getUniqueId(); // Embed an opaque `<input type="file">` element as a child of `options.element`. function createInput() { var input = document.createElement("input"); input.setAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME, buttonId); input.setAttribute("title", "file input"); self.setMultiple(options.multiple, input); if (options.folders && qq.supportedFeatures.folderSelection) { // selecting directories is only possible in Chrome now, via a vendor-specific prefixed attribute input.setAttribute("webkitdirectory", ""); } if (options.acceptFiles) { input.setAttribute("accept", options.acceptFiles); } input.setAttribute("type", "file"); input.setAttribute("name", options.name); qq(input).css({ position: "absolute", // in Opera only 'browse' button // is clickable and it is located at // the right side of the input right: 0, top: 0, fontFamily: "Arial", // It's especially important to make this an arbitrarily large value // to ensure the rendered input button in IE takes up the entire // space of the container element. Otherwise, the left side of the // button will require a double-click to invoke the file chooser. // In other browsers, this might cause other issues, so a large font-size // is only used in IE. There is a bug in IE8 where the opacity style is ignored // in some cases when the font-size is large. So, this workaround is not applied // to IE8. fontSize: qq.ie() && !qq.ie8() ? "3500px" : "118px", margin: 0, padding: 0, cursor: "pointer", opacity: 0 }); // Setting the file input's height to 100% in IE7 causes // most of the visible button to be unclickable. !qq.ie7() && qq(input).css({height: "100%"}); options.element.appendChild(input); disposeSupport.attach(input, "change", function() { options.onChange(input); }); // **These event handlers will be removed** in the future as the :hover CSS pseudo-class is available on all supported browsers disposeSupport.attach(input, "mouseover", function() { qq(options.element).addClass(options.hoverClass); }); disposeSupport.attach(input, "mouseout", function() { qq(options.element).removeClass(options.hoverClass); }); disposeSupport.attach(input, "focus", function() { qq(options.element).addClass(options.focusClass); }); disposeSupport.attach(input, "blur", function() { qq(options.element).removeClass(options.focusClass); }); return input; } // Make button suitable container for input qq(options.element).css({ position: "relative", overflow: "hidden", // Make sure browse button is in the right side in Internet Explorer direction: "ltr" }); // Exposed API qq.extend(this, { getInput: function() { return input; }, getButtonId: function() { return buttonId; }, setMultiple: function(isMultiple, optInput) { var input = optInput || this.getInput(); // Temporary workaround for bug in in iOS8 UIWebView that causes the browser to crash // before the file chooser appears if the file input doesn't contain a multiple attribute. // See #1283. if (options.ios8BrowserCrashWorkaround && qq.ios8() && (qq.iosChrome() || qq.iosSafariWebView())) { input.setAttribute("multiple", ""); } else { if (isMultiple) { input.setAttribute("multiple", ""); } else { input.removeAttribute("multiple"); } } }, setAcceptFiles: function(acceptFiles) { if (acceptFiles !== options.acceptFiles) { input.setAttribute("accept", acceptFiles); } }, reset: function() { if (input.parentNode) { qq(input).remove(); } qq(options.element).removeClass(options.focusClass); input = null; input = createInput(); } }); input = createInput(); }; qq.UploadButton.BUTTON_ID_ATTR_NAME = "qq-button-id"; /*globals qq */ qq.UploadData = function(uploaderProxy) { "use strict"; var data = [], byUuid = {}, byStatus = {}, byProxyGroupId = {}, byBatchId = {}; function getDataByIds(idOrIds) { if (qq.isArray(idOrIds)) { var entries = []; qq.each(idOrIds, function(idx, id) { entries.push(data[id]); }); return entries; } return data[idOrIds]; } function getDataByUuids(uuids) { if (qq.isArray(uuids)) { var entries = []; qq.each(uuids, function(idx, uuid) { entries.push(data[byUuid[uuid]]); }); return entries; } return data[byUuid[uuids]]; } function getDataByStatus(status) { var statusResults = [], statuses = [].concat(status); qq.each(statuses, function(index, statusEnum) { var statusResultIndexes = byStatus[statusEnum]; if (statusResultIndexes !== undefined) { qq.each(statusResultIndexes, function(i, dataIndex) { statusResults.push(data[dataIndex]); }); } }); return statusResults; } qq.extend(this, { /** * Adds a new file to the data cache for tracking purposes. * * @param spec Data that describes this file. Possible properties are: * * - uuid: Initial UUID for this file. * - name: Initial name of this file. * - size: Size of this file, omit if this cannot be determined * - status: Initial `qq.status` for this file. Omit for `qq.status.SUBMITTING`. * - batchId: ID of the batch this file belongs to * - proxyGroupId: ID of the proxy group associated with this file * * @returns {number} Internal ID for this file. */ addFile: function(spec) { var status = spec.status || qq.status.SUBMITTING, id = data.push({ name: spec.name, originalName: spec.name, uuid: spec.uuid, size: spec.size == null ? -1 : spec.size, status: status }) - 1; if (spec.batchId) { data[id].batchId = spec.batchId; if (byBatchId[spec.batchId] === undefined) { byBatchId[spec.batchId] = []; } byBatchId[spec.batchId].push(id); } if (spec.proxyGroupId) { data[id].proxyGroupId = spec.proxyGroupId; if (byProxyGroupId[spec.proxyGroupId] === undefined) { byProxyGroupId[spec.proxyGroupId] = []; } byProxyGroupId[spec.proxyGroupId].push(id); } data[id].id = id; byUuid[spec.uuid] = id; if (byStatus[status] === undefined) { byStatus[status] = []; } byStatus[status].push(id); uploaderProxy.onStatusChange(id, null, status); return id; }, retrieve: function(optionalFilter) { if (qq.isObject(optionalFilter) && data.length) { if (optionalFilter.id !== undefined) { return getDataByIds(optionalFilter.id); } else if (optionalFilter.uuid !== undefined) { return getDataByUuids(optionalFilter.uuid); } else if (optionalFilter.status) { return getDataByStatus(optionalFilter.status); } } else { return qq.extend([], data, true); } }, reset: function() { data = []; byUuid = {}; byStatus = {}; byBatchId = {}; }, setStatus: function(id, newStatus) { var oldStatus = data[id].status, byStatusOldStatusIndex = qq.indexOf(byStatus[oldStatus], id); byStatus[oldStatus].splice(byStatusOldStatusIndex, 1); data[id].status = newStatus; if (byStatus[newStatus] === undefined) { byStatus[newStatus] = []; } byStatus[newStatus].push(id); uploaderProxy.onStatusChange(id, oldStatus, newStatus); }, uuidChanged: function(id, newUuid) { var oldUuid = data[id].uuid; data[id].uuid = newUuid; byUuid[newUuid] = id; delete byUuid[oldUuid]; }, updateName: function(id, newName) { data[id].name = newName; }, updateSize: function(id, newSize) { data[id].size = newSize; }, // Only applicable if this file has a parent that we may want to reference later. setParentId: function(targetId, parentId) { data[targetId].parentId = parentId; }, getIdsInProxyGroup: function(id) { var proxyGroupId = data[id].proxyGroupId; if (proxyGroupId) { return byProxyGroupId[proxyGroupId]; } return []; }, getIdsInBatch: function(id) { var batchId = data[id].batchId; return byBatchId[batchId]; } }); }; qq.status = { SUBMITTING: "submitting", SUBMITTED: "submitted", REJECTED: "rejected", QUEUED: "queued", CANCELED: "canceled", PAUSED: "paused", UPLOADING: "uploading", UPLOAD_RETRYING: "retrying upload", UPLOAD_SUCCESSFUL: "upload successful", UPLOAD_FAILED: "upload failed", DELETE_FAILED: "delete failed", DELETING: "deleting", DELETED: "deleted" }; /*globals qq*/ /** * Defines the public API for FineUploaderBasic mode. */ (function() { "use strict"; qq.basePublicApi = { // DEPRECATED - TODO REMOVE IN NEXT MAJOR RELEASE (replaced by addFiles) addBlobs: function(blobDataOrArray, params, endpoint) { this.addFiles(blobDataOrArray, params, endpoint); }, addFiles: function(data, params, endpoint) { this._maybeHandleIos8SafariWorkaround(); var batchId = this._storedIds.length === 0 ? qq.getUniqueId() : this._currentBatchId, processBlob = qq.bind(function(blob) { this._handleNewFile({ blob: blob, name: this._options.blobs.defaultName }, batchId, verifiedFiles); }, this), processBlobData = qq.bind(function(blobData) { this._handleNewFile(blobData, batchId, verifiedFiles); }, this), processCanvas = qq.bind(function(canvas) { var blob = qq.canvasToBlob(canvas); this._handleNewFile({ blob: blob, name: this._options.blobs.defaultName + ".png" }, batchId, verifiedFiles); }, this), processCanvasData = qq.bind(function(canvasData) { var normalizedQuality = canvasData.quality && canvasData.quality / 100, blob = qq.canvasToBlob(canvasData.canvas, canvasData.type, normalizedQuality); this._handleNewFile({ blob: blob, name: canvasData.name }, batchId, verifiedFiles); }, this), processFileOrInput = qq.bind(function(fileOrInput) { if (qq.isInput(fileOrInput) && qq.supportedFeatures.ajaxUploading) { var files = Array.prototype.slice.call(fileOrInput.files), self = this; qq.each(files, function(idx, file) { self._handleNewFile(file, batchId, verifiedFiles); }); } else { this._handleNewFile(fileOrInput, batchId, verifiedFiles); } }, this), normalizeData = function() { if (qq.isFileList(data)) { data = Array.prototype.slice.call(data); } data = [].concat(data); }, self = this, verifiedFiles = []; this._currentBatchId = batchId; if (data) { normalizeData(); qq.each(data, function(idx, fileContainer) { if (qq.isFileOrInput(fileContainer)) { processFileOrInput(fileContainer); } else if (qq.isBlob(fileContainer)) { processBlob(fileContainer); } else if (qq.isObject(fileContainer)) { if (fileContainer.blob && fileContainer.name) { processBlobData(fileContainer); } else if (fileContainer.canvas && fileContainer.name) { processCanvasData(fileContainer); } } else if (fileContainer.tagName && fileContainer.tagName.toLowerCase() === "canvas") { processCanvas(fileContainer); } else { self.log(fileContainer + " is not a valid file container! Ignoring!", "warn"); } }); this.log("Received " + verifiedFiles.length + " files."); this._prepareItemsForUpload(verifiedFiles, params, endpoint); } }, cancel: function(id) { this._handler.cancel(id); }, cancelAll: function() { var storedIdsCopy = [], self = this; qq.extend(storedIdsCopy, this._storedIds); qq.each(storedIdsCopy, function(idx, storedFileId) { self.cancel(storedFileId); }); this._handler.cancelAll(); }, clearStoredFiles: function() { this._storedIds = []; }, continueUpload: function(id) { var uploadData = this._uploadData.retrieve({id: id}); if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) { return false; } if (uploadData.status === qq.status.PAUSED) { this.log(qq.format("Paused file ID {} ({}) will be continued. Not paused.", id, this.getName(id))); this._uploadFile(id); return true; } else { this.log(qq.format("Ignoring continue for file ID {} ({}). Not paused.", id, this.getName(id)), "error"); } return false; }, deleteFile: function(id) { return this._onSubmitDelete(id); }, // TODO document? doesExist: function(fileOrBlobId) { return this._handler.isValid(fileOrBlobId); }, // Generate a variable size thumbnail on an img or canvas, // returning a promise that is fulfilled when the attempt completes. // Thumbnail can either be based off of a URL for an image returned // by the server in the upload response, or the associated `Blob`. drawThumbnail: function(fileId, imgOrCanvas, maxSize, fromServer) { var promiseToReturn = new qq.Promise(), fileOrUrl, options; if (this._imageGenerator) { fileOrUrl = this._thumbnailUrls[fileId]; options = { scale: maxSize > 0, maxSize: maxSize > 0 ? maxSize : null }; // If client-side preview generation is possible // and we are not specifically looking for the image URl returned by the server... if (!fromServer && qq.supportedFeatures.imagePreviews) { fileOrUrl = this.getFile(fileId); } /* jshint eqeqeq:false,eqnull:true */ if (fileOrUrl == null) { promiseToReturn.failure({container: imgOrCanvas, error: "File or URL not found."}); } else { this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options).then( function success(modifiedContainer) { promiseToReturn.success(modifiedContainer); }, function failure(container, reason) { promiseToReturn.failure({container: container, error: reason || "Problem generating thumbnail"}); } ); } } else { promiseToReturn.failure({container: imgOrCanvas, error: "Missing image generator module"}); } return promiseToReturn; }, getButton: function(fileId) { return this._getButton(this._buttonIdsForFileIds[fileId]); }, getEndpoint: function(fileId) { return this._endpointStore.get(fileId); }, getFile: function(fileOrBlobId) { return this._handler.getFile(fileOrBlobId) || null; }, getInProgress: function() { return this._uploadData.retrieve({ status: [ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING, qq.status.QUEUED ] }).length; }, getName: function(id) { return this._uploadData.retrieve({id: id}).name; }, // Parent ID for a specific file, or null if this is the parent, or if it has no parent. getParentId: function(id) { var uploadDataEntry = this.getUploads({id: id}), parentId = null; if (uploadDataEntry) { if (uploadDataEntry.parentId !== undefined) { parentId = uploadDataEntry.parentId; } } return parentId; }, getResumableFilesData: function() { return this._handler.getResumableFilesData(); }, getSize: function(id) { return this._uploadData.retrieve({id: id}).size; }, getNetUploads: function() { return this._netUploaded; }, getRemainingAllowedItems: function() { var allowedItems = this._currentItemLimit; if (allowedItems > 0) { return allowedItems - this._netUploadedOrQueued; } return null; }, getUploads: function(optionalFilter) { return this._uploadData.retrieve(optionalFilter); }, getUuid: function(id) { return this._uploadData.retrieve({id: id}).uuid; }, log: function(str, level) { if (this._options.debug && (!level || level === "info")) { qq.log("[Fine Uploader " + qq.version + "] " + str); } else if (level && level !== "info") { qq.log("[Fine Uploader " + qq.version + "] " + str, level); } }, pauseUpload: function(id) { var uploadData = this._uploadData.retrieve({id: id}); if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) { return false; } // Pause only really makes sense if the file is uploading or retrying if (qq.indexOf([qq.status.UPLOADING, qq.status.UPLOAD_RETRYING], uploadData.status) >= 0) { if (this._handler.pause(id)) { this._uploadData.setStatus(id, qq.status.PAUSED); return true; } else { this.log(qq.format("Unable to pause file ID {} ({}).", id, this.getName(id)), "error"); } } else { this.log(qq.format("Ignoring pause for file ID {} ({}). Not in progress.", id, this.getName(id)), "error"); } return false; }, reset: function() { this.log("Resetting uploader..."); this._handler.reset(); this._storedIds = []; this._autoRetries = []; this._retryTimeouts = []; this._preventRetries = []; this._thumbnailUrls = []; qq.each(this._buttons, function(idx, button) { button.reset(); }); this._paramsStore.reset(); this._endpointStore.reset(); this._netUploadedOrQueued = 0; this._netUploaded = 0; this._uploadData.reset(); this._buttonIdsForFileIds = []; this._pasteHandler && this._pasteHandler.reset(); this._options.session.refreshOnReset && this._refreshSessionData(); this._succeededSinceLastAllComplete = []; this._failedSinceLastAllComplete = []; this._totalProgress && this._totalProgress.reset(); }, retry: function(id) { return this._manualRetry(id); }, scaleImage: function(id, specs) { var self = this; return qq.Scaler.prototype.scaleImage(id, specs, { log: qq.bind(self.log, self), getFile: qq.bind(self.getFile, self), uploadData: self._uploadData }); }, setCustomHeaders: function(headers, id) { this._customHeadersStore.set(headers, id); }, setDeleteFileCustomHeaders: function(headers, id) { this._deleteFileCustomHeadersStore.set(headers, id); }, setDeleteFileEndpoint: function(endpoint, id) { this._deleteFileEndpointStore.set(endpoint, id); }, setDeleteFileParams: function(params, id) { this._deleteFileParamsStore.set(params, id); }, // Re-sets the default endpoint, an endpoint for a specific file, or an endpoint for a specific button setEndpoint: function(endpoint, id) { this._endpointStore.set(endpoint, id); }, setForm: function(elementOrId) { this._updateFormSupportAndParams(elementOrId); }, setItemLimit: function(newItemLimit) { this._currentItemLimit = newItemLimit; }, setName: function(id, newName) { this._uploadData.updateName(id, newName); }, setParams: function(params, id) { this._paramsStore.set(params, id); }, setUuid: function(id, newUuid) { return this._uploadData.uuidChanged(id, newUuid); }, uploadStoredFiles: function() { if (this._storedIds.length === 0) { this._itemError("noFilesError"); } else { this._uploadStoredFiles(); } } }; /** * Defines the private (internal) API for FineUploaderBasic mode. */ qq.basePrivateApi = { // Updates internal state with a file record (not backed by a live file). Returns the assigned ID. _addCannedFile: function(sessionData) { var id = this._uploadData.addFile({ uuid: sessionData.uuid, name: sessionData.name, size: sessionData.size, status: qq.status.UPLOAD_SUCCESSFUL }); sessionData.deleteFileEndpoint && this.setDeleteFileEndpoint(sessionData.deleteFileEndpoint, id); sessionData.deleteFileParams && this.setDeleteFileParams(sessionData.deleteFileParams, id); if (sessionData.thumbnailUrl) { this._thumbnailUrls[id] = sessionData.thumbnailUrl; } this._netUploaded++; this._netUploadedOrQueued++; return id; }, _annotateWithButtonId: function(file, associatedInput) { if (qq.isFile(file)) { file.qqButtonId = this._getButtonId(associatedInput); } }, _batchError: function(message) { this._options.callbacks.onError(null, null, message, undefined); }, _createDeleteHandler: function() { var self = this; return new qq.DeleteFileAjaxRequester({ method: this._options.deleteFile.method.toUpperCase(), maxConnections: this._options.maxConnections, uuidParamName: this._options.request.uuidName, customHeaders: this._deleteFileCustomHeadersStore, paramsStore: this._deleteFileParamsStore, endpointStore: this._deleteFileEndpointStore, cors: this._options.cors, log: qq.bind(self.log, self), onDelete: function(id) { self._onDelete(id); self._options.callbacks.onDelete(id); }, onDeleteComplete: function(id, xhrOrXdr, isError) { self._onDeleteComplete(id, xhrOrXdr, isError); self._options.callbacks.onDeleteComplete(id, xhrOrXdr, isError); } }); }, _createPasteHandler: function() { var self = this; return new qq.PasteSupport({ targetElement: this._options.paste.targetElement, callbacks: { log: qq.bind(self.log, self), pasteReceived: function(blob) { self._handleCheckedCallback({ name: "onPasteReceived", callback: qq.bind(self._options.callbacks.onPasteReceived, self, blob), onSuccess: qq.bind(self._handlePasteSuccess, self, blob), identifier: "pasted image" }); } } }); }, _createStore: function(initialValue, _readOnlyValues_) { var store = {}, catchall = initialValue, perIdReadOnlyValues = {}, readOnlyValues = _readOnlyValues_, copy = function(orig) { if (qq.isObject(orig)) { return qq.extend({}, orig); } return orig; }, getReadOnlyValues = function() { if (qq.isFunction(readOnlyValues)) { return readOnlyValues(); } return readOnlyValues; }, includeReadOnlyValues = function(id, existing) { if (readOnlyValues && qq.isObject(existing)) { qq.extend(existing, getReadOnlyValues()); } if (perIdReadOnlyValues[id]) { qq.extend(existing, perIdReadOnlyValues[id]); } }; return { set: function(val, id) { /*jshint eqeqeq: true, eqnull: true*/ if (id == null) { store = {}; catchall = copy(val); } else { store[id] = copy(val); } }, get: function(id) { var values; /*jshint eqeqeq: true, eqnull: true*/ if (id != null && store[id]) { values = store[id]; } else { values = copy(catchall); } includeReadOnlyValues(id, values); return copy(values); }, addReadOnly: function(id, values) { // Only applicable to Object stores if (qq.isObject(store)) { // If null ID, apply readonly values to all files if (id === null) { if (qq.isFunction(values)) { readOnlyValues = values; } else { readOnlyValues = readOnlyValues || {}; qq.extend(readOnlyValues, values); } } else { perIdReadOnlyValues[id] = perIdReadOnlyValues[id] || {}; qq.extend(perIdReadOnlyValues[id], values); } } }, remove: function(fileId) { return delete store[fileId]; }, reset: function() { store = {}; perIdReadOnlyValues = {}; catchall = initialValue; } }; }, _createUploadDataTracker: function() { var self = this; return new qq.UploadData({ getName: function(id) { return self.getName(id); }, getUuid: function(id) { return self.getUuid(id); }, getSize: function(id) { return self.getSize(id); }, onStatusChange: function(id, oldStatus, newStatus) { self._onUploadStatusChange(id, oldStatus, newStatus); self._options.callbacks.onStatusChange(id, oldStatus, newStatus); self._maybeAllComplete(id, newStatus); if (self._totalProgress) { setTimeout(function() { self._totalProgress.onStatusChange(id, oldStatus, newStatus); }, 0); } } }); }, /** * Generate a tracked upload button. * * @param spec Object containing a required `element` property * along with optional `multiple`, `accept`, and `folders`. * @returns {qq.UploadButton} * @private */ _createUploadButton: function(spec) { var self = this, acceptFiles = spec.accept || this._options.validation.acceptFiles, allowedExtensions = spec.allowedExtensions || this._options.validation.allowedExtensions, button; function allowMultiple() { if (qq.supportedFeatures.ajaxUploading) { // Workaround for bug in iOS7+ (see #1039) if (self._options.workarounds.iosEmptyVideos && qq.ios() && !qq.ios6() && self._isAllowedExtension(allowedExtensions, ".mov")) { return false; } if (spec.multiple === undefined) { return self._options.multiple; } return spec.multiple; } return false; } button = new qq.UploadButton({ element: spec.element, folders: spec.folders, name: this._options.request.inputName, multiple: allowMultiple(), acceptFiles: acceptFiles, onChange: function(input) { self._onInputChange(input); }, hoverClass: this._options.classes.buttonHover, focusClass: this._options.classes.buttonFocus, ios8BrowserCrashWorkaround: this._options.workarounds.ios8BrowserCrash }); this._disposeSupport.addDisposer(function() { button.dispose(); }); self._buttons.push(button); return button; }, _createUploadHandler: function(additionalOptions, namespace) { var self = this, lastOnProgress = {}, options = { debug: this._options.debug, maxConnections: this._options.maxConnections, cors: this._options.cors, paramsStore: this._paramsStore, endpointStore: this._endpointStore, chunking: this._options.chunking, resume: this._options.resume, blobs: this._options.blobs, log: qq.bind(self.log, self), preventRetryParam: this._options.retry.preventRetryResponseProperty, onProgress: function(id, name, loaded, total) { if (loaded < 0 || total < 0) { return; } if (lastOnProgress[id]) { if (lastOnProgress[id].loaded !== loaded || lastOnProgress[id].total !== total) { self._onProgress(id, name, loaded, total); self._options.callbacks.onProgress(id, name, loaded, total); } } else { self._onProgress(id, name, loaded, total); self._options.callbacks.onProgress(id, name, loaded, total); } lastOnProgress[id] = {loaded: loaded, total: total}; }, onComplete: function(id, name, result, xhr) { delete lastOnProgress[id]; var status = self.getUploads({id: id}).status, retVal; // This is to deal with some observed cases where the XHR readyStateChange handler is // invoked by the browser multiple times for the same XHR instance with the same state // readyState value. Higher level: don't invoke complete-related code if we've already // done this. if (status === qq.status.UPLOAD_SUCCESSFUL || status === qq.status.UPLOAD_FAILED) { return; } retVal = self._onComplete(id, name, result, xhr); // If the internal `_onComplete` handler returns a promise, don't invoke the `onComplete` callback // until the promise has been fulfilled. if (retVal instanceof qq.Promise) { retVal.done(function() { self._options.callbacks.onComplete(id, name, result, xhr); }); } else { self._options.callbacks.onComplete(id, name, result, xhr); } }, onCancel: function(id, name, cancelFinalizationEffort) { var promise = new qq.Promise(); self._handleCheckedCallback({ name: "onCancel", callback: qq.bind(self._options.callbacks.onCancel, self, id, name), onFailure: promise.failure, onSuccess: function() { cancelFinalizationEffort.then(function() { self._onCancel(id, name); }); promise.success(); }, identifier: id }); return promise; }, onUploadPrep: qq.bind(this._onUploadPrep, this), onUpload: function(id, name) { self._onUpload(id, name); self._options.callbacks.onUpload(id, name); }, onUploadChunk: function(id, name, chunkData) { self._onUploadChunk(id, chunkData); self._options.callbacks.onUploadChunk(id, name, chunkData); }, onUploadChunkSuccess: function(id, chunkData, result, xhr) { self._options.callbacks.onUploadChunkSuccess.apply(self, arguments); }, onResume: function(id, name, chunkData) { return self._options.callbacks.onResume(id, name, chunkData); }, onAutoRetry: function(id, name, responseJSON, xhr) { return self._onAutoRetry.apply(self, arguments); }, onUuidChanged: function(id, newUuid) { self.log("Server requested UUID change from '" + self.getUuid(id) + "' to '" + newUuid + "'"); self.setUuid(id, newUuid); }, getName: qq.bind(self.getName, self), getUuid: qq.bind(self.getUuid, self), getSize: qq.bind(self.getSize, self), setSize: qq.bind(self._setSize, self), getDataByUuid: function(uuid) { return self.getUploads({uuid: uuid}); }, isQueued: function(id) { var status = self.getUploads({id: id}).status; return status === qq.status.QUEUED || status === qq.status.SUBMITTED || status === qq.status.UPLOAD_RETRYING || status === qq.status.PAUSED; }, getIdsInProxyGroup: self._uploadData.getIdsInProxyGroup, getIdsInBatch: self._uploadData.getIdsInBatch }; qq.each(this._options.request, function(prop, val) { options[prop] = val; }); options.customHeaders = this._customHeadersStore; if (additionalOptions) { qq.each(additionalOptions, function(key, val) { options[key] = val; }); } return new qq.UploadHandlerController(options, namespace); }, _fileOrBlobRejected: function(id) { this._netUploadedOrQueued--; this._uploadData.setStatus(id, qq.status.REJECTED); }, _formatSize: function(bytes) { var i = -1; do { bytes = bytes / 1000; i++; } while (bytes > 999); return Math.max(bytes, 0.1).toFixed(1) + this._options.text.sizeSymbols[i]; }, // Creates an internal object that tracks various properties of each extra button, // and then actually creates the extra button. _generateExtraButtonSpecs: function() { var self = this; this._extraButtonSpecs = {}; qq.each(this._options.extraButtons, function(idx, extraButtonOptionEntry) { var multiple = extraButtonOptionEntry.multiple, validation = qq.extend({}, self._options.validation, true), extraButtonSpec = qq.extend({}, extraButtonOptionEntry); if (multiple === undefined) { multiple = self._options.multiple; } if (extraButtonSpec.validation) { qq.extend(validation, extraButtonOptionEntry.validation, true); } qq.extend(extraButtonSpec, { multiple: multiple, validation: validation }, true); self._initExtraButton(extraButtonSpec); }); }, _getButton: function(buttonId) { var extraButtonsSpec = this._extraButtonSpecs[buttonId]; if (extraButtonsSpec) { return extraButtonsSpec.element; } else if (buttonId === this._defaultButtonId) { return this._options.button; } }, /** * Gets the internally used tracking ID for a button. * * @param buttonOrFileInputOrFile `File`, `<input type="file">`, or a button container element * @returns {*} The button's ID, or undefined if no ID is recoverable * @private */ _getButtonId: function(buttonOrFileInputOrFile) { var inputs, fileInput, fileBlobOrInput = buttonOrFileInputOrFile; // We want the reference file/blob here if this is a proxy (a file that will be generated on-demand later) if (fileBlobOrInput instanceof qq.BlobProxy) { fileBlobOrInput = fileBlobOrInput.referenceBlob; } // If the item is a `Blob` it will never be associated with a button or drop zone. if (fileBlobOrInput && !qq.isBlob(fileBlobOrInput)) { if (qq.isFile(fileBlobOrInput)) { return fileBlobOrInput.qqButtonId; } else if (fileBlobOrInput.tagName.toLowerCase() === "input" && fileBlobOrInput.type.toLowerCase() === "file") { return fileBlobOrInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME); } inputs = fileBlobOrInput.getElementsByTagName("input"); qq.each(inputs, function(idx, input) { if (input.getAttribute("type") === "file") { fileInput = input; return false; } }); if (fileInput) { return fileInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME); } } }, _getNotFinished: function() { return this._uploadData.retrieve({ status: [ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING, qq.status.QUEUED, qq.status.SUBMITTING, qq.status.SUBMITTED, qq.status.PAUSED ] }).length; }, // Get the validation options for this button. Could be the default validation option // or a specific one assigned to this particular button. _getValidationBase: function(buttonId) { var extraButtonSpec = this._extraButtonSpecs[buttonId]; return extraButtonSpec ? extraButtonSpec.validation : this._options.validation; }, _getValidationDescriptor: function(fileWrapper) { if (fileWrapper.file instanceof qq.BlobProxy) { return { name: qq.getFilename(fileWrapper.file.referenceBlob), size: fileWrapper.file.referenceBlob.size }; } return { name: this.getUploads({id: fileWrapper.id}).name, size: this.getUploads({id: fileWrapper.id}).size }; }, _getValidationDescriptors: function(fileWrappers) { var self = this, fileDescriptors = []; qq.each(fileWrappers, function(idx, fileWrapper) { fileDescriptors.push(self._getValidationDescriptor(fileWrapper)); }); return fileDescriptors; }, // Allows camera access on either the default or an extra button for iOS devices. _handleCameraAccess: function() { if (this._options.camera.ios && qq.ios()) { var acceptIosCamera = "image/*;capture=camera", button = this._options.camera.button, buttonId = button ? this._getButtonId(button) : this._defaultButtonId, optionRoot = this._options; // If we are not targeting the default button, it is an "extra" button if (buttonId && buttonId !== this._defaultButtonId) { optionRoot = this._extraButtonSpecs[buttonId]; } // Camera access won't work in iOS if the `multiple` attribute is present on the file input optionRoot.multiple = false; // update the options if (optionRoot.validation.acceptFiles === null) { optionRoot.validation.acceptFiles = acceptIosCamera; } else { optionRoot.validation.acceptFiles += "," + acceptIosCamera; } // update the already-created button qq.each(this._buttons, function(idx, button) { if (button.getButtonId() === buttonId) { button.setMultiple(optionRoot.multiple); button.setAcceptFiles(optionRoot.acceptFiles); return false; } }); } }, _handleCheckedCallback: function(details) { var self = this, callbackRetVal = details.callback(); if (qq.isGenericPromise(callbackRetVal)) { this.log(details.name + " - waiting for " + details.name + " promise to be fulfilled for " + details.identifier); return callbackRetVal.then( function(successParam) { self.log(details.name + " promise success for " + details.identifier); details.onSuccess(successParam); }, function() { if (details.onFailure) { self.log(details.name + " promise failure for " + details.identifier); details.onFailure(); } else { self.log(details.name + " promise failure for " + details.identifier); } }); } if (callbackRetVal !== false) { details.onSuccess(callbackRetVal); } else { if (details.onFailure) { this.log(details.name + " - return value was 'false' for " + details.identifier + ". Invoking failure callback."); details.onFailure(); } else { this.log(details.name + " - return value was 'false' for " + details.identifier + ". Will not proceed."); } } return callbackRetVal; }, // Updates internal state when a new file has been received, and adds it along with its ID to a passed array. _handleNewFile: function(file, batchId, newFileWrapperList) { var self = this, uuid = qq.getUniqueId(), size = -1, name = qq.getFilename(file), actualFile = file.blob || file, handler = this._customNewFileHandler ? this._customNewFileHandler : qq.bind(self._handleNewFileGeneric, self); if (!qq.isInput(actualFile) && actualFile.size >= 0) { size = actualFile.size; } handler(actualFile, name, uuid, size, newFileWrapperList, batchId, this._options.request.uuidName, { uploadData: self._uploadData, paramsStore: self._paramsStore, addFileToHandler: function(id, file) { self._handler.add(id, file); self._netUploadedOrQueued++; self._trackButton(id); } }); }, _handleNewFileGeneric: function(file, name, uuid, size, fileList, batchId) { var id = this._uploadData.addFile({uuid: uuid, name: name, size: size, batchId: batchId}); this._handler.add(id, file); this._trackButton(id); this._netUploadedOrQueued++; fileList.push({id: id, file: file}); }, _handlePasteSuccess: function(blob, extSuppliedName) { var extension = blob.type.split("/")[1], name = extSuppliedName; /*jshint eqeqeq: true, eqnull: true*/ if (name == null) { name = this._options.paste.defaultName; } name += "." + extension; this.addFiles({ name: name, blob: blob }); }, // Creates an extra button element _initExtraButton: function(spec) { var button = this._createUploadButton({ element: spec.element, multiple: spec.multiple, accept: spec.validation.acceptFiles, folders: spec.folders, allowedExtensions: spec.validation.allowedExtensions }); this._extraButtonSpecs[button.getButtonId()] = spec; }, _initFormSupportAndParams: function() { this._formSupport = qq.FormSupport && new qq.FormSupport( this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this) ); if (this._formSupport && this._formSupport.attachedToForm) { this._paramsStore = this._createStore( this._options.request.params, this._formSupport.getFormInputsAsObject ); this._options.autoUpload = this._formSupport.newAutoUpload; if (this._formSupport.newEndpoint) { this._options.request.endpoint = this._formSupport.newEndpoint; } } else { this._paramsStore = this._createStore(this._options.request.params); } }, _isDeletePossible: function() { if (!qq.DeleteFileAjaxRequester || !this._options.deleteFile.enabled) { return false; } if (this._options.cors.expected) { if (qq.supportedFeatures.deleteFileCorsXhr) { return true; } if (qq.supportedFeatures.deleteFileCorsXdr && this._options.cors.allowXdr) { return true; } return false; } return true; }, _isAllowedExtension: function(allowed, fileName) { var valid = false; if (!allowed.length) { return true; } qq.each(allowed, function(idx, allowedExt) { /** * If an argument is not a string, ignore it. Added when a possible issue with MooTools hijacking the * `allowedExtensions` array was discovered. See case #735 in the issue tracker for more details. */ if (qq.isString(allowedExt)) { /*jshint eqeqeq: true, eqnull: true*/ var extRegex = new RegExp("\\." + allowedExt + "$", "i"); if (fileName.match(extRegex) != null) { valid = true; return false; } } }); return valid; }, /** * Constructs and returns a message that describes an item/file error. Also calls `onError` callback. * * @param code REQUIRED - a code that corresponds to a stock message describing this type of error * @param maybeNameOrNames names of the items that have failed, if applicable * @param item `File`, `Blob`, or `<input type="file">` * @private */ _itemError: function(code, maybeNameOrNames, item) { var message = this._options.messages[code], allowedExtensions = [], names = [].concat(maybeNameOrNames), name = names[0], buttonId = this._getButtonId(item), validationBase = this._getValidationBase(buttonId), extensionsForMessage, placeholderMatch; function r(name, replacement) { message = message.replace(name, replacement); } qq.each(validationBase.allowedExtensions, function(idx, allowedExtension) { /** * If an argument is not a string, ignore it. Added when a possible issue with MooTools hijacking the * `allowedExtensions` array was discovered. See case #735 in the issue tracker for more details. */ if (qq.isString(allowedExtension)) { allowedExtensions.push(allowedExtension); } }); extensionsForMessage = allowedExtensions.join(", ").toLowerCase(); r("{file}", this._options.formatFileName(name)); r("{extensions}", extensionsForMessage); r("{sizeLimit}", this._formatSize(validationBase.sizeLimit)); r("{minSizeLimit}", this._formatSize(validationBase.minSizeLimit)); placeholderMatch = message.match(/(\{\w+\})/g); if (placeholderMatch !== null) { qq.each(placeholderMatch, function(idx, placeholder) { r(placeholder, names[idx]); }); } this._options.callbacks.onError(null, name, message, undefined); return message; }, /** * Conditionally orders a manual retry of a failed upload. * * @param id File ID of the failed upload * @param callback Optional callback to invoke if a retry is prudent. * In lieu of asking the upload handler to retry. * @returns {boolean} true if a manual retry will occur * @private */ _manualRetry: function(id, callback) { if (this._onBeforeManualRetry(id)) { this._netUploadedOrQueued++; this._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING); if (callback) { callback(id); } else { this._handler.retry(id); } return true; } }, _maybeAllComplete: function(id, status) { var self = this, notFinished = this._getNotFinished(); if (status === qq.status.UPLOAD_SUCCESSFUL) { this._succeededSinceLastAllComplete.push(id); } else if (status === qq.status.UPLOAD_FAILED) { this._failedSinceLastAllComplete.push(id); } if (notFinished === 0 && (this._succeededSinceLastAllComplete.length || this._failedSinceLastAllComplete.length)) { // Attempt to ensure onAllComplete is not invoked before other callbacks, such as onCancel & onComplete setTimeout(function() { self._onAllComplete(self._succeededSinceLastAllComplete, self._failedSinceLastAllComplete); }, 0); } }, _maybeHandleIos8SafariWorkaround: function() { var self = this; if (this._options.workarounds.ios8SafariUploads && qq.ios800() && qq.iosSafari()) { setTimeout(function() { window.alert(self._options.messages.unsupportedBrowserIos8Safari); }, 0); throw new qq.Error(this._options.messages.unsupportedBrowserIos8Safari); } }, _maybeParseAndSendUploadError: function(id, name, response, xhr) { // Assuming no one will actually set the response code to something other than 200 // and still set 'success' to true... if (!response.success) { if (xhr && xhr.status !== 200 && !response.error) { this._options.callbacks.onError(id, name, "XHR returned response code " + xhr.status, xhr); } else { var errorReason = response.error ? response.error : this._options.text.defaultResponseError; this._options.callbacks.onError(id, name, errorReason, xhr); } } }, _maybeProcessNextItemAfterOnValidateCallback: function(validItem, items, index, params, endpoint) { var self = this; if (items.length > index) { if (validItem || !this._options.validation.stopOnFirstInvalidFile) { //use setTimeout to prevent a stack overflow with a large number of files in the batch & non-promissory callbacks setTimeout(function() { var validationDescriptor = self._getValidationDescriptor(items[index]), buttonId = self._getButtonId(items[index].file), button = self._getButton(buttonId); self._handleCheckedCallback({ name: "onValidate", callback: qq.bind(self._options.callbacks.onValidate, self, validationDescriptor, button), onSuccess: qq.bind(self._onValidateCallbackSuccess, self, items, index, params, endpoint), onFailure: qq.bind(self._onValidateCallbackFailure, self, items, index, params, endpoint), identifier: "Item '" + validationDescriptor.name + "', size: " + validationDescriptor.size }); }, 0); } else if (!validItem) { for (; index < items.length; index++) { self._fileOrBlobRejected(items[index].id); } } } }, _onAllComplete: function(successful, failed) { this._totalProgress && this._totalProgress.onAllComplete(successful, failed, this._preventRetries); this._options.callbacks.onAllComplete(qq.extend([], successful), qq.extend([], failed)); this._succeededSinceLastAllComplete = []; this._failedSinceLastAllComplete = []; }, /** * Attempt to automatically retry a failed upload. * * @param id The file ID of the failed upload * @param name The name of the file associated with the failed upload * @param responseJSON Response from the server, parsed into a javascript object * @param xhr Ajax transport used to send the failed request * @param callback Optional callback to be invoked if a retry is prudent. * Invoked in lieu of asking the upload handler to retry. * @returns {boolean} true if an auto-retry will occur * @private */ _onAutoRetry: function(id, name, responseJSON, xhr, callback) { var self = this; self._preventRetries[id] = responseJSON[self._options.retry.preventRetryResponseProperty]; if (self._shouldAutoRetry(id, name, responseJSON)) { self._maybeParseAndSendUploadError.apply(self, arguments); self._options.callbacks.onAutoRetry(id, name, self._autoRetries[id]); self._onBeforeAutoRetry(id, name); self._retryTimeouts[id] = setTimeout(function() { self.log("Retrying " + name + "..."); self._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING); if (callback) { callback(id); } else { self._handler.retry(id); } }, self._options.retry.autoAttemptDelay * 1000); return true; } }, _onBeforeAutoRetry: function(id, name) { this.log("Waiting " + this._options.retry.autoAttemptDelay + " seconds before retrying " + name + "..."); }, //return false if we should not attempt the requested retry _onBeforeManualRetry: function(id) { var itemLimit = this._currentItemLimit, fileName; if (this._preventRetries[id]) { this.log("Retries are forbidden for id " + id, "warn"); return false; } else if (this._handler.isValid(id)) { fileName = this.getName(id); if (this._options.callbacks.onManualRetry(id, fileName) === false) { return false; } if (itemLimit > 0 && this._netUploadedOrQueued + 1 > itemLimit) { this._itemError("retryFailTooManyItems"); return false; } this.log("Retrying upload for '" + fileName + "' (id: " + id + ")..."); return true; } else { this.log("'" + id + "' is not a valid file ID", "error"); return false; } }, _onCancel: function(id, name) { this._netUploadedOrQueued--; clearTimeout(this._retryTimeouts[id]); var storedItemIndex = qq.indexOf(this._storedIds, id); if (!this._options.autoUpload && storedItemIndex >= 0) { this._storedIds.splice(storedItemIndex, 1); } this._uploadData.setStatus(id, qq.status.CANCELED); }, _onComplete: function(id, name, result, xhr) { if (!result.success) { this._netUploadedOrQueued--; this._uploadData.setStatus(id, qq.status.UPLOAD_FAILED); if (result[this._options.retry.preventRetryResponseProperty] === true) { this._preventRetries[id] = true; } } else { if (result.thumbnailUrl) { this._thumbnailUrls[id] = result.thumbnailUrl; } this._netUploaded++; this._uploadData.setStatus(id, qq.status.UPLOAD_SUCCESSFUL); } this._maybeParseAndSendUploadError(id, name, result, xhr); return result.success ? true : false; }, _onDelete: function(id) { this._uploadData.setStatus(id, qq.status.DELETING); }, _onDeleteComplete: function(id, xhrOrXdr, isError) { var name = this.getName(id); if (isError) { this._uploadData.setStatus(id, qq.status.DELETE_FAILED); this.log("Delete request for '" + name + "' has failed.", "error"); // For error reporing, we only have accesss to the response status if this is not // an `XDomainRequest`. if (xhrOrXdr.withCredentials === undefined) { this._options.callbacks.onError(id, name, "Delete request failed", xhrOrXdr); } else { this._options.callbacks.onError(id, name, "Delete request failed with response code " + xhrOrXdr.status, xhrOrXdr); } } else { this._netUploadedOrQueued--; this._netUploaded--; this._handler.expunge(id); this._uploadData.setStatus(id, qq.status.DELETED); this.log("Delete request for '" + name + "' has succeeded."); } }, _onInputChange: function(input) { var fileIndex; if (qq.supportedFeatures.ajaxUploading) { for (fileIndex = 0; fileIndex < input.files.length; fileIndex++) { this._annotateWithButtonId(input.files[fileIndex], input); } this.addFiles(input.files); } // Android 2.3.x will fire `onchange` even if no file has been selected else if (input.value.length > 0) { this.addFiles(input); } qq.each(this._buttons, function(idx, button) { button.reset(); }); }, _onProgress: function(id, name, loaded, total) { this._totalProgress && this._totalProgress.onIndividualProgress(id, loaded, total); }, _onSubmit: function(id, name) { //nothing to do yet in core uploader }, _onSubmitCallbackSuccess: function(id, name) { this._onSubmit.apply(this, arguments); this._uploadData.setStatus(id, qq.status.SUBMITTED); this._onSubmitted.apply(this, arguments); if (this._options.autoUpload) { this._options.callbacks.onSubmitted.apply(this, arguments); this._uploadFile(id); } else { this._storeForLater(id); this._options.callbacks.onSubmitted.apply(this, arguments); } }, _onSubmitDelete: function(id, onSuccessCallback, additionalMandatedParams) { var uuid = this.getUuid(id), adjustedOnSuccessCallback; if (onSuccessCallback) { adjustedOnSuccessCallback = qq.bind(onSuccessCallback, this, id, uuid, additionalMandatedParams); } if (this._isDeletePossible()) { this._handleCheckedCallback({ name: "onSubmitDelete", callback: qq.bind(this._options.callbacks.onSubmitDelete, this, id), onSuccess: adjustedOnSuccessCallback || qq.bind(this._deleteHandler.sendDelete, this, id, uuid, additionalMandatedParams), identifier: id }); return true; } else { this.log("Delete request ignored for ID " + id + ", delete feature is disabled or request not possible " + "due to CORS on a user agent that does not support pre-flighting.", "warn"); return false; } }, _onSubmitted: function(id) { //nothing to do in the base uploader }, _onTotalProgress: function(loaded, total) { this._options.callbacks.onTotalProgress(loaded, total); }, _onUploadPrep: function(id) { // nothing to do in the core uploader for now }, _onUpload: function(id, name) { this._uploadData.setStatus(id, qq.status.UPLOADING); }, _onUploadChunk: function(id, chunkData) { //nothing to do in the base uploader }, _onUploadStatusChange: function(id, oldStatus, newStatus) { // Make sure a "queued" retry attempt is canceled if the upload has been paused if (newStatus === qq.status.PAUSED) { clearTimeout(this._retryTimeouts[id]); } }, _onValidateBatchCallbackFailure: function(fileWrappers) { var self = this; qq.each(fileWrappers, function(idx, fileWrapper) { self._fileOrBlobRejected(fileWrapper.id); }); }, _onValidateBatchCallbackSuccess: function(validationDescriptors, items, params, endpoint, button) { var errorMessage, itemLimit = this._currentItemLimit, proposedNetFilesUploadedOrQueued = this._netUploadedOrQueued; if (itemLimit === 0 || proposedNetFilesUploadedOrQueued <= itemLimit) { if (items.length > 0) { this._handleCheckedCallback({ name: "onValidate", callback: qq.bind(this._options.callbacks.onValidate, this, validationDescriptors[0], button), onSuccess: qq.bind(this._onValidateCallbackSuccess, this, items, 0, params, endpoint), onFailure: qq.bind(this._onValidateCallbackFailure, this, items, 0, params, endpoint), identifier: "Item '" + items[0].file.name + "', size: " + items[0].file.size }); } else { this._itemError("noFilesError"); } } else { this._onValidateBatchCallbackFailure(items); errorMessage = this._options.messages.tooManyItemsError .replace(/\{netItems\}/g, proposedNetFilesUploadedOrQueued) .replace(/\{itemLimit\}/g, itemLimit); this._batchError(errorMessage); } }, _onValidateCallbackFailure: function(items, index, params, endpoint) { var nextIndex = index + 1; this._fileOrBlobRejected(items[index].id, items[index].file.name); this._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint); }, _onValidateCallbackSuccess: function(items, index, params, endpoint) { var self = this, nextIndex = index + 1, validationDescriptor = this._getValidationDescriptor(items[index]); this._validateFileOrBlobData(items[index], validationDescriptor) .then( function() { self._upload(items[index].id, params, endpoint); self._maybeProcessNextItemAfterOnValidateCallback(true, items, nextIndex, params, endpoint); }, function() { self._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint); } ); }, _prepareItemsForUpload: function(items, params, endpoint) { if (items.length === 0) { this._itemError("noFilesError"); return; } var validationDescriptors = this._getValidationDescriptors(items), buttonId = this._getButtonId(items[0].file), button = this._getButton(buttonId); this._handleCheckedCallback({ name: "onValidateBatch", callback: qq.bind(this._options.callbacks.onValidateBatch, this, validationDescriptors, button), onSuccess: qq.bind(this._onValidateBatchCallbackSuccess, this, validationDescriptors, items, params, endpoint, button), onFailure: qq.bind(this._onValidateBatchCallbackFailure, this, items), identifier: "batch validation" }); }, _preventLeaveInProgress: function() { var self = this; this._disposeSupport.attach(window, "beforeunload", function(e) { if (self.getInProgress()) { e = e || window.event; // for ie, ff e.returnValue = self._options.messages.onLeave; // for webkit return self._options.messages.onLeave; } }); }, // Attempts to refresh session data only if the `qq.Session` module exists // and a session endpoint has been specified. The `onSessionRequestComplete` // callback will be invoked once the refresh is complete. _refreshSessionData: function() { var self = this, options = this._options.session; /* jshint eqnull:true */ if (qq.Session && this._options.session.endpoint != null) { if (!this._session) { qq.extend(options, this._options.cors); options.log = qq.bind(this.log, this); options.addFileRecord = qq.bind(this._addCannedFile, this); this._session = new qq.Session(options); } setTimeout(function() { self._session.refresh().then(function(response, xhrOrXdr) { self._sessionRequestComplete(); self._options.callbacks.onSessionRequestComplete(response, true, xhrOrXdr); }, function(response, xhrOrXdr) { self._options.callbacks.onSessionRequestComplete(response, false, xhrOrXdr); }); }, 0); } }, _sessionRequestComplete: function() {}, _setSize: function(id, newSize) { this._uploadData.updateSize(id, newSize); this._totalProgress && this._totalProgress.onNewSize(id); }, _shouldAutoRetry: function(id, name, responseJSON) { var uploadData = this._uploadData.retrieve({id: id}); /*jshint laxbreak: true */ if (!this._preventRetries[id] && this._options.retry.enableAuto && uploadData.status !== qq.status.PAUSED) { if (this._autoRetries[id] === undefined) { this._autoRetries[id] = 0; } if (this._autoRetries[id] < this._options.retry.maxAutoAttempts) { this._autoRetries[id] += 1; return true; } } return false; }, _storeForLater: function(id) { this._storedIds.push(id); }, // Maps a file with the button that was used to select it. _trackButton: function(id) { var buttonId; if (qq.supportedFeatures.ajaxUploading) { buttonId = this._handler.getFile(id).qqButtonId; } else { buttonId = this._getButtonId(this._handler.getInput(id)); } if (buttonId) { this._buttonIdsForFileIds[id] = buttonId; } }, _updateFormSupportAndParams: function(formElementOrId) { this._options.form.element = formElementOrId; this._formSupport = qq.FormSupport && new qq.FormSupport( this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this) ); if (this._formSupport && this._formSupport.attachedToForm) { this._paramsStore.addReadOnly(null, this._formSupport.getFormInputsAsObject); this._options.autoUpload = this._formSupport.newAutoUpload; if (this._formSupport.newEndpoint) { this.setEndpoint(this._formSupport.newEndpoint); } } }, _upload: function(id, params, endpoint) { var name = this.getName(id); if (params) { this.setParams(params, id); } if (endpoint) { this.setEndpoint(endpoint, id); } this._handleCheckedCallback({ name: "onSubmit", callback: qq.bind(this._options.callbacks.onSubmit, this, id, name), onSuccess: qq.bind(this._onSubmitCallbackSuccess, this, id, name), onFailure: qq.bind(this._fileOrBlobRejected, this, id, name), identifier: id }); }, _uploadFile: function(id) { if (!this._handler.upload(id)) { this._uploadData.setStatus(id, qq.status.QUEUED); } }, _uploadStoredFiles: function() { var idToUpload, stillSubmitting, self = this; while (this._storedIds.length) { idToUpload = this._storedIds.shift(); this._uploadFile(idToUpload); } // If we are still waiting for some files to clear validation, attempt to upload these again in a bit stillSubmitting = this.getUploads({status: qq.status.SUBMITTING}).length; if (stillSubmitting) { qq.log("Still waiting for " + stillSubmitting + " files to clear submit queue. Will re-parse stored IDs array shortly."); setTimeout(function() { self._uploadStoredFiles(); }, 1000); } }, /** * Performs some internal validation checks on an item, defined in the `validation` option. * * @param fileWrapper Wrapper containing a `file` along with an `id` * @param validationDescriptor Normalized information about the item (`size`, `name`). * @returns qq.Promise with appropriate callbacks invoked depending on the validity of the file * @private */ _validateFileOrBlobData: function(fileWrapper, validationDescriptor) { var self = this, file = (function() { if (fileWrapper.file instanceof qq.BlobProxy) { return fileWrapper.file.referenceBlob; } return fileWrapper.file; }()), name = validationDescriptor.name, size = validationDescriptor.size, buttonId = this._getButtonId(fileWrapper.file), validationBase = this._getValidationBase(buttonId), validityChecker = new qq.Promise(); validityChecker.then( function() {}, function() { self._fileOrBlobRejected(fileWrapper.id, name); }); if (qq.isFileOrInput(file) && !this._isAllowedExtension(validationBase.allowedExtensions, name)) { this._itemError("typeError", name, file); return validityChecker.failure(); } if (size === 0) { this._itemError("emptyError", name, file); return validityChecker.failure(); } if (size > 0 && validationBase.sizeLimit && size > validationBase.sizeLimit) { this._itemError("sizeError", name, file); return validityChecker.failure(); } if (size > 0 && size < validationBase.minSizeLimit) { this._itemError("minSizeError", name, file); return validityChecker.failure(); } if (qq.ImageValidation && qq.supportedFeatures.imagePreviews && qq.isFile(file)) { new qq.ImageValidation(file, qq.bind(self.log, self)).validate(validationBase.image).then( validityChecker.success, function(errorCode) { self._itemError(errorCode + "ImageError", name, file); validityChecker.failure(); } ); } else { validityChecker.success(); } return validityChecker; }, _wrapCallbacks: function() { var self, safeCallback, prop; self = this; safeCallback = function(name, callback, args) { var errorMsg; try { return callback.apply(self, args); } catch (exception) { errorMsg = exception.message || exception.toString(); self.log("Caught exception in '" + name + "' callback - " + errorMsg, "error"); } }; /* jshint forin: false, loopfunc: true */ for (prop in this._options.callbacks) { (function() { var callbackName, callbackFunc; callbackName = prop; callbackFunc = self._options.callbacks[callbackName]; self._options.callbacks[callbackName] = function() { return safeCallback(callbackName, callbackFunc, arguments); }; }()); } } }; }()); /*globals qq*/ (function() { "use strict"; qq.FineUploaderBasic = function(o) { var self = this; // These options define FineUploaderBasic mode. this._options = { debug: false, button: null, multiple: true, maxConnections: 3, disableCancelForFormUploads: false, autoUpload: true, request: { customHeaders: {}, endpoint: "/server/upload", filenameParam: "qqfilename", forceMultipart: true, inputName: "qqfile", method: "POST", params: {}, paramsInBody: true, totalFileSizeName: "qqtotalfilesize", uuidName: "qquuid" }, validation: { allowedExtensions: [], sizeLimit: 0, minSizeLimit: 0, itemLimit: 0, stopOnFirstInvalidFile: true, acceptFiles: null, image: { maxHeight: 0, maxWidth: 0, minHeight: 0, minWidth: 0 } }, callbacks: { onSubmit: function(id, name) {}, onSubmitted: function(id, name) {}, onComplete: function(id, name, responseJSON, maybeXhr) {}, onAllComplete: function(successful, failed) {}, onCancel: function(id, name) {}, onUpload: function(id, name) {}, onUploadChunk: function(id, name, chunkData) {}, onUploadChunkSuccess: function(id, chunkData, responseJSON, xhr) {}, onResume: function(id, fileName, chunkData) {}, onProgress: function(id, name, loaded, total) {}, onTotalProgress: function(loaded, total) {}, onError: function(id, name, reason, maybeXhrOrXdr) {}, onAutoRetry: function(id, name, attemptNumber) {}, onManualRetry: function(id, name) {}, onValidateBatch: function(fileOrBlobData) {}, onValidate: function(fileOrBlobData) {}, onSubmitDelete: function(id) {}, onDelete: function(id) {}, onDeleteComplete: function(id, xhrOrXdr, isError) {}, onPasteReceived: function(blob) {}, onStatusChange: function(id, oldStatus, newStatus) {}, onSessionRequestComplete: function(response, success, xhrOrXdr) {} }, messages: { typeError: "{file} has an invalid extension. Valid extension(s): {extensions}.", sizeError: "{file} is too large, maximum file size is {sizeLimit}.", minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.", emptyError: "{file} is empty, please select files again without it.", noFilesError: "No files to upload.", tooManyItemsError: "Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}.", maxHeightImageError: "Image is too tall.", maxWidthImageError: "Image is too wide.", minHeightImageError: "Image is not tall enough.", minWidthImageError: "Image is not wide enough.", retryFailTooManyItems: "Retry failed - you have reached your file limit.", onLeave: "The files are being uploaded, if you leave now the upload will be canceled.", unsupportedBrowserIos8Safari: "Unrecoverable error - this browser does not permit file uploading of any kind due to serious bugs in iOS8 Safari. Please use iOS8 Chrome until Apple fixes these issues." }, retry: { enableAuto: false, maxAutoAttempts: 3, autoAttemptDelay: 5, preventRetryResponseProperty: "preventRetry" }, classes: { buttonHover: "qq-upload-button-hover", buttonFocus: "qq-upload-button-focus" }, chunking: { enabled: false, concurrent: { enabled: false }, mandatory: false, paramNames: { partIndex: "qqpartindex", partByteOffset: "qqpartbyteoffset", chunkSize: "qqchunksize", totalFileSize: "qqtotalfilesize", totalParts: "qqtotalparts" }, partSize: 2000000, // only relevant for traditional endpoints, only required when concurrent.enabled === true success: { endpoint: null } }, resume: { enabled: false, recordsExpireIn: 7, //days paramNames: { resuming: "qqresume" } }, formatFileName: function(fileOrBlobName) { return fileOrBlobName; }, text: { defaultResponseError: "Upload failure reason unknown", sizeSymbols: ["kB", "MB", "GB", "TB", "PB", "EB"] }, deleteFile: { enabled: false, method: "DELETE", endpoint: "/server/upload", customHeaders: {}, params: {} }, cors: { expected: false, sendCredentials: false, allowXdr: false }, blobs: { defaultName: "misc_data" }, paste: { targetElement: null, defaultName: "pasted_image" }, camera: { ios: false, // if ios is true: button is null means target the default button, otherwise target the button specified button: null }, // This refers to additional upload buttons to be handled by Fine Uploader. // Each element is an object, containing `element` as the only required // property. The `element` must be a container that will ultimately // contain an invisible `<input type="file">` created by Fine Uploader. // Optional properties of each object include `multiple`, `validation`, // and `folders`. extraButtons: [], // Depends on the session module. Used to query the server for an initial file list // during initialization and optionally after a `reset`. session: { endpoint: null, params: {}, customHeaders: {}, refreshOnReset: true }, // Send parameters associated with an existing form along with the files form: { // Element ID, HTMLElement, or null element: "qq-form", // Overrides the base `autoUpload`, unless `element` is null. autoUpload: false, // true = upload files on form submission (and squelch submit event) interceptSubmit: true }, // scale images client side, upload a new file for each scaled version scaling: { // send the original file as well sendOriginal: true, // fox orientation for scaled images orient: true, // If null, scaled image type will match reference image type. This value will be referred to // for any size record that does not specific a type. defaultType: null, defaultQuality: 80, failureText: "Failed to scale", includeExif: false, // metadata about each requested scaled version sizes: [] }, workarounds: { iosEmptyVideos: true, ios8SafariUploads: true, ios8BrowserCrash: false } }; // Replace any default options with user defined ones qq.extend(this._options, o, true); this._buttons = []; this._extraButtonSpecs = {}; this._buttonIdsForFileIds = []; this._wrapCallbacks(); this._disposeSupport = new qq.DisposeSupport(); this._storedIds = []; this._autoRetries = []; this._retryTimeouts = []; this._preventRetries = []; this._thumbnailUrls = []; this._netUploadedOrQueued = 0; this._netUploaded = 0; this._uploadData = this._createUploadDataTracker(); this._initFormSupportAndParams(); this._customHeadersStore = this._createStore(this._options.request.customHeaders); this._deleteFileCustomHeadersStore = this._createStore(this._options.deleteFile.customHeaders); this._deleteFileParamsStore = this._createStore(this._options.deleteFile.params); this._endpointStore = this._createStore(this._options.request.endpoint); this._deleteFileEndpointStore = this._createStore(this._options.deleteFile.endpoint); this._handler = this._createUploadHandler(); this._deleteHandler = qq.DeleteFileAjaxRequester && this._createDeleteHandler(); if (this._options.button) { this._defaultButtonId = this._createUploadButton({element: this._options.button}).getButtonId(); } this._generateExtraButtonSpecs(); this._handleCameraAccess(); if (this._options.paste.targetElement) { if (qq.PasteSupport) { this._pasteHandler = this._createPasteHandler(); } else { this.log("Paste support module not found", "error"); } } this._preventLeaveInProgress(); this._imageGenerator = qq.ImageGenerator && new qq.ImageGenerator(qq.bind(this.log, this)); this._refreshSessionData(); this._succeededSinceLastAllComplete = []; this._failedSinceLastAllComplete = []; this._scaler = (qq.Scaler && new qq.Scaler(this._options.scaling, qq.bind(this.log, this))) || {}; if (this._scaler.enabled) { this._customNewFileHandler = qq.bind(this._scaler.handleNewFile, this._scaler); } if (qq.TotalProgress && qq.supportedFeatures.progressBar) { this._totalProgress = new qq.TotalProgress( qq.bind(this._onTotalProgress, this), function(id) { var entry = self._uploadData.retrieve({id: id}); return (entry && entry.size) || 0; } ); } this._currentItemLimit = this._options.validation.itemLimit; }; // Define the private & public API methods. qq.FineUploaderBasic.prototype = qq.basePublicApi; qq.extend(qq.FineUploaderBasic.prototype, qq.basePrivateApi); }()); /*globals qq, XDomainRequest*/ /** Generic class for sending non-upload ajax requests and handling the associated responses **/ qq.AjaxRequester = function(o) { "use strict"; var log, shouldParamsBeInQueryString, queue = [], requestData = {}, options = { acceptHeader: null, validMethods: ["PATCH", "POST", "PUT"], method: "POST", contentType: "application/x-www-form-urlencoded", maxConnections: 3, customHeaders: {}, endpointStore: {}, paramsStore: {}, mandatedParams: {}, allowXRequestedWithAndCacheControl: true, successfulResponseCodes: { DELETE: [200, 202, 204], PATCH: [200, 201, 202, 203, 204], POST: [200, 201, 202, 203, 204], PUT: [200, 201, 202, 203, 204], GET: [200] }, cors: { expected: false, sendCredentials: false }, log: function(str, level) {}, onSend: function(id) {}, onComplete: function(id, xhrOrXdr, isError) {}, onProgress: null }; qq.extend(options, o); log = options.log; if (qq.indexOf(options.validMethods, options.method) < 0) { throw new Error("'" + options.method + "' is not a supported method for this type of request!"); } // [Simple methods](http://www.w3.org/TR/cors/#simple-method) // are defined by the W3C in the CORS spec as a list of methods that, in part, // make a CORS request eligible to be exempt from preflighting. function isSimpleMethod() { return qq.indexOf(["GET", "POST", "HEAD"], options.method) >= 0; } // [Simple headers](http://www.w3.org/TR/cors/#simple-header) // are defined by the W3C in the CORS spec as a list of headers that, in part, // make a CORS request eligible to be exempt from preflighting. function containsNonSimpleHeaders(headers) { var containsNonSimple = false; qq.each(containsNonSimple, function(idx, header) { if (qq.indexOf(["Accept", "Accept-Language", "Content-Language", "Content-Type"], header) < 0) { containsNonSimple = true; return false; } }); return containsNonSimple; } function isXdr(xhr) { //The `withCredentials` test is a commonly accepted way to determine if XHR supports CORS. return options.cors.expected && xhr.withCredentials === undefined; } // Returns either a new `XMLHttpRequest` or `XDomainRequest` instance. function getCorsAjaxTransport() { var xhrOrXdr; if (window.XMLHttpRequest || window.ActiveXObject) { xhrOrXdr = qq.createXhrInstance(); if (xhrOrXdr.withCredentials === undefined) { xhrOrXdr = new XDomainRequest(); } } return xhrOrXdr; } // Returns either a new XHR/XDR instance, or an existing one for the associated `File` or `Blob`. function getXhrOrXdr(id, suppliedXhr) { var xhrOrXdr = requestData[id].xhr; if (!xhrOrXdr) { if (suppliedXhr) { xhrOrXdr = suppliedXhr; } else { if (options.cors.expected) { xhrOrXdr = getCorsAjaxTransport(); } else { xhrOrXdr = qq.createXhrInstance(); } } requestData[id].xhr = xhrOrXdr; } return xhrOrXdr; } // Removes element from queue, sends next request function dequeue(id) { var i = qq.indexOf(queue, id), max = options.maxConnections, nextId; delete requestData[id]; queue.splice(i, 1); if (queue.length >= max && i < max) { nextId = queue[max - 1]; sendRequest(nextId); } } function onComplete(id, xdrError) { var xhr = getXhrOrXdr(id), method = options.method, isError = xdrError === true; dequeue(id); if (isError) { log(method + " request for " + id + " has failed", "error"); } else if (!isXdr(xhr) && !isResponseSuccessful(xhr.status)) { isError = true; log(method + " request for " + id + " has failed - response code " + xhr.status, "error"); } options.onComplete(id, xhr, isError); } function getParams(id) { var onDemandParams = requestData[id].additionalParams, mandatedParams = options.mandatedParams, params; if (options.paramsStore.get) { params = options.paramsStore.get(id); } if (onDemandParams) { qq.each(onDemandParams, function(name, val) { params = params || {}; params[name] = val; }); } if (mandatedParams) { qq.each(mandatedParams, function(name, val) { params = params || {}; params[name] = val; }); } return params; } function sendRequest(id, optXhr) { var xhr = getXhrOrXdr(id, optXhr), method = options.method, params = getParams(id), payload = requestData[id].payload, url; options.onSend(id); url = createUrl(id, params); // XDR and XHR status detection APIs differ a bit. if (isXdr(xhr)) { xhr.onload = getXdrLoadHandler(id); xhr.onerror = getXdrErrorHandler(id); } else { xhr.onreadystatechange = getXhrReadyStateChangeHandler(id); } registerForUploadProgress(id); // The last parameter is assumed to be ignored if we are actually using `XDomainRequest`. xhr.open(method, url, true); // Instruct the transport to send cookies along with the CORS request, // unless we are using `XDomainRequest`, which is not capable of this. if (options.cors.expected && options.cors.sendCredentials && !isXdr(xhr)) { xhr.withCredentials = true; } setHeaders(id); log("Sending " + method + " request for " + id); if (payload) { xhr.send(payload); } else if (shouldParamsBeInQueryString || !params) { xhr.send(); } else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/x-www-form-urlencoded") >= 0) { xhr.send(qq.obj2url(params, "")); } else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/json") >= 0) { xhr.send(JSON.stringify(params)); } else { xhr.send(params); } return xhr; } function createUrl(id, params) { var endpoint = options.endpointStore.get(id), addToPath = requestData[id].addToPath; /*jshint -W116,-W041 */ if (addToPath != undefined) { endpoint += "/" + addToPath; } if (shouldParamsBeInQueryString && params) { return qq.obj2url(params, endpoint); } else { return endpoint; } } // Invoked by the UA to indicate a number of possible states that describe // a live `XMLHttpRequest` transport. function getXhrReadyStateChangeHandler(id) { return function() { if (getXhrOrXdr(id).readyState === 4) { onComplete(id); } }; } function registerForUploadProgress(id) { var onProgress = options.onProgress; if (onProgress) { getXhrOrXdr(id).upload.onprogress = function(e) { if (e.lengthComputable) { onProgress(id, e.loaded, e.total); } }; } } // This will be called by IE to indicate **success** for an associated // `XDomainRequest` transported request. function getXdrLoadHandler(id) { return function() { onComplete(id); }; } // This will be called by IE to indicate **failure** for an associated // `XDomainRequest` transported request. function getXdrErrorHandler(id) { return function() { onComplete(id, true); }; } function setHeaders(id) { var xhr = getXhrOrXdr(id), customHeaders = options.customHeaders, onDemandHeaders = requestData[id].additionalHeaders || {}, method = options.method, allHeaders = {}; // If XDomainRequest is being used, we can't set headers, so just ignore this block. if (!isXdr(xhr)) { options.acceptHeader && xhr.setRequestHeader("Accept", options.acceptHeader); // Only attempt to add X-Requested-With & Cache-Control if permitted if (options.allowXRequestedWithAndCacheControl) { // Do not add X-Requested-With & Cache-Control if this is a cross-origin request // OR the cross-origin request contains a non-simple method or header. // This is done to ensure a preflight is not triggered exclusively based on the // addition of these 2 non-simple headers. if (!options.cors.expected || (!isSimpleMethod() || containsNonSimpleHeaders(customHeaders))) { xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("Cache-Control", "no-cache"); } } if (options.contentType && (method === "POST" || method === "PUT")) { xhr.setRequestHeader("Content-Type", options.contentType); } qq.extend(allHeaders, qq.isFunction(customHeaders) ? customHeaders(id) : customHeaders); qq.extend(allHeaders, onDemandHeaders); qq.each(allHeaders, function(name, val) { xhr.setRequestHeader(name, val); }); } } function isResponseSuccessful(responseCode) { return qq.indexOf(options.successfulResponseCodes[options.method], responseCode) >= 0; } function prepareToSend(id, optXhr, addToPath, additionalParams, additionalHeaders, payload) { requestData[id] = { addToPath: addToPath, additionalParams: additionalParams, additionalHeaders: additionalHeaders, payload: payload }; var len = queue.push(id); // if too many active connections, wait... if (len <= options.maxConnections) { return sendRequest(id, optXhr); } } shouldParamsBeInQueryString = options.method === "GET" || options.method === "DELETE"; qq.extend(this, { // Start the process of sending the request. The ID refers to the file associated with the request. initTransport: function(id) { var path, params, headers, payload, cacheBuster; return { // Optionally specify the end of the endpoint path for the request. withPath: function(appendToPath) { path = appendToPath; return this; }, // Optionally specify additional parameters to send along with the request. // These will be added to the query string for GET/DELETE requests or the payload // for POST/PUT requests. The Content-Type of the request will be used to determine // how these parameters should be formatted as well. withParams: function(additionalParams) { params = additionalParams; return this; }, // Optionally specify additional headers to send along with the request. withHeaders: function(additionalHeaders) { headers = additionalHeaders; return this; }, // Optionally specify a payload/body for the request. withPayload: function(thePayload) { payload = thePayload; return this; }, // Appends a cache buster (timestamp) to the request URL as a query parameter (only if GET or DELETE) withCacheBuster: function() { cacheBuster = true; return this; }, // Send the constructed request. send: function(optXhr) { if (cacheBuster && qq.indexOf(["GET", "DELETE"], options.method) >= 0) { params.qqtimestamp = new Date().getTime(); } return prepareToSend(id, optXhr, path, params, headers, payload); } }; }, canceled: function(id) { dequeue(id); } }); }; /* globals qq */ /** * Common upload handler functions. * * @constructor */ qq.UploadHandler = function(spec) { "use strict"; var proxy = spec.proxy, fileState = {}, onCancel = proxy.onCancel, getName = proxy.getName; qq.extend(this, { add: function(id, fileItem) { fileState[id] = fileItem; fileState[id].temp = {}; }, cancel: function(id) { var self = this, cancelFinalizationEffort = new qq.Promise(), onCancelRetVal = onCancel(id, getName(id), cancelFinalizationEffort); onCancelRetVal.then(function() { if (self.isValid(id)) { fileState[id].canceled = true; self.expunge(id); } cancelFinalizationEffort.success(); }); }, expunge: function(id) { delete fileState[id]; }, getThirdPartyFileId: function(id) { return fileState[id].key; }, isValid: function(id) { return fileState[id] !== undefined; }, reset: function() { fileState = {}; }, _getFileState: function(id) { return fileState[id]; }, _setThirdPartyFileId: function(id, thirdPartyFileId) { fileState[id].key = thirdPartyFileId; }, _wasCanceled: function(id) { return !!fileState[id].canceled; } }); }; /*globals qq*/ /** * Base upload handler module. Controls more specific handlers. * * @param o Options. Passed along to the specific handler submodule as well. * @param namespace [optional] Namespace for the specific handler. */ qq.UploadHandlerController = function(o, namespace) { "use strict"; var controller = this, chunkingPossible = false, concurrentChunkingPossible = false, chunking, preventRetryResponse, log, handler, options = { paramsStore: {}, maxConnections: 3, // maximum number of concurrent uploads chunking: { enabled: false, multiple: { enabled: false } }, log: function(str, level) {}, onProgress: function(id, fileName, loaded, total) {}, onComplete: function(id, fileName, response, xhr) {}, onCancel: function(id, fileName) {}, onUploadPrep: function(id) {}, // Called if non-trivial operations will be performed before onUpload onUpload: function(id, fileName) {}, onUploadChunk: function(id, fileName, chunkData) {}, onUploadChunkSuccess: function(id, chunkData, response, xhr) {}, onAutoRetry: function(id, fileName, response, xhr) {}, onResume: function(id, fileName, chunkData) {}, onUuidChanged: function(id, newUuid) {}, getName: function(id) {}, setSize: function(id, newSize) {}, isQueued: function(id) {}, getIdsInProxyGroup: function(id) {}, getIdsInBatch: function(id) {} }, chunked = { // Called when each chunk has uploaded successfully done: function(id, chunkIdx, response, xhr) { var chunkData = handler._getChunkData(id, chunkIdx); handler._getFileState(id).attemptingResume = false; delete handler._getFileState(id).temp.chunkProgress[chunkIdx]; handler._getFileState(id).loaded += chunkData.size; options.onUploadChunkSuccess(id, handler._getChunkDataForCallback(chunkData), response, xhr); }, // Called when all chunks have been successfully uploaded and we want to ask the handler to perform any // logic associated with closing out the file, such as combining the chunks. finalize: function(id) { var size = options.getSize(id), name = options.getName(id); log("All chunks have been uploaded for " + id + " - finalizing...."); handler.finalizeChunks(id).then( function(response, xhr) { log("Finalize successful for " + id); var normaizedResponse = upload.normalizeResponse(response, true); options.onProgress(id, name, size, size); handler._maybeDeletePersistedChunkData(id); upload.cleanup(id, normaizedResponse, xhr); }, function(response, xhr) { var normaizedResponse = upload.normalizeResponse(response, false); log("Problem finalizing chunks for file ID " + id + " - " + normaizedResponse.error, "error"); if (normaizedResponse.reset) { chunked.reset(id); } if (!options.onAutoRetry(id, name, normaizedResponse, xhr)) { upload.cleanup(id, normaizedResponse, xhr); } } ); }, hasMoreParts: function(id) { return !!handler._getFileState(id).chunking.remaining.length; }, nextPart: function(id) { var nextIdx = handler._getFileState(id).chunking.remaining.shift(); if (nextIdx >= handler._getTotalChunks(id)) { nextIdx = null; } return nextIdx; }, reset: function(id) { log("Server or callback has ordered chunking effort to be restarted on next attempt for item ID " + id, "error"); handler._maybeDeletePersistedChunkData(id); handler.reevaluateChunking(id); handler._getFileState(id).loaded = 0; }, sendNext: function(id) { var size = options.getSize(id), name = options.getName(id), chunkIdx = chunked.nextPart(id), chunkData = handler._getChunkData(id, chunkIdx), resuming = handler._getFileState(id).attemptingResume, inProgressChunks = handler._getFileState(id).chunking.inProgress || []; if (handler._getFileState(id).loaded == null) { handler._getFileState(id).loaded = 0; } // Don't follow-through with the resume attempt if the integrator returns false from onResume if (resuming && options.onResume(id, name, chunkData) === false) { chunked.reset(id); chunkIdx = chunked.nextPart(id); chunkData = handler._getChunkData(id, chunkIdx); resuming = false; } // If all chunks have already uploaded successfully, we must be re-attempting the finalize step. if (chunkIdx == null && inProgressChunks.length === 0) { chunked.finalize(id); } // Send the next chunk else { log("Sending chunked upload request for item " + id + ": bytes " + (chunkData.start + 1) + "-" + chunkData.end + " of " + size); options.onUploadChunk(id, name, handler._getChunkDataForCallback(chunkData)); inProgressChunks.push(chunkIdx); handler._getFileState(id).chunking.inProgress = inProgressChunks; if (concurrentChunkingPossible) { connectionManager.open(id, chunkIdx); } if (concurrentChunkingPossible && connectionManager.available() && handler._getFileState(id).chunking.remaining.length) { chunked.sendNext(id); } handler.uploadChunk(id, chunkIdx, resuming).then( // upload chunk success function success(response, xhr) { log("Chunked upload request succeeded for " + id + ", chunk " + chunkIdx); handler.clearCachedChunk(id, chunkIdx); var inProgressChunks = handler._getFileState(id).chunking.inProgress || [], responseToReport = upload.normalizeResponse(response, true), inProgressChunkIdx = qq.indexOf(inProgressChunks, chunkIdx); log(qq.format("Chunk {} for file {} uploaded successfully.", chunkIdx, id)); chunked.done(id, chunkIdx, responseToReport, xhr); if (inProgressChunkIdx >= 0) { inProgressChunks.splice(inProgressChunkIdx, 1); } handler._maybePersistChunkedState(id); if (!chunked.hasMoreParts(id) && inProgressChunks.length === 0) { chunked.finalize(id); } else if (chunked.hasMoreParts(id)) { chunked.sendNext(id); } }, // upload chunk failure function failure(response, xhr) { log("Chunked upload request failed for " + id + ", chunk " + chunkIdx); handler.clearCachedChunk(id, chunkIdx); var responseToReport = upload.normalizeResponse(response, false), inProgressIdx; if (responseToReport.reset) { chunked.reset(id); } else { inProgressIdx = qq.indexOf(handler._getFileState(id).chunking.inProgress, chunkIdx); if (inProgressIdx >= 0) { handler._getFileState(id).chunking.inProgress.splice(inProgressIdx, 1); handler._getFileState(id).chunking.remaining.unshift(chunkIdx); } } // We may have aborted all other in-progress chunks for this file due to a failure. // If so, ignore the failures associated with those aborts. if (!handler._getFileState(id).temp.ignoreFailure) { // If this chunk has failed, we want to ignore all other failures of currently in-progress // chunks since they will be explicitly aborted if (concurrentChunkingPossible) { handler._getFileState(id).temp.ignoreFailure = true; qq.each(handler._getXhrs(id), function(ckid, ckXhr) { ckXhr.abort(); }); // We must indicate that all aborted chunks are no longer in progress handler.moveInProgressToRemaining(id); // Free up any connections used by these chunks, but don't allow any // other files to take up the connections (until we have exhausted all auto-retries) connectionManager.free(id, true); } if (!options.onAutoRetry(id, name, responseToReport, xhr)) { // If one chunk fails, abort all of the others to avoid odd race conditions that occur // if a chunk succeeds immediately after one fails before we have determined if the upload // is a failure or not. upload.cleanup(id, responseToReport, xhr); } } } ) .done(function() { handler.clearXhr(id, chunkIdx); }) ; } } }, connectionManager = { _open: [], _openChunks: {}, _waiting: [], available: function() { var max = options.maxConnections, openChunkEntriesCount = 0, openChunksCount = 0; qq.each(connectionManager._openChunks, function(fileId, openChunkIndexes) { openChunkEntriesCount++; openChunksCount += openChunkIndexes.length; }); return max - (connectionManager._open.length - openChunkEntriesCount + openChunksCount); }, /** * Removes element from queue, starts upload of next */ free: function(id, dontAllowNext) { var allowNext = !dontAllowNext, waitingIndex = qq.indexOf(connectionManager._waiting, id), connectionsIndex = qq.indexOf(connectionManager._open, id), nextId; delete connectionManager._openChunks[id]; if (upload.getProxyOrBlob(id) instanceof qq.BlobProxy) { log("Generated blob upload has ended for " + id + ", disposing generated blob."); delete handler._getFileState(id).file; } // If this file was not consuming a connection, it was just waiting, so remove it from the waiting array if (waitingIndex >= 0) { connectionManager._waiting.splice(waitingIndex, 1); } // If this file was consuming a connection, allow the next file to be uploaded else if (allowNext && connectionsIndex >= 0) { connectionManager._open.splice(connectionsIndex, 1); nextId = connectionManager._waiting.shift(); if (nextId >= 0) { connectionManager._open.push(nextId); upload.start(nextId); } } }, getWaitingOrConnected: function() { var waitingOrConnected = []; // Chunked files may have multiple connections open per chunk (if concurrent chunking is enabled) // We need to grab the file ID of any file that has at least one chunk consuming a connection. qq.each(connectionManager._openChunks, function(fileId, chunks) { if (chunks && chunks.length) { waitingOrConnected.push(parseInt(fileId)); } }); // For non-chunked files, only one connection will be consumed per file. // This is where we aggregate those file IDs. qq.each(connectionManager._open, function(idx, fileId) { if (!connectionManager._openChunks[fileId]) { waitingOrConnected.push(parseInt(fileId)); } }); // There may be files waiting for a connection. waitingOrConnected = waitingOrConnected.concat(connectionManager._waiting); return waitingOrConnected; }, isUsingConnection: function(id) { return qq.indexOf(connectionManager._open, id) >= 0; }, open: function(id, chunkIdx) { if (chunkIdx == null) { connectionManager._waiting.push(id); } if (connectionManager.available()) { if (chunkIdx == null) { connectionManager._waiting.pop(); connectionManager._open.push(id); } else { (function() { var openChunksEntry = connectionManager._openChunks[id] || []; openChunksEntry.push(chunkIdx); connectionManager._openChunks[id] = openChunksEntry; }()); } return true; } return false; }, reset: function() { connectionManager._waiting = []; connectionManager._open = []; } }, simple = { send: function(id, name) { handler._getFileState(id).loaded = 0; log("Sending simple upload request for " + id); handler.uploadFile(id).then( function(response, optXhr) { log("Simple upload request succeeded for " + id); var responseToReport = upload.normalizeResponse(response, true), size = options.getSize(id); options.onProgress(id, name, size, size); upload.maybeNewUuid(id, responseToReport); upload.cleanup(id, responseToReport, optXhr); }, function(response, optXhr) { log("Simple upload request failed for " + id); var responseToReport = upload.normalizeResponse(response, false); if (!options.onAutoRetry(id, name, responseToReport, optXhr)) { upload.cleanup(id, responseToReport, optXhr); } } ); } }, upload = { cancel: function(id) { log("Cancelling " + id); options.paramsStore.remove(id); connectionManager.free(id); }, cleanup: function(id, response, optXhr) { var name = options.getName(id); options.onComplete(id, name, response, optXhr); if (handler._getFileState(id)) { handler._clearXhrs && handler._clearXhrs(id); } connectionManager.free(id); }, // Returns a qq.BlobProxy, or an actual File/Blob if no proxy is involved, or undefined // if none of these are available for the ID getProxyOrBlob: function(id) { return (handler.getProxy && handler.getProxy(id)) || (handler.getFile && handler.getFile(id)); }, initHandler: function() { var handlerType = namespace ? qq[namespace] : qq.traditional, handlerModuleSubtype = qq.supportedFeatures.ajaxUploading ? "Xhr" : "Form"; handler = new handlerType[handlerModuleSubtype + "UploadHandler"]( options, { getDataByUuid: options.getDataByUuid, getName: options.getName, getSize: options.getSize, getUuid: options.getUuid, log: log, onCancel: options.onCancel, onProgress: options.onProgress, onUuidChanged: options.onUuidChanged } ); if (handler._removeExpiredChunkingRecords) { handler._removeExpiredChunkingRecords(); } }, isDeferredEligibleForUpload: function(id) { return options.isQueued(id); }, // For Blobs that are part of a group of generated images, along with a reference image, // this will ensure the blobs in the group are uploaded in the order they were triggered, // even if some async processing must be completed on one or more Blobs first. maybeDefer: function(id, blob) { // If we don't have a file/blob yet & no file/blob exists for this item, request it, // and then submit the upload to the specific handler once the blob is available. // ASSUMPTION: This condition will only ever be true if XHR uploading is supported. if (blob && !handler.getFile(id) && blob instanceof qq.BlobProxy) { // Blob creation may take some time, so the caller may want to update the // UI to indicate that an operation is in progress, even before the actual // upload begins and an onUpload callback is invoked. options.onUploadPrep(id); log("Attempting to generate a blob on-demand for " + id); blob.create().then(function(generatedBlob) { log("Generated an on-demand blob for " + id); // Update record associated with this file by providing the generated Blob handler.updateBlob(id, generatedBlob); // Propagate the size for this generated Blob options.setSize(id, generatedBlob.size); // Order handler to recalculate chunking possibility, if applicable handler.reevaluateChunking(id); upload.maybeSendDeferredFiles(id); }, // Blob could not be generated. Fail the upload & attempt to prevent retries. Also bubble error message. function(errorMessage) { var errorResponse = {}; if (errorMessage) { errorResponse.error = errorMessage; } log(qq.format("Failed to generate blob for ID {}. Error message: {}.", id, errorMessage), "error"); options.onComplete(id, options.getName(id), qq.extend(errorResponse, preventRetryResponse), null); upload.maybeSendDeferredFiles(id); connectionManager.free(id); }); } else { return upload.maybeSendDeferredFiles(id); } return false; }, // Upload any grouped blobs, in the proper order, that are ready to be uploaded maybeSendDeferredFiles: function(id) { var idsInGroup = options.getIdsInProxyGroup(id), uploadedThisId = false; if (idsInGroup && idsInGroup.length) { log("Maybe ready to upload proxy group file " + id); qq.each(idsInGroup, function(idx, idInGroup) { if (upload.isDeferredEligibleForUpload(idInGroup) && !!handler.getFile(idInGroup)) { uploadedThisId = idInGroup === id; upload.now(idInGroup); } else if (upload.isDeferredEligibleForUpload(idInGroup)) { return false; } }); } else { uploadedThisId = true; upload.now(id); } return uploadedThisId; }, maybeNewUuid: function(id, response) { if (response.newUuid !== undefined) { options.onUuidChanged(id, response.newUuid); } }, // The response coming from handler implementations may be in various formats. // Instead of hoping a promise nested 5 levels deep will always return an object // as its first param, let's just normalize the response here. normalizeResponse: function(originalResponse, successful) { var response = originalResponse; // The passed "response" param may not be a response at all. // It could be a string, detailing the error, for example. if (!qq.isObject(originalResponse)) { response = {}; if (qq.isString(originalResponse) && !successful) { response.error = originalResponse; } } response.success = successful; return response; }, now: function(id) { var name = options.getName(id); if (!controller.isValid(id)) { throw new qq.Error(id + " is not a valid file ID to upload!"); } options.onUpload(id, name); if (chunkingPossible && handler._shouldChunkThisFile(id)) { chunked.sendNext(id); } else { simple.send(id, name); } }, start: function(id) { var blobToUpload = upload.getProxyOrBlob(id); if (blobToUpload) { return upload.maybeDefer(id, blobToUpload); } else { upload.now(id); return true; } } }; qq.extend(this, { /** * Adds file or file input to the queue **/ add: function(id, file) { handler.add.apply(this, arguments); }, /** * Sends the file identified by id */ upload: function(id) { if (connectionManager.open(id)) { return upload.start(id); } return false; }, retry: function(id) { // On retry, if concurrent chunking has been enabled, we may have aborted all other in-progress chunks // for a file when encountering a failed chunk upload. We then signaled the controller to ignore // all failures associated with these aborts. We are now retrying, so we don't want to ignore // any more failures at this point. if (concurrentChunkingPossible) { handler._getFileState(id).temp.ignoreFailure = false; } // If we are attempting to retry a file that is already consuming a connection, this is likely an auto-retry. // Just go ahead and ask the handler to upload again. if (connectionManager.isUsingConnection(id)) { return upload.start(id); } // If we are attempting to retry a file that is not currently consuming a connection, // this is likely a manual retry attempt. We will need to ensure a connection is available // before the retry commences. else { return controller.upload(id); } }, /** * Cancels file upload by id */ cancel: function(id) { var cancelRetVal = handler.cancel(id); if (qq.isGenericPromise(cancelRetVal)) { cancelRetVal.then(function() { upload.cancel(id); }); } else if (cancelRetVal !== false) { upload.cancel(id); } }, /** * Cancels all queued or in-progress uploads */ cancelAll: function() { var waitingOrConnected = connectionManager.getWaitingOrConnected(), i; // ensure files are cancelled in reverse order which they were added // to avoid a flash of time where a queued file begins to upload before it is canceled if (waitingOrConnected.length) { for (i = waitingOrConnected.length - 1; i >= 0; i--) { controller.cancel(waitingOrConnected[i]); } } connectionManager.reset(); }, // Returns a File, Blob, or the Blob/File for the reference/parent file if the targeted blob is a proxy. // Undefined if no file record is available. getFile: function(id) { if (handler.getProxy && handler.getProxy(id)) { return handler.getProxy(id).referenceBlob; } return handler.getFile && handler.getFile(id); }, // Returns true if the Blob associated with the ID is related to a proxy s isProxied: function(id) { return !!(handler.getProxy && handler.getProxy(id)); }, getInput: function(id) { if (handler.getInput) { return handler.getInput(id); } }, reset: function() { log("Resetting upload handler"); controller.cancelAll(); connectionManager.reset(); handler.reset(); }, expunge: function(id) { if (controller.isValid(id)) { return handler.expunge(id); } }, /** * Determine if the file exists. */ isValid: function(id) { return handler.isValid(id); }, getResumableFilesData: function() { if (handler.getResumableFilesData) { return handler.getResumableFilesData(); } return []; }, /** * This may or may not be implemented, depending on the handler. For handlers where a third-party ID is * available (such as the "key" for Amazon S3), this will return that value. Otherwise, the return value * will be undefined. * * @param id Internal file ID * @returns {*} Some identifier used by a 3rd-party service involved in the upload process */ getThirdPartyFileId: function(id) { if (controller.isValid(id)) { return handler.getThirdPartyFileId(id); } }, /** * Attempts to pause the associated upload if the specific handler supports this and the file is "valid". * @param id ID of the upload/file to pause * @returns {boolean} true if the upload was paused */ pause: function(id) { if (controller.isResumable(id) && handler.pause && controller.isValid(id) && handler.pause(id)) { connectionManager.free(id); handler.moveInProgressToRemaining(id); return true; } return false; }, // True if the file is eligible for pause/resume. isResumable: function(id) { return !!handler.isResumable && handler.isResumable(id); } }); qq.extend(options, o); log = options.log; chunkingPossible = options.chunking.enabled && qq.supportedFeatures.chunking; concurrentChunkingPossible = chunkingPossible && options.chunking.concurrent.enabled; preventRetryResponse = (function() { var response = {}; response[options.preventRetryParam] = true; return response; }()); upload.initHandler(); }; /* globals qq */ /** * Common APIs exposed to creators of upload via form/iframe handlers. This is reused and possibly overridden * in some cases by specific form upload handlers. * * @constructor */ qq.FormUploadHandler = function(spec) { "use strict"; var options = spec.options, handler = this, proxy = spec.proxy, formHandlerInstanceId = qq.getUniqueId(), onloadCallbacks = {}, detachLoadEvents = {}, postMessageCallbackTimers = {}, isCors = options.isCors, inputName = options.inputName, getUuid = proxy.getUuid, log = proxy.log, corsMessageReceiver = new qq.WindowReceiveMessage({log: log}); /** * Remove any trace of the file from the handler. * * @param id ID of the associated file */ function expungeFile(id) { delete detachLoadEvents[id]; // If we are dealing with CORS, we might still be waiting for a response from a loaded iframe. // In that case, terminate the timer waiting for a message from the loaded iframe // and stop listening for any more messages coming from this iframe. if (isCors) { clearTimeout(postMessageCallbackTimers[id]); delete postMessageCallbackTimers[id]; corsMessageReceiver.stopReceivingMessages(id); } var iframe = document.getElementById(handler._getIframeName(id)); if (iframe) { // To cancel request set src to something else. We use src="javascript:false;" // because it doesn't trigger ie6 prompt on https /* jshint scripturl:true */ iframe.setAttribute("src", "javascript:false;"); qq(iframe).remove(); } } /** * @param iframeName `document`-unique Name of the associated iframe * @returns {*} ID of the associated file */ function getFileIdForIframeName(iframeName) { return iframeName.split("_")[0]; } /** * Generates an iframe to be used as a target for upload-related form submits. This also adds the iframe * to the current `document`. Note that the iframe is hidden from view. * * @param name Name of the iframe. * @returns {HTMLIFrameElement} The created iframe */ function initIframeForUpload(name) { var iframe = qq.toElement("<iframe src='javascript:false;' name='" + name + "' />"); iframe.setAttribute("id", name); iframe.style.display = "none"; document.body.appendChild(iframe); return iframe; } /** * If we are in CORS mode, we must listen for messages (containing the server response) from the associated * iframe, since we cannot directly parse the content of the iframe due to cross-origin restrictions. * * @param iframe Listen for messages on this iframe. * @param callback Invoke this callback with the message from the iframe. */ function registerPostMessageCallback(iframe, callback) { var iframeName = iframe.id, fileId = getFileIdForIframeName(iframeName), uuid = getUuid(fileId); onloadCallbacks[uuid] = callback; // When the iframe has loaded (after the server responds to an upload request) // declare the attempt a failure if we don't receive a valid message shortly after the response comes in. detachLoadEvents[fileId] = qq(iframe).attach("load", function() { if (handler.getInput(fileId)) { log("Received iframe load event for CORS upload request (iframe name " + iframeName + ")"); postMessageCallbackTimers[iframeName] = setTimeout(function() { var errorMessage = "No valid message received from loaded iframe for iframe name " + iframeName; log(errorMessage, "error"); callback({ error: errorMessage }); }, 1000); } }); // Listen for messages coming from this iframe. When a message has been received, cancel the timer // that declares the upload a failure if a message is not received within a reasonable amount of time. corsMessageReceiver.receiveMessage(iframeName, function(message) { log("Received the following window message: '" + message + "'"); var fileId = getFileIdForIframeName(iframeName), response = handler._parseJsonResponse(message), uuid = response.uuid, onloadCallback; if (uuid && onloadCallbacks[uuid]) { log("Handling response for iframe name " + iframeName); clearTimeout(postMessageCallbackTimers[iframeName]); delete postMessageCallbackTimers[iframeName]; handler._detachLoadEvent(iframeName); onloadCallback = onloadCallbacks[uuid]; delete onloadCallbacks[uuid]; corsMessageReceiver.stopReceivingMessages(iframeName); onloadCallback(response); } else if (!uuid) { log("'" + message + "' does not contain a UUID - ignoring."); } }); } qq.extend(this, new qq.UploadHandler(spec)); qq.override(this, function(super_) { return { /** * Adds File or Blob to the queue **/ add: function(id, fileInput) { super_.add(id, {input: fileInput}); fileInput.setAttribute("name", inputName); // remove file input from DOM if (fileInput.parentNode) { qq(fileInput).remove(); } }, expunge: function(id) { expungeFile(id); super_.expunge(id); }, isValid: function(id) { return super_.isValid(id) && handler._getFileState(id).input !== undefined; } }; }); qq.extend(this, { getInput: function(id) { return handler._getFileState(id).input; }, /** * This function either delegates to a more specific message handler if CORS is involved, * or simply registers a callback when the iframe has been loaded that invokes the passed callback * after determining if the content of the iframe is accessible. * * @param iframe Associated iframe * @param callback Callback to invoke after we have determined if the iframe content is accessible. */ _attachLoadEvent: function(iframe, callback) { /*jslint eqeq: true*/ var responseDescriptor; if (isCors) { registerPostMessageCallback(iframe, callback); } else { detachLoadEvents[iframe.id] = qq(iframe).attach("load", function() { log("Received response for " + iframe.id); // when we remove iframe from dom // the request stops, but in IE load // event fires if (!iframe.parentNode) { return; } try { // fixing Opera 10.53 if (iframe.contentDocument && iframe.contentDocument.body && iframe.contentDocument.body.innerHTML == "false") { // In Opera event is fired second time // when body.innerHTML changed from false // to server response approx. after 1 sec // when we upload file with iframe return; } } catch (error) { //IE may throw an "access is denied" error when attempting to access contentDocument on the iframe in some cases log("Error when attempting to access iframe during handling of upload response (" + error.message + ")", "error"); responseDescriptor = {success: false}; } callback(responseDescriptor); }); } }, /** * Creates an iframe with a specific document-unique name. * * @param id ID of the associated file * @returns {HTMLIFrameElement} */ _createIframe: function(id) { var iframeName = handler._getIframeName(id); return initIframeForUpload(iframeName); }, /** * Called when we are no longer interested in being notified when an iframe has loaded. * * @param id Associated file ID */ _detachLoadEvent: function(id) { if (detachLoadEvents[id] !== undefined) { detachLoadEvents[id](); delete detachLoadEvents[id]; } }, /** * @param fileId ID of the associated file * @returns {string} The `document`-unique name of the iframe */ _getIframeName: function(fileId) { return fileId + "_" + formHandlerInstanceId; }, /** * Generates a form element and appends it to the `document`. When the form is submitted, a specific iframe is targeted. * The name of the iframe is passed in as a property of the spec parameter, and must be unique in the `document`. Note * that the form is hidden from view. * * @param spec An object containing various properties to be used when constructing the form. Required properties are * currently: `method`, `endpoint`, `params`, `paramsInBody`, and `targetName`. * @returns {HTMLFormElement} The created form */ _initFormForUpload: function(spec) { var method = spec.method, endpoint = spec.endpoint, params = spec.params, paramsInBody = spec.paramsInBody, targetName = spec.targetName, form = qq.toElement("<form method='" + method + "' enctype='multipart/form-data'></form>"), url = endpoint; if (paramsInBody) { qq.obj2Inputs(params, form); } else { url = qq.obj2url(params, endpoint); } form.setAttribute("action", url); form.setAttribute("target", targetName); form.style.display = "none"; document.body.appendChild(form); return form; }, /** * @param innerHtmlOrMessage JSON message * @returns {*} The parsed response, or an empty object if the response could not be parsed */ _parseJsonResponse: function(innerHtmlOrMessage) { var response = {}; try { response = qq.parseJson(innerHtmlOrMessage); } catch (error) { log("Error when attempting to parse iframe upload response (" + error.message + ")", "error"); } return response; } }); }; /* globals qq */ /** * Common API exposed to creators of XHR handlers. This is reused and possibly overriding in some cases by specific * XHR upload handlers. * * @constructor */ qq.XhrUploadHandler = function(spec) { "use strict"; var handler = this, namespace = spec.options.namespace, proxy = spec.proxy, chunking = spec.options.chunking, resume = spec.options.resume, chunkFiles = chunking && spec.options.chunking.enabled && qq.supportedFeatures.chunking, resumeEnabled = resume && spec.options.resume.enabled && chunkFiles && qq.supportedFeatures.resume, getName = proxy.getName, getSize = proxy.getSize, getUuid = proxy.getUuid, getEndpoint = proxy.getEndpoint, getDataByUuid = proxy.getDataByUuid, onUuidChanged = proxy.onUuidChanged, onProgress = proxy.onProgress, log = proxy.log; function abort(id) { qq.each(handler._getXhrs(id), function(xhrId, xhr) { var ajaxRequester = handler._getAjaxRequester(id, xhrId); xhr.onreadystatechange = null; xhr.upload.onprogress = null; xhr.abort(); ajaxRequester && ajaxRequester.canceled && ajaxRequester.canceled(id); }); } qq.extend(this, new qq.UploadHandler(spec)); qq.override(this, function(super_) { return { /** * Adds File or Blob to the queue **/ add: function(id, blobOrProxy) { if (qq.isFile(blobOrProxy) || qq.isBlob(blobOrProxy)) { super_.add(id, {file: blobOrProxy}); } else if (blobOrProxy instanceof qq.BlobProxy) { super_.add(id, {proxy: blobOrProxy}); } else { throw new Error("Passed obj is not a File, Blob, or proxy"); } handler._initTempState(id); resumeEnabled && handler._maybePrepareForResume(id); }, expunge: function(id) { abort(id); handler._maybeDeletePersistedChunkData(id); handler._clearXhrs(id); super_.expunge(id); } }; }); qq.extend(this, { // Clear the cached chunk `Blob` after we are done with it, just in case the `Blob` bytes are stored in memory. clearCachedChunk: function(id, chunkIdx) { delete handler._getFileState(id).temp.cachedChunks[chunkIdx]; }, clearXhr: function(id, chunkIdx) { var tempState = handler._getFileState(id).temp; if (tempState.xhrs) { delete tempState.xhrs[chunkIdx]; } if (tempState.ajaxRequesters) { delete tempState.ajaxRequesters[chunkIdx]; } }, // Called when all chunks have been successfully uploaded. Expected promissory return type. // This defines the default behavior if nothing further is required when all chunks have been uploaded. finalizeChunks: function(id, responseParser) { var lastChunkIdx = handler._getTotalChunks(id) - 1, xhr = handler._getXhr(id, lastChunkIdx); if (responseParser) { return new qq.Promise().success(responseParser(xhr), xhr); } return new qq.Promise().success({}, xhr); }, getFile: function(id) { return handler.isValid(id) && handler._getFileState(id).file; }, getProxy: function(id) { return handler.isValid(id) && handler._getFileState(id).proxy; }, /** * @returns {Array} Array of objects containing properties useful to integrators * when it is important to determine which files are potentially resumable. */ getResumableFilesData: function() { var resumableFilesData = []; handler._iterateResumeRecords(function(key, uploadData) { handler.moveInProgressToRemaining(null, uploadData.chunking.inProgress, uploadData.chunking.remaining); var data = { name: uploadData.name, remaining: uploadData.chunking.remaining, size: uploadData.size, uuid: uploadData.uuid }; if (uploadData.key) { data.key = uploadData.key; } resumableFilesData.push(data); }); return resumableFilesData; }, isResumable: function(id) { return !!chunking && handler.isValid(id) && !handler._getFileState(id).notResumable; }, moveInProgressToRemaining: function(id, optInProgress, optRemaining) { var inProgress = optInProgress || handler._getFileState(id).chunking.inProgress, remaining = optRemaining || handler._getFileState(id).chunking.remaining; if (inProgress) { inProgress.reverse(); qq.each(inProgress, function(idx, chunkIdx) { remaining.unshift(chunkIdx); }); inProgress.length = 0; } }, pause: function(id) { if (handler.isValid(id)) { log(qq.format("Aborting XHR upload for {} '{}' due to pause instruction.", id, getName(id))); handler._getFileState(id).paused = true; abort(id); return true; } }, reevaluateChunking: function(id) { if (chunking && handler.isValid(id)) { var state = handler._getFileState(id), totalChunks, i; delete state.chunking; state.chunking = {}; totalChunks = handler._getTotalChunks(id); if (totalChunks > 1 || chunking.mandatory) { state.chunking.enabled = true; state.chunking.parts = totalChunks; state.chunking.remaining = []; for (i = 0; i < totalChunks; i++) { state.chunking.remaining.push(i); } handler._initTempState(id); } else { state.chunking.enabled = false; } } }, updateBlob: function(id, newBlob) { if (handler.isValid(id)) { handler._getFileState(id).file = newBlob; } }, _clearXhrs: function(id) { var tempState = handler._getFileState(id).temp; qq.each(tempState.ajaxRequesters, function(chunkId) { delete tempState.ajaxRequesters[chunkId]; }); qq.each(tempState.xhrs, function(chunkId) { delete tempState.xhrs[chunkId]; }); }, /** * Creates an XHR instance for this file and stores it in the fileState. * * @param id File ID * @param optChunkIdx The chunk index associated with this XHR, if applicable * @returns {XMLHttpRequest} */ _createXhr: function(id, optChunkIdx) { return handler._registerXhr(id, optChunkIdx, qq.createXhrInstance()); }, _getAjaxRequester: function(id, optChunkIdx) { var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx; return handler._getFileState(id).temp.ajaxRequesters[chunkIdx]; }, _getChunkData: function(id, chunkIndex) { var chunkSize = chunking.partSize, fileSize = getSize(id), fileOrBlob = handler.getFile(id), startBytes = chunkSize * chunkIndex, endBytes = startBytes + chunkSize >= fileSize ? fileSize : startBytes + chunkSize, totalChunks = handler._getTotalChunks(id), cachedChunks = this._getFileState(id).temp.cachedChunks, // To work around a Webkit GC bug, we must keep each chunk `Blob` in scope until we are done with it. // See https://github.com/Widen/fine-uploader/issues/937#issuecomment-41418760 blob = cachedChunks[chunkIndex] || qq.sliceBlob(fileOrBlob, startBytes, endBytes); cachedChunks[chunkIndex] = blob; return { part: chunkIndex, start: startBytes, end: endBytes, count: totalChunks, blob: blob, size: endBytes - startBytes }; }, _getChunkDataForCallback: function(chunkData) { return { partIndex: chunkData.part, startByte: chunkData.start + 1, endByte: chunkData.end, totalParts: chunkData.count }; }, /** * @param id File ID * @returns {string} Identifier for this item that may appear in the browser's local storage */ _getLocalStorageId: function(id) { var formatVersion = "5.0", name = getName(id), size = getSize(id), chunkSize = chunking.partSize, endpoint = getEndpoint(id); return qq.format("qq{}resume{}-{}-{}-{}-{}", namespace, formatVersion, name, size, chunkSize, endpoint); }, _getMimeType: function(id) { return handler.getFile(id).type; }, _getPersistableData: function(id) { return handler._getFileState(id).chunking; }, /** * @param id ID of the associated file * @returns {number} Number of parts this file can be divided into, or undefined if chunking is not supported in this UA */ _getTotalChunks: function(id) { if (chunking) { var fileSize = getSize(id), chunkSize = chunking.partSize; return Math.ceil(fileSize / chunkSize); } }, _getXhr: function(id, optChunkIdx) { var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx; return handler._getFileState(id).temp.xhrs[chunkIdx]; }, _getXhrs: function(id) { return handler._getFileState(id).temp.xhrs; }, // Iterates through all XHR handler-created resume records (in local storage), // invoking the passed callback and passing in the key and value of each local storage record. _iterateResumeRecords: function(callback) { if (resumeEnabled) { qq.each(localStorage, function(key, item) { if (key.indexOf(qq.format("qq{}resume", namespace)) === 0) { var uploadData = JSON.parse(item); callback(key, uploadData); } }); } }, _initTempState: function(id) { handler._getFileState(id).temp = { ajaxRequesters: {}, chunkProgress: {}, xhrs: {}, cachedChunks: {} }; }, _markNotResumable: function(id) { handler._getFileState(id).notResumable = true; }, // Removes a chunked upload record from local storage, if possible. // Returns true if the item was removed, false otherwise. _maybeDeletePersistedChunkData: function(id) { var localStorageId; if (resumeEnabled && handler.isResumable(id)) { localStorageId = handler._getLocalStorageId(id); if (localStorageId && localStorage.getItem(localStorageId)) { localStorage.removeItem(localStorageId); return true; } } return false; }, // If this is a resumable upload, grab the relevant data from storage and items in memory that track this upload // so we can pick up from where we left off. _maybePrepareForResume: function(id) { var state = handler._getFileState(id), localStorageId, persistedData; // Resume is enabled and possible and this is the first time we've tried to upload this file in this session, // so prepare for a resume attempt. if (resumeEnabled && state.key === undefined) { localStorageId = handler._getLocalStorageId(id); persistedData = localStorage.getItem(localStorageId); // If we found this item in local storage, maybe we should resume it. if (persistedData) { persistedData = JSON.parse(persistedData); // If we found a resume record but we have already handled this file in this session, // don't try to resume it & ensure we don't persist future check data if (getDataByUuid(persistedData.uuid)) { handler._markNotResumable(id); } else { log(qq.format("Identified file with ID {} and name of {} as resumable.", id, getName(id))); onUuidChanged(id, persistedData.uuid); state.key = persistedData.key; state.chunking = persistedData.chunking; state.loaded = persistedData.loaded; state.attemptingResume = true; handler.moveInProgressToRemaining(id); } } } }, // Persist any data needed to resume this upload in a new session. _maybePersistChunkedState: function(id) { var state = handler._getFileState(id), localStorageId, persistedData; // If local storage isn't supported by the browser, or if resume isn't enabled or possible, give up if (resumeEnabled && handler.isResumable(id)) { localStorageId = handler._getLocalStorageId(id); persistedData = { name: getName(id), size: getSize(id), uuid: getUuid(id), key: state.key, chunking: state.chunking, loaded: state.loaded, lastUpdated: Date.now() }; try { localStorage.setItem(localStorageId, JSON.stringify(persistedData)); } catch (error) { log(qq.format("Unable to save resume data for '{}' due to error: '{}'.", id, error.toString()), "warn"); } } }, _registerProgressHandler: function(id, chunkIdx, chunkSize) { var xhr = handler._getXhr(id, chunkIdx), name = getName(id), progressCalculator = { simple: function(loaded, total) { var fileSize = getSize(id); if (loaded === total) { onProgress(id, name, fileSize, fileSize); } else { onProgress(id, name, (loaded >= fileSize ? fileSize - 1 : loaded), fileSize); } }, chunked: function(loaded, total) { var chunkProgress = handler._getFileState(id).temp.chunkProgress, totalSuccessfullyLoadedForFile = handler._getFileState(id).loaded, loadedForRequest = loaded, totalForRequest = total, totalFileSize = getSize(id), estActualChunkLoaded = loadedForRequest - (totalForRequest - chunkSize), totalLoadedForFile = totalSuccessfullyLoadedForFile; chunkProgress[chunkIdx] = estActualChunkLoaded; qq.each(chunkProgress, function(chunkIdx, chunkLoaded) { totalLoadedForFile += chunkLoaded; }); onProgress(id, name, totalLoadedForFile, totalFileSize); } }; xhr.upload.onprogress = function(e) { if (e.lengthComputable) { /* jshint eqnull: true */ var type = chunkSize == null ? "simple" : "chunked"; progressCalculator[type](e.loaded, e.total); } }; }, /** * Registers an XHR transport instance created elsewhere. * * @param id ID of the associated file * @param optChunkIdx The chunk index associated with this XHR, if applicable * @param xhr XMLHttpRequest object instance * @param optAjaxRequester `qq.AjaxRequester` associated with this request, if applicable. * @returns {XMLHttpRequest} */ _registerXhr: function(id, optChunkIdx, xhr, optAjaxRequester) { var xhrsId = optChunkIdx == null ? -1 : optChunkIdx, tempState = handler._getFileState(id).temp; tempState.xhrs = tempState.xhrs || {}; tempState.ajaxRequesters = tempState.ajaxRequesters || {}; tempState.xhrs[xhrsId] = xhr; if (optAjaxRequester) { tempState.ajaxRequesters[xhrsId] = optAjaxRequester; } return xhr; }, // Deletes any local storage records that are "expired". _removeExpiredChunkingRecords: function() { var expirationDays = resume.recordsExpireIn; handler._iterateResumeRecords(function(key, uploadData) { var expirationDate = new Date(uploadData.lastUpdated); // transform updated date into expiration date expirationDate.setDate(expirationDate.getDate() + expirationDays); if (expirationDate.getTime() <= Date.now()) { log("Removing expired resume record with key " + key); localStorage.removeItem(key); } }); }, /** * Determine if the associated file should be chunked. * * @param id ID of the associated file * @returns {*} true if chunking is enabled, possible, and the file can be split into more than 1 part */ _shouldChunkThisFile: function(id) { var state = handler._getFileState(id); if (!state.chunking) { handler.reevaluateChunking(id); } return state.chunking.enabled; } }); }; /*globals qq */ /*jshint -W117 */ qq.WindowReceiveMessage = function(o) { "use strict"; var options = { log: function(message, level) {} }, callbackWrapperDetachers = {}; qq.extend(options, o); qq.extend(this, { receiveMessage: function(id, callback) { var onMessageCallbackWrapper = function(event) { callback(event.data); }; if (window.postMessage) { callbackWrapperDetachers[id] = qq(window).attach("message", onMessageCallbackWrapper); } else { log("iframe message passing not supported in this browser!", "error"); } }, stopReceivingMessages: function(id) { if (window.postMessage) { var detacher = callbackWrapperDetachers[id]; if (detacher) { detacher(); } } } }); }; /*globals qq */ /** * Defines the public API for FineUploader mode. */ (function() { "use strict"; qq.uiPublicApi = { clearStoredFiles: function() { this._parent.prototype.clearStoredFiles.apply(this, arguments); this._templating.clearFiles(); }, addExtraDropzone: function(element) { this._dnd && this._dnd.setupExtraDropzone(element); }, removeExtraDropzone: function(element) { if (this._dnd) { return this._dnd.removeDropzone(element); } }, getItemByFileId: function(id) { if (!this._templating.isHiddenForever(id)) { return this._templating.getFileContainer(id); } }, reset: function() { this._parent.prototype.reset.apply(this, arguments); this._templating.reset(); if (!this._options.button && this._templating.getButton()) { this._defaultButtonId = this._createUploadButton({element: this._templating.getButton()}).getButtonId(); } if (this._dnd) { this._dnd.dispose(); this._dnd = this._setupDragAndDrop(); } this._totalFilesInBatch = 0; this._filesInBatchAddedToUi = 0; this._setupClickAndEditEventHandlers(); }, setName: function(id, newName) { var formattedFilename = this._options.formatFileName(newName); this._parent.prototype.setName.apply(this, arguments); this._templating.updateFilename(id, formattedFilename); }, pauseUpload: function(id) { var paused = this._parent.prototype.pauseUpload.apply(this, arguments); paused && this._templating.uploadPaused(id); return paused; }, continueUpload: function(id) { var continued = this._parent.prototype.continueUpload.apply(this, arguments); continued && this._templating.uploadContinued(id); return continued; }, getId: function(fileContainerOrChildEl) { return this._templating.getFileId(fileContainerOrChildEl); }, getDropTarget: function(fileId) { var file = this.getFile(fileId); return file.qqDropTarget; } }; /** * Defines the private (internal) API for FineUploader mode. */ qq.uiPrivateApi = { _getButton: function(buttonId) { var button = this._parent.prototype._getButton.apply(this, arguments); if (!button) { if (buttonId === this._defaultButtonId) { button = this._templating.getButton(); } } return button; }, _removeFileItem: function(fileId) { this._templating.removeFile(fileId); }, _setupClickAndEditEventHandlers: function() { this._fileButtonsClickHandler = qq.FileButtonsClickHandler && this._bindFileButtonsClickEvent(); // A better approach would be to check specifically for focusin event support by querying the DOM API, // but the DOMFocusIn event is not exposed as a property, so we have to resort to UA string sniffing. this._focusinEventSupported = !qq.firefox(); if (this._isEditFilenameEnabled()) { this._filenameClickHandler = this._bindFilenameClickEvent(); this._filenameInputFocusInHandler = this._bindFilenameInputFocusInEvent(); this._filenameInputFocusHandler = this._bindFilenameInputFocusEvent(); } }, _setupDragAndDrop: function() { var self = this, dropZoneElements = this._options.dragAndDrop.extraDropzones, templating = this._templating, defaultDropZone = templating.getDropZone(); defaultDropZone && dropZoneElements.push(defaultDropZone); return new qq.DragAndDrop({ dropZoneElements: dropZoneElements, allowMultipleItems: this._options.multiple, classes: { dropActive: this._options.classes.dropActive }, callbacks: { processingDroppedFiles: function() { templating.showDropProcessing(); }, processingDroppedFilesComplete: function(files, targetEl) { templating.hideDropProcessing(); qq.each(files, function(idx, file) { file.qqDropTarget = targetEl; }); if (files.length) { self.addFiles(files, null, null); } }, dropError: function(code, errorData) { self._itemError(code, errorData); }, dropLog: function(message, level) { self.log(message, level); } } }); }, _bindFileButtonsClickEvent: function() { var self = this; return new qq.FileButtonsClickHandler({ templating: this._templating, log: function(message, lvl) { self.log(message, lvl); }, onDeleteFile: function(fileId) { self.deleteFile(fileId); }, onCancel: function(fileId) { self.cancel(fileId); }, onRetry: function(fileId) { self.retry(fileId); }, onPause: function(fileId) { self.pauseUpload(fileId); }, onContinue: function(fileId) { self.continueUpload(fileId); }, onGetName: function(fileId) { return self.getName(fileId); } }); }, _isEditFilenameEnabled: function() { /*jshint -W014 */ return this._templating.isEditFilenamePossible() && !this._options.autoUpload && qq.FilenameClickHandler && qq.FilenameInputFocusHandler && qq.FilenameInputFocusHandler; }, _filenameEditHandler: function() { var self = this, templating = this._templating; return { templating: templating, log: function(message, lvl) { self.log(message, lvl); }, onGetUploadStatus: function(fileId) { return self.getUploads({id: fileId}).status; }, onGetName: function(fileId) { return self.getName(fileId); }, onSetName: function(id, newName) { self.setName(id, newName); }, onEditingStatusChange: function(id, isEditing) { var qqInput = qq(templating.getEditInput(id)), qqFileContainer = qq(templating.getFileContainer(id)); if (isEditing) { qqInput.addClass("qq-editing"); templating.hideFilename(id); templating.hideEditIcon(id); } else { qqInput.removeClass("qq-editing"); templating.showFilename(id); templating.showEditIcon(id); } // Force IE8 and older to repaint qqFileContainer.addClass("qq-temp").removeClass("qq-temp"); } }; }, _onUploadStatusChange: function(id, oldStatus, newStatus) { this._parent.prototype._onUploadStatusChange.apply(this, arguments); if (this._isEditFilenameEnabled()) { // Status for a file exists before it has been added to the DOM, so we must be careful here. if (this._templating.getFileContainer(id) && newStatus !== qq.status.SUBMITTED) { this._templating.markFilenameEditable(id); this._templating.hideEditIcon(id); } } if (newStatus === qq.status.UPLOAD_RETRYING) { this._templating.hideRetry(id); this._templating.setStatusText(id); qq(this._templating.getFileContainer(id)).removeClass(this._classes.retrying); } else if (newStatus === qq.status.UPLOAD_FAILED) { this._templating.hidePause(id); } }, _bindFilenameInputFocusInEvent: function() { var spec = qq.extend({}, this._filenameEditHandler()); return new qq.FilenameInputFocusInHandler(spec); }, _bindFilenameInputFocusEvent: function() { var spec = qq.extend({}, this._filenameEditHandler()); return new qq.FilenameInputFocusHandler(spec); }, _bindFilenameClickEvent: function() { var spec = qq.extend({}, this._filenameEditHandler()); return new qq.FilenameClickHandler(spec); }, _storeForLater: function(id) { this._parent.prototype._storeForLater.apply(this, arguments); this._templating.hideSpinner(id); }, _onAllComplete: function(successful, failed) { this._parent.prototype._onAllComplete.apply(this, arguments); this._templating.resetTotalProgress(); }, _onSubmit: function(id, name) { var file = this.getFile(id); if (file && file.qqPath && this._options.dragAndDrop.reportDirectoryPaths) { this._paramsStore.addReadOnly(id, { qqpath: file.qqPath }); } this._parent.prototype._onSubmit.apply(this, arguments); this._addToList(id, name); }, // The file item has been added to the DOM. _onSubmitted: function(id) { // If the edit filename feature is enabled, mark the filename element as "editable" and the associated edit icon if (this._isEditFilenameEnabled()) { this._templating.markFilenameEditable(id); this._templating.showEditIcon(id); // If the focusin event is not supported, we must add a focus handler to the newly create edit filename text input if (!this._focusinEventSupported) { this._filenameInputFocusHandler.addHandler(this._templating.getEditInput(id)); } } }, // Update the progress bar & percentage as the file is uploaded _onProgress: function(id, name, loaded, total) { this._parent.prototype._onProgress.apply(this, arguments); this._templating.updateProgress(id, loaded, total); if (Math.round(loaded / total * 100) === 100) { this._templating.hideCancel(id); this._templating.hidePause(id); this._templating.hideProgress(id); this._templating.setStatusText(id, this._options.text.waitingForResponse); // If ~last byte was sent, display total file size this._displayFileSize(id); } else { // If still uploading, display percentage - total size is actually the total request(s) size this._displayFileSize(id, loaded, total); } }, _onTotalProgress: function(loaded, total) { this._parent.prototype._onTotalProgress.apply(this, arguments); this._templating.updateTotalProgress(loaded, total); }, _onComplete: function(id, name, result, xhr) { var parentRetVal = this._parent.prototype._onComplete.apply(this, arguments), templating = this._templating, fileContainer = templating.getFileContainer(id), self = this; function completeUpload(result) { // If this file is not represented in the templating module, perhaps it was hidden intentionally. // If so, don't perform any UI-related tasks related to this file. if (!fileContainer) { return; } templating.setStatusText(id); qq(fileContainer).removeClass(self._classes.retrying); templating.hideProgress(id); if (self.getUploads({id: id}).status !== qq.status.UPLOAD_FAILED) { templating.hideCancel(id); } templating.hideSpinner(id); if (result.success) { self._markFileAsSuccessful(id); } else { qq(fileContainer).addClass(self._classes.fail); templating.showCancel(id); if (templating.isRetryPossible() && !self._preventRetries[id]) { qq(fileContainer).addClass(self._classes.retryable); templating.showRetry(id); } self._controlFailureTextDisplay(id, result); } } // The parent may need to perform some async operation before we can accurately determine the status of the upload. if (parentRetVal instanceof qq.Promise) { parentRetVal.done(function(newResult) { completeUpload(newResult); }); } else { completeUpload(result); } return parentRetVal; }, _markFileAsSuccessful: function(id) { var templating = this._templating; if (this._isDeletePossible()) { templating.showDeleteButton(id); } qq(templating.getFileContainer(id)).addClass(this._classes.success); this._maybeUpdateThumbnail(id); }, _onUploadPrep: function(id) { this._parent.prototype._onUploadPrep.apply(this, arguments); this._templating.showSpinner(id); }, _onUpload: function(id, name) { var parentRetVal = this._parent.prototype._onUpload.apply(this, arguments); this._templating.showSpinner(id); return parentRetVal; }, _onUploadChunk: function(id, chunkData) { this._parent.prototype._onUploadChunk.apply(this, arguments); // Only display the pause button if we have finished uploading at least one chunk // & this file can be resumed if (chunkData.partIndex > 0 && this._handler.isResumable(id)) { this._templating.allowPause(id); } }, _onCancel: function(id, name) { this._parent.prototype._onCancel.apply(this, arguments); this._removeFileItem(id); if (this._getNotFinished() === 0) { this._templating.resetTotalProgress(); } }, _onBeforeAutoRetry: function(id) { var retryNumForDisplay, maxAuto, retryNote; this._parent.prototype._onBeforeAutoRetry.apply(this, arguments); this._showCancelLink(id); if (this._options.retry.showAutoRetryNote) { retryNumForDisplay = this._autoRetries[id]; maxAuto = this._options.retry.maxAutoAttempts; retryNote = this._options.retry.autoRetryNote.replace(/\{retryNum\}/g, retryNumForDisplay); retryNote = retryNote.replace(/\{maxAuto\}/g, maxAuto); this._templating.setStatusText(id, retryNote); qq(this._templating.getFileContainer(id)).addClass(this._classes.retrying); } }, //return false if we should not attempt the requested retry _onBeforeManualRetry: function(id) { if (this._parent.prototype._onBeforeManualRetry.apply(this, arguments)) { this._templating.resetProgress(id); qq(this._templating.getFileContainer(id)).removeClass(this._classes.fail); this._templating.setStatusText(id); this._templating.showSpinner(id); this._showCancelLink(id); return true; } else { qq(this._templating.getFileContainer(id)).addClass(this._classes.retryable); this._templating.showRetry(id); return false; } }, _onSubmitDelete: function(id) { var onSuccessCallback = qq.bind(this._onSubmitDeleteSuccess, this); this._parent.prototype._onSubmitDelete.call(this, id, onSuccessCallback); }, _onSubmitDeleteSuccess: function(id, uuid, additionalMandatedParams) { if (this._options.deleteFile.forceConfirm) { this._showDeleteConfirm.apply(this, arguments); } else { this._sendDeleteRequest.apply(this, arguments); } }, _onDeleteComplete: function(id, xhr, isError) { this._parent.prototype._onDeleteComplete.apply(this, arguments); this._templating.hideSpinner(id); if (isError) { this._templating.setStatusText(id, this._options.deleteFile.deletingFailedText); this._templating.showDeleteButton(id); } else { this._removeFileItem(id); } }, _sendDeleteRequest: function(id, uuid, additionalMandatedParams) { this._templating.hideDeleteButton(id); this._templating.showSpinner(id); this._templating.setStatusText(id, this._options.deleteFile.deletingStatusText); this._deleteHandler.sendDelete.apply(this, arguments); }, _showDeleteConfirm: function(id, uuid, mandatedParams) { /*jshint -W004 */ var fileName = this.getName(id), confirmMessage = this._options.deleteFile.confirmMessage.replace(/\{filename\}/g, fileName), uuid = this.getUuid(id), deleteRequestArgs = arguments, self = this, retVal; retVal = this._options.showConfirm(confirmMessage); if (qq.isGenericPromise(retVal)) { retVal.then(function() { self._sendDeleteRequest.apply(self, deleteRequestArgs); }); } else if (retVal !== false) { self._sendDeleteRequest.apply(self, deleteRequestArgs); } }, _addToList: function(id, name, canned) { var prependData, prependIndex = 0, dontDisplay = this._handler.isProxied(id) && this._options.scaling.hideScaled, record; if (this._options.display.prependFiles) { if (this._totalFilesInBatch > 1 && this._filesInBatchAddedToUi > 0) { prependIndex = this._filesInBatchAddedToUi - 1; } prependData = { index: prependIndex }; } if (!canned) { if (this._options.disableCancelForFormUploads && !qq.supportedFeatures.ajaxUploading) { this._templating.disableCancel(); } // Cancel all existing (previous) files and clear the list if this file is not part of // a scaled file group that has already been accepted, or if this file is not part of // a scaled file group at all. if (!this._options.multiple) { record = this.getUploads({id: id}); this._handledProxyGroup = this._handledProxyGroup || record.proxyGroupId; if (record.proxyGroupId !== this._handledProxyGroup || !record.proxyGroupId) { this._handler.cancelAll(); this._clearList(); this._handledProxyGroup = null; } } } if (canned) { this._templating.addFileToCache(id, this._options.formatFileName(name), prependData, dontDisplay); this._thumbnailUrls[id] && this._templating.updateThumbnail(id, this._thumbnailUrls[id], true); } else { this._templating.addFile(id, this._options.formatFileName(name), prependData, dontDisplay); this._templating.generatePreview(id, this.getFile(id)); } this._filesInBatchAddedToUi += 1; if (canned || (this._options.display.fileSizeOnSubmit && qq.supportedFeatures.ajaxUploading)) { this._displayFileSize(id); } }, _clearList: function() { this._templating.clearFiles(); this.clearStoredFiles(); }, _displayFileSize: function(id, loadedSize, totalSize) { var size = this.getSize(id), sizeForDisplay = this._formatSize(size); if (size >= 0) { if (loadedSize !== undefined && totalSize !== undefined) { sizeForDisplay = this._formatProgress(loadedSize, totalSize); } this._templating.updateSize(id, sizeForDisplay); } }, _formatProgress: function(uploadedSize, totalSize) { var message = this._options.text.formatProgress; function r(name, replacement) { message = message.replace(name, replacement); } r("{percent}", Math.round(uploadedSize / totalSize * 100)); r("{total_size}", this._formatSize(totalSize)); return message; }, _controlFailureTextDisplay: function(id, response) { var mode, responseProperty, failureReason; mode = this._options.failedUploadTextDisplay.mode; responseProperty = this._options.failedUploadTextDisplay.responseProperty; if (mode === "custom") { failureReason = response[responseProperty]; if (!failureReason) { failureReason = this._options.text.failUpload; } this._templating.setStatusText(id, failureReason); if (this._options.failedUploadTextDisplay.enableTooltip) { this._showTooltip(id, failureReason); } } else if (mode === "default") { this._templating.setStatusText(id, this._options.text.failUpload); } else if (mode !== "none") { this.log("failedUploadTextDisplay.mode value of '" + mode + "' is not valid", "warn"); } }, _showTooltip: function(id, text) { this._templating.getFileContainer(id).title = text; }, _showCancelLink: function(id) { if (!this._options.disableCancelForFormUploads || qq.supportedFeatures.ajaxUploading) { this._templating.showCancel(id); } }, _itemError: function(code, name, item) { var message = this._parent.prototype._itemError.apply(this, arguments); this._options.showMessage(message); }, _batchError: function(message) { this._parent.prototype._batchError.apply(this, arguments); this._options.showMessage(message); }, _setupPastePrompt: function() { var self = this; this._options.callbacks.onPasteReceived = function() { var message = self._options.paste.namePromptMessage, defaultVal = self._options.paste.defaultName; return self._options.showPrompt(message, defaultVal); }; }, _fileOrBlobRejected: function(id, name) { this._totalFilesInBatch -= 1; this._parent.prototype._fileOrBlobRejected.apply(this, arguments); }, _prepareItemsForUpload: function(items, params, endpoint) { this._totalFilesInBatch = items.length; this._filesInBatchAddedToUi = 0; this._parent.prototype._prepareItemsForUpload.apply(this, arguments); }, _maybeUpdateThumbnail: function(fileId) { var thumbnailUrl = this._thumbnailUrls[fileId], fileStatus = this.getUploads({id: fileId}).status; if (fileStatus !== qq.status.DELETED && (thumbnailUrl || this._options.thumbnails.placeholders.waitUntilResponse || !qq.supportedFeatures.imagePreviews)) { // This will replace the "waiting" placeholder with a "preview not available" placeholder // if called with a null thumbnailUrl. this._templating.updateThumbnail(fileId, thumbnailUrl); } }, _addCannedFile: function(sessionData) { var id = this._parent.prototype._addCannedFile.apply(this, arguments); this._addToList(id, this.getName(id), true); this._templating.hideSpinner(id); this._templating.hideCancel(id); this._markFileAsSuccessful(id); return id; }, _setSize: function(id, newSize) { this._parent.prototype._setSize.apply(this, arguments); this._templating.updateSize(id, this._formatSize(newSize)); }, _sessionRequestComplete: function() { this._templating.addCacheToDom(); this._parent.prototype._sessionRequestComplete.apply(this, arguments); } }; }()); /*globals qq */ /** * This defines FineUploader mode, which is a default UI w/ drag & drop uploading. */ qq.FineUploader = function(o, namespace) { "use strict"; var self = this; // By default this should inherit instance data from FineUploaderBasic, but this can be overridden // if the (internal) caller defines a different parent. The parent is also used by // the private and public API functions that need to delegate to a parent function. this._parent = namespace ? qq[namespace].FineUploaderBasic : qq.FineUploaderBasic; this._parent.apply(this, arguments); // Options provided by FineUploader mode qq.extend(this._options, { element: null, button: null, listElement: null, dragAndDrop: { extraDropzones: [], reportDirectoryPaths: false }, text: { formatProgress: "{percent}% of {total_size}", failUpload: "Upload failed", waitingForResponse: "Processing...", paused: "Paused" }, template: "qq-template", classes: { retrying: "qq-upload-retrying", retryable: "qq-upload-retryable", success: "qq-upload-success", fail: "qq-upload-fail", editable: "qq-editable", hide: "qq-hide", dropActive: "qq-upload-drop-area-active" }, failedUploadTextDisplay: { mode: "default", //default, custom, or none responseProperty: "error", enableTooltip: true }, messages: { tooManyFilesError: "You may only drop one file", unsupportedBrowser: "Unrecoverable error - this browser does not permit file uploading of any kind." }, retry: { showAutoRetryNote: true, autoRetryNote: "Retrying {retryNum}/{maxAuto}..." }, deleteFile: { forceConfirm: false, confirmMessage: "Are you sure you want to delete {filename}?", deletingStatusText: "Deleting...", deletingFailedText: "Delete failed" }, display: { fileSizeOnSubmit: false, prependFiles: false }, paste: { promptForName: false, namePromptMessage: "Please name this image" }, thumbnails: { maxCount: 0, placeholders: { waitUntilResponse: false, notAvailablePath: null, waitingPath: null }, timeBetweenThumbs: 750 }, scaling: { hideScaled: false }, showMessage: function(message) { if (self._templating.hasDialog("alert")) { return self._templating.showDialog("alert", message); } else { setTimeout(function() { window.alert(message); }, 0); } }, showConfirm: function(message) { if (self._templating.hasDialog("confirm")) { return self._templating.showDialog("confirm", message); } else { return window.confirm(message); } }, showPrompt: function(message, defaultValue) { if (self._templating.hasDialog("prompt")) { return self._templating.showDialog("prompt", message, defaultValue); } else { return window.prompt(message, defaultValue); } } }, true); // Replace any default options with user defined ones qq.extend(this._options, o, true); this._templating = new qq.Templating({ log: qq.bind(this.log, this), templateIdOrEl: this._options.template, containerEl: this._options.element, fileContainerEl: this._options.listElement, button: this._options.button, imageGenerator: this._imageGenerator, classes: { hide: this._options.classes.hide, editable: this._options.classes.editable }, limits: { maxThumbs: this._options.thumbnails.maxCount, timeBetweenThumbs: this._options.thumbnails.timeBetweenThumbs }, placeholders: { waitUntilUpdate: this._options.thumbnails.placeholders.waitUntilResponse, thumbnailNotAvailable: this._options.thumbnails.placeholders.notAvailablePath, waitingForThumbnail: this._options.thumbnails.placeholders.waitingPath }, text: this._options.text }); if (this._options.workarounds.ios8SafariUploads && qq.ios800() && qq.iosSafari()) { this._templating.renderFailure(this._options.messages.unsupportedBrowserIos8Safari); } else if (!qq.supportedFeatures.uploading || (this._options.cors.expected && !qq.supportedFeatures.uploadCors)) { this._templating.renderFailure(this._options.messages.unsupportedBrowser); } else { this._wrapCallbacks(); this._templating.render(); this._classes = this._options.classes; if (!this._options.button && this._templating.getButton()) { this._defaultButtonId = this._createUploadButton({element: this._templating.getButton()}).getButtonId(); } this._setupClickAndEditEventHandlers(); if (qq.DragAndDrop && qq.supportedFeatures.fileDrop) { this._dnd = this._setupDragAndDrop(); } if (this._options.paste.targetElement && this._options.paste.promptForName) { if (qq.PasteSupport) { this._setupPastePrompt(); } else { this.log("Paste support module not found.", "error"); } } this._totalFilesInBatch = 0; this._filesInBatchAddedToUi = 0; } }; // Inherit the base public & private API methods qq.extend(qq.FineUploader.prototype, qq.basePublicApi); qq.extend(qq.FineUploader.prototype, qq.basePrivateApi); // Add the FineUploader/default UI public & private UI methods, which may override some base methods. qq.extend(qq.FineUploader.prototype, qq.uiPublicApi); qq.extend(qq.FineUploader.prototype, qq.uiPrivateApi); /* globals qq */ /* jshint -W065 */ /** * Module responsible for rendering all Fine Uploader UI templates. This module also asserts at least * a limited amount of control over the template elements after they are added to the DOM. * Wherever possible, this module asserts total control over template elements present in the DOM. * * @param spec Specification object used to control various templating behaviors * @constructor */ qq.Templating = function(spec) { "use strict"; var FILE_ID_ATTR = "qq-file-id", FILE_CLASS_PREFIX = "qq-file-id-", THUMBNAIL_MAX_SIZE_ATTR = "qq-max-size", THUMBNAIL_SERVER_SCALE_ATTR = "qq-server-scale", // This variable is duplicated in the DnD module since it can function as a standalone as well HIDE_DROPZONE_ATTR = "qq-hide-dropzone", DROPZPONE_TEXT_ATTR = "qq-drop-area-text", IN_PROGRESS_CLASS = "qq-in-progress", HIDDEN_FOREVER_CLASS = "qq-hidden-forever", fileBatch = { content: document.createElement("span"), map: {} }, isCancelDisabled = false, generatedThumbnails = 0, thumbnailQueueMonitorRunning = false, thumbGenerationQueue = [], thumbnailMaxSize = -1, options = { log: null, limits: { maxThumbs: 0, timeBetweenThumbs: 750 }, templateIdOrEl: "qq-template", containerEl: null, fileContainerEl: null, button: null, imageGenerator: null, classes: { hide: "qq-hide", editable: "qq-editable" }, placeholders: { waitUntilUpdate: false, thumbnailNotAvailable: null, waitingForThumbnail: null }, text: { paused: "Paused" } }, selectorClasses = { button: "qq-upload-button-selector", alertDialog: "qq-alert-dialog-selector", dialogCancelButton: "qq-cancel-button-selector", confirmDialog: "qq-confirm-dialog-selector", dialogMessage: "qq-dialog-message-selector", dialogOkButton: "qq-ok-button-selector", promptDialog: "qq-prompt-dialog-selector", uploader: "qq-uploader-selector", drop: "qq-upload-drop-area-selector", list: "qq-upload-list-selector", progressBarContainer: "qq-progress-bar-container-selector", progressBar: "qq-progress-bar-selector", totalProgressBarContainer: "qq-total-progress-bar-container-selector", totalProgressBar: "qq-total-progress-bar-selector", file: "qq-upload-file-selector", spinner: "qq-upload-spinner-selector", size: "qq-upload-size-selector", cancel: "qq-upload-cancel-selector", pause: "qq-upload-pause-selector", continueButton: "qq-upload-continue-selector", deleteButton: "qq-upload-delete-selector", retry: "qq-upload-retry-selector", statusText: "qq-upload-status-text-selector", editFilenameInput: "qq-edit-filename-selector", editNameIcon: "qq-edit-filename-icon-selector", dropText: "qq-upload-drop-area-text-selector", dropProcessing: "qq-drop-processing-selector", dropProcessingSpinner: "qq-drop-processing-spinner-selector", thumbnail: "qq-thumbnail-selector" }, previewGeneration = {}, cachedThumbnailNotAvailableImg = new qq.Promise(), cachedWaitingForThumbnailImg = new qq.Promise(), log, isEditElementsExist, isRetryElementExist, templateHtml, container, fileList, showThumbnails, serverScale, // During initialization of the templating module we should cache any // placeholder images so we can quickly swap them into the file list on demand. // Any placeholder images that cannot be loaded/found are simply ignored. cacheThumbnailPlaceholders = function() { var notAvailableUrl = options.placeholders.thumbnailNotAvailable, waitingUrl = options.placeholders.waitingForThumbnail, spec = { maxSize: thumbnailMaxSize, scale: serverScale }; if (showThumbnails) { if (notAvailableUrl) { options.imageGenerator.generate(notAvailableUrl, new Image(), spec).then( function(updatedImg) { cachedThumbnailNotAvailableImg.success(updatedImg); }, function() { cachedThumbnailNotAvailableImg.failure(); log("Problem loading 'not available' placeholder image at " + notAvailableUrl, "error"); } ); } else { cachedThumbnailNotAvailableImg.failure(); } if (waitingUrl) { options.imageGenerator.generate(waitingUrl, new Image(), spec).then( function(updatedImg) { cachedWaitingForThumbnailImg.success(updatedImg); }, function() { cachedWaitingForThumbnailImg.failure(); log("Problem loading 'waiting for thumbnail' placeholder image at " + waitingUrl, "error"); } ); } else { cachedWaitingForThumbnailImg.failure(); } } }, // Displays a "waiting for thumbnail" type placeholder image // iff we were able to load it during initialization of the templating module. displayWaitingImg = function(thumbnail) { var waitingImgPlacement = new qq.Promise(); cachedWaitingForThumbnailImg.then(function(img) { maybeScalePlaceholderViaCss(img, thumbnail); /* jshint eqnull:true */ if (!thumbnail.src) { thumbnail.src = img.src; thumbnail.onload = function() { thumbnail.onload = null; show(thumbnail); waitingImgPlacement.success(); }; } else { waitingImgPlacement.success(); } }, function() { // In some browsers (such as IE9 and older) an img w/out a src attribute // are displayed as "broken" images, so we should just hide the img tag // if we aren't going to display the "waiting" placeholder. hide(thumbnail); waitingImgPlacement.success(); }); return waitingImgPlacement; }, generateNewPreview = function(id, blob, spec) { var thumbnail = getThumbnail(id); log("Generating new thumbnail for " + id); blob.qqThumbnailId = id; return options.imageGenerator.generate(blob, thumbnail, spec).then( function() { generatedThumbnails++; show(thumbnail); previewGeneration[id].success(); }, function() { previewGeneration[id].failure(); // Display the "not available" placeholder img only if we are // not expecting a thumbnail at a later point, such as in a server response. if (!options.placeholders.waitUntilUpdate) { maybeSetDisplayNotAvailableImg(id, thumbnail); } }); }, generateNextQueuedPreview = function() { if (thumbGenerationQueue.length) { thumbnailQueueMonitorRunning = true; var queuedThumbRequest = thumbGenerationQueue.shift(); if (queuedThumbRequest.update) { processUpdateQueuedPreviewRequest(queuedThumbRequest); } else { processNewQueuedPreviewRequest(queuedThumbRequest); } } else { thumbnailQueueMonitorRunning = false; } }, getCancel = function(id) { return getTemplateEl(getFile(id), selectorClasses.cancel); }, getContinue = function(id) { return getTemplateEl(getFile(id), selectorClasses.continueButton); }, getDialog = function(type) { return getTemplateEl(container, selectorClasses[type + "Dialog"]); }, getDelete = function(id) { return getTemplateEl(getFile(id), selectorClasses.deleteButton); }, getDropProcessing = function() { return getTemplateEl(container, selectorClasses.dropProcessing); }, getEditIcon = function(id) { return getTemplateEl(getFile(id), selectorClasses.editNameIcon); }, getFile = function(id) { return fileBatch.map[id] || qq(fileList).getFirstByClass(FILE_CLASS_PREFIX + id); }, getFilename = function(id) { return getTemplateEl(getFile(id), selectorClasses.file); }, getPause = function(id) { return getTemplateEl(getFile(id), selectorClasses.pause); }, getProgress = function(id) { /* jshint eqnull:true */ // Total progress bar if (id == null) { return getTemplateEl(container, selectorClasses.totalProgressBarContainer) || getTemplateEl(container, selectorClasses.totalProgressBar); } // Per-file progress bar return getTemplateEl(getFile(id), selectorClasses.progressBarContainer) || getTemplateEl(getFile(id), selectorClasses.progressBar); }, getRetry = function(id) { return getTemplateEl(getFile(id), selectorClasses.retry); }, getSize = function(id) { return getTemplateEl(getFile(id), selectorClasses.size); }, getSpinner = function(id) { return getTemplateEl(getFile(id), selectorClasses.spinner); }, getTemplateEl = function(context, cssClass) { return context && qq(context).getFirstByClass(cssClass); }, getThumbnail = function(id) { return showThumbnails && getTemplateEl(getFile(id), selectorClasses.thumbnail); }, hide = function(el) { el && qq(el).addClass(options.classes.hide); }, // Ensures a placeholder image does not exceed any max size specified // via `style` attribute properties iff <canvas> was not used to scale // the placeholder AND the target <img> doesn't already have these `style` attribute properties set. maybeScalePlaceholderViaCss = function(placeholder, thumbnail) { var maxWidth = placeholder.style.maxWidth, maxHeight = placeholder.style.maxHeight; if (maxHeight && maxWidth && !thumbnail.style.maxWidth && !thumbnail.style.maxHeight) { qq(thumbnail).css({ maxWidth: maxWidth, maxHeight: maxHeight }); } }, // Displays a "thumbnail not available" type placeholder image // iff we were able to load this placeholder during initialization // of the templating module or after preview generation has failed. maybeSetDisplayNotAvailableImg = function(id, thumbnail) { var previewing = previewGeneration[id] || new qq.Promise().failure(), notAvailableImgPlacement = new qq.Promise(); cachedThumbnailNotAvailableImg.then(function(img) { previewing.then( function() { notAvailableImgPlacement.success(); }, function() { maybeScalePlaceholderViaCss(img, thumbnail); thumbnail.onload = function() { thumbnail.onload = null; notAvailableImgPlacement.success(); }; thumbnail.src = img.src; show(thumbnail); } ); }); return notAvailableImgPlacement; }, /** * Grabs the HTML from the script tag holding the template markup. This function will also adjust * some internally-tracked state variables based on the contents of the template. * The template is filtered so that irrelevant elements (such as the drop zone if DnD is not supported) * are omitted from the DOM. Useful errors will be thrown if the template cannot be parsed. * * @returns {{template: *, fileTemplate: *}} HTML for the top-level file items templates */ parseAndGetTemplate = function() { var scriptEl, scriptHtml, fileListNode, tempTemplateEl, fileListHtml, defaultButton, dropArea, thumbnail, dropProcessing, dropTextEl, uploaderEl; log("Parsing template"); /*jshint -W116*/ if (options.templateIdOrEl == null) { throw new Error("You MUST specify either a template element or ID!"); } // Grab the contents of the script tag holding the template. if (qq.isString(options.templateIdOrEl)) { scriptEl = document.getElementById(options.templateIdOrEl); if (scriptEl === null) { throw new Error(qq.format("Cannot find template script at ID '{}'!", options.templateIdOrEl)); } scriptHtml = scriptEl.innerHTML; } else { if (options.templateIdOrEl.innerHTML === undefined) { throw new Error("You have specified an invalid value for the template option! " + "It must be an ID or an Element."); } scriptHtml = options.templateIdOrEl.innerHTML; } scriptHtml = qq.trimStr(scriptHtml); tempTemplateEl = document.createElement("div"); tempTemplateEl.appendChild(qq.toElement(scriptHtml)); uploaderEl = qq(tempTemplateEl).getFirstByClass(selectorClasses.uploader); // Don't include the default template button in the DOM // if an alternate button container has been specified. if (options.button) { defaultButton = qq(tempTemplateEl).getFirstByClass(selectorClasses.button); if (defaultButton) { qq(defaultButton).remove(); } } // Omit the drop processing element from the DOM if DnD is not supported by the UA, // or the drag and drop module is not found. // NOTE: We are consciously not removing the drop zone if the UA doesn't support DnD // to support layouts where the drop zone is also a container for visible elements, // such as the file list. if (!qq.DragAndDrop || !qq.supportedFeatures.fileDrop) { dropProcessing = qq(tempTemplateEl).getFirstByClass(selectorClasses.dropProcessing); if (dropProcessing) { qq(dropProcessing).remove(); } } dropArea = qq(tempTemplateEl).getFirstByClass(selectorClasses.drop); // If DnD is not available then remove // it from the DOM as well. if (dropArea && !qq.DragAndDrop) { log("DnD module unavailable.", "info"); qq(dropArea).remove(); } if (!qq.supportedFeatures.fileDrop) { // don't display any "drop files to upload" background text uploaderEl.removeAttribute(DROPZPONE_TEXT_ATTR); if (dropArea && qq(dropArea).hasAttribute(HIDE_DROPZONE_ATTR)) { // If there is a drop area defined in the template, and the current UA doesn't support DnD, // and the drop area is marked as "hide before enter", ensure it is hidden as the DnD module // will not do this (since we will not be loading the DnD module) qq(dropArea).css({ display: "none" }); } } else if (qq(uploaderEl).hasAttribute(DROPZPONE_TEXT_ATTR) && dropArea) { dropTextEl = qq(dropArea).getFirstByClass(selectorClasses.dropText); dropTextEl && qq(dropTextEl).remove(); } // Ensure the `showThumbnails` flag is only set if the thumbnail element // is present in the template AND the current UA is capable of generating client-side previews. thumbnail = qq(tempTemplateEl).getFirstByClass(selectorClasses.thumbnail); if (!showThumbnails) { thumbnail && qq(thumbnail).remove(); } else if (thumbnail) { thumbnailMaxSize = parseInt(thumbnail.getAttribute(THUMBNAIL_MAX_SIZE_ATTR)); // Only enforce max size if the attr value is non-zero thumbnailMaxSize = thumbnailMaxSize > 0 ? thumbnailMaxSize : null; serverScale = qq(thumbnail).hasAttribute(THUMBNAIL_SERVER_SCALE_ATTR); } showThumbnails = showThumbnails && thumbnail; isEditElementsExist = qq(tempTemplateEl).getByClass(selectorClasses.editFilenameInput).length > 0; isRetryElementExist = qq(tempTemplateEl).getByClass(selectorClasses.retry).length > 0; fileListNode = qq(tempTemplateEl).getFirstByClass(selectorClasses.list); /*jshint -W116*/ if (fileListNode == null) { throw new Error("Could not find the file list container in the template!"); } fileListHtml = fileListNode.innerHTML; fileListNode.innerHTML = ""; // We must call `createElement` in IE8 in order to target and hide any <dialog> via CSS if (tempTemplateEl.getElementsByTagName("DIALOG").length) { document.createElement("dialog"); } log("Template parsing complete"); return { template: qq.trimStr(tempTemplateEl.innerHTML), fileTemplate: qq.trimStr(fileListHtml) }; }, prependFile = function(el, index, fileList) { var parentEl = fileList, beforeEl = parentEl.firstChild; if (index > 0) { beforeEl = qq(parentEl).children()[index].nextSibling; } parentEl.insertBefore(el, beforeEl); }, processNewQueuedPreviewRequest = function(queuedThumbRequest) { var id = queuedThumbRequest.id, optFileOrBlob = queuedThumbRequest.optFileOrBlob, relatedThumbnailId = optFileOrBlob && optFileOrBlob.qqThumbnailId, thumbnail = getThumbnail(id), spec = { maxSize: thumbnailMaxSize, scale: true, orient: true }; if (qq.supportedFeatures.imagePreviews) { if (thumbnail) { if (options.limits.maxThumbs && options.limits.maxThumbs <= generatedThumbnails) { maybeSetDisplayNotAvailableImg(id, thumbnail); generateNextQueuedPreview(); } else { displayWaitingImg(thumbnail).done(function() { previewGeneration[id] = new qq.Promise(); previewGeneration[id].done(function() { setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs); }); /* jshint eqnull: true */ // If we've already generated an <img> for this file, use the one that exists, // don't waste resources generating a new one. if (relatedThumbnailId != null) { useCachedPreview(id, relatedThumbnailId); } else { generateNewPreview(id, optFileOrBlob, spec); } }); } } // File element in template may have been removed, so move on to next item in queue else { generateNextQueuedPreview(); } } else if (thumbnail) { displayWaitingImg(thumbnail); generateNextQueuedPreview(); } }, processUpdateQueuedPreviewRequest = function(queuedThumbRequest) { var id = queuedThumbRequest.id, thumbnailUrl = queuedThumbRequest.thumbnailUrl, showWaitingImg = queuedThumbRequest.showWaitingImg, thumbnail = getThumbnail(id), spec = { maxSize: thumbnailMaxSize, scale: serverScale }; if (thumbnail) { if (thumbnailUrl) { if (options.limits.maxThumbs && options.limits.maxThumbs <= generatedThumbnails) { maybeSetDisplayNotAvailableImg(id, thumbnail); generateNextQueuedPreview(); } else { if (showWaitingImg) { displayWaitingImg(thumbnail); } return options.imageGenerator.generate(thumbnailUrl, thumbnail, spec).then( function() { show(thumbnail); generatedThumbnails++; setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs); }, function() { maybeSetDisplayNotAvailableImg(id, thumbnail); setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs); } ); } } else { maybeSetDisplayNotAvailableImg(id, thumbnail); generateNextQueuedPreview(); } } }, setProgressBarWidth = function(id, percent) { var bar = getProgress(id), /* jshint eqnull:true */ progressBarSelector = id == null ? selectorClasses.totalProgressBar : selectorClasses.progressBar; if (bar && !qq(bar).hasClass(progressBarSelector)) { bar = qq(bar).getFirstByClass(progressBarSelector); } if (bar) { qq(bar).css({width: percent + "%"}); bar.setAttribute("aria-valuenow", percent); } }, show = function(el) { el && qq(el).removeClass(options.classes.hide); }, useCachedPreview = function(targetThumbnailId, cachedThumbnailId) { var targetThumnail = getThumbnail(targetThumbnailId), cachedThumbnail = getThumbnail(cachedThumbnailId); log(qq.format("ID {} is the same file as ID {}. Will use generated thumbnail from ID {} instead.", targetThumbnailId, cachedThumbnailId, cachedThumbnailId)); // Generation of the related thumbnail may still be in progress, so, wait until it is done. previewGeneration[cachedThumbnailId].then(function() { generatedThumbnails++; previewGeneration[targetThumbnailId].success(); log(qq.format("Now using previously generated thumbnail created for ID {} on ID {}.", cachedThumbnailId, targetThumbnailId)); targetThumnail.src = cachedThumbnail.src; show(targetThumnail); }, function() { previewGeneration[targetThumbnailId].failure(); if (!options.placeholders.waitUntilUpdate) { maybeSetDisplayNotAvailableImg(targetThumbnailId, targetThumnail); } }); }; qq.extend(options, spec); log = options.log; // No need to worry about conserving CPU or memory on older browsers, // since there is no ability to preview, and thumbnail display is primitive and quick. if (!qq.supportedFeatures.imagePreviews) { options.limits.timeBetweenThumbs = 0; options.limits.maxThumbs = 0; } container = options.containerEl; showThumbnails = options.imageGenerator !== undefined; templateHtml = parseAndGetTemplate(); cacheThumbnailPlaceholders(); qq.extend(this, { render: function() { log("Rendering template in DOM."); generatedThumbnails = 0; container.innerHTML = templateHtml.template; hide(getDropProcessing()); this.hideTotalProgress(); fileList = options.fileContainerEl || getTemplateEl(container, selectorClasses.list); log("Template rendering complete"); }, renderFailure: function(message) { var cantRenderEl = qq.toElement(message); container.innerHTML = ""; container.appendChild(cantRenderEl); }, reset: function() { this.render(); }, clearFiles: function() { fileList.innerHTML = ""; }, disableCancel: function() { isCancelDisabled = true; }, addFile: function(id, name, prependInfo, hideForever, batch) { var fileEl = qq.toElement(templateHtml.fileTemplate), fileNameEl = getTemplateEl(fileEl, selectorClasses.file), uploaderEl = getTemplateEl(container, selectorClasses.uploader), fileContainer = batch ? fileBatch.content : fileList, thumb; if (batch) { fileBatch.map[id] = fileEl; } qq(fileEl).addClass(FILE_CLASS_PREFIX + id); uploaderEl.removeAttribute(DROPZPONE_TEXT_ATTR); if (fileNameEl) { qq(fileNameEl).setText(name); fileNameEl.setAttribute("title", name); } fileEl.setAttribute(FILE_ID_ATTR, id); if (prependInfo) { prependFile(fileEl, prependInfo.index, fileContainer); } else { fileContainer.appendChild(fileEl); } if (hideForever) { fileEl.style.display = "none"; qq(fileEl).addClass(HIDDEN_FOREVER_CLASS); } else { hide(getProgress(id)); hide(getSize(id)); hide(getDelete(id)); hide(getRetry(id)); hide(getPause(id)); hide(getContinue(id)); if (isCancelDisabled) { this.hideCancel(id); } thumb = getThumbnail(id); if (thumb && !thumb.src) { cachedWaitingForThumbnailImg.then(function(waitingImg) { thumb.src = waitingImg.src; if (waitingImg.style.maxHeight && waitingImg.style.maxWidth) { qq(thumb).css({ maxHeight: waitingImg.style.maxHeight, maxWidth: waitingImg.style.maxWidth }); } show(thumb); }); } } }, addFileToCache: function(id, name, prependInfo, hideForever) { this.addFile(id, name, prependInfo, hideForever, true); }, addCacheToDom: function() { fileList.appendChild(fileBatch.content); fileBatch.content = document.createElement("span"); fileBatch.map = {}; }, removeFile: function(id) { qq(getFile(id)).remove(); }, getFileId: function(el) { var currentNode = el; if (currentNode) { /*jshint -W116*/ while (currentNode.getAttribute(FILE_ID_ATTR) == null) { currentNode = currentNode.parentNode; } return parseInt(currentNode.getAttribute(FILE_ID_ATTR)); } }, getFileList: function() { return fileList; }, markFilenameEditable: function(id) { var filename = getFilename(id); filename && qq(filename).addClass(options.classes.editable); }, updateFilename: function(id, name) { var filenameEl = getFilename(id); if (filenameEl) { qq(filenameEl).setText(name); filenameEl.setAttribute("title", name); } }, hideFilename: function(id) { hide(getFilename(id)); }, showFilename: function(id) { show(getFilename(id)); }, isFileName: function(el) { return qq(el).hasClass(selectorClasses.file); }, getButton: function() { return options.button || getTemplateEl(container, selectorClasses.button); }, hideDropProcessing: function() { hide(getDropProcessing()); }, showDropProcessing: function() { show(getDropProcessing()); }, getDropZone: function() { return getTemplateEl(container, selectorClasses.drop); }, isEditFilenamePossible: function() { return isEditElementsExist; }, hideRetry: function(id) { hide(getRetry(id)); }, isRetryPossible: function() { return isRetryElementExist; }, showRetry: function(id) { show(getRetry(id)); }, getFileContainer: function(id) { return getFile(id); }, showEditIcon: function(id) { var icon = getEditIcon(id); icon && qq(icon).addClass(options.classes.editable); }, isHiddenForever: function(id) { return qq(getFile(id)).hasClass(HIDDEN_FOREVER_CLASS); }, hideEditIcon: function(id) { var icon = getEditIcon(id); icon && qq(icon).removeClass(options.classes.editable); }, isEditIcon: function(el) { return qq(el).hasClass(selectorClasses.editNameIcon, true); }, getEditInput: function(id) { return getTemplateEl(getFile(id), selectorClasses.editFilenameInput); }, isEditInput: function(el) { return qq(el).hasClass(selectorClasses.editFilenameInput, true); }, updateProgress: function(id, loaded, total) { var bar = getProgress(id), percent; if (bar && total > 0) { percent = Math.round(loaded / total * 100); if (percent === 100) { hide(bar); } else { show(bar); } setProgressBarWidth(id, percent); } }, updateTotalProgress: function(loaded, total) { this.updateProgress(null, loaded, total); }, hideProgress: function(id) { var bar = getProgress(id); bar && hide(bar); }, hideTotalProgress: function() { this.hideProgress(); }, resetProgress: function(id) { setProgressBarWidth(id, 0); this.hideTotalProgress(id); }, resetTotalProgress: function() { this.resetProgress(); }, showCancel: function(id) { if (!isCancelDisabled) { var cancel = getCancel(id); cancel && qq(cancel).removeClass(options.classes.hide); } }, hideCancel: function(id) { hide(getCancel(id)); }, isCancel: function(el) { return qq(el).hasClass(selectorClasses.cancel, true); }, allowPause: function(id) { show(getPause(id)); hide(getContinue(id)); }, uploadPaused: function(id) { this.setStatusText(id, options.text.paused); this.allowContinueButton(id); hide(getSpinner(id)); }, hidePause: function(id) { hide(getPause(id)); }, isPause: function(el) { return qq(el).hasClass(selectorClasses.pause, true); }, isContinueButton: function(el) { return qq(el).hasClass(selectorClasses.continueButton, true); }, allowContinueButton: function(id) { show(getContinue(id)); hide(getPause(id)); }, uploadContinued: function(id) { this.setStatusText(id, ""); this.allowPause(id); show(getSpinner(id)); }, showDeleteButton: function(id) { show(getDelete(id)); }, hideDeleteButton: function(id) { hide(getDelete(id)); }, isDeleteButton: function(el) { return qq(el).hasClass(selectorClasses.deleteButton, true); }, isRetry: function(el) { return qq(el).hasClass(selectorClasses.retry, true); }, updateSize: function(id, text) { var size = getSize(id); if (size) { show(size); qq(size).setText(text); } }, setStatusText: function(id, text) { var textEl = getTemplateEl(getFile(id), selectorClasses.statusText); if (textEl) { /*jshint -W116*/ if (text == null) { qq(textEl).clearText(); } else { qq(textEl).setText(text); } } }, hideSpinner: function(id) { qq(getFile(id)).removeClass(IN_PROGRESS_CLASS); hide(getSpinner(id)); }, showSpinner: function(id) { qq(getFile(id)).addClass(IN_PROGRESS_CLASS); show(getSpinner(id)); }, generatePreview: function(id, optFileOrBlob) { if (!this.isHiddenForever(id)) { thumbGenerationQueue.push({id: id, optFileOrBlob: optFileOrBlob}); !thumbnailQueueMonitorRunning && generateNextQueuedPreview(); } }, updateThumbnail: function(id, thumbnailUrl, showWaitingImg) { if (!this.isHiddenForever(id)) { thumbGenerationQueue.push({update: true, id: id, thumbnailUrl: thumbnailUrl, showWaitingImg: showWaitingImg}); !thumbnailQueueMonitorRunning && generateNextQueuedPreview(); } }, hasDialog: function(type) { return qq.supportedFeatures.dialogElement && !!getDialog(type); }, showDialog: function(type, message, defaultValue) { var dialog = getDialog(type), messageEl = getTemplateEl(dialog, selectorClasses.dialogMessage), inputEl = dialog.getElementsByTagName("INPUT")[0], cancelBtn = getTemplateEl(dialog, selectorClasses.dialogCancelButton), okBtn = getTemplateEl(dialog, selectorClasses.dialogOkButton), promise = new qq.Promise(), closeHandler = function() { cancelBtn.removeEventListener("click", cancelClickHandler); okBtn && okBtn.removeEventListener("click", okClickHandler); promise.failure(); }, cancelClickHandler = function() { cancelBtn.removeEventListener("click", cancelClickHandler); dialog.close(); }, okClickHandler = function() { dialog.removeEventListener("close", closeHandler); okBtn.removeEventListener("click", okClickHandler); dialog.close(); promise.success(inputEl && inputEl.value); }; dialog.addEventListener("close", closeHandler); cancelBtn.addEventListener("click", cancelClickHandler); okBtn && okBtn.addEventListener("click", okClickHandler); if (inputEl) { inputEl.value = defaultValue; } messageEl.textContent = message; dialog.showModal(); return promise; } }); }; /*globals qq */ qq.azure = qq.azure || {}; qq.azure.util = qq.azure.util || (function() { "use strict"; return { AZURE_PARAM_PREFIX: "x-ms-meta-", /** Test if a request header is actually a known Azure parameter. See: https://msdn.microsoft.com/en-us/library/azure/dd179451.aspx * * @param name Name of the Request Header parameter. * @returns {Boolean} Test result. */ _paramNameMatchesAzureParameter: function(name) { switch (name) { case "Cache-Control": case "Content-Disposition": case "Content-Encoding": case "Content-MD5": case "x-ms-blob-content-encoding": case "x-ms-blob-content-disposition": case "x-ms-blob-content-md5": case "x-ms-blob-cache-control": return true; default: return false; } }, /** Create Prefixed request headers which are appropriate for Azure. * * If the request header is appropriate for Azure (e.g. Cache-Control) then it should be * passed along without a metadata prefix. For all other request header parameter names, * qq.azure.util.AZURE_PARAM_PREFIX should be prepended. * * @param name Name of the Request Header parameter to construct a (possibly) prefixed name. * @returns {String} A valid Request Header parameter name. */ _getPrefixedParamName: function(name) { if (qq.azure.util._paramNameMatchesAzureParameter(name)) { return name; } else { return qq.azure.util.AZURE_PARAM_PREFIX + name; } }, getParamsAsHeaders: function(params) { var headers = {}; qq.each(params, function(name, val) { var headerName = qq.azure.util._getPrefixedParamName(name), value = null; if (qq.isFunction(val)) { value = String(val()); } else if (qq.isObject(val)) { qq.extend(headers, qq.azure.util.getParamsAsHeaders(val)); } else { value = String(val); } if (value !== null) { if (qq.azure.util._paramNameMatchesAzureParameter(name)) { headers[headerName] = value; } else { headers[headerName] = encodeURIComponent(value); } } }); return headers; }, parseAzureError: function(responseText, log) { var domParser = new DOMParser(), responseDoc = domParser.parseFromString(responseText, "application/xml"), errorTag = responseDoc.getElementsByTagName("Error")[0], errorDetails = {}, codeTag, messageTag; log("Received error response: " + responseText, "error"); if (errorTag) { messageTag = errorTag.getElementsByTagName("Message")[0]; if (messageTag) { errorDetails.message = messageTag.textContent; } codeTag = errorTag.getElementsByTagName("Code")[0]; if (codeTag) { errorDetails.code = codeTag.textContent; } log("Parsed Azure error: " + JSON.stringify(errorDetails), "error"); return errorDetails; } } }; }()); /*globals qq*/ /** * Defines the public API for non-traditional FineUploaderBasic mode. */ (function() { "use strict"; qq.nonTraditionalBasePublicApi = { setUploadSuccessParams: function(params, id) { this._uploadSuccessParamsStore.set(params, id); }, setUploadSuccessEndpoint: function(endpoint, id) { this._uploadSuccessEndpointStore.set(endpoint, id); } }; qq.nonTraditionalBasePrivateApi = { /** * When the upload has completed, if it is successful, send a request to the `successEndpoint` (if defined). * This will hold up the call to the `onComplete` callback until we have determined success of the upload * according to the local server, if a `successEndpoint` has been defined by the integrator. * * @param id ID of the completed upload * @param name Name of the associated item * @param result Object created from the server's parsed JSON response. * @param xhr Associated XmlHttpRequest, if this was used to send the request. * @returns {boolean || qq.Promise} true/false if success can be determined immediately, otherwise a `qq.Promise` * if we need to ask the server. * @private */ _onComplete: function(id, name, result, xhr) { var success = result.success ? true : false, self = this, onCompleteArgs = arguments, successEndpoint = this._uploadSuccessEndpointStore.get(id), successCustomHeaders = this._options.uploadSuccess.customHeaders, successMethod = this._options.uploadSuccess.method, cors = this._options.cors, promise = new qq.Promise(), uploadSuccessParams = this._uploadSuccessParamsStore.get(id), fileParams = this._paramsStore.get(id), // If we are waiting for confirmation from the local server, and have received it, // include properties from the local server response in the `response` parameter // sent to the `onComplete` callback, delegate to the parent `_onComplete`, and // fulfill the associated promise. onSuccessFromServer = function(successRequestResult) { delete self._failedSuccessRequestCallbacks[id]; qq.extend(result, successRequestResult); qq.FineUploaderBasic.prototype._onComplete.apply(self, onCompleteArgs); promise.success(successRequestResult); }, // If the upload success request fails, attempt to re-send the success request (via the core retry code). // The entire upload may be restarted if the server returns a "reset" property with a value of true as well. onFailureFromServer = function(successRequestResult) { var callback = submitSuccessRequest; qq.extend(result, successRequestResult); if (result && result.reset) { callback = null; } if (!callback) { delete self._failedSuccessRequestCallbacks[id]; } else { self._failedSuccessRequestCallbacks[id] = callback; } if (!self._onAutoRetry(id, name, result, xhr, callback)) { qq.FineUploaderBasic.prototype._onComplete.apply(self, onCompleteArgs); promise.failure(successRequestResult); } }, submitSuccessRequest, successAjaxRequester; // Ask the local server if the file sent is ok. if (success && successEndpoint) { successAjaxRequester = new qq.UploadSuccessAjaxRequester({ endpoint: successEndpoint, method: successMethod, customHeaders: successCustomHeaders, cors: cors, log: qq.bind(this.log, this) }); // combine custom params and default params qq.extend(uploadSuccessParams, self._getEndpointSpecificParams(id, result, xhr), true); // include any params associated with the file fileParams && qq.extend(uploadSuccessParams, fileParams, true); submitSuccessRequest = qq.bind(function() { successAjaxRequester.sendSuccessRequest(id, uploadSuccessParams) .then(onSuccessFromServer, onFailureFromServer); }, self); submitSuccessRequest(); return promise; } // If we are not asking the local server about the file, just delegate to the parent `_onComplete`. return qq.FineUploaderBasic.prototype._onComplete.apply(this, arguments); }, // If the failure occurred on an upload success request (and a reset was not ordered), try to resend that instead. _manualRetry: function(id) { var successRequestCallback = this._failedSuccessRequestCallbacks[id]; return qq.FineUploaderBasic.prototype._manualRetry.call(this, id, successRequestCallback); } }; }()); /*globals qq */ /** * This defines FineUploaderBasic mode w/ support for uploading to Azure, which provides all the basic * functionality of Fine Uploader Basic as well as code to handle uploads directly to Azure. * Some inherited options and API methods have a special meaning in the context of the Azure uploader. */ (function() { "use strict"; qq.azure.FineUploaderBasic = function(o) { if (!qq.supportedFeatures.ajaxUploading) { throw new qq.Error("Uploading directly to Azure is not possible in this browser."); } var options = { signature: { endpoint: null, customHeaders: {} }, // 'uuid', 'filename', or a function which may be promissory blobProperties: { name: "uuid" }, uploadSuccess: { endpoint: null, method: "POST", // In addition to the default params sent by Fine Uploader params: {}, customHeaders: {} }, chunking: { // If this is increased, Azure may respond with a 413 partSize: 4000000, // Don't chunk files less than this size minFileSize: 4000001 } }; // Replace any default options with user defined ones qq.extend(options, o, true); // Call base module qq.FineUploaderBasic.call(this, options); this._uploadSuccessParamsStore = this._createStore(this._options.uploadSuccess.params); this._uploadSuccessEndpointStore = this._createStore(this._options.uploadSuccess.endpoint); // This will hold callbacks for failed uploadSuccess requests that will be invoked on retry. // Indexed by file ID. this._failedSuccessRequestCallbacks = {}; // Holds blob names for file representations constructed from a session request. this._cannedBlobNames = {}; }; // Inherit basic public & private API methods. qq.extend(qq.azure.FineUploaderBasic.prototype, qq.basePublicApi); qq.extend(qq.azure.FineUploaderBasic.prototype, qq.basePrivateApi); qq.extend(qq.azure.FineUploaderBasic.prototype, qq.nonTraditionalBasePublicApi); qq.extend(qq.azure.FineUploaderBasic.prototype, qq.nonTraditionalBasePrivateApi); // Define public & private API methods for this module. qq.extend(qq.azure.FineUploaderBasic.prototype, { getBlobName: function(id) { /* jshint eqnull:true */ if (this._cannedBlobNames[id] == null) { return this._handler.getThirdPartyFileId(id); } return this._cannedBlobNames[id]; }, _getEndpointSpecificParams: function(id) { return { blob: this.getBlobName(id), uuid: this.getUuid(id), name: this.getName(id), container: this._endpointStore.get(id) }; }, _createUploadHandler: function() { return qq.FineUploaderBasic.prototype._createUploadHandler.call(this, { signature: this._options.signature, onGetBlobName: qq.bind(this._determineBlobName, this), deleteBlob: qq.bind(this._deleteBlob, this, true) }, "azure"); }, _determineBlobName: function(id) { var self = this, blobNameOptionValue = this._options.blobProperties.name, uuid = this.getUuid(id), filename = this.getName(id), fileExtension = qq.getExtension(filename); if (qq.isString(blobNameOptionValue)) { switch (blobNameOptionValue) { case "uuid": return new qq.Promise().success(uuid + "." + fileExtension); case "filename": return new qq.Promise().success(filename); default: return new qq.Promise.failure("Invalid blobName option value - " + blobNameOptionValue); } } else { return blobNameOptionValue.call(this, id); } }, _addCannedFile: function(sessionData) { var id; /* jshint eqnull:true */ if (sessionData.blobName == null) { throw new qq.Error("Did not find blob name property in server session response. This is required!"); } else { id = qq.FineUploaderBasic.prototype._addCannedFile.apply(this, arguments); this._cannedBlobNames[id] = sessionData.blobName; } return id; }, _deleteBlob: function(relatedToCancel, id) { var self = this, deleteBlobSasUri = {}, blobUriStore = { get: function(id) { return self._endpointStore.get(id) + "/" + self.getBlobName(id); } }, deleteFileEndpointStore = { get: function(id) { return deleteBlobSasUri[id]; } }, getSasSuccess = function(id, sasUri) { deleteBlobSasUri[id] = sasUri; deleteBlob.send(id); }, getSasFailure = function(id, reason, xhr) { if (relatedToCancel) { self.log("Will cancel upload, but cannot remove uncommitted parts from Azure due to issue retrieving SAS", "error"); qq.FineUploaderBasic.prototype._onCancel.call(self, id, self.getName(id)); } else { self._onDeleteComplete(id, xhr, true); self._options.callbacks.onDeleteComplete(id, xhr, true); } }, deleteBlob = new qq.azure.DeleteBlob({ endpointStore: deleteFileEndpointStore, log: qq.bind(self.log, self), onDelete: function(id) { self._onDelete(id); self._options.callbacks.onDelete(id); }, onDeleteComplete: function(id, xhrOrXdr, isError) { delete deleteBlobSasUri[id]; if (isError) { if (relatedToCancel) { self.log("Will cancel upload, but failed to remove uncommitted parts from Azure.", "error"); } else { qq.azure.util.parseAzureError(xhrOrXdr.responseText, qq.bind(self.log, self)); } } if (relatedToCancel) { qq.FineUploaderBasic.prototype._onCancel.call(self, id, self.getName(id)); self.log("Deleted uncommitted blob chunks for " + id); } else { self._onDeleteComplete(id, xhrOrXdr, isError); self._options.callbacks.onDeleteComplete(id, xhrOrXdr, isError); } } }), getSas = new qq.azure.GetSas({ cors: this._options.cors, endpointStore: { get: function() { return self._options.signature.endpoint; } }, restRequestVerb: deleteBlob.method, log: qq.bind(self.log, self) }); getSas.request(id, blobUriStore.get(id)).then( qq.bind(getSasSuccess, self, id), qq.bind(getSasFailure, self, id)); }, _createDeleteHandler: function() { var self = this; return { sendDelete: function(id, uuid) { self._deleteBlob(false, id); } }; } }); }()); /*globals qq */ /** * Upload handler used by the upload to Azure module that depends on File API support, and, therefore, makes use of * `XMLHttpRequest` level 2 to upload `File`s and `Blob`s directly to Azure Blob Storage containers via the * associated Azure API. * * @param spec Options passed from the base handler * @param proxy Callbacks & methods used to query for or push out data/changes */ // TODO l18n for error messages returned to UI qq.azure.XhrUploadHandler = function(spec, proxy) { "use strict"; var handler = this, log = proxy.log, cors = spec.cors, endpointStore = spec.endpointStore, paramsStore = spec.paramsStore, signature = spec.signature, filenameParam = spec.filenameParam, minFileSizeForChunking = spec.chunking.minFileSize, deleteBlob = spec.deleteBlob, onGetBlobName = spec.onGetBlobName, getName = proxy.getName, getSize = proxy.getSize, getBlobMetadata = function(id) { var params = paramsStore.get(id); params[filenameParam] = getName(id); return params; }, api = { putBlob: new qq.azure.PutBlob({ getBlobMetadata: getBlobMetadata, log: log }), putBlock: new qq.azure.PutBlock({ log: log }), putBlockList: new qq.azure.PutBlockList({ getBlobMetadata: getBlobMetadata, log: log }), getSasForPutBlobOrBlock: new qq.azure.GetSas({ cors: cors, customHeaders: signature.customHeaders, endpointStore: { get: function() { return signature.endpoint; } }, log: log, restRequestVerb: "PUT" }) }; function combineChunks(id) { var promise = new qq.Promise(); getSignedUrl(id).then(function(sasUri) { var mimeType = handler._getMimeType(id), blockIdEntries = handler._getPersistableData(id).blockIdEntries; api.putBlockList.send(id, sasUri, blockIdEntries, mimeType, function(xhr) { handler._registerXhr(id, null, xhr, api.putBlockList); }) .then(function(xhr) { log("Success combining chunks for id " + id); promise.success({}, xhr); }, function(xhr) { log("Attempt to combine chunks failed for id " + id, "error"); handleFailure(xhr, promise); }); }, promise.failure); return promise; } function determineBlobUrl(id) { var containerUrl = endpointStore.get(id), promise = new qq.Promise(), getBlobNameSuccess = function(blobName) { handler._setThirdPartyFileId(id, blobName); promise.success(containerUrl + "/" + blobName); }, getBlobNameFailure = function(reason) { promise.failure(reason); }; onGetBlobName(id).then(getBlobNameSuccess, getBlobNameFailure); return promise; } function getSignedUrl(id, optChunkIdx) { // We may have multiple SAS requests in progress for the same file, so we must include the chunk idx // as part of the ID when communicating with the SAS ajax requester to avoid collisions. var getSasId = optChunkIdx == null ? id : id + "." + optChunkIdx, promise = new qq.Promise(), getSasSuccess = function(sasUri) { log("GET SAS request succeeded."); promise.success(sasUri); }, getSasFailure = function(reason, getSasXhr) { log("GET SAS request failed: " + reason, "error"); promise.failure({error: "Problem communicating with local server"}, getSasXhr); }, determineBlobUrlSuccess = function(blobUrl) { api.getSasForPutBlobOrBlock.request(getSasId, blobUrl).then( getSasSuccess, getSasFailure ); }, determineBlobUrlFailure = function(reason) { log(qq.format("Failed to determine blob name for ID {} - {}", id, reason), "error"); promise.failure({error: reason}); }; determineBlobUrl(id).then(determineBlobUrlSuccess, determineBlobUrlFailure); return promise; } function handleFailure(xhr, promise) { var azureError = qq.azure.util.parseAzureError(xhr.responseText, log), errorMsg = "Problem sending file to Azure"; promise.failure({error: errorMsg, azureError: azureError && azureError.message, reset: xhr.status === 403 }); } qq.extend(this, { uploadChunk: function(id, chunkIdx) { var promise = new qq.Promise(); getSignedUrl(id, chunkIdx).then( function(sasUri) { var xhr = handler._createXhr(id, chunkIdx), chunkData = handler._getChunkData(id, chunkIdx); handler._registerProgressHandler(id, chunkIdx, chunkData.size); handler._registerXhr(id, chunkIdx, xhr, api.putBlock); // We may have multiple put block requests in progress for the same file, so we must include the chunk idx // as part of the ID when communicating with the put block ajax requester to avoid collisions. api.putBlock.upload(id + "." + chunkIdx, xhr, sasUri, chunkIdx, chunkData.blob).then( function(blockIdEntry) { if (!handler._getPersistableData(id).blockIdEntries) { handler._getPersistableData(id).blockIdEntries = []; } handler._getPersistableData(id).blockIdEntries.push(blockIdEntry); log("Put Block call succeeded for " + id); promise.success({}, xhr); }, function() { log(qq.format("Put Block call failed for ID {} on part {}", id, chunkIdx), "error"); handleFailure(xhr, promise); } ); }, promise.failure ); return promise; }, uploadFile: function(id) { var promise = new qq.Promise(), fileOrBlob = handler.getFile(id); getSignedUrl(id).then(function(sasUri) { var xhr = handler._createXhr(id); handler._registerProgressHandler(id); api.putBlob.upload(id, xhr, sasUri, fileOrBlob).then( function() { log("Put Blob call succeeded for " + id); promise.success({}, xhr); }, function() { log("Put Blob call failed for " + id, "error"); handleFailure(xhr, promise); } ); }, promise.failure); return promise; } }); qq.extend(this, new qq.XhrUploadHandler({ options: qq.extend({namespace: "azure"}, spec), proxy: qq.extend({getEndpoint: spec.endpointStore.get}, proxy) } )); qq.override(this, function(super_) { return { expunge: function(id) { var relatedToCancel = handler._wasCanceled(id), chunkingData = handler._getPersistableData(id), blockIdEntries = (chunkingData && chunkingData.blockIdEntries) || []; if (relatedToCancel && blockIdEntries.length > 0) { deleteBlob(id); } super_.expunge(id); }, finalizeChunks: function(id) { return combineChunks(id); }, _shouldChunkThisFile: function(id) { var maybePossible = super_._shouldChunkThisFile(id); return maybePossible && getSize(id) >= minFileSizeForChunking; } }; }); }; /* globals qq */ /** * Sends a GET request to the integrator's server, which should return a Shared Access Signature URI used to * make a specific request on a Blob via the Azure REST API. */ qq.azure.GetSas = function(o) { "use strict"; var requester, options = { cors: { expected: false, sendCredentials: false }, customHeaders: {}, restRequestVerb: "PUT", endpointStore: null, log: function(str, level) {} }, requestPromises = {}; qq.extend(options, o); function sasResponseReceived(id, xhr, isError) { var promise = requestPromises[id]; if (isError) { promise.failure("Received response code " + xhr.status, xhr); } else { if (xhr.responseText.length) { promise.success(xhr.responseText); } else { promise.failure("Empty response.", xhr); } } delete requestPromises[id]; } requester = qq.extend(this, new qq.AjaxRequester({ acceptHeader: "application/json", validMethods: ["GET"], method: "GET", successfulResponseCodes: { GET: [200] }, contentType: null, customHeaders: options.customHeaders, endpointStore: options.endpointStore, cors: options.cors, log: options.log, onComplete: sasResponseReceived })); qq.extend(this, { request: function(id, blobUri) { var requestPromise = new qq.Promise(), restVerb = options.restRequestVerb; options.log(qq.format("Submitting GET SAS request for a {} REST request related to file ID {}.", restVerb, id)); requestPromises[id] = requestPromise; requester.initTransport(id) .withParams({ bloburi: blobUri, _method: restVerb }) .withCacheBuster() .send(); return requestPromise; } }); }; /*globals qq, XMLHttpRequest*/ /** * Sends a POST request to the server to notify it of a successful upload to an endpoint. The server is expected to indicate success * or failure via the response status. Specific information about the failure can be passed from the server via an `error` * property (by default) in an "application/json" response. * * @param o Options associated with all requests. * @constructor */ qq.UploadSuccessAjaxRequester = function(o) { "use strict"; var requester, pendingRequests = [], options = { method: "POST", endpoint: null, maxConnections: 3, customHeaders: {}, paramsStore: {}, cors: { expected: false, sendCredentials: false }, log: function(str, level) {} }; qq.extend(options, o); function handleSuccessResponse(id, xhrOrXdr, isError) { var promise = pendingRequests[id], responseJson = xhrOrXdr.responseText, successIndicator = {success: true}, failureIndicator = {success: false}, parsedResponse; delete pendingRequests[id]; options.log(qq.format("Received the following response body to an upload success request for id {}: {}", id, responseJson)); try { parsedResponse = qq.parseJson(responseJson); // If this is a cross-origin request, the server may return a 200 response w/ error or success properties // in order to ensure any specific error message is picked up by Fine Uploader for all browsers, // since XDomainRequest (used in IE9 and IE8) doesn't give you access to the // response body for an "error" response. if (isError || (parsedResponse && (parsedResponse.error || parsedResponse.success === false))) { options.log("Upload success request was rejected by the server.", "error"); promise.failure(qq.extend(parsedResponse, failureIndicator)); } else { options.log("Upload success was acknowledged by the server."); promise.success(qq.extend(parsedResponse, successIndicator)); } } catch (error) { // This will be executed if a JSON response is not present. This is not mandatory, so account for this properly. if (isError) { options.log(qq.format("Your server indicated failure in its upload success request response for id {}!", id), "error"); promise.failure(failureIndicator); } else { options.log("Upload success was acknowledged by the server."); promise.success(successIndicator); } } } requester = qq.extend(this, new qq.AjaxRequester({ acceptHeader: "application/json", method: options.method, endpointStore: { get: function() { return options.endpoint; } }, paramsStore: options.paramsStore, maxConnections: options.maxConnections, customHeaders: options.customHeaders, log: options.log, onComplete: handleSuccessResponse, cors: options.cors })); qq.extend(this, { /** * Sends a request to the server, notifying it that a recently submitted file was successfully sent. * * @param id ID of the associated file * @param spec `Object` with the properties that correspond to important values that we want to * send to the server with this request. * @returns {qq.Promise} A promise to be fulfilled when the response has been received and parsed. The parsed * payload of the response will be passed into the `failure` or `success` promise method. */ sendSuccessRequest: function(id, spec) { var promise = new qq.Promise(); options.log("Submitting upload success request/notification for " + id); requester.initTransport(id) .withParams(spec) .send(); pendingRequests[id] = promise; return promise; } }); }; /* globals qq */ /** * Implements the Delete Blob Azure REST API call. http://msdn.microsoft.com/en-us/library/windowsazure/dd179413.aspx. */ qq.azure.DeleteBlob = function(o) { "use strict"; var requester, method = "DELETE", options = { endpointStore: {}, onDelete: function(id) {}, onDeleteComplete: function(id, xhr, isError) {}, log: function(str, level) {} }; qq.extend(options, o); requester = qq.extend(this, new qq.AjaxRequester({ validMethods: [method], method: method, successfulResponseCodes: (function() { var codes = {}; codes[method] = [202]; return codes; }()), contentType: null, endpointStore: options.endpointStore, allowXRequestedWithAndCacheControl: false, cors: { expected: true }, log: options.log, onSend: options.onDelete, onComplete: options.onDeleteComplete })); qq.extend(this, { method: method, send: function(id) { options.log("Submitting Delete Blob request for " + id); return requester.initTransport(id) .send(); } }); }; /* globals qq */ /** * Implements the Put Blob Azure REST API call. http://msdn.microsoft.com/en-us/library/windowsazure/dd179451.aspx. */ qq.azure.PutBlob = function(o) { "use strict"; var requester, method = "PUT", options = { getBlobMetadata: function(id) {}, log: function(str, level) {} }, endpoints = {}, promises = {}, endpointHandler = { get: function(id) { return endpoints[id]; } }; qq.extend(options, o); requester = qq.extend(this, new qq.AjaxRequester({ validMethods: [method], method: method, successfulResponseCodes: (function() { var codes = {}; codes[method] = [201]; return codes; }()), contentType: null, customHeaders: function(id) { var params = options.getBlobMetadata(id), headers = qq.azure.util.getParamsAsHeaders(params); headers["x-ms-blob-type"] = "BlockBlob"; return headers; }, endpointStore: endpointHandler, allowXRequestedWithAndCacheControl: false, cors: { expected: true }, log: options.log, onComplete: function(id, xhr, isError) { var promise = promises[id]; delete endpoints[id]; delete promises[id]; if (isError) { promise.failure(); } else { promise.success(); } } })); qq.extend(this, { method: method, upload: function(id, xhr, url, file) { var promise = new qq.Promise(); options.log("Submitting Put Blob request for " + id); promises[id] = promise; endpoints[id] = url; requester.initTransport(id) .withPayload(file) .withHeaders({"Content-Type": file.type}) .send(xhr); return promise; } }); }; /* globals qq */ /** * Implements the Put Block List Azure REST API call. http://msdn.microsoft.com/en-us/library/windowsazure/dd179467.aspx. */ qq.azure.PutBlockList = function(o) { "use strict"; var requester, method = "PUT", promises = {}, options = { getBlobMetadata: function(id) {}, log: function(str, level) {} }, endpoints = {}, endpointHandler = { get: function(id) { return endpoints[id]; } }; qq.extend(options, o); requester = qq.extend(this, new qq.AjaxRequester({ validMethods: [method], method: method, successfulResponseCodes: (function() { var codes = {}; codes[method] = [201]; return codes; }()), customHeaders: function(id) { var params = options.getBlobMetadata(id); return qq.azure.util.getParamsAsHeaders(params); }, contentType: "text/plain", endpointStore: endpointHandler, allowXRequestedWithAndCacheControl: false, cors: { expected: true }, log: options.log, onSend: function() {}, onComplete: function(id, xhr, isError) { var promise = promises[id]; delete endpoints[id]; delete promises[id]; if (isError) { promise.failure(xhr); } else { promise.success(xhr); } } })); function createRequestBody(blockIdEntries) { var doc = document.implementation.createDocument(null, "BlockList", null); // If we don't sort the block ID entries by part number, the file will be combined incorrectly by Azure blockIdEntries.sort(function(a, b) { return a.part - b.part; }); // Construct an XML document for each pair of etag/part values that correspond to part uploads. qq.each(blockIdEntries, function(idx, blockIdEntry) { var latestEl = doc.createElement("Latest"), latestTextEl = doc.createTextNode(blockIdEntry.id); latestEl.appendChild(latestTextEl); qq(doc).children()[0].appendChild(latestEl); }); // Turn the resulting XML document into a string fit for transport. return new XMLSerializer().serializeToString(doc); } qq.extend(this, { method: method, send: function(id, sasUri, blockIdEntries, fileMimeType, registerXhrCallback) { var promise = new qq.Promise(), blockIdsXml = createRequestBody(blockIdEntries), xhr; promises[id] = promise; options.log(qq.format("Submitting Put Block List request for {}", id)); endpoints[id] = qq.format("{}&comp=blocklist", sasUri); xhr = requester.initTransport(id) .withPayload(blockIdsXml) .withHeaders({"x-ms-blob-content-type": fileMimeType}) .send(); registerXhrCallback(xhr); return promise; } }); }; /* globals qq */ /** * Implements the Put Block Azure REST API call. http://msdn.microsoft.com/en-us/library/windowsazure/dd135726.aspx. */ qq.azure.PutBlock = function(o) { "use strict"; var requester, method = "PUT", blockIdEntries = {}, promises = {}, options = { log: function(str, level) {} }, endpoints = {}, endpointHandler = { get: function(id) { return endpoints[id]; } }; qq.extend(options, o); requester = qq.extend(this, new qq.AjaxRequester({ validMethods: [method], method: method, successfulResponseCodes: (function() { var codes = {}; codes[method] = [201]; return codes; }()), contentType: null, endpointStore: endpointHandler, allowXRequestedWithAndCacheControl: false, cors: { expected: true }, log: options.log, onComplete: function(id, xhr, isError) { var promise = promises[id], blockIdEntry = blockIdEntries[id]; delete endpoints[id]; delete promises[id]; delete blockIdEntries[id]; if (isError) { promise.failure(); } else { promise.success(blockIdEntry); } } })); function createBlockId(partNum) { var digits = 5, zeros = new Array(digits + 1).join("0"), paddedPartNum = (zeros + partNum).slice(-digits); return btoa(paddedPartNum); } qq.extend(this, { method: method, upload: function(id, xhr, sasUri, partNum, blob) { var promise = new qq.Promise(), blockId = createBlockId(partNum); promises[id] = promise; options.log(qq.format("Submitting Put Block request for {} = part {}", id, partNum)); endpoints[id] = qq.format("{}&comp=block&blockid={}", sasUri, encodeURIComponent(blockId)); blockIdEntries[id] = {part: partNum, id: blockId}; requester.initTransport(id) .withPayload(blob) .send(xhr); return promise; } }); }; /*globals qq */ /** * This defines FineUploader mode w/ support for uploading to Azure, which provides all the basic * functionality of Fine Uploader as well as code to handle uploads directly to Azure. * This module inherits all logic from UI & core mode and adds some UI-related logic * specific to the upload-to-Azure workflow. Some inherited options and API methods have a special meaning * in the context of the Azure uploader. */ (function() { "use strict"; qq.azure.FineUploader = function(o) { var options = { failedUploadTextDisplay: { mode: "custom" } }; // Replace any default options with user defined ones qq.extend(options, o, true); // Inherit instance data from FineUploader, which should in turn inherit from azure.FineUploaderBasic. qq.FineUploader.call(this, options, "azure"); }; // Inherit the API methods from FineUploaderBasicS3 qq.extend(qq.azure.FineUploader.prototype, qq.azure.FineUploaderBasic.prototype); // Inherit public and private API methods related to UI qq.extend(qq.azure.FineUploader.prototype, qq.uiPublicApi); qq.extend(qq.azure.FineUploader.prototype, qq.uiPrivateApi); // Define public & private API methods for this module. qq.extend(qq.azure.FineUploader.prototype, { }); }()); /*globals qq*/ qq.PasteSupport = function(o) { "use strict"; var options, detachPasteHandler; options = { targetElement: null, callbacks: { log: function(message, level) {}, pasteReceived: function(blob) {} } }; function isImage(item) { return item.type && item.type.indexOf("image/") === 0; } function registerPasteHandler() { detachPasteHandler = qq(options.targetElement).attach("paste", function(event) { var clipboardData = event.clipboardData; if (clipboardData) { qq.each(clipboardData.items, function(idx, item) { if (isImage(item)) { var blob = item.getAsFile(); options.callbacks.pasteReceived(blob); } }); } }); } function unregisterPasteHandler() { if (detachPasteHandler) { detachPasteHandler(); } } qq.extend(options, o); registerPasteHandler(); qq.extend(this, { reset: function() { unregisterPasteHandler(); } }); }; /*globals qq, document, CustomEvent*/ qq.DragAndDrop = function(o) { "use strict"; var options, HIDE_ZONES_EVENT_NAME = "qq-hidezones", HIDE_BEFORE_ENTER_ATTR = "qq-hide-dropzone", uploadDropZones = [], droppedFiles = [], disposeSupport = new qq.DisposeSupport(); options = { dropZoneElements: [], allowMultipleItems: true, classes: { dropActive: null }, callbacks: new qq.DragAndDrop.callbacks() }; qq.extend(options, o, true); function uploadDroppedFiles(files, uploadDropZone) { // We need to convert the `FileList` to an actual `Array` to avoid iteration issues var filesAsArray = Array.prototype.slice.call(files); options.callbacks.dropLog("Grabbed " + files.length + " dropped files."); uploadDropZone.dropDisabled(false); options.callbacks.processingDroppedFilesComplete(filesAsArray, uploadDropZone.getElement()); } function traverseFileTree(entry) { var parseEntryPromise = new qq.Promise(); if (entry.isFile) { entry.file(function(file) { var name = entry.name, fullPath = entry.fullPath, indexOfNameInFullPath = fullPath.indexOf(name); // remove file name from full path string fullPath = fullPath.substr(0, indexOfNameInFullPath); // remove leading slash in full path string if (fullPath.charAt(0) === "/") { fullPath = fullPath.substr(1); } file.qqPath = fullPath; droppedFiles.push(file); parseEntryPromise.success(); }, function(fileError) { options.callbacks.dropLog("Problem parsing '" + entry.fullPath + "'. FileError code " + fileError.code + ".", "error"); parseEntryPromise.failure(); }); } else if (entry.isDirectory) { getFilesInDirectory(entry).then( function allEntriesRead(entries) { var entriesLeft = entries.length; qq.each(entries, function(idx, entry) { traverseFileTree(entry).done(function() { entriesLeft -= 1; if (entriesLeft === 0) { parseEntryPromise.success(); } }); }); if (!entries.length) { parseEntryPromise.success(); } }, function readFailure(fileError) { options.callbacks.dropLog("Problem parsing '" + entry.fullPath + "'. FileError code " + fileError.code + ".", "error"); parseEntryPromise.failure(); } ); } return parseEntryPromise; } // Promissory. Guaranteed to read all files in the root of the passed directory. function getFilesInDirectory(entry, reader, accumEntries, existingPromise) { var promise = existingPromise || new qq.Promise(), dirReader = reader || entry.createReader(); dirReader.readEntries( function readSuccess(entries) { var newEntries = accumEntries ? accumEntries.concat(entries) : entries; if (entries.length) { setTimeout(function() { // prevent stack oveflow, however unlikely getFilesInDirectory(entry, dirReader, newEntries, promise); }, 0); } else { promise.success(newEntries); } }, promise.failure ); return promise; } function handleDataTransfer(dataTransfer, uploadDropZone) { var pendingFolderPromises = [], handleDataTransferPromise = new qq.Promise(); options.callbacks.processingDroppedFiles(); uploadDropZone.dropDisabled(true); if (dataTransfer.files.length > 1 && !options.allowMultipleItems) { options.callbacks.processingDroppedFilesComplete([]); options.callbacks.dropError("tooManyFilesError", ""); uploadDropZone.dropDisabled(false); handleDataTransferPromise.failure(); } else { droppedFiles = []; if (qq.isFolderDropSupported(dataTransfer)) { qq.each(dataTransfer.items, function(idx, item) { var entry = item.webkitGetAsEntry(); if (entry) { //due to a bug in Chrome's File System API impl - #149735 if (entry.isFile) { droppedFiles.push(item.getAsFile()); } else { pendingFolderPromises.push(traverseFileTree(entry).done(function() { pendingFolderPromises.pop(); if (pendingFolderPromises.length === 0) { handleDataTransferPromise.success(); } })); } } }); } else { droppedFiles = dataTransfer.files; } if (pendingFolderPromises.length === 0) { handleDataTransferPromise.success(); } } return handleDataTransferPromise; } function setupDropzone(dropArea) { var dropZone = new qq.UploadDropZone({ HIDE_ZONES_EVENT_NAME: HIDE_ZONES_EVENT_NAME, element: dropArea, onEnter: function(e) { qq(dropArea).addClass(options.classes.dropActive); e.stopPropagation(); }, onLeaveNotDescendants: function(e) { qq(dropArea).removeClass(options.classes.dropActive); }, onDrop: function(e) { handleDataTransfer(e.dataTransfer, dropZone).then( function() { uploadDroppedFiles(droppedFiles, dropZone); }, function() { options.callbacks.dropLog("Drop event DataTransfer parsing failed. No files will be uploaded.", "error"); } ); } }); disposeSupport.addDisposer(function() { dropZone.dispose(); }); qq(dropArea).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropArea).hide(); uploadDropZones.push(dropZone); return dropZone; } function isFileDrag(dragEvent) { var fileDrag; qq.each(dragEvent.dataTransfer.types, function(key, val) { if (val === "Files") { fileDrag = true; return false; } }); return fileDrag; } // Attempt to determine when the file has left the document. It is not always possible to detect this // in all cases, but it is generally possible in all browsers, with a few exceptions. // // Exceptions: // * IE10+ & Safari: We can't detect a file leaving the document if the Explorer window housing the file // overlays the browser window. // * IE10+: If the file is dragged out of the window too quickly, IE does not set the expected values of the // event's X & Y properties. function leavingDocumentOut(e) { if (qq.firefox()) { return !e.relatedTarget; } if (qq.safari()) { return e.x < 0 || e.y < 0; } return e.x === 0 && e.y === 0; } function setupDragDrop() { var dropZones = options.dropZoneElements, maybeHideDropZones = function() { setTimeout(function() { qq.each(dropZones, function(idx, dropZone) { qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropZone).hide(); qq(dropZone).removeClass(options.classes.dropActive); }); }, 10); }; qq.each(dropZones, function(idx, dropZone) { var uploadDropZone = setupDropzone(dropZone); // IE <= 9 does not support the File API used for drag+drop uploads if (dropZones.length && qq.supportedFeatures.fileDrop) { disposeSupport.attach(document, "dragenter", function(e) { if (!uploadDropZone.dropDisabled() && isFileDrag(e)) { qq.each(dropZones, function(idx, dropZone) { // We can't apply styles to non-HTMLElements, since they lack the `style` property. // Also, if the drop zone isn't initially hidden, let's not mess with `style.display`. if (dropZone instanceof HTMLElement && qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR)) { qq(dropZone).css({display: "block"}); } }); } }); } }); disposeSupport.attach(document, "dragleave", function(e) { if (leavingDocumentOut(e)) { maybeHideDropZones(); } }); // Just in case we were not able to detect when a dragged file has left the document, // hide all relevant drop zones the next time the mouse enters the document. // Note that mouse events such as this one are not fired during drag operations. disposeSupport.attach(qq(document).children()[0], "mouseenter", function(e) { maybeHideDropZones(); }); disposeSupport.attach(document, "drop", function(e) { e.preventDefault(); maybeHideDropZones(); }); disposeSupport.attach(document, HIDE_ZONES_EVENT_NAME, maybeHideDropZones); } setupDragDrop(); qq.extend(this, { setupExtraDropzone: function(element) { options.dropZoneElements.push(element); setupDropzone(element); }, removeDropzone: function(element) { var i, dzs = options.dropZoneElements; for (i in dzs) { if (dzs[i] === element) { return dzs.splice(i, 1); } } }, dispose: function() { disposeSupport.dispose(); qq.each(uploadDropZones, function(idx, dropZone) { dropZone.dispose(); }); } }); }; qq.DragAndDrop.callbacks = function() { "use strict"; return { processingDroppedFiles: function() {}, processingDroppedFilesComplete: function(files, targetEl) {}, dropError: function(code, errorSpecifics) { qq.log("Drag & drop error code '" + code + " with these specifics: '" + errorSpecifics + "'", "error"); }, dropLog: function(message, level) { qq.log(message, level); } }; }; qq.UploadDropZone = function(o) { "use strict"; var disposeSupport = new qq.DisposeSupport(), options, element, preventDrop, dropOutsideDisabled; options = { element: null, onEnter: function(e) {}, onLeave: function(e) {}, // is not fired when leaving element by hovering descendants onLeaveNotDescendants: function(e) {}, onDrop: function(e) {} }; qq.extend(options, o); element = options.element; function dragoverShouldBeCanceled() { return qq.safari() || (qq.firefox() && qq.windows()); } function disableDropOutside(e) { // run only once for all instances if (!dropOutsideDisabled) { // for these cases we need to catch onDrop to reset dropArea if (dragoverShouldBeCanceled) { disposeSupport.attach(document, "dragover", function(e) { e.preventDefault(); }); } else { disposeSupport.attach(document, "dragover", function(e) { if (e.dataTransfer) { e.dataTransfer.dropEffect = "none"; e.preventDefault(); } }); } dropOutsideDisabled = true; } } function isValidFileDrag(e) { // e.dataTransfer currently causing IE errors // IE9 does NOT support file API, so drag-and-drop is not possible if (!qq.supportedFeatures.fileDrop) { return false; } var effectTest, dt = e.dataTransfer, // do not check dt.types.contains in webkit, because it crashes safari 4 isSafari = qq.safari(); // dt.effectAllowed is none in Safari 5 // dt.types.contains check is for firefox // dt.effectAllowed crashes IE 11 & 10 when files have been dragged from // the filesystem effectTest = qq.ie() && qq.supportedFeatures.fileDrop ? true : dt.effectAllowed !== "none"; return dt && effectTest && (dt.files || (!isSafari && dt.types.contains && dt.types.contains("Files"))); } function isOrSetDropDisabled(isDisabled) { if (isDisabled !== undefined) { preventDrop = isDisabled; } return preventDrop; } function triggerHidezonesEvent() { var hideZonesEvent; function triggerUsingOldApi() { hideZonesEvent = document.createEvent("Event"); hideZonesEvent.initEvent(options.HIDE_ZONES_EVENT_NAME, true, true); } if (window.CustomEvent) { try { hideZonesEvent = new CustomEvent(options.HIDE_ZONES_EVENT_NAME); } catch (err) { triggerUsingOldApi(); } } else { triggerUsingOldApi(); } document.dispatchEvent(hideZonesEvent); } function attachEvents() { disposeSupport.attach(element, "dragover", function(e) { if (!isValidFileDrag(e)) { return; } // dt.effectAllowed crashes IE 11 & 10 when files have been dragged from // the filesystem var effect = qq.ie() && qq.supportedFeatures.fileDrop ? null : e.dataTransfer.effectAllowed; if (effect === "move" || effect === "linkMove") { e.dataTransfer.dropEffect = "move"; // for FF (only move allowed) } else { e.dataTransfer.dropEffect = "copy"; // for Chrome } e.stopPropagation(); e.preventDefault(); }); disposeSupport.attach(element, "dragenter", function(e) { if (!isOrSetDropDisabled()) { if (!isValidFileDrag(e)) { return; } options.onEnter(e); } }); disposeSupport.attach(element, "dragleave", function(e) { if (!isValidFileDrag(e)) { return; } options.onLeave(e); var relatedTarget = document.elementFromPoint(e.clientX, e.clientY); // do not fire when moving a mouse over a descendant if (qq(this).contains(relatedTarget)) { return; } options.onLeaveNotDescendants(e); }); disposeSupport.attach(element, "drop", function(e) { if (!isOrSetDropDisabled()) { if (!isValidFileDrag(e)) { return; } e.preventDefault(); e.stopPropagation(); options.onDrop(e); triggerHidezonesEvent(); } }); } disableDropOutside(); attachEvents(); qq.extend(this, { dropDisabled: function(isDisabled) { return isOrSetDropDisabled(isDisabled); }, dispose: function() { disposeSupport.dispose(); }, getElement: function() { return element; } }); }; /*globals qq, XMLHttpRequest*/ qq.DeleteFileAjaxRequester = function(o) { "use strict"; var requester, options = { method: "DELETE", uuidParamName: "qquuid", endpointStore: {}, maxConnections: 3, customHeaders: function(id) {return {};}, paramsStore: {}, cors: { expected: false, sendCredentials: false }, log: function(str, level) {}, onDelete: function(id) {}, onDeleteComplete: function(id, xhrOrXdr, isError) {} }; qq.extend(options, o); function getMandatedParams() { if (options.method.toUpperCase() === "POST") { return { _method: "DELETE" }; } return {}; } requester = qq.extend(this, new qq.AjaxRequester({ acceptHeader: "application/json", validMethods: ["POST", "DELETE"], method: options.method, endpointStore: options.endpointStore, paramsStore: options.paramsStore, mandatedParams: getMandatedParams(), maxConnections: options.maxConnections, customHeaders: function(id) { return options.customHeaders.get(id); }, log: options.log, onSend: options.onDelete, onComplete: options.onDeleteComplete, cors: options.cors })); qq.extend(this, { sendDelete: function(id, uuid, additionalMandatedParams) { var additionalOptions = additionalMandatedParams || {}; options.log("Submitting delete file request for " + id); if (options.method === "DELETE") { requester.initTransport(id) .withPath(uuid) .withParams(additionalOptions) .send(); } else { additionalOptions[options.uuidParamName] = uuid; requester.initTransport(id) .withParams(additionalOptions) .send(); } } }); }; /*global qq, define */ /*jshint strict:false,bitwise:false,nonew:false,asi:true,-W064,-W116,-W089 */ /** * Mega pixel image rendering library for iOS6+ * * Fixes iOS6+'s image file rendering issue for large size image (over mega-pixel), * which causes unexpected subsampling when drawing it in canvas. * By using this library, you can safely render the image with proper stretching. * * Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.com> * Released under the MIT license * * Heavily modified by Widen for Fine Uploader */ (function() { /** * Detect subsampling in loaded image. * In iOS, larger images than 2M pixels may be subsampled in rendering. */ function detectSubsampling(img) { var iw = img.naturalWidth, ih = img.naturalHeight, canvas = document.createElement("canvas"), ctx; if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image canvas.width = canvas.height = 1; ctx = canvas.getContext("2d"); ctx.drawImage(img, -iw + 1, 0); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering edge pixel or not. // if alpha value is 0 image is not covering, hence subsampled. return ctx.getImageData(0, 0, 1, 1).data[3] === 0; } else { return false; } } /** * Detecting vertical squash in loaded image. * Fixes a bug which squash image vertically while drawing into canvas for some images. */ function detectVerticalSquash(img, iw, ih) { var canvas = document.createElement("canvas"), sy = 0, ey = ih, py = ih, ctx, data, alpha, ratio; canvas.width = 1; canvas.height = ih; ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); data = ctx.getImageData(0, 0, 1, ih).data; // search image edge pixel position in case it is squashed vertically. while (py > sy) { alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } ratio = (py / ih); return (ratio === 0) ? 1 : ratio; } /** * Rendering image element (with resizing) and get its data URL */ function renderImageToDataURL(img, options, doSquash) { var canvas = document.createElement("canvas"), mime = options.mime || "image/jpeg"; renderImageToCanvas(img, canvas, options, doSquash); return canvas.toDataURL(mime, options.quality || 0.8); } function maybeCalculateDownsampledDimensions(spec) { var maxPixels = 5241000; //iOS specific value if (!qq.ios()) { throw new qq.Error("Downsampled dimensions can only be reliably calculated for iOS!"); } if (spec.origHeight * spec.origWidth > maxPixels) { return { newHeight: Math.round(Math.sqrt(maxPixels * (spec.origHeight / spec.origWidth))), newWidth: Math.round(Math.sqrt(maxPixels * (spec.origWidth / spec.origHeight))) } } } /** * Rendering image element (with resizing) into the canvas element */ function renderImageToCanvas(img, canvas, options, doSquash) { var iw = img.naturalWidth, ih = img.naturalHeight, width = options.width, height = options.height, ctx = canvas.getContext("2d"), modifiedDimensions; ctx.save(); if (!qq.supportedFeatures.unlimitedScaledImageSize) { modifiedDimensions = maybeCalculateDownsampledDimensions({ origWidth: width, origHeight: height }); if (modifiedDimensions) { qq.log(qq.format("Had to reduce dimensions due to device limitations from {}w / {}h to {}w / {}h", width, height, modifiedDimensions.newWidth, modifiedDimensions.newHeight), "warn"); width = modifiedDimensions.newWidth; height = modifiedDimensions.newHeight; } } transformCoordinate(canvas, width, height, options.orientation); // Fine Uploader specific: Save some CPU cycles if not using iOS // Assumption: This logic is only needed to overcome iOS image sampling issues if (qq.ios()) { (function() { if (detectSubsampling(img)) { iw /= 2; ih /= 2; } var d = 1024, // size of tiling canvas tmpCanvas = document.createElement("canvas"), vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1, dw = Math.ceil(d * width / iw), dh = Math.ceil(d * height / ih / vertSquashRatio), sy = 0, dy = 0, tmpCtx, sx, dx; tmpCanvas.width = tmpCanvas.height = d; tmpCtx = tmpCanvas.getContext("2d"); while (sy < ih) { sx = 0, dx = 0; while (sx < iw) { tmpCtx.clearRect(0, 0, d, d); tmpCtx.drawImage(img, -sx, -sy); ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh); sx += d; dx += dw; } sy += d; dy += dh; } ctx.restore(); tmpCanvas = tmpCtx = null; }()) } else { ctx.drawImage(img, 0, 0, width, height); } canvas.qqImageRendered && canvas.qqImageRendered(); } /** * Transform canvas coordination according to specified frame size and orientation * Orientation value is from EXIF tag */ function transformCoordinate(canvas, width, height, orientation) { switch (orientation) { case 5: case 6: case 7: case 8: canvas.width = height; canvas.height = width; break; default: canvas.width = width; canvas.height = height; } var ctx = canvas.getContext("2d"); switch (orientation) { case 2: // horizontal flip ctx.translate(width, 0); ctx.scale(-1, 1); break; case 3: // 180 rotate left ctx.translate(width, height); ctx.rotate(Math.PI); break; case 4: // vertical flip ctx.translate(0, height); ctx.scale(1, -1); break; case 5: // vertical flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.scale(1, -1); break; case 6: // 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(0, -height); break; case 7: // horizontal flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(width, -height); ctx.scale(-1, 1); break; case 8: // 90 rotate left ctx.rotate(-0.5 * Math.PI); ctx.translate(-width, 0); break; default: break; } } /** * MegaPixImage class */ function MegaPixImage(srcImage, errorCallback) { var self = this; if (window.Blob && srcImage instanceof Blob) { (function() { var img = new Image(), URL = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null; if (!URL) { throw Error("No createObjectURL function found to create blob url"); } img.src = URL.createObjectURL(srcImage); self.blob = srcImage; srcImage = img; }()); } if (!srcImage.naturalWidth && !srcImage.naturalHeight) { srcImage.onload = function() { var listeners = self.imageLoadListeners; if (listeners) { self.imageLoadListeners = null; // IE11 doesn't reliably report actual image dimensions immediately after onload for small files, // so let's push this to the end of the UI thread queue. setTimeout(function() { for (var i = 0, len = listeners.length; i < len; i++) { listeners[i](); } }, 0); } }; srcImage.onerror = errorCallback; this.imageLoadListeners = []; } this.srcImage = srcImage; } /** * Rendering megapix image into specified target element */ MegaPixImage.prototype.render = function(target, options) { options = options || {}; var self = this, imgWidth = this.srcImage.naturalWidth, imgHeight = this.srcImage.naturalHeight, width = options.width, height = options.height, maxWidth = options.maxWidth, maxHeight = options.maxHeight, doSquash = !this.blob || this.blob.type === "image/jpeg", tagName = target.tagName.toLowerCase(), opt; if (this.imageLoadListeners) { this.imageLoadListeners.push(function() { self.render(target, options) }); return; } if (width && !height) { height = (imgHeight * width / imgWidth) << 0; } else if (height && !width) { width = (imgWidth * height / imgHeight) << 0; } else { width = imgWidth; height = imgHeight; } if (maxWidth && width > maxWidth) { width = maxWidth; height = (imgHeight * width / imgWidth) << 0; } if (maxHeight && height > maxHeight) { height = maxHeight; width = (imgWidth * height / imgHeight) << 0; } opt = { width: width, height: height }, qq.each(options, function(optionsKey, optionsValue) { opt[optionsKey] = optionsValue; }); if (tagName === "img") { (function() { var oldTargetSrc = target.src; target.src = renderImageToDataURL(self.srcImage, opt, doSquash); oldTargetSrc === target.src && target.onload(); }()) } else if (tagName === "canvas") { renderImageToCanvas(this.srcImage, target, opt, doSquash); } if (typeof this.onrender === "function") { this.onrender(target); } }; qq.MegaPixImage = MegaPixImage; })(); /*globals qq */ /** * Draws a thumbnail of a Blob/File/URL onto an <img> or <canvas>. * * @constructor */ qq.ImageGenerator = function(log) { "use strict"; function isImg(el) { return el.tagName.toLowerCase() === "img"; } function isCanvas(el) { return el.tagName.toLowerCase() === "canvas"; } function isImgCorsSupported() { return new Image().crossOrigin !== undefined; } function isCanvasSupported() { var canvas = document.createElement("canvas"); return canvas.getContext && canvas.getContext("2d"); } // This is only meant to determine the MIME type of a renderable image file. // It is used to ensure images drawn from a URL that have transparent backgrounds // are rendered correctly, among other things. function determineMimeOfFileName(nameWithPath) { /*jshint -W015 */ var pathSegments = nameWithPath.split("/"), name = pathSegments[pathSegments.length - 1], extension = qq.getExtension(name); extension = extension && extension.toLowerCase(); switch (extension) { case "jpeg": case "jpg": return "image/jpeg"; case "png": return "image/png"; case "bmp": return "image/bmp"; case "gif": return "image/gif"; case "tiff": case "tif": return "image/tiff"; } } // This will likely not work correctly in IE8 and older. // It's only used as part of a formula to determine // if a canvas can be used to scale a server-hosted thumbnail. // If canvas isn't supported by the UA (IE8 and older) // this method should not even be called. function isCrossOrigin(url) { var targetAnchor = document.createElement("a"), targetProtocol, targetHostname, targetPort; targetAnchor.href = url; targetProtocol = targetAnchor.protocol; targetPort = targetAnchor.port; targetHostname = targetAnchor.hostname; if (targetProtocol.toLowerCase() !== window.location.protocol.toLowerCase()) { return true; } if (targetHostname.toLowerCase() !== window.location.hostname.toLowerCase()) { return true; } // IE doesn't take ports into consideration when determining if two endpoints are same origin. if (targetPort !== window.location.port && !qq.ie()) { return true; } return false; } function registerImgLoadListeners(img, promise) { img.onload = function() { img.onload = null; img.onerror = null; promise.success(img); }; img.onerror = function() { img.onload = null; img.onerror = null; log("Problem drawing thumbnail!", "error"); promise.failure(img, "Problem drawing thumbnail!"); }; } function registerCanvasDrawImageListener(canvas, promise) { // The image is drawn on the canvas by a third-party library, // and we want to know when this is completed. Since the library // may invoke drawImage many times in a loop, we need to be called // back when the image is fully rendered. So, we are expecting the // code that draws this image to follow a convention that involves a // function attached to the canvas instance be invoked when it is done. canvas.qqImageRendered = function() { promise.success(canvas); }; } // Fulfills a `qq.Promise` when an image has been drawn onto the target, // whether that is a <canvas> or an <img>. The attempt is considered a // failure if the target is not an <img> or a <canvas>, or if the drawing // attempt was not successful. function registerThumbnailRenderedListener(imgOrCanvas, promise) { var registered = isImg(imgOrCanvas) || isCanvas(imgOrCanvas); if (isImg(imgOrCanvas)) { registerImgLoadListeners(imgOrCanvas, promise); } else if (isCanvas(imgOrCanvas)) { registerCanvasDrawImageListener(imgOrCanvas, promise); } else { promise.failure(imgOrCanvas); log(qq.format("Element container of type {} is not supported!", imgOrCanvas.tagName), "error"); } return registered; } // Draw a preview iff the current UA can natively display it. // Also rotate the image if necessary. function draw(fileOrBlob, container, options) { var drawPreview = new qq.Promise(), identifier = new qq.Identify(fileOrBlob, log), maxSize = options.maxSize, // jshint eqnull:true orient = options.orient == null ? true : options.orient, megapixErrorHandler = function() { container.onerror = null; container.onload = null; log("Could not render preview, file may be too large!", "error"); drawPreview.failure(container, "Browser cannot render image!"); }; identifier.isPreviewable().then( function(mime) { // If options explicitly specify that Orientation is not desired, // replace the orient task with a dummy promise that "succeeds" immediately. var dummyExif = { parse: function() { return new qq.Promise().success(); } }, exif = orient ? new qq.Exif(fileOrBlob, log) : dummyExif, mpImg = new qq.MegaPixImage(fileOrBlob, megapixErrorHandler); if (registerThumbnailRenderedListener(container, drawPreview)) { exif.parse().then( function(exif) { var orientation = exif && exif.Orientation; mpImg.render(container, { maxWidth: maxSize, maxHeight: maxSize, orientation: orientation, mime: mime }); }, function(failureMsg) { log(qq.format("EXIF data could not be parsed ({}). Assuming orientation = 1.", failureMsg)); mpImg.render(container, { maxWidth: maxSize, maxHeight: maxSize, mime: mime }); } ); } }, function() { log("Not previewable"); drawPreview.failure(container, "Not previewable"); } ); return drawPreview; } function drawOnCanvasOrImgFromUrl(url, canvasOrImg, draw, maxSize) { var tempImg = new Image(), tempImgRender = new qq.Promise(); registerThumbnailRenderedListener(tempImg, tempImgRender); if (isCrossOrigin(url)) { tempImg.crossOrigin = "anonymous"; } tempImg.src = url; tempImgRender.then( function rendered() { registerThumbnailRenderedListener(canvasOrImg, draw); var mpImg = new qq.MegaPixImage(tempImg); mpImg.render(canvasOrImg, { maxWidth: maxSize, maxHeight: maxSize, mime: determineMimeOfFileName(url) }); }, draw.failure ); } function drawOnImgFromUrlWithCssScaling(url, img, draw, maxSize) { registerThumbnailRenderedListener(img, draw); // NOTE: The fact that maxWidth/height is set on the thumbnail for scaled images // that must drop back to CSS is known and exploited by the templating module. // In this module, we pre-render "waiting" thumbs for all files immediately after they // are submitted, and we must be sure to pass any style associated with the "waiting" preview. qq(img).css({ maxWidth: maxSize + "px", maxHeight: maxSize + "px" }); img.src = url; } // Draw a (server-hosted) thumbnail given a URL. // This will optionally scale the thumbnail as well. // It attempts to use <canvas> to scale, but will fall back // to max-width and max-height style properties if the UA // doesn't support canvas or if the images is cross-domain and // the UA doesn't support the crossorigin attribute on img tags, // which is required to scale a cross-origin image using <canvas> & // then export it back to an <img>. function drawFromUrl(url, container, options) { var draw = new qq.Promise(), scale = options.scale, maxSize = scale ? options.maxSize : null; // container is an img, scaling needed if (scale && isImg(container)) { // Iff canvas is available in this UA, try to use it for scaling. // Otherwise, fall back to CSS scaling if (isCanvasSupported()) { // Attempt to use <canvas> for image scaling, // but we must fall back to scaling via CSS/styles // if this is a cross-origin image and the UA doesn't support <img> CORS. if (isCrossOrigin(url) && !isImgCorsSupported()) { drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize); } else { drawOnCanvasOrImgFromUrl(url, container, draw, maxSize); } } else { drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize); } } // container is a canvas, scaling optional else if (isCanvas(container)) { drawOnCanvasOrImgFromUrl(url, container, draw, maxSize); } // container is an img & no scaling: just set the src attr to the passed url else if (registerThumbnailRenderedListener(container, draw)) { container.src = url; } return draw; } qq.extend(this, { /** * Generate a thumbnail. Depending on the arguments, this may either result in * a client-side rendering of an image (if a `Blob` is supplied) or a server-generated * image that may optionally be scaled client-side using <canvas> or CSS/styles (as a fallback). * * @param fileBlobOrUrl a `File`, `Blob`, or a URL pointing to the image * @param container <img> or <canvas> to contain the preview * @param options possible properties include `maxSize` (int), `orient` (bool - default true), and `resize` (bool - default true) * @returns qq.Promise fulfilled when the preview has been drawn, or the attempt has failed */ generate: function(fileBlobOrUrl, container, options) { if (qq.isString(fileBlobOrUrl)) { log("Attempting to update thumbnail based on server response."); return drawFromUrl(fileBlobOrUrl, container, options || {}); } else { log("Attempting to draw client-side image preview."); return draw(fileBlobOrUrl, container, options || {}); } } }); }; /*globals qq */ /** * EXIF image data parser. Currently only parses the Orientation tag value, * but this may be expanded to other tags in the future. * * @param fileOrBlob Attempt to parse EXIF data in this `Blob` * @constructor */ qq.Exif = function(fileOrBlob, log) { "use strict"; // Orientation is the only tag parsed here at this time. var TAG_IDS = [274], TAG_INFO = { 274: { name: "Orientation", bytes: 2 } }; // Convert a little endian (hex string) to big endian (decimal). function parseLittleEndian(hex) { var result = 0, pow = 0; while (hex.length > 0) { result += parseInt(hex.substring(0, 2), 16) * Math.pow(2, pow); hex = hex.substring(2, hex.length); pow += 8; } return result; } // Find the byte offset, of Application Segment 1 (EXIF). // External callers need not supply any arguments. function seekToApp1(offset, promise) { var theOffset = offset, thePromise = promise; if (theOffset === undefined) { theOffset = 2; thePromise = new qq.Promise(); } qq.readBlobToHex(fileOrBlob, theOffset, 4).then(function(hex) { var match = /^ffe([0-9])/.exec(hex), segmentLength; if (match) { if (match[1] !== "1") { segmentLength = parseInt(hex.slice(4, 8), 16); seekToApp1(theOffset + segmentLength + 2, thePromise); } else { thePromise.success(theOffset); } } else { thePromise.failure("No EXIF header to be found!"); } }); return thePromise; } // Find the byte offset of Application Segment 1 (EXIF) for valid JPEGs only. function getApp1Offset() { var promise = new qq.Promise(); qq.readBlobToHex(fileOrBlob, 0, 6).then(function(hex) { if (hex.indexOf("ffd8") !== 0) { promise.failure("Not a valid JPEG!"); } else { seekToApp1().then(function(offset) { promise.success(offset); }, function(error) { promise.failure(error); }); } }); return promise; } // Determine the byte ordering of the EXIF header. function isLittleEndian(app1Start) { var promise = new qq.Promise(); qq.readBlobToHex(fileOrBlob, app1Start + 10, 2).then(function(hex) { promise.success(hex === "4949"); }); return promise; } // Determine the number of directory entries in the EXIF header. function getDirEntryCount(app1Start, littleEndian) { var promise = new qq.Promise(); qq.readBlobToHex(fileOrBlob, app1Start + 18, 2).then(function(hex) { if (littleEndian) { return promise.success(parseLittleEndian(hex)); } else { promise.success(parseInt(hex, 16)); } }); return promise; } // Get the IFD portion of the EXIF header as a hex string. function getIfd(app1Start, dirEntries) { var offset = app1Start + 20, bytes = dirEntries * 12; return qq.readBlobToHex(fileOrBlob, offset, bytes); } // Obtain an array of all directory entries (as hex strings) in the EXIF header. function getDirEntries(ifdHex) { var entries = [], offset = 0; while (offset + 24 <= ifdHex.length) { entries.push(ifdHex.slice(offset, offset + 24)); offset += 24; } return entries; } // Obtain values for all relevant tags and return them. function getTagValues(littleEndian, dirEntries) { var TAG_VAL_OFFSET = 16, tagsToFind = qq.extend([], TAG_IDS), vals = {}; qq.each(dirEntries, function(idx, entry) { var idHex = entry.slice(0, 4), id = littleEndian ? parseLittleEndian(idHex) : parseInt(idHex, 16), tagsToFindIdx = tagsToFind.indexOf(id), tagValHex, tagName, tagValLength; if (tagsToFindIdx >= 0) { tagName = TAG_INFO[id].name; tagValLength = TAG_INFO[id].bytes; tagValHex = entry.slice(TAG_VAL_OFFSET, TAG_VAL_OFFSET + (tagValLength * 2)); vals[tagName] = littleEndian ? parseLittleEndian(tagValHex) : parseInt(tagValHex, 16); tagsToFind.splice(tagsToFindIdx, 1); } if (tagsToFind.length === 0) { return false; } }); return vals; } qq.extend(this, { /** * Attempt to parse the EXIF header for the `Blob` associated with this instance. * * @returns {qq.Promise} To be fulfilled when the parsing is complete. * If successful, the parsed EXIF header as an object will be included. */ parse: function() { var parser = new qq.Promise(), onParseFailure = function(message) { log(qq.format("EXIF header parse failed: '{}' ", message)); parser.failure(message); }; getApp1Offset().then(function(app1Offset) { log(qq.format("Moving forward with EXIF header parsing for '{}'", fileOrBlob.name === undefined ? "blob" : fileOrBlob.name)); isLittleEndian(app1Offset).then(function(littleEndian) { log(qq.format("EXIF Byte order is {} endian", littleEndian ? "little" : "big")); getDirEntryCount(app1Offset, littleEndian).then(function(dirEntryCount) { log(qq.format("Found {} APP1 directory entries", dirEntryCount)); getIfd(app1Offset, dirEntryCount).then(function(ifdHex) { var dirEntries = getDirEntries(ifdHex), tagValues = getTagValues(littleEndian, dirEntries); log("Successfully parsed some EXIF tags"); parser.success(tagValues); }, onParseFailure); }, onParseFailure); }, onParseFailure); }, onParseFailure); return parser; } }); }; /*globals qq */ qq.Identify = function(fileOrBlob, log) { "use strict"; function isIdentifiable(magicBytes, questionableBytes) { var identifiable = false, magicBytesEntries = [].concat(magicBytes); qq.each(magicBytesEntries, function(idx, magicBytesArrayEntry) { if (questionableBytes.indexOf(magicBytesArrayEntry) === 0) { identifiable = true; return false; } }); return identifiable; } qq.extend(this, { /** * Determines if a Blob can be displayed natively in the current browser. This is done by reading magic * bytes in the beginning of the file, so this is an asynchronous operation. Before we attempt to read the * file, we will examine the blob's type attribute to save CPU cycles. * * @returns {qq.Promise} Promise that is fulfilled when identification is complete. * If successful, the MIME string is passed to the success handler. */ isPreviewable: function() { var self = this, idenitifer = new qq.Promise(), previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name; log(qq.format("Attempting to determine if {} can be rendered in this browser", name)); log("First pass: check type attribute of blob object."); if (this.isPreviewableSync()) { log("Second pass: check for magic bytes in file header."); qq.readBlobToHex(fileOrBlob, 0, 4).then(function(hex) { qq.each(self.PREVIEWABLE_MIME_TYPES, function(mime, bytes) { if (isIdentifiable(bytes, hex)) { // Safari is the only supported browser that can deal with TIFFs natively, // so, if this is a TIFF and the UA isn't Safari, declare this file "non-previewable". if (mime !== "image/tiff" || qq.supportedFeatures.tiffPreviews) { previewable = true; idenitifer.success(mime); } return false; } }); log(qq.format("'{}' is {} able to be rendered in this browser", name, previewable ? "" : "NOT")); if (!previewable) { idenitifer.failure(); } }, function() { log("Error reading file w/ name '" + name + "'. Not able to be rendered in this browser."); idenitifer.failure(); }); } else { idenitifer.failure(); } return idenitifer; }, /** * Determines if a Blob can be displayed natively in the current browser. This is done by checking the * blob's type attribute. This is a synchronous operation, useful for situations where an asynchronous operation * would be challenging to support. Note that the blob's type property is not as accurate as reading the * file's magic bytes. * * @returns {Boolean} true if the blob can be rendered in the current browser */ isPreviewableSync: function() { var fileMime = fileOrBlob.type, // Assumption: This will only ever be executed in browsers that support `Object.keys`. isRecognizedImage = qq.indexOf(Object.keys(this.PREVIEWABLE_MIME_TYPES), fileMime) >= 0, previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name; if (isRecognizedImage) { if (fileMime === "image/tiff") { previewable = qq.supportedFeatures.tiffPreviews; } else { previewable = true; } } !previewable && log(name + " is not previewable in this browser per the blob's type attr"); return previewable; } }); }; qq.Identify.prototype.PREVIEWABLE_MIME_TYPES = { "image/jpeg": "ffd8ff", "image/gif": "474946", "image/png": "89504e", "image/bmp": "424d", "image/tiff": ["49492a00", "4d4d002a"] }; /*globals qq*/ /** * Attempts to validate an image, wherever possible. * * @param blob File or Blob representing a user-selecting image. * @param log Uses this to post log messages to the console. * @constructor */ qq.ImageValidation = function(blob, log) { "use strict"; /** * @param limits Object with possible image-related limits to enforce. * @returns {boolean} true if at least one of the limits has a non-zero value */ function hasNonZeroLimits(limits) { var atLeastOne = false; qq.each(limits, function(limit, value) { if (value > 0) { atLeastOne = true; return false; } }); return atLeastOne; } /** * @returns {qq.Promise} The promise is a failure if we can't obtain the width & height. * Otherwise, `success` is called on the returned promise with an object containing * `width` and `height` properties. */ function getWidthHeight() { var sizeDetermination = new qq.Promise(); new qq.Identify(blob, log).isPreviewable().then(function() { var image = new Image(), url = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null; if (url) { image.onerror = function() { log("Cannot determine dimensions for image. May be too large.", "error"); sizeDetermination.failure(); }; image.onload = function() { sizeDetermination.success({ width: this.width, height: this.height }); }; image.src = url.createObjectURL(blob); } else { log("No createObjectURL function available to generate image URL!", "error"); sizeDetermination.failure(); } }, sizeDetermination.failure); return sizeDetermination; } /** * * @param limits Object with possible image-related limits to enforce. * @param dimensions Object containing `width` & `height` properties for the image to test. * @returns {String || undefined} The name of the failing limit. Undefined if no failing limits. */ function getFailingLimit(limits, dimensions) { var failingLimit; qq.each(limits, function(limitName, limitValue) { if (limitValue > 0) { var limitMatcher = /(max|min)(Width|Height)/.exec(limitName), dimensionPropName = limitMatcher[2].charAt(0).toLowerCase() + limitMatcher[2].slice(1), actualValue = dimensions[dimensionPropName]; /*jshint -W015*/ switch (limitMatcher[1]) { case "min": if (actualValue < limitValue) { failingLimit = limitName; return false; } break; case "max": if (actualValue > limitValue) { failingLimit = limitName; return false; } break; } } }); return failingLimit; } /** * Validate the associated blob. * * @param limits * @returns {qq.Promise} `success` is called on the promise is the image is valid or * if the blob is not an image, or if the image is not verifiable. * Otherwise, `failure` with the name of the failing limit. */ this.validate = function(limits) { var validationEffort = new qq.Promise(); log("Attempting to validate image."); if (hasNonZeroLimits(limits)) { getWidthHeight().then(function(dimensions) { var failingLimit = getFailingLimit(limits, dimensions); if (failingLimit) { validationEffort.failure(failingLimit); } else { validationEffort.success(); } }, validationEffort.success); } else { validationEffort.success(); } return validationEffort; }; }; /* globals qq */ /** * Module used to control populating the initial list of files. * * @constructor */ qq.Session = function(spec) { "use strict"; var options = { endpoint: null, params: {}, customHeaders: {}, cors: {}, addFileRecord: function(sessionData) {}, log: function(message, level) {} }; qq.extend(options, spec, true); function isJsonResponseValid(response) { if (qq.isArray(response)) { return true; } options.log("Session response is not an array.", "error"); } function handleFileItems(fileItems, success, xhrOrXdr, promise) { var someItemsIgnored = false; success = success && isJsonResponseValid(fileItems); if (success) { qq.each(fileItems, function(idx, fileItem) { /* jshint eqnull:true */ if (fileItem.uuid == null) { someItemsIgnored = true; options.log(qq.format("Session response item {} did not include a valid UUID - ignoring.", idx), "error"); } else if (fileItem.name == null) { someItemsIgnored = true; options.log(qq.format("Session response item {} did not include a valid name - ignoring.", idx), "error"); } else { try { options.addFileRecord(fileItem); return true; } catch (err) { someItemsIgnored = true; options.log(err.message, "error"); } } return false; }); } promise[success && !someItemsIgnored ? "success" : "failure"](fileItems, xhrOrXdr); } // Initiate a call to the server that will be used to populate the initial file list. // Returns a `qq.Promise`. this.refresh = function() { /*jshint indent:false */ var refreshEffort = new qq.Promise(), refreshCompleteCallback = function(response, success, xhrOrXdr) { handleFileItems(response, success, xhrOrXdr, refreshEffort); }, requsterOptions = qq.extend({}, options), requester = new qq.SessionAjaxRequester( qq.extend(requsterOptions, {onComplete: refreshCompleteCallback}) ); requester.queryServer(); return refreshEffort; }; }; /*globals qq, XMLHttpRequest*/ /** * Thin module used to send GET requests to the server, expecting information about session * data used to initialize an uploader instance. * * @param spec Various options used to influence the associated request. * @constructor */ qq.SessionAjaxRequester = function(spec) { "use strict"; var requester, options = { endpoint: null, customHeaders: {}, params: {}, cors: { expected: false, sendCredentials: false }, onComplete: function(response, success, xhrOrXdr) {}, log: function(str, level) {} }; qq.extend(options, spec); function onComplete(id, xhrOrXdr, isError) { var response = null; /* jshint eqnull:true */ if (xhrOrXdr.responseText != null) { try { response = qq.parseJson(xhrOrXdr.responseText); } catch (err) { options.log("Problem parsing session response: " + err.message, "error"); isError = true; } } options.onComplete(response, !isError, xhrOrXdr); } requester = qq.extend(this, new qq.AjaxRequester({ acceptHeader: "application/json", validMethods: ["GET"], method: "GET", endpointStore: { get: function() { return options.endpoint; } }, customHeaders: options.customHeaders, log: options.log, onComplete: onComplete, cors: options.cors })); qq.extend(this, { queryServer: function() { var params = qq.extend({}, options.params); options.log("Session query request."); requester.initTransport("sessionRefresh") .withParams(params) .withCacheBuster() .send(); } }); }; /* globals qq */ /** * Module that handles support for existing forms. * * @param options Options passed from the integrator-supplied options related to form support. * @param startUpload Callback to invoke when files "stored" should be uploaded. * @param log Proxy for the logger * @constructor */ qq.FormSupport = function(options, startUpload, log) { "use strict"; var self = this, interceptSubmit = options.interceptSubmit, formEl = options.element, autoUpload = options.autoUpload; // Available on the public API associated with this module. qq.extend(this, { // To be used by the caller to determine if the endpoint will be determined by some processing // that occurs in this module, such as if the form has an action attribute. // Ignore if `attachToForm === false`. newEndpoint: null, // To be used by the caller to determine if auto uploading should be allowed. // Ignore if `attachToForm === false`. newAutoUpload: autoUpload, // true if a form was detected and is being tracked by this module attachedToForm: false, // Returns an object with names and values for all valid form elements associated with the attached form. getFormInputsAsObject: function() { /* jshint eqnull:true */ if (formEl == null) { return null; } return self._form2Obj(formEl); } }); // If the form contains an action attribute, this should be the new upload endpoint. function determineNewEndpoint(formEl) { if (formEl.getAttribute("action")) { self.newEndpoint = formEl.getAttribute("action"); } } // Return true only if the form is valid, or if we cannot make this determination. // If the form is invalid, ensure invalid field(s) are highlighted in the UI. function validateForm(formEl, nativeSubmit) { if (formEl.checkValidity && !formEl.checkValidity()) { log("Form did not pass validation checks - will not upload.", "error"); nativeSubmit(); } else { return true; } } // Intercept form submit attempts, unless the integrator has told us not to do this. function maybeUploadOnSubmit(formEl) { var nativeSubmit = formEl.submit; // Intercept and squelch submit events. qq(formEl).attach("submit", function(event) { event = event || window.event; if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } validateForm(formEl, nativeSubmit) && startUpload(); }); // The form's `submit()` function may be called instead (i.e. via jQuery.submit()). // Intercept that too. formEl.submit = function() { validateForm(formEl, nativeSubmit) && startUpload(); }; } // If the element value passed from the uploader is a string, assume it is an element ID - select it. // The rest of the code in this module depends on this being an HTMLElement. function determineFormEl(formEl) { if (formEl) { if (qq.isString(formEl)) { formEl = document.getElementById(formEl); } if (formEl) { log("Attaching to form element."); determineNewEndpoint(formEl); interceptSubmit && maybeUploadOnSubmit(formEl); } } return formEl; } formEl = determineFormEl(formEl); this.attachedToForm = !!formEl; }; qq.extend(qq.FormSupport.prototype, { // Converts all relevant form fields to key/value pairs. This is meant to mimic the data a browser will // construct from a given form when the form is submitted. _form2Obj: function(form) { "use strict"; var obj = {}, notIrrelevantType = function(type) { var irrelevantTypes = [ "button", "image", "reset", "submit" ]; return qq.indexOf(irrelevantTypes, type.toLowerCase()) < 0; }, radioOrCheckbox = function(type) { return qq.indexOf(["checkbox", "radio"], type.toLowerCase()) >= 0; }, ignoreValue = function(el) { if (radioOrCheckbox(el.type) && !el.checked) { return true; } return el.disabled && el.type.toLowerCase() !== "hidden"; }, selectValue = function(select) { var value = null; qq.each(qq(select).children(), function(idx, child) { if (child.tagName.toLowerCase() === "option" && child.selected) { value = child.value; return false; } }); return value; }; qq.each(form.elements, function(idx, el) { if ((qq.isInput(el, true) || el.tagName.toLowerCase() === "textarea") && notIrrelevantType(el.type) && !ignoreValue(el)) { obj[el.name] = el.value; } else if (el.tagName.toLowerCase() === "select" && !ignoreValue(el)) { var value = selectValue(el); if (value !== null) { obj[el.name] = value; } } }); return obj; } }); /* globals qq, ExifRestorer */ /** * Controls generation of scaled images based on a reference image encapsulated in a `File` or `Blob`. * Scaled images are generated and converted to blobs on-demand. * Multiple scaled images per reference image with varying sizes and other properties are supported. * * @param spec Information about the scaled images to generate. * @param log Logger instance * @constructor */ qq.Scaler = function(spec, log) { "use strict"; var self = this, includeOriginal = spec.sendOriginal, orient = spec.orient, defaultType = spec.defaultType, defaultQuality = spec.defaultQuality / 100, failedToScaleText = spec.failureText, includeExif = spec.includeExif, sizes = this._getSortedSizes(spec.sizes); // Revealed API for instances of this module qq.extend(this, { // If no targeted sizes have been declared or if this browser doesn't support // client-side image preview generation, there is no scaling to do. enabled: qq.supportedFeatures.scaling && sizes.length > 0, getFileRecords: function(originalFileUuid, originalFileName, originalBlobOrBlobData) { var self = this, records = [], originalBlob = originalBlobOrBlobData.blob ? originalBlobOrBlobData.blob : originalBlobOrBlobData, idenitifier = new qq.Identify(originalBlob, log); // If the reference file cannot be rendered natively, we can't create scaled versions. if (idenitifier.isPreviewableSync()) { // Create records for each scaled version & add them to the records array, smallest first. qq.each(sizes, function(idx, sizeRecord) { var outputType = self._determineOutputType({ defaultType: defaultType, requestedType: sizeRecord.type, refType: originalBlob.type }); records.push({ uuid: qq.getUniqueId(), name: self._getName(originalFileName, { name: sizeRecord.name, type: outputType, refType: originalBlob.type }), blob: new qq.BlobProxy(originalBlob, qq.bind(self._generateScaledImage, self, { maxSize: sizeRecord.maxSize, orient: orient, type: outputType, quality: defaultQuality, failedText: failedToScaleText, includeExif: includeExif, log: log })) }); }); records.push({ uuid: originalFileUuid, name: originalFileName, size: originalBlob.size, blob: includeOriginal ? originalBlob : null }); } else { records.push({ uuid: originalFileUuid, name: originalFileName, size: originalBlob.size, blob: originalBlob }); } return records; }, handleNewFile: function(file, name, uuid, size, fileList, batchId, uuidParamName, api) { var self = this, buttonId = file.qqButtonId || (file.blob && file.blob.qqButtonId), scaledIds = [], originalId = null, addFileToHandler = api.addFileToHandler, uploadData = api.uploadData, paramsStore = api.paramsStore, proxyGroupId = qq.getUniqueId(); qq.each(self.getFileRecords(uuid, name, file), function(idx, record) { var blobSize = record.size, id; if (record.blob instanceof qq.BlobProxy) { blobSize = -1; } id = uploadData.addFile({ uuid: record.uuid, name: record.name, size: blobSize, batchId: batchId, proxyGroupId: proxyGroupId }); if (record.blob instanceof qq.BlobProxy) { scaledIds.push(id); } else { originalId = id; } if (record.blob) { addFileToHandler(id, record.blob); fileList.push({id: id, file: record.blob}); } else { uploadData.setStatus(id, qq.status.REJECTED); } }); // If we are potentially uploading an original file and some scaled versions, // ensure the scaled versions include reference's to the parent's UUID and size // in their associated upload requests. if (originalId !== null) { qq.each(scaledIds, function(idx, scaledId) { var params = { qqparentuuid: uploadData.retrieve({id: originalId}).uuid, qqparentsize: uploadData.retrieve({id: originalId}).size }; // Make sure the UUID for each scaled image is sent with the upload request, // to be consistent (since we may need to ensure it is sent for the original file as well). params[uuidParamName] = uploadData.retrieve({id: scaledId}).uuid; uploadData.setParentId(scaledId, originalId); paramsStore.addReadOnly(scaledId, params); }); // If any scaled images are tied to this parent image, be SURE we send its UUID as an upload request // parameter as well. if (scaledIds.length) { (function() { var param = {}; param[uuidParamName] = uploadData.retrieve({id: originalId}).uuid; paramsStore.addReadOnly(originalId, param); }()); } } } }); }; qq.extend(qq.Scaler.prototype, { scaleImage: function(id, specs, api) { "use strict"; if (!qq.supportedFeatures.scaling) { throw new qq.Error("Scaling is not supported in this browser!"); } var scalingEffort = new qq.Promise(), log = api.log, file = api.getFile(id), uploadData = api.uploadData.retrieve({id: id}), name = uploadData && uploadData.name, uuid = uploadData && uploadData.uuid, scalingOptions = { sendOriginal: false, orient: specs.orient, defaultType: specs.type || null, defaultQuality: specs.quality, failedToScaleText: "Unable to scale", sizes: [{name: "", maxSize: specs.maxSize}] }, scaler = new qq.Scaler(scalingOptions, log); if (!qq.Scaler || !qq.supportedFeatures.imagePreviews || !file) { scalingEffort.failure(); log("Could not generate requested scaled image for " + id + ". " + "Scaling is either not possible in this browser, or the file could not be located.", "error"); } else { (qq.bind(function() { // Assumption: There will never be more than one record var record = scaler.getFileRecords(uuid, name, file)[0]; if (record && record.blob instanceof qq.BlobProxy) { record.blob.create().then(scalingEffort.success, scalingEffort.failure); } else { log(id + " is not a scalable image!", "error"); scalingEffort.failure(); } }, this)()); } return scalingEffort; }, // NOTE: We cannot reliably determine at this time if the UA supports a specific MIME type for the target format. // image/jpeg and image/png are the only safe choices at this time. _determineOutputType: function(spec) { "use strict"; var requestedType = spec.requestedType, defaultType = spec.defaultType, referenceType = spec.refType; // If a default type and requested type have not been specified, this should be a // JPEG if the original type is a JPEG, otherwise, a PNG. if (!defaultType && !requestedType) { if (referenceType !== "image/jpeg") { return "image/png"; } return referenceType; } // A specified default type is used when a requested type is not specified. if (!requestedType) { return defaultType; } // If requested type is specified, use it, as long as this recognized type is supported by the current UA if (qq.indexOf(Object.keys(qq.Identify.prototype.PREVIEWABLE_MIME_TYPES), requestedType) >= 0) { if (requestedType === "image/tiff") { return qq.supportedFeatures.tiffPreviews ? requestedType : defaultType; } return requestedType; } return defaultType; }, // Get a file name for a generated scaled file record, based on the provided scaled image description _getName: function(originalName, scaledVersionProperties) { "use strict"; var startOfExt = originalName.lastIndexOf("."), versionType = scaledVersionProperties.type || "image/png", referenceType = scaledVersionProperties.refType, scaledName = "", scaledExt = qq.getExtension(originalName), nameAppendage = ""; if (scaledVersionProperties.name && scaledVersionProperties.name.trim().length) { nameAppendage = " (" + scaledVersionProperties.name + ")"; } if (startOfExt >= 0) { scaledName = originalName.substr(0, startOfExt); if (referenceType !== versionType) { scaledExt = versionType.split("/")[1]; } scaledName += nameAppendage + "." + scaledExt; } else { scaledName = originalName + nameAppendage; } return scaledName; }, // We want the smallest scaled file to be uploaded first _getSortedSizes: function(sizes) { "use strict"; sizes = qq.extend([], sizes); return sizes.sort(function(a, b) { if (a.maxSize > b.maxSize) { return 1; } if (a.maxSize < b.maxSize) { return -1; } return 0; }); }, _generateScaledImage: function(spec, sourceFile) { "use strict"; var self = this, log = spec.log, maxSize = spec.maxSize, orient = spec.orient, type = spec.type, quality = spec.quality, failedText = spec.failedText, includeExif = spec.includeExif && sourceFile.type === "image/jpeg" && type === "image/jpeg", scalingEffort = new qq.Promise(), imageGenerator = new qq.ImageGenerator(log), canvas = document.createElement("canvas"); log("Attempting to generate scaled version for " + sourceFile.name); imageGenerator.generate(sourceFile, canvas, {maxSize: maxSize, orient: orient}).then(function() { var scaledImageDataUri = canvas.toDataURL(type, quality), signalSuccess = function() { log("Success generating scaled version for " + sourceFile.name); var blob = qq.dataUriToBlob(scaledImageDataUri); scalingEffort.success(blob); }; if (includeExif) { self._insertExifHeader(sourceFile, scaledImageDataUri, log).then(function(scaledImageDataUriWithExif) { scaledImageDataUri = scaledImageDataUriWithExif; signalSuccess(); }, function() { log("Problem inserting EXIF header into scaled image. Using scaled image w/out EXIF data.", "error"); signalSuccess(); }); } else { signalSuccess(); } }, function() { log("Failed attempt to generate scaled version for " + sourceFile.name, "error"); scalingEffort.failure(failedText); }); return scalingEffort; }, // Attempt to insert the original image's EXIF header into a scaled version. _insertExifHeader: function(originalImage, scaledImageDataUri, log) { "use strict"; var reader = new FileReader(), insertionEffort = new qq.Promise(), originalImageDataUri = ""; reader.onload = function() { originalImageDataUri = reader.result; insertionEffort.success(ExifRestorer.restore(originalImageDataUri, scaledImageDataUri)); }; reader.onerror = function() { log("Problem reading " + originalImage.name + " during attempt to transfer EXIF data to scaled version.", "error"); insertionEffort.failure(); }; reader.readAsDataURL(originalImage); return insertionEffort; }, _dataUriToBlob: function(dataUri) { "use strict"; var byteString, mimeString, arrayBuffer, intArray; // convert base64 to raw binary data held in a string if (dataUri.split(",")[0].indexOf("base64") >= 0) { byteString = atob(dataUri.split(",")[1]); } else { byteString = decodeURI(dataUri.split(",")[1]); } // extract the MIME mimeString = dataUri.split(",")[0] .split(":")[1] .split(";")[0]; // write the bytes of the binary string to an ArrayBuffer arrayBuffer = new ArrayBuffer(byteString.length); intArray = new Uint8Array(arrayBuffer); qq.each(byteString, function(idx, character) { intArray[idx] = character.charCodeAt(0); }); return this._createBlob(arrayBuffer, mimeString); }, _createBlob: function(data, mime) { "use strict"; var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder, blobBuilder = BlobBuilder && new BlobBuilder(); if (blobBuilder) { blobBuilder.append(data); return blobBuilder.getBlob(mime); } else { return new Blob([data], {type: mime}); } } }); //Based on MinifyJpeg //http://elicon.blog57.fc2.com/blog-entry-206.html var ExifRestorer = (function() { var ExifRestorer = {}; ExifRestorer.KEY_STR = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "="; ExifRestorer.encode64 = function(input) { var output = "", chr1, chr2, chr3 = "", enc1, enc2, enc3, enc4 = "", i = 0; do { chr1 = input[i++]; chr2 = input[i++]; chr3 = input[i++]; enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this.KEY_STR.charAt(enc1) + this.KEY_STR.charAt(enc2) + this.KEY_STR.charAt(enc3) + this.KEY_STR.charAt(enc4); chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return output; }; ExifRestorer.restore = function(origFileBase64, resizedFileBase64) { var expectedBase64Header = "data:image/jpeg;base64,"; if (!origFileBase64.match(expectedBase64Header)) { return resizedFileBase64; } var rawImage = this.decode64(origFileBase64.replace(expectedBase64Header, "")); var segments = this.slice2Segments(rawImage); var image = this.exifManipulation(resizedFileBase64, segments); return expectedBase64Header + this.encode64(image); }; ExifRestorer.exifManipulation = function(resizedFileBase64, segments) { var exifArray = this.getExifArray(segments), newImageArray = this.insertExif(resizedFileBase64, exifArray), aBuffer = new Uint8Array(newImageArray); return aBuffer; }; ExifRestorer.getExifArray = function(segments) { var seg; for (var x = 0; x < segments.length; x++) { seg = segments[x]; if (seg[0] == 255 & seg[1] == 225) //(ff e1) { return seg; } } return []; }; ExifRestorer.insertExif = function(resizedFileBase64, exifArray) { var imageData = resizedFileBase64.replace("data:image/jpeg;base64,", ""), buf = this.decode64(imageData), separatePoint = buf.indexOf(255,3), mae = buf.slice(0, separatePoint), ato = buf.slice(separatePoint), array = mae; array = array.concat(exifArray); array = array.concat(ato); return array; }; ExifRestorer.slice2Segments = function(rawImageArray) { var head = 0, segments = []; while (1) { if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 218){break;} if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 216) { head += 2; } else { var length = rawImageArray[head + 2] * 256 + rawImageArray[head + 3], endPoint = head + length + 2, seg = rawImageArray.slice(head, endPoint); segments.push(seg); head = endPoint; } if (head > rawImageArray.length){break;} } return segments; }; ExifRestorer.decode64 = function(input) { var output = "", chr1, chr2, chr3 = "", enc1, enc2, enc3, enc4 = "", i = 0, buf = []; // remove all characters that are not A-Z, a-z, 0-9, +, /, or = var base64test = /[^A-Za-z0-9\+\/\=]/g; if (base64test.exec(input)) { throw new Error("There were invalid base64 characters in the input text. " + "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='"); } input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); do { enc1 = this.KEY_STR.indexOf(input.charAt(i++)); enc2 = this.KEY_STR.indexOf(input.charAt(i++)); enc3 = this.KEY_STR.indexOf(input.charAt(i++)); enc4 = this.KEY_STR.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; buf.push(chr1); if (enc3 != 64) { buf.push(chr2); } if (enc4 != 64) { buf.push(chr3); } chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return buf; }; return ExifRestorer; })(); /* globals qq */ /** * Keeps a running tally of total upload progress for a batch of files. * * @param callback Invoked when total progress changes, passing calculated total loaded & total size values. * @param getSize Function that returns the size of a file given its ID * @constructor */ qq.TotalProgress = function(callback, getSize) { "use strict"; var perFileProgress = {}, totalLoaded = 0, totalSize = 0, lastLoadedSent = -1, lastTotalSent = -1, callbackProxy = function(loaded, total) { if (loaded !== lastLoadedSent || total !== lastTotalSent) { callback(loaded, total); } lastLoadedSent = loaded; lastTotalSent = total; }, /** * @param failed Array of file IDs that have failed * @param retryable Array of file IDs that are retryable * @returns true if none of the failed files are eligible for retry */ noRetryableFiles = function(failed, retryable) { var none = true; qq.each(failed, function(idx, failedId) { if (qq.indexOf(retryable, failedId) >= 0) { none = false; return false; } }); return none; }, onCancel = function(id) { updateTotalProgress(id, -1, -1); delete perFileProgress[id]; }, onAllComplete = function(successful, failed, retryable) { if (failed.length === 0 || noRetryableFiles(failed, retryable)) { callbackProxy(totalSize, totalSize); this.reset(); } }, onNew = function(id) { var size = getSize(id); // We might not know the size yet, such as for blob proxies if (size > 0) { updateTotalProgress(id, 0, size); perFileProgress[id] = {loaded: 0, total: size}; } }, /** * Invokes the callback with the current total progress of all files in the batch. Called whenever it may * be appropriate to re-calculate and dissemenate this data. * * @param id ID of a file that has changed in some important way * @param newLoaded New loaded value for this file. -1 if this value should no longer be part of calculations * @param newTotal New total size of the file. -1 if this value should no longer be part of calculations */ updateTotalProgress = function(id, newLoaded, newTotal) { var oldLoaded = perFileProgress[id] ? perFileProgress[id].loaded : 0, oldTotal = perFileProgress[id] ? perFileProgress[id].total : 0; if (newLoaded === -1 && newTotal === -1) { totalLoaded -= oldLoaded; totalSize -= oldTotal; } else { if (newLoaded) { totalLoaded += newLoaded - oldLoaded; } if (newTotal) { totalSize += newTotal - oldTotal; } } callbackProxy(totalLoaded, totalSize); }; qq.extend(this, { // Called when a batch of files has completed uploading. onAllComplete: onAllComplete, // Called when the status of a file has changed. onStatusChange: function(id, oldStatus, newStatus) { if (newStatus === qq.status.CANCELED || newStatus === qq.status.REJECTED) { onCancel(id); } else if (newStatus === qq.status.SUBMITTING) { onNew(id); } }, // Called whenever the upload progress of an individual file has changed. onIndividualProgress: function(id, loaded, total) { updateTotalProgress(id, loaded, total); perFileProgress[id] = {loaded: loaded, total: total}; }, // Called whenever the total size of a file has changed, such as when the size of a generated blob is known. onNewSize: function(id) { onNew(id); }, reset: function() { perFileProgress = {}; totalLoaded = 0; totalSize = 0; } }); }; /*globals qq */ // Base handler for UI (FineUploader mode) events. // Some more specific handlers inherit from this one. qq.UiEventHandler = function(s, protectedApi) { "use strict"; var disposer = new qq.DisposeSupport(), spec = { eventType: "click", attachTo: null, onHandled: function(target, event) {} }; // This makes up the "public" API methods that will be accessible // to instances constructing a base or child handler qq.extend(this, { addHandler: function(element) { addHandler(element); }, dispose: function() { disposer.dispose(); } }); function addHandler(element) { disposer.attach(element, spec.eventType, function(event) { // Only in IE: the `event` is a property of the `window`. event = event || window.event; // On older browsers, we must check the `srcElement` instead of the `target`. var target = event.target || event.srcElement; spec.onHandled(target, event); }); } // These make up the "protected" API methods that children of this base handler will utilize. qq.extend(protectedApi, { getFileIdFromItem: function(item) { return item.qqFileId; }, getDisposeSupport: function() { return disposer; } }); qq.extend(spec, s); if (spec.attachTo) { addHandler(spec.attachTo); } }; /* global qq */ qq.FileButtonsClickHandler = function(s) { "use strict"; var inheritedInternalApi = {}, spec = { templating: null, log: function(message, lvl) {}, onDeleteFile: function(fileId) {}, onCancel: function(fileId) {}, onRetry: function(fileId) {}, onPause: function(fileId) {}, onContinue: function(fileId) {}, onGetName: function(fileId) {} }, buttonHandlers = { cancel: function(id) { spec.onCancel(id); }, retry: function(id) { spec.onRetry(id); }, deleteButton: function(id) { spec.onDeleteFile(id); }, pause: function(id) { spec.onPause(id); }, continueButton: function(id) { spec.onContinue(id); } }; function examineEvent(target, event) { qq.each(buttonHandlers, function(buttonType, handler) { var firstLetterCapButtonType = buttonType.charAt(0).toUpperCase() + buttonType.slice(1), fileId; if (spec.templating["is" + firstLetterCapButtonType](target)) { fileId = spec.templating.getFileId(target); qq.preventDefault(event); spec.log(qq.format("Detected valid file button click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId)); handler(fileId); return false; } }); } qq.extend(spec, s); spec.eventType = "click"; spec.onHandled = examineEvent; spec.attachTo = spec.templating.getFileList(); qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi)); }; /*globals qq */ // Child of FilenameEditHandler. Used to detect click events on filename display elements. qq.FilenameClickHandler = function(s) { "use strict"; var inheritedInternalApi = {}, spec = { templating: null, log: function(message, lvl) {}, classes: { file: "qq-upload-file", editNameIcon: "qq-edit-filename-icon" }, onGetUploadStatus: function(fileId) {}, onGetName: function(fileId) {} }; qq.extend(spec, s); // This will be called by the parent handler when a `click` event is received on the list element. function examineEvent(target, event) { if (spec.templating.isFileName(target) || spec.templating.isEditIcon(target)) { var fileId = spec.templating.getFileId(target), status = spec.onGetUploadStatus(fileId); // We only allow users to change filenames of files that have been submitted but not yet uploaded. if (status === qq.status.SUBMITTED) { spec.log(qq.format("Detected valid filename click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId)); qq.preventDefault(event); inheritedInternalApi.handleFilenameEdit(fileId, target, true); } } } spec.eventType = "click"; spec.onHandled = examineEvent; qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi)); }; /*globals qq */ // Child of FilenameEditHandler. Used to detect focusin events on file edit input elements. qq.FilenameInputFocusInHandler = function(s, inheritedInternalApi) { "use strict"; var spec = { templating: null, onGetUploadStatus: function(fileId) {}, log: function(message, lvl) {} }; if (!inheritedInternalApi) { inheritedInternalApi = {}; } // This will be called by the parent handler when a `focusin` event is received on the list element. function handleInputFocus(target, event) { if (spec.templating.isEditInput(target)) { var fileId = spec.templating.getFileId(target), status = spec.onGetUploadStatus(fileId); if (status === qq.status.SUBMITTED) { spec.log(qq.format("Detected valid filename input focus event on file '{}', ID: {}.", spec.onGetName(fileId), fileId)); inheritedInternalApi.handleFilenameEdit(fileId, target); } } } spec.eventType = "focusin"; spec.onHandled = handleInputFocus; qq.extend(spec, s); qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi)); }; /*globals qq */ /** * Child of FilenameInputFocusInHandler. Used to detect focus events on file edit input elements. This child module is only * needed for UAs that do not support the focusin event. Currently, only Firefox lacks this event. * * @param spec Overrides for default specifications */ qq.FilenameInputFocusHandler = function(spec) { "use strict"; spec.eventType = "focus"; spec.attachTo = null; qq.extend(this, new qq.FilenameInputFocusInHandler(spec, {})); }; /*globals qq */ // Handles edit-related events on a file item (FineUploader mode). This is meant to be a parent handler. // Children will delegate to this handler when specific edit-related actions are detected. qq.FilenameEditHandler = function(s, inheritedInternalApi) { "use strict"; var spec = { templating: null, log: function(message, lvl) {}, onGetUploadStatus: function(fileId) {}, onGetName: function(fileId) {}, onSetName: function(fileId, newName) {}, onEditingStatusChange: function(fileId, isEditing) {} }; function getFilenameSansExtension(fileId) { var filenameSansExt = spec.onGetName(fileId), extIdx = filenameSansExt.lastIndexOf("."); if (extIdx > 0) { filenameSansExt = filenameSansExt.substr(0, extIdx); } return filenameSansExt; } function getOriginalExtension(fileId) { var origName = spec.onGetName(fileId); return qq.getExtension(origName); } // Callback iff the name has been changed function handleNameUpdate(newFilenameInputEl, fileId) { var newName = newFilenameInputEl.value, origExtension; if (newName !== undefined && qq.trimStr(newName).length > 0) { origExtension = getOriginalExtension(fileId); if (origExtension !== undefined) { newName = newName + "." + origExtension; } spec.onSetName(fileId, newName); } spec.onEditingStatusChange(fileId, false); } // The name has been updated if the filename edit input loses focus. function registerInputBlurHandler(inputEl, fileId) { inheritedInternalApi.getDisposeSupport().attach(inputEl, "blur", function() { handleNameUpdate(inputEl, fileId); }); } // The name has been updated if the user presses enter. function registerInputEnterKeyHandler(inputEl, fileId) { inheritedInternalApi.getDisposeSupport().attach(inputEl, "keyup", function(event) { var code = event.keyCode || event.which; if (code === 13) { handleNameUpdate(inputEl, fileId); } }); } qq.extend(spec, s); spec.attachTo = spec.templating.getFileList(); qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi)); qq.extend(inheritedInternalApi, { handleFilenameEdit: function(id, target, focusInput) { var newFilenameInputEl = spec.templating.getEditInput(id); spec.onEditingStatusChange(id, true); newFilenameInputEl.value = getFilenameSansExtension(id); if (focusInput) { newFilenameInputEl.focus(); } registerInputBlurHandler(newFilenameInputEl, id); registerInputEnterKeyHandler(newFilenameInputEl, id); } }); }; /*! 2015-09-22 */
(function($window, L, d3) { "use strict"; /** * @method throwException * @param message {String} * @param path {String} * @return {void} */ var throwException = function throwException(message, path) { if (path) { // Output a link for a more informative message in the EXCEPTIONS.md. console.error('See: https://github.com/Wildhoney/Leaflet.FreeDraw/blob/master/EXCEPTIONS.md#' + path); } // ..And then output the thrown exception. throw "Leaflet.FreeDraw: " + message + "."; }; L.FreeDraw = L.FeatureGroup.extend({ /** * @property map * @type {L.Map|null} */ map: null, /** * @property svg * @type {Object} */ svg: {}, /** * Determines whether the user is currently creating a polygon. * * @property creating * @type {Boolean} */ creating: false, /** * Responsible for holding the line function that is required by D3 to draw the line based * on the user's cursor position. * * @property lineFunction * @type {Function} */ lineFunction: function () {}, /** * Responsible for holding an array of latitudinal and longitudinal points for generating * the polygon. * * @property latLngs * @type {Array} */ latLngs: [], /** * @property options * @type {Object} */ options: {}, /** * @property markers * @type {L.LayerGroup|null} */ markerLayer: L.layerGroup(), /** * @property hull * @type {Object} */ hull: {}, /** * @property edges * @type {Array} */ edges: [], /** * @property mode * @type {Number} */ mode: 1, /** * Responsible for holding the coordinates of the user's last cursor position for drawing * the D3 polygon tracing the user's cursor. * * @property fromPoint * @type {Object} */ fromPoint: { x: 0, y: 0 }, /** * @property movingEdge * @type {L.polygon|null} */ movingEdge: null, /** * Responsible for knowing whether a boundary update should be propagated once the user exits * the editing mode. * * @property boundaryUpdateRequired * @type {Boolean} */ boundaryUpdateRequired: false, /** * @method initialize * @param options {Object} * @return {void} */ initialize: function initialize(options) { L.Util.setOptions(this, options); this.options = new L.FreeDraw.Options(); this.hull = new L.FreeDraw.Hull(); this.setMode(options.mode || this.mode); }, /** * @method onAdd * @param map {L.Map} * @return {void} */ onAdd: function onAdd(map) { // Lazily hook up the options and hull objects. this.map = map; this.mode = this.mode || L.FreeDraw.MODES.VIEW; // Define the line function for drawing the polygon from the user's mouse pointer. this.lineFunction = d3.svg.line().x(function(d) { return d.x; }).y(function(d) { return d.y; }) .interpolate('linear'); // Create a new instance of the D3 free-hand tracer. this.createD3(); // Attach all of the events. this._attachMouseDown(); this._attachMouseMove(); this._attachMouseUpLeave(); // Set the default mode. this.setMode(this.mode); }, /** * @method setMode * @param mode {Number} * @return {void} */ setMode: function setMode(mode) { var isCreate = !!(mode & L.FreeDraw.MODES.CREATE), method = !isCreate ? 'enable' : 'disable'; // Set the current mode. this.mode = mode; if (!this.map) { return; } if (this.boundaryUpdateRequired && !(this.mode & L.FreeDraw.MODES.EDIT)) { // Share the boundaries if there's an update available and the user is changing the mode // to anything else but the edit mode again. this.notifyBoundaries(); this.boundaryUpdateRequired = false; } // Update the permissions for what the user can do on the map. this.map.dragging[method](); this.map.touchZoom[method](); this.map.doubleClickZoom[method](); this.map.scrollWheelZoom[method](); /** * Responsible for applying the necessary classes to the map based on the * current active modes. * * @method defineClasses * @return {void} */ (function defineClasses(modes, classList) { classList.remove('mode-create'); classList.remove('mode-edit'); classList.remove('mode-delete'); classList.remove('mode-view'); if (mode & modes.CREATE) { classList.add('mode-create'); } if (mode & modes.EDIT) { classList.add('mode-edit'); } if (mode & modes.DELETE) { classList.add('mode-delete'); } if (mode & modes.VIEW) { classList.add('mode-view'); } }(L.FreeDraw.MODES, this.map._container.classList)); }, /** * @method createD3 * @return {void} */ createD3: function createD3() { this.svg = d3.select('body').append('svg').attr('class', this.options.svgClassName) .attr('width', 200).attr('height', 200); }, /** * @method destroyD3 * @return {L.FreeDraw} * @chainable */ destroyD3: function destroyD3() { this.svg.remove(); this.svg = {}; return this; }, /** * @method createPolygon * @param latLngs {L.latLng[]} * @return {L.polygon} */ createPolygon: function createPolygon(latLngs) { // Begin to create a brand-new polygon. this.destroyD3().createD3(); var polygon = L.polygon(latLngs, { color: '#D7217E', weight: 0, fill: true, fillColor: '#D7217E', fillOpacity: 0.75, smoothFactor: this.options.smoothFactor }); // Add the polyline to the map, and then find the edges of the polygon. polygon.addTo(this.map); polygon._latlngs = []; this.attachEdges(polygon); polygon._parts[0].forEach(function forEach(edge) { // Iterate over all of the parts to update the latLngs to clobber the redrawing upon zooming. polygon._latlngs.push(this.map.containerPointToLatLng(edge)); }.bind(this)); this.notifyBoundaries(); return polygon; }, /** * @method destroyPolygon * @param polygon {Object} * @return {void} */ destroyPolygon: function destroyPolygon(polygon) { // Remove the shape. polygon._container.remove(); // ...And then remove all of its related edges to prevent memory leaks. this.edges = this.edges.filter(function filter(edge) { if (edge._polygon !== polygon) { return true; } // Physically remove the edge from the DOM. edge._icon.remove(); }); this.notifyBoundaries(); }, /** * @method clearPolygons * @return {void} */ clearPolygons: function clearPolygons() { this.edges.forEach(function forEach(edge) { // Iteratively remove each polygon in the DOM. this.destroyPolygon(edge._polygon); }.bind(this)); this.notifyBoundaries(); }, /** * @method notifyBoundaries * @return {void} */ notifyBoundaries: function notifyBoundaries() { var latLngs = [], last = null, index = -1; this.edges.forEach(function forEach(edge) { if (edge._polygonId !== last) { index++; } if (typeof latLngs[index] === 'undefined') { // Create the array entry point if it hasn't yet been defined. latLngs[index] = []; } last = edge._polygonId; latLngs[index].push(edge['_latlng']); }.bind(this)); // Invoke the user passed method for specifying latitude/longitudes. this.options.markersFn(latLngs, this.setMarkers.bind(this)); }, /** * @method setMarkers * @param markers {L.Marker[]} * @param divIcon {L.DivIcon} * @return {void} */ setMarkers: function setMarkers(markers, divIcon) { if (typeof divIcon !== 'undefined' && !(divIcon instanceof L.DivIcon)) { // Ensure if the user has passed a second argument that it is a valid DIV icon. throwException('Second argument must be an instance of L.DivIcon'); } // Reset the markers collection. this.map.removeLayer(this.markerLayer); this.markerLayer = L.layerGroup(); this.markerLayer.addTo(this.map); if (!markers || markers.length === 0) { return; } var options = divIcon ? { icon: divIcon } : {}; // Iterate over each marker to plot it on the map. for (var addIndex = 0, addLength = markers.length; addIndex < addLength; addIndex++) { if (!(markers[addIndex] instanceof L.LatLng)) { throwException('Supplied markers must be instances of L.LatLng'); } // Add the marker using the custom DIV icon if it has been specified. var marker = L.marker(markers[addIndex], options); this.markerLayer.addLayer(marker); } }, /** * @method attachEdges * @param polygon {L.polygon} * @return {void} */ attachEdges: function attachEdges(polygon) { // Extract the parts from the polygon. var parts = polygon._parts[0]; parts.forEach(function forEach(point, index) { // Leaflet creates elbows in the polygon, which we need to utilise to add the // points for modifying its shape. var edge = L.divIcon({ className: this.options.iconClassName }), latLng = this.map.layerPointToLatLng(point); edge = L.marker(latLng, { icon: edge }).addTo(this.map); // Marker requires instances so that it can modify its shape. edge._polygon = polygon; edge._polygonId = polygon['_leaflet_id']; edge._index = index; edge._length = parts.length; this.edges.push(edge); edge.on('mousedown', function onMouseDown(event) { event.originalEvent.preventDefault(); event.originalEvent.stopPropagation(); this.movingEdge = event.target; }.bind(this)); }.bind(this)); }, updatePolygonEdge: function updatePolygon(edge, posX, posY) { var updatedLatLng = this.map.containerPointToLatLng(L.point(posX, posY)); edge.setLatLng(updatedLatLng); // Fetch all of the edges in the group based on the polygon. var edges = this.edges.filter(function filter(marker) { return marker._polygon === edge._polygon; }); var updatedLatLngs = []; edges.forEach(function forEach(marker) { updatedLatLngs.push(marker.getLatLng()); }); // Update the latitude and longitude values. edge._polygon.setLatLngs(updatedLatLngs); edge._polygon.redraw(); }, /** * @method _attachMouseDown * @return {void} * @private */ _attachMouseDown: function _attachMouseDown() { this.map.on('mousedown', function onMouseDown(event) { /** * Used for determining if the user clicked with the right mouse button. * * @constant RIGHT_CLICK * @type {Number} */ var RIGHT_CLICK = 2; if (event.originalEvent.button === RIGHT_CLICK) { return; } if (!this.options.multiplePolygons && this.edges.length) { // User is only allowed to create one polygon. return; } var originalEvent = event.originalEvent; originalEvent.stopPropagation(); originalEvent.preventDefault(); this.latLngs = []; this.fromPoint = { x: originalEvent.clientX, y: originalEvent.clientY }; if (this.mode & L.FreeDraw.MODES.CREATE) { // Place the user in create polygon mode. this.creating = true; } }.bind(this)); }, /** * @method _attachMouseMove * @return {void} * @private */ _attachMouseMove: function _attachMouseMove() { this.map.on('mousemove', function onMouseMove(event) { var originalEvent = event.originalEvent; if (this.movingEdge) { // User is in fact modifying the shape of the polygon. this._editMouseMove(originalEvent); return; } if (!this.creating) { // We can't do anything else if the user is not in the process of creating a brand-new // polygon. return; } this._createMouseMove(originalEvent); }.bind(this)); }, /** * @method _editMouseMove * @param event {Object} * @return {void} * @private */ _editMouseMove: function _editMouseMove(event) { var pointModel = L.point(event.clientX, event.clientY); // Modify the position of the marker on the map based on the user's mouse position. var styleDeclaration = this.movingEdge._icon.style; styleDeclaration[L.DomUtil.TRANSFORM] = pointModel; // Update the polygon's shape in real-time as the user drags their cursor. this.updatePolygonEdge(this.movingEdge, pointModel.x, pointModel.y); }, /** * @method _attachMouseUpLeave * @return {void} * @private */ _attachMouseUpLeave: function _attachMouseUpLeave() { this.map.on('mouseup mouseout mouseleave', function onMouseUpAndMouseLeave() { if (this.movingEdge) { if (!this.options.boundariesAfterEdit) { // Notify of a boundary update immediately after editing one edge. this.notifyBoundaries(); } else { // Change the option so that the boundaries will be invoked once the edit mode // has been exited. this.boundaryUpdateRequired = true; } this.movingEdge = null; return; } this._createMouseUp(); }.bind(this)); }, /** * @method _createMouseMove * @param event {Object} * @return {void} * @private */ _createMouseMove: function _createMouseMove(event) { // Grab the cursor's position from the event object. var pointerX = event.clientX, pointerY = event.clientY; // Resolve the pixel point to the latitudinal and longitudinal equivalent. var point = L.point(pointerX, pointerY), latLng = this.map.containerPointToLatLng(point); // Line data that is fed into the D3 line function we defined earlier. var lineData = [this.fromPoint, { x: pointerX, y: pointerY }]; // Draw SVG line based on the last movement of the mouse's position. this.svg.append('path').attr('d', this.lineFunction(lineData)) .attr('stroke', '#D7217E').attr('stroke-width', 2).attr('fill', 'none'); // Take the pointer's position from the event for the next invocation of the mouse move event, // and store the resolved latitudinal and longitudinal values. this.fromPoint.x = pointerX; this.fromPoint.y = pointerY; this.latLngs.push(latLng); }, /** * @method _createMouseUp * @return {void} * @private */ _createMouseUp: function _createMouseUp() { // User has finished creating their polygon! this.creating = false; if (this.latLngs.length <= 2) { // User has failed to drag their cursor enough to create a valid polygon. return; } if (this.options.hullAlgorithm) { // Use the defined hull algorithm. this.hull.setMap(this.map); var latLngs = this.hull[this.options.hullAlgorithm](this.latLngs); } // Required for joining the two ends of the free-hand drawing to create a closed polygon. this.latLngs.push(this.latLngs[0]); // Physically draw the Leaflet generated polygon. var polygon = this.createPolygon(latLngs || this.latLngs); this.latLngs = []; polygon.on('click', function onClick() { if (this.mode & L.FreeDraw.MODES.DELETE) { // Remove the polygon when the user clicks on it, and they're in delete mode. this.destroyPolygon(polygon); } }.bind(this)); if (this.options.createExitMode) { // Automatically exit the user from the creation mode. this.setMode(this.mode ^ L.FreeDraw.MODES.CREATE); } } }); /** * @constant MODES * @type {Object} */ L.FreeDraw.MODES = { VIEW: 1, CREATE: 2, EDIT: 4, DELETE: 8, ALL: 1 | 2 | 4 | 8 }; })(window, window.L, window.d3); (function() { "use strict"; /** * @module FreeDraw * @submodule Hull * @author Adam Timberlake * @link https://github.com/Wildhoney/Leaflet.FreeDraw * @constructor */ L.FreeDraw.Hull = function FreeDrawHull() {}; /** * @property prototype * @type {Object} */ L.FreeDraw.Hull.prototype = { /** * @property map * @type {L.Map|Object} */ map: {}, /** * @method setMap * @param map {L.Map} * @return {void} */ setMap: function setMap(map) { this.map = map; }, /** * @link https://github.com/brian3kb/graham_scan_js * @method brian3kbGrahamScan * @param latLngs {L.LatLng[]} * @return {L.LatLng[]} */ brian3kbGrahamScan: function brian3kbGrahamScan(latLngs) { var convexHull = new ConvexHullGrahamScan(), resolvedPoints = [], points = [], hullLatLngs = []; latLngs.forEach(function forEach(latLng) { // Resolve each latitude/longitude to its respective container point. points.push(this.map.latLngToContainerPoint(latLng)); }.bind(this)); points.forEach(function forEach(point) { convexHull.addPoint(point.x, point.y); }.bind(this)); var hullPoints = convexHull.getHull(); hullPoints.forEach(function forEach(hullPoint) { resolvedPoints.push(L.point(hullPoint.x, hullPoint.y)); }.bind(this)); // Create an unbroken polygon. resolvedPoints.push(resolvedPoints[0]); resolvedPoints.forEach(function forEach(point) { hullLatLngs.push(this.map.containerPointToLatLng(point)); }.bind(this)); return hullLatLngs; }, /** * @link https://github.com/Wildhoney/ConcaveHull * @method wildhoneyConcaveHull * @param latLngs {L.LatLng[]} * @return {L.LatLng[]} */ wildhoneyConcaveHull: function wildhoneyConcaveHull(latLngs) { latLngs.push(latLngs[0]); return new ConcaveHull(latLngs).getLatLngs(); } } }()); (function() { "use strict"; /** * @module FreeDraw * @submodule Options * @author Adam Timberlake * @link https://github.com/Wildhoney/Leaflet.FreeDraw * @constructor */ L.FreeDraw.Options = function FreeDrawOptions() {}; /** * @property prototype * @type {Object} */ L.FreeDraw.Options.prototype = { /** * @property multiplePolygons * @type {Boolean} */ multiplePolygons: true, /** * @property hullAlgorithm * @type {String|Boolean} */ hullAlgorithm: false, /** * @property boundariesAfterEdit * @type {Boolean} */ boundariesAfterEdit: false, /** * @property createExitMode * @type {Boolean} */ createExitMode: true, /** * @method markersFn * @type {Function} */ markersFn: function() {}, /** * @property hullAlgorithms * @type {Object} */ hullAlgorithms: { 'brian3kb/graham_scan_js': 'brian3kbGrahamScan', 'Wildhoney/ConcaveHull': 'wildhoneyConcaveHull' }, /** * @property svgClassName * @type {String} */ svgClassName: 'tracer', /** * @property smoothFactor * @type {Number} */ smoothFactor: 5, /** * @property iconClassName * @type {String} */ iconClassName: 'polygon-elbow', /** * @method exitModeAfterCreate * @param value {Boolean} * @return {void} */ exitModeAfterCreate: function exitModeAfterCreate(value) { this.createExitMode = !!value; }, /** * @method allowMultiplePolygons * @param allow {Boolean} * @return {void} */ allowMultiplePolygons: function allowMultiplePolygons(allow) { this.multiplePolygons = !!allow; }, /** * @method setSVGClassName * @param className {String} * @return {void} */ setSVGClassName: function setSVGClassName(className) { this.svgClassName = className; }, /** * @method setBoundariesAfterEdit * @param value {Boolean} * @return {void} */ setBoundariesAfterEdit: function setBoundariesAfterEdit(value) { this.boundariesAfterEdit = !!value; }, /** * @method smoothFactor * @param factor {Number} * @return {void} */ setSmoothFactor: function setSmoothFactor(factor) { this.smoothFactor = +factor; }, /** * @method setIconClassName * @param className {String} * @return {void} */ setIconClassName: function setIconClassName(className) { this.iconClassName = className; }, /** * @method getMarkers * @param markersFn {Function} * @return {void} */ getMarkers: function getMarkers(markersFn) { this.markersFn = markersFn; }, /** * @method setHullAlgorithm * @param algorithm {String|Boolean} * @return {void} */ setHullAlgorithm: function setHullAlgorithm(algorithm) { if (algorithm && !this.hullAlgorithms.hasOwnProperty(algorithm)) { // Ensure the passed algorithm is valid. return; } this.hullAlgorithm = this.hullAlgorithms[algorithm]; } }; })();
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v4.0.6 * @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 gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var context_1 = require("../context/context"); var context_2 = require("../context/context"); var svgFactory = svgFactory_1.SvgFactory.getInstance(); var HeaderTemplateLoader = (function () { function HeaderTemplateLoader() { } HeaderTemplateLoader.prototype.createHeaderElement = function (column) { var params = { column: column, colDef: column.getColDef, context: this.gridOptionsWrapper.getContext(), api: this.gridOptionsWrapper.getApi() }; // option 1 - see if user provided a template in colDef var userProvidedTemplate = column.getColDef().headerCellTemplate; if (typeof userProvidedTemplate === 'function') { var colDefFunc = userProvidedTemplate; userProvidedTemplate = colDefFunc(params); } // option 2 - check the gridOptions for cellTemplate if (!userProvidedTemplate && this.gridOptionsWrapper.getHeaderCellTemplate()) { userProvidedTemplate = this.gridOptionsWrapper.getHeaderCellTemplate(); } // option 3 - check the gridOptions for templateFunction if (!userProvidedTemplate && this.gridOptionsWrapper.getHeaderCellTemplateFunc()) { var gridOptionsFunc = this.gridOptionsWrapper.getHeaderCellTemplateFunc(); userProvidedTemplate = gridOptionsFunc(params); } // finally, if still no template, use the default if (!userProvidedTemplate) { userProvidedTemplate = this.createDefaultHeaderElement(column); } // template can be a string or a dom element, if string we need to convert to a dom element var result; if (typeof userProvidedTemplate === 'string') { result = utils_1.Utils.loadTemplate(userProvidedTemplate); } else if (utils_1.Utils.isNodeOrElement(userProvidedTemplate)) { result = userProvidedTemplate; } else { console.error('ag-Grid: header template must be a string or an HTML element'); } return result; }; HeaderTemplateLoader.prototype.createDefaultHeaderElement = function (column) { var eTemplate = utils_1.Utils.loadTemplate(HeaderTemplateLoader.HEADER_CELL_TEMPLATE); this.addInIcon(eTemplate, 'sortAscending', '#agSortAsc', column, svgFactory.createArrowUpSvg); this.addInIcon(eTemplate, 'sortDescending', '#agSortDesc', column, svgFactory.createArrowDownSvg); this.addInIcon(eTemplate, 'sortUnSort', '#agNoSort', column, svgFactory.createArrowUpDownSvg); this.addInIcon(eTemplate, 'menu', '#agMenu', column, svgFactory.createMenuSvg); this.addInIcon(eTemplate, 'filter', '#agFilter', column, svgFactory.createFilterSvg); return eTemplate; }; HeaderTemplateLoader.prototype.addInIcon = function (eTemplate, iconName, cssSelector, column, defaultIconFactory) { var eIcon = utils_1.Utils.createIconNoSpan(iconName, this.gridOptionsWrapper, column, defaultIconFactory); eTemplate.querySelector(cssSelector).appendChild(eIcon); }; // used when cell is dragged HeaderTemplateLoader.HEADER_CELL_DND_TEMPLATE = '<div class="ag-header-cell ag-header-cell-ghost">' + ' <span id="eGhostIcon" class="ag-header-cell-ghost-icon ag-shake-left-to-right"></span>' + ' <div id="agHeaderCellLabel" class="ag-header-cell-label">' + ' <span id="agText" class="ag-header-cell-text"></span>' + ' </div>' + '</div>'; HeaderTemplateLoader.HEADER_CELL_TEMPLATE = '<div class="ag-header-cell">' + ' <div id="agResizeBar" class="ag-header-cell-resize"></div>' + ' <span id="agMenu" class="ag-header-icon ag-header-cell-menu-button"></span>' + ' <div id="agHeaderCellLabel" class="ag-header-cell-label">' + ' <span id="agSortAsc" class="ag-header-icon ag-sort-ascending-icon"></span>' + ' <span id="agSortDesc" class="ag-header-icon ag-sort-descending-icon"></span>' + ' <span id="agNoSort" class="ag-header-icon ag-sort-none-icon"></span>' + ' <span id="agFilter" class="ag-header-icon ag-filter-icon"></span>' + ' <span id="agText" class="ag-header-cell-text"></span>' + ' </div>' + '</div>'; __decorate([ context_2.Autowired('gridOptionsWrapper'), __metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper) ], HeaderTemplateLoader.prototype, "gridOptionsWrapper", void 0); HeaderTemplateLoader = __decorate([ context_1.Bean('headerTemplateLoader'), __metadata('design:paramtypes', []) ], HeaderTemplateLoader); return HeaderTemplateLoader; })(); exports.HeaderTemplateLoader = HeaderTemplateLoader;
(function () { 'use strict'; // Must configure the common service and set its // events via the commonConfigProvider angular.module('common') .factory('spinner', ['common', 'commonConfig', spinner]); function spinner(common, commonConfig) { var service = { spinnerHide: spinnerHide, spinnerShow: spinnerShow }; return service; function spinnerHide() { spinnerToggle(false); } function spinnerShow() { spinnerToggle(true); } function spinnerToggle(show) { common.$broadcast(commonConfig.config.spinnerToggleEvent, { show: show }); } } })();
/*! ======================================================= VERSION 9.2.2 ========================================================= */ "use strict"; function _typeof(obj) { return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; } /*! ========================================================= * bootstrap-slider.js * * Maintainers: * Kyle Kemp * - Twitter: @seiyria * - Github: seiyria * Rohit Kalkur * - Twitter: @Rovolutionary * - Github: rovolution * * ========================================================= * * 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. * ========================================================= */ /** * Bridget makes jQuery widgets * v1.0.1 * MIT license */ var windowIsDefined = (typeof window === "undefined" ? "undefined" : _typeof(window)) === "object"; (function (factory) { if (typeof define === "function" && define.amd) { define(["jquery"], factory); } else if ((typeof module === "undefined" ? "undefined" : _typeof(module)) === "object" && module.exports) { var jQuery; try { jQuery = require("jquery"); } catch (err) { jQuery = null; } module.exports = factory(jQuery); } else if (window) { window.Slider = factory(window.jQuery); } })(function ($) { // Constants var NAMESPACE_MAIN = 'slider'; var NAMESPACE_ALTERNATE = 'bootstrapSlider'; // Polyfill console methods if (windowIsDefined && !window.console) { window.console = {}; } if (windowIsDefined && !window.console.log) { window.console.log = function () {}; } if (windowIsDefined && !window.console.warn) { window.console.warn = function () {}; } // Reference to Slider constructor var Slider; (function ($) { 'use strict'; // -------------------------- utils -------------------------- // var slice = Array.prototype.slice; function noop() {} // -------------------------- definition -------------------------- // function defineBridget($) { // bail if no jQuery if (!$) { return; } // -------------------------- addOptionMethod -------------------------- // /** * adds option method -> $().plugin('option', {...}) * @param {Function} PluginClass - constructor class */ function addOptionMethod(PluginClass) { // don't overwrite original option method if (PluginClass.prototype.option) { return; } // option setter PluginClass.prototype.option = function (opts) { // bail out if not an object if (!$.isPlainObject(opts)) { return; } this.options = $.extend(true, this.options, opts); }; } // -------------------------- plugin bridge -------------------------- // // helper function for logging errors // $.error breaks jQuery chaining var logError = typeof console === 'undefined' ? noop : function (message) { console.error(message); }; /** * jQuery plugin bridge, access methods like $elem.plugin('method') * @param {String} namespace - plugin name * @param {Function} PluginClass - constructor class */ function bridge(namespace, PluginClass) { // add to jQuery fn namespace $.fn[namespace] = function (options) { if (typeof options === 'string') { // call plugin method when first argument is a string // get arguments for method var args = slice.call(arguments, 1); for (var i = 0, len = this.length; i < len; i++) { var elem = this[i]; var instance = $.data(elem, namespace); if (!instance) { logError("cannot call methods on " + namespace + " prior to initialization; " + "attempted to call '" + options + "'"); continue; } if (!$.isFunction(instance[options]) || options.charAt(0) === '_') { logError("no such method '" + options + "' for " + namespace + " instance"); continue; } // trigger method with arguments var returnValue = instance[options].apply(instance, args); // break look and return first value if provided if (returnValue !== undefined && returnValue !== instance) { return returnValue; } } // return this if no return value return this; } else { var objects = this.map(function () { var instance = $.data(this, namespace); if (instance) { // apply options & init instance.option(options); instance._init(); } else { // initialize new instance instance = new PluginClass(this, options); $.data(this, namespace, instance); } return $(this); }); if (!objects || objects.length > 1) { return objects; } else { return objects[0]; } } }; } // -------------------------- bridget -------------------------- // /** * converts a Prototypical class into a proper jQuery plugin * the class must have a ._init method * @param {String} namespace - plugin name, used in $().pluginName * @param {Function} PluginClass - constructor class */ $.bridget = function (namespace, PluginClass) { addOptionMethod(PluginClass); bridge(namespace, PluginClass); }; return $.bridget; } // get jquery from browser global defineBridget($); })($); /************************************************* BOOTSTRAP-SLIDER SOURCE CODE **************************************************/ (function ($) { var ErrorMsgs = { formatInvalidInputErrorMsg: function formatInvalidInputErrorMsg(input) { return "Invalid input value '" + input + "' passed in"; }, callingContextNotSliderInstance: "Calling context element does not have instance of Slider bound to it. Check your code to make sure the JQuery object returned from the call to the slider() initializer is calling the method" }; var SliderScale = { linear: { toValue: function toValue(percentage) { var rawValue = percentage / 100 * (this.options.max - this.options.min); var shouldAdjustWithBase = true; if (this.options.ticks_positions.length > 0) { var minv, maxv, minp, maxp = 0; for (var i = 1; i < this.options.ticks_positions.length; i++) { if (percentage <= this.options.ticks_positions[i]) { minv = this.options.ticks[i - 1]; minp = this.options.ticks_positions[i - 1]; maxv = this.options.ticks[i]; maxp = this.options.ticks_positions[i]; break; } } var partialPercentage = (percentage - minp) / (maxp - minp); rawValue = minv + partialPercentage * (maxv - minv); shouldAdjustWithBase = false; } var adjustment = shouldAdjustWithBase ? this.options.min : 0; var value = adjustment + Math.round(rawValue / this.options.step) * this.options.step; if (value < this.options.min) { return this.options.min; } else if (value > this.options.max) { return this.options.max; } else { return value; } }, toPercentage: function toPercentage(value) { if (this.options.max === this.options.min) { return 0; } if (this.options.ticks_positions.length > 0) { var minv, maxv, minp, maxp = 0; for (var i = 0; i < this.options.ticks.length; i++) { if (value <= this.options.ticks[i]) { minv = i > 0 ? this.options.ticks[i - 1] : 0; minp = i > 0 ? this.options.ticks_positions[i - 1] : 0; maxv = this.options.ticks[i]; maxp = this.options.ticks_positions[i]; break; } } if (i > 0) { var partialPercentage = (value - minv) / (maxv - minv); return minp + partialPercentage * (maxp - minp); } } return 100 * (value - this.options.min) / (this.options.max - this.options.min); } }, logarithmic: { /* Based on http://stackoverflow.com/questions/846221/logarithmic-slider */ toValue: function toValue(percentage) { var min = this.options.min === 0 ? 0 : Math.log(this.options.min); var max = Math.log(this.options.max); var value = Math.exp(min + (max - min) * percentage / 100); value = this.options.min + Math.round((value - this.options.min) / this.options.step) * this.options.step; /* Rounding to the nearest step could exceed the min or * max, so clip to those values. */ if (value < this.options.min) { return this.options.min; } else if (value > this.options.max) { return this.options.max; } else { return value; } }, toPercentage: function toPercentage(value) { if (this.options.max === this.options.min) { return 0; } else { var max = Math.log(this.options.max); var min = this.options.min === 0 ? 0 : Math.log(this.options.min); var v = value === 0 ? 0 : Math.log(value); return 100 * (v - min) / (max - min); } } } }; /************************************************* CONSTRUCTOR **************************************************/ Slider = function (element, options) { createNewSlider.call(this, element, options); return this; }; function createNewSlider(element, options) { /* The internal state object is used to store data about the current 'state' of slider. This includes values such as the `value`, `enabled`, etc... */ this._state = { value: null, enabled: null, offset: null, size: null, percentage: null, inDrag: false, over: false }; if (typeof element === "string") { this.element = document.querySelector(element); } else if (element instanceof HTMLElement) { this.element = element; } /************************************************* Process Options **************************************************/ options = options ? options : {}; var optionTypes = Object.keys(this.defaultOptions); for (var i = 0; i < optionTypes.length; i++) { var optName = optionTypes[i]; // First check if an option was passed in via the constructor var val = options[optName]; // If no data attrib, then check data atrributes val = typeof val !== 'undefined' ? val : getDataAttrib(this.element, optName); // Finally, if nothing was specified, use the defaults val = val !== null ? val : this.defaultOptions[optName]; // Set all options on the instance of the Slider if (!this.options) { this.options = {}; } this.options[optName] = val; } /* Validate `tooltip_position` against 'orientation` - if `tooltip_position` is incompatible with orientation, swith it to a default compatible with specified `orientation` -- default for "vertical" -> "right" -- default for "horizontal" -> "left" */ if (this.options.orientation === "vertical" && (this.options.tooltip_position === "top" || this.options.tooltip_position === "bottom")) { this.options.tooltip_position = "right"; } else if (this.options.orientation === "horizontal" && (this.options.tooltip_position === "left" || this.options.tooltip_position === "right")) { this.options.tooltip_position = "top"; } function getDataAttrib(element, optName) { var dataName = "data-slider-" + optName.replace(/_/g, '-'); var dataValString = element.getAttribute(dataName); try { return JSON.parse(dataValString); } catch (err) { return dataValString; } } /************************************************* Create Markup **************************************************/ var origWidth = this.element.style.width; var updateSlider = false; var parent = this.element.parentNode; var sliderTrackSelection; var sliderTrackLow, sliderTrackHigh; var sliderMinHandle; var sliderMaxHandle; if (this.sliderElem) { updateSlider = true; } else { /* Create elements needed for slider */ this.sliderElem = document.createElement("div"); this.sliderElem.className = "slider"; /* Create slider track elements */ var sliderTrack = document.createElement("div"); sliderTrack.className = "slider-track"; sliderTrackLow = document.createElement("div"); sliderTrackLow.className = "slider-track-low"; sliderTrackSelection = document.createElement("div"); sliderTrackSelection.className = "slider-selection"; sliderTrackHigh = document.createElement("div"); sliderTrackHigh.className = "slider-track-high"; sliderMinHandle = document.createElement("div"); sliderMinHandle.className = "slider-handle min-slider-handle"; sliderMinHandle.setAttribute('role', 'slider'); sliderMinHandle.setAttribute('aria-valuemin', this.options.min); sliderMinHandle.setAttribute('aria-valuemax', this.options.max); sliderMaxHandle = document.createElement("div"); sliderMaxHandle.className = "slider-handle max-slider-handle"; sliderMaxHandle.setAttribute('role', 'slider'); sliderMaxHandle.setAttribute('aria-valuemin', this.options.min); sliderMaxHandle.setAttribute('aria-valuemax', this.options.max); sliderTrack.appendChild(sliderTrackLow); sliderTrack.appendChild(sliderTrackSelection); sliderTrack.appendChild(sliderTrackHigh); /* Create highlight range elements */ this.rangeHighlightElements = []; if (Array.isArray(this.options.rangeHighlights) && this.options.rangeHighlights.length > 0) { for (var j = 0; j < this.options.rangeHighlights.length; j++) { var rangeHighlightElement = document.createElement("div"); rangeHighlightElement.className = "slider-rangeHighlight slider-selection"; this.rangeHighlightElements.push(rangeHighlightElement); sliderTrack.appendChild(rangeHighlightElement); } } /* Add aria-labelledby to handle's */ var isLabelledbyArray = Array.isArray(this.options.labelledby); if (isLabelledbyArray && this.options.labelledby[0]) { sliderMinHandle.setAttribute('aria-labelledby', this.options.labelledby[0]); } if (isLabelledbyArray && this.options.labelledby[1]) { sliderMaxHandle.setAttribute('aria-labelledby', this.options.labelledby[1]); } if (!isLabelledbyArray && this.options.labelledby) { sliderMinHandle.setAttribute('aria-labelledby', this.options.labelledby); sliderMaxHandle.setAttribute('aria-labelledby', this.options.labelledby); } /* Create ticks */ this.ticks = []; if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) { this.ticksContainer = document.createElement('div'); this.ticksContainer.className = 'slider-tick-container'; for (i = 0; i < this.options.ticks.length; i++) { var tick = document.createElement('div'); tick.className = 'slider-tick'; this.ticks.push(tick); this.ticksContainer.appendChild(tick); } sliderTrackSelection.className += " tick-slider-selection"; } this.tickLabels = []; if (Array.isArray(this.options.ticks_labels) && this.options.ticks_labels.length > 0) { this.tickLabelContainer = document.createElement('div'); this.tickLabelContainer.className = 'slider-tick-label-container'; for (i = 0; i < this.options.ticks_labels.length; i++) { var label = document.createElement('div'); var noTickPositionsSpecified = this.options.ticks_positions.length === 0; var tickLabelsIndex = this.options.reversed && noTickPositionsSpecified ? this.options.ticks_labels.length - (i + 1) : i; label.className = 'slider-tick-label'; label.innerHTML = this.options.ticks_labels[tickLabelsIndex]; this.tickLabels.push(label); this.tickLabelContainer.appendChild(label); } } var createAndAppendTooltipSubElements = function createAndAppendTooltipSubElements(tooltipElem) { var arrow = document.createElement("div"); arrow.className = "tooltip-arrow"; var inner = document.createElement("div"); inner.className = "tooltip-inner"; tooltipElem.appendChild(arrow); tooltipElem.appendChild(inner); }; /* Create tooltip elements */ var sliderTooltip = document.createElement("div"); sliderTooltip.className = "tooltip tooltip-main"; sliderTooltip.setAttribute('role', 'presentation'); createAndAppendTooltipSubElements(sliderTooltip); var sliderTooltipMin = document.createElement("div"); sliderTooltipMin.className = "tooltip tooltip-min"; sliderTooltipMin.setAttribute('role', 'presentation'); createAndAppendTooltipSubElements(sliderTooltipMin); var sliderTooltipMax = document.createElement("div"); sliderTooltipMax.className = "tooltip tooltip-max"; sliderTooltipMax.setAttribute('role', 'presentation'); createAndAppendTooltipSubElements(sliderTooltipMax); /* Append components to sliderElem */ this.sliderElem.appendChild(sliderTrack); this.sliderElem.appendChild(sliderTooltip); this.sliderElem.appendChild(sliderTooltipMin); this.sliderElem.appendChild(sliderTooltipMax); if (this.tickLabelContainer) { this.sliderElem.appendChild(this.tickLabelContainer); } if (this.ticksContainer) { this.sliderElem.appendChild(this.ticksContainer); } this.sliderElem.appendChild(sliderMinHandle); this.sliderElem.appendChild(sliderMaxHandle); /* Append slider element to parent container, right before the original <input> element */ parent.insertBefore(this.sliderElem, this.element); /* Hide original <input> element */ this.element.style.display = "none"; } /* If JQuery exists, cache JQ references */ if ($) { this.$element = $(this.element); this.$sliderElem = $(this.sliderElem); } /************************************************* Setup **************************************************/ this.eventToCallbackMap = {}; this.sliderElem.id = this.options.id; this.touchCapable = 'ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch; this.touchX = 0; this.touchY = 0; this.tooltip = this.sliderElem.querySelector('.tooltip-main'); this.tooltipInner = this.tooltip.querySelector('.tooltip-inner'); this.tooltip_min = this.sliderElem.querySelector('.tooltip-min'); this.tooltipInner_min = this.tooltip_min.querySelector('.tooltip-inner'); this.tooltip_max = this.sliderElem.querySelector('.tooltip-max'); this.tooltipInner_max = this.tooltip_max.querySelector('.tooltip-inner'); if (SliderScale[this.options.scale]) { this.options.scale = SliderScale[this.options.scale]; } if (updateSlider === true) { // Reset classes this._removeClass(this.sliderElem, 'slider-horizontal'); this._removeClass(this.sliderElem, 'slider-vertical'); this._removeClass(this.tooltip, 'hide'); this._removeClass(this.tooltip_min, 'hide'); this._removeClass(this.tooltip_max, 'hide'); // Undo existing inline styles for track ["left", "top", "width", "height"].forEach(function (prop) { this._removeProperty(this.trackLow, prop); this._removeProperty(this.trackSelection, prop); this._removeProperty(this.trackHigh, prop); }, this); // Undo inline styles on handles [this.handle1, this.handle2].forEach(function (handle) { this._removeProperty(handle, 'left'); this._removeProperty(handle, 'top'); }, this); // Undo inline styles and classes on tooltips [this.tooltip, this.tooltip_min, this.tooltip_max].forEach(function (tooltip) { this._removeProperty(tooltip, 'left'); this._removeProperty(tooltip, 'top'); this._removeProperty(tooltip, 'margin-left'); this._removeProperty(tooltip, 'margin-top'); this._removeClass(tooltip, 'right'); this._removeClass(tooltip, 'top'); }, this); } if (this.options.orientation === 'vertical') { this._addClass(this.sliderElem, 'slider-vertical'); this.stylePos = 'top'; this.mousePos = 'pageY'; this.sizePos = 'offsetHeight'; } else { this._addClass(this.sliderElem, 'slider-horizontal'); this.sliderElem.style.width = origWidth; this.options.orientation = 'horizontal'; this.stylePos = 'left'; this.mousePos = 'pageX'; this.sizePos = 'offsetWidth'; } this._setTooltipPosition(); /* In case ticks are specified, overwrite the min and max bounds */ if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) { this.options.max = Math.max.apply(Math, this.options.ticks); this.options.min = Math.min.apply(Math, this.options.ticks); } if (Array.isArray(this.options.value)) { this.options.range = true; this._state.value = this.options.value; } else if (this.options.range) { // User wants a range, but value is not an array this._state.value = [this.options.value, this.options.max]; } else { this._state.value = this.options.value; } this.trackLow = sliderTrackLow || this.trackLow; this.trackSelection = sliderTrackSelection || this.trackSelection; this.trackHigh = sliderTrackHigh || this.trackHigh; if (this.options.selection === 'none') { this._addClass(this.trackLow, 'hide'); this._addClass(this.trackSelection, 'hide'); this._addClass(this.trackHigh, 'hide'); } this.handle1 = sliderMinHandle || this.handle1; this.handle2 = sliderMaxHandle || this.handle2; if (updateSlider === true) { // Reset classes this._removeClass(this.handle1, 'round triangle'); this._removeClass(this.handle2, 'round triangle hide'); for (i = 0; i < this.ticks.length; i++) { this._removeClass(this.ticks[i], 'round triangle hide'); } } var availableHandleModifiers = ['round', 'triangle', 'custom']; var isValidHandleType = availableHandleModifiers.indexOf(this.options.handle) !== -1; if (isValidHandleType) { this._addClass(this.handle1, this.options.handle); this._addClass(this.handle2, this.options.handle); for (i = 0; i < this.ticks.length; i++) { this._addClass(this.ticks[i], this.options.handle); } } this._state.offset = this._offset(this.sliderElem); this._state.size = this.sliderElem[this.sizePos]; this.setValue(this._state.value); /****************************************** Bind Event Listeners ******************************************/ // Bind keyboard handlers this.handle1Keydown = this._keydown.bind(this, 0); this.handle1.addEventListener("keydown", this.handle1Keydown, false); this.handle2Keydown = this._keydown.bind(this, 1); this.handle2.addEventListener("keydown", this.handle2Keydown, false); this.mousedown = this._mousedown.bind(this); this.touchstart = this._touchstart.bind(this); this.touchmove = this._touchmove.bind(this); if (this.touchCapable) { // Bind touch handlers this.sliderElem.addEventListener("touchstart", this.touchstart, false); this.sliderElem.addEventListener("touchmove", this.touchmove, false); } this.sliderElem.addEventListener("mousedown", this.mousedown, false); // Bind window handlers this.resize = this._resize.bind(this); window.addEventListener("resize", this.resize, false); // Bind tooltip-related handlers if (this.options.tooltip === 'hide') { this._addClass(this.tooltip, 'hide'); this._addClass(this.tooltip_min, 'hide'); this._addClass(this.tooltip_max, 'hide'); } else if (this.options.tooltip === 'always') { this._showTooltip(); this._alwaysShowTooltip = true; } else { this.showTooltip = this._showTooltip.bind(this); this.hideTooltip = this._hideTooltip.bind(this); this.sliderElem.addEventListener("mouseenter", this.showTooltip, false); this.sliderElem.addEventListener("mouseleave", this.hideTooltip, false); this.handle1.addEventListener("focus", this.showTooltip, false); this.handle1.addEventListener("blur", this.hideTooltip, false); this.handle2.addEventListener("focus", this.showTooltip, false); this.handle2.addEventListener("blur", this.hideTooltip, false); } if (this.options.enabled) { this.enable(); } else { this.disable(); } } /************************************************* INSTANCE PROPERTIES/METHODS - Any methods bound to the prototype are considered part of the plugin's `public` interface **************************************************/ Slider.prototype = { _init: function _init() {}, // NOTE: Must exist to support bridget constructor: Slider, defaultOptions: { id: "", min: 0, max: 10, step: 1, precision: 0, orientation: 'horizontal', value: 5, range: false, selection: 'before', tooltip: 'show', tooltip_split: false, handle: 'round', reversed: false, enabled: true, formatter: function formatter(val) { if (Array.isArray(val)) { return val[0] + " : " + val[1]; } else { return val; } }, natural_arrow_keys: false, ticks: [], ticks_positions: [], ticks_labels: [], ticks_snap_bounds: 0, scale: 'linear', focus: false, tooltip_position: null, labelledby: null, rangeHighlights: [] }, getElement: function getElement() { return this.sliderElem; }, getValue: function getValue() { if (this.options.range) { return this._state.value; } else { return this._state.value[0]; } }, setValue: function setValue(val, triggerSlideEvent, triggerChangeEvent) { if (!val) { val = 0; } var oldValue = this.getValue(); this._state.value = this._validateInputValue(val); var applyPrecision = this._applyPrecision.bind(this); if (this.options.range) { this._state.value[0] = applyPrecision(this._state.value[0]); this._state.value[1] = applyPrecision(this._state.value[1]); this._state.value[0] = Math.max(this.options.min, Math.min(this.options.max, this._state.value[0])); this._state.value[1] = Math.max(this.options.min, Math.min(this.options.max, this._state.value[1])); } else { this._state.value = applyPrecision(this._state.value); this._state.value = [Math.max(this.options.min, Math.min(this.options.max, this._state.value))]; this._addClass(this.handle2, 'hide'); if (this.options.selection === 'after') { this._state.value[1] = this.options.max; } else { this._state.value[1] = this.options.min; } } if (this.options.max > this.options.min) { this._state.percentage = [this._toPercentage(this._state.value[0]), this._toPercentage(this._state.value[1]), this.options.step * 100 / (this.options.max - this.options.min)]; } else { this._state.percentage = [0, 0, 100]; } this._layout(); var newValue = this.options.range ? this._state.value : this._state.value[0]; this._setDataVal(newValue); if (triggerSlideEvent === true) { this._trigger('slide', newValue); } if (oldValue !== newValue && triggerChangeEvent === true) { this._trigger('change', { oldValue: oldValue, newValue: newValue }); } return this; }, destroy: function destroy() { // Remove event handlers on slider elements this._removeSliderEventHandlers(); // Remove the slider from the DOM this.sliderElem.parentNode.removeChild(this.sliderElem); /* Show original <input> element */ this.element.style.display = ""; // Clear out custom event bindings this._cleanUpEventCallbacksMap(); // Remove data values this.element.removeAttribute("data"); // Remove JQuery handlers/data if ($) { this._unbindJQueryEventHandlers(); this.$element.removeData('slider'); } }, disable: function disable() { this._state.enabled = false; this.handle1.removeAttribute("tabindex"); this.handle2.removeAttribute("tabindex"); this._addClass(this.sliderElem, 'slider-disabled'); this._trigger('slideDisabled'); return this; }, enable: function enable() { this._state.enabled = true; this.handle1.setAttribute("tabindex", 0); this.handle2.setAttribute("tabindex", 0); this._removeClass(this.sliderElem, 'slider-disabled'); this._trigger('slideEnabled'); return this; }, toggle: function toggle() { if (this._state.enabled) { this.disable(); } else { this.enable(); } return this; }, isEnabled: function isEnabled() { return this._state.enabled; }, on: function on(evt, callback) { this._bindNonQueryEventHandler(evt, callback); return this; }, off: function off(evt, callback) { if ($) { this.$element.off(evt, callback); this.$sliderElem.off(evt, callback); } else { this._unbindNonQueryEventHandler(evt, callback); } }, getAttribute: function getAttribute(attribute) { if (attribute) { return this.options[attribute]; } else { return this.options; } }, setAttribute: function setAttribute(attribute, value) { this.options[attribute] = value; return this; }, refresh: function refresh() { this._removeSliderEventHandlers(); createNewSlider.call(this, this.element, this.options); if ($) { // Bind new instance of slider to the element $.data(this.element, 'slider', this); } return this; }, relayout: function relayout() { this._resize(); this._layout(); return this; }, /******************************+ HELPERS - Any method that is not part of the public interface. - Place it underneath this comment block and write its signature like so: _fnName : function() {...} ********************************/ _removeSliderEventHandlers: function _removeSliderEventHandlers() { // Remove keydown event listeners this.handle1.removeEventListener("keydown", this.handle1Keydown, false); this.handle2.removeEventListener("keydown", this.handle2Keydown, false); if (this.showTooltip) { this.handle1.removeEventListener("focus", this.showTooltip, false); this.handle2.removeEventListener("focus", this.showTooltip, false); } if (this.hideTooltip) { this.handle1.removeEventListener("blur", this.hideTooltip, false); this.handle2.removeEventListener("blur", this.hideTooltip, false); } // Remove event listeners from sliderElem if (this.showTooltip) { this.sliderElem.removeEventListener("mouseenter", this.showTooltip, false); } if (this.hideTooltip) { this.sliderElem.removeEventListener("mouseleave", this.hideTooltip, false); } this.sliderElem.removeEventListener("touchstart", this.touchstart, false); this.sliderElem.removeEventListener("touchmove", this.touchmove, false); this.sliderElem.removeEventListener("mousedown", this.mousedown, false); // Remove window event listener window.removeEventListener("resize", this.resize, false); }, _bindNonQueryEventHandler: function _bindNonQueryEventHandler(evt, callback) { if (this.eventToCallbackMap[evt] === undefined) { this.eventToCallbackMap[evt] = []; } this.eventToCallbackMap[evt].push(callback); }, _unbindNonQueryEventHandler: function _unbindNonQueryEventHandler(evt, callback) { var callbacks = this.eventToCallbackMap[evt]; if (callbacks !== undefined) { for (var i = 0; i < callbacks.length; i++) { if (callbacks[i] === callback) { callbacks.splice(i, 1); break; } } } }, _cleanUpEventCallbacksMap: function _cleanUpEventCallbacksMap() { var eventNames = Object.keys(this.eventToCallbackMap); for (var i = 0; i < eventNames.length; i++) { var eventName = eventNames[i]; this.eventToCallbackMap[eventName] = null; } }, _showTooltip: function _showTooltip() { if (this.options.tooltip_split === false) { this._addClass(this.tooltip, 'in'); this.tooltip_min.style.display = 'none'; this.tooltip_max.style.display = 'none'; } else { this._addClass(this.tooltip_min, 'in'); this._addClass(this.tooltip_max, 'in'); this.tooltip.style.display = 'none'; } this._state.over = true; }, _hideTooltip: function _hideTooltip() { if (this._state.inDrag === false && this.alwaysShowTooltip !== true) { this._removeClass(this.tooltip, 'in'); this._removeClass(this.tooltip_min, 'in'); this._removeClass(this.tooltip_max, 'in'); } this._state.over = false; }, _layout: function _layout() { var positionPercentages; if (this.options.reversed) { positionPercentages = [100 - this._state.percentage[0], this.options.range ? 100 - this._state.percentage[1] : this._state.percentage[1]]; } else { positionPercentages = [this._state.percentage[0], this._state.percentage[1]]; } this.handle1.style[this.stylePos] = positionPercentages[0] + '%'; this.handle1.setAttribute('aria-valuenow', this._state.value[0]); this.handle2.style[this.stylePos] = positionPercentages[1] + '%'; this.handle2.setAttribute('aria-valuenow', this._state.value[1]); /* Position highlight range elements */ if (this.rangeHighlightElements.length > 0 && Array.isArray(this.options.rangeHighlights) && this.options.rangeHighlights.length > 0) { for (var _i = 0; _i < this.options.rangeHighlights.length; _i++) { var startPercent = this._toPercentage(this.options.rangeHighlights[_i].start); var endPercent = this._toPercentage(this.options.rangeHighlights[_i].end); if (this.options.reversed) { var sp = 100 - endPercent; endPercent = 100 - startPercent; startPercent = sp; } var currentRange = this._createHighlightRange(startPercent, endPercent); if (currentRange) { if (this.options.orientation === 'vertical') { this.rangeHighlightElements[_i].style.top = currentRange.start + "%"; this.rangeHighlightElements[_i].style.height = currentRange.size + "%"; } else { this.rangeHighlightElements[_i].style.left = currentRange.start + "%"; this.rangeHighlightElements[_i].style.width = currentRange.size + "%"; } } else { this.rangeHighlightElements[_i].style.display = "none"; } } } /* Position ticks and labels */ if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) { var styleSize = this.options.orientation === 'vertical' ? 'height' : 'width'; var styleMargin = this.options.orientation === 'vertical' ? 'marginTop' : 'marginLeft'; var labelSize = this._state.size / (this.options.ticks.length - 1); if (this.tickLabelContainer) { var extraMargin = 0; if (this.options.ticks_positions.length === 0) { if (this.options.orientation !== 'vertical') { this.tickLabelContainer.style[styleMargin] = -labelSize / 2 + 'px'; } extraMargin = this.tickLabelContainer.offsetHeight; } else { /* Chidren are position absolute, calculate height by finding the max offsetHeight of a child */ for (i = 0; i < this.tickLabelContainer.childNodes.length; i++) { if (this.tickLabelContainer.childNodes[i].offsetHeight > extraMargin) { extraMargin = this.tickLabelContainer.childNodes[i].offsetHeight; } } } if (this.options.orientation === 'horizontal') { this.sliderElem.style.marginBottom = extraMargin + 'px'; } } for (var i = 0; i < this.options.ticks.length; i++) { var percentage = this.options.ticks_positions[i] || this._toPercentage(this.options.ticks[i]); if (this.options.reversed) { percentage = 100 - percentage; } this.ticks[i].style[this.stylePos] = percentage + '%'; /* Set class labels to denote whether ticks are in the selection */ this._removeClass(this.ticks[i], 'in-selection'); if (!this.options.range) { if (this.options.selection === 'after' && percentage >= positionPercentages[0]) { this._addClass(this.ticks[i], 'in-selection'); } else if (this.options.selection === 'before' && percentage <= positionPercentages[0]) { this._addClass(this.ticks[i], 'in-selection'); } } else if (percentage >= positionPercentages[0] && percentage <= positionPercentages[1]) { this._addClass(this.ticks[i], 'in-selection'); } if (this.tickLabels[i]) { this.tickLabels[i].style[styleSize] = labelSize + 'px'; if (this.options.orientation !== 'vertical' && this.options.ticks_positions[i] !== undefined) { this.tickLabels[i].style.position = 'absolute'; this.tickLabels[i].style[this.stylePos] = percentage + '%'; this.tickLabels[i].style[styleMargin] = -labelSize / 2 + 'px'; } else if (this.options.orientation === 'vertical') { this.tickLabels[i].style['marginLeft'] = this.sliderElem.offsetWidth + 'px'; this.tickLabelContainer.style['marginTop'] = this.sliderElem.offsetWidth / 2 * -1 + 'px'; } } } } var formattedTooltipVal; if (this.options.range) { formattedTooltipVal = this.options.formatter(this._state.value); this._setText(this.tooltipInner, formattedTooltipVal); this.tooltip.style[this.stylePos] = (positionPercentages[1] + positionPercentages[0]) / 2 + '%'; if (this.options.orientation === 'vertical') { this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px'); } else { this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px'); } if (this.options.orientation === 'vertical') { this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px'); } else { this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px'); } var innerTooltipMinText = this.options.formatter(this._state.value[0]); this._setText(this.tooltipInner_min, innerTooltipMinText); var innerTooltipMaxText = this.options.formatter(this._state.value[1]); this._setText(this.tooltipInner_max, innerTooltipMaxText); this.tooltip_min.style[this.stylePos] = positionPercentages[0] + '%'; if (this.options.orientation === 'vertical') { this._css(this.tooltip_min, 'margin-top', -this.tooltip_min.offsetHeight / 2 + 'px'); } else { this._css(this.tooltip_min, 'margin-left', -this.tooltip_min.offsetWidth / 2 + 'px'); } this.tooltip_max.style[this.stylePos] = positionPercentages[1] + '%'; if (this.options.orientation === 'vertical') { this._css(this.tooltip_max, 'margin-top', -this.tooltip_max.offsetHeight / 2 + 'px'); } else { this._css(this.tooltip_max, 'margin-left', -this.tooltip_max.offsetWidth / 2 + 'px'); } } else { formattedTooltipVal = this.options.formatter(this._state.value[0]); this._setText(this.tooltipInner, formattedTooltipVal); this.tooltip.style[this.stylePos] = positionPercentages[0] + '%'; if (this.options.orientation === 'vertical') { this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px'); } else { this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px'); } } if (this.options.orientation === 'vertical') { this.trackLow.style.top = '0'; this.trackLow.style.height = Math.min(positionPercentages[0], positionPercentages[1]) + '%'; this.trackSelection.style.top = Math.min(positionPercentages[0], positionPercentages[1]) + '%'; this.trackSelection.style.height = Math.abs(positionPercentages[0] - positionPercentages[1]) + '%'; this.trackHigh.style.bottom = '0'; this.trackHigh.style.height = 100 - Math.min(positionPercentages[0], positionPercentages[1]) - Math.abs(positionPercentages[0] - positionPercentages[1]) + '%'; } else { this.trackLow.style.left = '0'; this.trackLow.style.width = Math.min(positionPercentages[0], positionPercentages[1]) + '%'; this.trackSelection.style.left = Math.min(positionPercentages[0], positionPercentages[1]) + '%'; this.trackSelection.style.width = Math.abs(positionPercentages[0] - positionPercentages[1]) + '%'; this.trackHigh.style.right = '0'; this.trackHigh.style.width = 100 - Math.min(positionPercentages[0], positionPercentages[1]) - Math.abs(positionPercentages[0] - positionPercentages[1]) + '%'; var offset_min = this.tooltip_min.getBoundingClientRect(); var offset_max = this.tooltip_max.getBoundingClientRect(); if (this.options.tooltip_position === 'bottom') { if (offset_min.right > offset_max.left) { this._removeClass(this.tooltip_max, 'bottom'); this._addClass(this.tooltip_max, 'top'); this.tooltip_max.style.top = ''; this.tooltip_max.style.bottom = 22 + 'px'; } else { this._removeClass(this.tooltip_max, 'top'); this._addClass(this.tooltip_max, 'bottom'); this.tooltip_max.style.top = this.tooltip_min.style.top; this.tooltip_max.style.bottom = ''; } } else { if (offset_min.right > offset_max.left) { this._removeClass(this.tooltip_max, 'top'); this._addClass(this.tooltip_max, 'bottom'); this.tooltip_max.style.top = 18 + 'px'; } else { this._removeClass(this.tooltip_max, 'bottom'); this._addClass(this.tooltip_max, 'top'); this.tooltip_max.style.top = this.tooltip_min.style.top; } } } }, _createHighlightRange: function _createHighlightRange(start, end) { if (this._isHighlightRange(start, end)) { if (start > end) { return { 'start': end, 'size': start - end }; } return { 'start': start, 'size': end - start }; } return null; }, _isHighlightRange: function _isHighlightRange(start, end) { if (0 <= start && start <= 100 && 0 <= end && end <= 100) { return true; } else { return false; } }, _resize: function _resize(ev) { /*jshint unused:false*/ this._state.offset = this._offset(this.sliderElem); this._state.size = this.sliderElem[this.sizePos]; this._layout(); }, _removeProperty: function _removeProperty(element, prop) { if (element.style.removeProperty) { element.style.removeProperty(prop); } else { element.style.removeAttribute(prop); } }, _mousedown: function _mousedown(ev) { if (!this._state.enabled) { return false; } this._state.offset = this._offset(this.sliderElem); this._state.size = this.sliderElem[this.sizePos]; var percentage = this._getPercentage(ev); if (this.options.range) { var diff1 = Math.abs(this._state.percentage[0] - percentage); var diff2 = Math.abs(this._state.percentage[1] - percentage); this._state.dragged = diff1 < diff2 ? 0 : 1; this._adjustPercentageForRangeSliders(percentage); } else { this._state.dragged = 0; } this._state.percentage[this._state.dragged] = percentage; this._layout(); if (this.touchCapable) { document.removeEventListener("touchmove", this.mousemove, false); document.removeEventListener("touchend", this.mouseup, false); } if (this.mousemove) { document.removeEventListener("mousemove", this.mousemove, false); } if (this.mouseup) { document.removeEventListener("mouseup", this.mouseup, false); } this.mousemove = this._mousemove.bind(this); this.mouseup = this._mouseup.bind(this); if (this.touchCapable) { // Touch: Bind touch events: document.addEventListener("touchmove", this.mousemove, false); document.addEventListener("touchend", this.mouseup, false); } // Bind mouse events: document.addEventListener("mousemove", this.mousemove, false); document.addEventListener("mouseup", this.mouseup, false); this._state.inDrag = true; var newValue = this._calculateValue(); this._trigger('slideStart', newValue); this._setDataVal(newValue); this.setValue(newValue, false, true); this._pauseEvent(ev); if (this.options.focus) { this._triggerFocusOnHandle(this._state.dragged); } return true; }, _touchstart: function _touchstart(ev) { if (ev.changedTouches === undefined) { this._mousedown(ev); return; } var touch = ev.changedTouches[0]; this.touchX = touch.pageX; this.touchY = touch.pageY; }, _triggerFocusOnHandle: function _triggerFocusOnHandle(handleIdx) { if (handleIdx === 0) { this.handle1.focus(); } if (handleIdx === 1) { this.handle2.focus(); } }, _keydown: function _keydown(handleIdx, ev) { if (!this._state.enabled) { return false; } var dir; switch (ev.keyCode) { case 37: // left case 40: // down dir = -1; break; case 39: // right case 38: // up dir = 1; break; } if (!dir) { return; } // use natural arrow keys instead of from min to max if (this.options.natural_arrow_keys) { var ifVerticalAndNotReversed = this.options.orientation === 'vertical' && !this.options.reversed; var ifHorizontalAndReversed = this.options.orientation === 'horizontal' && this.options.reversed; if (ifVerticalAndNotReversed || ifHorizontalAndReversed) { dir = -dir; } } var val = this._state.value[handleIdx] + dir * this.options.step; if (this.options.range) { val = [!handleIdx ? val : this._state.value[0], handleIdx ? val : this._state.value[1]]; } this._trigger('slideStart', val); this._setDataVal(val); this.setValue(val, true, true); this._setDataVal(val); this._trigger('slideStop', val); this._layout(); this._pauseEvent(ev); return false; }, _pauseEvent: function _pauseEvent(ev) { if (ev.stopPropagation) { ev.stopPropagation(); } if (ev.preventDefault) { ev.preventDefault(); } ev.cancelBubble = true; ev.returnValue = false; }, _mousemove: function _mousemove(ev) { if (!this._state.enabled) { return false; } var percentage = this._getPercentage(ev); this._adjustPercentageForRangeSliders(percentage); this._state.percentage[this._state.dragged] = percentage; this._layout(); var val = this._calculateValue(true); this.setValue(val, true, true); return false; }, _touchmove: function _touchmove(ev) { if (ev.changedTouches === undefined) { return; } var touch = ev.changedTouches[0]; var xDiff = touch.pageX - this.touchX; var yDiff = touch.pageY - this.touchY; if (!this._state.inDrag) { // Vertical Slider if (this.options.orientation === 'vertical' && xDiff <= 5 && xDiff >= -5 && (yDiff >= 15 || yDiff <= -15)) { this._mousedown(ev); } // Horizontal slider. else if (yDiff <= 5 && yDiff >= -5 && (xDiff >= 15 || xDiff <= -15)) { this._mousedown(ev); } } }, _adjustPercentageForRangeSliders: function _adjustPercentageForRangeSliders(percentage) { if (this.options.range) { var precision = this._getNumDigitsAfterDecimalPlace(percentage); precision = precision ? precision - 1 : 0; var percentageWithAdjustedPrecision = this._applyToFixedAndParseFloat(percentage, precision); if (this._state.dragged === 0 && this._applyToFixedAndParseFloat(this._state.percentage[1], precision) < percentageWithAdjustedPrecision) { this._state.percentage[0] = this._state.percentage[1]; this._state.dragged = 1; } else if (this._state.dragged === 1 && this._applyToFixedAndParseFloat(this._state.percentage[0], precision) > percentageWithAdjustedPrecision) { this._state.percentage[1] = this._state.percentage[0]; this._state.dragged = 0; } } }, _mouseup: function _mouseup() { if (!this._state.enabled) { return false; } if (this.touchCapable) { // Touch: Unbind touch event handlers: document.removeEventListener("touchmove", this.mousemove, false); document.removeEventListener("touchend", this.mouseup, false); } // Unbind mouse event handlers: document.removeEventListener("mousemove", this.mousemove, false); document.removeEventListener("mouseup", this.mouseup, false); this._state.inDrag = false; if (this._state.over === false) { this._hideTooltip(); } var val = this._calculateValue(true); this._layout(); this._setDataVal(val); this._trigger('slideStop', val); return false; }, _calculateValue: function _calculateValue(snapToClosestTick) { var val; if (this.options.range) { val = [this.options.min, this.options.max]; if (this._state.percentage[0] !== 0) { val[0] = this._toValue(this._state.percentage[0]); val[0] = this._applyPrecision(val[0]); } if (this._state.percentage[1] !== 100) { val[1] = this._toValue(this._state.percentage[1]); val[1] = this._applyPrecision(val[1]); } } else { val = this._toValue(this._state.percentage[0]); val = parseFloat(val); val = this._applyPrecision(val); } if (snapToClosestTick) { var min = [val, Infinity]; for (var i = 0; i < this.options.ticks.length; i++) { var diff = Math.abs(this.options.ticks[i] - val); if (diff <= min[1]) { min = [this.options.ticks[i], diff]; } } if (min[1] <= this.options.ticks_snap_bounds) { return min[0]; } } return val; }, _applyPrecision: function _applyPrecision(val) { var precision = this.options.precision || this._getNumDigitsAfterDecimalPlace(this.options.step); return this._applyToFixedAndParseFloat(val, precision); }, _getNumDigitsAfterDecimalPlace: function _getNumDigitsAfterDecimalPlace(num) { var match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); if (!match) { return 0; } return Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0)); }, _applyToFixedAndParseFloat: function _applyToFixedAndParseFloat(num, toFixedInput) { var truncatedNum = num.toFixed(toFixedInput); return parseFloat(truncatedNum); }, /* Credits to Mike Samuel for the following method! Source: http://stackoverflow.com/questions/10454518/javascript-how-to-retrieve-the-number-of-decimals-of-a-string-number */ _getPercentage: function _getPercentage(ev) { if (this.touchCapable && (ev.type === 'touchstart' || ev.type === 'touchmove')) { ev = ev.touches[0]; } var eventPosition = ev[this.mousePos]; var sliderOffset = this._state.offset[this.stylePos]; var distanceToSlide = eventPosition - sliderOffset; // Calculate what percent of the length the slider handle has slid var percentage = distanceToSlide / this._state.size * 100; percentage = Math.round(percentage / this._state.percentage[2]) * this._state.percentage[2]; if (this.options.reversed) { percentage = 100 - percentage; } // Make sure the percent is within the bounds of the slider. // 0% corresponds to the 'min' value of the slide // 100% corresponds to the 'max' value of the slide return Math.max(0, Math.min(100, percentage)); }, _validateInputValue: function _validateInputValue(val) { if (typeof val === 'number') { return val; } else if (Array.isArray(val)) { this._validateArray(val); return val; } else { throw new Error(ErrorMsgs.formatInvalidInputErrorMsg(val)); } }, _validateArray: function _validateArray(val) { for (var i = 0; i < val.length; i++) { var input = val[i]; if (typeof input !== 'number') { throw new Error(ErrorMsgs.formatInvalidInputErrorMsg(input)); } } }, _setDataVal: function _setDataVal(val) { this.element.setAttribute('data-value', val); this.element.setAttribute('value', val); this.element.value = val; }, _trigger: function _trigger(evt, val) { val = val || val === 0 ? val : undefined; var callbackFnArray = this.eventToCallbackMap[evt]; if (callbackFnArray && callbackFnArray.length) { for (var i = 0; i < callbackFnArray.length; i++) { var callbackFn = callbackFnArray[i]; callbackFn(val); } } /* If JQuery exists, trigger JQuery events */ if ($) { this._triggerJQueryEvent(evt, val); } }, _triggerJQueryEvent: function _triggerJQueryEvent(evt, val) { var eventData = { type: evt, value: val }; this.$element.trigger(eventData); this.$sliderElem.trigger(eventData); }, _unbindJQueryEventHandlers: function _unbindJQueryEventHandlers() { this.$element.off(); this.$sliderElem.off(); }, _setText: function _setText(element, text) { if (typeof element.textContent !== "undefined") { element.textContent = text; } else if (typeof element.innerText !== "undefined") { element.innerText = text; } }, _removeClass: function _removeClass(element, classString) { var classes = classString.split(" "); var newClasses = element.className; for (var i = 0; i < classes.length; i++) { var classTag = classes[i]; var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)"); newClasses = newClasses.replace(regex, " "); } element.className = newClasses.trim(); }, _addClass: function _addClass(element, classString) { var classes = classString.split(" "); var newClasses = element.className; for (var i = 0; i < classes.length; i++) { var classTag = classes[i]; var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)"); var ifClassExists = regex.test(newClasses); if (!ifClassExists) { newClasses += " " + classTag; } } element.className = newClasses.trim(); }, _offsetLeft: function _offsetLeft(obj) { return obj.getBoundingClientRect().left; }, _offsetTop: function _offsetTop(obj) { var offsetTop = obj.offsetTop; while ((obj = obj.offsetParent) && !isNaN(obj.offsetTop)) { offsetTop += obj.offsetTop; if (obj.tagName !== 'BODY') { offsetTop -= obj.scrollTop; } } return offsetTop; }, _offset: function _offset(obj) { return { left: this._offsetLeft(obj), top: this._offsetTop(obj) }; }, _css: function _css(elementRef, styleName, value) { if ($) { $.style(elementRef, styleName, value); } else { var style = styleName.replace(/^-ms-/, "ms-").replace(/-([\da-z])/gi, function (all, letter) { return letter.toUpperCase(); }); elementRef.style[style] = value; } }, _toValue: function _toValue(percentage) { return this.options.scale.toValue.apply(this, [percentage]); }, _toPercentage: function _toPercentage(value) { return this.options.scale.toPercentage.apply(this, [value]); }, _setTooltipPosition: function _setTooltipPosition() { var tooltips = [this.tooltip, this.tooltip_min, this.tooltip_max]; if (this.options.orientation === 'vertical') { var tooltipPos = this.options.tooltip_position || 'right'; var oppositeSide = tooltipPos === 'left' ? 'right' : 'left'; tooltips.forEach((function (tooltip) { this._addClass(tooltip, tooltipPos); tooltip.style[oppositeSide] = '100%'; }).bind(this)); } else if (this.options.tooltip_position === 'bottom') { tooltips.forEach((function (tooltip) { this._addClass(tooltip, 'bottom'); tooltip.style.top = 22 + 'px'; }).bind(this)); } else { tooltips.forEach((function (tooltip) { this._addClass(tooltip, 'top'); tooltip.style.top = -this.tooltip.outerHeight - 14 + 'px'; }).bind(this)); } } }; /********************************* Attach to global namespace *********************************/ if ($) { (function () { var autoRegisterNamespace = undefined; if (!$.fn.slider) { $.bridget(NAMESPACE_MAIN, Slider); autoRegisterNamespace = NAMESPACE_MAIN; } else { if (windowIsDefined) { window.console.warn("bootstrap-slider.js - WARNING: $.fn.slider namespace is already bound. Use the $.fn.bootstrapSlider namespace instead."); } autoRegisterNamespace = NAMESPACE_ALTERNATE; } $.bridget(NAMESPACE_ALTERNATE, Slider); // Auto-Register data-provide="slider" Elements $(function () { $("input[data-provide=slider]")[autoRegisterNamespace](); }); })(); } })($); return Slider; });
'use strict'; module.exports = { set: function (v) { this.setProperty('-webkit-perspective', v); }, get: function () { return this.getPropertyValue('-webkit-perspective'); }, enumerable: true };
'use strict'; // Do this as the first thing so that any code reading it knows the right env. process.env.BABEL_ENV = 'development'; process.env.NODE_ENV = 'development'; // Makes the script crash on unhandled rejections instead of silently // ignoring them. In the future, promise rejections that are not handled will // terminate the Node.js process with a non-zero exit code. process.on('unhandledRejection', err => { throw err; }); // Ensure environment variables are read. require('../config/env'); const fs = require('fs'); const chalk = require('chalk'); const webpack = require('webpack'); const WebpackDevServer = require('webpack-dev-server'); const clearConsole = require('react-dev-utils/clearConsole'); const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); const { choosePort, createCompiler, prepareProxy, prepareUrls, } = require('react-dev-utils/WebpackDevServerUtils'); const openBrowser = require('react-dev-utils/openBrowser'); const paths = require('../config/paths'); const config = require('../config/webpack.config.dev'); const createDevServerConfig = require('../config/webpackDevServer.config'); const useYarn = fs.existsSync(paths.yarnLockFile); const isInteractive = process.stdout.isTTY; // Warn and crash if required files are missing if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { process.exit(1); } // Tools like Cloud9 rely on this. const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000; const HOST = process.env.HOST || '0.0.0.0'; if (process.env.HOST) { console.log( chalk.cyan( `Attempting to bind to HOST environment variable: ${chalk.yellow( chalk.bold(process.env.HOST) )}` ) ); console.log( `If this was unintentional, check that you haven't mistakenly set it in your shell.` ); console.log(`Learn more here: ${chalk.yellow('http://bit.ly/2mwWSwH')}`); console.log(); } // We attempt to use the default port but if it is busy, we offer the user to // run on a different port. `choosePort()` Promise resolves to the next free port. choosePort(HOST, DEFAULT_PORT) .then(port => { if (port == null) { // We have not found a port. return; } const protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; const appName = require(paths.appPackageJson).name; const urls = prepareUrls(protocol, HOST, port); // Create a webpack compiler that is configured with custom messages. const compiler = createCompiler(webpack, config, appName, urls, useYarn); // Load proxy config const proxySetting = require(paths.appPackageJson).proxy; const proxyConfig = prepareProxy(proxySetting, paths.appPublic); // Serve webpack assets generated by the compiler over a web sever. const serverConfig = createDevServerConfig( proxyConfig, urls.lanUrlForConfig ); const devServer = new WebpackDevServer(compiler, serverConfig); // Launch WebpackDevServer. devServer.listen(port, HOST, err => { if (err) { return console.log(err); } if (isInteractive) { clearConsole(); } console.log(chalk.cyan('Starting the development server...\n')); openBrowser(urls.localUrlForBrowser); }); ['SIGINT', 'SIGTERM'].forEach(function(sig) { process.on(sig, function() { devServer.close(); process.exit(); }); }); }) .catch(err => { if (err && err.message) { console.log(err.message); } process.exit(1); });
'use strict'; /** * @ngdoc service * @name $window * * @description * A reference to the browser's `window` object. While `window` * is globally available in JavaScript, it causes testability problems, because * it is a global variable. In angular we always refer to it through the * `$window` service, so it may be overridden, removed or mocked for testing. * * Expressions, like the one defined for the `ngClick` directive in the example * below, are evaluated with respect to the current scope. Therefore, there is * no risk of inadvertently coding in a dependency on a global value in such an * expression. * * @example <example> <file name="index.html"> <script> function Ctrl($scope, $window) { $scope.greeting = 'Hello, World!'; $scope.doGreeting = function(greeting) { $window.alert(greeting); }; } </script> <div ng-controller="Ctrl"> <input type="text" ng-model="greeting" /> <button ng-click="doGreeting(greeting)">ALERT</button> </div> </file> <file name="protractor.js" type="protractor"> it('should display the greeting in the input box', function() { element(by.model('greeting')).sendKeys('Hello, E2E Tests'); // If we click the button it will block the test runner // element(':button').click(); }); </file> </example> */ function $WindowProvider(){ this.$get = valueFn(window); }
(function() { var Ember = { assert: function() {}, FEATURES: { isEnabled: function() {} } }; /*! * @overview Ember - JavaScript Application Framework * @copyright Copyright 2011-2014 Tilde Inc. and contributors * Portions Copyright 2006-2011 Strobe Inc. * Portions Copyright 2008-2011 Apple Inc. All rights reserved. * @license Licensed under MIT license * See https://raw.github.com/emberjs/ember.js/master/LICENSE * @version 1.4.0 */ (function() { /** @module ember @submodule ember-handlebars-compiler */ // Eliminate dependency on any Ember to simplify precompilation workflow var objectCreate = Object.create || function(parent) { function F() {} F.prototype = parent; return new F(); }; var Handlebars = (Ember.imports && Ember.imports.Handlebars) || (this && this.Handlebars); if (!Handlebars && typeof require === 'function') { Handlebars = require('handlebars'); } Ember.assert("Ember Handlebars requires Handlebars version 1.0 or 1.1. Include " + "a SCRIPT tag in the HTML HEAD linking to the Handlebars file " + "before you link to Ember.", Handlebars); Ember.assert("Ember Handlebars requires Handlebars version 1.0 or 1.1, " + "COMPILER_REVISION expected: 4, got: " + Handlebars.COMPILER_REVISION + " - Please note: Builds of master may have other COMPILER_REVISION values.", Handlebars.COMPILER_REVISION === 4); /** Prepares the Handlebars templating library for use inside Ember's view system. The `Ember.Handlebars` object is the standard Handlebars library, extended to use Ember's `get()` method instead of direct property access, which allows computed properties to be used inside templates. To create an `Ember.Handlebars` template, call `Ember.Handlebars.compile()`. This will return a function that can be used by `Ember.View` for rendering. @class Handlebars @namespace Ember */ Ember.Handlebars = objectCreate(Handlebars); /** Register a bound helper or custom view helper. ## Simple bound helper example ```javascript Ember.Handlebars.helper('capitalize', function(value) { return value.toUpperCase(); }); ``` The above bound helper can be used inside of templates as follows: ```handlebars {{capitalize name}} ``` In this case, when the `name` property of the template's context changes, the rendered value of the helper will update to reflect this change. For more examples of bound helpers, see documentation for `Ember.Handlebars.registerBoundHelper`. ## Custom view helper example Assuming a view subclass named `App.CalendarView` were defined, a helper for rendering instances of this view could be registered as follows: ```javascript Ember.Handlebars.helper('calendar', App.CalendarView): ``` The above bound helper can be used inside of templates as follows: ```handlebars {{calendar}} ``` Which is functionally equivalent to: ```handlebars {{view App.CalendarView}} ``` Options in the helper will be passed to the view in exactly the same manner as with the `view` helper. @method helper @for Ember.Handlebars @param {String} name @param {Function|Ember.View} function or view class constructor @param {String} dependentKeys* */ Ember.Handlebars.helper = function(name, value) { Ember.assert("You tried to register a component named '" + name + "', but component names must include a '-'", !Ember.Component.detect(value) || name.match(/-/)); if (Ember.View.detect(value)) { Ember.Handlebars.registerHelper(name, Ember.Handlebars.makeViewHelper(value)); } else { Ember.Handlebars.registerBoundHelper.apply(null, arguments); } }; /** Returns a helper function that renders the provided ViewClass. Used internally by Ember.Handlebars.helper and other methods involving helper/component registration. @private @method helper @for Ember.Handlebars @param {Function} ViewClass view class constructor */ Ember.Handlebars.makeViewHelper = function(ViewClass) { return function(options) { Ember.assert("You can only pass attributes (such as name=value) not bare values to a helper for a View found in '" + ViewClass.toString() + "'", arguments.length < 2); return Ember.Handlebars.helpers.view.call(this, ViewClass, options); }; }; /** @class helpers @namespace Ember.Handlebars */ Ember.Handlebars.helpers = objectCreate(Handlebars.helpers); /** Override the the opcode compiler and JavaScript compiler for Handlebars. @class Compiler @namespace Ember.Handlebars @private @constructor */ Ember.Handlebars.Compiler = function() {}; // Handlebars.Compiler doesn't exist in runtime-only if (Handlebars.Compiler) { Ember.Handlebars.Compiler.prototype = objectCreate(Handlebars.Compiler.prototype); } Ember.Handlebars.Compiler.prototype.compiler = Ember.Handlebars.Compiler; /** @class JavaScriptCompiler @namespace Ember.Handlebars @private @constructor */ Ember.Handlebars.JavaScriptCompiler = function() {}; // Handlebars.JavaScriptCompiler doesn't exist in runtime-only if (Handlebars.JavaScriptCompiler) { Ember.Handlebars.JavaScriptCompiler.prototype = objectCreate(Handlebars.JavaScriptCompiler.prototype); Ember.Handlebars.JavaScriptCompiler.prototype.compiler = Ember.Handlebars.JavaScriptCompiler; } Ember.Handlebars.JavaScriptCompiler.prototype.namespace = "Ember.Handlebars"; Ember.Handlebars.JavaScriptCompiler.prototype.initializeBuffer = function() { return "''"; }; /** Override the default buffer for Ember Handlebars. By default, Handlebars creates an empty String at the beginning of each invocation and appends to it. Ember's Handlebars overrides this to append to a single shared buffer. @private @method appendToBuffer @param string {String} */ Ember.Handlebars.JavaScriptCompiler.prototype.appendToBuffer = function(string) { return "data.buffer.push("+string+");"; }; // Hacks ahead: // Handlebars presently has a bug where the `blockHelperMissing` hook // doesn't get passed the name of the missing helper name, but rather // gets passed the value of that missing helper evaluated on the current // context, which is most likely `undefined` and totally useless. // // So we alter the compiled template function to pass the name of the helper // instead, as expected. // // This can go away once the following is closed: // https://github.com/wycats/handlebars.js/issues/634 var DOT_LOOKUP_REGEX = /helpers\.(.*?)\)/, BRACKET_STRING_LOOKUP_REGEX = /helpers\['(.*?)'/, INVOCATION_SPLITTING_REGEX = /(.*blockHelperMissing\.call\(.*)(stack[0-9]+)(,.*)/; Ember.Handlebars.JavaScriptCompiler.stringifyLastBlockHelperMissingInvocation = function(source) { var helperInvocation = source[source.length - 1], helperName = (DOT_LOOKUP_REGEX.exec(helperInvocation) || BRACKET_STRING_LOOKUP_REGEX.exec(helperInvocation))[1], matches = INVOCATION_SPLITTING_REGEX.exec(helperInvocation); source[source.length - 1] = matches[1] + "'" + helperName + "'" + matches[3]; } var stringifyBlockHelperMissing = Ember.Handlebars.JavaScriptCompiler.stringifyLastBlockHelperMissingInvocation; var originalBlockValue = Ember.Handlebars.JavaScriptCompiler.prototype.blockValue; Ember.Handlebars.JavaScriptCompiler.prototype.blockValue = function() { originalBlockValue.apply(this, arguments); stringifyBlockHelperMissing(this.source); }; var originalAmbiguousBlockValue = Ember.Handlebars.JavaScriptCompiler.prototype.ambiguousBlockValue; Ember.Handlebars.JavaScriptCompiler.prototype.ambiguousBlockValue = function() { originalAmbiguousBlockValue.apply(this, arguments); stringifyBlockHelperMissing(this.source); }; var prefix = "ember" + (+new Date()), incr = 1; /** Rewrite simple mustaches from `{{foo}}` to `{{bind "foo"}}`. This means that all simple mustaches in Ember's Handlebars will also set up an observer to keep the DOM up to date when the underlying property changes. @private @method mustache @for Ember.Handlebars.Compiler @param mustache */ Ember.Handlebars.Compiler.prototype.mustache = function(mustache) { if (mustache.isHelper && mustache.id.string === 'control') { mustache.hash = mustache.hash || new Handlebars.AST.HashNode([]); mustache.hash.pairs.push(["controlID", new Handlebars.AST.StringNode(prefix + incr++)]); } else if (mustache.params.length || mustache.hash) { // no changes required } else { var id = new Handlebars.AST.IdNode([{ part: '_triageMustache' }]); // Update the mustache node to include a hash value indicating whether the original node // was escaped. This will allow us to properly escape values when the underlying value // changes and we need to re-render the value. if (!mustache.escaped) { mustache.hash = mustache.hash || new Handlebars.AST.HashNode([]); mustache.hash.pairs.push(["unescaped", new Handlebars.AST.StringNode("true")]); } mustache = new Handlebars.AST.MustacheNode([id].concat([mustache.id]), mustache.hash, !mustache.escaped); } return Handlebars.Compiler.prototype.mustache.call(this, mustache); }; /** Used for precompilation of Ember Handlebars templates. This will not be used during normal app execution. @method precompile @for Ember.Handlebars @static @param {String} string The template to precompile */ Ember.Handlebars.precompile = function(string) { var ast = Handlebars.parse(string); var options = { knownHelpers: { action: true, unbound: true, 'bind-attr': true, template: true, view: true, _triageMustache: true }, data: true, stringParams: true }; var environment = new Ember.Handlebars.Compiler().compile(ast, options); return new Ember.Handlebars.JavaScriptCompiler().compile(environment, options, undefined, true); }; // We don't support this for Handlebars runtime-only if (Handlebars.compile) { /** The entry point for Ember Handlebars. This replaces the default `Handlebars.compile` and turns on template-local data and String parameters. @method compile @for Ember.Handlebars @static @param {String} string The template to compile @return {Function} */ Ember.Handlebars.compile = function(string) { var ast = Handlebars.parse(string); var options = { data: true, stringParams: true }; var environment = new Ember.Handlebars.Compiler().compile(ast, options); var templateSpec = new Ember.Handlebars.JavaScriptCompiler().compile(environment, options, undefined, true); var template = Ember.Handlebars.template(templateSpec); template.isMethod = false; //Make sure we don't wrap templates with ._super return template; }; } })(); exports.precompile = Ember.Handlebars.precompile; exports.EmberHandlebars = Ember.Handlebars; })();
// GFM table, non-standard 'use strict'; function getLine(state, line) { var pos = state.bMarks[line] + state.blkIndent, max = state.eMarks[line]; return state.src.substr(pos, max - pos); } function escapedSplit(str) { var result = [], pos = 0, max = str.length, ch, escapes = 0, lastPos = 0, backTicked = false, lastBackTick = 0; ch = str.charCodeAt(pos); while (pos < max) { if (ch === 0x60/* ` */ && (escapes % 2 === 0)) { backTicked = !backTicked; lastBackTick = pos; } else if (ch === 0x7c/* | */ && (escapes % 2 === 0) && !backTicked) { result.push(str.substring(lastPos, pos)); lastPos = pos + 1; } else if (ch === 0x5c/* \ */) { escapes++; } else { escapes = 0; } pos++; // If there was an un-closed backtick, go back to just after // the last backtick, but as if it was a normal character if (pos === max && backTicked) { backTicked = false; pos = lastBackTick + 1; } ch = str.charCodeAt(pos); } result.push(str.substring(lastPos)); return result; } module.exports = function table(state, startLine, endLine, silent) { var ch, lineText, pos, i, nextLine, rows, token, aligns, t, tableLines, tbodyLines; // should have at least three lines if (startLine + 2 > endLine) { return false; } nextLine = startLine + 1; if (state.tShift[nextLine] < state.blkIndent) { return false; } // first character of the second line should be '|' or '-' pos = state.bMarks[nextLine] + state.tShift[nextLine]; if (pos >= state.eMarks[nextLine]) { return false; } ch = state.src.charCodeAt(pos); if (ch !== 0x7C/* | */ && ch !== 0x2D/* - */ && ch !== 0x3A/* : */) { return false; } lineText = getLine(state, startLine + 1); if (!/^[-:| ]+$/.test(lineText)) { return false; } rows = lineText.split('|'); if (rows.length < 2) { return false; } aligns = []; for (i = 0; i < rows.length; i++) { t = rows[i].trim(); if (!t) { // allow empty columns before and after table, but not in between columns; // e.g. allow ` |---| `, disallow ` ---||--- ` if (i === 0 || i === rows.length - 1) { continue; } else { return false; } } if (!/^:?-+:?$/.test(t)) { return false; } if (t.charCodeAt(t.length - 1) === 0x3A/* : */) { aligns.push(t.charCodeAt(0) === 0x3A/* : */ ? 'center' : 'right'); } else if (t.charCodeAt(0) === 0x3A/* : */) { aligns.push('left'); } else { aligns.push(''); } } lineText = getLine(state, startLine).trim(); if (lineText.indexOf('|') === -1) { return false; } rows = escapedSplit(lineText.replace(/^\||\|$/g, '')); if (aligns.length !== rows.length) { return false; } if (silent) { return true; } token = state.push('table_open', 'table', 1); token.map = tableLines = [ startLine, 0 ]; token = state.push('thead_open', 'thead', 1); token.map = [ startLine, startLine + 1 ]; token = state.push('tr_open', 'tr', 1); token.map = [ startLine, startLine + 1 ]; for (i = 0; i < rows.length; i++) { token = state.push('th_open', 'th', 1); token.map = [ startLine, startLine + 1 ]; if (aligns[i]) { token.attrs = [ [ 'style', 'text-align:' + aligns[i] ] ]; } token = state.push('inline', '', 0); token.content = rows[i].trim(); token.map = [ startLine, startLine + 1 ]; token.children = []; token = state.push('th_close', 'th', -1); } token = state.push('tr_close', 'tr', -1); token = state.push('thead_close', 'thead', -1); token = state.push('tbody_open', 'tbody', 1); token.map = tbodyLines = [ startLine + 2, 0 ]; for (nextLine = startLine + 2; nextLine < endLine; nextLine++) { if (state.tShift[nextLine] < state.blkIndent) { break; } lineText = getLine(state, nextLine).trim(); if (lineText.indexOf('|') === -1) { break; } rows = escapedSplit(lineText.replace(/^\||\|$/g, '')); // set number of columns to number of columns in header row rows.length = aligns.length; token = state.push('tr_open', 'tr', 1); for (i = 0; i < rows.length; i++) { token = state.push('td_open', 'td', 1); if (aligns[i]) { token.attrs = [ [ 'style', 'text-align:' + aligns[i] ] ]; } token = state.push('inline', '', 0); token.content = rows[i] ? rows[i].trim() : ''; token.children = []; token = state.push('td_close', 'td', -1); } token = state.push('tr_close', 'tr', -1); } token = state.push('tbody_close', 'tbody', -1); token = state.push('table_close', 'table', -1); tableLines[1] = tbodyLines[1] = nextLine; state.line = nextLine; return true; };
import dsv from "./dsv"; var tsv = dsv("\t"); export var tsvParse = tsv.parse; export var tsvParseRows = tsv.parseRows; export var tsvFormat = tsv.format; export var tsvFormatRows = tsv.formatRows;
/* * angular-mm-foundation * http://pineconellc.github.io/angular-foundation/ * Version: 0.5.1 - 2014-11-29 * License: MIT * (c) Pinecone, LLC */ angular.module("mm.foundation", ["mm.foundation.accordion","mm.foundation.alert","mm.foundation.bindHtml","mm.foundation.buttons","mm.foundation.position","mm.foundation.mediaQueries","mm.foundation.dropdownToggle","mm.foundation.interchange","mm.foundation.transition","mm.foundation.modal","mm.foundation.offcanvas","mm.foundation.pagination","mm.foundation.tooltip","mm.foundation.popover","mm.foundation.progressbar","mm.foundation.rating","mm.foundation.tabs","mm.foundation.topbar","mm.foundation.tour","mm.foundation.typeahead"]); angular.module('mm.foundation.accordion', []) .constant('accordionConfig', { closeOthers: true }) .controller('AccordionController', ['$scope', '$attrs', 'accordionConfig', function ($scope, $attrs, accordionConfig) { // This array keeps track of the accordion groups this.groups = []; // Ensure that all the groups in this accordion are closed, unless close-others explicitly says not to this.closeOthers = function(openGroup) { var closeOthers = angular.isDefined($attrs.closeOthers) ? $scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers; if ( closeOthers ) { angular.forEach(this.groups, function (group) { if ( group !== openGroup ) { group.isOpen = false; } }); } }; // This is called from the accordion-group directive to add itself to the accordion this.addGroup = function(groupScope) { var that = this; this.groups.push(groupScope); groupScope.$on('$destroy', function (event) { that.removeGroup(groupScope); }); }; // This is called from the accordion-group directive when to remove itself this.removeGroup = function(group) { var index = this.groups.indexOf(group); if ( index !== -1 ) { this.groups.splice(this.groups.indexOf(group), 1); } }; }]) // The accordion directive simply sets up the directive controller // and adds an accordion CSS class to itself element. .directive('accordion', function () { return { restrict:'EA', controller:'AccordionController', transclude: true, replace: false, templateUrl: 'template/accordion/accordion.html' }; }) // The accordion-group directive indicates a block of html that will expand and collapse in an accordion .directive('accordionGroup', ['$parse', function($parse) { return { require:'^accordion', // We need this directive to be inside an accordion restrict:'EA', transclude:true, // It transcludes the contents of the directive into the template replace: true, // The element containing the directive will be replaced with the template templateUrl:'template/accordion/accordion-group.html', scope:{ heading:'@' }, // Create an isolated scope and interpolate the heading attribute onto this scope controller: function() { this.setHeading = function(element) { this.heading = element; }; }, link: function(scope, element, attrs, accordionCtrl) { var getIsOpen, setIsOpen; accordionCtrl.addGroup(scope); scope.isOpen = false; if ( attrs.isOpen ) { getIsOpen = $parse(attrs.isOpen); setIsOpen = getIsOpen.assign; scope.$parent.$watch(getIsOpen, function(value) { scope.isOpen = !!value; }); } scope.$watch('isOpen', function(value) { if ( value ) { accordionCtrl.closeOthers(scope); } if ( setIsOpen ) { setIsOpen(scope.$parent, value); } }); } }; }]) // Use accordion-heading below an accordion-group to provide a heading containing HTML // <accordion-group> // <accordion-heading>Heading containing HTML - <img src="..."></accordion-heading> // </accordion-group> .directive('accordionHeading', function() { return { restrict: 'EA', transclude: true, // Grab the contents to be used as the heading template: '', // In effect remove this element! replace: true, require: '^accordionGroup', compile: function(element, attr, transclude) { return function link(scope, element, attr, accordionGroupCtrl) { // Pass the heading to the accordion-group controller // so that it can be transcluded into the right place in the template // [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat] accordionGroupCtrl.setHeading(transclude(scope, function() {})); }; } }; }) // Use in the accordion-group template to indicate where you want the heading to be transcluded // You must provide the property on the accordion-group controller that will hold the transcluded element // <div class="accordion-group"> // <div class="accordion-heading" ><a ... accordion-transclude="heading">...</a></div> // ... // </div> .directive('accordionTransclude', function() { return { require: '^accordionGroup', link: function(scope, element, attr, controller) { scope.$watch(function() { return controller[attr.accordionTransclude]; }, function(heading) { if ( heading ) { element.html(''); element.append(heading); } }); } }; }); angular.module("mm.foundation.alert", []) .controller('AlertController', ['$scope', '$attrs', function ($scope, $attrs) { $scope.closeable = 'close' in $attrs; }]) .directive('alert', function () { return { restrict:'EA', controller:'AlertController', templateUrl:'template/alert/alert.html', transclude:true, replace:true, scope: { type: '=', close: '&' } }; }); angular.module('mm.foundation.bindHtml', []) .directive('bindHtmlUnsafe', function () { return function (scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.bindHtmlUnsafe); scope.$watch(attr.bindHtmlUnsafe, function bindHtmlUnsafeWatchAction(value) { element.html(value || ''); }); }; }); angular.module('mm.foundation.buttons', []) .constant('buttonConfig', { activeClass: 'active', toggleEvent: 'click' }) .controller('ButtonsController', ['buttonConfig', function(buttonConfig) { this.activeClass = buttonConfig.activeClass; this.toggleEvent = buttonConfig.toggleEvent; }]) .directive('btnRadio', function () { return { require: ['btnRadio', 'ngModel'], controller: 'ButtonsController', link: function (scope, element, attrs, ctrls) { var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; //model -> UI ngModelCtrl.$render = function () { element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio))); }; //ui->model element.bind(buttonsCtrl.toggleEvent, function () { if (!element.hasClass(buttonsCtrl.activeClass)) { scope.$apply(function () { ngModelCtrl.$setViewValue(scope.$eval(attrs.btnRadio)); ngModelCtrl.$render(); }); } }); } }; }) .directive('btnCheckbox', function () { return { require: ['btnCheckbox', 'ngModel'], controller: 'ButtonsController', link: function (scope, element, attrs, ctrls) { var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; function getTrueValue() { return getCheckboxValue(attrs.btnCheckboxTrue, true); } function getFalseValue() { return getCheckboxValue(attrs.btnCheckboxFalse, false); } function getCheckboxValue(attributeValue, defaultValue) { var val = scope.$eval(attributeValue); return angular.isDefined(val) ? val : defaultValue; } //model -> UI ngModelCtrl.$render = function () { element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue())); }; //ui->model element.bind(buttonsCtrl.toggleEvent, function () { scope.$apply(function () { ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue()); ngModelCtrl.$render(); }); }); } }; }); angular.module('mm.foundation.position', []) /** * A set of utility methods that can be use to retrieve position of DOM elements. * It is meant to be used where we need to absolute-position DOM elements in * relation to other, existing elements (this is the case for tooltips, popovers, * typeahead suggestions etc.). */ .factory('$position', ['$document', '$window', function ($document, $window) { function getStyle(el, cssprop) { if (el.currentStyle) { //IE return el.currentStyle[cssprop]; } else if ($window.getComputedStyle) { return $window.getComputedStyle(el)[cssprop]; } // finally try and get inline style return el.style[cssprop]; } /** * Checks if a given element is statically positioned * @param element - raw DOM element */ function isStaticPositioned(element) { return (getStyle(element, "position") || 'static' ) === 'static'; } /** * returns the closest, non-statically positioned parentOffset of a given element * @param element */ var parentOffsetEl = function (element) { var docDomEl = $document[0]; var offsetParent = element.offsetParent || docDomEl; while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docDomEl; }; return { /** * Provides read-only equivalent of jQuery's position function: * http://api.jquery.com/position/ */ position: function (element) { var elBCR = this.offset(element); var offsetParentBCR = { top: 0, left: 0 }; var offsetParentEl = parentOffsetEl(element[0]); if (offsetParentEl != $document[0]) { offsetParentBCR = this.offset(angular.element(offsetParentEl)); offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop; offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft; } var boundingClientRect = element[0].getBoundingClientRect(); return { width: boundingClientRect.width || element.prop('offsetWidth'), height: boundingClientRect.height || element.prop('offsetHeight'), top: elBCR.top - offsetParentBCR.top, left: elBCR.left - offsetParentBCR.left }; }, /** * Provides read-only equivalent of jQuery's offset function: * http://api.jquery.com/offset/ */ offset: function (element) { var boundingClientRect = element[0].getBoundingClientRect(); return { width: boundingClientRect.width || element.prop('offsetWidth'), height: boundingClientRect.height || element.prop('offsetHeight'), top: boundingClientRect.top + ($window.pageYOffset || $document[0].body.scrollTop || $document[0].documentElement.scrollTop), left: boundingClientRect.left + ($window.pageXOffset || $document[0].body.scrollLeft || $document[0].documentElement.scrollLeft) }; } }; }]); angular.module("mm.foundation.mediaQueries", []) .factory('matchMedia', ['$document', '$window', function($document, $window) { // MatchMedia for IE <= 9 return $window.matchMedia || (function matchMedia(doc, undefined){ var bool, docElem = doc.documentElement, refNode = docElem.firstElementChild || docElem.firstChild, // fakeBody required for <FF4 when executed in <head> fakeBody = doc.createElement("body"), div = doc.createElement("div"); div.id = "mq-test-1"; div.style.cssText = "position:absolute;top:-100em"; fakeBody.style.background = "none"; fakeBody.appendChild(div); return function (q) { div.innerHTML = "&shy;<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>"; docElem.insertBefore(fakeBody, refNode); bool = div.offsetWidth === 42; docElem.removeChild(fakeBody); return { matches: bool, media: q }; }; }($document[0])); }]) .factory('mediaQueries', ['$document', 'matchMedia', function($document, matchMedia) { var head = angular.element($document[0].querySelector('head')); head.append('<meta class="foundation-mq-topbar" />'); head.append('<meta class="foundation-mq-small" />'); head.append('<meta class="foundation-mq-medium" />'); head.append('<meta class="foundation-mq-large" />'); var regex = /^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g; var queries = { topbar: getComputedStyle(head[0].querySelector('meta.foundation-mq-topbar')).fontFamily.replace(regex, ''), small : getComputedStyle(head[0].querySelector('meta.foundation-mq-small')).fontFamily.replace(regex, ''), medium : getComputedStyle(head[0].querySelector('meta.foundation-mq-medium')).fontFamily.replace(regex, ''), large : getComputedStyle(head[0].querySelector('meta.foundation-mq-large')).fontFamily.replace(regex, '') }; return { topbarBreakpoint: function () { return !matchMedia(queries.topbar).matches; }, small: function () { return matchMedia(queries.small).matches; }, medium: function () { return matchMedia(queries.medium).matches; }, large: function () { return matchMedia(queries.large).matches; } }; }]); /* * dropdownToggle - Provides dropdown menu functionality * @restrict class or attribute * @example: <a dropdown-toggle="#dropdown-menu">My Dropdown Menu</a> <ul id="dropdown-menu" class="f-dropdown"> <li ng-repeat="choice in dropChoices"> <a ng-href="{{choice.href}}">{{choice.text}}</a> </li> </ul> */ angular.module('mm.foundation.dropdownToggle', [ 'mm.foundation.position', 'mm.foundation.mediaQueries' ]) .controller('DropdownToggleController', ['$scope', '$attrs', 'mediaQueries', function($scope, $attrs, mediaQueries) { this.small = function() { return mediaQueries.small() && !mediaQueries.medium(); }; }]) .directive('dropdownToggle', ['$document', '$window', '$location', '$position', function ($document, $window, $location, $position) { var openElement = null, closeMenu = angular.noop; return { restrict: 'CA', scope: { dropdownToggle: '@' }, controller: 'DropdownToggleController', link: function(scope, element, attrs, controller) { var parent = element.parent(); var dropdown = angular.element($document[0].querySelector(scope.dropdownToggle)); var parentHasDropdown = function() { return parent.hasClass('has-dropdown'); }; var onClick = function (event) { dropdown = angular.element($document[0].querySelector(scope.dropdownToggle)); var elementWasOpen = (element === openElement); event.preventDefault(); event.stopPropagation(); if (!!openElement) { closeMenu(); } if (!elementWasOpen && !element.hasClass('disabled') && !element.prop('disabled')) { dropdown.css('display', 'block'); // We display the element so that offsetParent is populated var offset = $position.offset(element); var parentOffset = $position.offset(angular.element(dropdown[0].offsetParent)); var dropdownWidth = dropdown.prop('offsetWidth'); var css = { top: offset.top - parentOffset.top + offset.height + 'px' }; if (controller.small()) { css.left = Math.max((parentOffset.width - dropdownWidth) / 2, 8) + 'px'; css.position = 'absolute'; css.width = '95%'; css['max-width'] = 'none'; } else { var left = Math.round(offset.left - parentOffset.left); var rightThreshold = $window.innerWidth - dropdownWidth - 8; if (left > rightThreshold) { left = rightThreshold; dropdown.removeClass('left').addClass('right'); } css.left = left + 'px'; css.position = null; css['max-width'] = null; } dropdown.css(css); if (parentHasDropdown()) { parent.addClass('hover'); } openElement = element; closeMenu = function (event) { $document.off('click', closeMenu); dropdown.css('display', 'none'); closeMenu = angular.noop; openElement = null; if (parent.hasClass('hover')) { parent.removeClass('hover'); } }; $document.on('click', closeMenu); } }; if (dropdown) { dropdown.css('display', 'none'); } scope.$watch('$location.path', function() { closeMenu(); }); element.on('click', onClick); element.on('$destroy', function() { element.off('click', onClick); }); } }; }]); /** * @ngdoc service * @name mm.foundation.interchange * @description * * Package containing all services and directives * about the `interchange` module */ angular.module('mm.foundation.interchange', ['mm.foundation.mediaQueries']) /** * @ngdoc function * @name mm.foundation.interchange.interchageQuery * @function interchageQuery * @description * * this service inject meta tags objects in the head * to get the list of media queries from Foundation * stylesheets. * * @return {object} Queries list name => mediaQuery */ .factory('interchangeQueries', ['$document', function ($document) { var element, mediaSize, formatList = { 'default': 'only screen', landscape : 'only screen and (orientation: landscape)', portrait : 'only screen and (orientation: portrait)', retina : 'only screen and (-webkit-min-device-pixel-ratio: 2),' + 'only screen and (min--moz-device-pixel-ratio: 2),' + 'only screen and (-o-min-device-pixel-ratio: 2/1),' + 'only screen and (min-device-pixel-ratio: 2),' + 'only screen and (min-resolution: 192dpi),' + 'only screen and (min-resolution: 2dppx)' }, classPrefix = 'foundation-mq-', classList = ['small', 'medium', 'large', 'xlarge', 'xxlarge'], head = angular.element($document[0].querySelector('head')); for (var i = 0; i < classList.length; i++) { head.append('<meta class="' + classPrefix + classList[i] + '" />'); element = getComputedStyle(head[0].querySelector('meta.' + classPrefix + classList[i])); mediaSize = element.fontFamily.replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''); formatList[classList[i]] = mediaSize; } return formatList; }]) /** * @ngdoc function * @name mm.foundation.interchange.interchangeQueriesManager * @function interchangeQueriesManager * @description * * interface to add and remove named queries * in the interchangeQueries list */ .factory('interchangeQueriesManager', ['interchangeQueries', function (interchangeQueries) { return { /** * @ngdoc method * @name interchangeQueriesManager#add * @methodOf mm.foundation.interchange.interchangeQueriesManager * @description * * Add a custom media query in the `interchangeQueries` * factory. This method does not allow to update an existing * media query. * * @param {string} name MediaQuery name * @param {string} media MediaQuery * @returns {boolean} True if the insert is a success */ add: function (name, media) { if (!name || !media || !angular.isString(name) || !angular.isString(media) || !!interchangeQueries[name]) { return false; } interchangeQueries[name] = media; return true; } }; }]) /** * @ngdoc function * @name mm.foundation.interchange.interchangeTools * @function interchangeTools * @description * * Tools to help with the `interchange` module. */ .factory('interchangeTools', ['$window', 'matchMedia', 'interchangeQueries', function ($window, matchMedia, namedQueries) { /** * @ngdoc method * @name interchangeTools#parseAttribute * @methodOf mm.foundation.interchange.interchangeTools * @description * * Attribute parser to transform an `interchange` attribute * value to an object with media query (name or query) as key, * and file to use as value. * * ``` * { * small: 'bridge-500.jpg', * large: 'bridge-1200.jpg' * } * ``` * * @param {string} value Interchange query string * @returns {object} Attribute parsed */ var parseAttribute = function (value) { var raw = value.split(/\[(.*?)\]/), i = raw.length, breaker = /^(.+)\,\ \((.+)\)$/, breaked, output = {}; while (i--) { if (raw[i].replace(/[\W\d]+/, '').length > 4) { breaked = breaker.exec(raw[i]); if (!!breaked && breaked.length === 3) { output[breaked[2]] = breaked[1]; } } } return output; }; /** * @ngdoc method * @name interchangeTools#findCurrentMediaFile * @methodOf mm.foundation.interchange.interchangeTools * @description * * Find the current item to display from a file list * (object returned by `parseAttribute`) and the * current page dimensions. * * ``` * { * small: 'bridge-500.jpg', * large: 'bridge-1200.jpg' * } * ``` * * @param {object} files Parsed version of `interchange` attribute * @returns {string} File to display (or `undefined`) */ var findCurrentMediaFile = function (files) { var file, media, match; for (file in files) { media = namedQueries[file] || file; match = matchMedia(media); if (match.matches) { return files[file]; } } return; }; return { parseAttribute: parseAttribute, findCurrentMediaFile: findCurrentMediaFile }; }]) /** * @ngdoc directive * @name mm.foundation.interchange.directive:interchange * @restrict A * @element DIV|IMG * @priority 450 * @scope true * @description * * Interchange directive, following the same features as * ZURB documentation. The directive is splitted in 3 parts. * * 1. This directive use `compile` and not `link` for a simple * reason: if the method is applied on a DIV element to * display a template, the compile method will inject an ng-include. * Because using a `templateUrl` or `template` to do it wouldn't * be appropriate for all cases (`IMG` or dynamic backgrounds). * And doing it in `link` is too late to be applied. * * 2. In the `compile:post`, the attribute is parsed to find * out the type of content to display. * * 3. At the start and on event `resize`, the method `replace` * is called to reevaluate which file is supposed to be displayed * and update the value if necessary. The methd will also * trigger a `replace` event. */ .directive('interchange', ['$window', '$rootScope', 'interchangeTools', function ($window, $rootScope, interchangeTools) { var pictureFilePattern = /[A-Za-z0-9-_]+\.(jpg|jpeg|png|gif|bmp|tiff)\ *,/i; return { restrict: 'A', scope: true, priority: 450, compile: function compile($element, attrs) { // Set up the attribute to update if ($element[0].nodeName === 'DIV' && !pictureFilePattern.test(attrs.interchange)) { $element.html('<ng-include src="currentFile"></ng-include>'); } return { pre: function preLink($scope, $element, attrs) {}, post: function postLink($scope, $element, attrs) { var currentFile, nodeName; // Set up the attribute to update nodeName = $element && $element[0] && $element[0].nodeName; $scope.fileMap = interchangeTools.parseAttribute(attrs.interchange); // Find the type of interchange switch (nodeName) { case 'DIV': // If the tag is a div, we test the current file to see if it's picture currentFile = interchangeTools.findCurrentMediaFile($scope.fileMap); if (/[A-Za-z0-9-_]+\.(jpg|jpeg|png|gif|bmp|tiff)$/i.test(currentFile)) { $scope.type = 'background'; } else { $scope.type = 'include'; } break; case 'IMG': $scope.type = 'image'; break; default: return; } var replace = function (e) { // The the new file to display (exit if the same) var currentFile = interchangeTools.findCurrentMediaFile($scope.fileMap); if (!!$scope.currentFile && $scope.currentFile === currentFile) { return; } // Set up the new file $scope.currentFile = currentFile; switch ($scope.type) { case 'image': $element.attr('src', $scope.currentFile); break; case 'background': $element.css('background-image', 'url(' + $scope.currentFile + ')'); break; } // Trigger events $rootScope.$emit('replace', $element, $scope); if (!!e) { $scope.$apply(); } }; // Start replace(); $window.addEventListener('resize', replace); $scope.$on('$destroy', function () { $window.removeEventListener('resize', replace); }); } }; } }; }]); angular.module('mm.foundation.transition', []) /** * $transition service provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete. * @param {DOMElement} element The DOMElement that will be animated. * @param {string|object|function} trigger The thing that will cause the transition to start: * - As a string, it represents the css class to be added to the element. * - As an object, it represents a hash of style attributes to be applied to the element. * - As a function, it represents a function to be called that will cause the transition to occur. * @return {Promise} A promise that is resolved when the transition finishes. */ .factory('$transition', ['$q', '$timeout', '$rootScope', function($q, $timeout, $rootScope) { var $transition = function(element, trigger, options) { options = options || {}; var deferred = $q.defer(); var endEventName = $transition[options.animation ? "animationEndEventName" : "transitionEndEventName"]; var transitionEndHandler = function(event) { $rootScope.$apply(function() { element.unbind(endEventName, transitionEndHandler); deferred.resolve(element); }); }; if (endEventName) { element.bind(endEventName, transitionEndHandler); } // Wrap in a timeout to allow the browser time to update the DOM before the transition is to occur $timeout(function() { if ( angular.isString(trigger) ) { element.addClass(trigger); } else if ( angular.isFunction(trigger) ) { trigger(element); } else if ( angular.isObject(trigger) ) { element.css(trigger); } //If browser does not support transitions, instantly resolve if ( !endEventName ) { deferred.resolve(element); } }); // Add our custom cancel function to the promise that is returned // We can call this if we are about to run a new transition, which we know will prevent this transition from ending, // i.e. it will therefore never raise a transitionEnd event for that transition deferred.promise.cancel = function() { if ( endEventName ) { element.unbind(endEventName, transitionEndHandler); } deferred.reject('Transition cancelled'); }; return deferred.promise; }; // Work out the name of the transitionEnd event var transElement = document.createElement('trans'); var transitionEndEventNames = { 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'transitionend', 'OTransition': 'oTransitionEnd', 'transition': 'transitionend' }; var animationEndEventNames = { 'WebkitTransition': 'webkitAnimationEnd', 'MozTransition': 'animationend', 'OTransition': 'oAnimationEnd', 'transition': 'animationend' }; function findEndEventName(endEventNames) { for (var name in endEventNames){ if (transElement.style[name] !== undefined) { return endEventNames[name]; } } } $transition.transitionEndEventName = findEndEventName(transitionEndEventNames); $transition.animationEndEventName = findEndEventName(animationEndEventNames); return $transition; }]); angular.module('mm.foundation.modal', ['mm.foundation.transition']) /** * A helper, internal data structure that acts as a map but also allows getting / removing * elements in the LIFO order */ .factory('$$stackedMap', function () { return { createNew: function () { var stack = []; return { add: function (key, value) { stack.push({ key: key, value: value }); }, get: function (key) { for (var i = 0; i < stack.length; i++) { if (key == stack[i].key) { return stack[i]; } } }, keys: function() { var keys = []; for (var i = 0; i < stack.length; i++) { keys.push(stack[i].key); } return keys; }, top: function () { return stack[stack.length - 1]; }, remove: function (key) { var idx = -1; for (var i = 0; i < stack.length; i++) { if (key == stack[i].key) { idx = i; break; } } return stack.splice(idx, 1)[0]; }, removeTop: function () { return stack.splice(stack.length - 1, 1)[0]; }, length: function () { return stack.length; } }; } }; }) /** * A helper directive for the $modal service. It creates a backdrop element. */ .directive('modalBackdrop', ['$modalStack', '$timeout', function ($modalStack, $timeout) { return { restrict: 'EA', replace: true, templateUrl: 'template/modal/backdrop.html', link: function (scope) { scope.animate = false; //trigger CSS transitions $timeout(function () { scope.animate = true; }); scope.close = function (evt) { var modal = $modalStack.getTop(); if (modal && modal.value.backdrop && modal.value.backdrop != 'static' && (evt.target === evt.currentTarget)) { evt.preventDefault(); evt.stopPropagation(); $modalStack.dismiss(modal.key, 'backdrop click'); } }; } }; }]) .directive('modalWindow', ['$modalStack', '$timeout', function ($modalStack, $timeout) { return { restrict: 'EA', scope: { index: '@', animate: '=' }, replace: true, transclude: true, templateUrl: 'template/modal/window.html', link: function (scope, element, attrs) { scope.windowClass = attrs.windowClass || ''; $timeout(function () { // trigger CSS transitions scope.animate = true; // If the modal contains any autofocus elements refocus onto the first one if (element[0].querySelectorAll('[autofocus]').length > 0) { element[0].querySelectorAll('[autofocus]')[0].focus(); } else{ // otherwise focus the freshly-opened modal element[0].querySelector('div').focus(); } }); } }; }]) .factory('$modalStack', ['$window', '$transition', '$timeout', '$document', '$compile', '$rootScope', '$$stackedMap', function ($window, $transition, $timeout, $document, $compile, $rootScope, $$stackedMap) { var OPENED_MODAL_CLASS = 'modal-open'; var backdropDomEl, backdropScope; var openedWindows = $$stackedMap.createNew(); var $modalStack = {}; function backdropIndex() { var topBackdropIndex = -1; var opened = openedWindows.keys(); for (var i = 0; i < opened.length; i++) { if (openedWindows.get(opened[i]).value.backdrop) { topBackdropIndex = i; } } return topBackdropIndex; } $rootScope.$watch(backdropIndex, function(newBackdropIndex){ if (backdropScope) { backdropScope.index = newBackdropIndex; } }); function removeModalWindow(modalInstance) { var body = $document.find('body').eq(0); var modalWindow = openedWindows.get(modalInstance).value; //clean up the stack openedWindows.remove(modalInstance); //remove window DOM element removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, 300, function() { modalWindow.modalScope.$destroy(); body.toggleClass(OPENED_MODAL_CLASS, openedWindows.length() > 0); checkRemoveBackdrop(); }); } function checkRemoveBackdrop() { //remove backdrop if no longer needed if (backdropDomEl && backdropIndex() == -1) { var backdropScopeRef = backdropScope; removeAfterAnimate(backdropDomEl, backdropScope, 150, function () { backdropScopeRef.$destroy(); backdropScopeRef = null; }); backdropDomEl = undefined; backdropScope = undefined; } } function removeAfterAnimate(domEl, scope, emulateTime, done) { // Closing animation scope.animate = false; var transitionEndEventName = $transition.transitionEndEventName; if (transitionEndEventName) { // transition out var timeout = $timeout(afterAnimating, emulateTime); domEl.bind(transitionEndEventName, function () { $timeout.cancel(timeout); afterAnimating(); scope.$apply(); }); } else { // Ensure this call is async $timeout(afterAnimating, 0); } function afterAnimating() { if (afterAnimating.done) { return; } afterAnimating.done = true; domEl.remove(); if (done) { done(); } } } $document.bind('keydown', function (evt) { var modal; if (evt.which === 27) { modal = openedWindows.top(); if (modal && modal.value.keyboard) { $rootScope.$apply(function () { $modalStack.dismiss(modal.key); }); } } }); $modalStack.open = function (modalInstance, modal) { openedWindows.add(modalInstance, { deferred: modal.deferred, modalScope: modal.scope, backdrop: modal.backdrop, keyboard: modal.keyboard }); var body = $document.find('body').eq(0), currBackdropIndex = backdropIndex(); if (currBackdropIndex >= 0 && !backdropDomEl) { backdropScope = $rootScope.$new(true); backdropScope.index = currBackdropIndex; backdropDomEl = $compile('<div modal-backdrop></div>')(backdropScope); body.append(backdropDomEl); } // Create a faux modal div just to measure its // distance to top var faux = angular.element('<div class="reveal-modal" style="z-index:-1""></div>'); body.append(faux[0]); var marginTop = parseInt(getComputedStyle(faux[0]).top) || 0; faux.remove(); // Using pageYOffset instead of scrollY to ensure compatibility with IE var scrollY = $window.pageYOffset || 0; var openAt = scrollY + marginTop; var angularDomEl = angular.element('<div modal-window style="visibility: visible; top:' + openAt +'px;"></div>'); angularDomEl.attr('window-class', modal.windowClass); angularDomEl.attr('index', openedWindows.length() - 1); angularDomEl.attr('animate', 'animate'); angularDomEl.html(modal.content); var modalDomEl = $compile(angularDomEl)(modal.scope); openedWindows.top().value.modalDomEl = modalDomEl; body.append(modalDomEl); body.addClass(OPENED_MODAL_CLASS); }; $modalStack.close = function (modalInstance, result) { var modalWindow = openedWindows.get(modalInstance).value; if (modalWindow) { modalWindow.deferred.resolve(result); removeModalWindow(modalInstance); } }; $modalStack.dismiss = function (modalInstance, reason) { var modalWindow = openedWindows.get(modalInstance).value; if (modalWindow) { modalWindow.deferred.reject(reason); removeModalWindow(modalInstance); } }; $modalStack.dismissAll = function (reason) { var topModal = this.getTop(); while (topModal) { this.dismiss(topModal.key, reason); topModal = this.getTop(); } }; $modalStack.getTop = function () { return openedWindows.top(); }; return $modalStack; }]) .provider('$modal', function () { var $modalProvider = { options: { backdrop: true, //can be also false or 'static' keyboard: true }, $get: ['$injector', '$rootScope', '$q', '$http', '$templateCache', '$controller', '$modalStack', function ($injector, $rootScope, $q, $http, $templateCache, $controller, $modalStack) { var $modal = {}; function getTemplatePromise(options) { return options.template ? $q.when(options.template) : $http.get(options.templateUrl, {cache: $templateCache}).then(function (result) { return result.data; }); } function getResolvePromises(resolves) { var promisesArr = []; angular.forEach(resolves, function (value, key) { if (angular.isFunction(value) || angular.isArray(value)) { promisesArr.push($q.when($injector.invoke(value))); } }); return promisesArr; } $modal.open = function (modalOptions) { var modalResultDeferred = $q.defer(); var modalOpenedDeferred = $q.defer(); //prepare an instance of a modal to be injected into controllers and returned to a caller var modalInstance = { result: modalResultDeferred.promise, opened: modalOpenedDeferred.promise, close: function (result) { $modalStack.close(modalInstance, result); }, dismiss: function (reason) { $modalStack.dismiss(modalInstance, reason); } }; //merge and clean up options modalOptions = angular.extend({}, $modalProvider.options, modalOptions); modalOptions.resolve = modalOptions.resolve || {}; //verify options if (!modalOptions.template && !modalOptions.templateUrl) { throw new Error('One of template or templateUrl options is required.'); } var templateAndResolvePromise = $q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve))); templateAndResolvePromise.then(function resolveSuccess(tplAndVars) { var modalScope = (modalOptions.scope || $rootScope).$new(); modalScope.$close = modalInstance.close; modalScope.$dismiss = modalInstance.dismiss; var ctrlInstance, ctrlLocals = {}; var resolveIter = 1; //controllers if (modalOptions.controller) { ctrlLocals.$scope = modalScope; ctrlLocals.$modalInstance = modalInstance; angular.forEach(modalOptions.resolve, function (value, key) { ctrlLocals[key] = tplAndVars[resolveIter++]; }); ctrlInstance = $controller(modalOptions.controller, ctrlLocals); } $modalStack.open(modalInstance, { scope: modalScope, deferred: modalResultDeferred, content: tplAndVars[0], backdrop: modalOptions.backdrop, keyboard: modalOptions.keyboard, windowClass: modalOptions.windowClass }); }, function resolveError(reason) { modalResultDeferred.reject(reason); }); templateAndResolvePromise.then(function () { modalOpenedDeferred.resolve(true); }, function () { modalOpenedDeferred.reject(false); }); return modalInstance; }; return $modal; }] }; return $modalProvider; }); angular.module("mm.foundation.offcanvas", []) .directive('offCanvasWrap', ['$window', function ($window) { return { scope: {}, restrict: 'C', link: function ($scope, element, attrs) { var win = angular.element($window); var sidebar = $scope.sidebar = element; $scope.hide = function () { sidebar.removeClass('move-left'); sidebar.removeClass('move-right'); }; win.bind("resize.body", $scope.hide); $scope.$on('$destroy', function() { win.unbind("resize.body", $scope.hide); }); }, controller: ['$scope', function($scope) { this.leftToggle = function() { $scope.sidebar.toggleClass("move-right"); }; this.rightToggle = function() { $scope.sidebar.toggleClass("move-left"); }; this.hide = function() { $scope.hide(); }; }] }; }]) .directive('leftOffCanvasToggle', [function () { return { require: '^offCanvasWrap', restrict: 'C', link: function ($scope, element, attrs, offCanvasWrap) { element.on('click', function () { offCanvasWrap.leftToggle(); }); } }; }]) .directive('rightOffCanvasToggle', [function () { return { require: '^offCanvasWrap', restrict: 'C', link: function ($scope, element, attrs, offCanvasWrap) { element.on('click', function () { offCanvasWrap.rightToggle(); }); } }; }]) .directive('exitOffCanvas', [function () { return { require: '^offCanvasWrap', restrict: 'C', link: function ($scope, element, attrs, offCanvasWrap) { element.on('click', function () { offCanvasWrap.hide(); }); } }; }]) .directive('offCanvasList', [function () { return { require: '^offCanvasWrap', restrict: 'C', link: function ($scope, element, attrs, offCanvasWrap) { element.on('click', function () { offCanvasWrap.hide(); }); } }; }]); angular.module('mm.foundation.pagination', []) .controller('PaginationController', ['$scope', '$attrs', '$parse', '$interpolate', function ($scope, $attrs, $parse, $interpolate) { var self = this, setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop; this.init = function(defaultItemsPerPage) { if ($attrs.itemsPerPage) { $scope.$parent.$watch($parse($attrs.itemsPerPage), function(value) { self.itemsPerPage = parseInt(value, 10); $scope.totalPages = self.calculateTotalPages(); }); } else { this.itemsPerPage = defaultItemsPerPage; } }; this.noPrevious = function() { return this.page === 1; }; this.noNext = function() { return this.page === $scope.totalPages; }; this.isActive = function(page) { return this.page === page; }; this.calculateTotalPages = function() { var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage); return Math.max(totalPages || 0, 1); }; this.getAttributeValue = function(attribute, defaultValue, interpolate) { return angular.isDefined(attribute) ? (interpolate ? $interpolate(attribute)($scope.$parent) : $scope.$parent.$eval(attribute)) : defaultValue; }; this.render = function() { this.page = parseInt($scope.page, 10) || 1; if (this.page > 0 && this.page <= $scope.totalPages) { $scope.pages = this.getPages(this.page, $scope.totalPages); } }; $scope.selectPage = function(page) { if ( ! self.isActive(page) && page > 0 && page <= $scope.totalPages) { $scope.page = page; $scope.onSelectPage({ page: page }); } }; $scope.$watch('page', function() { self.render(); }); $scope.$watch('totalItems', function() { $scope.totalPages = self.calculateTotalPages(); }); $scope.$watch('totalPages', function(value) { setNumPages($scope.$parent, value); // Readonly variable if ( self.page > value ) { $scope.selectPage(value); } else { self.render(); } }); }]) .constant('paginationConfig', { itemsPerPage: 10, boundaryLinks: false, directionLinks: true, firstText: 'First', previousText: 'Previous', nextText: 'Next', lastText: 'Last', rotate: true }) .directive('pagination', ['$parse', 'paginationConfig', function($parse, config) { return { restrict: 'EA', scope: { page: '=', totalItems: '=', onSelectPage:' &' }, controller: 'PaginationController', templateUrl: 'template/pagination/pagination.html', replace: true, link: function(scope, element, attrs, paginationCtrl) { // Setup configuration parameters var maxSize, boundaryLinks = paginationCtrl.getAttributeValue(attrs.boundaryLinks, config.boundaryLinks ), directionLinks = paginationCtrl.getAttributeValue(attrs.directionLinks, config.directionLinks ), firstText = paginationCtrl.getAttributeValue(attrs.firstText, config.firstText, true), previousText = paginationCtrl.getAttributeValue(attrs.previousText, config.previousText, true), nextText = paginationCtrl.getAttributeValue(attrs.nextText, config.nextText, true), lastText = paginationCtrl.getAttributeValue(attrs.lastText, config.lastText, true), rotate = paginationCtrl.getAttributeValue(attrs.rotate, config.rotate); paginationCtrl.init(config.itemsPerPage); if (attrs.maxSize) { scope.$parent.$watch($parse(attrs.maxSize), function(value) { maxSize = parseInt(value, 10); paginationCtrl.render(); }); } // Create page object used in template function makePage(number, text, isActive, isDisabled) { return { number: number, text: text, active: isActive, disabled: isDisabled }; } paginationCtrl.getPages = function(currentPage, totalPages) { var pages = []; // Default page limits var startPage = 1, endPage = totalPages; var isMaxSized = ( angular.isDefined(maxSize) && maxSize < totalPages ); // recompute if maxSize if ( isMaxSized ) { if ( rotate ) { // Current page is displayed in the middle of the visible ones startPage = Math.max(currentPage - Math.floor(maxSize/2), 1); endPage = startPage + maxSize - 1; // Adjust if limit is exceeded if (endPage > totalPages) { endPage = totalPages; startPage = endPage - maxSize + 1; } } else { // Visible pages are paginated with maxSize startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1; // Adjust last page if limit is exceeded endPage = Math.min(startPage + maxSize - 1, totalPages); } } // Add page number links for (var number = startPage; number <= endPage; number++) { var page = makePage(number, number, paginationCtrl.isActive(number), false); pages.push(page); } // Add links to move between page sets if ( isMaxSized && ! rotate ) { if ( startPage > 1 ) { var previousPageSet = makePage(startPage - 1, '...', false, false); pages.unshift(previousPageSet); } if ( endPage < totalPages ) { var nextPageSet = makePage(endPage + 1, '...', false, false); pages.push(nextPageSet); } } // Add previous & next links if (directionLinks) { var previousPage = makePage(currentPage - 1, previousText, false, paginationCtrl.noPrevious()); pages.unshift(previousPage); var nextPage = makePage(currentPage + 1, nextText, false, paginationCtrl.noNext()); pages.push(nextPage); } // Add first & last links if (boundaryLinks) { var firstPage = makePage(1, firstText, false, paginationCtrl.noPrevious()); pages.unshift(firstPage); var lastPage = makePage(totalPages, lastText, false, paginationCtrl.noNext()); pages.push(lastPage); } return pages; }; } }; }]) .constant('pagerConfig', { itemsPerPage: 10, previousText: '« Previous', nextText: 'Next »', align: true }) .directive('pager', ['pagerConfig', function(config) { return { restrict: 'EA', scope: { page: '=', totalItems: '=', onSelectPage:' &' }, controller: 'PaginationController', templateUrl: 'template/pagination/pager.html', replace: true, link: function(scope, element, attrs, paginationCtrl) { // Setup configuration parameters var previousText = paginationCtrl.getAttributeValue(attrs.previousText, config.previousText, true), nextText = paginationCtrl.getAttributeValue(attrs.nextText, config.nextText, true), align = paginationCtrl.getAttributeValue(attrs.align, config.align); paginationCtrl.init(config.itemsPerPage); // Create page object used in template function makePage(number, text, isDisabled, isPrevious, isNext) { return { number: number, text: text, disabled: isDisabled, previous: ( align && isPrevious ), next: ( align && isNext ) }; } paginationCtrl.getPages = function(currentPage) { return [ makePage(currentPage - 1, previousText, paginationCtrl.noPrevious(), true, false), makePage(currentPage + 1, nextText, paginationCtrl.noNext(), false, true) ]; }; } }; }]); /** * The following features are still outstanding: animation as a * function, placement as a function, inside, support for more triggers than * just mouse enter/leave, html tooltips, and selector delegation. */ angular.module( 'mm.foundation.tooltip', [ 'mm.foundation.position', 'mm.foundation.bindHtml' ] ) /** * The $tooltip service creates tooltip- and popover-like directives as well as * houses global options for them. */ .provider( '$tooltip', function () { // The default options tooltip and popover. var defaultOptions = { placement: 'top', animation: true, popupDelay: 0 }; // Default hide triggers for each show trigger var triggerMap = { 'mouseenter': 'mouseleave', 'click': 'click', 'focus': 'blur' }; // The options specified to the provider globally. var globalOptions = {}; /** * `options({})` allows global configuration of all tooltips in the * application. * * var app = angular.module( 'App', ['mm.foundation.tooltip'], function( $tooltipProvider ) { * // place tooltips left instead of top by default * $tooltipProvider.options( { placement: 'left' } ); * }); */ this.options = function( value ) { angular.extend( globalOptions, value ); }; /** * This allows you to extend the set of trigger mappings available. E.g.: * * $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' ); */ this.setTriggers = function setTriggers ( triggers ) { angular.extend( triggerMap, triggers ); }; /** * This is a helper function for translating camel-case to snake-case. */ function snake_case(name){ var regexp = /[A-Z]/g; var separator = '-'; return name.replace(regexp, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } /** * Returns the actual instance of the $tooltip service. * TODO support multiple triggers */ this.$get = [ '$window', '$compile', '$timeout', '$parse', '$document', '$position', '$interpolate', function ( $window, $compile, $timeout, $parse, $document, $position, $interpolate ) { return function $tooltip ( type, prefix, defaultTriggerShow ) { var options = angular.extend( {}, defaultOptions, globalOptions ); /** * Returns an object of show and hide triggers. * * If a trigger is supplied, * it is used to show the tooltip; otherwise, it will use the `trigger` * option passed to the `$tooltipProvider.options` method; else it will * default to the trigger supplied to this directive factory. * * The hide trigger is based on the show trigger. If the `trigger` option * was passed to the `$tooltipProvider.options` method, it will use the * mapped trigger from `triggerMap` or the passed trigger if the map is * undefined; otherwise, it uses the `triggerMap` value of the show * trigger; else it will just use the show trigger. */ function getTriggers ( trigger ) { var show = trigger || options.trigger || defaultTriggerShow; var hide = triggerMap[show] || show; return { show: show, hide: hide }; } var directiveName = snake_case( type ); var startSym = $interpolate.startSymbol(); var endSym = $interpolate.endSymbol(); var template = '<div '+ directiveName +'-popup '+ 'title="'+startSym+'tt_title'+endSym+'" '+ 'content="'+startSym+'tt_content'+endSym+'" '+ 'placement="'+startSym+'tt_placement'+endSym+'" '+ 'animation="tt_animation" '+ 'is-open="tt_isOpen"'+ '>'+ '</div>'; return { restrict: 'EA', scope: true, compile: function (tElem, tAttrs) { var tooltipLinker = $compile( template ); return function link ( scope, element, attrs ) { var tooltip; var transitionTimeout; var popupTimeout; var appendToBody = angular.isDefined( options.appendToBody ) ? options.appendToBody : false; var triggers = getTriggers( undefined ); var hasRegisteredTriggers = false; var hasEnableExp = angular.isDefined(attrs[prefix+'Enable']); var positionTooltip = function (){ var position, ttWidth, ttHeight, ttPosition; // Get the position of the directive element. position = appendToBody ? $position.offset( element ) : $position.position( element ); // Get the height and width of the tooltip so we can center it. ttWidth = tooltip.prop( 'offsetWidth' ); ttHeight = tooltip.prop( 'offsetHeight' ); // Calculate the tooltip's top and left coordinates to center it with // this directive. switch ( scope.tt_placement ) { case 'right': ttPosition = { top: position.top + position.height / 2 - ttHeight / 2, left: position.left + position.width + 10 }; break; case 'bottom': ttPosition = { top: position.top + position.height + 10, left: position.left }; break; case 'left': ttPosition = { top: position.top + position.height / 2 - ttHeight / 2, left: position.left - ttWidth - 10 }; break; default: ttPosition = { top: position.top - ttHeight - 10, left: position.left }; break; } ttPosition.top += 'px'; ttPosition.left += 'px'; // Now set the calculated positioning. tooltip.css( ttPosition ); }; // By default, the tooltip is not open. // TODO add ability to start tooltip opened scope.tt_isOpen = false; function toggleTooltipBind () { if ( ! scope.tt_isOpen ) { showTooltipBind(); } else { hideTooltipBind(); } } // Show the tooltip with delay if specified, otherwise show it immediately function showTooltipBind() { if(hasEnableExp && !scope.$eval(attrs[prefix+'Enable'])) { return; } if ( scope.tt_popupDelay ) { popupTimeout = $timeout( show, scope.tt_popupDelay, false ); popupTimeout.then(function(reposition){reposition();}); } else { show()(); } } function hideTooltipBind () { scope.$apply(function () { hide(); }); } // Show the tooltip popup element. function show() { // Don't show empty tooltips. if ( ! scope.tt_content ) { return angular.noop; } createTooltip(); // If there is a pending remove transition, we must cancel it, lest the // tooltip be mysteriously removed. if ( transitionTimeout ) { $timeout.cancel( transitionTimeout ); } // Set the initial positioning. tooltip.css({ top: 0, left: 0, display: 'block' }); // Now we add it to the DOM because need some info about it. But it's not // visible yet anyway. if ( appendToBody ) { $document.find( 'body' ).append( tooltip ); } else { element.after( tooltip ); } positionTooltip(); // And show the tooltip. scope.tt_isOpen = true; scope.$digest(); // digest required as $apply is not called // Return positioning function as promise callback for correct // positioning after draw. return positionTooltip; } // Hide the tooltip popup element. function hide() { // First things first: we don't show it anymore. scope.tt_isOpen = false; //if tooltip is going to be shown after delay, we must cancel this $timeout.cancel( popupTimeout ); // And now we remove it from the DOM. However, if we have animation, we // need to wait for it to expire beforehand. // FIXME: this is a placeholder for a port of the transitions library. if ( scope.tt_animation ) { transitionTimeout = $timeout(removeTooltip, 500); } else { removeTooltip(); } } function createTooltip() { // There can only be one tooltip element per directive shown at once. if (tooltip) { removeTooltip(); } tooltip = tooltipLinker(scope, function () {}); // Get contents rendered into the tooltip scope.$digest(); } function removeTooltip() { if (tooltip) { tooltip.remove(); tooltip = null; } } /** * Observe the relevant attributes. */ attrs.$observe( type, function ( val ) { scope.tt_content = val; if (!val && scope.tt_isOpen ) { hide(); } }); attrs.$observe( prefix+'Title', function ( val ) { scope.tt_title = val; }); attrs[prefix+'Placement'] = attrs[prefix+'Placement'] || null; attrs.$observe( prefix+'Placement', function ( val ) { scope.tt_placement = angular.isDefined( val ) && val ? val : options.placement; }); attrs[prefix+'PopupDelay'] = attrs[prefix+'PopupDelay'] || null; attrs.$observe( prefix+'PopupDelay', function ( val ) { var delay = parseInt( val, 10 ); scope.tt_popupDelay = ! isNaN(delay) ? delay : options.popupDelay; }); var unregisterTriggers = function() { if ( hasRegisteredTriggers ) { if ( angular.isFunction( triggers.show ) ) { unregisterTriggerFunction(); } else { element.unbind( triggers.show, showTooltipBind ); element.unbind( triggers.hide, hideTooltipBind ); } } }; var unregisterTriggerFunction = function () {}; attrs[prefix+'Trigger'] = attrs[prefix+'Trigger'] || null; attrs.$observe( prefix+'Trigger', function ( val ) { unregisterTriggers(); unregisterTriggerFunction(); triggers = getTriggers( val ); if ( angular.isFunction( triggers.show ) ) { unregisterTriggerFunction = scope.$watch( function () { return triggers.show( scope, element, attrs ); }, function ( val ) { return val ? $timeout( show ) : $timeout( hide ); }); } else { if ( triggers.show === triggers.hide ) { element.bind( triggers.show, toggleTooltipBind ); } else { element.bind( triggers.show, showTooltipBind ); element.bind( triggers.hide, hideTooltipBind ); } } hasRegisteredTriggers = true; }); var animation = scope.$eval(attrs[prefix + 'Animation']); scope.tt_animation = angular.isDefined(animation) ? !!animation : options.animation; attrs.$observe( prefix+'AppendToBody', function ( val ) { appendToBody = angular.isDefined( val ) ? $parse( val )( scope ) : appendToBody; }); // if a tooltip is attached to <body> we need to remove it on // location change as its parent scope will probably not be destroyed // by the change. if ( appendToBody ) { scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess () { if ( scope.tt_isOpen ) { hide(); } }); } // Make sure tooltip is destroyed and removed. scope.$on('$destroy', function onDestroyTooltip() { $timeout.cancel( transitionTimeout ); $timeout.cancel( popupTimeout ); unregisterTriggers(); unregisterTriggerFunction(); removeTooltip(); }); }; } }; }; }]; }) .directive( 'tooltipPopup', function () { return { restrict: 'EA', replace: true, scope: { content: '@', placement: '@', animation: '&', isOpen: '&' }, templateUrl: 'template/tooltip/tooltip-popup.html' }; }) .directive( 'tooltip', [ '$tooltip', function ( $tooltip ) { return $tooltip( 'tooltip', 'tooltip', 'mouseenter' ); }]) .directive( 'tooltipHtmlUnsafePopup', function () { return { restrict: 'EA', replace: true, scope: { content: '@', placement: '@', animation: '&', isOpen: '&' }, templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html' }; }) .directive( 'tooltipHtmlUnsafe', [ '$tooltip', function ( $tooltip ) { return $tooltip( 'tooltipHtmlUnsafe', 'tooltip', 'mouseenter' ); }]); /** * The following features are still outstanding: popup delay, animation as a * function, placement as a function, inside, support for more triggers than * just mouse enter/leave, html popovers, and selector delegatation. */ angular.module( 'mm.foundation.popover', [ 'mm.foundation.tooltip' ] ) .directive( 'popoverPopup', function () { return { restrict: 'EA', replace: true, scope: { title: '@', content: '@', placement: '@', animation: '&', isOpen: '&' }, templateUrl: 'template/popover/popover.html' }; }) .directive( 'popover', [ '$tooltip', function ( $tooltip ) { return $tooltip( 'popover', 'popover', 'click' ); }]); angular.module('mm.foundation.progressbar', ['mm.foundation.transition']) .constant('progressConfig', { animate: true, max: 100 }) .controller('ProgressController', ['$scope', '$attrs', 'progressConfig', '$transition', function($scope, $attrs, progressConfig, $transition) { var self = this, bars = [], max = angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : progressConfig.max, animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate; this.addBar = function(bar, element) { var oldValue = 0, index = bar.$parent.$index; if ( angular.isDefined(index) && bars[index] ) { oldValue = bars[index].value; } bars.push(bar); this.update(element, bar.value, oldValue); bar.$watch('value', function(value, oldValue) { if (value !== oldValue) { self.update(element, value, oldValue); } }); bar.$on('$destroy', function() { self.removeBar(bar); }); }; // Update bar element width this.update = function(element, newValue, oldValue) { var percent = this.getPercentage(newValue); if (animate) { element.css('width', this.getPercentage(oldValue) + '%'); $transition(element, {width: percent + '%'}); } else { element.css({'transition': 'none', 'width': percent + '%'}); } }; this.removeBar = function(bar) { bars.splice(bars.indexOf(bar), 1); }; this.getPercentage = function(value) { return Math.round(100 * value / max); }; }]) .directive('progress', function() { return { restrict: 'EA', replace: true, transclude: true, controller: 'ProgressController', require: 'progress', scope: {}, template: '<div class="progress" ng-transclude></div>' //templateUrl: 'template/progressbar/progress.html' // Works in AngularJS 1.2 }; }) .directive('bar', function() { return { restrict: 'EA', replace: true, transclude: true, require: '^progress', scope: { value: '=', type: '@' }, templateUrl: 'template/progressbar/bar.html', link: function(scope, element, attrs, progressCtrl) { progressCtrl.addBar(scope, element); } }; }) .directive('progressbar', function() { return { restrict: 'EA', replace: true, transclude: true, controller: 'ProgressController', scope: { value: '=', type: '@' }, templateUrl: 'template/progressbar/progressbar.html', link: function(scope, element, attrs, progressCtrl) { progressCtrl.addBar(scope, angular.element(element.children()[0])); } }; }); angular.module('mm.foundation.rating', []) .constant('ratingConfig', { max: 5, stateOn: null, stateOff: null }) .controller('RatingController', ['$scope', '$attrs', '$parse', 'ratingConfig', function($scope, $attrs, $parse, ratingConfig) { this.maxRange = angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max; this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn; this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff; this.createRateObjects = function(states) { var defaultOptions = { stateOn: this.stateOn, stateOff: this.stateOff }; for (var i = 0, n = states.length; i < n; i++) { states[i] = angular.extend({ index: i }, defaultOptions, states[i]); } return states; }; // Get objects used in template $scope.range = angular.isDefined($attrs.ratingStates) ? this.createRateObjects(angular.copy($scope.$parent.$eval($attrs.ratingStates))): this.createRateObjects(new Array(this.maxRange)); $scope.rate = function(value) { if ( $scope.value !== value && !$scope.readonly ) { $scope.value = value; } }; $scope.enter = function(value) { if ( ! $scope.readonly ) { $scope.val = value; } $scope.onHover({value: value}); }; $scope.reset = function() { $scope.val = angular.copy($scope.value); $scope.onLeave(); }; $scope.$watch('value', function(value) { $scope.val = value; }); $scope.readonly = false; if ($attrs.readonly) { $scope.$parent.$watch($parse($attrs.readonly), function(value) { $scope.readonly = !!value; }); } }]) .directive('rating', function() { return { restrict: 'EA', scope: { value: '=', onHover: '&', onLeave: '&' }, controller: 'RatingController', templateUrl: 'template/rating/rating.html', replace: true }; }); /** * @ngdoc overview * @name mm.foundation.tabs * * @description * AngularJS version of the tabs directive. */ angular.module('mm.foundation.tabs', []) .controller('TabsetController', ['$scope', function TabsetCtrl($scope) { var ctrl = this, tabs = ctrl.tabs = $scope.tabs = []; ctrl.select = function(tab) { angular.forEach(tabs, function(tab) { tab.active = false; }); tab.active = true; }; ctrl.addTab = function addTab(tab) { tabs.push(tab); if (tabs.length === 1 || tab.active) { ctrl.select(tab); } }; ctrl.removeTab = function removeTab(tab) { var index = tabs.indexOf(tab); //Select a new tab if the tab to be removed is selected if (tab.active && tabs.length > 1) { //If this is the last tab, select the previous tab. else, the next tab. var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1; ctrl.select(tabs[newActiveIndex]); } tabs.splice(index, 1); }; }]) /** * @ngdoc directive * @name mm.foundation.tabs.directive:tabset * @restrict EA * * @description * Tabset is the outer container for the tabs directive * * @param {boolean=} vertical Whether or not to use vertical styling for the tabs. * @param {boolean=} justified Whether or not to use justified styling for the tabs. * * @example <example module="mm.foundation"> <file name="index.html"> <tabset> <tab heading="Tab 1"><b>First</b> Content!</tab> <tab heading="Tab 2"><i>Second</i> Content!</tab> </tabset> <hr /> <tabset vertical="true"> <tab heading="Vertical Tab 1"><b>First</b> Vertical Content!</tab> <tab heading="Vertical Tab 2"><i>Second</i> Vertical Content!</tab> </tabset> <tabset justified="true"> <tab heading="Justified Tab 1"><b>First</b> Justified Content!</tab> <tab heading="Justified Tab 2"><i>Second</i> Justified Content!</tab> </tabset> </file> </example> */ .directive('tabset', function() { return { restrict: 'EA', transclude: true, replace: true, scope: {}, controller: 'TabsetController', templateUrl: 'template/tabs/tabset.html', link: function(scope, element, attrs) { scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false; scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false; scope.type = angular.isDefined(attrs.type) ? scope.$parent.$eval(attrs.type) : 'tabs'; } }; }) /** * @ngdoc directive * @name mm.foundation.tabs.directive:tab * @restrict EA * * @param {string=} heading The visible heading, or title, of the tab. Set HTML headings with {@link mm.foundation.tabs.directive:tabHeading tabHeading}. * @param {string=} select An expression to evaluate when the tab is selected. * @param {boolean=} active A binding, telling whether or not this tab is selected. * @param {boolean=} disabled A binding, telling whether or not this tab is disabled. * * @description * Creates a tab with a heading and content. Must be placed within a {@link mm.foundation.tabs.directive:tabset tabset}. * * @example <example module="mm.foundation"> <file name="index.html"> <div ng-controller="TabsDemoCtrl"> <button class="button small" ng-click="items[0].active = true"> Select item 1, using active binding </button> <button class="button small" ng-click="items[1].disabled = !items[1].disabled"> Enable/disable item 2, using disabled binding </button> <br /> <tabset> <tab heading="Tab 1">First Tab</tab> <tab select="alertMe()"> <tab-heading><i class="fa fa-bell"></i> Alert me!</tab-heading> Second Tab, with alert callback and html heading! </tab> <tab ng-repeat="item in items" heading="{{item.title}}" disabled="item.disabled" active="item.active"> {{item.content}} </tab> </tabset> </div> </file> <file name="script.js"> function TabsDemoCtrl($scope) { $scope.items = [ { title:"Dynamic Title 1", content:"Dynamic Item 0" }, { title:"Dynamic Title 2", content:"Dynamic Item 1", disabled: true } ]; $scope.alertMe = function() { setTimeout(function() { alert("You've selected the alert tab!"); }); }; }; </file> </example> */ /** * @ngdoc directive * @name mm.foundation.tabs.directive:tabHeading * @restrict EA * * @description * Creates an HTML heading for a {@link mm.foundation.tabs.directive:tab tab}. Must be placed as a child of a tab element. * * @example <example module="mm.foundation"> <file name="index.html"> <tabset> <tab> <tab-heading><b>HTML</b> in my titles?!</tab-heading> And some content, too! </tab> <tab> <tab-heading><i class="fa fa-heart"></i> Icon heading?!?</tab-heading> That's right. </tab> </tabset> </file> </example> */ .directive('tab', ['$parse', function($parse) { return { require: '^tabset', restrict: 'EA', replace: true, templateUrl: 'template/tabs/tab.html', transclude: true, scope: { heading: '@', onSelect: '&select', //This callback is called in contentHeadingTransclude //once it inserts the tab's content into the dom onDeselect: '&deselect' }, controller: function() { //Empty controller so other directives can require being 'under' a tab }, compile: function(elm, attrs, transclude) { return function postLink(scope, elm, attrs, tabsetCtrl) { var getActive, setActive; if (attrs.active) { getActive = $parse(attrs.active); setActive = getActive.assign; scope.$parent.$watch(getActive, function updateActive(value, oldVal) { // Avoid re-initializing scope.active as it is already initialized // below. (watcher is called async during init with value === // oldVal) if (value !== oldVal) { scope.active = !!value; } }); scope.active = getActive(scope.$parent); } else { setActive = getActive = angular.noop; } scope.$watch('active', function(active) { if( !angular.isFunction(setActive) ){ return; } // Note this watcher also initializes and assigns scope.active to the // attrs.active expression. setActive(scope.$parent, active); if (active) { tabsetCtrl.select(scope); scope.onSelect(); } else { scope.onDeselect(); } }); scope.disabled = false; if ( attrs.disabled ) { scope.$parent.$watch($parse(attrs.disabled), function(value) { scope.disabled = !! value; }); } scope.select = function() { if ( ! scope.disabled ) { scope.active = true; } }; tabsetCtrl.addTab(scope); scope.$on('$destroy', function() { tabsetCtrl.removeTab(scope); }); //We need to transclude later, once the content container is ready. //when this link happens, we're inside a tab heading. scope.$transcludeFn = transclude; }; } }; }]) .directive('tabHeadingTransclude', [function() { return { restrict: 'A', require: '^tab', link: function(scope, elm, attrs, tabCtrl) { scope.$watch('headingElement', function updateHeadingElement(heading) { if (heading) { elm.html(''); elm.append(heading); } }); } }; }]) .directive('tabContentTransclude', function() { return { restrict: 'A', require: '^tabset', link: function(scope, elm, attrs) { var tab = scope.$eval(attrs.tabContentTransclude); //Now our tab is ready to be transcluded: both the tab heading area //and the tab content area are loaded. Transclude 'em both. tab.$transcludeFn(tab.$parent, function(contents) { angular.forEach(contents, function(node) { if (isTabHeading(node)) { //Let tabHeadingTransclude know. tab.headingElement = node; } else { elm.append(node); } }); }); } }; function isTabHeading(node) { return node.tagName && ( node.hasAttribute('tab-heading') || node.hasAttribute('data-tab-heading') || node.tagName.toLowerCase() === 'tab-heading' || node.tagName.toLowerCase() === 'data-tab-heading' ); } }) ; angular.module("mm.foundation.topbar", ['mm.foundation.mediaQueries']) .factory('closest', [function(){ return function(el, selector) { var matchesSelector = function (node, selector) { var nodes = (node.parentNode || node.document).querySelectorAll(selector); var i = -1; while (nodes[++i] && nodes[i] != node){} return !!nodes[i]; }; var element = el[0]; while (element) { if (matchesSelector(element, selector)) { return angular.element(element); } else { element = element.parentElement; } } return false; }; }]) .directive('topBar', ['$timeout','$compile', '$window', '$document', 'mediaQueries', function ($timeout, $compile, $window, $document, mediaQueries) { return { scope: { stickyClass : '@', backText: '@', stickyOn : '=', customBackText: '=', isHover: '=', mobileShowParentLink: '=', scrolltop : '=', }, restrict: 'EA', replace: true, templateUrl: 'template/topbar/top-bar.html', transclude: true, link: function ($scope, element, attrs) { var topbar = $scope.topbar = element; var topbarContainer = topbar.parent(); var body = angular.element($document[0].querySelector('body')); var isSticky = $scope.isSticky = function () { var sticky = topbarContainer.hasClass($scope.settings.stickyClass); if (sticky && $scope.settings.stickyOn === 'all') { return true; } else if (sticky && mediaQueries.small() && $scope.settings.stickyOn === 'small') { return true; } else if (sticky && mediaQueries.medium() && $scope.settings.stickyOn === 'medium') { return true; } else if (sticky && mediaQueries.large() && $scope.settings.stickyOn === 'large') { return true; } return false; }; var updateStickyPositioning = function(){ if (!$scope.stickyTopbar || !$scope.isSticky()) { return; } var $class = angular.element($document[0].querySelector('.' + $scope.settings.stickyClass)); var distance = stickyoffset; if ($window.pageYOffset > distance && !$class.hasClass('fixed')) { $class.addClass('fixed'); body.css('padding-top', $scope.originalHeight + 'px'); } else if ($window.pageYOffset <= distance && $class.hasClass('fixed')) { $class.removeClass('fixed'); body.css('padding-top', ''); } }; $scope.toggle = function(on) { if(!mediaQueries.topbarBreakpoint()){ return false; } var expand = (on === undefined) ? !topbar.hasClass('expanded') : on; if (expand){ topbar.addClass('expanded'); } else { topbar.removeClass('expanded'); } if ($scope.settings.scrolltop) { if (!expand && topbar.hasClass('fixed')) { topbar.parent().addClass('fixed'); topbar.removeClass('fixed'); body.css('padding-top', $scope.originalHeight + 'px'); } else if (expand && topbar.parent().hasClass('fixed')) { topbar.parent().removeClass('fixed'); topbar.addClass('fixed'); body.css('padding-top', ''); $window.scrollTo(0,0); } } else { if(isSticky()) { topbar.parent().addClass('fixed'); } if(topbar.parent().hasClass('fixed')) { if (!expand) { topbar.removeClass('fixed'); topbar.parent().removeClass('expanded'); updateStickyPositioning(); } else { topbar.addClass('fixed'); topbar.parent().addClass('expanded'); body.css('padding-top', $scope.originalHeight + 'px'); } } } }; if(topbarContainer.hasClass('fixed') || isSticky() ) { $scope.stickyTopbar = true; $scope.height = topbarContainer[0].offsetHeight; var stickyoffset = topbarContainer[0].getBoundingClientRect().top; } else { $scope.height = topbar[0].offsetHeight; } $scope.originalHeight = $scope.height; $scope.$watch('height', function(h){ if(h){ topbar.css('height', h + 'px'); } else { topbar.css('height', ''); } }); var lastBreakpoint = mediaQueries.topbarBreakpoint(); angular.element($window).bind('resize', function(){ var currentBreakpoint = mediaQueries.topbarBreakpoint(); if(lastBreakpoint === currentBreakpoint){ return; } lastBreakpoint = mediaQueries.topbarBreakpoint(); topbar.removeClass('expanded'); topbar.parent().removeClass('expanded'); $scope.height = ''; var sections = angular.element(topbar[0].querySelectorAll('section')); angular.forEach(sections, function(section){ angular.element(section.querySelectorAll('li.moved')).removeClass('moved'); }); $scope.$apply(); }); // update sticky positioning angular.element($window).bind("scroll", function() { updateStickyPositioning(); $scope.$apply(); }); $scope.$on('$destroy', function(){ angular.element($window).unbind("scroll"); angular.element($window).unbind("resize"); }); if (topbarContainer.hasClass('fixed')) { body.css('padding-top', $scope.originalHeight + 'px'); } }, controller: ['$window', '$scope', 'closest', function($window, $scope, closest) { $scope.settings = {}; $scope.settings.stickyClass = $scope.stickyClass || 'sticky'; $scope.settings.backText = $scope.backText || 'Back'; $scope.settings.stickyOn = $scope.stickyOn || 'all'; $scope.settings.customBackText = $scope.customBackText === undefined ? true : $scope.customBackText; $scope.settings.isHover = $scope.isHover === undefined ? true : $scope.isHover; $scope.settings.mobileShowParentLink = $scope.mobileShowParentLink === undefined ? true : $scope.mobileShowParentLink; $scope.settings.scrolltop = $scope.scrolltop === undefined ? true : $scope.scrolltop; // jump to top when sticky nav menu toggle is clicked this.settings = $scope.settings; $scope.index = 0; var outerHeight = function(el){ var height = el.offsetHeight; var style = el.currentStyle || getComputedStyle(el); height += parseInt(style.marginTop, 10) + parseInt(style.marginBottom, 10); return height; }; var sections = []; this.addSection = function(section){ sections.push(section); }; this.removeSection = function(section){ var index = sections.indexOf(section); if (index > -1) { sections.splice(index, 1); } }; var dir = /rtl/i.test($document.find('html').attr('dir')) ? 'right' : 'left'; $scope.$watch('index', function(index){ for(var i = 0; i < sections.length; i++){ sections[i].move(dir, index); } }); this.toggle = function(on){ $scope.toggle(on); for(var i = 0; i < sections.length; i++){ sections[i].reset(); } $scope.index = 0; $scope.height = ''; $scope.$apply(); }; this.back = function(event) { if($scope.index < 1 || !mediaQueries.topbarBreakpoint()){ return; } var $link = angular.element(event.currentTarget); var $movedLi = closest($link, 'li.moved'); var $previousLevelUl = $movedLi.parent(); $scope.index = $scope.index -1; if($scope.index === 0){ $scope.height = ''; } else { $scope.height = $scope.originalHeight + outerHeight($previousLevelUl[0]); } $timeout(function () { $movedLi.removeClass('moved'); }, 300); }; this.forward = function(event) { if(!mediaQueries.topbarBreakpoint()){ return false; } var $link = angular.element(event.currentTarget); var $selectedLi = closest($link, 'li'); $selectedLi.addClass('moved'); $scope.height = $scope.originalHeight + outerHeight($link.parent()[0].querySelector('ul')); $scope.index = $scope.index + 1; $scope.$apply(); }; }] }; }]) .directive('toggleTopBar', ['closest', function (closest) { return { scope: {}, require: '^topBar', restrict: 'A', replace: true, templateUrl: 'template/topbar/toggle-top-bar.html', transclude: true, link: function ($scope, element, attrs, topBar) { element.bind('click', function(event) { var li = closest(angular.element(event.currentTarget), 'li'); if(!li.hasClass('back') && !li.hasClass('has-dropdown')) { topBar.toggle(); } }); $scope.$on('$destroy', function(){ element.unbind('click'); }); } }; }]) .directive('topBarSection', ['$compile', 'closest', function ($compile, closest) { return { scope: {}, require: '^topBar', restrict: 'EA', replace: true, templateUrl: 'template/topbar/top-bar-section.html', transclude: true, link: function ($scope, element, attrs, topBar) { var section = element; $scope.reset = function(){ angular.element(section[0].querySelectorAll('li.moved')).removeClass('moved'); }; $scope.move = function(dir, index){ if(dir === 'left'){ section.css({"left": index * -100 + '%'}); } else { section.css({"right": index * -100 + '%'}); } }; topBar.addSection($scope); $scope.$on("$destroy", function(){ topBar.removeSection($scope); }); // Top level links close menu on click var links = section[0].querySelectorAll('li>a'); angular.forEach(links, function(link){ var $link = angular.element(link); var li = closest($link, 'li'); if(li.hasClass('has-dropdown') || li.hasClass('back') || li.hasClass('title')){ return; } $link.bind('click', function(){ topBar.toggle(false); }); $scope.$on('$destroy', function(){ $link.bind('click'); }); }); } }; }]) .directive('hasDropdown', ['mediaQueries', function (mediaQueries) { return { scope: {}, require: '^topBar', restrict: 'A', templateUrl: 'template/topbar/has-dropdown.html', replace: true, transclude: true, link: function ($scope, element, attrs, topBar) { $scope.triggerLink = element.children('a')[0]; var $link = angular.element($scope.triggerLink); $link.bind('click', function(event){ topBar.forward(event); }); $scope.$on('$destroy', function(){ $link.unbind('click'); }); element.bind('mouseenter', function() { if(topBar.settings.isHover && !mediaQueries.topbarBreakpoint()){ element.addClass('not-click'); } }); element.bind('click', function(event) { if(!topBar.settings.isHover && !mediaQueries.topbarBreakpoint()){ element.toggleClass('not-click'); } }); element.bind('mouseleave', function() { element.removeClass('not-click'); }); $scope.$on('$destroy', function(){ element.unbind('click'); element.unbind('mouseenter'); element.unbind('mouseleave'); }); }, controller: ['$window', '$scope', function($window, $scope) { this.triggerLink = $scope.triggerLink; }] }; }]) .directive('topBarDropdown', ['$compile', function ($compile) { return { scope: {}, require: ['^topBar', '^hasDropdown'], restrict: 'A', replace: true, templateUrl: 'template/topbar/top-bar-dropdown.html', transclude: true, link: function ($scope, element, attrs, ctrls) { var topBar = ctrls[0]; var hasDropdown = ctrls[1]; var $link = angular.element(hasDropdown.triggerLink); var url = $link.attr('href'); $scope.linkText = $link.text(); $scope.back = function(event){ topBar.back(event); }; // Add back link if (topBar.settings.customBackText) { $scope.backText = topBar.settings.backText; } else { $scope.backText = '&laquo; ' + $link.html(); } var $titleLi; if (topBar.settings.mobileShowParentLink && url && url.length > 1) { $titleLi = angular.element('<li class="title back js-generated">' + '<h5><a href="#" ng-click="back($event);">{{backText}}</a></h5></li>' + '<li><a class="parent-link js-generated" href="' + url + '">{{linkText}}</a></li>'); } else { $titleLi = angular.element('<li class="title back js-generated">' + '<h5><a href="" ng-click="back($event);">{{backText}}</a></h5></li>'); } $compile($titleLi)($scope); element.prepend($titleLi); } }; }]); angular.module( 'mm.foundation.tour', [ 'mm.foundation.position', 'mm.foundation.tooltip' ] ) .service( '$tour', [ '$window', function ( $window ) { var currentIndex = getCurrentStep(); var ended = false; var steps = {}; function getCurrentStep() { return parseInt( $window.localStorage.getItem( 'mm.tour.step' ), 10 ); } function setCurrentStep(step) { currentIndex = step; $window.localStorage.setItem( 'mm.tour.step', step ); } this.add = function ( index, attrs ) { steps[ index ] = attrs; }; this.has = function ( index ) { return !!steps[ index ]; }; this.isActive = function () { return currentIndex > 0; }; this.current = function ( index ) { if ( index ) { setCurrentStep( currentIndex ); } else { return currentIndex; } }; this.start = function () { setCurrentStep( 1 ); }; this.next = function () { setCurrentStep( currentIndex + 1 ); }; this.end = function () { setCurrentStep( 0 ); }; }]) .directive( 'stepTextPopup', ['$tour', function ( $tour ) { return { restrict: 'EA', replace: true, scope: { title: '@', content: '@', placement: '@', animation: '&', isOpen: '&' }, templateUrl: 'template/tour/tour.html', link: function (scope, element) { scope.isLastStep = function () { return !$tour.has( $tour.current() + 1 ); }; scope.endTour = function () { element.remove(); $tour.end(); }; scope.nextStep = function () { element.remove(); $tour.next(); }; } }; }]) .directive( 'stepText', [ '$position', '$tooltip', '$tour', '$window', function ( $position, $tooltip, $tour, $window ) { function isElementInViewport( element ) { var rect = element[0].getBoundingClientRect(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= ($window.innerHeight - 80) && rect.right <= $window.innerWidth ); } function show( scope, element, attrs ) { var index = parseInt( attrs.stepIndex, 10); if ( $tour.isActive() && index ) { $tour.add( index, attrs ); if ( index === $tour.current() ) { if ( !isElementInViewport( element ) ) { var offset = $position.offset( element ); $window.scrollTo( 0, offset.top - $window.innerHeight / 2 ); } return true; } } return false; } return $tooltip( 'stepText', 'step', show ); }]); angular.module('mm.foundation.typeahead', ['mm.foundation.position', 'mm.foundation.bindHtml']) /** * A helper service that can parse typeahead's syntax (string provided by users) * Extracted to a separate service for ease of unit testing */ .factory('typeaheadParser', ['$parse', function ($parse) { // 00000111000000000000022200000000000000003333333333333330000000000044000 var TYPEAHEAD_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+(.*)$/; return { parse:function (input) { var match = input.match(TYPEAHEAD_REGEXP); if (!match) { throw new Error( "Expected typeahead specification in form of '_modelValue_ (as _label_)? for _item_ in _collection_'" + " but got '" + input + "'."); } return { itemName:match[3], source:$parse(match[4]), viewMapper:$parse(match[2] || match[1]), modelMapper:$parse(match[1]) }; } }; }]) .directive('typeahead', ['$compile', '$parse', '$q', '$timeout', '$document', '$position', 'typeaheadParser', function ($compile, $parse, $q, $timeout, $document, $position, typeaheadParser) { var HOT_KEYS = [9, 13, 27, 38, 40]; return { require:'ngModel', link:function (originalScope, element, attrs, modelCtrl) { //SUPPORTED ATTRIBUTES (OPTIONS) //minimal no of characters that needs to be entered before typeahead kicks-in var minSearch = originalScope.$eval(attrs.typeaheadMinLength) || 1; //minimal wait time after last character typed before typehead kicks-in var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0; //should it restrict model values to the ones selected from the popup only? var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false; //binding to a variable that indicates if matches are being retrieved asynchronously var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop; //a callback executed when a match is selected var onSelectCallback = $parse(attrs.typeaheadOnSelect); var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined; var appendToBody = attrs.typeaheadAppendToBody ? $parse(attrs.typeaheadAppendToBody) : false; //INTERNAL VARIABLES //model setter executed upon match selection var $setModelValue = $parse(attrs.ngModel).assign; //expressions used by typeahead var parserResult = typeaheadParser.parse(attrs.typeahead); var hasFocus; //pop-up element used to display matches var popUpEl = angular.element('<div typeahead-popup></div>'); popUpEl.attr({ matches: 'matches', active: 'activeIdx', select: 'select(activeIdx)', query: 'query', position: 'position' }); //custom item template if (angular.isDefined(attrs.typeaheadTemplateUrl)) { popUpEl.attr('template-url', attrs.typeaheadTemplateUrl); } //create a child scope for the typeahead directive so we are not polluting original scope //with typeahead-specific data (matches, query etc.) var scope = originalScope.$new(); originalScope.$on('$destroy', function(){ scope.$destroy(); }); var resetMatches = function() { scope.matches = []; scope.activeIdx = -1; }; var getMatchesAsync = function(inputValue) { var locals = {$viewValue: inputValue}; isLoadingSetter(originalScope, true); $q.when(parserResult.source(originalScope, locals)).then(function(matches) { //it might happen that several async queries were in progress if a user were typing fast //but we are interested only in responses that correspond to the current view value if (inputValue === modelCtrl.$viewValue && hasFocus) { if (matches.length > 0) { scope.activeIdx = 0; scope.matches.length = 0; //transform labels for(var i=0; i<matches.length; i++) { locals[parserResult.itemName] = matches[i]; scope.matches.push({ label: parserResult.viewMapper(scope, locals), model: matches[i] }); } scope.query = inputValue; //position pop-up with matches - we need to re-calculate its position each time we are opening a window //with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page //due to other elements being rendered scope.position = appendToBody ? $position.offset(element) : $position.position(element); scope.position.top = scope.position.top + element.prop('offsetHeight'); } else { resetMatches(); } isLoadingSetter(originalScope, false); } }, function(){ resetMatches(); isLoadingSetter(originalScope, false); }); }; resetMatches(); //we need to propagate user's query so we can higlight matches scope.query = undefined; //Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later var timeoutPromise; //plug into $parsers pipeline to open a typeahead on view changes initiated from DOM //$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue modelCtrl.$parsers.unshift(function (inputValue) { if (inputValue && inputValue.length >= minSearch) { if (waitTime > 0) { if (timeoutPromise) { $timeout.cancel(timeoutPromise);//cancel previous timeout } timeoutPromise = $timeout(function () { getMatchesAsync(inputValue); }, waitTime); } else { getMatchesAsync(inputValue); } } else { isLoadingSetter(originalScope, false); resetMatches(); } if (isEditable) { return inputValue; } else { if (!inputValue) { // Reset in case user had typed something previously. modelCtrl.$setValidity('editable', true); return inputValue; } else { modelCtrl.$setValidity('editable', false); return undefined; } } }); modelCtrl.$formatters.push(function (modelValue) { var candidateViewValue, emptyViewValue; var locals = {}; if (inputFormatter) { locals['$model'] = modelValue; return inputFormatter(originalScope, locals); } else { //it might happen that we don't have enough info to properly render input value //we need to check for this situation and simply return model value if we can't apply custom formatting locals[parserResult.itemName] = modelValue; candidateViewValue = parserResult.viewMapper(originalScope, locals); locals[parserResult.itemName] = undefined; emptyViewValue = parserResult.viewMapper(originalScope, locals); return candidateViewValue!== emptyViewValue ? candidateViewValue : modelValue; } }); scope.select = function (activeIdx) { //called from within the $digest() cycle var locals = {}; var model, item; locals[parserResult.itemName] = item = scope.matches[activeIdx].model; model = parserResult.modelMapper(originalScope, locals); $setModelValue(originalScope, model); modelCtrl.$setValidity('editable', true); onSelectCallback(originalScope, { $item: item, $model: model, $label: parserResult.viewMapper(originalScope, locals) }); resetMatches(); //return focus to the input element if a mach was selected via a mouse click event element[0].focus(); }; //bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27) element.bind('keydown', function (evt) { //typeahead is open and an "interesting" key was pressed if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) { return; } evt.preventDefault(); if (evt.which === 40) { scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length; scope.$digest(); } else if (evt.which === 38) { scope.activeIdx = (scope.activeIdx ? scope.activeIdx : scope.matches.length) - 1; scope.$digest(); } else if (evt.which === 13 || evt.which === 9) { scope.$apply(function () { scope.select(scope.activeIdx); }); } else if (evt.which === 27) { evt.stopPropagation(); resetMatches(); scope.$digest(); } }); element.bind('blur', function (evt) { hasFocus = false; }); element.bind('focus', function (evt) { hasFocus = true; }); // Keep reference to click handler to unbind it. var dismissClickHandler = function (evt) { if (element[0] !== evt.target) { resetMatches(); scope.$digest(); } }; $document.bind('click', dismissClickHandler); originalScope.$on('$destroy', function(){ $document.unbind('click', dismissClickHandler); }); var $popup = $compile(popUpEl)(scope); if ( appendToBody ) { $document.find('body').append($popup); } else { element.after($popup); } } }; }]) .directive('typeaheadPopup', function () { return { restrict:'EA', scope:{ matches:'=', query:'=', active:'=', position:'=', select:'&' }, replace:true, templateUrl:'template/typeahead/typeahead-popup.html', link:function (scope, element, attrs) { scope.templateUrl = attrs.templateUrl; scope.isOpen = function () { return scope.matches.length > 0; }; scope.isActive = function (matchIdx) { return scope.active == matchIdx; }; scope.selectActive = function (matchIdx) { scope.active = matchIdx; }; scope.selectMatch = function (activeIdx) { scope.select({activeIdx:activeIdx}); }; } }; }) .directive('typeaheadMatch', ['$http', '$templateCache', '$compile', '$parse', function ($http, $templateCache, $compile, $parse) { return { restrict:'EA', scope:{ index:'=', match:'=', query:'=' }, link:function (scope, element, attrs) { var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html'; $http.get(tplUrl, {cache: $templateCache}).success(function(tplContent){ element.replaceWith($compile(tplContent.trim())(scope)); }); } }; }]) .filter('typeaheadHighlight', function() { function escapeRegexp(queryToEscape) { return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); } return function(matchItem, query) { return query ? matchItem.replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem; }; });
/** * @author Mat Groves http://matgroves.com/ @Doormat23 * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/fun/dotscreen.js */ /** * * This filter applies a dotscreen effect making display objects appear to be made out of black and white halftone dots like an old printer * @class DotScreenFilter * @contructor */ PIXI.DotScreenFilter = function() { PIXI.AbstractFilter.call( this ); this.passes = [this]; // set the uniforms this.uniforms = { scale: {type: '1f', value:1}, angle: {type: '1f', value:5}, dimensions: {type: '4fv', value:[0,0,0,0]} }; this.fragmentSrc = [ 'precision mediump float;', 'varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'uniform vec4 dimensions;', 'uniform sampler2D uSampler;', 'uniform float angle;', 'uniform float scale;', 'float pattern() {', ' float s = sin(angle), c = cos(angle);', ' vec2 tex = vTextureCoord * dimensions.xy;', ' vec2 point = vec2(', ' c * tex.x - s * tex.y,', ' s * tex.x + c * tex.y', ' ) * scale;', ' return (sin(point.x) * sin(point.y)) * 4.0;', '}', 'void main() {', ' vec4 color = texture2D(uSampler, vTextureCoord);', ' float average = (color.r + color.g + color.b) / 3.0;', ' gl_FragColor = vec4(vec3(average * 10.0 - 5.0 + pattern()), color.a);', '}' ]; }; PIXI.DotScreenFilter.prototype = Object.create( PIXI.DotScreenFilter.prototype ); PIXI.DotScreenFilter.prototype.constructor = PIXI.DotScreenFilter; /** * * This describes the the scale * @property scale * @type Number */ Object.defineProperty(PIXI.DotScreenFilter.prototype, 'scale', { get: function() { return this.uniforms.scale.value; }, set: function(value) { this.dirty = true; this.uniforms.scale.value = value; } }); /** * * This radius describes angle * @property angle * @type Number */ Object.defineProperty(PIXI.DotScreenFilter.prototype, 'angle', { get: function() { return this.uniforms.angle.value; }, set: function(value) { this.dirty = true; this.uniforms.angle.value = value; } });
/* * /MathJax/localization/br/HTML-CSS.js * * Copyright (c) 2009-2015 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("br","HTML-CSS",{version:"2.5.0",isLoaded:true,strings:{LoadWebFont:"O karga\u00F1 ar font web %1",CantLoadWebFont:"Ne c'haller ket karga\u00F1 ar font web %1",CantFindFontUsing:"Ne c'haller ket kavout ur font dereat e-touez %1",FirefoxCantLoadWebFont:"Ne c'hall ket Firefox karga\u00F1 ar fonto\u00F9 adalek un ostiz a-bell",WebFontsNotAvailable:"N'haller ket kaout ar Fonto\u00F9 web. Ar fonto\u00F9 skeudenn a vo implijet en o flas"}});MathJax.Ajax.loadComplete("[MathJax]/localization/br/HTML-CSS.js");
const inherits = require('inherits'); const ColumnCompiler_Oracle = require('../../oracle/schema/columncompiler'); import {assign} from 'lodash'; function ColumnCompiler_Oracledb() { ColumnCompiler_Oracle.apply(this, arguments); } inherits(ColumnCompiler_Oracledb, ColumnCompiler_Oracle); assign(ColumnCompiler_Oracledb.prototype, { time: 'timestamp with local time zone', datetime: function(without) { return without ? 'timestamp' : 'timestamp with local time zone'; }, timestamp: function(without) { return without ? 'timestamp' : 'timestamp with local time zone'; } }); module.exports = ColumnCompiler_Oracledb;
describe('uniqueEmail directive', function() { var Users, $scope, form; function setTestValue(value) { $scope.model.testValue = value; $scope.$digest(); } beforeEach(function() { // Mockup Users resource angular.module('mock-Users', []).factory('Users', function() { Users = jasmine.createSpyObj('Users', ['query']); return Users; }); }); beforeEach(module('admin-users-edit-uniqueEmail', 'mock-Users')); beforeEach(inject(function($compile, $rootScope){ $scope = $rootScope; var element = angular.element( '<form name="form"><input name="testInput" ng-model="model.testValue" unique-email></form>' ); $scope.model = { testValue: null}; $compile(element)($scope); $scope.$digest(); form = $scope.form; })); it('should be valid initially', function() { expect(form.testInput.$valid).toBe(true); }); it('should not call Users.query when the model changes', function() { setTestValue('different'); expect(Users.query).not.toHaveBeenCalled(); }); it('should call Users.query when the view changes', function() { form.testInput.$setViewValue('different'); expect(Users.query).toHaveBeenCalled(); }); it('should set model to invalid if the Users callback contains users', function() { Users.query.andCallFake(function(query, callback) { callback(['someUser']); }); form.testInput.$setViewValue('different'); expect(form.testInput.$valid).toBe(false); }); it('should set model to valid if the Users callback contains no users', function() { Users.query.andCallFake(function(query, callback) { callback([]); }); form.testInput.$setViewValue('different'); expect(form.testInput.$valid).toBe(true); }); });
(function( $ ) { module( "slider: events" ); //Specs from http://wiki.jqueryui.com/Slider#specs //"change callback: triggers when the slider has stopped moving and has a new // value (even if same as previous value), via mouse(mouseup) or keyboard(keyup) // or value method/option" test( "mouse based interaction", function() { expect( 4 ); var element = $( "#slider1" ) .slider({ start: function( event ) { equal( event.originalEvent.type, "mousedown", "start triggered by mousedown" ); }, slide: function( event) { equal( event.originalEvent.type, "mousemove", "slider triggered by mousemove" ); }, stop: function( event ) { equal( event.originalEvent.type, "mouseup", "stop triggered by mouseup" ); }, change: function( event ) { equal( event.originalEvent.type, "mouseup", "change triggered by mouseup" ); } }); element.find( ".ui-slider-handle" ).eq( 0 ) .simulate( "drag", { dx: 10, dy: 10 } ); }); test( "keyboard based interaction", function() { expect( 3 ); // Test keyup at end of handle slide (keyboard) var element = $( "#slider1" ) .slider({ start: function( event ) { equal( event.originalEvent.type, "keydown", "start triggered by keydown" ); }, slide: function() { ok( false, "Slider never triggered by keys" ); }, stop: function( event ) { equal( event.originalEvent.type, "keyup", "stop triggered by keyup" ); }, change: function( event ) { equal( event.originalEvent.type, "keyup", "change triggered by keyup" ); } }); element.find( ".ui-slider-handle" ).eq( 0 ) .simulate( "keydown", { keyCode: $.ui.keyCode.LEFT } ) .simulate( "keypress", { keyCode: $.ui.keyCode.LEFT } ) .simulate( "keyup", { keyCode: $.ui.keyCode.LEFT } ); }); test( "programmatic event triggers", function() { expect( 6 ); // Test value method var element = $( "<div></div>" ) .slider({ change: function() { ok( true, "change triggered by value method" ); } }) .slider( "value", 0 ); // Test values method element = $( "<div></div>" ) .slider({ values: [ 10, 20 ], change: function() { ok( true, "change triggered by values method" ); } }) .slider( "values", [ 80, 90 ] ); // Test value option element = $( "<div></div>" ) .slider({ change: function() { ok( true, "change triggered by value option" ); } }) .slider( "option", "value", 0 ); // Test values option element = $( "<div></div>" ) .slider({ values: [ 10, 20 ], change: function() { ok( true, "change triggered by values option" ); } }) .slider( "option", "values", [ 80, 90 ] ); }); test( "mouse based interaction part two: when handles overlap", function() { expect( 4 ); var element = $( "#slider1" ) .slider({ values: [ 0, 0, 0 ], start: function( event, ui ) { equal( handles.index( ui.handle ), 2, "rightmost handle activated when overlapping at minimum (#3736)" ); } }), handles = element.find( ".ui-slider-handle" ); handles.eq( 0 ).simulate( "drag", { dx: 10 } ); element.slider( "destroy" ); element = $( "#slider1" ) .slider({ values: [ 10, 10, 10 ], max: 10, start: function( event, ui ) { equal( handles.index( ui.handle ), 0, "leftmost handle activated when overlapping at maximum" ); } }), handles = element.find( ".ui-slider-handle" ); handles.eq( 0 ).simulate( "drag", { dx: -10 } ); element.slider( "destroy" ); element = $( "#slider1" ) .slider({ values: [ 19, 20 ] }), handles = element.find( ".ui-slider-handle" ); handles.eq( 0 ).simulate( "drag", { dx: 10 } ); element.one( "slidestart", function( event, ui ) { equal( handles.index( ui.handle ), 0, "left handle activated if left was moved last" ); }); handles.eq( 0 ).simulate( "drag", { dx: 10 } ); element.slider( "destroy" ); element = $( "#slider1" ) .slider({ values: [ 19, 20 ] }), handles = element.find( ".ui-slider-handle" ); handles.eq( 1 ).simulate( "drag", { dx: -10 } ); element.one( "slidestart", function( event, ui ) { equal( handles.index( ui.handle ), 1, "right handle activated if right was moved last (#3467)" ); }); handles.eq( 0 ).simulate( "drag", { dx: 10 } ); }); })( jQuery );
var parse = require('../parse/index.js') /** * @category Quarter Helpers * @summary Return the last day of a year quarter for the given date. * * @description * Return the last day of a year quarter for the given date. * The result will be in the local timezone. * * @param {Date|String|Number} date - the original date * @returns {Date} the last day of a quarter * * @example * // The last day of a quarter for 2 September 2014 11:55:00: * var result = lastDayOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) * //=> Tue Sep 30 2014 00:00:00 */ function lastDayOfQuarter (dirtyDate) { var date = parse(dirtyDate) var currentMonth = date.getMonth() var month = currentMonth - currentMonth % 3 + 3 date.setMonth(month, 0) date.setHours(0, 0, 0, 0) return date } module.exports = lastDayOfQuarter
// Copyright 2014 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. (function(shared, scope, testing) { function groupChildDuration(node) { return node._timing.delay + node.activeDuration + node._timing.endDelay; }; function KeyframeEffect(effect) { this._frames = shared.normalizeKeyframes(effect); } KeyframeEffect.prototype = { getFrames: function() { return this._frames; } }; scope.Animation = function(target, effect, timingInput) { this.target = target; // TODO: Store a clone, not the same instance. this._timingInput = timingInput; this._timing = shared.normalizeTimingInput(timingInput); // TODO: Make modifications to timing update the underlying player this.timing = shared.makeTiming(timingInput); // TODO: Make this a live object - will need to separate normalization of // keyframes into a shared module. if (typeof effect == 'function') this.effect = effect; else this.effect = new KeyframeEffect(effect); this._effect = effect; this.activeDuration = shared.calculateActiveDuration(this._timing); return this; }; var originalElementAnimate = Element.prototype.animate; Element.prototype.animate = function(effect, timing) { return scope.timeline.play(new scope.Animation(this, effect, timing)); }; var nullTarget = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); scope.newUnderlyingPlayerForAnimation = function(animation) { var target = animation.target || nullTarget; var effect = animation._effect; if (typeof effect == 'function') { effect = []; } return originalElementAnimate.apply(target, [effect, animation._timingInput]); }; scope.bindPlayerForAnimation = function(player) { if (player.source && typeof player.source.effect == 'function') { scope.bindPlayerForCustomEffect(player); } }; var pendingGroups = []; scope.awaitStartTime = function(groupPlayer) { if (groupPlayer.startTime !== null || !groupPlayer._isGroup) return; if (pendingGroups.length == 0) { requestAnimationFrame(updatePendingGroups); } pendingGroups.push(groupPlayer); }; function updatePendingGroups() { var updated = false; while (pendingGroups.length) { pendingGroups.shift()._updateChildren(); updated = true; } return updated; } var originalGetComputedStyle = window.getComputedStyle; Object.defineProperty(window, 'getComputedStyle', { configurable: true, enumerable: true, value: function() { var result = originalGetComputedStyle.apply(this, arguments); if (updatePendingGroups()) result = originalGetComputedStyle.apply(this, arguments); return result; }, }); // TODO: Call into this less frequently. scope.Player.prototype._updateChildren = function() { if (this.paused || !this.source || !this._isGroup) return; var offset = this.source._timing.delay; for (var i = 0; i < this.source.children.length; i++) { var child = this.source.children[i]; var childPlayer; if (i >= this._childPlayers.length) { childPlayer = window.document.timeline.play(child); this._childPlayers.push(childPlayer); } else { childPlayer = this._childPlayers[i]; } child.player = this.source.player; if (childPlayer.startTime != this.startTime + offset) { if (this.startTime === null) { childPlayer.currentTime = this.source.player.currentTime - offset; childPlayer._startTime = null; } else { childPlayer.startTime = this.startTime + offset; } childPlayer._updateChildren(); } if (this.playbackRate == -1 && this.currentTime < offset && childPlayer.currentTime !== -1) { childPlayer.currentTime = -1; } if (this.source instanceof window.AnimationSequence) offset += groupChildDuration(child); } }; window.Animation = scope.Animation; window.Element.prototype.getAnimationPlayers = function() { return document.timeline.getAnimationPlayers().filter(function(player) { return player.source !== null && player.source.target == this; }.bind(this)); }; scope.groupChildDuration = groupChildDuration; }(webAnimationsShared, webAnimationsNext, webAnimationsTesting));
/** * archiver-utils * * Copyright (c) 2012-2014 Chris Talkington, contributors. * Licensed under the MIT license. * https://github.com/archiverjs/node-archiver/blob/master/LICENSE-MIT */ var fs = require('graceful-fs'); var path = require('path'); var _ = require('lodash'); var glob = require('glob'); var file = module.exports = {}; var pathSeparatorRe = /[\/\\]/g; // Process specified wildcard glob patterns or filenames against a // callback, excluding and uniquing files in the result set. var processPatterns = function(patterns, fn) { // Filepaths to return. var result = []; // Iterate over flattened patterns array. _.flatten(patterns).forEach(function(pattern) { // If the first character is ! it should be omitted var exclusion = pattern.indexOf('!') === 0; // If the pattern is an exclusion, remove the ! if (exclusion) { pattern = pattern.slice(1); } // Find all matching files for this pattern. var matches = fn(pattern); if (exclusion) { // If an exclusion, remove matching files. result = _.difference(result, matches); } else { // Otherwise add matching files. result = _.union(result, matches); } }); return result; }; // True if the file path exists. file.exists = function() { var filepath = path.join.apply(path, arguments); return fs.existsSync(filepath); }; // Return an array of all file paths that match the given wildcard patterns. file.expand = function() { var args = _.toArray(arguments); // If the first argument is an options object, save those options to pass // into the File.prototype.glob.sync method. var options = _.isPlainObject(args[0]) ? args.shift() : {}; // Use the first argument if it's an Array, otherwise convert the arguments // object to an array and use that. var patterns = Array.isArray(args[0]) ? args[0] : args; // Return empty set if there are no patterns or filepaths. if (patterns.length === 0) { return []; } // Return all matching filepaths. var matches = processPatterns(patterns, function(pattern) { // Find all matching files for this pattern. return glob.sync(pattern, options); }); // Filter result set? if (options.filter) { matches = matches.filter(function(filepath) { filepath = path.join(options.cwd || '', filepath); try { if (typeof options.filter === 'function') { return options.filter(filepath); } else { // If the file is of the right type and exists, this should work. return fs.statSync(filepath)[options.filter](); } } catch(e) { // Otherwise, it's probably not the right type. return false; } }); } return matches; }; // Build a multi task "files" object dynamically. file.expandMapping = function(patterns, destBase, options) { options = _.defaults({}, options, { rename: function(destBase, destPath) { return path.join(destBase || '', destPath); } }); var files = []; var fileByDest = {}; // Find all files matching pattern, using passed-in options. file.expand(options, patterns).forEach(function(src) { var destPath = src; // Flatten? if (options.flatten) { destPath = path.basename(destPath); } // Change the extension? if (options.ext) { destPath = destPath.replace(/(\.[^\/]*)?$/, options.ext); } // Generate destination filename. var dest = options.rename(destBase, destPath, options); // Prepend cwd to src path if necessary. if (options.cwd) { src = path.join(options.cwd, src); } // Normalize filepaths to be unix-style. dest = dest.replace(pathSeparatorRe, '/'); src = src.replace(pathSeparatorRe, '/'); // Map correct src path to dest path. if (fileByDest[dest]) { // If dest already exists, push this src onto that dest's src array. fileByDest[dest].src.push(src); } else { // Otherwise create a new src-dest file mapping object. files.push({ src: [src], dest: dest, }); // And store a reference for later use. fileByDest[dest] = files[files.length - 1]; } }); return files; }; // reusing bits of grunt's multi-task source normalization file.normalizeFilesArray = function(data) { var files = []; data.forEach(function(obj) { var prop; if ('src' in obj || 'dest' in obj) { files.push(obj); } }); if (files.length === 0) { return []; } files = _(files).chain().forEach(function(obj) { if (!('src' in obj) || !obj.src) { return; } // Normalize .src properties to flattened array. if (Array.isArray(obj.src)) { obj.src = _.flatten(obj.src); } else { obj.src = [obj.src]; } }).map(function(obj) { // Build options object, removing unwanted properties. var expandOptions = _.extend({}, obj); delete expandOptions.src; delete expandOptions.dest; // Expand file mappings. if (obj.expand) { return file.expandMapping(obj.src, obj.dest, expandOptions).map(function(mapObj) { // Copy obj properties to result. var result = _.extend({}, obj); // Make a clone of the orig obj available. result.orig = _.extend({}, obj); // Set .src and .dest, processing both as templates. result.src = mapObj.src; result.dest = mapObj.dest; // Remove unwanted properties. ['expand', 'cwd', 'flatten', 'rename', 'ext'].forEach(function(prop) { delete result[prop]; }); return result; }); } // Copy obj properties to result, adding an .orig property. var result = _.extend({}, obj); // Make a clone of the orig obj available. result.orig = _.extend({}, obj); if ('src' in result) { // Expose an expand-on-demand getter method as .src. Object.defineProperty(result, 'src', { enumerable: true, get: function fn() { var src; if (!('result' in fn)) { src = obj.src; // If src is an array, flatten it. Otherwise, make it into an array. src = Array.isArray(src) ? _.flatten(src) : [src]; // Expand src files, memoizing result. fn.result = file.expand(expandOptions, src); } return fn.result; } }); } if ('dest' in result) { result.dest = obj.dest; } return result; }).flatten().value(); return files; };
"use strict"; var _foob, _foob$test; (_foob = foob).add.apply(_foob, babelHelpers.toConsumableArray(numbers)); (_foob$test = foob.test).add.apply(_foob$test, babelHelpers.toConsumableArray(numbers));
/** * The MIT License * * Copyright (c) 2010 Adam Abrons and Misko Hevery http://getangular.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* NUGGGGGH MUST TONGUE WANGS \ ..... C C / /< / ___ __________/_#__=o /(- /(\_\________ \ \ ) \ )_ \o \ /|\ /|\ |' | | _| /o __\ / ' | / / | /_/\______| ( _( < \ \ \ \ \ | \____\____\ ____\_\__\_\ /` /` o\ |___ |_______|.. . b'ger IN THE FINAL BUILD THIS FILE DOESN'T HAVE DIRECT ACCESS TO GLOBAL FUNCTIONS DEFINED IN Angular.js YOU *MUST* REFER TO THEM VIA angular OBJECT (e.g. angular.forEach(...)) AND MAKE SURE THAT THE GIVEN FUNCTION IS EXPORTED TO THE angular NAMESPACE in AngularPublic.js */ /** * @workInProgress * @ngdoc overview * @name angular.mock * @description * * The `angular.mock` object is a namespace for all built-in mock services that ship with angular. * It automatically replaces real services if the `angular-mocks.js` file is loaded after * `angular.js` and before any tests. * * Built-in mocks: * * * {@link angular.mock.service.$browser $browser } - A mock implementation of the browser. * * {@link angular.mock.service.$exceptionHandler $exceptionHandler } - A mock implementation of the * angular service exception handler. * * {@link angular.mock.service.$log $log } - A mock implementation of the angular service log. */ angular.mock = {}; /** * @workInProgress * @ngdoc service * @name angular.mock.service.$browser */ function MockBrowser() { var self = this, expectations = {}, requests = []; this.isMock = true; self.url = "http://server"; self.lastUrl = self.url; // used by url polling fn self.pollFns = []; // register url polling fn self.onHashChange = function(listener) { self.pollFns.push( function() { if (self.lastUrl != self.url) { self.lastUrl = self.url; listener(); } } ); return listener; }; self.xhr = function(method, url, data, callback, headers) { headers = headers || {}; if (data && angular.isObject(data)) data = angular.toJson(data); if (data && angular.isString(data)) url += "|" + data; var expect = expectations[method] || {}; var expectation = expect[url]; if (!expectation) { throw new Error("Unexpected request for method '" + method + "' and url '" + url + "'."); } requests.push(function(){ angular.forEach(expectation.headers, function(value, key){ if (headers[key] !== value) { throw new Error("Missing HTTP request header: " + key + ": " + value); } }); callback(expectation.code, expectation.response); }); }; self.xhr.expectations = expectations; self.xhr.requests = requests; self.xhr.expect = function(method, url, data, headers) { if (data && angular.isObject(data)) data = angular.toJson(data); if (data && angular.isString(data)) url += "|" + data; var expect = expectations[method] || (expectations[method] = {}); return { respond: function(code, response) { if (!angular.isNumber(code)) { response = code; code = 200; } expect[url] = {code:code, response:response, headers: headers || {}}; } }; }; self.xhr.expectGET = angular.bind(self, self.xhr.expect, 'GET'); self.xhr.expectPOST = angular.bind(self, self.xhr.expect, 'POST'); self.xhr.expectDELETE = angular.bind(self, self.xhr.expect, 'DELETE'); self.xhr.expectPUT = angular.bind(self, self.xhr.expect, 'PUT'); self.xhr.expectJSON = angular.bind(self, self.xhr.expect, 'JSON'); self.xhr.flush = function() { if (requests.length == 0) { throw new Error("No xhr requests to be flushed!"); } while(requests.length) { requests.pop()(); } }; self.cookieHash = {}; self.lastCookieHash = {}; self.deferredFns = []; self.defer = function(fn) { self.deferredFns.push(fn); }; self.defer.flush = function() { while (self.deferredFns.length) self.deferredFns.shift()(); }; } MockBrowser.prototype = { poll: function poll(){ angular.forEach(this.pollFns, function(pollFn){ pollFn(); }); }, addPollFn: function(pollFn) { this.pollFns.push(pollFn); return pollFn; }, hover: function(onHover) { }, getUrl: function(){ return this.url; }, setUrl: function(url){ this.url = url; }, cookies: function(name, value) { if (name) { if (value == undefined) { delete this.cookieHash[name]; } else { if (angular.isString(value) && //strings only value.length <= 4096) { //strict cookie storage limits this.cookieHash[name] = value; } } } else { if (!angular.equals(this.cookieHash, this.lastCookieHash)) { this.lastCookieHash = angular.copy(this.cookieHash); this.cookieHash = angular.copy(this.cookieHash); } return this.cookieHash; } }, addJs: function(){} }; angular.service('$browser', function(){ return new MockBrowser(); }); /** * @workInProgress * @ngdoc service * @name angular.mock.service.$exceptionHandler * * @description * Mock implementation of {@link angular.service.$exceptionHandler} that rethrows any error passed * into `$exceptionHandler`. If any errors are are passed into the handler in tests, it typically * means that there is a bug in the application or test, so this mock will make these tests fail. * * See {@link angular.mock} for more info on angular mocks. */ angular.service('$exceptionHandler', function(e) { return function(e) {throw e;}; }); /** * @workInProgress * @ngdoc service * @name angular.mock.service.$log * * @description * Mock implementation of {@link angular.service.$log} that gathers all logged messages in arrays * (one array per logging level). These arrays are exposed as `logs` property of each of the * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`. * * See {@link angular.mock} for more info on angular mocks. */ angular.service('$log', MockLogFactory); function MockLogFactory() { var $log = { log: function(){ $log.log.logs.push(arguments); }, warn: function(){ $log.warn.logs.push(arguments); }, info: function(){ $log.info.logs.push(arguments); }, error: function(){ $log.error.logs.push(arguments); } }; $log.log.logs = []; $log.warn.logs = []; $log.info.logs = []; $log.error.logs = []; return $log; } /** * Mock of the Date type which has its timezone specified via constroctor arg. * * The main purpose is to create Date-like instances with timezone fixed to the specified timezone * offset, so that we can test code that depends on local timezone settings without dependency on * the time zone settings of the machine where the code is running. * * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored) * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC* * * @example * !!!! WARNING !!!!! * This is not a complete Date object so only methods that were implemented can be called safely. * To make matters worse, TzDate instances inherit stuff from Date via a prototype. * * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is * incomplete we might be missing some non-standard methods. This can result in errors like: * "Date.prototype.foo called on incompatible Object". * * <pre> * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z'); * newYearInBratislava.getTimezoneOffset() => -60; * newYearInBratislava.getFullYear() => 2010; * newYearInBratislava.getMonth() => 0; * newYearInBratislava.getDate() => 1; * newYearInBratislava.getHours() => 0; * newYearInBratislava.getMinutes() => 0; * </pre> * */ function TzDate(offset, timestamp) { if (angular.isString(timestamp)) { var tsStr = timestamp; this.origDate = angular.String.toDate(timestamp); timestamp = this.origDate.getTime(); if (isNaN(timestamp)) throw { name: "Illegal Argument", message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string" }; } else { this.origDate = new Date(timestamp); } var localOffset = new Date(timestamp).getTimezoneOffset(); this.offsetDiff = localOffset*60*1000 - offset*1000*60*60; this.date = new Date(timestamp + this.offsetDiff); this.getTime = function() { return this.date.getTime() - this.offsetDiff; }; this.toLocaleDateString = function() { return this.date.toLocaleDateString(); }; this.getFullYear = function() { return this.date.getFullYear(); }; this.getMonth = function() { return this.date.getMonth(); }; this.getDate = function() { return this.date.getDate(); }; this.getHours = function() { return this.date.getHours(); }; this.getMinutes = function() { return this.date.getMinutes(); }; this.getSeconds = function() { return this.date.getSeconds(); }; this.getTimezoneOffset = function() { return offset * 60; }; this.getUTCFullYear = function() { return this.origDate.getUTCFullYear(); }; this.getUTCMonth = function() { return this.origDate.getUTCMonth(); }; this.getUTCDate = function() { return this.origDate.getUTCDate(); }; this.getUTCHours = function() { return this.origDate.getUTCHours(); }; this.getUTCMinutes = function() { return this.origDate.getUTCMinutes(); }; this.getUTCSeconds = function() { return this.origDate.getUTCSeconds(); }; //hide all methods not implemented in this mock that the Date prototype exposes var unimplementedMethods = ['getDay', 'getMilliseconds', 'getTime', 'getUTCDay', 'getUTCMilliseconds', 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', 'setYear', 'toDateString', 'toJSON', 'toGMTString', 'toLocaleFormat', 'toLocaleString', 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf']; angular.forEach(unimplementedMethods, function(methodName) { this[methodName] = function() { throw { name: "MethodNotImplemented", message: "Method '" + methodName + "' is not implemented in the TzDate mock" }; }; }); } //make "tzDateInstance instanceof Date" return true TzDate.prototype = Date.prototype;
module.exports = function(hljs) { var LASSO_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9_.]*'; var LASSO_ANGLE_RE = '<\\?(lasso(script)?|=)'; var LASSO_CLOSE_RE = '\\]|\\?>'; var LASSO_KEYWORDS = { literal: 'true false none minimal full all void and or not ' + 'bw nbw ew new cn ncn lt lte gt gte eq neq rx nrx ft', built_in: 'array date decimal duration integer map pair string tag xml null ' + 'bytes list queue set stack staticarray tie local var variable ' + 'global data self inherited', keyword: 'error_code error_msg error_pop error_push error_reset cache ' + 'database_names database_schemanames database_tablenames define_tag ' + 'define_type email_batch encode_set html_comment handle handle_error ' + 'header if inline iterate ljax_target link link_currentaction ' + 'link_currentgroup link_currentrecord link_detail link_firstgroup ' + 'link_firstrecord link_lastgroup link_lastrecord link_nextgroup ' + 'link_nextrecord link_prevgroup link_prevrecord log loop ' + 'namespace_using output_none portal private protect records referer ' + 'referrer repeating resultset rows search_args search_arguments ' + 'select sort_args sort_arguments thread_atomic value_list while ' + 'abort case else if_empty if_false if_null if_true loop_abort ' + 'loop_continue loop_count params params_up return return_value ' + 'run_children soap_definetag soap_lastrequest soap_lastresponse ' + 'tag_name ascending average by define descending do equals ' + 'frozen group handle_failure import in into join let match max ' + 'min on order parent protected provide public require returnhome ' + 'skip split_thread sum take thread to trait type where with ' + 'yield yieldhome' }; var HTML_COMMENT = { className: 'comment', begin: '<!--', end: '-->', relevance: 0 }; var LASSO_NOPROCESS = { className: 'preprocessor', begin: '\\[noprocess\\]', starts: { className: 'markup', end: '\\[/noprocess\\]', returnEnd: true, contains: [HTML_COMMENT] } }; var LASSO_START = { className: 'preprocessor', begin: '\\[/noprocess|' + LASSO_ANGLE_RE }; var LASSO_DATAMEMBER = { className: 'variable', begin: '\'' + LASSO_IDENT_RE + '\'' }; var LASSO_CODE = [ hljs.C_LINE_COMMENT_MODE, { className: 'javadoc', begin: '/\\*\\*!', end: '\\*/', contains: [hljs.PHRASAL_WORDS_MODE] }, hljs.C_BLOCK_COMMENT_MODE, hljs.inherit(hljs.C_NUMBER_MODE, {begin: hljs.C_NUMBER_RE + '|-?(infinity|nan)\\b'}), hljs.inherit(hljs.APOS_STRING_MODE, {illegal: null}), hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null}), { className: 'string', begin: '`', end: '`' }, { className: 'variable', variants: [ { begin: '[#$]' + LASSO_IDENT_RE }, { begin: '#', end: '\\d+', illegal: '\\W' } ] }, { className: 'tag', begin: '::\\s*', end: LASSO_IDENT_RE, illegal: '\\W' }, { className: 'attribute', variants: [ { begin: '-' + hljs.UNDERSCORE_IDENT_RE, relevance: 0 }, { begin: '(\\.\\.\\.)' } ] }, { className: 'subst', variants: [ { begin: '->\\s*', contains: [LASSO_DATAMEMBER] }, { begin: ':=|/(?!\\w)=?|[-+*%=<>&|!?\\\\]+', relevance: 0 } ] }, { className: 'built_in', begin: '\\.\\.?', relevance: 0, contains: [LASSO_DATAMEMBER] }, { className: 'class', beginKeywords: 'define', returnEnd: true, end: '\\(|=>', contains: [ hljs.inherit(hljs.TITLE_MODE, {begin: hljs.UNDERSCORE_IDENT_RE + '(=(?!>))?'}) ] } ]; return { aliases: ['ls', 'lassoscript'], case_insensitive: true, lexemes: LASSO_IDENT_RE + '|&[lg]t;', keywords: LASSO_KEYWORDS, contains: [ { className: 'preprocessor', begin: LASSO_CLOSE_RE, relevance: 0, starts: { className: 'markup', end: '\\[|' + LASSO_ANGLE_RE, returnEnd: true, relevance: 0, contains: [HTML_COMMENT] } }, LASSO_NOPROCESS, LASSO_START, { className: 'preprocessor', begin: '\\[no_square_brackets', starts: { end: '\\[/no_square_brackets\\]', // not implemented in the language lexemes: LASSO_IDENT_RE + '|&[lg]t;', keywords: LASSO_KEYWORDS, contains: [ { className: 'preprocessor', begin: LASSO_CLOSE_RE, relevance: 0, starts: { className: 'markup', end: LASSO_ANGLE_RE, returnEnd: true, contains: [HTML_COMMENT] } }, LASSO_NOPROCESS, LASSO_START ].concat(LASSO_CODE) } }, { className: 'preprocessor', begin: '\\[', relevance: 0 }, { className: 'shebang', begin: '^#!.+lasso9\\b', relevance: 10 } ].concat(LASSO_CODE) }; };
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview provides a reusable youtube UI component given a youtube data * model. * * goog.ui.media.Youtube is actually a {@link goog.ui.ControlRenderer}, a * stateless class - that could/should be used as a Singleton with the static * method {@code goog.ui.media.Youtube.getInstance} -, that knows how to render * youtube videos. It is designed to be used with a {@link goog.ui.Control}, * which will actually control the media renderer and provide the * {@link goog.ui.Component} base. This design guarantees that all different * types of medias will behave alike but will look different. * * goog.ui.media.Youtube expects {@code goog.ui.media.YoutubeModel} on * {@code goog.ui.Control.getModel} as data models, and render a flash object * that will play that URL. * * Example of usage: * * <pre> * var video = goog.ui.media.YoutubeModel.newInstance( * 'http://www.youtube.com/watch?v=ddl5f44spwQ'); * goog.ui.media.Youtube.newControl(video).render(); * </pre> * * youtube medias currently support the following states: * * <ul> * <li> {@link goog.ui.Component.State.DISABLED}: shows 'flash not available' * <li> {@link goog.ui.Component.State.HOVER}: mouse cursor is over the video * <li> {@link !goog.ui.Component.State.SELECTED}: a static thumbnail is shown * <li> {@link goog.ui.Component.State.SELECTED}: video is playing * </ul> * * Which can be accessed by * <pre> * youtube.setEnabled(true); * youtube.setHighlighted(true); * youtube.setSelected(true); * </pre> * * This package also provides a few static auxiliary methods, such as: * * <pre> * var videoId = goog.ui.media.Youtube.parseUrl( * 'http://www.youtube.com/watch?v=ddl5f44spwQ'); * </pre> * * * @supported IE6, FF2+, Safari. Requires flash to actually work. * * TODO(user): test on other browsers */ goog.provide('goog.ui.media.Youtube'); goog.provide('goog.ui.media.YoutubeModel'); goog.require('goog.string'); goog.require('goog.ui.Component.Error'); goog.require('goog.ui.Component.State'); goog.require('goog.ui.media.FlashObject'); goog.require('goog.ui.media.Media'); goog.require('goog.ui.media.MediaModel'); goog.require('goog.ui.media.MediaModel.Player'); goog.require('goog.ui.media.MediaModel.Thumbnail'); goog.require('goog.ui.media.MediaRenderer'); /** * Subclasses a goog.ui.media.MediaRenderer to provide a Youtube specific media * renderer. * * This class knows how to parse youtube urls, and render the DOM structure * of youtube video players and previews. This class is meant to be used as a * singleton static stateless class, that takes {@code goog.ui.media.Media} * instances and renders it. It expects {@code goog.ui.media.Media.getModel} to * return a well formed, previously constructed, youtube video id, which is the * data model this renderer will use to construct the DOM structure. * {@see goog.ui.media.Youtube.newControl} for a example of constructing a * control with this renderer. * * goog.ui.media.Youtube currently supports all {@link goog.ui.Component.State}. * It will change its DOM structure between SELECTED and !SELECTED, and rely on * CSS definitions on the others. On !SELECTED, the renderer will render a * youtube static <img>, with a thumbnail of the video. On SELECTED, the * renderer will append to the DOM a flash object, that contains the youtube * video. * * This design is patterned after http://go/closure_control_subclassing * * It uses {@link goog.ui.media.FlashObject} to embed the flash object. * * @constructor * @extends {goog.ui.media.MediaRenderer} */ goog.ui.media.Youtube = function() { goog.ui.media.MediaRenderer.call(this); }; goog.inherits(goog.ui.media.Youtube, goog.ui.media.MediaRenderer); goog.addSingletonGetter(goog.ui.media.Youtube); /** * A static convenient method to construct a goog.ui.media.Media control out of * a youtube model. It sets it as the data model goog.ui.media.Youtube renderer * uses, sets the states supported by the renderer, and returns a Control that * binds everything together. This is what you should be using for constructing * Youtube videos, except if you need finer control over the configuration. * * @param {goog.ui.media.YoutubeModel} youtubeModel The youtube data model. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for * document interaction. * @return {goog.ui.media.Media} A Control binded to the youtube renderer. * @suppress {visibility} Calling protected control.setStateInternal(). */ goog.ui.media.Youtube.newControl = function(youtubeModel, opt_domHelper) { var control = new goog.ui.media.Media( youtubeModel, goog.ui.media.Youtube.getInstance(), opt_domHelper); control.setStateInternal(goog.ui.Component.State.ACTIVE); return control; }; /** * Default CSS class to be applied to the root element of components rendered * by this renderer. * @type {string} */ goog.ui.media.Youtube.CSS_CLASS = goog.getCssName('goog-ui-media-youtube'); /** * Changes the state of a {@code control}. Currently only changes the DOM * structure when the youtube movie is SELECTED (by default fired by a MOUSEUP * on the thumbnail), which means we have to embed the youtube flash video and * play it. * * @param {goog.ui.Control} c The media control. * @param {goog.ui.Component.State} state The state to be set or cleared. * @param {boolean} enable Whether the state is enabled or disabled. * @override */ goog.ui.media.Youtube.prototype.setState = function(c, state, enable) { var control = /** @type {goog.ui.media.Media} */ (c); goog.ui.media.Youtube.superClass_.setState.call(this, control, state, enable); // control.createDom has to be called before any state is set. // Use control.setStateInternal if you need to set states if (!control.getElement()) { throw Error(goog.ui.Component.Error.STATE_INVALID); } var domHelper = control.getDomHelper(); var dataModel = /** @type {goog.ui.media.YoutubeModel} */ (control.getDataModel()); if (!!(state & goog.ui.Component.State.SELECTED) && enable) { var flashEls = domHelper.getElementsByTagNameAndClass( 'div', goog.ui.media.FlashObject.CSS_CLASS, control.getElement()); if (flashEls.length > 0) { return; } var youtubeFlash = new goog.ui.media.FlashObject( dataModel.getPlayer().getUrl() || '', domHelper); control.addChild(youtubeFlash, true); } }; /** * Returns the CSS class to be applied to the root element of components * rendered using this renderer. * * @return {string} Renderer-specific CSS class. * @override */ goog.ui.media.Youtube.prototype.getCssClass = function() { return goog.ui.media.Youtube.CSS_CLASS; }; /** * The {@code goog.ui.media.Youtube} media data model. It stores a required * {@code videoId} field, sets the youtube URL, and allows a few optional * parameters. * * @param {string} videoId The youtube video id. * @param {string=} opt_caption An optional caption of the youtube video. * @param {string=} opt_description An optional description of the youtube * video. * @constructor * @extends {goog.ui.media.MediaModel} */ goog.ui.media.YoutubeModel = function(videoId, opt_caption, opt_description) { goog.ui.media.MediaModel.call( this, goog.ui.media.YoutubeModel.buildUrl(videoId), opt_caption, opt_description, goog.ui.media.MediaModel.MimeType.FLASH); /** * The Youtube video id. * @type {string} * @private */ this.videoId_ = videoId; this.setThumbnails([new goog.ui.media.MediaModel.Thumbnail( goog.ui.media.YoutubeModel.getThumbnailUrl(videoId))]); this.setPlayer(new goog.ui.media.MediaModel.Player( this.getFlashUrl(videoId, true))); }; goog.inherits(goog.ui.media.YoutubeModel, goog.ui.media.MediaModel); /** * A youtube regular expression matcher. It matches the VIDEOID of URLs like * http://www.youtube.com/watch?v=VIDEOID. Based on: * googledata/contentonebox/opencob/specs/common/YTPublicExtractorCard.xml * @type {RegExp} * @private * @const */ // Be careful about the placement of the dashes in the character classes. Eg, // use "[\\w=-]" instead of "[\\w-=]" if you mean to include the dash as a // character and not create a character range like "[a-f]". goog.ui.media.YoutubeModel.MATCHER_ = new RegExp( // Lead in. 'http://(?:[a-zA-Z]{2,3}\\.)?' + // Watch URL prefix. This should handle new URLs of the form: // http://www.youtube.com/watch#!v=jqxENMKaeCU&feature=related // where the parameters appear after "#!" instead of "?". '(?:youtube\\.com/watch)' + // Get the video id: // The video ID is a parameter v=[videoid] either right after the "?" // or after some other parameters. '(?:\\?(?:[\\w=-]+&(?:amp;)?)*v=([\\w-]+)' + '(?:&(?:amp;)?[\\w=-]+)*)?' + // Get any extra arguments in the URL's hash part. '(?:#[!]?(?:' + // Video ID from the v=[videoid] parameter, optionally surrounded by other // & separated parameters. '(?:(?:[\\w=-]+&(?:amp;)?)*(?:v=([\\w-]+))' + '(?:&(?:amp;)?[\\w=-]+)*)' + '|' + // Continue supporting "?" for the video ID // and "#" for other hash parameters. '(?:[\\w=&-]+)' + '))?' + // Should terminate with a non-word, non-dash (-) character. '[^\\w-]?', 'i'); /** * A auxiliary static method that parses a youtube URL, extracting the ID of the * video, and builds a YoutubeModel. * * @param {string} youtubeUrl A youtube URL. * @param {string=} opt_caption An optional caption of the youtube video. * @param {string=} opt_description An optional description of the youtube * video. * @return {goog.ui.media.YoutubeModel} The data model that represents the * youtube URL. * @see goog.ui.media.YoutubeModel.getVideoId() * @throws Error in case the parsing fails. */ goog.ui.media.YoutubeModel.newInstance = function(youtubeUrl, opt_caption, opt_description) { var extract = goog.ui.media.YoutubeModel.MATCHER_.exec(youtubeUrl); if (extract) { var videoId = extract[1] || extract[2]; return new goog.ui.media.YoutubeModel( videoId, opt_caption, opt_description); } throw Error('failed to parse video id from youtube url: ' + youtubeUrl); }; /** * The opposite of {@code goog.ui.media.Youtube.newInstance}: it takes a videoId * and returns a youtube URL. * * @param {string} videoId The youtube video ID. * @return {string} The youtube URL. */ goog.ui.media.YoutubeModel.buildUrl = function(videoId) { return 'http://www.youtube.com/watch?v=' + goog.string.urlEncode(videoId); }; /** * A static auxiliary method that builds a static image URL with a preview of * the youtube video. * * NOTE(user): patterned after Gmail's gadgets/youtube, * * TODO(user): how do I specify the width/height of the resulting image on the * url ? is there an official API for http://ytimg.com ? * * @param {string} youtubeId The youtube video ID. * @return {string} An URL that contains an image with a preview of the youtube * movie. */ goog.ui.media.YoutubeModel.getThumbnailUrl = function(youtubeId) { return 'http://i.ytimg.com/vi/' + youtubeId + '/default.jpg'; }; /** * An auxiliary method that builds URL of the flash movie to be embedded, * out of the youtube video id. * * @param {string} videoId The youtube video ID. * @param {boolean=} opt_autoplay Whether the flash movie should start playing * as soon as it is shown, or if it should show a 'play' button. * @return {string} The flash URL to be embedded on the page. */ goog.ui.media.YoutubeModel.prototype.getFlashUrl = function(videoId, opt_autoplay) { var autoplay = opt_autoplay ? '&autoplay=1' : ''; // YouTube video ids are extracted from youtube URLs, which are user // generated input. the video id is later used to embed a flash object, // which is generated through HTML construction. We goog.string.urlEncode // the video id to make sure the URL is safe to be embedded. return 'http://www.youtube.com/v/' + goog.string.urlEncode(videoId) + '&hl=en&fs=1' + autoplay; }; /** * Gets the Youtube video id. * @return {string} The Youtube video id. */ goog.ui.media.YoutubeModel.prototype.getVideoId = function() { return this.videoId_; };
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "PG", "PTG" ], "DAY": [ "Ahad", "Isnin", "Selasa", "Rabu", "Khamis", "Jumaat", "Sabtu" ], "ERANAMES": [ "S.M.", "TM" ], "ERAS": [ "S.M.", "TM" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "Januari", "Februari", "Mac", "April", "Mei", "Jun", "Julai", "Ogos", "September", "Oktober", "November", "Disember" ], "SHORTDAY": [ "Ahd", "Isn", "Sel", "Rab", "Kha", "Jum", "Sab" ], "SHORTMONTH": [ "Jan", "Feb", "Mac", "Apr", "Mei", "Jun", "Jul", "Ogo", "Sep", "Okt", "Nov", "Dis" ], "STANDALONEMONTH": [ "Januari", "Februari", "Mac", "April", "Mei", "Jun", "Julai", "Ogos", "September", "Oktober", "November", "Disember" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "d/MM/yy h:mm a", "shortDate": "d/MM/yy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "RM", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "ms", "pluralCat": function(n, opt_precision) { return PLURAL_CATEGORY.OTHER;} }); }]);
Monocle.Controls.Contents = function (reader) { var API = { constructor: Monocle.Controls.Contents } var k = API.constants = API.constructor; var p = API.properties = { reader: reader } function createControlElements() { var div = reader.dom.make('div', 'controls_contents_container'); contentsForBook(div, reader.getBook()); return div; } function contentsForBook(div, book) { while (div.hasChildNodes()) { div.removeChild(div.firstChild); } var list = div.dom.append('ol', 'controls_contents_list'); var contents = book.properties.contents; for (var i = 0; i < contents.length; ++i) { chapterBuilder(list, contents[i], 0); } } function chapterBuilder(list, chp, padLvl) { var index = list.childNodes.length; var li = list.dom.append('li', 'controls_contents_chapter', index); var span = li.dom.append( 'span', 'controls_contents_chapterTitle', index, { html: chp.title } ); span.style.paddingLeft = padLvl + "em"; var invoked = function () { p.reader.skipToChapter(chp.src); p.reader.hideControl(API); } Monocle.Events.listenForTap(li, invoked, 'controls_contents_chapter_active'); if (chp.children) { for (var i = 0; i < chp.children.length; ++i) { chapterBuilder(list, chp.children[i], padLvl + 1); } } } API.createControlElements = createControlElements; return API; } ; Monocle.Controls.Magnifier = function (reader) { var API = { constructor: Monocle.Controls.Magnifier } var k = API.constants = API.constructor; var p = API.properties = { buttons: [], magnified: false } function initialize() { p.reader = reader; } function createControlElements(holder) { var btn = holder.dom.make('div', 'controls_magnifier_button'); btn.smallA = btn.dom.append('span', 'controls_magnifier_a', { text: 'A' }); btn.largeA = btn.dom.append('span', 'controls_magnifier_A', { text: 'A' }); p.buttons.push(btn); Monocle.Events.listenForTap(btn, toggleMagnification); return btn; } function toggleMagnification(evt) { var opacities; p.magnified = !p.magnified; if (p.magnified) { opacities = [0.3, 1]; p.reader.formatting.setFontScale(k.MAGNIFICATION, true); } else { opacities = [1, 0.3]; p.reader.formatting.setFontScale(null, true); } for (var i = 0; i < p.buttons.length; i++) { p.buttons[i].smallA.style.opacity = opacities[0]; p.buttons[i].largeA.style.opacity = opacities[1]; } } API.createControlElements = createControlElements; initialize(); return API; } Monocle.Controls.Magnifier.MAGNIFICATION = 1.2; // A panel is an invisible column of interactivity. When contact occurs // (mousedown, touchstart), the panel expands to the full width of its // container, to catch all interaction events and prevent them from hitting // other things. // // Panels are used primarily to provide hit zones for page flipping // interactions, but you can do whatever you like with them. // // After instantiating a panel and adding it to the reader as a control, // you can call listenTo() with a hash of methods for any of 'start', 'move' // 'end' and 'cancel'. // Monocle.Controls.Panel = function () { var API = { constructor: Monocle.Controls.Panel } var k = API.constants = API.constructor; var p = API.properties = { evtCallbacks: {} } function createControlElements(cntr) { p.div = cntr.dom.make('div', k.CLS.panel); p.div.dom.setStyles(k.DEFAULT_STYLES); Monocle.Events.listenForContact( p.div, { 'start': start, 'move': move, 'end': end, 'cancel': cancel }, { useCapture: false } ); return p.div; } function setDirection(dir) { p.direction = dir; } function listenTo(evtCallbacks) { p.evtCallbacks = evtCallbacks; } function deafen() { p.evtCallbacks = {} } function start(evt) { p.contact = true; evt.m.offsetX += p.div.offsetLeft; evt.m.offsetY += p.div.offsetTop; expand(); invoke('start', evt); } function move(evt) { if (!p.contact) { return; } invoke('move', evt); } function end(evt) { if (!p.contact) { return; } Monocle.Events.deafenForContact(p.div, p.listeners); contract(); p.contact = false; invoke('end', evt); } function cancel(evt) { if (!p.contact) { return; } Monocle.Events.deafenForContact(p.div, p.listeners); contract(); p.contact = false; invoke('cancel', evt); } function invoke(evtType, evt) { if (p.evtCallbacks[evtType]) { p.evtCallbacks[evtType](p.direction, evt.m.offsetX, evt.m.offsetY, API); } evt.preventDefault(); } function expand() { if (p.expanded) { return; } p.div.dom.addClass(k.CLS.expanded); p.expanded = true; } function contract(evt) { if (!p.expanded) { return; } p.div.dom.removeClass(k.CLS.expanded); p.expanded = false; } API.createControlElements = createControlElements; API.listenTo = listenTo; API.deafen = deafen; API.expand = expand; API.contract = contract; API.setDirection = setDirection; return API; } Monocle.Controls.Panel.CLS = { panel: 'panel', expanded: 'controls_panel_expanded' } Monocle.Controls.Panel.DEFAULT_STYLES = { position: 'absolute', height: '100%' } ; Monocle.Controls.PlaceSaver = function (bookId) { var API = { constructor: Monocle.Controls.PlaceSaver } var k = API.constants = API.constructor; var p = API.properties = {} function initialize() { applyToBook(bookId); } function assignToReader(reader) { p.reader = reader; p.reader.listen('monocle:turn', savePlaceToCookie); } function applyToBook(bookId) { p.bkTitle = bookId.toLowerCase().replace(/[^a-z0-9]/g, ''); p.prefix = k.COOKIE_NAMESPACE + p.bkTitle + "."; } function setCookie(key, value, days) { var expires = ""; if (days) { var d = new Date(); d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires="+d.toGMTString(); } var path = "; path=/"; document.cookie = p.prefix + key + "=" + value + expires + path; return value; } function getCookie(key) { if (!document.cookie) { return null; } var regex = new RegExp(p.prefix + key + "=(.+?)(;|$)"); var matches = document.cookie.match(regex); if (matches) { return matches[1]; } else { return null; } } function savePlaceToCookie() { var place = p.reader.getPlace(); setCookie( "component", encodeURIComponent(place.componentId()), k.COOKIE_EXPIRES_IN_DAYS ); setCookie( "percent", place.percentageThrough(), k.COOKIE_EXPIRES_IN_DAYS ); } function savedPlace() { var locus = { componentId: getCookie('component'), percent: getCookie('percent') } if (locus.componentId && locus.percent) { locus.componentId = decodeURIComponent(locus.componentId); locus.percent = parseFloat(locus.percent); return locus; } else { return null; } } function restorePlace() { var locus = savedPlace(); if (locus) { p.reader.moveTo(locus); } } API.assignToReader = assignToReader; API.savedPlace = savedPlace; API.restorePlace = restorePlace; initialize(); return API; } Monocle.Controls.PlaceSaver.COOKIE_NAMESPACE = "monocle.controls.placesaver."; Monocle.Controls.PlaceSaver.COOKIE_EXPIRES_IN_DAYS = 7; // Set to 0 for session-based expiry. ; Monocle.Controls.Scrubber = function (reader) { var API = { constructor: Monocle.Controls.Scrubber } var k = API.constants = API.constructor; var p = API.properties = {} function initialize() { p.reader = reader; p.reader.listen('monocle:turn', updateNeedles); updateNeedles(); } function pixelToPlace(x, cntr) { if (!p.componentIds) { p.componentIds = p.reader.getBook().properties.componentIds; p.componentWidth = 100 / p.componentIds.length; } var pc = (x / cntr.offsetWidth) * 100; var cmpt = p.componentIds[Math.floor(pc / p.componentWidth)]; var cmptPc = ((pc % p.componentWidth) / p.componentWidth); return { componentId: cmpt, percentageThrough: cmptPc }; } function placeToPixel(place, cntr) { if (!p.componentIds) { p.componentIds = p.reader.getBook().properties.componentIds; p.componentWidth = 100 / p.componentIds.length; } var componentIndex = p.componentIds.indexOf(place.componentId()); var pc = p.componentWidth * componentIndex; pc += place.percentageThrough() * p.componentWidth; return Math.round((pc / 100) * cntr.offsetWidth); } function updateNeedles() { if (p.hidden || !p.reader.dom.find(k.CLS.container)) { return; } var place = p.reader.getPlace(); var x = placeToPixel(place, p.reader.dom.find(k.CLS.container)); var needle, i = 0; for (var i = 0, needle; needle = p.reader.dom.find(k.CLS.needle, i); ++i) { setX(needle, x - needle.offsetWidth / 2); p.reader.dom.find(k.CLS.trail, i).style.width = x + "px"; } } function setX(node, x) { var cntr = p.reader.dom.find(k.CLS.container); x = Math.min(cntr.offsetWidth - node.offsetWidth, x); x = Math.max(x, 0); Monocle.Styles.setX(node, x); } function createControlElements(holder) { var cntr = holder.dom.make('div', k.CLS.container); var track = cntr.dom.append('div', k.CLS.track); var needleTrail = cntr.dom.append('div', k.CLS.trail); var needle = cntr.dom.append('div', k.CLS.needle); var bubble = cntr.dom.append('div', k.CLS.bubble); var cntrListeners, bodyListeners; var moveEvt = function (evt, x) { evt.preventDefault(); x = (typeof x == "number") ? x : evt.m.registrantX; var place = pixelToPlace(x, cntr); setX(needle, x - needle.offsetWidth / 2); var book = p.reader.getBook(); var chps = book.chaptersForComponent(place.componentId); var cmptIndex = p.componentIds.indexOf(place.componentId); var chp = chps[Math.floor(chps.length * place.percentageThrough)]; if (cmptIndex > -1 && book.properties.components[cmptIndex]) { var actualPlace = Monocle.Place.FromPercentageThrough( book.properties.components[cmptIndex], place.percentageThrough ); chp = actualPlace.chapterInfo() || chp; } if (chp) { bubble.innerHTML = chp.title; } setX(bubble, x - bubble.offsetWidth / 2); p.lastX = x; return place; } var endEvt = function (evt) { var place = moveEvt(evt, p.lastX); p.reader.moveTo({ percent: place.percentageThrough, componentId: place.componentId }); Monocle.Events.deafenForContact(cntr, cntrListeners); Monocle.Events.deafenForContact(document.body, bodyListeners); bubble.style.display = "none"; } var startFn = function (evt) { bubble.style.display = "block"; moveEvt(evt); cntrListeners = Monocle.Events.listenForContact( cntr, { move: moveEvt } ); bodyListeners = Monocle.Events.listenForContact( document.body, { end: endEvt } ); } Monocle.Events.listenForContact(cntr, { start: startFn }); return cntr; } API.createControlElements = createControlElements; API.updateNeedles = updateNeedles; initialize(); return API; } Monocle.Controls.Scrubber.CLS = { container: 'controls_scrubber_container', track: 'controls_scrubber_track', needle: 'controls_scrubber_needle', trail: 'controls_scrubber_trail', bubble: 'controls_scrubber_bubble' } ; Monocle.Controls.Spinner = function (reader) { var API = { constructor: Monocle.Controls.Spinner } var k = API.constants = API.constructor; var p = API.properties = { reader: reader, divs: [], spinCount: 0, repeaters: {}, showForPages: [] } function createControlElements(cntr) { var anim = cntr.dom.make('div', 'controls_spinner_anim'); p.divs.push(anim); return anim; } function registerSpinEvt(startEvtType, stopEvtType) { var label = startEvtType; p.reader.listen(startEvtType, function (evt) { spin(label, evt) }); p.reader.listen(stopEvtType, function (evt) { spun(label, evt) }); } // Registers spin/spun event handlers for certain time-consuming events. // function listenForUsualDelays() { registerSpinEvt('monocle:componentloading', 'monocle:componentloaded'); registerSpinEvt('monocle:componentchanging', 'monocle:componentchange'); registerSpinEvt('monocle:resizing', 'monocle:resize'); registerSpinEvt('monocle:jumping', 'monocle:jump'); registerSpinEvt('monocle:recalculating', 'monocle:recalculated'); } // Displays the spinner. Both arguments are optional. // function spin(label, evt) { label = label || k.GENERIC_LABEL; //console.log('Spinning on ' + (evt ? evt.type : label)); p.repeaters[label] = true; p.reader.showControl(API); // If the delay is on a page other than the page we've been assigned to, // don't show the animation. p.global ensures that if an event affects // all pages, the animation is always shown, even if other events in this // spin cycle are page-specific. var page = evt && evt.m && evt.m.page ? evt.m.page : null; if (!page) { p.global = true; } for (var i = 0; i < p.divs.length; ++i) { var owner = p.divs[i].parentNode.parentNode; if (page == owner) { p.showForPages.push(page); } var show = p.global || p.showForPages.indexOf(page) >= 0; p.divs[i].style.display = show ? 'block' : 'none'; } } // Stops displaying the spinner. Both arguments are optional. // function spun(label, evt) { label = label || k.GENERIC_LABEL; //console.log('Spun on ' + (evt ? evt.type : label)); p.repeaters[label] = false; for (var l in p.repeaters) { if (p.repeaters[l]) { return; } } p.global = false; p.showForPages = []; p.reader.hideControl(API); } API.createControlElements = createControlElements; API.listenForUsualDelays = listenForUsualDelays; API.spin = spin; API.spun = spun; return API; } Monocle.Controls.Spinner.GENERIC_LABEL = "generic"; Monocle.Controls.Stencil = function (reader, behaviorClasses) { var API = { constructor: Monocle.Controls.Stencil } var k = API.constants = API.constructor; var p = API.properties = { reader: reader, behaviors: [], components: {}, masks: [] } // Create the stencil container and listen for draw/update events. // function createControlElements(holder) { behaviorClasses = behaviorClasses || k.DEFAULT_BEHAVIORS; for (var i = 0, ii = behaviorClasses.length; i < ii; ++i) { addBehavior(behaviorClasses[i]); } p.container = holder.dom.make('div', k.CLS.container); p.reader.listen('monocle:turning', hide); p.reader.listen('monocle:turn:cancel', show); p.reader.listen('monocle:turn', update); p.reader.listen('monocle:stylesheetchange', update); p.reader.listen('monocle:resize', update); update(); return p.container; } // Pass this method an object that responds to 'findElements(doc)' with // an array of DOM elements for that document, and to 'fitMask(elem, mask)'. // // After you have added all your behaviors this way, you would typically // call update() to make them take effect immediately. // function addBehavior(bhvrClass) { var bhvr = new bhvrClass(API); if (typeof bhvr.findElements != 'function') { console.warn('Missing "findElements" method for behavior: %o', bhvr); } if (typeof bhvr.fitMask != 'function') { console.warn('Missing "fitMask" method for behavior: %o', bhvr); } p.behaviors.push(bhvr); } // Resets any pre-calculated rectangles for the active component, // recalculates them, and forces masks to be "drawn" (moved into the new // rectangular locations). // function update() { var visPages = p.reader.visiblePages(); if (!visPages || !visPages.length) { return; } var pageDiv = visPages[0]; var cmptId = pageComponentId(pageDiv); if (!cmptId) { return; } p.components[cmptId] = null; calculateRectangles(pageDiv); draw(); } function hide() { p.container.style.display = 'none'; } function show() { p.container.style.display = 'block'; } // Removes any existing masks. function clear() { while (p.container.childNodes.length) { p.container.removeChild(p.container.lastChild); } } // Aligns the stencil container to the shape of the page, then moves the // masks to sit above any currently visible rectangles. // function draw() { var pageDiv = p.reader.visiblePages()[0]; var cmptId = pageComponentId(pageDiv); if (!p.components[cmptId]) { return; } // Position the container. alignToComponent(pageDiv); // Clear old masks. clear(); // Layout the masks. if (!p.disabled) { show(); var rects = p.components[cmptId]; if (rects && rects.length) { layoutRectangles(pageDiv, rects); } } } // Iterate over all the <a> elements in the active component, and // create an array of rectangular points corresponding to their positions. // function calculateRectangles(pageDiv) { var cmptId = pageComponentId(pageDiv); if (!p.components[cmptId]) { p.components[cmptId] = []; } else { return; } var doc = pageDiv.m.activeFrame.contentDocument; var offset = getOffset(pageDiv); for (var b = 0, bb = p.behaviors.length; b < bb; ++b) { var bhvr = p.behaviors[b]; var elems = bhvr.findElements(doc); for (var i = 0; i < elems.length; ++i) { var elem = elems[i]; if (elem.getClientRects) { var r = elem.getClientRects(); for (var j = 0; j < r.length; j++) { p.components[cmptId].push({ element: elem, behavior: bhvr, left: Math.ceil(r[j].left + offset.l), top: Math.ceil(r[j].top), width: Math.floor(r[j].width), height: Math.floor(r[j].height) }); } } } } return p.components[cmptId]; } // Update location of visible rectangles - creating as required. // function layoutRectangles(pageDiv, rects) { var offset = getOffset(pageDiv); var visRects = []; for (var i = 0; i < rects.length; ++i) { if (rectVisible(rects[i], offset.l, offset.l + offset.w)) { visRects.push(rects[i]); } } for (i = 0; i < visRects.length; ++i) { var r = visRects[i]; var cr = { left: r.left - offset.l, top: r.top, width: r.width, height: r.height }; var mask = createMask(r.element, r.behavior); mask.dom.setStyles({ display: 'block', left: cr.left+"px", top: cr.top+"px", width: cr.width+"px", height: cr.height+"px", position: 'absolute' }); mask.stencilRect = cr; } } // Find the offset position in pixels from the left of the current page. // function getOffset(pageDiv) { return { l: pageDiv.m.offset || 0, w: pageDiv.m.dimensions.properties.width }; } // Is this area presently on the screen? // function rectVisible(rect, l, r) { return rect.left >= l && rect.left < r; } // Returns the active component id for the given page, or the current // page if no argument passed in. // function pageComponentId(pageDiv) { pageDiv = pageDiv || p.reader.visiblePages()[0]; if (!pageDiv.m.activeFrame.m.component) { return; } return pageDiv.m.activeFrame.m.component.properties.id; } // Positions the stencil container over the active frame. // function alignToComponent(pageDiv) { cmpt = pageDiv.m.activeFrame.parentNode; p.container.dom.setStyles({ left: cmpt.offsetLeft+"px", top: cmpt.offsetTop+"px" }); } function createMask(element, bhvr) { var mask = p.container.dom.append(bhvr.maskTagName || 'div', k.CLS.mask); Monocle.Events.listenForContact(mask, { start: function () { p.reader.dispatchEvent('monocle:magic:halt'); }, move: function (evt) { evt.preventDefault(); }, end: function () { p.reader.dispatchEvent('monocle:magic:init'); } }); bhvr.fitMask(element, mask); return mask; } // Make the active masks visible (by giving them a class -- override style // in monoctrl.css). // function toggleHighlights() { var cls = k.CLS.highlights; if (p.container.dom.hasClass(cls)) { p.container.dom.removeClass(cls); } else { p.container.dom.addClass(cls); } } function disable() { p.disabled = true; draw(); } function enable() { p.disabled = false; draw(); } function filterElement(elem, behavior) { if (typeof behavior.filterElement == 'function') { return behavior.filterElement(elem); } return elem; } function maskAssigned(elem, mask, behavior) { if (typeof behavior.maskAssigned == 'function') { return behavior.maskAssigned(elem, mask); } return false; } API.createControlElements = createControlElements; API.addBehavior = addBehavior; API.draw = draw; API.update = update; API.toggleHighlights = toggleHighlights; return API; } Monocle.Controls.Stencil.CLS = { container: 'controls_stencil_container', mask: 'controls_stencil_mask', highlights: 'controls_stencil_highlighted' } Monocle.Controls.Stencil.Links = function (stencil) { var API = { constructor: Monocle.Controls.Stencil.Links } // Optionally specify the HTML tagname of the mask. API.maskTagName = 'a'; // Returns an array of all the elements in the given doc that should // be covered with a stencil mask for interactivity. // // (Hint: doc.querySelectorAll() is your friend.) // API.findElements = function (doc) { return doc.querySelectorAll('a[href]'); } // Return an element. It should usually be a child of the container element, // with a className of the given maskClass. You set up the interactivity of // the mask element here. // API.fitMask = function (link, mask) { var hrefObject = deconstructHref(link); if (hrefObject.internal) { mask.setAttribute('href', 'javascript:"Skip to chapter"'); Monocle.Events.listen(mask, 'click', function (evt) { stencil.properties.reader.skipToChapter(hrefObject.internal); evt.preventDefault(); }); } else { mask.setAttribute('href', hrefObject.external); mask.setAttribute('target', '_blank'); link.setAttribute('target', '_blank'); // For good measure. } } // Returns an object with either: // // - an 'external' property -- an absolute URL with a protocol, // host & etc, which should be treated as an external resource (eg, // open in new window) // // OR // // - an 'internal' property -- a relative URL (with optional hash anchor), // that is treated as a link to component in the book // // A weird but useful property of <a> tags is that while // link.getAttribute('href') will return the actual string value of the // attribute (eg, 'foo.html'), link.href will return the absolute URL (eg, // 'http://example.com/monocles/foo.html'). // function deconstructHref(elem) { var url = elem.href; if (!elem.getAttribute('target')) { var m = url.match(/([^#]*)(#.*)?$/); var path = m[1]; var anchor = m[2] || ''; var cmpts = stencil.properties.reader.getBook().properties.componentIds; for (var i = 0, ii = cmpts.length; i < ii; ++i) { if (path.substr(0 - cmpts[i].length) == cmpts[i]) { return { internal: cmpts[i] + anchor }; } } } return { external: url }; } return API; } Monocle.Controls.Stencil.DEFAULT_BEHAVIORS = [Monocle.Controls.Stencil.Links];
(function () { function RunningInNode () { return( (typeof require) == "function" && (typeof exports) == "object" && (typeof module) == "object" && (typeof __filename) == "string" && (typeof __dirname) == "string" ); } if (!RunningInNode()) { if (!this.Tautologistics) this.Tautologistics = {}; if (!this.Tautologistics.NodeHtmlParser) this.Tautologistics.NodeHtmlParser = {}; if (!this.Tautologistics.NodeHtmlParser.Tests) this.Tautologistics.NodeHtmlParser.Tests = []; exports = {}; this.Tautologistics.NodeHtmlParser.Tests.push(exports); } exports.name = "Basic test"; exports.html = "<html><title>The Title</title><body>Hello world</body></html>"; exports.expected = [ { raw: 'html' , data: 'html' , type: 'tag' , name: 'html' , children: [ { raw: 'title' , data: 'title' , type: 'tag' , name: 'title' , children: [ { raw: 'The Title', data: 'The Title', type: 'text' } ] } , { raw: 'body' , data: 'body' , type: 'tag' , name: 'body' , children: [ { raw: 'Hello world' , data: 'Hello world' , type: 'text' } ] } ] } ]; })();
class Semicolon { ; }
'use strict'; var $export = require('./$.export'); var $re = require('./$.replacer')(/&(?:amp|lt|gt|quot|apos);/g, { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&apos;': "'" }); $export($export.P + $export.F, 'String', {unescapeHTML: function unescapeHTML(){ return $re(this); }});
/*************** Details ***************/ /*! * velocity.ui.js: UI effects pack for Velocity. Load this file after jquery.velocity.js. * @version 4.0.5 * @docs http://velocityjs.org/#uiPack * @support <=IE8: Callouts will have no effect, and transitions will simply fade in/out. IE9/Android 2.3: Most effects are fully supported, the rest fade in/out. All other browsers: Full support. * @license Copyright Julian Shapiro. MIT License: http://en.wikipedia.org/wiki/MIT_License * @license Indicated portions adapted from Animate.css, copyright Daniel Eden. MIT License: http://en.wikipedia.org/wiki/MIT_License * @license Indicated portions adapted from Magic.css, copyright Christian Pucci. MIT License: http://en.wikipedia.org/wiki/MIT_License */ (function() { /************* Setup *************/ var Container = (window.jQuery || window.Zepto || window); if (!Container.Velocity || !Container.Velocity.Utilities) { console.log("Velocity UI Pack: Velocity must be loaded first. Aborting."); return; } if (!Container.Velocity.version || (Container.Velocity.version.major <= 0 && Container.Velocity.version.minor <= 5 && Container.Velocity.version.patch <= 2)) { var abortError = "Velocity UI Pack: You need to update Velocity (jquery.velocity.js) to a newer version. Visit http://github.com/julianshapiro/velocity."; alert(abortError); throw new Error(abortError); } /****************** Registration ******************/ Container.Velocity.RegisterUI = function (effectName, properties) { /* Animate the expansion/contraction of the elements' parent's height for In/Out effects. */ function animateParentHeight (elements, direction, totalDuration, stagger) { var totalHeightDelta = 0, parentNode; /* Sum the total height (including padding and margin) of all targeted elements. */ Container.Velocity.Utilities.each(elements, function(i, element) { if (stagger) { /* Increase the totalDuration by the successive delay amounts produced by the stagger option. */ totalDuration += i * stagger; } parentNode = element.parentNode; Container.Velocity.Utilities.each([ "height", "paddingTop", "paddingBottom", "marginTop", "marginBottom"], function(i, property) { totalHeightDelta += parseFloat(Container.Velocity.CSS.getPropertyValue(element, property)); }); }); /* Animate the parent element's height adjustment (with a varying duration multiplier for aesthetic benefits). */ Container.Velocity.animate( parentNode, { height: (direction === "In" ? "+" : "-") + "=" + totalHeightDelta }, { queue: false, easing: "ease-in-out", duration: totalDuration * (direction === "In" ? 0.6 : 1) } ); } /* Register a custom sequence for each effect. */ Container.Velocity.Sequences[effectName] = function (element, sequenceOptions, elementsIndex, elementsSize, elements, promiseData) { var finalElement = (elementsIndex === elementsSize - 1); /* Iterate through each effect's call array. */ for (var callIndex = 0; callIndex < properties.calls.length; callIndex++) { var call = properties.calls[callIndex], propertyMap = call[0], sequenceDuration = (sequenceOptions.duration || properties.defaultDuration || 1000), durationPercentage = call[1], callOptions = call[2] || {}, opts = {}; /* Assign the whitelisted per-call options. */ opts.duration = sequenceDuration * (durationPercentage || 1); opts.queue = sequenceOptions.queue || ""; opts.easing = callOptions.easing || "ease"; opts.delay = callOptions.delay || 0; /* Special processing for the first effect call. */ if (callIndex === 0) { /* If a delay was passed into the sequence, combine it with the first call's delay. */ opts.delay += (sequenceOptions.delay || 0); if (elementsIndex === 0) { opts.begin = function() { /* Only trigger a begin callback on the first effect call with the first element in the set. */ sequenceOptions.begin && sequenceOptions.begin.call(elements, elements); /* Only trigger animateParentHeight() if we're using an In/Out transition. */ var direction = effectName.match(/(In|Out)$/); if (sequenceOptions.animateParentHeight && direction) { animateParentHeight(elements, direction[0], sequenceDuration + opts.delay, sequenceOptions.stagger); } } } /* If the user isn't overriding the display option, default to "auto" for "In"-suffixed transitions. */ if (sequenceOptions.display !== null) { if (sequenceOptions.display && sequenceOptions.display !== "none") { opts.display = sequenceOptions.display; } else if (/In$/.test(effectName)) { /* Inline elements cannot be subjected to transforms, so we switch them to inline-block. */ var defaultDisplay = Container.Velocity.CSS.Values.getDisplayType(element); opts.display = (defaultDisplay === "inline") ? "inline-block" : defaultDisplay; } } if (sequenceOptions.visibility && sequenceOptions.visibility !== "hidden") { opts.visibility = sequenceOptions.visibility; } } /* Special processing for the last effect call. */ if (callIndex === properties.calls.length - 1) { /* Append promise resolving onto the user's sequence callback. */ function injectFinalCallbacks () { if (sequenceOptions.display === undefined && /Out$/.test(effectName)) { Container.Velocity.Utilities.each(elements, function(i, element) { Container.Velocity.CSS.setPropertyValue(element, "display", "none"); }); } sequenceOptions.complete && sequenceOptions.complete.call(elements, elements); if (promiseData) { promiseData.resolver(elements || element); } } opts.complete = function() { if (properties.reset) { for (var resetProperty in properties.reset) { var resetValue = properties.reset[resetProperty]; /* Format each non-array value in the reset property map to [ value, value ] so that changes apply immediately and DOM querying is avoided (via forcefeeding). */ if (typeof resetValue === "string" || typeof resetValue === "number") { properties.reset[resetProperty] = [ properties.reset[resetProperty], properties.reset[resetProperty] ]; } } /* So that the reset values are applied instantly upon the next rAF tick, use a zero duration and parallel queueing. */ var resetOptions = { duration: 0, queue: false }; /* Since the reset option uses up the complete callback, we trigger the user's complete callback at the end of ours. */ if (finalElement) { resetOptions.complete = injectFinalCallbacks; } Container.Velocity.animate(element, properties.reset, resetOptions); /* Only trigger the user's complete callback on the last effect call with the last element in the set. */ } else if (finalElement) { injectFinalCallbacks(); } }; if (sequenceOptions.visibility === "hidden") { opts.visibility = sequenceOptions.visibility; } } Container.Velocity.animate(element, propertyMap, opts); } }; }; /********************* Packaged Effects *********************/ /* Externalize the packagedEffects data so that they can optionally be modified and re-registered. */ Container.Velocity.RegisterUI.packagedEffects = { /* Animate.css */ "callout.bounce": { defaultDuration: 550, calls: [ [ { translateY: -30 }, 0.25 ], [ { translateY: 0 }, 0.125 ], [ { translateY: -15 }, 0.125 ], [ { translateY: 0 }, 0.25 ] ] }, /* Animate.css */ "callout.shake": { defaultDuration: 800, calls: [ [ { translateX: -11 }, 0.125 ], [ { translateX: 11 }, 0.125 ], [ { translateX: -11 }, 0.125 ], [ { translateX: 11 }, 0.125 ], [ { translateX: -11 }, 0.125 ], [ { translateX: 11 }, 0.125 ], [ { translateX: -11 }, 0.125 ], [ { translateX: 0 }, 0.125 ] ] }, /* Animate.css */ "callout.flash": { defaultDuration: 1100, calls: [ [ { opacity: [ 0, "easeInOutQuad", 1 ] }, 0.25 ], [ { opacity: [ 1, "easeInOutQuad" ] }, 0.25 ], [ { opacity: [ 0, "easeInOutQuad" ] }, 0.25 ], [ { opacity: [ 1, "easeInOutQuad" ] }, 0.25 ] ] }, /* Animate.css */ "callout.pulse": { defaultDuration: 825, calls: [ [ { scaleX: 1.1, scaleY: 1.1 }, 0.50 ], [ { scaleX: 1, scaleY: 1 }, 0.50 ] ] }, /* Animate.css */ "callout.swing": { defaultDuration: 950, calls: [ [ { rotateZ: 15 }, 0.20 ], [ { rotateZ: -10 }, 0.20 ], [ { rotateZ: 5 }, 0.20 ], [ { rotateZ: -5 }, 0.20 ], [ { rotateZ: 0 }, 0.20 ] ] }, /* Animate.css */ "callout.tada": { defaultDuration: 1000, calls: [ [ { scaleX: 0.9, scaleY: 0.9, rotateZ: -3 }, 0.10 ], [ { scaleX: 1.1, scaleY: 1.1, rotateZ: 3 }, 0.10 ], [ { scaleX: 1.1, scaleY: 1.1, rotateZ: -3 }, 0.10 ], [ "reverse", 0.125 ], [ "reverse", 0.125 ], [ "reverse", 0.125 ], [ "reverse", 0.125 ], [ "reverse", 0.125 ], [ { scaleX: 1, scaleY: 1, rotateZ: 0 }, 0.20 ] ] }, "transition.fadeIn": { defaultDuration: 500, calls: [ [ { opacity: [ 1, 0 ] } ] ] }, "transition.fadeOut": { defaultDuration: 500, calls: [ [ { opacity: [ 0, 1 ] } ] ] }, /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.flipXIn": { defaultDuration: 700, calls: [ [ { opacity: [ 1, 0 ], transformPerspective: [ 800, 800 ], rotateY: [ 0, -55 ] } ] ], reset: { transformPerspective: 0 } }, /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.flipXOut": { defaultDuration: 700, calls: [ [ { opacity: [ 0, 1 ], transformPerspective: [ 800, 800 ], rotateY: 55 } ] ], reset: { transformPerspective: 0, rotateY: 0 } }, /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.flipYIn": { defaultDuration: 800, calls: [ [ { opacity: [ 1, 0 ], transformPerspective: [ 800, 800 ], rotateX: [ 0, -45 ] } ] ], reset: { transformPerspective: 0 } }, /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.flipYOut": { defaultDuration: 800, calls: [ [ { opacity: [ 0, 1 ], transformPerspective: [ 800, 800 ], rotateX: 25 } ] ], reset: { transformPerspective: 0, rotateX: 0 } }, /* Animate.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.flipBounceXIn": { defaultDuration: 900, calls: [ [ { opacity: [ 0.725, 0 ], transformPerspective: [ 400, 400 ], rotateY: [ -10, 90 ] }, 0.50 ], [ { opacity: 0.80, rotateY: 10 }, 0.25 ], [ { opacity: 1, rotateY: 0 }, 0.25 ] ], reset: { transformPerspective: 0 } }, /* Animate.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.flipBounceXOut": { defaultDuration: 800, calls: [ [ { opacity: [ 0.9, 1 ], transformPerspective: [ 400, 400 ], rotateY: -10 }, 0.50 ], [ { opacity: 0, rotateY: 90 }, 0.50 ] ], reset: { transformPerspective: 0, rotateY: 0 } }, /* Animate.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.flipBounceYIn": { defaultDuration: 850, calls: [ [ { opacity: [ 0.725, 0 ], transformPerspective: [ 400, 400 ], rotateX: [ -10, 90 ] }, 0.50 ], [ { opacity: 0.80, rotateX: 10 }, 0.25 ], [ { opacity: 1, rotateX: 0 }, 0.25 ] ], reset: { transformPerspective: 0 } }, /* Animate.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.flipBounceYOut": { defaultDuration: 800, calls: [ [ { opacity: [ 0.9, 1 ], transformPerspective: [ 400, 400 ], rotateX: -15 }, 0.50 ], [ { opacity: 0, rotateX: 90 }, 0.50 ] ], reset: { transformPerspective: 0, rotateX: 0 } }, /* Magic.css */ "transition.swoopIn": { defaultDuration: 850, calls: [ [ { opacity: [ 1, 0 ], transformOriginX: [ "100%", "50%" ], transformOriginY: [ "100%", "100%" ], scaleX: [ 1, 0 ], scaleY: [ 1, 0 ], translateX: [ 0, -700 ], translateZ: 0 } ] ], reset: { transformOriginX: "50%", transformOriginY: "50%" } }, /* Magic.css */ "transition.swoopOut": { defaultDuration: 850, calls: [ [ { opacity: [ 0, 1 ], transformOriginX: [ "50%", "100%" ], transformOriginY: [ "100%", "100%" ], scaleX: 0, scaleY: 0, translateX: -700, translateZ: 0 } ] ], reset: { transformOriginX: "50%", transformOriginY: "50%", scaleX: 1, scaleY: 1, translateX: 0 } }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3. (Fades and scales only.) */ "transition.whirlIn": { defaultDuration: 900, calls: [ [ { opacity: [ 1, 0 ], transformOriginX: [ "50%", "50%" ], transformOriginY: [ "50%", "50%" ], scaleX: [ 1, 0 ], scaleY: [ 1, 0 ], rotateY: [ 0, 160 ] } ] ] }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3. (Fades and scales only.) */ "transition.whirlOut": { defaultDuration: 900, calls: [ [ { opacity: [ 0, 1 ], transformOriginX: [ "50%", "50%" ], transformOriginY: [ "50%", "50%" ], scaleX: 0, scaleY: 0, rotateY: 160 } ] ], reset: { scaleX: 1, scaleY: 1, rotateY: 0 } }, "transition.shrinkIn": { defaultDuration: 700, calls: [ [ { opacity: [ 1, 0 ], transformOriginX: [ "50%", "50%" ], transformOriginY: [ "50%", "50%" ], scaleX: [ 1, 1.5 ], scaleY: [ 1, 1.5 ], translateZ: 0 } ] ] }, "transition.shrinkOut": { defaultDuration: 650, calls: [ [ { opacity: [ 0, 1 ], transformOriginX: [ "50%", "50%" ], transformOriginY: [ "50%", "50%" ], scaleX: 1.3, scaleY: 1.3, translateZ: 0 } ] ], reset: { scaleX: 1, scaleY: 1 } }, "transition.expandIn": { defaultDuration: 700, calls: [ [ { opacity: [ 1, 0 ], transformOriginX: [ "50%", "50%" ], transformOriginY: [ "50%", "50%" ], scaleX: [ 1, 0.625 ], scaleY: [ 1, 0.625 ], translateZ: 0 } ] ] }, "transition.expandOut": { defaultDuration: 700, calls: [ [ { opacity: [ 0, 1 ], transformOriginX: [ "50%", "50%" ], transformOriginY: [ "50%", "50%" ], scaleX: 0.5, scaleY: 0.5, translateZ: 0 } ] ], reset: { scaleX: 1, scaleY: 1 } }, /* Animate.css */ "transition.bounceIn": { defaultDuration: 800, calls: [ [ { opacity: [ 1, 0 ], scaleX: [ 1.05, 0.3 ], scaleY: [ 1.05, 0.3 ] }, 0.40 ], [ { scaleX: 0.9, scaleY: 0.9, translateZ: 0 }, 0.20 ], [ { scaleX: 1, scaleY: 1 }, 0.50 ] ] }, /* Animate.css */ "transition.bounceOut": { defaultDuration: 800, calls: [ [ { scaleX: 0.95, scaleY: 0.95 }, 0.40 ], [ { scaleX: 1.1, scaleY: 1.1, translateZ: 0 }, 0.40 ], [ { opacity: [ 0, 1 ], scaleX: 0.3, scaleY: 0.3 }, 0.20 ] ], reset: { scaleX: 1, scaleY: 1 } }, /* Animate.css */ "transition.bounceUpIn": { defaultDuration: 800, calls: [ [ { opacity: [ 1, 0 ], translateY: [ -30, 1000 ] }, 0.60, { easing: "easeOutCirc" } ], [ { translateY: 10 }, 0.20 ], [ { translateY: 0 }, 0.20 ] ] }, /* Animate.css */ "transition.bounceUpOut": { defaultDuration: 1000, calls: [ [ { translateY: 20 }, 0.20 ], [ { opacity: [ 0, "easeInCirc", 1 ], translateY: -1000 }, 0.80 ] ], reset: { translateY: 0 } }, /* Animate.css */ "transition.bounceDownIn": { defaultDuration: 800, calls: [ [ { opacity: [ 1, 0 ], translateY: [ 30, -1000 ] }, 0.60, { easing: "easeOutCirc" } ], [ { translateY: -10 }, 0.20 ], [ { translateY: 0 }, 0.20 ] ] }, /* Animate.css */ "transition.bounceDownOut": { defaultDuration: 1000, calls: [ [ { translateY: -20 }, 0.20 ], [ { opacity: [ 0, "easeInCirc", 1 ], translateY: 1000 }, 0.80 ] ], reset: { translateY: 0 } }, /* Animate.css */ "transition.bounceLeftIn": { defaultDuration: 750, calls: [ [ { opacity: [ 1, 0 ], translateX: [ 30, -1250 ] }, 0.60, { easing: "easeOutCirc" } ], [ { translateX: -10 }, 0.20 ], [ { translateX: 0 }, 0.20 ] ] }, /* Animate.css */ "transition.bounceLeftOut": { defaultDuration: 750, calls: [ [ { translateX: 30 }, 0.20 ], [ { opacity: [ 0, "easeInCirc", 1 ], translateX: -1250 }, 0.80 ] ], reset: { translateX: 0 } }, /* Animate.css */ "transition.bounceRightIn": { defaultDuration: 750, calls: [ [ { opacity: [ 1, 0 ], translateX: [ -30, 1250 ] }, 0.60, { easing: "easeOutCirc" } ], [ { translateX: 10 }, 0.20 ], [ { translateX: 0 }, 0.20 ] ] }, /* Animate.css */ "transition.bounceRightOut": { defaultDuration: 750, calls: [ [ { translateX: -30 }, 0.20 ], [ { opacity: [ 0, "easeInCirc", 1 ], translateX: 1250 }, 0.80 ] ], reset: { translateX: 0 } }, "transition.slideUpIn": { defaultDuration: 900, calls: [ [ { opacity: [ 1, 0 ], translateY: [ 0, 20 ], translateZ: 0 } ] ] }, "transition.slideUpOut": { defaultDuration: 900, calls: [ [ { opacity: [ 0, 1 ], translateY: -20, translateZ: 0 } ] ], reset: { translateY: 0 } }, "transition.slideDownIn": { defaultDuration: 900, calls: [ [ { opacity: [ 1, 0 ], translateY: [ 0, -20 ], translateZ: 0 } ] ] }, "transition.slideDownOut": { defaultDuration: 900, calls: [ [ { opacity: [ 0, 1 ], translateY: 20, translateZ: 0 } ] ], reset: { translateY: 0 } }, "transition.slideLeftIn": { defaultDuration: 1000, calls: [ [ { opacity: [ 1, 0 ], translateX: [ 0, -20 ], translateZ: 0 } ] ] }, "transition.slideLeftOut": { defaultDuration: 1050, calls: [ [ { opacity: [ 0, 1 ], translateX: -20, translateZ: 0 } ] ], reset: { translateX: 0 } }, "transition.slideRightIn": { defaultDuration: 1000, calls: [ [ { opacity: [ 1, 0 ], translateX: [ 0, 20 ], translateZ: 0 } ] ] }, "transition.slideRightOut": { defaultDuration: 1050, calls: [ [ { opacity: [ 0, 1 ], translateX: 20, translateZ: 0 } ] ], reset: { translateX: 0 } }, "transition.slideUpBigIn": { defaultDuration: 850, calls: [ [ { opacity: [ 1, 0 ], translateY: [ 0, 75 ], translateZ: 0 } ] ] }, "transition.slideUpBigOut": { defaultDuration: 800, calls: [ [ { opacity: [ 0, 1 ], translateY: -75, translateZ: 0 } ] ], reset: { translateY: 0 } }, "transition.slideDownBigIn": { defaultDuration: 850, calls: [ [ { opacity: [ 1, 0 ], translateY: [ 0, -75 ], translateZ: 0 } ] ] }, "transition.slideDownBigOut": { defaultDuration: 800, calls: [ [ { opacity: [ 0, 1 ], translateY: 75, translateZ: 0 } ] ], reset: { translateY: 0 } }, "transition.slideLeftBigIn": { defaultDuration: 800, calls: [ [ { opacity: [ 1, 0 ], translateX: [ 0, -75 ], translateZ: 0 } ] ] }, "transition.slideLeftBigOut": { defaultDuration: 750, calls: [ [ { opacity: [ 0, 1 ], translateX: -75, translateZ: 0 } ] ], reset: { translateX: 0 } }, "transition.slideRightBigIn": { defaultDuration: 800, calls: [ [ { opacity: [ 1, 0 ], translateX: [ 0, 75 ], translateZ: 0 } ] ] }, "transition.slideRightBigOut": { defaultDuration: 750, calls: [ [ { opacity: [ 0, 1 ], translateX: 75, translateZ: 0 } ] ], reset: { translateX: 0 } }, /* Magic.css */ "transition.perspectiveUpIn": { defaultDuration: 800, calls: [ [ { opacity: [ 1, 0 ], transformPerspective: [ 800, 800 ], transformOriginX: [ 0, 0 ], transformOriginY: [ "100%", "100%" ], rotateX: [ 0, -180 ] } ] ], reset: { transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%" } }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.perspectiveUpOut": { defaultDuration: 850, calls: [ [ { opacity: [ 0, 1 ], transformPerspective: [ 800, 800 ], transformOriginX: [ 0, 0 ], transformOriginY: [ "100%", "100%" ], rotateX: -180 } ] ], reset: { transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%", rotateX: 0 } }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.perspectiveDownIn": { defaultDuration: 800, calls: [ [ { opacity: [ 1, 0 ], transformPerspective: [ 800, 800 ], transformOriginX: [ 0, 0 ], transformOriginY: [ 0, 0 ], rotateX: [ 0, 180 ] } ] ], reset: { transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%" } }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.perspectiveDownOut": { defaultDuration: 850, calls: [ [ { opacity: [ 0, 1 ], transformPerspective: [ 800, 800 ], transformOriginX: [ 0, 0 ], transformOriginY: [ 0, 0 ], rotateX: 180 } ] ], reset: { transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%", rotateX: 0 } }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.perspectiveLeftIn": { defaultDuration: 950, calls: [ [ { opacity: [ 1, 0 ], transformPerspective: [ 2000, 2000 ], transformOriginX: [ 0, 0 ], transformOriginY: [ 0, 0 ], rotateY: [ 0, -180 ] } ] ], reset: { transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%" } }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.perspectiveLeftOut": { defaultDuration: 950, calls: [ [ { opacity: [ 0, 1 ], transformPerspective: [ 2000, 2000 ], transformOriginX: [ 0, 0 ], transformOriginY: [ 0, 0 ], rotateY: -180 } ] ], reset: { transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%", rotateY: 0 } }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.perspectiveRightIn": { defaultDuration: 950, calls: [ [ { opacity: [ 1, 0 ], transformPerspective: [ 2000, 2000 ], transformOriginX: [ "100%", "100%" ], transformOriginY: [ 0, 0 ], rotateY: [ 0, 180 ] } ] ], reset: { transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%" } }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.perspectiveRightOut": { defaultDuration: 950, calls: [ [ { opacity: [ 0, 1 ], transformPerspective: [ 2000, 2000 ], transformOriginX: [ "100%", "100%" ], transformOriginY: [ 0, 0 ], rotateY: 180 } ] ], reset: { transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%", rotateY: 0 } } }; /* Register the packaged effects. */ for (var effectName in Container.Velocity.RegisterUI.packagedEffects) { Container.Velocity.RegisterUI(effectName, Container.Velocity.RegisterUI.packagedEffects[effectName]); } })();
var fns = []; for (let i = 0; i < 10; i++) { fns.push(function () { return i; }); i += 1; } assert.equal(fns[0](), 1); assert.equal(fns[1](), 3); assert.equal(fns[2](), 5); assert.equal(fns[3](), 7); assert.equal(fns[4](), 9);
// flow-typed signature: 323fcc1a3353d5f7a36c5f1edcd963ef // flow-typed version: 41f45a7d8c/react-addons-test-utils_v15.x.x/flow_>=v0.23.x declare type ReactAddonTest$FunctionOrComponentClass = React$Component<any, any, any> | Function; declare module 'react-addons-test-utils' { declare var Simulate: { [eventName: string]: (element: Element, eventData?: Object) => void; }; declare function renderIntoDocument(instance: React$Element<any>): React$Component<any, any, any>; declare function mockComponent(componentClass: ReactAddonTest$FunctionOrComponentClass, mockTagName?: string): Object; declare function isElement(element: React$Element<any>): boolean; declare function isElementOfType(element: React$Element<any>, componentClass: ReactAddonTest$FunctionOrComponentClass): boolean; declare function isDOMComponent(instance: React$Component<any, any, any>): boolean; declare function isCompositeComponent(instance: React$Component<any, any, any>): boolean; declare function isCompositeComponentWithType(instance: React$Component<any, any, any>, componentClass: ReactAddonTest$FunctionOrComponentClass): boolean; declare function findAllInRenderedTree(tree: React$Component<any, any, any>, test: (child: React$Component<any, any, any>) => boolean): Array<React$Component<any, any, any>>; declare function scryRenderedDOMComponentsWithClass(tree: React$Component<any, any, any>, className: string): Array<Element>; declare function findRenderedDOMComponentWithClass(tree: React$Component<any, any, any>, className: string): ?Element; declare function scryRenderedDOMComponentsWithTag(tree: React$Component<any, any, any>, tagName: string): Array<Element>; declare function findRenderedDOMComponentWithTag(tree: React$Component<any, any, any>, tagName: string): ?Element; declare function scryRenderedComponentsWithType(tree: React$Component<any, any, any>, componentClass: ReactAddonTest$FunctionOrComponentClass): Array<React$Component<any, any, any>>; declare function findRenderedComponentWithType(tree: React$Component<any, any, any>, componentClass: ReactAddonTest$FunctionOrComponentClass): ?React$Component<any, any, any>; declare class ReactShallowRender { render(element: React$Element<any>): void; getRenderOutput(): React$Element<any>; } declare function createRenderer(): ReactShallowRender; }
/*! * js-data-http * @version 3.0.0-beta.1 - Homepage <http://www.js-data.io/docs/dshttpadapter> * @author Jason Dobry <jason.dobry@gmail.com> * @copyright (c) 2014-2015 Jason Dobry * @license MIT <https://github.com/js-data/js-data-http/blob/master/LICENSE> * * @overview Http adapter for js-data. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("js-data")); else if(typeof define === 'function' && define.amd) define(["js-data"], factory); else if(typeof exports === 'object') exports["DSHttpAdapter"] = factory(require("js-data")); else root["DSHttpAdapter"] = factory(root["JSData"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__) { 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__) { var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var JSData = __webpack_require__(1); var DSUtils = JSData.DSUtils; var deepMixIn = DSUtils.deepMixIn; var removeCircular = DSUtils.removeCircular; var copy = DSUtils.copy; var makePath = DSUtils.makePath; var isString = DSUtils.isString; var isNumber = DSUtils.isNumber; function encode(val) { return encodeURIComponent(val).replace(/%40/gi, '@').replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+'); } function buildUrl(url, params) { if (!params) { return url; } var parts = []; DSUtils.forOwn(params, function (val, key) { if (val === null || typeof val === 'undefined') { return; } if (!DSUtils.isArray(val)) { val = [val]; } DSUtils.forEach(val, function (v) { if (window.toString.call(v) === '[object Date]') { v = v.toISOString(); } else if (DSUtils.isObject(v)) { v = DSUtils.toJson(v); } parts.push(encode(key) + '=' + encode(v)); }); }); if (parts.length > 0) { url += (url.indexOf('?') === -1 ? '?' : '&') + parts.join('&'); } return url; } var Defaults = (function () { function Defaults() { _classCallCheck(this, Defaults); } _createClass(Defaults, [{ key: 'queryTransform', value: function queryTransform(resourceConfig, params) { return params; } }, { key: 'deserialize', value: function deserialize(resourceConfig, data) { return data ? 'data' in data ? data.data : data : data; } }, { key: 'serialize', value: function serialize(resourceConfig, data) { return data; } }, { key: 'log', value: function log() {} }, { key: 'error', value: function error() {} }]); return Defaults; })(); var defaultsPrototype = Defaults.prototype; defaultsPrototype.httpLibName = 'axios'; defaultsPrototype.basePath = ''; defaultsPrototype.forceTrailingSlash = ''; defaultsPrototype.httpConfig = {}; defaultsPrototype.useFetch = false; var DSHttpAdapter = (function () { function DSHttpAdapter(options) { _classCallCheck(this, DSHttpAdapter); options = options || {}; this.defaults = new Defaults(); this.http = options.http; delete options.http; if (console) { this.defaults.log = function (a, b) { return console[typeof console.info === 'function' ? 'info' : 'log'](a, b); }; } if (console) { this.defaults.error = function (a, b) { return console[typeof console.error === 'function' ? 'error' : 'log'](a, b); }; } deepMixIn(this.defaults, options); if (this.defaults.useFetch && window.fetch) { this.defaults.deserialize = function (resourceConfig, response) { return response.json(); }; this.http = function (config) { var requestConfig = { method: config.method, // turn the plain headers object into the Fetch Headers object headers: new window.Headers(config.headers) }; if (config.data) { requestConfig.body = DSUtils.toJson(config.data); } return window.fetch(new window.Request(buildUrl(config.url, config.params), requestConfig)).then(function (response) { response.config = { method: config.method, url: config.url }; return response; }); }; } if (!this.http) { try { this.http = window[this.defaults.httpLibName]; } catch (e) {} } } _createClass(DSHttpAdapter, [{ key: 'getEndpoint', value: function getEndpoint(resourceConfig, id, options) { var _this2 = this; options = options || {}; options.params = options.params || {}; var item = undefined; var parentKey = resourceConfig.parentKey; var endpoint = options.hasOwnProperty('endpoint') ? options.endpoint : resourceConfig.endpoint; var parentField = resourceConfig.parentField; var parentDef = resourceConfig.getResource(resourceConfig.parent); var parentId = options.params[parentKey]; if (parentId === false || !parentKey || !parentDef) { if (parentId === false) { delete options.params[parentKey]; } return endpoint; } else { delete options.params[parentKey]; if (DSUtils._sn(id)) { item = resourceConfig.get(id); } else if (DSUtils._o(id)) { item = id; } if (item) { parentId = parentId || item[parentKey] || (item[parentField] ? item[parentField][parentDef.idAttribute] : null); } if (parentId) { var _ret = (function () { delete options.endpoint; var _options = {}; DSUtils.forOwn(options, function (value, key) { _options[key] = value; }); return { v: DSUtils.makePath(_this2.getEndpoint(parentDef, parentId, DSUtils._(parentDef, _options)), parentId, endpoint) }; })(); if (typeof _ret === 'object') return _ret.v; } else { return endpoint; } } } }, { key: 'getPath', value: function getPath(method, resourceConfig, id, options) { var _this = this; options = options || {}; var args = [options.basePath || _this.defaults.basePath || resourceConfig.basePath, this.getEndpoint(resourceConfig, isString(id) || isNumber(id) || method === 'create' ? id : null, options)]; if (method === 'find' || method === 'update' || method === 'destroy') { args.push(id); } return makePath.apply(DSUtils, args); } }, { key: 'HTTP', value: function HTTP(config) { var _this = this; var start = new Date(); config = copy(config); config = deepMixIn(config, _this.defaults.httpConfig); if (_this.defaults.forceTrailingSlash && config.url[config.url.length - 1] !== '/') { config.url += '/'; } if (typeof config.data === 'object') { config.data = removeCircular(config.data); } config.method = config.method.toUpperCase(); var suffix = config.suffix || _this.defaults.suffix; if (suffix && config.url.substr(config.url.length - suffix.length) !== suffix) { config.url += suffix; } function logResponse(data) { var str = start.toUTCString() + ' - ' + config.method.toUpperCase() + ' ' + config.url + ' - ' + data.status + ' ' + (new Date().getTime() - start.getTime()) + 'ms'; if (data.status >= 200 && data.status < 300) { if (_this.defaults.log) { _this.defaults.log(str, data); } return data; } else { if (_this.defaults.error) { _this.defaults.error('\'FAILED: ' + str, data); } return DSUtils.Promise.reject(data); } } if (!this.http) { throw new Error('You have not configured this adapter with an http library!'); } return this.http(config).then(logResponse, logResponse); } }, { key: 'GET', value: function GET(url, config) { config = config || {}; if (!('method' in config)) { config.method = 'get'; } return this.HTTP(deepMixIn(config, { url: url })); } }, { key: 'POST', value: function POST(url, attrs, config) { config = config || {}; if (!('method' in config)) { config.method = 'post'; } return this.HTTP(deepMixIn(config, { url: url, data: attrs })); } }, { key: 'PUT', value: function PUT(url, attrs, config) { config = config || {}; if (!('method' in config)) { config.method = 'put'; } return this.HTTP(deepMixIn(config, { url: url, data: attrs || {} })); } }, { key: 'DEL', value: function DEL(url, config) { config = config || {}; if (!('method' in config)) { config.method = 'delete'; } return this.HTTP(deepMixIn(config, { url: url })); } }, { key: 'find', value: function find(resourceConfig, id, options) { var _this = this; options = options ? copy(options) : {}; options.suffix = options.suffix || resourceConfig.suffix; options.params = options.params || {}; options.params = _this.defaults.queryTransform(resourceConfig, options.params); return _this.GET(_this.getPath('find', resourceConfig, id, options), options).then(function (data) { var item = (options.deserialize ? options.deserialize : _this.defaults.deserialize)(resourceConfig, data); return !item ? DSUtils.Promise.reject(new Error('Not Found!')) : item; }); } }, { key: 'findAll', value: function findAll(resourceConfig, params, options) { var _this = this; options = options ? copy(options) : {}; options.suffix = options.suffix || resourceConfig.suffix; options.params = options.params || {}; if (params) { params = _this.defaults.queryTransform(resourceConfig, params); deepMixIn(options.params, params); } return _this.GET(_this.getPath('findAll', resourceConfig, params, options), options).then(function (data) { return (options.deserialize ? options.deserialize : _this.defaults.deserialize)(resourceConfig, data); }); } }, { key: 'create', value: function create(resourceConfig, attrs, options) { var _this = this; options = options ? copy(options) : {}; options.suffix = options.suffix || resourceConfig.suffix; options.params = options.params || {}; options.params = _this.defaults.queryTransform(resourceConfig, options.params); return _this.POST(_this.getPath('create', resourceConfig, attrs, options), options.serialize ? options.serialize(resourceConfig, attrs) : _this.defaults.serialize(resourceConfig, attrs), options).then(function (data) { return (options.deserialize ? options.deserialize : _this.defaults.deserialize)(resourceConfig, data); }); } }, { key: 'update', value: function update(resourceConfig, id, attrs, options) { var _this = this; options = options ? copy(options) : {}; options.suffix = options.suffix || resourceConfig.suffix; options.params = options.params || {}; options.params = _this.defaults.queryTransform(resourceConfig, options.params); return _this.PUT(_this.getPath('update', resourceConfig, id, options), options.serialize ? options.serialize(resourceConfig, attrs) : _this.defaults.serialize(resourceConfig, attrs), options).then(function (data) { return (options.deserialize ? options.deserialize : _this.defaults.deserialize)(resourceConfig, data); }); } }, { key: 'updateAll', value: function updateAll(resourceConfig, attrs, params, options) { var _this = this; options = options ? copy(options) : {}; options.suffix = options.suffix || resourceConfig.suffix; options.params = options.params || {}; if (params) { params = _this.defaults.queryTransform(resourceConfig, params); deepMixIn(options.params, params); } return this.PUT(_this.getPath('updateAll', resourceConfig, attrs, options), options.serialize ? options.serialize(resourceConfig, attrs) : _this.defaults.serialize(resourceConfig, attrs), options).then(function (data) { return (options.deserialize ? options.deserialize : _this.defaults.deserialize)(resourceConfig, data); }); } }, { key: 'destroy', value: function destroy(resourceConfig, id, options) { var _this = this; options = options ? copy(options) : {}; options.suffix = options.suffix || resourceConfig.suffix; options.params = options.params || {}; options.params = _this.defaults.queryTransform(resourceConfig, options.params); return _this.DEL(_this.getPath('destroy', resourceConfig, id, options), options).then(function (data) { return (options.deserialize ? options.deserialize : _this.defaults.deserialize)(resourceConfig, data); }); } }, { key: 'destroyAll', value: function destroyAll(resourceConfig, params, options) { var _this = this; options = options ? copy(options) : {}; options.suffix = options.suffix || resourceConfig.suffix; options.params = options.params || {}; if (params) { params = _this.defaults.queryTransform(resourceConfig, params); deepMixIn(options.params, params); } return this.DEL(_this.getPath('destroyAll', resourceConfig, params, options), options).then(function (data) { return (options.deserialize ? options.deserialize : _this.defaults.deserialize)(resourceConfig, data); }); } }]); return DSHttpAdapter; })(); module.exports = DSHttpAdapter; /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ } /******/ ]) }); ;
/*! * Qoopido.js library v3.4.9, 2014-7-26 * https://github.com/dlueth/qoopido.js * (c) 2014 Dirk Lueth * Dual licensed under MIT and GPL */ !function(t){window.qoopido.register("polyfill/string/ucfirst",t)}(function(){"use strict";return String.prototype.ucfirst||(String.prototype.ucfirst=function(){var t=this;return t.charAt(0).toUpperCase()+t.slice(1)}),String.prototype.ucfirst});
/* YUI 3.16.0 (build 76f0e08) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('datasource-polling', function (Y, NAME) { /** * Extends DataSource with polling functionality. * * @module datasource * @submodule datasource-polling */ /** * Adds polling to the DataSource Utility. * @class Pollable * @extends DataSource.Local */ function Pollable() { this._intervals = {}; } Pollable.prototype = { /** * @property _intervals * @description Hash of polling interval IDs that have been enabled, * stored here to be able to clear all intervals. * @private */ _intervals: null, /** * Sets up a polling mechanism to send requests at set intervals and * forward responses to given callback. * * @method setInterval * @param msec {Number} Length of interval in milliseconds. * @param [request] {Object} An object literal with the following properties: * <dl> * <dt><code>request</code></dt> * <dd>The request to send to the live data source, if any.</dd> * <dt><code>callback</code></dt> * <dd>An object literal with the following properties: * <dl> * <dt><code>success</code></dt> * <dd>The function to call when the data is ready.</dd> * <dt><code>failure</code></dt> * <dd>The function to call upon a response failure condition.</dd> * <dt><code>argument</code></dt> * <dd>Arbitrary data payload that will be passed back to the success and failure handlers.</dd> * </dl> * </dd> * <dt><code>cfg</code></dt> * <dd>Configuration object, if any.</dd> * </dl> * @return {Number} Interval ID. */ setInterval: function(msec, request) { var x = Y.later(msec, this, this.sendRequest, [ request ], true); this._intervals[x.id] = x; // First call happens immediately, but async Y.later(0, this, this.sendRequest, [request]); return x.id; }, /** * Disables polling mechanism associated with the given interval ID. * * @method clearInterval * @param id {Number} Interval ID. */ clearInterval: function(id, key) { // In case of being called by clearAllIntervals() id = key || id; if(this._intervals[id]) { // Clear the interval this._intervals[id].cancel(); // Clear from tracker delete this._intervals[id]; } }, /** * Clears all intervals. * * @method clearAllIntervals */ clearAllIntervals: function() { Y.each(this._intervals, this.clearInterval, this); } }; Y.augment(Y.DataSource.Local, Pollable); }, '3.16.0', {"requires": ["datasource-local"]});
/** * Select2 French translation */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Aucun résultat trouvé"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Merci de saisir " + n + " caractère" + (n == 1? "" : "s") + " de plus"; }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Merci de supprimer " + n + " caractère" + (n == 1? "" : "s"); }, formatSelectionTooBig: function (limit) { return "Vous pouvez seulement sélectionner " + limit + " élément" + (limit == 1 ? "" : "s"); }, formatLoadMore: function (pageNumber) { return "Chargement de résultats supplémentaires…"; }, formatSearching: function () { return "Recherche en cours…"; } }); })(jQuery);
import { showConfirmationDialog, escape } from "./dialog"; const outputRow = (output) => [ "<li>", "<samp>", escape(output.address), ": </samp>&nbsp;", '<samp class="amount">', { atoms: output.amount }, "</samp>", "</li>" ]; export default (totalOutAmount, outputs) => showConfirmationDialog({ title: { id: "confDialog.signTx.title", m: "Sign Transaction" }, content: [ "<p>", { id: "confDialog.signTransaction.message", m: "Really sign the given transaction?" }, "</p>", "<p>", { id: "confDialog.signTransaction.totalOutLabel", m: "Total Spent Amount:" }, '<samp class="amount"> ', { atoms: totalOutAmount }, "</samp>", "</p>", "<p>", outputs.length > 0 ? { id: "confDialog.signTransaction.outputs", m: "Non-wallet outputs:" } : "", "</p>", "<ul>", outputs.map(outputRow), "</ul>" ] });
"use strict"; import ActionTypes from "../constants/ActionTypes"; import AppDispatcher from "../dispatchers/AppDispatcher"; // TODO modify this so it uses compose export function modifyPendingAction(type, pendingAction, ...args) { AppDispatcher.dispatch({ type: ActionTypes.PENDING_ACTION, data: { type: type, action: pendingAction.bind(null, args[0], args[1]) } }); } export function clearPendingAction() { AppDispatcher.dispatch({ type: ActionTypes.PENDING_ACTION, data: null }); } export function executePendingAction(pendingAction) { pendingAction(); clearPendingAction(); }
import React from 'react'; import { Map } from 'immutable'; export const basePropTypes = { settings: React.PropTypes.instanceOf(Map), user: React.PropTypes.instanceOf(Map), entityConfig: React.PropTypes.instanceOf(Map).isRequired, ui: React.PropTypes.instanceOf(Map).isRequired, data: React.PropTypes.instanceOf(Map).isRequired };
'use strict'; var gulp = require('gulp'), path = require('path'), del = require('del'), sourcemaps = require('gulp-sourcemaps'), concat = require('gulp-concat'), uglify = require('gulp-uglify'), rev = require('gulp-rev'), sourcemaps = require('gulp-sourcemaps'), annotate = require('gulp-ng-annotate'), templates = require('gulp-angular-templatecache'), jade = require('gulp-jade'), less = require('gulp-less'), concat = require('gulp-concat'); gulp.task('app:clean', false, function() { del.sync(['build/static/app*', 'build/manifest/app*', 'build/templates.js']); }); gulp.task('app:templates', false, ['app:clean'], function() { return gulp.src('src/**/*.jade') .pipe(jade()) .pipe(templates({ module: 'app', base: function(file) { var relPath = path.relative(file.base, file.path); return path.join(path.dirname(relPath), path.basename(relPath, '.html')) + '.jade'; } })) .pipe(gulp.dest('build')); }); gulp.task('app:js', false, ['app:clean', 'app:templates'], function() { return gulp.src(['src/**/*.js', 'build/templates.js']) .pipe(sourcemaps.init()) .pipe(concat({ path: 'app.js', cwd: '.' })) .pipe(annotate()) .pipe(uglify()) .pipe(rev()) .pipe(sourcemaps.write('.', { sourceRoot: 'src' })) .pipe(gulp.dest('build/static')) .pipe(rev.manifest({path: 'manifest/app.js.json'})) .pipe(gulp.dest('build')); }); gulp.task('app:less', false, ['app:clean'], function() { return gulp.src('src/**/*.less') .pipe(sourcemaps.init()) .pipe(concat({ path: 'app.less', cwd: '.' })) .pipe(less()) .pipe(rev()) .pipe(sourcemaps.write('.', { sourceRoot: 'src' })) .pipe(gulp.dest('build/static')) .pipe(rev.manifest({path: 'manifest/app.less.json'})) .pipe(gulp.dest('build')); }); gulp.task('app', ['app:js', 'app:less', 'app:templates']); gulp.task('app:regenerate', false, ['app'], require('./lib/generateIndexPage'));
var getDependencyInstances = require('./get-dependency-instances') , getFnArgs = require('./get-function-arguments') , getFnName = require('./get-function-name') module.exports = function (plugin) { var bound = plugin.bind(this) // Bind pluginable bound.dependencies = getFnArgs(plugin) bound.name = getFnName(bound) if (bound.dependencies.length === 0) return bound var error bound.dependencies.forEach(function (dependency) { if (this.plugins[dependency] === undefined) { error = bound.name + ' has an unknown dependency ' + dependency } }.bind(this)) if (error) throw new Error(error) var args = getDependencyInstances(this.plugins, bound) return bound.bind.apply(bound, [ this ].concat(args)) }
'use strict' const Site = use('site') const qr = require('@perl/qr') class WpFacebook extends Site { static matches (siteUrlStr) { return qr`wp[.]com/graph[.]facebook[.]com`.test(siteUrlStr) } normalizeLink (link) { const url = require('url') const linkBits = url.parse(link) linkBits.host = 'i0.wp.com' linkBits.pathname = linkBits.pathname.replace(/v2.2[/]/, '') + '/.jpg' return url.format(linkBits) } async getChapter (fetch, chapter) { const ChapterContent = use('chapter-content') return new ChapterContent(chapter, { name: chapter.link, base: chapter.link, content: '<img src="' + chapter.fetchWith() + '">' }) } } module.exports = WpFacebook
import './about.styl'; import aboutRoutes from './about.routes'; import aboutCtrl from './about.controller'; export default ngModule => { aboutRoutes(ngModule); aboutCtrl(ngModule); };