code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
_jpi.prototype.removeGroup = function(group, deleteMembers, manipulateDOM, doNotFireEvent) { return this.getGroupManager().removeGroup(group, deleteMembers, manipulateDOM, doNotFireEvent); };
Remove a group, and optionally remove its members from the jsPlumb instance. @method removeGroup @param {String|Group} group Group to delete, or ID of Group to delete. @param {Boolean} [deleteMembers=false] If true, group members will be removed along with the group. Otherwise they will just be 'orphaned' (returned to the main container). @returns {Map[String, Position}} When deleteMembers is false, this method returns a map of {id->position}
_jpi.prototype.removeGroup ( group , deleteMembers , manipulateDOM , doNotFireEvent )
javascript
lettersporter/easy-flow
src/components/ef/jsplumb.js
https://github.com/lettersporter/easy-flow/blob/master/src/components/ef/jsplumb.js
Apache-2.0
_jpi.prototype.removeAllGroups = function(deleteMembers, manipulateDOM, doNotFireEvent) { this.getGroupManager().removeAllGroups(deleteMembers, manipulateDOM, doNotFireEvent); };
Remove all groups, and optionally remove their members from the jsPlumb instance. @method removeAllGroup @param {Boolean} [deleteMembers=false] If true, group members will be removed along with the groups. Otherwise they will just be 'orphaned' (returned to the main container).
_jpi.prototype.removeAllGroups ( deleteMembers , manipulateDOM , doNotFireEvent )
javascript
lettersporter/easy-flow
src/components/ef/jsplumb.js
https://github.com/lettersporter/easy-flow/blob/master/src/components/ef/jsplumb.js
Apache-2.0
_jpi.prototype.getGroup = function(groupId) { return this.getGroupManager().getGroup(groupId); };
Get a Group @method getGroup @param {String} groupId ID of the group to get @return {Group} Group with the given ID, null if not found.
_jpi.prototype.getGroup ( groupId )
javascript
lettersporter/easy-flow
src/components/ef/jsplumb.js
https://github.com/lettersporter/easy-flow/blob/master/src/components/ef/jsplumb.js
Apache-2.0
_jpi.prototype.getGroups = function() { return this.getGroupManager().getGroups(); };
Gets all the Groups managed by the jsPlumb instance. @returns {Group[]} List of Groups. Empty if none.
_jpi.prototype.getGroups ( )
javascript
lettersporter/easy-flow
src/components/ef/jsplumb.js
https://github.com/lettersporter/easy-flow/blob/master/src/components/ef/jsplumb.js
Apache-2.0
_jpi.prototype.expandGroup = function(group) { this.getGroupManager().expandGroup(group); };
Expands a group element. jsPlumb doesn't do "everything" for you here, because what it means to expand a Group will vary from application to application. jsPlumb does these things: - Hides any connections that are internal to the group (connections between members, and connections from member of the group to the group itself) - Proxies all connections for which the source or target is a member of the group. - Hides the proxied connections. - Adds the jtk-group-expanded class to the group's element - Removes the jtk-group-collapsed class from the group's element. @method expandGroup @param {String|Group} group Group to expand, or ID of Group to expand.
_jpi.prototype.expandGroup ( group )
javascript
lettersporter/easy-flow
src/components/ef/jsplumb.js
https://github.com/lettersporter/easy-flow/blob/master/src/components/ef/jsplumb.js
Apache-2.0
_jpi.prototype.collapseGroup = function(groupId) { this.getGroupManager().collapseGroup(groupId); };
Collapses a group element. jsPlumb doesn't do "everything" for you here, because what it means to collapse a Group will vary from application to application. jsPlumb does these things: - Shows any connections that are internal to the group (connections between members, and connections from member of the group to the group itself) - Removes proxies for all connections for which the source or target is a member of the group. - Shows the previously proxied connections. - Adds the jtk-group-collapsed class to the group's element - Removes the jtk-group-expanded class from the group's element. @method expandGroup @param {String|Group} group Group to expand, or ID of Group to expand.
_jpi.prototype.collapseGroup ( groupId )
javascript
lettersporter/easy-flow
src/components/ef/jsplumb.js
https://github.com/lettersporter/easy-flow/blob/master/src/components/ef/jsplumb.js
Apache-2.0
_jpi.prototype.toggleGroup = function(group) { group = this.getGroupManager().getGroup(group); if (group != null) { this.getGroupManager()[group.collapsed ? "expandGroup" : "collapseGroup"](group); } };
Collapses or expands a group element depending on its current state. See notes in the collapseGroup and expandGroup method. @method toggleGroup @param {String|Group} group Group to expand/collapse, or ID of Group to expand/collapse.
_jpi.prototype.toggleGroup ( group )
javascript
lettersporter/easy-flow
src/components/ef/jsplumb.js
https://github.com/lettersporter/easy-flow/blob/master/src/components/ef/jsplumb.js
Apache-2.0
_jpi.prototype.getGroupFor = function(el) { el = this.getElement(el); if (el) { return el[GROUP]; } };
Gets the Group that the given element belongs to, null if none. @method getGroupFor @param {String|Element} el Element, or element ID. @returns {Group} A Group, if found, or null.
_jpi.prototype.getGroupFor ( el )
javascript
lettersporter/easy-flow
src/components/ef/jsplumb.js
https://github.com/lettersporter/easy-flow/blob/master/src/components/ef/jsplumb.js
Apache-2.0
var TWEEN = TWEEN || ( function () { var i, tl, interval, time, tweens = []; return { start: function ( fps ) { interval = setInterval( this.update, 1000 / ( fps || 60 ) ); }, stop: function () { clearInterval( interval ); }, add: function ( tween ) { tweens.push( tween ); }, remove: function ( tween ) { i = tweens.indexOf( tween ); if ( i !== -1 ) { tweens.splice( i, 1 ); } }, update: function () { i = 0; tl = tweens.length; time = new Date().getTime(); while ( i < tl ) { if ( tweens[ i ].update( time ) ) { i++; } else { tweens.splice( i, 1 ); tl--; } } } }; } )();
@author sole / http://soledadpenades.com @author mr.doob / http://mrdoob.com @author Robert Eisele / http://www.xarg.org @author Philippe / http://philippe.elsass.me @author Robert Penner / http://www.robertpenner.com/easing_terms_of_use.html
(anonymous) ( )
javascript
spite/ccapture.js
examples/basic/js/Tween.js
https://github.com/spite/ccapture.js/blob/master/examples/basic/js/Tween.js
MIT
ArrayBufferDataStream.prototype.writeEBMLVarIntWidth = function(i, width) { switch (width) { case 1: this.writeU8((1 << 7) | i); break; case 2: this.writeU8((1 << 6) | (i >> 8)); this.writeU8(i); break; case 3: this.writeU8((1 << 5) | (i >> 16)); this.writeU8(i >> 8); this.writeU8(i); break; case 4: this.writeU8((1 << 4) | (i >> 24)); this.writeU8(i >> 16); this.writeU8(i >> 8); this.writeU8(i); break; case 5: /* * JavaScript converts its doubles to 32-bit integers for bitwise operations, so we need to do a * division by 2^32 instead of a right-shift of 32 to retain those top 3 bits */ this.writeU8((1 << 3) | ((i / 4294967296) & 0x7)); this.writeU8(i >> 24); this.writeU8(i >> 16); this.writeU8(i >> 8); this.writeU8(i); break; default: throw new RuntimeException("Bad EBML VINT size " + width); } };
Write the given 32-bit integer to the stream as an EBML variable-length integer using the given byte width (use measureEBMLVarInt). No error checking is performed to ensure that the supplied width is correct for the integer. @param i Integer to be written @param width Number of bytes to write to the stream
ArrayBufferDataStream.prototype.writeEBMLVarIntWidth ( i , width )
javascript
spite/ccapture.js
src/webm-writer-0.2.0.js
https://github.com/spite/ccapture.js/blob/master/src/webm-writer-0.2.0.js
MIT
ArrayBufferDataStream.prototype.measureEBMLVarInt = function(val) { if (val < (1 << 7) - 1) { /* Top bit is set, leaving 7 bits to hold the integer, but we can't store 127 because * "all bits set to one" is a reserved value. Same thing for the other cases below: */ return 1; } else if (val < (1 << 14) - 1) { return 2; } else if (val < (1 << 21) - 1) { return 3; } else if (val < (1 << 28) - 1) { return 4; } else if (val < 34359738367) { // 2 ^ 35 - 1 (can address 32GB) return 5; } else { throw new RuntimeException("EBML VINT size not supported " + val); } };
Return the number of bytes needed to encode the given integer as an EBML VINT.
ArrayBufferDataStream.prototype.measureEBMLVarInt ( val )
javascript
spite/ccapture.js
src/webm-writer-0.2.0.js
https://github.com/spite/ccapture.js/blob/master/src/webm-writer-0.2.0.js
MIT
ArrayBufferDataStream.prototype.writeUnsignedIntBE = function(u, width) { if (width === undefined) { width = this.measureUnsignedInt(u); } // Each case falls through: switch (width) { case 5: this.writeU8(Math.floor(u / 4294967296)); // Need to use division to access >32 bits of floating point var case 4: this.writeU8(u >> 24); case 3: this.writeU8(u >> 16); case 2: this.writeU8(u >> 8); case 1: this.writeU8(u); break; default: throw new RuntimeException("Bad UINT size " + width); } };
Write the given unsigned 32-bit integer to the stream in big-endian order using the given byte width. No error checking is performed to ensure that the supplied width is correct for the integer. Omit the width parameter to have it determined automatically for you. @param u Unsigned integer to be written @param width Number of bytes to write to the stream
ArrayBufferDataStream.prototype.writeUnsignedIntBE ( u , width )
javascript
spite/ccapture.js
src/webm-writer-0.2.0.js
https://github.com/spite/ccapture.js/blob/master/src/webm-writer-0.2.0.js
MIT
ArrayBufferDataStream.prototype.measureUnsignedInt = function(val) { // Force to 32-bit unsigned integer if (val < (1 << 8)) { return 1; } else if (val < (1 << 16)) { return 2; } else if (val < (1 << 24)) { return 3; } else if (val < 4294967296) { return 4; } else { return 5; } };
Return the number of bytes needed to hold the non-zero bits of the given unsigned integer.
ArrayBufferDataStream.prototype.measureUnsignedInt ( val )
javascript
spite/ccapture.js
src/webm-writer-0.2.0.js
https://github.com/spite/ccapture.js/blob/master/src/webm-writer-0.2.0.js
MIT
ArrayBufferDataStream.prototype.getAsDataArray = function() { if (this.pos < this.data.byteLength) { return this.data.subarray(0, this.pos); } else if (this.pos == this.data.byteLength) { return this.data; } else { throw "ArrayBufferDataStream's pos lies beyond end of buffer"; } };
Return a view on the portion of the buffer from the beginning to the current seek position as a Uint8Array.
ArrayBufferDataStream.prototype.getAsDataArray ( )
javascript
spite/ccapture.js
src/webm-writer-0.2.0.js
https://github.com/spite/ccapture.js/blob/master/src/webm-writer-0.2.0.js
MIT
this.seek = function (offset) { if (offset < 0) { throw "Offset may not be negative"; } if (isNaN(offset)) { throw "Offset may not be NaN"; } if (offset > this.length) { throw "Seeking beyond the end of file is not allowed"; } this.pos = offset; };
Seek to the given absolute offset. You may not seek beyond the end of the file (this would create a hole and/or allow blocks to be written in non- sequential order, which isn't currently supported by the memory buffer backend).
this.seek ( offset )
javascript
spite/ccapture.js
src/webm-writer-0.2.0.js
https://github.com/spite/ccapture.js/blob/master/src/webm-writer-0.2.0.js
MIT
this.complete = function (mimeType) { if (fd || fileWriter) { writePromise = writePromise.then(function () { return null; }); } else { // After writes complete we need to merge the buffer to give to the caller writePromise = writePromise.then(function () { var result = []; for (var i = 0; i < buffer.length; i++) { result.push(buffer[i].data); } return new Blob(result, {mimeType: mimeType}); }); } return writePromise; };
Finish all writes to the buffer, returning a promise that signals when that is complete. If a FileWriter was not provided, the promise is resolved with a Blob that represents the completed BlobBuffer contents. You can optionally pass in a mimeType to be used for this blob. If a FileWriter was provided, the promise is resolved with null as the first argument.
this.complete ( mimeType )
javascript
spite/ccapture.js
src/webm-writer-0.2.0.js
https://github.com/spite/ccapture.js/blob/master/src/webm-writer-0.2.0.js
MIT
this.write = function (data) { var newEntry = { offset: this.pos, data: data, length: measureData(data) }, isAppend = newEntry.offset >= this.length; this.pos += newEntry.length; this.length = Math.max(this.length, this.pos); // After previous writes complete, perform our write writePromise = writePromise.then(function () { if (fd) { return new Promise(function(resolve, reject) { convertToUint8Array(newEntry.data).then(function(dataArray) { var totalWritten = 0, buffer = Buffer.from(dataArray.buffer), handleWriteComplete = function(err, written, buffer) { totalWritten += written; if (totalWritten >= buffer.length) { resolve(); } else { // We still have more to write... fs.write(fd, buffer, totalWritten, buffer.length - totalWritten, newEntry.offset + totalWritten, handleWriteComplete); } }; fs.write(fd, buffer, 0, buffer.length, newEntry.offset, handleWriteComplete); }); }); } else if (fileWriter) { return new Promise(function (resolve, reject) { fileWriter.onwriteend = resolve; fileWriter.seek(newEntry.offset); fileWriter.write(new Blob([newEntry.data])); }); } else if (!isAppend) { // We might be modifying a write that was already buffered in memory. // Slow linear search to find a block we might be overwriting for (var i = 0; i < buffer.length; i++) { var entry = buffer[i]; // If our new entry overlaps the old one in any way... if (!(newEntry.offset + newEntry.length <= entry.offset || newEntry.offset >= entry.offset + entry.length)) { if (newEntry.offset < entry.offset || newEntry.offset + newEntry.length > entry.offset + entry.length) { throw new Error("Overwrite crosses blob boundaries"); } if (newEntry.offset == entry.offset && newEntry.length == entry.length) { // We overwrote the entire block entry.data = newEntry.data; // We're done return; } else { return convertToUint8Array(entry.data) .then(function (entryArray) { entry.data = entryArray; return convertToUint8Array(newEntry.data); }).then(function (newEntryArray) { newEntry.data = newEntryArray; entry.data.set(newEntry.data, newEntry.offset - entry.offset); }); } } } // Else fall through to do a simple append, as we didn't overwrite any pre-existing blocks } buffer.push(newEntry); }); }; /** * Finish all writes to the buffer, returning a promise that signals when that is complete. * * If a FileWriter was not provided, the promise is resolved with a Blob that represents the completed BlobBuffer * contents. You can optionally pass in a mimeType to be used for this blob. * * If a FileWriter was provided, the promise is resolved with null as the first argument. */ this.complete = function (mimeType) { if (fd || fileWriter) { writePromise = writePromise.then(function () { return null; }); } else { // After writes complete we need to merge the buffer to give to the caller writePromise = writePromise.then(function () { var result = []; for (var i = 0; i < buffer.length; i++) { result.push(buffer[i].data); } return new Blob(result, {mimeType: mimeType}); }); } return writePromise; }; };
Write the Blob-convertible data to the buffer at the current seek position. Note: If overwriting existing data, the write must not cross preexisting block boundaries (written data must be fully contained by the extent of a previous write).
this.write ( data )
javascript
spite/ccapture.js
src/webm-writer-0.2.0.js
https://github.com/spite/ccapture.js/blob/master/src/webm-writer-0.2.0.js
MIT
function decodeBase64WebPDataURL(url) { if (typeof url !== "string" || !url.match(/^data:image\/webp;base64,/i)) { return false; } return window.atob(url.substring("data:image\/webp;base64,".length)); }
Decode a Base64 data URL into a binary string. Returns the binary string, or false if the URL could not be decoded.
decodeBase64WebPDataURL ( url )
javascript
spite/ccapture.js
src/webm-writer-0.2.0.js
https://github.com/spite/ccapture.js/blob/master/src/webm-writer-0.2.0.js
MIT
isDigit: function isDigit(keyCode) { return ZERO <= keyCode && keyCode <= NINE; },
@param {number} keyCode @returns {boolean}
isDigit ( keyCode )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
isDirectional: function isDirectional(keyCode) { return keyCode === LEFT || keyCode === RIGHT || keyCode === UP || keyCode === DOWN; }
Is an arrow keyCode. @param {number} keyCode @returns {boolean}
isDirectional ( keyCode )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function keyBindingsForPlatform(platform) { var osx = platform === 'OSX'; var ctrl = osx ? META : CTRL; if (!cache[platform]) { cache[platform] = build(function (bind) { bind(A, ctrl, 'selectAll'); bind(LEFT, null, 'moveLeft'); bind(LEFT, ALT, 'moveWordLeft'); bind(LEFT, SHIFT, 'moveLeftAndModifySelection'); bind(LEFT, ALT | SHIFT, 'moveWordLeftAndModifySelection'); bind(RIGHT, null, 'moveRight'); bind(RIGHT, ALT, 'moveWordRight'); bind(RIGHT, SHIFT, 'moveRightAndModifySelection'); bind(RIGHT, ALT | SHIFT, 'moveWordRightAndModifySelection'); bind(UP, null, 'moveUp'); bind(UP, ALT, 'moveToBeginningOfParagraph'); bind(UP, SHIFT, 'moveUpAndModifySelection'); bind(UP, ALT | SHIFT, 'moveParagraphBackwardAndModifySelection'); bind(DOWN, null, 'moveDown'); bind(DOWN, ALT, 'moveToEndOfParagraph'); bind(DOWN, SHIFT, 'moveDownAndModifySelection'); bind(DOWN, ALT | SHIFT, 'moveParagraphForwardAndModifySelection'); bind(BACKSPACE, null, 'deleteBackward'); bind(BACKSPACE, SHIFT, 'deleteBackward'); bind(BACKSPACE, ALT, 'deleteWordBackward'); bind(BACKSPACE, ALT | SHIFT, 'deleteWordBackward'); bind(BACKSPACE, ctrl, 'deleteBackwardToBeginningOfLine'); bind(BACKSPACE, ctrl | SHIFT, 'deleteBackwardToBeginningOfLine'); bind(DELETE, null, 'deleteForward'); bind(DELETE, ALT, 'deleteWordForward'); bind(TAB, null, 'insertTab'); bind(TAB, SHIFT, 'insertBackTab'); bind(ENTER, null, 'insertNewline'); bind(Z, ctrl, 'undo'); if (osx) { bind(LEFT, META, 'moveToBeginningOfLine'); bind(LEFT, META | SHIFT, 'moveToBeginningOfLineAndModifySelection'); bind(RIGHT, META, 'moveToEndOfLine'); bind(RIGHT, META | SHIFT, 'moveToEndOfLineAndModifySelection'); bind(UP, META, 'moveToBeginningOfDocument'); bind(UP, META | SHIFT, 'moveToBeginningOfDocumentAndModifySelection'); bind(DOWN, META, 'moveToEndOfDocument'); bind(DOWN, META | SHIFT, 'moveToEndOfDocumentAndModifySelection'); bind(BACKSPACE, CTRL, 'deleteBackwardByDecomposingPreviousCharacter'); bind(BACKSPACE, CTRL | SHIFT, 'deleteBackwardByDecomposingPreviousCharacter'); bind(Z, META | SHIFT, 'redo'); } else { bind(Y, CTRL, 'redo'); } }); } return cache[platform]; }
Builds a BindingSet based on the current platform. @param {string} platform A string name of a platform (e.g. "OSX"). @returns {BindingSet} keybindings appropriate for the given platform.
keyBindingsForPlatform ( platform )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function isWordChar(chr) { return chr && /^\w$/.test(chr); }
Tests is string passed in is a single word. @param {string} chr @returns {boolean} @private
isWordChar ( chr )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function hasLeftWordBreakAtIndex(text, index) { if (index === 0) { return true; } else { return !isWordChar(text[index - 1]) && isWordChar(text[index]); } }
Checks if char to the left of {index} in {string} is a break (non-char). @param {string} text @param {number} index @returns {boolean} @private
hasLeftWordBreakAtIndex ( text , index )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function hasRightWordBreakAtIndex(text, index) { if (index === text.length - 1) { return true; } else { return isWordChar(text[index]) && !isWordChar(text[index + 1]); } }
Checks if char to the right of {index} in {string} is a break (non-char). @param {string} text @param {number} index @returns {boolean} @private
hasRightWordBreakAtIndex ( text , index )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function Input(value, range) { _classCallCheck(this, Input); this._value = ''; this._selectedRange = { start: 0, length: 0 }; this.shouldCancelEvents = true; this.selectionAffinity = Affinity.NONE; if (value) { this.setText(value); } if (range) { this.setSelectedRange(range); } this._buildKeybindings(); }
Sets up the initial properties of the TextField and sets up the event listeners @param {string} value @param {Object} range ({start: 0, length: 0})
Input ( value , range )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function increment(strint) { var length = strint.length; if (length === 0) { return '1'; } var last = parseInt(strint[length - 1], 10); if (last === 9) { return increment(strint.slice(0, length - 1)) + '0'; } else { return strint.slice(0, length - 1) + (last + 1); } }
Increments the given integer represented by a string by one. @example increment('1'); // '2' increment('99'); // '100' increment(''); // '1' @param {string} strint @return {string} @private
increment ( strint )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function parse(strnum) { switch (strnum) { case 'NaN':case 'Infinity':case '-Infinity': return null; } var match = strnum.match(NUMBER_PATTERN); if (!match) { throw new Error('cannot round malformed number: ' + strnum); } return [match[1] !== undefined, match[2], match[3] || '']; }
Parses the given decimal string into its component parts. @example stround.parse('3.14'); // [false, '3', '14'] stround.parse('-3.45'); // [true, '3', '45'] @param {string} strnum @return {?Array}
parse ( strnum )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function shiftParts(_ref3, exponent) { var _ref32 = _slicedToArray(_ref3, 3); var negative = _ref32[0]; var intPart = _ref32[1]; var fracPart = _ref32[2]; var partToMove = undefined; if (exponent > 0) { partToMove = fracPart.slice(0, exponent); while (partToMove.length < exponent) { partToMove += '0'; } intPart += partToMove; fracPart = fracPart.slice(exponent); } else if (exponent < 0) { while (intPart.length < -exponent) { intPart = '0' + intPart; } partToMove = intPart.slice(intPart.length + exponent); fracPart = partToMove + fracPart; intPart = intPart.slice(0, intPart.length - partToMove.length); } return [negative, intPart, fracPart]; }
Shift the exponent of the given number (in parts) by the given amount. @example stround.shiftParts([false, '12', ''], 2); // [false, '1200', ''] stround.shiftParts([false, '12', ''], -2); // [false, '', '12'] @param {Array} parts @param {number} exponent @return {Array}
shiftParts ( _ref3 , exponent )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function shift(strnum, exponent) { if (typeof strnum === 'number') { strnum = '' + strnum; } var parsed = parse(strnum); if (parsed === null) { return strnum; } else { return format(shiftParts(parsed, exponent)); } }
Shift the exponent of the given number (as a string) by the given amount. shift('12', 2); // '1200' shift('12', -2); // '0.12' @param {string|number} strnum @param {number} exponent @return {string}
shift ( strnum , exponent )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function round(strnum, precision, mode) { if (typeof strnum === 'number') { strnum = '' + strnum; } if (typeof strnum !== 'string') { throw new Error('expected a string or number, got: ' + strnum); } if (strnum.length === 0) { return strnum; } if (precision === null || precision === undefined) { precision = 0; } if (mode === undefined) { mode = modes.HALF_EVEN; } var parsed = parse(strnum); if (parsed === null) { return strnum; } if (precision > 0) { parsed = shiftParts(parsed, precision); } var _parsed = parsed; var _parsed2 = _slicedToArray(_parsed, 3); var negative = _parsed2[0]; var intPart = _parsed2[1]; var fracPart = _parsed2[2]; switch (mode) { case modes.CEILING:case modes.FLOOR:case modes.UP: var foundNonZeroDigit = false; for (var i = 0, _length = fracPart.length; i < _length; i++) { if (fracPart[i] !== '0') { foundNonZeroDigit = true; break; } } if (foundNonZeroDigit) { if (mode === modes.UP || negative !== (mode === modes.CEILING)) { intPart = increment(intPart); } } break; case modes.HALF_EVEN:case modes.HALF_DOWN:case modes.HALF_UP: var shouldRoundUp = false; var firstFracPartDigit = parseInt(fracPart[0], 10); if (firstFracPartDigit > 5) { shouldRoundUp = true; } else if (firstFracPartDigit === 5) { if (mode === modes.HALF_UP) { shouldRoundUp = true; } if (!shouldRoundUp) { for (var i = 1, _length2 = fracPart.length; i < _length2; i++) { if (fracPart[i] !== '0') { shouldRoundUp = true; break; } } } if (!shouldRoundUp && mode === modes.HALF_EVEN) { var lastIntPartDigit = parseInt(intPart[intPart.length - 1], 10); shouldRoundUp = lastIntPartDigit % 2 !== 0; } } if (shouldRoundUp) { intPart = increment(intPart); } break; } return format(shiftParts([negative, intPart, ''], -precision)); }
Round the given number represented by a string according to the given precision and mode. @param {string|number} strnum @param {number|null|undefined=} precision @param {modes=} mode @return {string}
round ( strnum , precision , mode )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function format(_ref) { var _ref2 = _slicedToArray(_ref, 3); var negative = _ref2[0]; var intPart = _ref2[1]; var fracPart = _ref2[2]; if (intPart.length === 0) { intPart = '0'; } else { var firstNonZeroIndex = undefined; for (firstNonZeroIndex = 0; firstNonZeroIndex < intPart.length; firstNonZeroIndex++) { if (intPart[firstNonZeroIndex] !== '0') { break; } } if (firstNonZeroIndex !== intPart.length) { intPart = intPart.slice(firstNonZeroIndex); } } return (negative ? NEG + intPart : intPart) + (fracPart.length ? SEP + fracPart : ''); } /** * Shift the exponent of the given number (in parts) by the given amount. * * @example * * stround.shiftParts([false, '12', ''], 2); // [false, '1200', ''] * stround.shiftParts([false, '12', ''], -2); // [false, '', '12'] * * @param {Array} parts * @param {number} exponent * @return {Array} */ function shiftParts(_ref3, exponent) { var _ref32 = _slicedToArray(_ref3, 3); var negative = _ref32[0]; var intPart = _ref32[1]; var fracPart = _ref32[2]; var partToMove = undefined; if (exponent > 0) { partToMove = fracPart.slice(0, exponent); while (partToMove.length < exponent) { partToMove += '0'; } intPart += partToMove; fracPart = fracPart.slice(exponent); } else if (exponent < 0) { while (intPart.length < -exponent) { intPart = '0' + intPart; } partToMove = intPart.slice(intPart.length + exponent); fracPart = partToMove + fracPart; intPart = intPart.slice(0, intPart.length - partToMove.length); } return [negative, intPart, fracPart]; } /** * Shift the exponent of the given number (as a string) by the given amount. * * shift('12', 2); // '1200' * shift('12', -2); // '0.12' * * @param {string|number} strnum * @param {number} exponent * @return {string} */ function shift(strnum, exponent) { if (typeof strnum === 'number') { strnum = '' + strnum; } var parsed = parse(strnum); if (parsed === null) { return strnum; } else { return format(shiftParts(parsed, exponent)); } } /** * Round the given number represented by a string according to the given * precision and mode. * * @param {string|number} strnum * @param {number|null|undefined=} precision * @param {modes=} mode * @return {string} */ function round(strnum, precision, mode) { if (typeof strnum === 'number') { strnum = '' + strnum; } if (typeof strnum !== 'string') { throw new Error('expected a string or number, got: ' + strnum); } if (strnum.length === 0) { return strnum; } if (precision === null || precision === undefined) { precision = 0; } if (mode === undefined) { mode = modes.HALF_EVEN; } var parsed = parse(strnum); if (parsed === null) { return strnum; } if (precision > 0) { parsed = shiftParts(parsed, precision); } var _parsed = parsed; var _parsed2 = _slicedToArray(_parsed, 3); var negative = _parsed2[0]; var intPart = _parsed2[1]; var fracPart = _parsed2[2]; switch (mode) { case modes.CEILING:case modes.FLOOR:case modes.UP: var foundNonZeroDigit = false; for (var i = 0, _length = fracPart.length; i < _length; i++) { if (fracPart[i] !== '0') { foundNonZeroDigit = true; break; } } if (foundNonZeroDigit) { if (mode === modes.UP || negative !== (mode === modes.CEILING)) { intPart = increment(intPart); } } break; case modes.HALF_EVEN:case modes.HALF_DOWN:case modes.HALF_UP: var shouldRoundUp = false; var firstFracPartDigit = parseInt(fracPart[0], 10); if (firstFracPartDigit > 5) { shouldRoundUp = true; } else if (firstFracPartDigit === 5) { if (mode === modes.HALF_UP) { shouldRoundUp = true; } if (!shouldRoundUp) { for (var i = 1, _length2 = fracPart.length; i < _length2; i++) { if (fracPart[i] !== '0') { shouldRoundUp = true; break; } } } if (!shouldRoundUp && mode === modes.HALF_EVEN) { var lastIntPartDigit = parseInt(intPart[intPart.length - 1], 10); shouldRoundUp = lastIntPartDigit % 2 !== 0; } } if (shouldRoundUp) { intPart = increment(intPart); } break; } return format(shiftParts([negative, intPart, ''], -precision)); } });
Format the given number configuration as a number string. @example stround.format([false, '12', '34']); // '12.34' stround.format([true, '8', '']); // '-8' stround.format([true, '', '7']); // '-0.7' @param {Array} parts @return {string}
format ( _ref )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
var AdaptiveCardFormatter = (function () { function AdaptiveCardFormatter() { _classCallCheck(this, AdaptiveCardFormatter); /** @private */ this.amexCardFormatter = new _amex_card_formatter2['default'](); /** @private */ this.defaultCardFormatter = new _default_card_formatter2['default'](); /** @private */ this.formatter = this.defaultCardFormatter; } /** * Will pick the right formatter based on the `pan` and will return the * formatted string. * * @param {string} pan * @returns {string} formatted string */ _createClass(AdaptiveCardFormatter, [{ key: 'format', value: function format(pan) { return this._formatterForPan(pan).format(pan); } /** * Will call parse on the formatter. * * @param {string} text * @param {function(string)} error * @returns {string} returns value with delimiters removed */ }, { key: 'parse', value: function parse(text, error) { return this.formatter.parse(text, error); } /** * Determines whether the given change should be allowed and, if so, whether * it should be altered. * * @param {TextFieldStateChange} change * @param {function(!string)} error * @returns {boolean} */ }, { key: 'isChangeValid', value: function isChangeValid(change, error) { this.formatter = this._formatterForPan(change.proposed.text); return this.formatter.isChangeValid(change, error); } /** * Decides which formatter to use. * * @param {string} pan * @returns {Formatter} * @private */ }, { key: '_formatterForPan', value: function _formatterForPan(pan) { if ((0, _card_utils.determineCardType)(pan.replace(/[^\d]+/g, '')) === _card_utils.AMEX) { return this.amexCardFormatter; } else { return this.defaultCardFormatter; } } }]); return AdaptiveCardFormatter; })();
AdaptiveCardFormatter will decide if it needs to use {@link AmexCardFormatter} or {@link DefaultCardFormatter}.
(anonymous) ( )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
var AmexCardFormatter = (function (_DefaultCardFormatter) { _inherits(AmexCardFormatter, _DefaultCardFormatter); function AmexCardFormatter() { _classCallCheck(this, AmexCardFormatter); _get(Object.getPrototypeOf(AmexCardFormatter.prototype), 'constructor', this).apply(this, arguments); } _createClass(AmexCardFormatter, [{ key: 'hasDelimiterAtIndex', /** * @override */ value: function hasDelimiterAtIndex(index) { return index === 4 || index === 11; } /** * @override */ }, { key: 'maximumLength', get: function get() { return 15 + 2; } }]); return AmexCardFormatter; })(_default_card_formatter2['default']);
Amex credit card formatter. @extends DefaultCardFormatter
(anonymous) ( _DefaultCardFormatter )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
var CardTextField = (function (_TextField) { _inherits(CardTextField, _TextField); /** * @param {HTMLElement} element */ function CardTextField(element) { _classCallCheck(this, CardTextField); _get(Object.getPrototypeOf(CardTextField.prototype), 'constructor', this).call(this, element, new _adaptive_card_formatter2['default']()); this.setCardMaskStrategy(CardMaskStrategy.None); /** * Whether we are currently masking the displayed text. * * @private */ this._masked = false; /** * Whether we are currently editing. * * @private */ this._editing = false; } /** * Gets the card type for the current value. * * @returns {string} Returns one of 'visa', 'mastercard', 'amex' and 'discover'. */ _createClass(CardTextField, [{ key: 'cardType', value: function cardType() { return (0, _card_utils.determineCardType)(this.value()); } /** * Gets the type of masking this field uses. * * @returns {CardMaskStrategy} */ }, { key: 'cardMaskStrategy', value: function cardMaskStrategy() { return this._cardMaskStrategy; } /** * Sets the type of masking this field uses. * * @param {CardMaskStrategy} cardMaskStrategy One of CardMaskStrategy. */ }, { key: 'setCardMaskStrategy', value: function setCardMaskStrategy(cardMaskStrategy) { if (cardMaskStrategy !== this._cardMaskStrategy) { this._cardMaskStrategy = cardMaskStrategy; this._syncMask(); } } /** * Returns a masked version of the current formatted PAN. Example: * * @example * field.setText('4111 1111 1111 1111'); * field.cardMask(); // "•••• •••• •••• 1111" * * @returns {string} Returns a masked card string. */ }, { key: 'cardMask', value: function cardMask() { var text = this.text(); var last4 = text.slice(-4); var toMask = text.slice(0, -4); return toMask.replace(/\d/g, '•') + last4; } /** * Gets the formatted PAN for this field. * * @returns {string} */ }, { key: 'text', value: function text() { if (this._masked) { return this._unmaskedText; } else { return _get(Object.getPrototypeOf(CardTextField.prototype), 'text', this).call(this); } } /** * Sets the formatted PAN for this field. * * @param {string} text A formatted PAN. */ }, { key: 'setText', value: function setText(text) { if (this._masked) { this._unmaskedText = text; text = this.cardMask(); } _get(Object.getPrototypeOf(CardTextField.prototype), 'setText', this).call(this, text); } /** * Called by our superclass, used to implement card masking. * * @private */ }, { key: 'textFieldDidEndEditing', value: function textFieldDidEndEditing() { this._editing = false; this._syncMask(); } /** * Called by our superclass, used to implement card masking. * * @private */ }, { key: 'textFieldDidBeginEditing', value: function textFieldDidBeginEditing() { this._editing = true; this._syncMask(); } /** * Enables masking if it is not already enabled. * * @private */ }, { key: '_enableMasking', value: function _enableMasking() { if (!this._masked) { this._unmaskedText = this.text(); this._masked = true; this.setText(this._unmaskedText); } } /** * Disables masking if it is currently enabled. * * @private */ }, { key: '_disableMasking', value: function _disableMasking() { if (this._masked) { this._masked = false; this.setText(this._unmaskedText); this._unmaskedText = null; } } /** * Enables or disables masking based on the mask settings. * * @private */ }, { key: '_syncMask', value: function _syncMask() { if (this.cardMaskStrategy() === CardMaskStrategy.DoneEditing) { if (this._editing) { this._disableMasking(); } else { this._enableMasking(); } } } /** * Enum for card mask strategies. * * @readonly * @enum {number} */ }], [{ key: 'CardMaskStrategy', get: function get() { return CardMaskStrategy; } }]); return CardTextField; })(_text_field2['default']);
CardTextField add some functionality for credit card inputs @extends TextField
(anonymous) ( _TextField )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function determineCardType(pan) { if (pan === null || pan === undefined) { return null; } pan = pan.toString(); var firsttwo = parseInt(pan.slice(0, 2), 10); var iin = parseInt(pan.slice(0, 6), 10); var halfiin = parseInt(pan.slice(0, 3), 10); if (pan[0] === '4') { return VISA; } else if (pan.slice(0, 4) === '6011' || firsttwo === 65 || halfiin >= 664 && halfiin <= 649 || iin >= 622126 && iin <= 622925) { return DISCOVER; } else if (pan.slice(0, 4) === '2131' || pan.slice(0, 4) === '1800' || firsttwo === 35) { return JCB; } else if (firsttwo >= 51 && firsttwo <= 55) { return MASTERCARD; } else if (firsttwo === 34 || firsttwo === 37) { return AMEX; } }
Pass in a credit card number and it'll return the type of card it is. @param {string} pan @returns {?string} returns the type of card based in the digits
determineCardType ( pan )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function luhnCheck(pan) { var sum = 0; var flip = true; for (var i = pan.length - 1; i >= 0; i--) { var digit = parseInt(pan.charAt(i), 10); sum += (flip = !flip) ? Math.floor(digit * 2 / 10) + Math.floor(digit * 2 % 10) : digit; } return sum % 10 === 0; }
Pass in a credit card number and it'll return if it passes the [luhn algorithm](http://en.wikipedia.org/wiki/Luhn_algorithm) @param {string} pan @returns {boolean}
luhnCheck ( pan )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function validCardLength(pan) { switch (determineCardType(pan)) { case VISA: return pan.length === 13 || pan.length === 16; case DISCOVER:case MASTERCARD: return pan.length === 16; case JCB: return pan.length === 15 || pan.length === 16; case AMEX: return pan.length === 15; default: return false; } }
Pass in a credit card number and it'll return if it is a valid length for that type. If it doesn't know the type it'll return false @param {string} pan @returns {boolean}
validCardLength ( pan )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
var DefaultCardFormatter = (function (_DelimitedTextFormatter) { _inherits(DefaultCardFormatter, _DelimitedTextFormatter); function DefaultCardFormatter() { _classCallCheck(this, DefaultCardFormatter); _get(Object.getPrototypeOf(DefaultCardFormatter.prototype), 'constructor', this).call(this, ' '); } /** * @param {number} index * @returns {boolean} */ _createClass(DefaultCardFormatter, [{ key: 'hasDelimiterAtIndex', value: function hasDelimiterAtIndex(index) { return index === 4 || index === 9 || index === 14; } /** * Will call parse on the formatter. * * @param {string} text * @param {function(string)} error * @returns {string} returns value with delimiters removed */ }, { key: 'parse', value: function parse(text, error) { var value = this._valueFromText(text); if (typeof error === 'function') { if (!(0, _card_utils.validCardLength)(value)) { error('card-formatter.number-too-short'); } if (!(0, _card_utils.luhnCheck)(value)) { error('card-formatter.invalid-number'); } } return _get(Object.getPrototypeOf(DefaultCardFormatter.prototype), 'parse', this).call(this, text, error); } /** * Parses the given text by removing delimiters. * * @param {?string} text * @returns {string} * @private */ }, { key: '_valueFromText', value: function _valueFromText(text) { return _get(Object.getPrototypeOf(DefaultCardFormatter.prototype), '_valueFromText', this).call(this, (text || '').replace(/[^\d]/g, '')); } /** * Gets the maximum length of a formatted default card number. * * @returns {number} */ }, { key: 'maximumLength', get: function get() { return 16 + 3; } }]); return DefaultCardFormatter; })(_delimited_text_formatter2['default']);
A generic credit card formatter. @extends DelimitedTextFormatter
(anonymous) ( _DelimitedTextFormatter )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function DelimitedTextFormatter(delimiter) { var isLazy = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; _classCallCheck(this, DelimitedTextFormatter); _get(Object.getPrototypeOf(DelimitedTextFormatter.prototype), 'constructor', this).call(this); if (arguments.length === 0) { return; } if (delimiter === null || delimiter === undefined || delimiter.length !== 1) { throw new Error('delimiter must have just one character'); } this.delimiter = delimiter; // If the formatter is lazy, delimiter will not be added until input has gone // past the delimiter index. Useful for 'optional' extension, like zip codes. // 94103 -> type '1' -> 94103-1 this.isLazy = isLazy; }
@param {string=} delimiter @param {boolean=} isLazy @throws {Error} delimiter must have just one character
DelimitedTextFormatter ( delimiter )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
var DelimitedTextFormatter = (function (_Formatter) { _inherits(DelimitedTextFormatter, _Formatter); /** * @param {string=} delimiter * @param {boolean=} isLazy * @throws {Error} delimiter must have just one character */ function DelimitedTextFormatter(delimiter) { var isLazy = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; _classCallCheck(this, DelimitedTextFormatter); _get(Object.getPrototypeOf(DelimitedTextFormatter.prototype), 'constructor', this).call(this); if (arguments.length === 0) { return; } if (delimiter === null || delimiter === undefined || delimiter.length !== 1) { throw new Error('delimiter must have just one character'); } this.delimiter = delimiter; // If the formatter is lazy, delimiter will not be added until input has gone // past the delimiter index. Useful for 'optional' extension, like zip codes. // 94103 -> type '1' -> 94103-1 this.isLazy = isLazy; } /** * Determines the delimiter character at the given index. * * @param {number} index * @returns {?string} */ _createClass(DelimitedTextFormatter, [{ key: 'delimiterAt', value: function delimiterAt(index) { if (!this.hasDelimiterAtIndex(index)) { return null; } return this.delimiter; } /** * Determines whether the given character is a delimiter. * * @param {string} chr * @returns {boolean} */ }, { key: 'isDelimiter', value: function isDelimiter(chr) { return chr === this.delimiter; } /** * Formats the given value by adding delimiters where needed. * * @param {?string} value * @returns {string} */ }, { key: 'format', value: function format(value) { return this._textFromValue(value); } /** * Formats the given value by adding delimiters where needed. * * @param {?string} value * @returns {string} * @private */ }, { key: '_textFromValue', value: function _textFromValue(value) { if (!value) { return ''; } var result = ''; var delimiter = undefined; var maximumLength = this.maximumLength; for (var i = 0, l = value.length; i < l; i++) { while (delimiter = this.delimiterAt(result.length)) { result += delimiter; } result += value[i]; if (!this.isLazy) { while (delimiter = this.delimiterAt(result.length)) { result += delimiter; } } } if (maximumLength !== undefined && maximumLength !== null) { return result.slice(0, maximumLength); } else { return result; } } /** * Parses the given text by removing delimiters. * * @param {?string} text * @returns {string} */ }, { key: 'parse', value: function parse(text) { return this._valueFromText(text); } /** * Parses the given text by removing delimiters. * * @param {?string} text * @returns {string} * @private */ }, { key: '_valueFromText', value: function _valueFromText(text) { if (!text) { return ''; } var result = ''; for (var i = 0, l = text.length; i < l; i++) { if (!this.isDelimiter(text[i])) { result += text[i]; } } return result; } /** * Determines whether the given change should be allowed and, if so, whether * it should be altered. * * @param {TextFieldStateChange} change * @param {function(string)} error * @returns {boolean} */ }, { key: 'isChangeValid', value: function isChangeValid(change, error) { if (!_get(Object.getPrototypeOf(DelimitedTextFormatter.prototype), 'isChangeValid', this).call(this, change, error)) { return false; } var newText = change.proposed.text; var range = change.proposed.selectedRange; var hasSelection = range.length !== 0; var startMovedLeft = range.start < change.current.selectedRange.start; var startMovedRight = range.start > change.current.selectedRange.start; var endMovedLeft = range.start + range.length < change.current.selectedRange.start + change.current.selectedRange.length; var endMovedRight = range.start + range.length > change.current.selectedRange.start + change.current.selectedRange.length; var startMovedOverADelimiter = startMovedLeft && this.hasDelimiterAtIndex(range.start) || startMovedRight && this.hasDelimiterAtIndex(range.start - 1); var endMovedOverADelimiter = endMovedLeft && this.hasDelimiterAtIndex(range.start + range.length) || endMovedRight && this.hasDelimiterAtIndex(range.start + range.length - 1); if (this.isDelimiter(change.deleted.text)) { var newCursorPosition = change.deleted.start - 1; // delete any immediately preceding delimiters while (this.isDelimiter(newText.charAt(newCursorPosition))) { newText = newText.substring(0, newCursorPosition) + newText.substring(newCursorPosition + 1); newCursorPosition--; } // finally delete the real character that was intended newText = newText.substring(0, newCursorPosition) + newText.substring(newCursorPosition + 1); } // adjust the cursor / selection if (startMovedLeft && startMovedOverADelimiter) { // move left over any immediately preceding delimiters while (this.delimiterAt(range.start - 1)) { range.start--; range.length++; } // finally move left over the real intended character range.start--; range.length++; } if (startMovedRight) { // move right over any delimiters found on the way, including any leading delimiters for (var i = change.current.selectedRange.start; i < range.start + range.length; i++) { if (this.delimiterAt(i)) { range.start++; if (range.length > 0) { range.length--; } } } while (this.delimiterAt(range.start)) { range.start++; range.length--; } } if (hasSelection) { // Otherwise, the logic for the range start takes care of everything. if (endMovedOverADelimiter) { if (endMovedLeft) { // move left over any immediately preceding delimiters while (this.delimiterAt(range.start + range.length - 1)) { range.length--; } // finally move left over the real intended character range.length--; } if (endMovedRight) { // move right over any immediately following delimiters while (this.delimiterAt(range.start + range.length)) { range.length++; } // finally move right over the real intended character range.length++; } } // trailing delimiters in the selection while (this.hasDelimiterAtIndex(range.start + range.length - 1)) { if (startMovedLeft || endMovedLeft) { range.length--; } else { range.length++; } } while (this.hasDelimiterAtIndex(range.start)) { if (startMovedRight || endMovedRight) { range.start++; range.length--; } else { range.start--; range.length++; } } } else { range.length = 0; } var result = true; var value = this._valueFromText(newText, function () { result = false; error.apply(undefined, arguments); }); if (result) { change.proposed.text = this._textFromValue(value); } return result; } }]); return DelimitedTextFormatter; })(_formatter2['default']);
A generic delimited formatter. @extends Formatter
(anonymous) ( _Formatter )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
var ExpiryDateField = (function (_TextField) { _inherits(ExpiryDateField, _TextField); /** * @param {HTMLElement} element */ function ExpiryDateField(element) { _classCallCheck(this, ExpiryDateField); _get(Object.getPrototypeOf(ExpiryDateField.prototype), 'constructor', this).call(this, element, new _expiry_date_formatter2['default']()); } /** * Called by our superclass, used to post-process the text. * * @private */ _createClass(ExpiryDateField, [{ key: 'textFieldDidEndEditing', value: function textFieldDidEndEditing() { var value = this.value(); if (value) { this.setText(this.formatter().format(value)); } } }]); return ExpiryDateField; })(_text_field2['default']);
Adds a default formatter for expiration dates. @extends TextField
(anonymous) ( _TextField )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function interpretTwoDigitYear(year) { var thisYear = new Date().getFullYear(); var thisCentury = thisYear - thisYear % 100; var centuries = [thisCentury, thisCentury - 100, thisCentury + 100].sort(function (a, b) { return Math.abs(thisYear - (year + a)) - Math.abs(thisYear - (year + b)); }); return year + centuries[0]; }
Give this function a 2 digit year it'll return with 4. @example interpretTwoDigitYear(15); // => 2015 interpretTwoDigitYear(97); // => 1997 @param {number} year @returns {number} @private
interpretTwoDigitYear ( year )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function replaceCurrencySymbol(string, currencySymbol) { return string.replace(/¤/g, currencySymbol); }
@param {string} string @param {string} currencySymbol @return {string} @private
replaceCurrencySymbol ( string , currencySymbol )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function replacePlusSign(string, plusSign) { return string.replace(/\+/g, plusSign); }
@param {string} string @param {string} plusSign @returns {string} @private
replacePlusSign ( string , plusSign )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function replaceMinusSign(string, minusSign) { return string.replace(/-/g, minusSign); }
@param {string} string @param {string} minusSign @returns {string} @private
replaceMinusSign ( string , minusSign )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
value: function format(settings) { var result = ''; var minimumIntegerDigits = settings.minimumIntegerDigits; if (minimumIntegerDigits !== 0) { result += chars(PADDING, minimumIntegerDigits); } result = DIGIT + result; if (settings.usesGroupingSeparator) { while (result.length <= settings.groupingSize) { result = DIGIT + result; } result = result.slice(0, -settings.groupingSize) + GROUPING_SEPARATOR + result.slice(-settings.groupingSize); } var minimumFractionDigits = settings.minimumFractionDigits; var maximumFractionDigits = settings.maximumFractionDigits; var hasFractionalPart = settings.alwaysShowsDecimalSeparator || minimumFractionDigits > 0 || maximumFractionDigits > 0; if (hasFractionalPart) { result += DECIMAL_SEPARATOR; for (var i = 0, _length = maximumFractionDigits; i < _length; i++) { result += i < minimumFractionDigits ? PADDING : DIGIT; } } return settings.prefix + result + settings.suffix; }
@param {NumberFormatterSettings} settings @returns {string}
format ( settings )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function PhoneFormatter() { _classCallCheck(this, PhoneFormatter); _get(Object.getPrototypeOf(PhoneFormatter.prototype), 'constructor', this).call(this); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args.length !== 0) { throw new Error('were you trying to set a delimiter (' + args[0] + ')?'); } }
@throws {Error} if anything is passed in @param {Array} args
PhoneFormatter ( )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function TextField(element, formatter) { _classCallCheck(this, TextField); _get(Object.getPrototypeOf(TextField.prototype), 'constructor', this).call(this); var caret = getCaret(element); if (typeof element.get === 'function') { console.warn('DEPRECATION: FieldKit.TextField instances should no longer be ' + 'created with a jQuery-wrapped element.'); element = element.get(0); } this.element = element; this._formatter = formatter; this._enabled = true; this._manualCaret = { start: 0, end: 0 }; this._placeholder = null; this._disabledPlaceholder = null; this._focusedPlaceholder = null; this._unfocusedPlaceholder = null; this._isDirty = false; this._valueOnFocus = ''; this._currentValue = ''; // Make sure textDidChange fires while the value is correct this._needsKeyUpTextDidChangeTrigger = false; this._blur = (0, _utils.bind)(this._blur, this); this._focus = (0, _utils.bind)(this._focus, this); this._click = (0, _utils.bind)(this._click, this); this._paste = (0, _utils.bind)(this._paste, this); this._keyUp = (0, _utils.bind)(this._keyUp, this); this._keyPress = (0, _utils.bind)(this._keyPress, this); this._keyDown = (0, _utils.bind)(this._keyDown, this); if (element['field-kit-text-field']) { throw new Error('already attached a TextField to this element'); } else { element['field-kit-text-field'] = this; } element.addEventListener('keydown', this._keyDown); element.addEventListener('keypress', this._keyPress); element.addEventListener('keyup', this._keyUp); element.addEventListener('click', this._click); element.addEventListener('paste', this._paste); element.addEventListener('focus', this._focus); element.addEventListener('blur', this._blur); if (!element.getAttribute('autocapitalize')) { element.setAttribute('autocapitalize', 'off'); } var window = element.ownerDocument.defaultView; /** * Fixes caret bug (Android) that caused the input * to place inserted characters in the wrong place * Expected: 1234 5678| => 1234 5678 9| * Bug: 1234 5678| => 1234 5679| 8 * * @private */ this._needsManualCaret = window.navigator.userAgent.toLowerCase().indexOf('android') > -1; this.setText(element.value); this.setSelectedRange({ start: caret.start, length: caret.end - caret.start }); }
Sets up the initial properties of the TextField and sets up the event listeners @param {HTMLElement} element @param {Formatter} formatter
TextField ( element , formatter )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function isDigits(string) { return DIGITS_PATTERN.test(string); }
@param {string} string @returns {boolean}
isDigits ( string )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function startsWith(prefix, string) { return string.slice(0, prefix.length) === prefix; }
@param {string} prefix @param {string} string @returns {boolean}
startsWith ( prefix , string )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function endsWith(suffix, string) { return string.slice(string.length - suffix.length) === suffix; }
@param {string} suffix @param {string} string @returns {boolean}
endsWith ( suffix , string )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function zpad(length, n) { var result = '' + n; while (result.length < length) { result = '0' + result; } return result; }
Will pad n with `0` up until length. @example zpad(16, '1234'); // => 0000000000001234 @param {number} length @param {(string|number)} n @returns {string}
zpad ( length , n )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function zpad2(n) { return zpad(2, n); }
Will pad n with `0` up until length is 2. @example zpad2('2'); // => 02 @param {(string|number)} n @returns {string}
zpad2 ( n )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function bind(fn, context) { return fn.bind(context); }
PhantomJS 1.9 does not have Function.bind. @param {Function} fn @param {*} context @returns {*}
bind ( fn , context )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function replaceStringSelection(replacement, text, range) { var end = range.start + range.length; return text.substring(0, range.start) + replacement + text.substring(end); }
Replaces the characters within the selection with given text. @example // 12|34567|8 replaceStringSelection('12345678', '00', { start: 2, length: 5 }); // 12|00|8 @param {string} replacement @param {string} text @param {object} {start: number, length: number} @returns {string}
replaceStringSelection ( replacement , text , range )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function forEach(iterable, iterator) { if (iterable && typeof iterable.forEach === 'function') { iterable.forEach(iterator); } else if (({}).toString.call(iterable) === '[object Array]') { for (var i = 0, l = iterable.length; i < l; i++) { iterator.call(null, iterable[i], i, iterable); } } else { for (var key in iterable) { if (hasOwnProp.call(iterable, key)) { iterator.call(null, iterable[key], key, iterable); } } } }
@param {*} iterable @param {Function} iterator
forEach ( iterable , iterator )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function hasGetter(object, property) { // Skip if getOwnPropertyDescriptor throws (IE8) try { Object.getOwnPropertyDescriptor({}, 'sq'); } catch (e) { return false; } var descriptor = undefined; if (object && object.constructor && object.constructor.prototype) { descriptor = Object.getOwnPropertyDescriptor(object.constructor.prototype, property); } if (!descriptor) { descriptor = Object.getOwnPropertyDescriptor(object, property); } if (descriptor && descriptor.get) { return true; } else { return false; } }
@param {Object} object @param {string} property @returns {boolean}
hasGetter ( object , property )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function getAllPropertyNames(object) { if (object === null || object === undefined) { return []; } var result = getOwnPropertyNames(object); var prototype = object.constructor && object.constructor.prototype; while (prototype) { result.push.apply(result, _toConsumableArray(getOwnPropertyNames(prototype))); prototype = getPrototypeOf(prototype); } return result; }
@param {Object} object @returns {?string[]}
getAllPropertyNames ( object )
javascript
square/field-kit
public/javascript/field-kit.js
https://github.com/square/field-kit/blob/master/public/javascript/field-kit.js
Apache-2.0
function buildSettings(overrides) { var key; var result = /** @type NumberFormatterSettings */ {}; for (key in DEFAULT_SETTINGS) { if (DEFAULT_SETTINGS.hasOwnProperty(key)) { result[key] = DEFAULT_SETTINGS[key]; } } if (overrides) { for (key in overrides) { if (overrides.hasOwnProperty(key)) { result[key] = overrides[key]; } } } return result; }
Builds a full settings object from defaults with the given overrides. @param {Object=} overrides @returns {NumberFormatterSettings}
buildSettings ( overrides )
javascript
square/field-kit
test/unit/number_formatter_settings_formatter_test.js
https://github.com/square/field-kit/blob/master/test/unit/number_formatter_settings_formatter_test.js
Apache-2.0
textFieldDidEndEditing() { const value = this.value(); if (value) { this.setText(this.formatter().format(value)); } }
Called by our superclass, used to post-process the text. @private
textFieldDidEndEditing ( )
javascript
square/field-kit
src/expiry_date_field.js
https://github.com/square/field-kit/blob/master/src/expiry_date_field.js
Apache-2.0
canUndo() { return this._undos.length !== 0; }
Determines whether there are any undo actions on the stack. @returns {boolean}
canUndo ( )
javascript
square/field-kit
src/undo_manager.js
https://github.com/square/field-kit/blob/master/src/undo_manager.js
Apache-2.0
canRedo() { return this._redos.length !== 0; }
Determines whether there are any redo actions on the stack. @returns {boolean}
canRedo ( )
javascript
square/field-kit
src/undo_manager.js
https://github.com/square/field-kit/blob/master/src/undo_manager.js
Apache-2.0
isUndoing() { return this._isUndoing; }
Indicates whether or not this manager is currently processing an undo. @returns {boolean}
isUndoing ( )
javascript
square/field-kit
src/undo_manager.js
https://github.com/square/field-kit/blob/master/src/undo_manager.js
Apache-2.0
isRedoing() { return this._isRedoing; }
Indicates whether or not this manager is currently processing a redo. @returns {boolean}
isRedoing ( )
javascript
square/field-kit
src/undo_manager.js
https://github.com/square/field-kit/blob/master/src/undo_manager.js
Apache-2.0
registerUndo(target, selector, ...args) { if (this._isUndoing) { this._appendRedo(target, selector, ...args); } else { if (!this._isRedoing) { this._redos.length = 0; } this._appendUndo(target, selector, ...args); } }
Manually registers an simple undo action with the given args. If this undo manager is currently undoing then this will register a redo action instead. If this undo manager is neither undoing or redoing then the redo stack will be cleared. @param {Object} target call `selector` on this object @param {string} selector the method name to call on `target` @param {...Object} args arguments to pass when calling `selector` on `target`
registerUndo ( target , selector , ... args )
javascript
square/field-kit
src/undo_manager.js
https://github.com/square/field-kit/blob/master/src/undo_manager.js
Apache-2.0
_appendUndo(target, selector, ...args) { this._undos.push({ target: target, selector: selector, args: args }); }
Appends an undo action to the internal stack. @param {Object} target call `selector` on this object @param {string} selector the method name to call on `target` @param {...Object} args arguments to pass when calling `selector` on `target` @private
_appendUndo ( target , selector , ... args )
javascript
square/field-kit
src/undo_manager.js
https://github.com/square/field-kit/blob/master/src/undo_manager.js
Apache-2.0
_appendRedo(target, selector, ...args) { this._redos.push({ target: target, selector: selector, args: args }); }
Appends a redo action to the internal stack. @param {Object} target call `selector` on this object @param {string} selector the method name to call on `target` @param {...Object} args arguments to pass when calling `selector` on `target` @private
_appendRedo ( target , selector , ... args )
javascript
square/field-kit
src/undo_manager.js
https://github.com/square/field-kit/blob/master/src/undo_manager.js
Apache-2.0
undo() { if (!this.canUndo()) { throw new Error('there are no registered undos'); } const data = this._undos.pop(); const target = data.target; const selector = data.selector; const args = data.args; this._isUndoing = true; target[selector].apply(target, args); this._isUndoing = false; }
Performs the top-most undo action on the stack. @throws {Error} Raises an error if there are no available undo actions.
undo ( )
javascript
square/field-kit
src/undo_manager.js
https://github.com/square/field-kit/blob/master/src/undo_manager.js
Apache-2.0
redo() { if (!this.canRedo()) { throw new Error('there are no registered redos'); } const data = this._redos.pop(); const target = data.target; const selector = data.selector; const args = data.args; this._isRedoing = true; target[selector].apply(target, args); this._isRedoing = false; }
Performs the top-most redo action on the stack. @throws {Error} Raises an error if there are no available redo actions.
redo ( )
javascript
square/field-kit
src/undo_manager.js
https://github.com/square/field-kit/blob/master/src/undo_manager.js
Apache-2.0
proxyFor(target) { const proxy = {}; const self = this; function proxyMethod(selector) { return function(...args) { self.registerUndo(target, selector, ...args); }; } getAllPropertyNames(target).forEach(selector => { // don't trigger anything that has a getter if (hasGetter(target, selector)) { return; } // don't try to proxy properties that aren't functions if (typeof target[selector] !== 'function') { return; } // set up a proxy function to register an undo proxy[selector] = proxyMethod(selector); }); return proxy; }
Returns a proxy object based on target that will register undo/redo actions by calling methods on the proxy. @example setSize(size) { this.undoManager.proxyFor(this).setSize(this._size); this._size = size; } @param {Object} target call `selector` on this object @returns {Object}
proxyFor ( target )
javascript
square/field-kit
src/undo_manager.js
https://github.com/square/field-kit/blob/master/src/undo_manager.js
Apache-2.0
format(pan) { return this._formatterForPan(pan).format(pan); }
Will pick the right formatter based on the `pan` and will return the formatted string. @param {string} pan @returns {string} formatted string
format ( pan )
javascript
square/field-kit
src/adaptive_card_formatter.js
https://github.com/square/field-kit/blob/master/src/adaptive_card_formatter.js
Apache-2.0
parse(text, error) { return this.formatter.parse(text, error); }
Will call parse on the formatter. @param {string} text @param {function(string)} error @returns {string} returns value with delimiters removed
parse ( text , error )
javascript
square/field-kit
src/adaptive_card_formatter.js
https://github.com/square/field-kit/blob/master/src/adaptive_card_formatter.js
Apache-2.0
isChangeValid(change, error) { this.formatter = this._formatterForPan(change.proposed.text); return this.formatter.isChangeValid(change, error); }
Determines whether the given change should be allowed and, if so, whether it should be altered. @param {TextFieldStateChange} change @param {function(!string)} error @returns {boolean}
isChangeValid ( change , error )
javascript
square/field-kit
src/adaptive_card_formatter.js
https://github.com/square/field-kit/blob/master/src/adaptive_card_formatter.js
Apache-2.0
_formatterForPan(pan) { if (determineCardType(pan.replace(/[^\d]+/g, '')) === AMEX) { return this.amexCardFormatter; } else { return this.defaultCardFormatter; } }
Decides which formatter to use. @param {string} pan @returns {Formatter} @private
_formatterForPan ( pan )
javascript
square/field-kit
src/adaptive_card_formatter.js
https://github.com/square/field-kit/blob/master/src/adaptive_card_formatter.js
Apache-2.0
hasDelimiterAtIndex(index) { return index === 2; }
@param {number} index @returns {boolean}
hasDelimiterAtIndex ( index )
javascript
square/field-kit
src/expiry_date_formatter.js
https://github.com/square/field-kit/blob/master/src/expiry_date_formatter.js
Apache-2.0
format(value) { if (!value) { return ''; } let {month, year} = value; year = year % 100; return super.format(zpad2(month) + zpad2(year)); }
Formats the given value by adding delimiters where needed. @param {?string} value @returns {string}
format ( value )
javascript
square/field-kit
src/expiry_date_formatter.js
https://github.com/square/field-kit/blob/master/src/expiry_date_formatter.js
Apache-2.0
isChangeValid(change, error) { if (DIGITS_PATTERN.test(change.inserted.text)) { return super.isChangeValid(change, error); } else { return false; } }
Determines whether the given change should be allowed and, if so, whether it should be altered. @param {TextFieldStateChange} change @param {function(string)} error @returns {boolean}
isChangeValid ( change , error )
javascript
square/field-kit
src/social_security_number_formatter.js
https://github.com/square/field-kit/blob/master/src/social_security_number_formatter.js
Apache-2.0
cardType() { return determineCardType(this.value()); }
Gets the card type for the current value. @returns {string} Returns one of 'visa', 'mastercard', 'amex' and 'discover'.
cardType ( )
javascript
square/field-kit
src/card_text_field.js
https://github.com/square/field-kit/blob/master/src/card_text_field.js
Apache-2.0
cardMaskStrategy() { return this._cardMaskStrategy; }
Gets the type of masking this field uses. @returns {CardMaskStrategy}
cardMaskStrategy ( )
javascript
square/field-kit
src/card_text_field.js
https://github.com/square/field-kit/blob/master/src/card_text_field.js
Apache-2.0
setCardMaskStrategy(cardMaskStrategy) { if (cardMaskStrategy !== this._cardMaskStrategy) { this._cardMaskStrategy = cardMaskStrategy; this._syncMask(); } }
Sets the type of masking this field uses. @param {CardMaskStrategy} cardMaskStrategy One of CardMaskStrategy.
setCardMaskStrategy ( cardMaskStrategy )
javascript
square/field-kit
src/card_text_field.js
https://github.com/square/field-kit/blob/master/src/card_text_field.js
Apache-2.0
cardMask() { const text = this.text(); const last4 = text.slice(-4); let toMask = text.slice(0, -4); return toMask.replace(/\d/g, '•') + last4; }
Returns a masked version of the current formatted PAN. Example: @example field.setText('4111 1111 1111 1111'); field.cardMask(); // "•••• •••• •••• 1111" @returns {string} Returns a masked card string.
cardMask ( )
javascript
square/field-kit
src/card_text_field.js
https://github.com/square/field-kit/blob/master/src/card_text_field.js
Apache-2.0
text() { if (this._masked) { return this._unmaskedText; } else { return super.text(); } }
Gets the formatted PAN for this field. @returns {string}
text ( )
javascript
square/field-kit
src/card_text_field.js
https://github.com/square/field-kit/blob/master/src/card_text_field.js
Apache-2.0
setText(text) { if (this._masked) { this._unmaskedText = text; text = this.cardMask(); } super.setText(text); }
Sets the formatted PAN for this field. @param {string} text A formatted PAN.
setText ( text )
javascript
square/field-kit
src/card_text_field.js
https://github.com/square/field-kit/blob/master/src/card_text_field.js
Apache-2.0
textFieldDidEndEditing() { this._editing = false; this._syncMask(); }
Called by our superclass, used to implement card masking. @private
textFieldDidEndEditing ( )
javascript
square/field-kit
src/card_text_field.js
https://github.com/square/field-kit/blob/master/src/card_text_field.js
Apache-2.0
_enableMasking() { if (!this._masked) { this._unmaskedText = this.text(); this._masked = true; this.setText(this._unmaskedText); } }
Enables masking if it is not already enabled. @private
_enableMasking ( )
javascript
square/field-kit
src/card_text_field.js
https://github.com/square/field-kit/blob/master/src/card_text_field.js
Apache-2.0
_disableMasking() { if (this._masked) { this._masked = false; this.setText(this._unmaskedText); this._unmaskedText = null; } }
Disables masking if it is currently enabled. @private
_disableMasking ( )
javascript
square/field-kit
src/card_text_field.js
https://github.com/square/field-kit/blob/master/src/card_text_field.js
Apache-2.0
_syncMask() { if (this.cardMaskStrategy() === CardMaskStrategy.DoneEditing) { if (this._editing) { this._disableMasking(); } else { this._enableMasking(); } } }
Enables or disables masking based on the mask settings. @private
_syncMask ( )
javascript
square/field-kit
src/card_text_field.js
https://github.com/square/field-kit/blob/master/src/card_text_field.js
Apache-2.0
static get CardMaskStrategy() { return CardMaskStrategy; }
Enum for card mask strategies. @readonly @enum {number}
CardMaskStrategy ( )
javascript
square/field-kit
src/card_text_field.js
https://github.com/square/field-kit/blob/master/src/card_text_field.js
Apache-2.0
textDidChange() {}
Called when the user has changed the text of the field. Can be used in subclasses to perform actions suitable for this event. @private
textDidChange ( )
javascript
square/field-kit
src/text_field.js
https://github.com/square/field-kit/blob/master/src/text_field.js
Apache-2.0
textFieldDidEndEditing() {}
Called when the user has in some way declared that they are done editing, such as leaving the field or perhaps pressing enter. Can be used in subclasses to perform actions suitable for this event. @private
textFieldDidEndEditing ( )
javascript
square/field-kit
src/text_field.js
https://github.com/square/field-kit/blob/master/src/text_field.js
Apache-2.0
textFieldDidBeginEditing() {}
Performs actions necessary for beginning editing. @private
textFieldDidBeginEditing ( )
javascript
square/field-kit
src/text_field.js
https://github.com/square/field-kit/blob/master/src/text_field.js
Apache-2.0
_textDidChange() { const delegate = this._delegate; this.textDidChange(); if (delegate && typeof delegate.textDidChange === 'function') { delegate.textDidChange(this); } // manually fire the HTML5 input event this._fireEvent('input'); }
Performs actions necessary for text change. @private
_textDidChange ( )
javascript
square/field-kit
src/text_field.js
https://github.com/square/field-kit/blob/master/src/text_field.js
Apache-2.0
_textFieldDidEndEditing() { const delegate = this._delegate; this.textFieldDidEndEditing(); if (delegate && typeof delegate.textFieldDidEndEditing === 'function') { delegate.textFieldDidEndEditing(this); } // manually fire the HTML5 change event, only when a change has been made since focus if (this._isDirty && (this._valueOnFocus !== this.element.value)) { this._fireEvent('change'); } // reset the dirty property this._isDirty = false; this._valueOnFocus = ''; }
Performs actions necessary for ending editing. @private
_textFieldDidEndEditing ( )
javascript
square/field-kit
src/text_field.js
https://github.com/square/field-kit/blob/master/src/text_field.js
Apache-2.0
delegate() { return this._delegate; }
Gets the current delegate for this text field. @returns {TextFieldDelegate}
delegate ( )
javascript
square/field-kit
src/text_field.js
https://github.com/square/field-kit/blob/master/src/text_field.js
Apache-2.0
setDelegate(delegate) { this._delegate = delegate; }
Sets the current delegate for this text field. @param {TextFieldDelegate} delegate
setDelegate ( delegate )
javascript
square/field-kit
src/text_field.js
https://github.com/square/field-kit/blob/master/src/text_field.js
Apache-2.0
formatter() { if (!this._formatter) { this._formatter = new Formatter(); const maximumLengthString = this.element.getAttribute('maxlength'); if (maximumLengthString !== undefined && maximumLengthString !== null) { this._formatter.maximumLength = parseInt(maximumLengthString, 10); } } return this._formatter; }
Gets the current formatter. Formatters are used to translate between text and value properties of the field. @returns {Formatter}
formatter ( )
javascript
square/field-kit
src/text_field.js
https://github.com/square/field-kit/blob/master/src/text_field.js
Apache-2.0
setFormatter(formatter) { const value = this.value(); this._formatter = formatter; this.setValue(value); }
Sets the current formatter. @param {Formatter} formatter
setFormatter ( formatter )
javascript
square/field-kit
src/text_field.js
https://github.com/square/field-kit/blob/master/src/text_field.js
Apache-2.0
insertNewline() { this._textFieldDidEndEditing(); this._didEndEditingButKeptFocus = true; }
Handles a key event could be trying to end editing.
insertNewline ( )
javascript
square/field-kit
src/text_field.js
https://github.com/square/field-kit/blob/master/src/text_field.js
Apache-2.0
readSelectionFromPasteboard(pasteboard) { let range, text; text = pasteboard.getData('Text'); this.replaceSelection(text); range = this.selectedRange(); range.start += range.length; range.length = 0; this.setSelectedRange(range); }
Replaces the current selection with text from the given pasteboard. @param {DataTransfer} pasteboard
readSelectionFromPasteboard ( pasteboard )
javascript
square/field-kit
src/text_field.js
https://github.com/square/field-kit/blob/master/src/text_field.js
Apache-2.0
rollbackInvalidChanges(callback) { let result = null; let errorType = null; const change = TextFieldStateChange.build(this, () => result = callback()); const error = function(type) { errorType = type; }; if (change.hasChanges()) { const formatter = this.formatter(); if (formatter && typeof formatter.isChangeValid === 'function') { if (!this._isDirty) { this._valueOnFocus = change.current.text || ''; this._isDirty = true; } if (formatter.isChangeValid(change, error)) { change.recomputeDiff(); this.setText(change.proposed.text); this.setSelectedRange(change.proposed.selectedRange); } else { const delegate = this.delegate(); if (delegate) { if (typeof delegate.textFieldDidFailToValidateChange === 'function') { delegate.textFieldDidFailToValidateChange(this, change, errorType); } } this.setText(change.current.text); this.setSelectedRange(change.current.selectedRange); return result; } } if (change.inserted.text.length || change.deleted.text.length) { this.undoManager().proxyFor(this)._applyChangeFromUndoManager(change); this._textDidChange(); } } return result; }
Checks changes after invoking the passed function for validity and rolls them back if the changes turned out to be invalid. @returns {Object} whatever object `callback` returns
rollbackInvalidChanges ( callback )
javascript
square/field-kit
src/text_field.js
https://github.com/square/field-kit/blob/master/src/text_field.js
Apache-2.0