code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function xorBlock(words, offset, blockSize) { var block; // Shortcut var iv = this._iv; // Choose mixing block if (iv) { block = iv; // Remove IV for subsequent blocks this._iv = undefined; } else { block = this._prevBlock; } // XOR blocks for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } }
Processes the data block at offset. @param {Array} words The data words to operate on. @param {number} offset The offset where the block starts. @example mode.processBlock(data.words, offset);
xorBlock
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/cipher-core.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/cipher-core.js
MIT
function swapEndian(word) { return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); }
Converts a UTF-16 LE string to a word array. @param {string} utf16Str The UTF-16 LE string. @return {WordArray} The word array. @static @example var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
swapEndian
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/crypto-js.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/crypto-js.js
MIT
function parseLoop(base64Str, base64StrLength, reverseMap) { var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); var bitsCombined = bits1 | bits2; words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }
Converts a Base64 string to a word array. @param {string} base64Str The Base64 string. @return {WordArray} The word array. @static @example var wordArray = CryptoJS.enc.Base64.parse(base64String);
parseLoop
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/crypto-js.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/crypto-js.js
MIT
function parseLoop(base64Str, base64StrLength, reverseMap) { var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); var bitsCombined = bits1 | bits2; words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }
Converts a Base64url string to a word array. @param {string} base64Str The Base64url string. @param {boolean} urlSafe Whether to use url safe @return {WordArray} The word array. @static @example var wordArray = CryptoJS.enc.Base64url.parse(base64String);
parseLoop
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/crypto-js.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/crypto-js.js
MIT
function isPrime(n) { var sqrtN = Math.sqrt(n); for (var factor = 2; factor <= sqrtN; factor++) { if (!(n % factor)) { return false; } } return true; }
Shortcut function to the HMAC's object interface. @param {WordArray|string} message The message to hash. @param {WordArray|string} key The secret key. @return {WordArray} The HMAC. @static @example var hmac = CryptoJS.HmacSHA1(message, key);
isPrime
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/crypto-js.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/crypto-js.js
MIT
function getFractionalBits(n) { return ((n - (n | 0)) * 0x100000000) | 0; }
Shortcut function to the HMAC's object interface. @param {WordArray|string} message The message to hash. @param {WordArray|string} key The secret key. @return {WordArray} The HMAC. @static @example var hmac = CryptoJS.HmacSHA1(message, key);
getFractionalBits
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/crypto-js.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/crypto-js.js
MIT
function X64Word_create() { return X64Word.create.apply(X64Word, arguments); }
Shortcut function to the HMAC's object interface. @param {WordArray|string} message The message to hash. @param {WordArray|string} key The secret key. @return {WordArray} The HMAC. @static @example var hmac = CryptoJS.HmacSHA224(message, key);
X64Word_create
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/crypto-js.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/crypto-js.js
MIT
function selectCipherStrategy(key) { if (typeof key == 'string') { return PasswordBasedCipher; } else { return SerializableCipher; } }
Creates shortcut functions to a cipher's object interface. @param {Cipher} cipher The cipher to create a helper for. @return {Object} An object with encrypt and decrypt shortcut functions. @static @example var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
selectCipherStrategy
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/crypto-js.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/crypto-js.js
MIT
function xorBlock(words, offset, blockSize) { var block; // Shortcut var iv = this._iv; // Choose mixing block if (iv) { block = iv; // Remove IV for subsequent blocks this._iv = undefined; } else { block = this._prevBlock; } // XOR blocks for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } }
Processes the data block at offset. @param {Array} words The data words to operate on. @param {number} offset The offset where the block starts. @example mode.processBlock(data.words, offset);
xorBlock
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/crypto-js.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/crypto-js.js
MIT
function incWord(word) { if (((word >> 24) & 0xff) === 0xff) { //overflow var b1 = (word >> 16)&0xff; var b2 = (word >> 8)&0xff; var b3 = word & 0xff; if (b1 === 0xff) // overflow b1 { b1 = 0; if (b2 === 0xff) { b2 = 0; if (b3 === 0xff) { b3 = 0; } else { ++b3; } } else { ++b2; } } else { ++b1; } word = 0; word += (b1 << 16); word += (b2 << 8); word += b3; } else { word += (0x01 << 24); } return word; }
@preserve Counter block mode compatible with Dr Brian Gladman fileenc.c derived from CryptoJS.mode.CTR Jan Hruby jhruby.web@gmail.com
incWord
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/crypto-js.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/crypto-js.js
MIT
function incCounter(counter) { if ((counter[0] = incWord(counter[0])) === 0) { // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 counter[1] = incWord(counter[1]); } return counter; }
@preserve Counter block mode compatible with Dr Brian Gladman fileenc.c derived from CryptoJS.mode.CTR Jan Hruby jhruby.web@gmail.com
incCounter
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/crypto-js.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/crypto-js.js
MIT
function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; }
Rabbit stream cipher algorithm. This is a legacy version that neglected to convert the key to little-endian. This error doesn't affect the cipher's security, but it does affect its compatibility with other implementations.
nextState
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/crypto-js.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/crypto-js.js
MIT
function parseLoop(base64Str, base64StrLength, reverseMap) { var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); var bitsCombined = bits1 | bits2; words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }
Converts a Base64 string to a word array. @param {string} base64Str The Base64 string. @return {WordArray} The word array. @static @example var wordArray = CryptoJS.enc.Base64.parse(base64String);
parseLoop
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/enc-base64.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/enc-base64.js
MIT
function parseLoop(base64Str, base64StrLength, reverseMap) { var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); var bitsCombined = bits1 | bits2; words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }
Converts a Base64url string to a word array. @param {string} base64Str The Base64url string. @param {boolean} urlSafe Whether to use url safe @return {WordArray} The word array. @static @example var wordArray = CryptoJS.enc.Base64url.parse(base64String);
parseLoop
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/enc-base64url.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/enc-base64url.js
MIT
function swapEndian(word) { return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); }
Converts a UTF-16 LE string to a word array. @param {string} utf16Str The UTF-16 LE string. @return {WordArray} The word array. @static @example var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
swapEndian
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/enc-utf16.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/enc-utf16.js
MIT
function incWord(word) { if (((word >> 24) & 0xff) === 0xff) { //overflow var b1 = (word >> 16)&0xff; var b2 = (word >> 8)&0xff; var b3 = word & 0xff; if (b1 === 0xff) // overflow b1 { b1 = 0; if (b2 === 0xff) { b2 = 0; if (b3 === 0xff) { b3 = 0; } else { ++b3; } } else { ++b2; } } else { ++b1; } word = 0; word += (b1 << 16); word += (b2 << 8); word += b3; } else { word += (0x01 << 24); } return word; }
@preserve Counter block mode compatible with Dr Brian Gladman fileenc.c derived from CryptoJS.mode.CTR Jan Hruby jhruby.web@gmail.com
incWord
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/mode-ctr-gladman.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/mode-ctr-gladman.js
MIT
function incCounter(counter) { if ((counter[0] = incWord(counter[0])) === 0) { // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 counter[1] = incWord(counter[1]); } return counter; }
@preserve Counter block mode compatible with Dr Brian Gladman fileenc.c derived from CryptoJS.mode.CTR Jan Hruby jhruby.web@gmail.com
incCounter
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/mode-ctr-gladman.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/mode-ctr-gladman.js
MIT
function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; }
Rabbit stream cipher algorithm. This is a legacy version that neglected to convert the key to little-endian. This error doesn't affect the cipher's security, but it does affect its compatibility with other implementations.
nextState
javascript
tangyoha/telegram_media_downloader
module/static/aes/crypto-js-master/rabbit-legacy.js
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/rabbit-legacy.js
MIT
function getFileName(lang, i, isBeta, chapter) { if (i === 0 && lang === "en") { return "index.html"; } let fileName = `${pad(i)}_${lang}.html`; if (chapter !== undefined && chapter !== null) { fileName = `chapter_${chapter}_${lang}.html`; } return fileName; }
@param {string} lang @param {number} i @param {boolean} isBeta currently unused @param {string} chapter @returns {string}
getFileName
javascript
richardanaya/tour_of_rust
generate.js
https://github.com/richardanaya/tour_of_rust/blob/master/generate.js
MIT
function getWord(words, lang, w) { if (words[lang][w]) { return words[lang][w]; } return words.en[w]; }
@param {string[]} words @param {string} lang @param {string} w @returns {string}
getWord
javascript
richardanaya/tour_of_rust
generate.js
https://github.com/richardanaya/tour_of_rust/blob/master/generate.js
MIT
getHead = (words, lang) => { let rtl_langs = ["ar"]; let lang_dir = rtl_langs.includes(lang) ? "rtl" : "ltr"; return `<!DOCTYPE html> <html lang="${lang}" dir="${lang_dir}"> <head> <title>${getWord( words, lang, "tor" )} - Let's go on an adventure!</title> <meta charset="UTF-8"> <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> <meta content="utf-8" http-equiv="encoding"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="keywords" content="Rust, Programming, Learning"> <meta name="description" content="Welcome to the Tour of Rust. This is meant to be a step by step guide through the features of the Rust programming language"> <meta name="theme-color" content="#ff6801"/> <link rel="stylesheet" href="tour.css"> <link rel="preload" href="https://fonts.gstatic.com/s/neuton/v12/UMBQrPtMoH62xUZKdK0vfQr4LLkw6A.woff2" as="font" /> <link rel="preload" href="https://fonts.gstatic.com/s/neuton/v12/UMBTrPtMoH62xUZCz4g6UCj1Bg.woff2" as="font" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Neuton:ital,wght@0,400;0,700;1,400&display=swap" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Serif:wght@400;700&display=swap" /> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"> <link rel="manifest" href="./site.webmanifest"> <script src="./tour.js" defer></script> </head>`; }
@param {string[]} words @param {string} lang @returns {string}
getHead
javascript
richardanaya/tour_of_rust
generate.js
https://github.com/richardanaya/tour_of_rust/blob/master/generate.js
MIT
getHead = (words, lang) => { let rtl_langs = ["ar"]; let lang_dir = rtl_langs.includes(lang) ? "rtl" : "ltr"; return `<!DOCTYPE html> <html lang="${lang}" dir="${lang_dir}"> <head> <title>${getWord( words, lang, "tor" )} - Let's go on an adventure!</title> <meta charset="UTF-8"> <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> <meta content="utf-8" http-equiv="encoding"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="keywords" content="Rust, Programming, Learning"> <meta name="description" content="Welcome to the Tour of Rust. This is meant to be a step by step guide through the features of the Rust programming language"> <meta name="theme-color" content="#ff6801"/> <link rel="stylesheet" href="tour.css"> <link rel="preload" href="https://fonts.gstatic.com/s/neuton/v12/UMBQrPtMoH62xUZKdK0vfQr4LLkw6A.woff2" as="font" /> <link rel="preload" href="https://fonts.gstatic.com/s/neuton/v12/UMBTrPtMoH62xUZCz4g6UCj1Bg.woff2" as="font" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Neuton:ital,wght@0,400;0,700;1,400&display=swap" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Serif:wght@400;700&display=swap" /> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"> <link rel="manifest" href="./site.webmanifest"> <script src="./tour.js" defer></script> </head>`; }
@param {string[]} words @param {string} lang @returns {string}
getHead
javascript
richardanaya/tour_of_rust
generate.js
https://github.com/richardanaya/tour_of_rust/blob/master/generate.js
MIT
lazyLoad(args) { lazyLoadImage(args.target, null, () => { //callback }) }
Lazy load the related image. @see ../utils/image.js It is recommended to wrap your `<img>` into an element with the CSS class name `.c-lazy`. The CSS class name modifier `.-lazy-loaded` will be applied on both the image and the parent wrapper. ```html <div class="c-lazy o-ratio u-4:3"> <img data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/640/480?v=1" alt="" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /> </div> ``` @param {LocomotiveScroll} args - The Locomotive Scroll instance.
lazyLoad
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/modules/Scroll.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/modules/Scroll.js
MIT
scrollTo(params) { let { target, ...options } = params options = Object.assign({ // Defaults duration: 1, }, options) this.scroll?.scrollTo(target, options) }
Lazy load the related image. @see ../utils/image.js It is recommended to wrap your `<img>` into an element with the CSS class name `.c-lazy`. The CSS class name modifier `.-lazy-loaded` will be applied on both the image and the parent wrapper. ```html <div class="c-lazy o-ratio u-4:3"> <img data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/640/480?v=1" alt="" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /> </div> ``` @param {LocomotiveScroll} args - The Locomotive Scroll instance.
scrollTo
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/modules/Scroll.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/modules/Scroll.js
MIT
function conformsToReference(font, criterion) { for (const [ key, value ] of Object.entries(criterion)) { switch (key) { case 'family': { if (trim(font[key]) !== value) { return false; } break; } case 'weight': { /** * Note concerning font weights: * Loose equality (`==`) is used to compare numeric weights, * a number (`400`) and a numeric string (`"400"`). * Comparison between numeric and keyword values is neglected. * * @link https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#common_weight_name_mapping */ if (font[key] != value) { return false; } break; } default: { if (font[key] !== value) { return false; } break; } } } return true; }
Determines if the given font matches the given `FontFaceReference`. @param {FontFace} font - The font to inspect. @param {FontFaceReference} criterion - The object of property values to match. @returns {boolean}
conformsToReference
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/fonts.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/fonts.js
MIT
function conformsToShorthand(font, criterion) { const family = trim(font.family); if (trim(family) === criterion) { return true; } if ( criterion.endsWith(trim(family)) && ( criterion.match(font.weight) || criterion.match(font.style) ) ) { return true; } return true; }
Determines if the given font matches the given font shorthand. @param {FontFace} font - The font to inspect. @param {string} criterion - The font shorthand to match. @returns {boolean}
conformsToShorthand
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/fonts.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/fonts.js
MIT
function conformsToAnyReference(font, criteria) { for (const criterion of criteria) { if (conformsToReference(font, criterion)) { return true; } } return false; }
Determines if the given font matches any of the given criteria. @param {FontFace} font - The font to inspect. @param {FontFaceReference[]} criteria - A list of objects with property values to match. @returns {boolean}
conformsToAnyReference
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/fonts.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/fonts.js
MIT
function findManyByReference(search) { const found = []; for (const font of document.fonts) { if (conformsToReference(font, search)) { found.push(font); } } return found; }
Returns an iterator of all `FontFace` from `document.fonts` that satisfy the provided `FontFaceReference`. @param {FontFaceReference} font @returns {FontFace[]}
findManyByReference
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/fonts.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/fonts.js
MIT
function findManyByShorthand(search) { const found = []; for (const font of document.fonts) { if (conformsToShorthand(font, search)) { found.push(font); } } return found; }
Returns an iterator of all `FontFace` from `document.fonts` that satisfy the provided font shorthand. @param {string} font @returns {FontFace[]}
findManyByShorthand
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/fonts.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/fonts.js
MIT
function findOneByReference(search) { for (const font of document.fonts) { if (conformsToReference(font, criterion)) { return font; } } return null; }
Returns the first `FontFace` from `document.fonts` that satisfies the provided `FontFaceReference`. @param {FontFaceReference} font @returns {?FontFace}
findOneByReference
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/fonts.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/fonts.js
MIT
function findOneByShorthand(search) { for (const font of document.fonts) { if (conformsToShorthand(font, search)) { return font; } } return null; }
Returns the first `FontFace` from `document.fonts` that satisfies the provided font shorthand. Examples: - "Roboto" - "italic bold 16px Roboto" @param {string} font @returns {?FontFace}
findOneByShorthand
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/fonts.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/fonts.js
MIT
function getAny(search) { if (search) { switch (typeof search) { case 'string': return findOneByShorthand(search); case 'object': return findOneByReference(search); } } throw new TypeError( 'Expected font query to be font shorthand or font reference' ); }
Returns a `FontFace` from `document.fonts` that satisfies the provided query. @param {FontFaceReference|string} font - Either: - a `FontFaceReference` object - a font family name - a font specification, for example "italic bold 16px Roboto" @returns {?FontFace} @throws {TypeError}
getAny
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/fonts.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/fonts.js
MIT
function getMany(queries) { if (!Array.isArray(queries)) { queries = [ queries ]; } const found = new Set(); queries.forEach((search) => { if (search) { switch (typeof search) { case 'string': found.add(...findManyByShorthand(search)); return; case 'object': found.add(...findManyByReference(search)); return; } } throw new TypeError( 'Expected font query to be font shorthand or font reference' ); }) return [ ...found ]; }
Returns an iterator of all `FontFace` from `document.fonts` that satisfy the provided queries. @param {FontFaceReference|string|(FontFaceReference|string)[]} queries @returns {FontFace[]} @throws {TypeError}
getMany
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/fonts.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/fonts.js
MIT
function hasAny(search) { if (search instanceof FontFace) { return document.fonts.has(search); } return getAny(search) != null; }
Determines if a font face is registered. @param {FontFace|FontFaceReference|string} search - Either: - a `FontFace` instance - a `FontFaceReference` object - a font family name - a font specification, for example "italic bold 16px Roboto" @returns {boolean}
hasAny
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/fonts.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/fonts.js
MIT
async function loadFonts(fontsToLoad, debug = false) { if ((fontsToLoad.size ?? fontsToLoad.length) === 0) { throw new TypeError( 'Expected at least one font' ); } return await loadFontsWithAPI([ ...fontsToLoad ], debug); }
Eagerly load fonts. Most user agents only fetch and load fonts when they are first needed ("lazy loaded"), which can result in a perceptible delay. This function will "eager load" the fonts. @param {(FontFace|FontFaceReference)[]} fontsToLoad - List of fonts to load. @param {boolean} [debug] - If TRUE, log details to the console. @returns {Promise}
loadFonts
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/fonts.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/fonts.js
MIT
async function loadFontFaceWithAPI(font) { return await (font.status === 'unloaded' ? font.load() : font.loaded ).then((font) => font, (err) => font) }
Eagerly load a font using `FontFaceSet` API. @param {FontFace} font @returns {Promise}
loadFontFaceWithAPI
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/fonts.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/fonts.js
MIT
async function loadFontsWithAPI(fontsToLoad, debug = false) { debug && console.group('[loadFonts:API]', fontsToLoad.length, '/', document.fonts.size); const fontsToBeLoaded = []; for (const fontToLoad of fontsToLoad) { if (fontToLoad instanceof FontFace) { if (!document.fonts.has(fontToLoad)) { document.fonts.add(fontToLoad); } fontsToBeLoaded.push( loadFontFaceWithAPI(fontToLoad) ); } else { fontsToBeLoaded.push( ...getMany(fontToLoad).map((font) => loadFontFaceWithAPI(font)) ); } } debug && console.groupEnd(); return await Promise.all(fontsToBeLoaded); }
Eagerly load fonts using `FontFaceSet` API. @param {FontFaceReference[]} fontsToLoad @param {boolean} [debug] @returns {Promise}
loadFontsWithAPI
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/fonts.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/fonts.js
MIT
function trim(value) { return value.replace(/['"]+/g, ''); }
Removes quotes from the the string. When a `@font-face` is declared, the font family is sometimes defined in quotes which end up included in the `FontFace` instance. @param {string} value @returns {string}
trim
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/fonts.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/fonts.js
MIT
async function whenReady(queries) { const fonts = getMany(queries); return await Promise.all(fonts.map((font) => font.loaded)); }
Returns a Promise that resolves with the specified fonts when they are done loading or failed. @param {FontFaceReference|string|(FontFaceReference|string)[]} queries @returns {Promise}
whenReady
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/fonts.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/fonts.js
MIT
function setGridHelperStyles($container, gutterCssVar, marginCssVar) { const elStyles = $container.style; elStyles.zIndex = '10000'; elStyles.position = 'fixed'; elStyles.top = '0'; elStyles.left = '0'; elStyles.display = 'flex'; elStyles.width = '100%'; elStyles.height = '100%'; elStyles.columnGap = `var(${gutterCssVar}, 0)`; elStyles.paddingLeft = `var(${marginCssVar}, 0)`; elStyles.paddingRight = `var(${marginCssVar}, 0)`; elStyles.pointerEvents = 'none'; elStyles.visibility = 'hidden'; }
Set grid container styles @param {HTMLElement} $container - DOM Element that contains a list of generated columns @param {string} gutterCssVar - CSS variable used to define grid gutters. @param {string} marginCssVar - CSS variable used to define grid margins.
setGridHelperStyles
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/grid-helper.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/grid-helper.js
MIT
function setGridHelperColumns($container, rgbaColor) { // Clear columns $container.innerHTML = ''; // Loop through columns const columns = Number( window.getComputedStyle($container).getPropertyValue('--grid-columns') ); let $col; for (var i = 0; i < columns; i++) { $col = document.createElement('div'); $col.style.flex = '1 1 0'; $col.style.backgroundColor = rgbaColor; $container.appendChild($col); } }
Set grid columns @param {HTMLElement} $container - DOM Element that will contain a list of generated columns @param {string} rgbaColor - RGBA color to stylize the generated columns
setGridHelperColumns
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/grid-helper.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/grid-helper.js
MIT
function setGridEvents($container, rgbaColor) { // Handle resize window.addEventListener( 'resize', setGridHelperColumns($container, rgbaColor) ); // Toggle grid let ctrlDown = false; let isActive = false; document.addEventListener('keydown', (e) => { if (e.key == 'Control') { ctrlDown = true; } else { if (ctrlDown && e.key == 'g') { if (isActive) { $container.style.visibility = 'hidden'; } else { $container.style.visibility = 'visible'; } isActive = !isActive; } } }); document.addEventListener('keyup', (e) => { if (e.key == 'Control') { ctrlDown = false; } }); }
Set grid events Resize to rebuild columns Keydown/Keyup to toggle the grid display @param {HTMLElement} $container - DOM Element that contains a list of generated columns @param {string} rgbaColor - RGBA color to stylize the generated columns
setGridEvents
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/grid-helper.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/grid-helper.js
MIT
escapeHtml = str => str.replace(/[&<>'"]/g, tag => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#39;', '"': '&quot;' }[tag]))
Escape HTML string @param {string} str - string to escape @return {string} escaped string
escapeHtml
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/html.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/html.js
MIT
escapeHtml = str => str.replace(/[&<>'"]/g, tag => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#39;', '"': '&quot;' }[tag]))
Escape HTML string @param {string} str - string to escape @return {string} escaped string
escapeHtml
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/html.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/html.js
MIT
unescapeHtml = str => str.replace('&amp;', '&') .replace('&lt;', '<') .replace('&gt;', '>') .replace('&#39;', "'") .replace('&quot;', '"')
Unescape HTML string @param {string} str - string to unescape @return {string} unescaped string
unescapeHtml
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/html.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/html.js
MIT
unescapeHtml = str => str.replace('&amp;', '&') .replace('&lt;', '<') .replace('&gt;', '>') .replace('&#39;', "'") .replace('&quot;', '"')
Unescape HTML string @param {string} str - string to unescape @return {string} unescaped string
unescapeHtml
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/html.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/html.js
MIT
getNodeData = node => { // All attributes const attributes = node.attributes // Regex Pattern const pattern = /^data\-(.+)$/ // Output const data = {} for (let i in attributes) { if (!attributes[i]) { continue } // Attributes name (ex: data-module) let name = attributes[i].name // This happens. if (!name) { continue } let match = name.match(pattern) if (!match) { continue } // If this throws an error, you have some // serious problems in your HTML. data[match[1]] = getData(node.getAttribute(name)) } return data; }
Get element data attributes @param {HTMLElement} node - node element @return {array} node data
getNodeData
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/html.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/html.js
MIT
getNodeData = node => { // All attributes const attributes = node.attributes // Regex Pattern const pattern = /^data\-(.+)$/ // Output const data = {} for (let i in attributes) { if (!attributes[i]) { continue } // Attributes name (ex: data-module) let name = attributes[i].name // This happens. if (!name) { continue } let match = name.match(pattern) if (!match) { continue } // If this throws an error, you have some // serious problems in your HTML. data[match[1]] = getData(node.getAttribute(name)) } return data; }
Get element data attributes @param {HTMLElement} node - node element @return {array} node data
getNodeData
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/html.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/html.js
MIT
getData = data => { if (data === 'true') { return true } if (data === 'false') { return false } if (data === 'null') { return null } // Only convert to a number if it doesn't change the string if (data === +data+'') { return +data } if (rbrace.test(data)) { return JSON.parse(data) } return data }
Parse value to data type. @link https://github.com/jquery/jquery/blob/3.1.1/src/data.js @param {string} data - value to convert @return {mixed} value in its natural data type
getData
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/html.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/html.js
MIT
getData = data => { if (data === 'true') { return true } if (data === 'false') { return false } if (data === 'null') { return null } // Only convert to a number if it doesn't change the string if (data === +data+'') { return +data } if (rbrace.test(data)) { return JSON.parse(data) } return data }
Parse value to data type. @link https://github.com/jquery/jquery/blob/3.1.1/src/data.js @param {string} data - value to convert @return {mixed} value in its natural data type
getData
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/html.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/html.js
MIT
getParents = $el => { // Set up a parent array let parents = [] // Push each parent element to the array for (; $el && $el !== document; $el = $el.parentNode) { parents.push($el) } // Return our parent array return parents }
Returns an array containing all the parent nodes of the given node @param {HTMLElement} $el - DOM Element @return {array} parent nodes
getParents
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/html.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/html.js
MIT
getParents = $el => { // Set up a parent array let parents = [] // Push each parent element to the array for (; $el && $el !== document; $el = $el.parentNode) { parents.push($el) } // Return our parent array return parents }
Returns an array containing all the parent nodes of the given node @param {HTMLElement} $el - DOM Element @return {array} parent nodes
getParents
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/html.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/html.js
MIT
getImageMetadata = $img => ({ url: $img.src, width: $img.naturalWidth, height: $img.naturalHeight, ratio: $img.naturalWidth / $img.naturalHeight, })
Get an image meta data @param {HTMLImageElement} $img - The image element. @return {object} The given image meta data
getImageMetadata
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/image.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/image.js
MIT
getImageMetadata = $img => ({ url: $img.src, width: $img.naturalWidth, height: $img.naturalHeight, ratio: $img.naturalWidth / $img.naturalHeight, })
Get an image meta data @param {HTMLImageElement} $img - The image element. @return {object} The given image meta data
getImageMetadata
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/image.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/image.js
MIT
loadImage = (url, options = {}) => { return new Promise((resolve, reject) => { const $img = new Image() if (options.crossOrigin) { $img.crossOrigin = options.crossOrigin } const loadCallback = () => { resolve({ element: $img, ...getImageMetadata($img), }) } if($img.decode) { $img.src = url $img.decode().then(loadCallback).catch(e => { reject(e) }) } else { $img.onload = loadCallback $img.onerror = (e) => { reject(e) } $img.src = url } }) }
Load the given image. @param {string} url - The URI to lazy load into $el. @param {object} options - An object of options @return {void}
loadImage
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/image.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/image.js
MIT
loadImage = (url, options = {}) => { return new Promise((resolve, reject) => { const $img = new Image() if (options.crossOrigin) { $img.crossOrigin = options.crossOrigin } const loadCallback = () => { resolve({ element: $img, ...getImageMetadata($img), }) } if($img.decode) { $img.src = url $img.decode().then(loadCallback).catch(e => { reject(e) }) } else { $img.onload = loadCallback $img.onerror = (e) => { reject(e) } $img.src = url } }) }
Load the given image. @param {string} url - The URI to lazy load into $el. @param {object} options - An object of options @return {void}
loadImage
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/image.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/image.js
MIT
loadCallback = () => { resolve({ element: $img, ...getImageMetadata($img), }) }
Load the given image. @param {string} url - The URI to lazy load into $el. @param {object} options - An object of options @return {void}
loadCallback
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/image.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/image.js
MIT
loadCallback = () => { resolve({ element: $img, ...getImageMetadata($img), }) }
Load the given image. @param {string} url - The URI to lazy load into $el. @param {object} options - An object of options @return {void}
loadCallback
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/image.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/image.js
MIT
lazyLoadImage = async ($el, url, callback) => { let src = url ? url : $el.dataset.src let loadedImage = LAZY_LOADED_IMAGES.find(image => image.url === src) if (!loadedImage) { loadedImage = await loadImage(src) if (!loadedImage.url) { return } LAZY_LOADED_IMAGES.push(loadedImage) } if($el.src === src) { return } if ($el.tagName === 'IMG') { $el.src = loadedImage.url } else { $el.style.backgroundImage = `url(${loadedImage.url})` } requestAnimationFrame(() => { let lazyParent = $el.closest(`.${CSS_CLASS.LAZY_CONTAINER}`) if(lazyParent) { lazyParent.classList.add(CSS_CLASS.LAZY_LOADED) lazyParent.style.backgroundImage = '' } $el.classList.add(CSS_CLASS.LAZY_LOADED) callback?.() }) }
Lazy load the given image. @param {HTMLImageElement} $el - The image element. @param {?string} url - The URI to lazy load into $el. If falsey, the value of the `data-src` attribute on $el will be used as the URI. @param {?function} callback - A function to call when the image is loaded. @return {void}
lazyLoadImage
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/image.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/image.js
MIT
lazyLoadImage = async ($el, url, callback) => { let src = url ? url : $el.dataset.src let loadedImage = LAZY_LOADED_IMAGES.find(image => image.url === src) if (!loadedImage) { loadedImage = await loadImage(src) if (!loadedImage.url) { return } LAZY_LOADED_IMAGES.push(loadedImage) } if($el.src === src) { return } if ($el.tagName === 'IMG') { $el.src = loadedImage.url } else { $el.style.backgroundImage = `url(${loadedImage.url})` } requestAnimationFrame(() => { let lazyParent = $el.closest(`.${CSS_CLASS.LAZY_CONTAINER}`) if(lazyParent) { lazyParent.classList.add(CSS_CLASS.LAZY_LOADED) lazyParent.style.backgroundImage = '' } $el.classList.add(CSS_CLASS.LAZY_LOADED) callback?.() }) }
Lazy load the given image. @param {HTMLImageElement} $el - The image element. @param {?string} url - The URI to lazy load into $el. If falsey, the value of the `data-src` attribute on $el will be used as the URI. @param {?function} callback - A function to call when the image is loaded. @return {void}
lazyLoadImage
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/image.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/image.js
MIT
roundNumber = (number, precision = 2) => { return Number.parseFloat(number.toPrecision(precision)); }
Round number to the specified precision. This function is necessary because `Number.prototype.toPrecision()` and `Number.prototype.toFixed()` @param {number} number - The floating point number to round. @param {number} [precision] - The number of digits to appear after the decimal point. @return {number} The rounded number.
roundNumber
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/maths.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/maths.js
MIT
roundNumber = (number, precision = 2) => { return Number.parseFloat(number.toPrecision(precision)); }
Round number to the specified precision. This function is necessary because `Number.prototype.toPrecision()` and `Number.prototype.toFixed()` @param {number} number - The floating point number to round. @param {number} [precision] - The number of digits to appear after the decimal point. @return {number} The rounded number.
roundNumber
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/maths.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/maths.js
MIT
debounce = (callback, delay, immediate = false) => { let timeout = null return (...args) => { clearTimeout(timeout) const later = () => { timeout = null if (!immediate) { callback(...args) } } if (immediate && !timeout) { callback(...args) } timeout = setTimeout(later, delay) } }
Creates a debounced function. A debounced function delays invoking `callback` until after `delay` milliseconds have elapsed since the last time the debounced function was invoked. Useful for behaviour that should only happen _before_ or _after_ an event has stopped occurring. @template {function} T @param {T} callback - The function to debounce. @param {number} delay - The number of milliseconds to wait. @param {boolean} [immediate] - If `true`, `callback` is invoked before `delay`. If `false`, `callback` is invoked after `delay`. @return {function<T>} The new debounced function.
debounce
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/tickers.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/tickers.js
MIT
debounce = (callback, delay, immediate = false) => { let timeout = null return (...args) => { clearTimeout(timeout) const later = () => { timeout = null if (!immediate) { callback(...args) } } if (immediate && !timeout) { callback(...args) } timeout = setTimeout(later, delay) } }
Creates a debounced function. A debounced function delays invoking `callback` until after `delay` milliseconds have elapsed since the last time the debounced function was invoked. Useful for behaviour that should only happen _before_ or _after_ an event has stopped occurring. @template {function} T @param {T} callback - The function to debounce. @param {number} delay - The number of milliseconds to wait. @param {boolean} [immediate] - If `true`, `callback` is invoked before `delay`. If `false`, `callback` is invoked after `delay`. @return {function<T>} The new debounced function.
debounce
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/tickers.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/tickers.js
MIT
later = () => { timeout = null if (!immediate) { callback(...args) } }
Creates a debounced function. A debounced function delays invoking `callback` until after `delay` milliseconds have elapsed since the last time the debounced function was invoked. Useful for behaviour that should only happen _before_ or _after_ an event has stopped occurring. @template {function} T @param {T} callback - The function to debounce. @param {number} delay - The number of milliseconds to wait. @param {boolean} [immediate] - If `true`, `callback` is invoked before `delay`. If `false`, `callback` is invoked after `delay`. @return {function<T>} The new debounced function.
later
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/tickers.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/tickers.js
MIT
later = () => { timeout = null if (!immediate) { callback(...args) } }
Creates a debounced function. A debounced function delays invoking `callback` until after `delay` milliseconds have elapsed since the last time the debounced function was invoked. Useful for behaviour that should only happen _before_ or _after_ an event has stopped occurring. @template {function} T @param {T} callback - The function to debounce. @param {number} delay - The number of milliseconds to wait. @param {boolean} [immediate] - If `true`, `callback` is invoked before `delay`. If `false`, `callback` is invoked after `delay`. @return {function<T>} The new debounced function.
later
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/tickers.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/tickers.js
MIT
getTranslate = $el => { if(!window.getComputedStyle) { return } let translate const style = getComputedStyle($el) const transform = style.msTransform || style.webkitTransform || style.MozTransform || style.OTransform || style.transform const matrix3D = transform.match(/^matrix3d\((.+)\)$/) if(matrix3D) { translate = parseFloat(matrix3D[1].split(', ')[13]) } else { const matrix = transform.match(/^matrix\((.+)\)$/) translate = { x: matrix ? parseFloat(matrix[1].split(', ')[4]) : 0 y: matrix ? parseFloat(matrix[1].split(', ')[5]) : 0 } } return translate }
Get translate function @param {HTMLElement} $el - DOM Element @return {number|object} translate value
getTranslate
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/transform.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/transform.js
MIT
getTranslate = $el => { if(!window.getComputedStyle) { return } let translate const style = getComputedStyle($el) const transform = style.msTransform || style.webkitTransform || style.MozTransform || style.OTransform || style.transform const matrix3D = transform.match(/^matrix3d\((.+)\)$/) if(matrix3D) { translate = parseFloat(matrix3D[1].split(', ')[13]) } else { const matrix = transform.match(/^matrix\((.+)\)$/) translate = { x: matrix ? parseFloat(matrix[1].split(', ')[4]) : 0 y: matrix ? parseFloat(matrix[1].split(', ')[5]) : 0 } } return translate }
Get translate function @param {HTMLElement} $el - DOM Element @return {number|object} translate value
getTranslate
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/transform.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/transform.js
MIT
get isEnabled() { return isVisibilityChangeObserved; }
Checks if the "visibilitychange" event listener has been registered. @return {boolean} Returns `false` if the event listener is not registered, otherwise returns `true`.
isEnabled
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/visibility.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/visibility.js
MIT
disableCustomEvents() { if (isVisibilityChangeObserved) { isVisibilityChangeObserved = false; document.removeEventListener('visibilitychange', handleCustomVisibilityChange); return true; } return false; }
Removes the "visibilitychange" event listener. @return {boolean} Returns `false` if the event listener was already unregistered, otherwise returns `true`.
disableCustomEvents
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/visibility.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/visibility.js
MIT
enableCustomEvents() { if (!isVisibilityChangeObserved) { isVisibilityChangeObserved = true; document.addEventListener('visibilitychange', handleCustomVisibilityChange); return true; } return false; }
Registers the "visibilitychange" event listener. @return {boolean} Returns `false` if the event listener was already registered, otherwise returns `true`.
enableCustomEvents
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/visibility.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/visibility.js
MIT
function handleCustomVisibilityChange(event) { document.dispatchEvent(new CustomEvent(`visibility${document.visibilityState}`, { detail: { cause: event } })); }
Dispatches a custom visibility event at the document derived from the value of {@see document.visibilityState}. @listens document#visibilitychange @fires PageVisibility#visibilityhidden @fires PageVisibility#visibilityvisible @param {Event} event @return {void}
handleCustomVisibilityChange
javascript
locomotivemtl/locomotive-boilerplate
assets/scripts/utils/visibility.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/assets/scripts/utils/visibility.js
MIT
function configureServer(server, { paths, tasks }) { const views = createViewsArray(paths.views); // Reload on any changes to views or processed files server.watch( [ ...views, join(paths.scripts.dest, '*.js'), join(paths.styles.dest, '*.css'), join(paths.svgs.dest, '*.svg'), ] ).on('change', server.reload); // Watch source scripts server.watch( [ join(paths.scripts.src, '**/*.js'), ] ).on('change', () => { compileScripts(...developmentScriptsArgs); }); // Watch source concats if (tasks.concats?.length) { server.watch( resolve( tasks.concats.reduce( (patterns, { includes }) => patterns.concat(includes), [] ) ) ).on('change', () => { concatFiles(...developmentConcatFilesArgs); }); } // Watch source styles server.watch( [ join(paths.styles.src, '**/*.scss'), ] ).on('change', () => { compileStyles(...developmentStylesArgs); }); // Watch source SVGs server.watch( [ join(paths.svgs.src, '*.svg'), ] ).on('change', () => { compileSVGs(...developmentSVGsArgs); }); }
Configures the BrowserSync options. @param {BrowserSync} server - The BrowserSync API. @param {object} loconfig - The project configset. @param {object} loconfig.paths - The paths options. @param {object} loconfig.tasks - The tasks options. @return {void}
configureServer
javascript
locomotivemtl/locomotive-boilerplate
build/watch.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/watch.js
MIT
function createServerOptions({ paths, server: options }) { const config = { open: false, notify: false, ghostMode: false }; // Resolve the URL for the BrowserSync server if (isNonEmptyString(paths.url)) { // Use proxy config.proxy = paths.url; } else if (isNonEmptyString(paths.dest)) { // Use base directory config.server = { baseDir: paths.dest }; } merge(config, resolve(options)); // If HTTPS is enabled, prepend `https://` to proxy URL if (options?.https) { if (isNonEmptyString(config.proxy?.target)) { config.proxy.target = prependSchemeToUrl(config.proxy.target, 'https'); } else if (isNonEmptyString(config.proxy)) { config.proxy = prependSchemeToUrl(config.proxy, 'https'); } } return config; }
Creates a new object with all the BrowserSync options. @param {object} loconfig - The project configset. @param {object} loconfig.paths - The paths options. @param {object} loconfig.server - The server options. @return {object} Returns the server options.
createServerOptions
javascript
locomotivemtl/locomotive-boilerplate
build/watch.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/watch.js
MIT
function createViewsArray(views) { if (Array.isArray(views)) { return Array.from(views); } switch (typeof views) { case 'string': return [ views ]; case 'object': if (views != null) { return Object.values(views); } } throw new TypeError( 'Expected \'views\' to be a string, array, or object' ); }
Creates a new array (shallow-copied) from the views configset. @param {*} views - The views configset. @throws {TypeError} If views is invalid. @return {array} Returns the views array.
createViewsArray
javascript
locomotivemtl/locomotive-boilerplate
build/watch.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/watch.js
MIT
function prependSchemeToUrl(url, scheme = 'http') { if (regexUrlStartsWithProtocol.test(url)) { return url.replace(regexUrlStartsWithProtocol, `${scheme}://`); } return `${scheme}://${url}`; }
Prepends the scheme to the URL. @param {string} url - The URL to mutate. @param {string} [scheme] - The URL scheme to prepend. @return {string} Returns the mutated URL.
prependSchemeToUrl
javascript
locomotivemtl/locomotive-boilerplate
build/watch.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/watch.js
MIT
function isNonEmptyString(value) { return (typeof value === 'string' && value.length > 0); }
Determines whether the passed value is a string with at least one character. @param {*} value - The value to be checked. @return {boolean} Returns `true` if the value is a non-empty string, otherwise `false`.
isNonEmptyString
javascript
locomotivemtl/locomotive-boilerplate
build/watch.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/watch.js
MIT
async function importGlob() { for (let name of candidates) { try { let globModule = await import(name); if (typeof globModule.default !== 'function') { throw new TypeError(`Expected ${name} to be a function`); } /** * Wrap the function to ensure * a common pattern. */ switch (name) { case 'tiny-glob': /** [1][5] */ return createArrayableGlob( /** [6] */ createPresetGlob(globModule.default, { filesOnly: true }) ); case 'globby': /** [2][5] - If `patterns` is a string, wraps into an array. */ return (patterns, options) => globModule.default([].concat(patterns), options); case 'glob': /** [1][5] */ return createArrayableGlob( /** [4] */ promisify(globModule.default) ); default: return globModule.default; } } catch (err) { // swallow this error; skip to the next candidate. } } throw new TypeError( `No glob library was found, expected one of: ${candidates.join(', ')}` ); }
Imports the first available glob function. @throws {TypeError} If no glob library was found. @returns {GlobFn}
importGlob
javascript
locomotivemtl/locomotive-boilerplate
build/helpers/glob.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/helpers/glob.js
MIT
function createArrayableGlob(globFn) { return (patterns, options) => { /** [2] If `patterns` is a string, wraps into an array. */ patterns = [].concat(patterns); const globs = patterns.map((pattern) => globFn(pattern, options)); return Promise.all(globs).then((files) => { return [].concat.apply([], files); }); }; }
Creates a wrapper function for the glob function to provide support for arrays of patterns. @param {function} globFn - The glob function. @returns {GlobFn}
createArrayableGlob
javascript
locomotivemtl/locomotive-boilerplate
build/helpers/glob.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/helpers/glob.js
MIT
function createPresetGlob(globFn, presets) { return (patterns, options) => globFn(patterns, Object.assign({}, presets, options)); }
Creates a wrapper function for the glob function to define new default options. @param {function} globFn - The glob function. @param {GlobOptions} presets - The glob function options to preset. @returns {GlobFn}
createPresetGlob
javascript
locomotivemtl/locomotive-boilerplate
build/helpers/glob.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/helpers/glob.js
MIT
function notification(options, callback) { if (typeof options === 'string') { options = { message: options }; } else if (!options.title && !options.message) { throw new TypeError( 'Notification expects at least a \'message\' parameter' ); } if (typeof options.icon === 'undefined') { options.icon = 'https://user-images.githubusercontent.com/4596862/54868065-c2aea200-4d5e-11e9-9ce3-e0013c15f48c.png'; } // If notification does not use a callback, // shorten the wait before timing out. if (typeof callback === 'undefined') { if (typeof options.wait === 'undefined') { if (typeof options.timeout === 'undefined') { options.timeout = 5; } } } notifier.notify(options, callback); }
Sends a cross-platform native notification. Wraps around node-notifier to assign default values. @param {string|object} options - The notification options or a message. @param {string} options.title - The notification title. @param {string} options.message - The notification message. @param {string} options.icon - The notification icon. @param {function} callback - The notification callback. @return {void}
notification
javascript
locomotivemtl/locomotive-boilerplate
build/helpers/notification.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/helpers/notification.js
MIT
function createProcessor(pluginsListOrMap, options) { if (!postcss) { return null; } const plugins = parsePlugins(pluginsListOrMap, options); return postcss(plugins); }
Attempts to create a PostCSS Processor with the given plugins and options. @param {PluginCollection} pluginsListOrMap - A list or map of plugins. If a map of plugins, the plugin name looks up `options`. @param {PostCSSOptions} options - The PostCSS wrapper options. @returns {Processor|null}
createProcessor
javascript
locomotivemtl/locomotive-boilerplate
build/helpers/postcss.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/helpers/postcss.js
MIT
function parsePlugins(pluginsListOrMap, options) { if (Array.isArray(pluginsListOrMap)) { return pluginsListOrMap; } /** @type {PluginList} */ const plugins = []; for (let [ name, plugin ] of Object.entries(pluginsListOrMap)) { if (name in options) { plugin = plugin[name](options[name]); } plugins.push(plugin); } return plugins; }
Parses the PostCSS plugins and options. @param {PluginCollection} pluginsListOrMap - A list or map of plugins. If a map of plugins, the plugin name looks up `options`. @param {PostCSSOptions} options - The PostCSS wrapper options. @returns {PluginList}
parsePlugins
javascript
locomotivemtl/locomotive-boilerplate
build/helpers/postcss.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/helpers/postcss.js
MIT
async function purgeUnusedCSS(outfile, label) { const contentFiles = loconfig.tasks.purgeCSS?.content; if (!Array.isArray(contentFiles) || !contentFiles.length) { return; } label = label ?? basename(outfile); const timeLabel = `${label} purged in`; console.time(timeLabel); const purgeCSSResults = await (new PurgeCSS()).purge({ content: contentFiles, css: [ outfile ], defaultExtractor: content => content.match(/[a-z0-9_\-\\\/\@]+/gi) || [], fontFaces: true, keyframes: true, safelist: { // Keep all except .u-gc-* | .u-margin-* | .u-padding-* standard: [ /^(?!.*\b(u-gc-|u-margin|u-padding)).*$/ ] }, variables: true, }) for (let result of purgeCSSResults) { await writeFile(outfile, result.css) message(`${label} purged`, 'chore', timeLabel); } }
Purge unused styles from CSS files. @async @param {string} outfile - The path of a css file If missing the function stops. @param {string} label - The CSS file label or name. @return {Promise}
purgeUnusedCSS
javascript
locomotivemtl/locomotive-boilerplate
build/tasks/styles.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/tasks/styles.js
MIT
async function bumpVersions(versionOptions = null) { if (versionOptions == null) { versionOptions = productionVersionOptions; } else if ( versionOptions !== developmentVersionOptions && versionOptions !== productionVersionOptions ) { versionOptions = merge({}, defaultVersionOptions, versionOptions); } const queue = new Map(); /** * @async * @param {object} entry - The entrypoint to process. * @param {string} entry.outfile - The file to write to. * @param {?string} [entry.label] - The task label. * Defaults to the outfile name. * @param {?string} [entry.format] - The version number format. * @param {?string} [entry.key] - The JSON field name assign the version number to. * @param {?string|number} [entry.pretty] - The white space to use to format the JSON file. * @return {Promise} */ loconfig.tasks.versions?.forEach(({ outfile, label = null, ...options }) => { if (!label) { label = basename(outfile || 'undefined'); } options.pretty = (options.pretty ?? versionOptions.prettyPrint); options.format = (options.format ?? versionOptions.versionFormat); options.key = (options.key ?? versionOptions.versionKey); if (queue.has(outfile)) { queue.get(outfile).then(() => handleBumpVersion(outfile, label, options)); } else { queue.set(outfile, handleBumpVersion(outfile, label, options)); } }); }
Bumps version numbers in file. @async @param {object} [versionOptions=null] - Customize the version options. If `null`, default production options are used. @return {Promise}
bumpVersions
javascript
locomotivemtl/locomotive-boilerplate
build/tasks/versions.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/tasks/versions.js
MIT
function createVersionNumber(format, oldValue = null) { let [ type, modifier ] = format.split(':', 2); switch (type) { case 'hex': case 'hexadecimal': try { modifier = Number.parseInt(modifier); if (Number.isNaN(modifier)) { modifier = 6; } return randomBytes(modifier).toString('hex'); } catch (err) { throw new TypeError( `${err.message} for \'format\' type "hexadecimal"`, { cause: err } ); } case 'inc': case 'increment': try { if (modifier === 'semver') { return incrementSemVer(oldValue, [ 'buildmetadata', 'patch' ]); } return incrementNumber(oldValue, modifier); } catch (err) { throw new TypeError( `${err.message} for \'format\' type "increment"`, { cause: err } ); } case 'regex': case 'regexp': try { return new RegExp(modifier); } catch (err) { throw new TypeError( `${err.message} for \'format\' type "regexp"`, { cause: err } ); } case 'timestamp': return Date.now().valueOf(); } throw new TypeError( 'Expected \'format\' to be either "timestamp", "increment", or "hexadecimal"' ); }
Creates a formatted version number or string. @param {string} format - The version format. @param {?string} [oldValue] - The old version value. @return {string|number} @throws TypeError If the format or value are invalid.
createVersionNumber
javascript
locomotivemtl/locomotive-boilerplate
build/tasks/versions.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/tasks/versions.js
MIT
async function handleBumpVersionInJson(outfile, label, options) { outfile = resolve(outfile); let json; try { json = JSON.parse(await readFile(outfile, { encoding: 'utf8' })); } catch (err) { json = {}; message(`${label} is a new file`, 'notice'); await mkdir(dirname(outfile), { recursive: true }); } json[options.key] = createVersionNumber(options.format, json?.[options.key]); return await writeFile( outfile, JSON.stringify(json, null, options.pretty), { encoding: 'utf8' } ); }
Changes the version number for the provided JSON key in file. @async @param {string} outfile @param {string} label @param {object} options @param {string} options.key @return {Promise}
handleBumpVersionInJson
javascript
locomotivemtl/locomotive-boilerplate
build/tasks/versions.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/tasks/versions.js
MIT
async function handleBumpVersionWithRegExp(outfile, label, options) { outfile = resolve(outfile); const bckfile = `${outfile}~`; await rename(outfile, bckfile); try { const rl = readline.createInterface({ input: createReadStream(bckfile), }); let newVersion = null; const writeStream = createWriteStream(outfile, { encoding: 'utf8' }); rl.on('line', (line) => { const found = line.match(options.key); if (found) { const groups = (found.groups ?? {}); const oldVersion = (groups.build ?? groups.version ?? found[1] ?? found[0]); const newVersion = createVersionNumber(options.format, oldVersion); const replacement = found[0].replace(oldVersion, newVersion); line = line.replace(found[0], replacement); } writeStream.write(line + "\n"); }); await events.once(rl, 'close'); await rm(bckfile); } catch (err) { await rm(outfile, { force: true }); await rename(bckfile, outfile); throw err; } }
Changes the version number for the provided RegExp in file. @async @param {string} outfile @param {string} label @param {object} options @param {RegExp} options.key @return {Promise}
handleBumpVersionWithRegExp
javascript
locomotivemtl/locomotive-boilerplate
build/tasks/versions.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/tasks/versions.js
MIT
function incrementNumber(value, increment = 1) { const version = Number.parseInt(value); if (Number.isNaN(version)) { throw new TypeError( `Expected an integer version number, received [${value}]` ); } increment = Number.parseInt(increment); if (Number.isNaN(increment)) { throw new TypeError( 'Expected an integer increment number' ); } return (version + increment); }
Increments the given integer. @param {string|int} value - The number to increment. @param {string|int} [increment=1] - The amount to increment by. @return {int} @throws TypeError If the version number is invalid.
incrementNumber
javascript
locomotivemtl/locomotive-boilerplate
build/tasks/versions.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/tasks/versions.js
MIT
function incrementSemVer(value, target = 'patch', increment = 1) { const found = value.match(REGEXP_SEMVER); if (!found) { throw new TypeError( `Expected a SemVer version number, received [${value}]` ); } if (Array.isArray(target)) { for (const group of target) { if (found.groups[group] != null) { target = group; break; } } } if (!target || !found.groups[target]) { throw new TypeError( `Expected a supported SemVer segment, received [${target}]` ); } const segments = { 'major': '', 'minor': '.', 'patch': '.', 'prerelease': '-', 'buildmetadata': '+', }; let replacement = ''; for (const [ segment, delimiter ] of Object.entries(segments)) { if (found.groups?.[segment] != null) { const newVersion = (segment === target) ? incrementNumber(found.groups[segment], increment) : found.groups[segment]; replacement += `${delimiter}${newVersion}`; } } return value.replace(found[0], replacement); }
Increments the given SemVer version number. @param {string} value - The version to mutate. @param {string|string[]} [target] - The segment to increment, one of: 'major', 'minor', 'patch', ~~'prerelease'~~, 'buildmetadata'. @param {string|int} [increment=1] - The amount to increment by. @return {string} @throws TypeError If the version or target are invalid.
incrementSemVer
javascript
locomotivemtl/locomotive-boilerplate
build/tasks/versions.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/tasks/versions.js
MIT
function parseVersionKey(key) { if (key instanceof RegExp) { return key; } if (typeof key !== 'string') { throw new TypeError( 'Expected \'key\' to be either a string or a RegExp' ); } const delimiter = key.indexOf(':'); if (delimiter === -1) { // Assumes its a JSON key return key; } const type = key.slice(0, delimiter); const value = key.slice(delimiter + 1); switch (type) { case 'json': return value; case 'regex': case 'regexp': return new RegExp(value); } throw new TypeError( 'Expected \'key\' type to be either "json" or "regexp"' ); }
Parses the version key. @param {*} key - The version key. @return {string|RegExp}
parseVersionKey
javascript
locomotivemtl/locomotive-boilerplate
build/tasks/versions.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/tasks/versions.js
MIT
function escapeRegExp(str) { return str.replace(regexUnescaped, '\\$&'); }
Quotes regular expression characters. @param {string} str - The input string. @return {string} Returns the quoted (escaped) string.
escapeRegExp
javascript
locomotivemtl/locomotive-boilerplate
build/utils/index.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/utils/index.js
MIT
function flatten(input, prefix, target = {}) { for (const key in input) { const field = (prefix ? prefix + '.' + key : key); if (isObjectLike(input[key])) { flatten(input[key], field, target); } else { target[field] = input[key]; } } return target; }
Creates a new object with all nested object properties concatenated into it recursively. Nested keys are flattened into a property path: ```js { a: { b: { c: 1 } }, d: 1 } ``` ```js { "a.b.c": 1, "d": 1 } ``` @param {object} input - The object to flatten. @param {string} prefix - The parent key prefix. @param {object} target - The object that will receive the flattened properties. @return {object} Returns the `target` object.
flatten
javascript
locomotivemtl/locomotive-boilerplate
build/utils/index.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/utils/index.js
MIT
function isObjectLike(value) { return (value != null && typeof value === 'object'); }
Determines whether the passed value is an `Object`. @param {*} value - The value to be checked. @return {boolean} Returns `true` if the value is an `Object`, otherwise `false`.
isObjectLike
javascript
locomotivemtl/locomotive-boilerplate
build/utils/index.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/utils/index.js
MIT
function merge(target, ...sources) { for (const source of sources) { if (target === source) { throw new TypeError( 'Cannot merge, target and source are the same' ); } for (const key in source) { if (source[key] != null) { if (isObjectLike(source[key]) && isObjectLike(target[key])) { merge(target[key], source[key]); continue; } else if (Array.isArray(source[key]) && Array.isArray(target[key])) { target[key] = target[key].concat(source[key]); continue; } } target[key] = source[key]; } } return target; }
Creates a new object with all nested object properties merged into it recursively. @param {object} target - The target object. @param {object[]} ...sources - The source object(s). @throws {TypeError} If the target and source are the same. @return {object} Returns the `target` object.
merge
javascript
locomotivemtl/locomotive-boilerplate
build/utils/index.js
https://github.com/locomotivemtl/locomotive-boilerplate/blob/master/build/utils/index.js
MIT
on() { activeEffectScope = this; }
This should only be called on non-detached scopes @internal
on
javascript
icai/vue3-calendar
lib/calendar.js
https://github.com/icai/vue3-calendar/blob/master/lib/calendar.js
MIT
off() { activeEffectScope = this.parent; }
This should only be called on non-detached scopes @internal
off
javascript
icai/vue3-calendar
lib/calendar.js
https://github.com/icai/vue3-calendar/blob/master/lib/calendar.js
MIT
stop(fromParent) { if (this._active) { let i, l; for (i = 0, l = this.effects.length; i < l; i++) { this.effects[i].stop(); } for (i = 0, l = this.cleanups.length; i < l; i++) { this.cleanups[i](); } if (this.scopes) { for (i = 0, l = this.scopes.length; i < l; i++) { this.scopes[i].stop(true); } } if (!this.detached && this.parent && !fromParent) { const last = this.parent.scopes.pop(); if (last && last !== this) { this.parent.scopes[this.index] = last; last.index = this.index; } } this.parent = void 0; this._active = false; } }
This should only be called on non-detached scopes @internal
stop
javascript
icai/vue3-calendar
lib/calendar.js
https://github.com/icai/vue3-calendar/blob/master/lib/calendar.js
MIT
function effectScope(detached) { return new EffectScope(detached); }
This should only be called on non-detached scopes @internal
effectScope
javascript
icai/vue3-calendar
lib/calendar.js
https://github.com/icai/vue3-calendar/blob/master/lib/calendar.js
MIT
function recordEffectScope(effect, scope = activeEffectScope) { if (scope && scope.active) { scope.effects.push(effect); } }
This should only be called on non-detached scopes @internal
recordEffectScope
javascript
icai/vue3-calendar
lib/calendar.js
https://github.com/icai/vue3-calendar/blob/master/lib/calendar.js
MIT