id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
21,600
ripple/ripple-rest
server/response-handler.js
connectionError
function connectionError(response, message, body) { var content = errorContent(ErrorType.connection, message, body); send(response, content, StatusCode.badGateway); }
javascript
function connectionError(response, message, body) { var content = errorContent(ErrorType.connection, message, body); send(response, content, StatusCode.badGateway); }
[ "function", "connectionError", "(", "response", ",", "message", ",", "body", ")", "{", "var", "content", "=", "errorContent", "(", "ErrorType", ".", "connection", ",", "message", ",", "body", ")", ";", "send", "(", "response", ",", "content", ",", "StatusCode", ".", "badGateway", ")", ";", "}" ]
Send an connection error response @param response - response object @param message - (optional) additional error message @param body - (optional) additional body to the response
[ "Send", "an", "connection", "error", "response" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/server/response-handler.js#L176-L179
21,601
ripple/ripple-rest
server/response-handler.js
timeOutError
function timeOutError(response, message, body) { var content = errorContent(ErrorType.connection, message, body); send(response, content, StatusCode.timeout); }
javascript
function timeOutError(response, message, body) { var content = errorContent(ErrorType.connection, message, body); send(response, content, StatusCode.timeout); }
[ "function", "timeOutError", "(", "response", ",", "message", ",", "body", ")", "{", "var", "content", "=", "errorContent", "(", "ErrorType", ".", "connection", ",", "message", ",", "body", ")", ";", "send", "(", "response", ",", "content", ",", "StatusCode", ".", "timeout", ")", ";", "}" ]
Send a timeout error response @param response - response object @param message - (optional) additional error message @param body - (optional) additional body to the response
[ "Send", "a", "timeout", "error", "response" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/server/response-handler.js#L199-L202
21,602
ripple/ripple-rest
api/transactions.js
function(transaction, _callback) { transaction.remote = api.remote; if (options.blockDuplicates === true) { blockDuplicates(transaction, options, _callback); } else { _callback(null, transaction); } }
javascript
function(transaction, _callback) { transaction.remote = api.remote; if (options.blockDuplicates === true) { blockDuplicates(transaction, options, _callback); } else { _callback(null, transaction); } }
[ "function", "(", "transaction", ",", "_callback", ")", "{", "transaction", ".", "remote", "=", "api", ".", "remote", ";", "if", "(", "options", ".", "blockDuplicates", "===", "true", ")", "{", "blockDuplicates", "(", "transaction", ",", "options", ",", "_callback", ")", ";", "}", "else", "{", "_callback", "(", "null", ",", "transaction", ")", ";", "}", "}" ]
Duplicate blocking is performed here
[ "Duplicate", "blocking", "is", "performed", "here" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/transactions.js#L89-L97
21,603
ripple/ripple-rest
api/transactions.js
function(transaction, _callback) { try { transaction.secret(secret); } catch (exception) { return _callback(exception); } transaction.once('error', _callback); transaction.once('submitted', function(message) { if (message.result.slice(0, 3) === 'tec' && options.validated !== true) { return formatTransactionResponseWrapper(transaction, message, _callback); } // Handle erred transactions that should not make it into ledger (all // errors that aren't tec-class). This function is called before the // transaction `error` listener. switch (message.engine_result) { case 'terNO_ACCOUNT': case 'terNO_AUTH': case 'terNO_LINE': case 'terINSUF_FEE_B': // The transaction needs to be aborted. Preserve the original ter- // class error for presentation to the client transaction.removeListener('error', _callback); transaction.once('error', function() { _callback(message); }); transaction.abort(); break; } }); transaction.once('proposed', function(message) { if (options.validated !== true) { formatTransactionResponseWrapper(transaction, message, _callback); } }); transaction.once('success', function(message) { if (options.validated === true) { formatTransactionResponseWrapper(transaction, message, _callback); } }); if (options.saveTransaction === true) { transaction.on('state', function() { var transactionSummary = transaction.summary(); if (transactionSummary.submitIndex !== undefined) { api.db.saveTransaction(transactionSummary); } }); transaction.on('postsubmit', function() { api.db.saveTransaction(transaction.summary()); }); } transaction.submit(); }
javascript
function(transaction, _callback) { try { transaction.secret(secret); } catch (exception) { return _callback(exception); } transaction.once('error', _callback); transaction.once('submitted', function(message) { if (message.result.slice(0, 3) === 'tec' && options.validated !== true) { return formatTransactionResponseWrapper(transaction, message, _callback); } // Handle erred transactions that should not make it into ledger (all // errors that aren't tec-class). This function is called before the // transaction `error` listener. switch (message.engine_result) { case 'terNO_ACCOUNT': case 'terNO_AUTH': case 'terNO_LINE': case 'terINSUF_FEE_B': // The transaction needs to be aborted. Preserve the original ter- // class error for presentation to the client transaction.removeListener('error', _callback); transaction.once('error', function() { _callback(message); }); transaction.abort(); break; } }); transaction.once('proposed', function(message) { if (options.validated !== true) { formatTransactionResponseWrapper(transaction, message, _callback); } }); transaction.once('success', function(message) { if (options.validated === true) { formatTransactionResponseWrapper(transaction, message, _callback); } }); if (options.saveTransaction === true) { transaction.on('state', function() { var transactionSummary = transaction.summary(); if (transactionSummary.submitIndex !== undefined) { api.db.saveTransaction(transactionSummary); } }); transaction.on('postsubmit', function() { api.db.saveTransaction(transaction.summary()); }); } transaction.submit(); }
[ "function", "(", "transaction", ",", "_callback", ")", "{", "try", "{", "transaction", ".", "secret", "(", "secret", ")", ";", "}", "catch", "(", "exception", ")", "{", "return", "_callback", "(", "exception", ")", ";", "}", "transaction", ".", "once", "(", "'error'", ",", "_callback", ")", ";", "transaction", ".", "once", "(", "'submitted'", ",", "function", "(", "message", ")", "{", "if", "(", "message", ".", "result", ".", "slice", "(", "0", ",", "3", ")", "===", "'tec'", "&&", "options", ".", "validated", "!==", "true", ")", "{", "return", "formatTransactionResponseWrapper", "(", "transaction", ",", "message", ",", "_callback", ")", ";", "}", "// Handle erred transactions that should not make it into ledger (all", "// errors that aren't tec-class). This function is called before the", "// transaction `error` listener.", "switch", "(", "message", ".", "engine_result", ")", "{", "case", "'terNO_ACCOUNT'", ":", "case", "'terNO_AUTH'", ":", "case", "'terNO_LINE'", ":", "case", "'terINSUF_FEE_B'", ":", "// The transaction needs to be aborted. Preserve the original ter-", "// class error for presentation to the client", "transaction", ".", "removeListener", "(", "'error'", ",", "_callback", ")", ";", "transaction", ".", "once", "(", "'error'", ",", "function", "(", ")", "{", "_callback", "(", "message", ")", ";", "}", ")", ";", "transaction", ".", "abort", "(", ")", ";", "break", ";", "}", "}", ")", ";", "transaction", ".", "once", "(", "'proposed'", ",", "function", "(", "message", ")", "{", "if", "(", "options", ".", "validated", "!==", "true", ")", "{", "formatTransactionResponseWrapper", "(", "transaction", ",", "message", ",", "_callback", ")", ";", "}", "}", ")", ";", "transaction", ".", "once", "(", "'success'", ",", "function", "(", "message", ")", "{", "if", "(", "options", ".", "validated", "===", "true", ")", "{", "formatTransactionResponseWrapper", "(", "transaction", ",", "message", ",", "_callback", ")", ";", "}", "}", ")", ";", "if", "(", "options", ".", "saveTransaction", "===", "true", ")", "{", "transaction", ".", "on", "(", "'state'", ",", "function", "(", ")", "{", "var", "transactionSummary", "=", "transaction", ".", "summary", "(", ")", ";", "if", "(", "transactionSummary", ".", "submitIndex", "!==", "undefined", ")", "{", "api", ".", "db", ".", "saveTransaction", "(", "transactionSummary", ")", ";", "}", "}", ")", ";", "transaction", ".", "on", "(", "'postsubmit'", ",", "function", "(", ")", "{", "api", ".", "db", ".", "saveTransaction", "(", "transaction", ".", "summary", "(", ")", ")", ";", "}", ")", ";", "}", "transaction", ".", "submit", "(", ")", ";", "}" ]
Transaction parameters are set, listeners are registered, and is submitted here
[ "Transaction", "parameters", "are", "set", "listeners", "are", "registered", "and", "is", "submitted", "here" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/transactions.js#L100-L161
21,604
ripple/ripple-rest
api/transactions.js
getTransactionAndRespond
function getTransactionAndRespond(account, identifier, options, callback) { getTransaction( this, account, identifier, options, function(error, transaction) { if (error) { callback(error); } else { callback(null, {transaction: transaction}); } } ); }
javascript
function getTransactionAndRespond(account, identifier, options, callback) { getTransaction( this, account, identifier, options, function(error, transaction) { if (error) { callback(error); } else { callback(null, {transaction: transaction}); } } ); }
[ "function", "getTransactionAndRespond", "(", "account", ",", "identifier", ",", "options", ",", "callback", ")", "{", "getTransaction", "(", "this", ",", "account", ",", "identifier", ",", "options", ",", "function", "(", "error", ",", "transaction", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "{", "transaction", ":", "transaction", "}", ")", ";", "}", "}", ")", ";", "}" ]
Wrapper around getTransaction function that is meant to be used directly as a client-facing function. Unlike getTransaction, it will call next with any errors and send a JSON response to the client on success. See getTransaction for parameter details
[ "Wrapper", "around", "getTransaction", "function", "that", "is", "meant", "to", "be", "used", "directly", "as", "a", "client", "-", "facing", "function", ".", "Unlike", "getTransaction", "it", "will", "call", "next", "with", "any", "errors", "and", "send", "a", "JSON", "response", "to", "the", "client", "on", "success", "." ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/transactions.js#L342-L356
21,605
ripple/ripple-rest
api/transactions.js
getAccountTx
function getAccountTx(api, options, callback) { var params = { account: options.account, ledger_index_min: options.ledger_index_min || options.ledger_index || -1, ledger_index_max: options.ledger_index_max || options.ledger_index || -1, limit: options.limit || DEFAULT_RESULTS_PER_PAGE, forward: options.earliestFirst, marker: options.marker }; if (options.binary) { params.binary = true; } api.remote.requestAccountTx(params, function(error, account_tx_results) { if (error) { return callback(error); } var transactions = []; account_tx_results.transactions.forEach(function(tx_entry) { if (!tx_entry.validated) { return; } var tx = tx_entry.tx; tx.meta = tx_entry.meta; tx.validated = tx_entry.validated; transactions.push(tx); }); callback(null, { transactions: transactions, marker: account_tx_results.marker }); }); }
javascript
function getAccountTx(api, options, callback) { var params = { account: options.account, ledger_index_min: options.ledger_index_min || options.ledger_index || -1, ledger_index_max: options.ledger_index_max || options.ledger_index || -1, limit: options.limit || DEFAULT_RESULTS_PER_PAGE, forward: options.earliestFirst, marker: options.marker }; if (options.binary) { params.binary = true; } api.remote.requestAccountTx(params, function(error, account_tx_results) { if (error) { return callback(error); } var transactions = []; account_tx_results.transactions.forEach(function(tx_entry) { if (!tx_entry.validated) { return; } var tx = tx_entry.tx; tx.meta = tx_entry.meta; tx.validated = tx_entry.validated; transactions.push(tx); }); callback(null, { transactions: transactions, marker: account_tx_results.marker }); }); }
[ "function", "getAccountTx", "(", "api", ",", "options", ",", "callback", ")", "{", "var", "params", "=", "{", "account", ":", "options", ".", "account", ",", "ledger_index_min", ":", "options", ".", "ledger_index_min", "||", "options", ".", "ledger_index", "||", "-", "1", ",", "ledger_index_max", ":", "options", ".", "ledger_index_max", "||", "options", ".", "ledger_index", "||", "-", "1", ",", "limit", ":", "options", ".", "limit", "||", "DEFAULT_RESULTS_PER_PAGE", ",", "forward", ":", "options", ".", "earliestFirst", ",", "marker", ":", "options", ".", "marker", "}", ";", "if", "(", "options", ".", "binary", ")", "{", "params", ".", "binary", "=", "true", ";", "}", "api", ".", "remote", ".", "requestAccountTx", "(", "params", ",", "function", "(", "error", ",", "account_tx_results", ")", "{", "if", "(", "error", ")", "{", "return", "callback", "(", "error", ")", ";", "}", "var", "transactions", "=", "[", "]", ";", "account_tx_results", ".", "transactions", ".", "forEach", "(", "function", "(", "tx_entry", ")", "{", "if", "(", "!", "tx_entry", ".", "validated", ")", "{", "return", ";", "}", "var", "tx", "=", "tx_entry", ".", "tx", ";", "tx", ".", "meta", "=", "tx_entry", ".", "meta", ";", "tx", ".", "validated", "=", "tx_entry", ".", "validated", ";", "transactions", ".", "push", "(", "tx", ")", ";", "}", ")", ";", "callback", "(", "null", ",", "{", "transactions", ":", "transactions", ",", "marker", ":", "account_tx_results", ".", "marker", "}", ")", ";", "}", ")", ";", "}" ]
Wrapper around the standard ripple-lib requestAccountTx function @param {Remote} remote @param {RippleAddress} options.account @param {Number} [-1] options.ledger_index_min @param {Number} [-1] options.ledger_index_max @param {Boolean} [false] options.earliestFirst @param {Boolean} [false] options.binary @param {opaque value} options.marker @param {Function} callback @callback @param {Error} error @param {Array of transactions in JSON format} response.transactions @param {opaque value} response.marker
[ "Wrapper", "around", "the", "standard", "ripple", "-", "lib", "requestAccountTx", "function" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/transactions.js#L375-L406
21,606
ripple/ripple-rest
api/transactions.js
getLocalAndRemoteTransactions
function getLocalAndRemoteTransactions(api, options, callback) { function queryRippled(_callback) { getAccountTx(api, options, function(error, results) { if (error) { _callback(error); } else { // Set marker so that when this function is called again // recursively it starts from the last place it left off options.marker = results.marker; _callback(null, results.transactions); } }); } function queryDB(_callback) { if (options.exclude_failed) { _callback(null, []); } else { api.db.getFailedTransactions(options, _callback); } } var transactionSources = [ queryRippled, queryDB ]; async.parallel(transactionSources, function(error, sourceResults) { if (error) { return callback(error); } var results = sourceResults[0].concat(sourceResults[1]); var transactions = _.uniq(results, function(tx) { return tx.hash; }); callback(null, transactions); }); }
javascript
function getLocalAndRemoteTransactions(api, options, callback) { function queryRippled(_callback) { getAccountTx(api, options, function(error, results) { if (error) { _callback(error); } else { // Set marker so that when this function is called again // recursively it starts from the last place it left off options.marker = results.marker; _callback(null, results.transactions); } }); } function queryDB(_callback) { if (options.exclude_failed) { _callback(null, []); } else { api.db.getFailedTransactions(options, _callback); } } var transactionSources = [ queryRippled, queryDB ]; async.parallel(transactionSources, function(error, sourceResults) { if (error) { return callback(error); } var results = sourceResults[0].concat(sourceResults[1]); var transactions = _.uniq(results, function(tx) { return tx.hash; }); callback(null, transactions); }); }
[ "function", "getLocalAndRemoteTransactions", "(", "api", ",", "options", ",", "callback", ")", "{", "function", "queryRippled", "(", "_callback", ")", "{", "getAccountTx", "(", "api", ",", "options", ",", "function", "(", "error", ",", "results", ")", "{", "if", "(", "error", ")", "{", "_callback", "(", "error", ")", ";", "}", "else", "{", "// Set marker so that when this function is called again", "// recursively it starts from the last place it left off", "options", ".", "marker", "=", "results", ".", "marker", ";", "_callback", "(", "null", ",", "results", ".", "transactions", ")", ";", "}", "}", ")", ";", "}", "function", "queryDB", "(", "_callback", ")", "{", "if", "(", "options", ".", "exclude_failed", ")", "{", "_callback", "(", "null", ",", "[", "]", ")", ";", "}", "else", "{", "api", ".", "db", ".", "getFailedTransactions", "(", "options", ",", "_callback", ")", ";", "}", "}", "var", "transactionSources", "=", "[", "queryRippled", ",", "queryDB", "]", ";", "async", ".", "parallel", "(", "transactionSources", ",", "function", "(", "error", ",", "sourceResults", ")", "{", "if", "(", "error", ")", "{", "return", "callback", "(", "error", ")", ";", "}", "var", "results", "=", "sourceResults", "[", "0", "]", ".", "concat", "(", "sourceResults", "[", "1", "]", ")", ";", "var", "transactions", "=", "_", ".", "uniq", "(", "results", ",", "function", "(", "tx", ")", "{", "return", "tx", ".", "hash", ";", "}", ")", ";", "callback", "(", "null", ",", "transactions", ")", ";", "}", ")", ";", "}" ]
Retrieve transactions from the Remote as well as the local database. @param {Remote} remote @param {/lib/db-interface} dbinterface @param {RippleAddress} options.account @param {Number} [-1] options.ledger_index_min @param {Number} [-1] options.ledger_index_max @param {Boolean} [false] options.earliestFirst @param {Boolean} [false] options.binary @param {Boolean} [false] options.exclude_failed @param {opaque value} options.marker @param {Function} callback @callback @param {Error} error @param {Array of transactions in JSON format} transactions
[ "Retrieve", "transactions", "from", "the", "Remote", "as", "well", "as", "the", "local", "database", "." ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/transactions.js#L426-L466
21,607
ripple/ripple-rest
api/transactions.js
transactionFilter
function transactionFilter(transactions, options) { var filtered_transactions = transactions.filter(function(transaction) { if (options.exclude_failed) { if (transaction.state === 'failed' || (transaction.meta && transaction.meta.TransactionResult !== 'tesSUCCESS')) { return false; } } if (options.types && options.types.length > 0) { if (options.types.indexOf( transaction.TransactionType.toLowerCase()) === -1) { return false; } } if (options.source_account) { if (transaction.Account !== options.source_account) { return false; } } if (options.destination_account) { if (transaction.Destination !== options.destination_account) { return false; } } if (options.direction) { if (options.direction === 'outgoing' && transaction.Account !== options.account) { return false; } if (options.direction === 'incoming' && transaction.Destination && transaction.Destination !== options.account) { return false; } } return true; }); return filtered_transactions; }
javascript
function transactionFilter(transactions, options) { var filtered_transactions = transactions.filter(function(transaction) { if (options.exclude_failed) { if (transaction.state === 'failed' || (transaction.meta && transaction.meta.TransactionResult !== 'tesSUCCESS')) { return false; } } if (options.types && options.types.length > 0) { if (options.types.indexOf( transaction.TransactionType.toLowerCase()) === -1) { return false; } } if (options.source_account) { if (transaction.Account !== options.source_account) { return false; } } if (options.destination_account) { if (transaction.Destination !== options.destination_account) { return false; } } if (options.direction) { if (options.direction === 'outgoing' && transaction.Account !== options.account) { return false; } if (options.direction === 'incoming' && transaction.Destination && transaction.Destination !== options.account) { return false; } } return true; }); return filtered_transactions; }
[ "function", "transactionFilter", "(", "transactions", ",", "options", ")", "{", "var", "filtered_transactions", "=", "transactions", ".", "filter", "(", "function", "(", "transaction", ")", "{", "if", "(", "options", ".", "exclude_failed", ")", "{", "if", "(", "transaction", ".", "state", "===", "'failed'", "||", "(", "transaction", ".", "meta", "&&", "transaction", ".", "meta", ".", "TransactionResult", "!==", "'tesSUCCESS'", ")", ")", "{", "return", "false", ";", "}", "}", "if", "(", "options", ".", "types", "&&", "options", ".", "types", ".", "length", ">", "0", ")", "{", "if", "(", "options", ".", "types", ".", "indexOf", "(", "transaction", ".", "TransactionType", ".", "toLowerCase", "(", ")", ")", "===", "-", "1", ")", "{", "return", "false", ";", "}", "}", "if", "(", "options", ".", "source_account", ")", "{", "if", "(", "transaction", ".", "Account", "!==", "options", ".", "source_account", ")", "{", "return", "false", ";", "}", "}", "if", "(", "options", ".", "destination_account", ")", "{", "if", "(", "transaction", ".", "Destination", "!==", "options", ".", "destination_account", ")", "{", "return", "false", ";", "}", "}", "if", "(", "options", ".", "direction", ")", "{", "if", "(", "options", ".", "direction", "===", "'outgoing'", "&&", "transaction", ".", "Account", "!==", "options", ".", "account", ")", "{", "return", "false", ";", "}", "if", "(", "options", ".", "direction", "===", "'incoming'", "&&", "transaction", ".", "Destination", "&&", "transaction", ".", "Destination", "!==", "options", ".", "account", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", ")", ";", "return", "filtered_transactions", ";", "}" ]
Filter transactions based on the given set of options. @param {Array of transactions in JSON format} transactions @param {Boolean} [false] options.exclude_failed @param {Array of Strings} options.types Possible values are "payment", "offercreate", "offercancel", "trustset", "accountset" @param {RippleAddress} options.source_account @param {RippleAddress} options.destination_account @param {String} options.direction Possible values are "incoming", "outgoing" @returns {Array of transactions in JSON format} filtered_transactions
[ "Filter", "transactions", "based", "on", "the", "given", "set", "of", "options", "." ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/transactions.js#L481-L519
21,608
ripple/ripple-rest
api/transactions.js
getAccountTransactions
function getAccountTransactions(api, options, callback) { try { validate.address(options.account); } catch(err) { return callback(err); } if (!options.min) { options.min = module.exports.DEFAULT_RESULTS_PER_PAGE; } if (!options.max) { options.max = Math.max(options.min, module.exports.DEFAULT_RESULTS_PER_PAGE); } if (!options.limit) { options.limit = module.exports.DEFAULT_LIMIT; } function queryTransactions(async_callback) { getLocalAndRemoteTransactions(api, options, async_callback); } function filterTransactions(transactions, async_callback) { async_callback(null, transactionFilter(transactions, options)); } function sortTransactions(transactions, async_callback) { var compare = options.earliestFirst ? utils.compareTransactions : _.rearg(utils.compareTransactions, 1, 0); transactions.sort(compare); async_callback(null, transactions); } function mergeAndTruncateResults(transactions, async_callback) { if (options.previous_transactions && options.previous_transactions.length > 0) { transactions = options.previous_transactions.concat(transactions); } if (options.offset && options.offset > 0) { var offset_remaining = options.offset - transactions.length; transactions = transactions.slice(options.offset); options.offset = offset_remaining; } if (transactions.length > options.max) { transactions = transactions.slice(0, options.max); } async_callback(null, transactions); } function asyncWaterfallCallback(error, transactions) { if (error) { return callback(error); } if (!options.min || transactions.length >= options.min || !options.marker) { callback(null, transactions); } else { options.previous_transactions = transactions; setImmediate(function() { getAccountTransactions(api, options, callback); }); } } var steps = [ queryTransactions, filterTransactions, sortTransactions, mergeAndTruncateResults ]; async.waterfall(steps, asyncWaterfallCallback); }
javascript
function getAccountTransactions(api, options, callback) { try { validate.address(options.account); } catch(err) { return callback(err); } if (!options.min) { options.min = module.exports.DEFAULT_RESULTS_PER_PAGE; } if (!options.max) { options.max = Math.max(options.min, module.exports.DEFAULT_RESULTS_PER_PAGE); } if (!options.limit) { options.limit = module.exports.DEFAULT_LIMIT; } function queryTransactions(async_callback) { getLocalAndRemoteTransactions(api, options, async_callback); } function filterTransactions(transactions, async_callback) { async_callback(null, transactionFilter(transactions, options)); } function sortTransactions(transactions, async_callback) { var compare = options.earliestFirst ? utils.compareTransactions : _.rearg(utils.compareTransactions, 1, 0); transactions.sort(compare); async_callback(null, transactions); } function mergeAndTruncateResults(transactions, async_callback) { if (options.previous_transactions && options.previous_transactions.length > 0) { transactions = options.previous_transactions.concat(transactions); } if (options.offset && options.offset > 0) { var offset_remaining = options.offset - transactions.length; transactions = transactions.slice(options.offset); options.offset = offset_remaining; } if (transactions.length > options.max) { transactions = transactions.slice(0, options.max); } async_callback(null, transactions); } function asyncWaterfallCallback(error, transactions) { if (error) { return callback(error); } if (!options.min || transactions.length >= options.min || !options.marker) { callback(null, transactions); } else { options.previous_transactions = transactions; setImmediate(function() { getAccountTransactions(api, options, callback); }); } } var steps = [ queryTransactions, filterTransactions, sortTransactions, mergeAndTruncateResults ]; async.waterfall(steps, asyncWaterfallCallback); }
[ "function", "getAccountTransactions", "(", "api", ",", "options", ",", "callback", ")", "{", "try", "{", "validate", ".", "address", "(", "options", ".", "account", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "if", "(", "!", "options", ".", "min", ")", "{", "options", ".", "min", "=", "module", ".", "exports", ".", "DEFAULT_RESULTS_PER_PAGE", ";", "}", "if", "(", "!", "options", ".", "max", ")", "{", "options", ".", "max", "=", "Math", ".", "max", "(", "options", ".", "min", ",", "module", ".", "exports", ".", "DEFAULT_RESULTS_PER_PAGE", ")", ";", "}", "if", "(", "!", "options", ".", "limit", ")", "{", "options", ".", "limit", "=", "module", ".", "exports", ".", "DEFAULT_LIMIT", ";", "}", "function", "queryTransactions", "(", "async_callback", ")", "{", "getLocalAndRemoteTransactions", "(", "api", ",", "options", ",", "async_callback", ")", ";", "}", "function", "filterTransactions", "(", "transactions", ",", "async_callback", ")", "{", "async_callback", "(", "null", ",", "transactionFilter", "(", "transactions", ",", "options", ")", ")", ";", "}", "function", "sortTransactions", "(", "transactions", ",", "async_callback", ")", "{", "var", "compare", "=", "options", ".", "earliestFirst", "?", "utils", ".", "compareTransactions", ":", "_", ".", "rearg", "(", "utils", ".", "compareTransactions", ",", "1", ",", "0", ")", ";", "transactions", ".", "sort", "(", "compare", ")", ";", "async_callback", "(", "null", ",", "transactions", ")", ";", "}", "function", "mergeAndTruncateResults", "(", "transactions", ",", "async_callback", ")", "{", "if", "(", "options", ".", "previous_transactions", "&&", "options", ".", "previous_transactions", ".", "length", ">", "0", ")", "{", "transactions", "=", "options", ".", "previous_transactions", ".", "concat", "(", "transactions", ")", ";", "}", "if", "(", "options", ".", "offset", "&&", "options", ".", "offset", ">", "0", ")", "{", "var", "offset_remaining", "=", "options", ".", "offset", "-", "transactions", ".", "length", ";", "transactions", "=", "transactions", ".", "slice", "(", "options", ".", "offset", ")", ";", "options", ".", "offset", "=", "offset_remaining", ";", "}", "if", "(", "transactions", ".", "length", ">", "options", ".", "max", ")", "{", "transactions", "=", "transactions", ".", "slice", "(", "0", ",", "options", ".", "max", ")", ";", "}", "async_callback", "(", "null", ",", "transactions", ")", ";", "}", "function", "asyncWaterfallCallback", "(", "error", ",", "transactions", ")", "{", "if", "(", "error", ")", "{", "return", "callback", "(", "error", ")", ";", "}", "if", "(", "!", "options", ".", "min", "||", "transactions", ".", "length", ">=", "options", ".", "min", "||", "!", "options", ".", "marker", ")", "{", "callback", "(", "null", ",", "transactions", ")", ";", "}", "else", "{", "options", ".", "previous_transactions", "=", "transactions", ";", "setImmediate", "(", "function", "(", ")", "{", "getAccountTransactions", "(", "api", ",", "options", ",", "callback", ")", ";", "}", ")", ";", "}", "}", "var", "steps", "=", "[", "queryTransactions", ",", "filterTransactions", ",", "sortTransactions", ",", "mergeAndTruncateResults", "]", ";", "async", ".", "waterfall", "(", "steps", ",", "asyncWaterfallCallback", ")", ";", "}" ]
Recursively get transactions for the specified account from the Remote and local database. If options.min is set, this will recurse until it has retrieved that number of transactions or it has reached the end of the account's transaction history. @param {Remote} remote @param {/lib/db-interface} dbinterface @param {RippleAddress} options.account @param {Number} [-1] options.ledger_index_min @param {Number} [-1] options.ledger_index_max @param {Boolean} [false] options.earliestFirst @param {Boolean} [false] options.binary @param {Boolean} [false] options.exclude_failed @param {Number} [DEFAULT_RESULTS_PER_PAGE] options.min @param {Number} [DEFAULT_RESULTS_PER_PAGE] options.max @param {Array of Strings} options.types Possible values are "payment", "offercreate", "offercancel", "trustset", "accountset" @param {opaque value} options.marker @param {Array of Transactions} options.previous_transactions Included automatically when this function is called recursively @param {Express.js Response} res @param {Function} callback @callback @param {Error} error @param {Array of transactions in JSON format} transactions
[ "Recursively", "get", "transactions", "for", "the", "specified", "account", "from", "the", "Remote", "and", "local", "database", ".", "If", "options", ".", "min", "is", "set", "this", "will", "recurse", "until", "it", "has", "retrieved", "that", "number", "of", "transactions", "or", "it", "has", "reached", "the", "end", "of", "the", "account", "s", "transaction", "history", "." ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/transactions.js#L549-L620
21,609
ripple/ripple-rest
api/notifications.js
attachPreviousAndNextTransactionIdentifiers
function attachPreviousAndNextTransactionIdentifiers(api, notificationDetails, topCallback) { // Get all of the transactions affecting the specified // account in the given ledger. This is done so that // we can query for one more than that number on either // side to ensure that we'll find the next and previous // transactions, no matter how many transactions the // given account had in the same ledger function getAccountTransactionsInBaseTransactionLedger(callback) { var params = { account: notificationDetails.account, ledger_index_min: notificationDetails.transaction.ledger_index, ledger_index_max: notificationDetails.transaction.ledger_index, exclude_failed: false, max: 99999999, limit: 200 // arbitrary, just checking number of transactions in ledger }; transactions.getAccountTransactions(api, params, callback); } // All we care about is the count of the transactions function countAccountTransactionsInBaseTransactionledger(txns, callback) { callback(null, txns.length); } // Query for one more than the numTransactionsInLedger // going forward and backwards to get a range of transactions // that will definitely include the next and previous transactions function getNextAndPreviousTransactions(numTransactionsInLedger, callback) { async.concat([false, true], function(earliestFirst, concat_callback) { var params = { account: notificationDetails.account, max: numTransactionsInLedger + 1, min: numTransactionsInLedger + 1, limit: numTransactionsInLedger + 1, earliestFirst: earliestFirst }; // In rippled -1 corresponds to the first or last ledger // in its database, depending on whether it is the min or max value if (params.earliestFirst) { params.ledger_index_max = -1; params.ledger_index_min = notificationDetails.transaction.ledger_index; } else { params.ledger_index_max = notificationDetails.transaction.ledger_index; params.ledger_index_min = -1; } transactions.getAccountTransactions(api, params, concat_callback); }, callback); } // Sort the transactions returned by ledger_index and remove duplicates function sortTransactions(allTransactions, callback) { allTransactions.push(notificationDetails.transaction); var txns = _.uniq(allTransactions, function(tx) { return tx.hash; }); txns.sort(utils.compareTransactions); callback(null, txns); } // Find the baseTransaction amongst the results. Because the // transactions have been sorted, the next and previous transactions // will be the ones on either side of the base transaction function findPreviousAndNextTransactions(txns, callback) { // Find the index in the array of the baseTransaction var baseTransactionIndex = _.findIndex(txns, function(possibility) { if (possibility.hash === notificationDetails.transaction.hash) { return true; } else if (possibility.client_resource_id && (possibility.client_resource_id === notificationDetails.transaction.client_resource_id || possibility.client_resource_id === notificationDetails.identifier)) { return true; } return false; }); // The previous transaction is the one with an index in // the array of baseTransactionIndex - 1 if (baseTransactionIndex > 0) { var previous_transaction = txns[baseTransactionIndex - 1]; notificationDetails.previous_transaction_identifier = (previous_transaction.from_local_db ? previous_transaction.client_resource_id : previous_transaction.hash); notificationDetails.previous_hash = previous_transaction.hash; } // The next transaction is the one with an index in // the array of baseTransactionIndex + 1 if (baseTransactionIndex + 1 < txns.length) { var next_transaction = txns[baseTransactionIndex + 1]; notificationDetails.next_transaction_identifier = (next_transaction.from_local_db ? next_transaction.client_resource_id : next_transaction.hash); notificationDetails.next_hash = next_transaction.hash; } callback(null, notificationDetails); } var steps = [ getAccountTransactionsInBaseTransactionLedger, countAccountTransactionsInBaseTransactionledger, getNextAndPreviousTransactions, sortTransactions, findPreviousAndNextTransactions ]; async.waterfall(steps, topCallback); }
javascript
function attachPreviousAndNextTransactionIdentifiers(api, notificationDetails, topCallback) { // Get all of the transactions affecting the specified // account in the given ledger. This is done so that // we can query for one more than that number on either // side to ensure that we'll find the next and previous // transactions, no matter how many transactions the // given account had in the same ledger function getAccountTransactionsInBaseTransactionLedger(callback) { var params = { account: notificationDetails.account, ledger_index_min: notificationDetails.transaction.ledger_index, ledger_index_max: notificationDetails.transaction.ledger_index, exclude_failed: false, max: 99999999, limit: 200 // arbitrary, just checking number of transactions in ledger }; transactions.getAccountTransactions(api, params, callback); } // All we care about is the count of the transactions function countAccountTransactionsInBaseTransactionledger(txns, callback) { callback(null, txns.length); } // Query for one more than the numTransactionsInLedger // going forward and backwards to get a range of transactions // that will definitely include the next and previous transactions function getNextAndPreviousTransactions(numTransactionsInLedger, callback) { async.concat([false, true], function(earliestFirst, concat_callback) { var params = { account: notificationDetails.account, max: numTransactionsInLedger + 1, min: numTransactionsInLedger + 1, limit: numTransactionsInLedger + 1, earliestFirst: earliestFirst }; // In rippled -1 corresponds to the first or last ledger // in its database, depending on whether it is the min or max value if (params.earliestFirst) { params.ledger_index_max = -1; params.ledger_index_min = notificationDetails.transaction.ledger_index; } else { params.ledger_index_max = notificationDetails.transaction.ledger_index; params.ledger_index_min = -1; } transactions.getAccountTransactions(api, params, concat_callback); }, callback); } // Sort the transactions returned by ledger_index and remove duplicates function sortTransactions(allTransactions, callback) { allTransactions.push(notificationDetails.transaction); var txns = _.uniq(allTransactions, function(tx) { return tx.hash; }); txns.sort(utils.compareTransactions); callback(null, txns); } // Find the baseTransaction amongst the results. Because the // transactions have been sorted, the next and previous transactions // will be the ones on either side of the base transaction function findPreviousAndNextTransactions(txns, callback) { // Find the index in the array of the baseTransaction var baseTransactionIndex = _.findIndex(txns, function(possibility) { if (possibility.hash === notificationDetails.transaction.hash) { return true; } else if (possibility.client_resource_id && (possibility.client_resource_id === notificationDetails.transaction.client_resource_id || possibility.client_resource_id === notificationDetails.identifier)) { return true; } return false; }); // The previous transaction is the one with an index in // the array of baseTransactionIndex - 1 if (baseTransactionIndex > 0) { var previous_transaction = txns[baseTransactionIndex - 1]; notificationDetails.previous_transaction_identifier = (previous_transaction.from_local_db ? previous_transaction.client_resource_id : previous_transaction.hash); notificationDetails.previous_hash = previous_transaction.hash; } // The next transaction is the one with an index in // the array of baseTransactionIndex + 1 if (baseTransactionIndex + 1 < txns.length) { var next_transaction = txns[baseTransactionIndex + 1]; notificationDetails.next_transaction_identifier = (next_transaction.from_local_db ? next_transaction.client_resource_id : next_transaction.hash); notificationDetails.next_hash = next_transaction.hash; } callback(null, notificationDetails); } var steps = [ getAccountTransactionsInBaseTransactionLedger, countAccountTransactionsInBaseTransactionledger, getNextAndPreviousTransactions, sortTransactions, findPreviousAndNextTransactions ]; async.waterfall(steps, topCallback); }
[ "function", "attachPreviousAndNextTransactionIdentifiers", "(", "api", ",", "notificationDetails", ",", "topCallback", ")", "{", "// Get all of the transactions affecting the specified", "// account in the given ledger. This is done so that", "// we can query for one more than that number on either", "// side to ensure that we'll find the next and previous", "// transactions, no matter how many transactions the", "// given account had in the same ledger", "function", "getAccountTransactionsInBaseTransactionLedger", "(", "callback", ")", "{", "var", "params", "=", "{", "account", ":", "notificationDetails", ".", "account", ",", "ledger_index_min", ":", "notificationDetails", ".", "transaction", ".", "ledger_index", ",", "ledger_index_max", ":", "notificationDetails", ".", "transaction", ".", "ledger_index", ",", "exclude_failed", ":", "false", ",", "max", ":", "99999999", ",", "limit", ":", "200", "// arbitrary, just checking number of transactions in ledger", "}", ";", "transactions", ".", "getAccountTransactions", "(", "api", ",", "params", ",", "callback", ")", ";", "}", "// All we care about is the count of the transactions", "function", "countAccountTransactionsInBaseTransactionledger", "(", "txns", ",", "callback", ")", "{", "callback", "(", "null", ",", "txns", ".", "length", ")", ";", "}", "// Query for one more than the numTransactionsInLedger", "// going forward and backwards to get a range of transactions", "// that will definitely include the next and previous transactions", "function", "getNextAndPreviousTransactions", "(", "numTransactionsInLedger", ",", "callback", ")", "{", "async", ".", "concat", "(", "[", "false", ",", "true", "]", ",", "function", "(", "earliestFirst", ",", "concat_callback", ")", "{", "var", "params", "=", "{", "account", ":", "notificationDetails", ".", "account", ",", "max", ":", "numTransactionsInLedger", "+", "1", ",", "min", ":", "numTransactionsInLedger", "+", "1", ",", "limit", ":", "numTransactionsInLedger", "+", "1", ",", "earliestFirst", ":", "earliestFirst", "}", ";", "// In rippled -1 corresponds to the first or last ledger", "// in its database, depending on whether it is the min or max value", "if", "(", "params", ".", "earliestFirst", ")", "{", "params", ".", "ledger_index_max", "=", "-", "1", ";", "params", ".", "ledger_index_min", "=", "notificationDetails", ".", "transaction", ".", "ledger_index", ";", "}", "else", "{", "params", ".", "ledger_index_max", "=", "notificationDetails", ".", "transaction", ".", "ledger_index", ";", "params", ".", "ledger_index_min", "=", "-", "1", ";", "}", "transactions", ".", "getAccountTransactions", "(", "api", ",", "params", ",", "concat_callback", ")", ";", "}", ",", "callback", ")", ";", "}", "// Sort the transactions returned by ledger_index and remove duplicates", "function", "sortTransactions", "(", "allTransactions", ",", "callback", ")", "{", "allTransactions", ".", "push", "(", "notificationDetails", ".", "transaction", ")", ";", "var", "txns", "=", "_", ".", "uniq", "(", "allTransactions", ",", "function", "(", "tx", ")", "{", "return", "tx", ".", "hash", ";", "}", ")", ";", "txns", ".", "sort", "(", "utils", ".", "compareTransactions", ")", ";", "callback", "(", "null", ",", "txns", ")", ";", "}", "// Find the baseTransaction amongst the results. Because the", "// transactions have been sorted, the next and previous transactions", "// will be the ones on either side of the base transaction", "function", "findPreviousAndNextTransactions", "(", "txns", ",", "callback", ")", "{", "// Find the index in the array of the baseTransaction", "var", "baseTransactionIndex", "=", "_", ".", "findIndex", "(", "txns", ",", "function", "(", "possibility", ")", "{", "if", "(", "possibility", ".", "hash", "===", "notificationDetails", ".", "transaction", ".", "hash", ")", "{", "return", "true", ";", "}", "else", "if", "(", "possibility", ".", "client_resource_id", "&&", "(", "possibility", ".", "client_resource_id", "===", "notificationDetails", ".", "transaction", ".", "client_resource_id", "||", "possibility", ".", "client_resource_id", "===", "notificationDetails", ".", "identifier", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", ")", ";", "// The previous transaction is the one with an index in", "// the array of baseTransactionIndex - 1", "if", "(", "baseTransactionIndex", ">", "0", ")", "{", "var", "previous_transaction", "=", "txns", "[", "baseTransactionIndex", "-", "1", "]", ";", "notificationDetails", ".", "previous_transaction_identifier", "=", "(", "previous_transaction", ".", "from_local_db", "?", "previous_transaction", ".", "client_resource_id", ":", "previous_transaction", ".", "hash", ")", ";", "notificationDetails", ".", "previous_hash", "=", "previous_transaction", ".", "hash", ";", "}", "// The next transaction is the one with an index in", "// the array of baseTransactionIndex + 1", "if", "(", "baseTransactionIndex", "+", "1", "<", "txns", ".", "length", ")", "{", "var", "next_transaction", "=", "txns", "[", "baseTransactionIndex", "+", "1", "]", ";", "notificationDetails", ".", "next_transaction_identifier", "=", "(", "next_transaction", ".", "from_local_db", "?", "next_transaction", ".", "client_resource_id", ":", "next_transaction", ".", "hash", ")", ";", "notificationDetails", ".", "next_hash", "=", "next_transaction", ".", "hash", ";", "}", "callback", "(", "null", ",", "notificationDetails", ")", ";", "}", "var", "steps", "=", "[", "getAccountTransactionsInBaseTransactionLedger", ",", "countAccountTransactionsInBaseTransactionledger", ",", "getNextAndPreviousTransactions", ",", "sortTransactions", ",", "findPreviousAndNextTransactions", "]", ";", "async", ".", "waterfall", "(", "steps", ",", "topCallback", ")", ";", "}" ]
Find the previous and next transaction hashes or client_resource_ids using both the rippled and local database. Report errors to the client using res.json or pass the notificationDetails with the added fields back to the callback. @param {Remote} $.remote @param {/lib/db-interface} $.dbinterface @param {Express.js Response} res @param {RippleAddress} notificationDetails.account @param {Ripple Transaction in JSON Format} notificationDetails.transaction @param {Hex-encoded String|ResourceId} notificationDetails.identifier @param {Function} callback @callback @param {Error} error @param {Object} notificationDetails
[ "Find", "the", "previous", "and", "next", "transaction", "hashes", "or", "client_resource_ids", "using", "both", "the", "rippled", "and", "local", "database", ".", "Report", "errors", "to", "the", "client", "using", "res", ".", "json", "or", "pass", "the", "notificationDetails", "with", "the", "added", "fields", "back", "to", "the", "callback", "." ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/notifications.js#L32-L151
21,610
ripple/ripple-rest
api/notifications.js
getAccountTransactionsInBaseTransactionLedger
function getAccountTransactionsInBaseTransactionLedger(callback) { var params = { account: notificationDetails.account, ledger_index_min: notificationDetails.transaction.ledger_index, ledger_index_max: notificationDetails.transaction.ledger_index, exclude_failed: false, max: 99999999, limit: 200 // arbitrary, just checking number of transactions in ledger }; transactions.getAccountTransactions(api, params, callback); }
javascript
function getAccountTransactionsInBaseTransactionLedger(callback) { var params = { account: notificationDetails.account, ledger_index_min: notificationDetails.transaction.ledger_index, ledger_index_max: notificationDetails.transaction.ledger_index, exclude_failed: false, max: 99999999, limit: 200 // arbitrary, just checking number of transactions in ledger }; transactions.getAccountTransactions(api, params, callback); }
[ "function", "getAccountTransactionsInBaseTransactionLedger", "(", "callback", ")", "{", "var", "params", "=", "{", "account", ":", "notificationDetails", ".", "account", ",", "ledger_index_min", ":", "notificationDetails", ".", "transaction", ".", "ledger_index", ",", "ledger_index_max", ":", "notificationDetails", ".", "transaction", ".", "ledger_index", ",", "exclude_failed", ":", "false", ",", "max", ":", "99999999", ",", "limit", ":", "200", "// arbitrary, just checking number of transactions in ledger", "}", ";", "transactions", ".", "getAccountTransactions", "(", "api", ",", "params", ",", "callback", ")", ";", "}" ]
Get all of the transactions affecting the specified account in the given ledger. This is done so that we can query for one more than that number on either side to ensure that we'll find the next and previous transactions, no matter how many transactions the given account had in the same ledger
[ "Get", "all", "of", "the", "transactions", "affecting", "the", "specified", "account", "in", "the", "given", "ledger", ".", "This", "is", "done", "so", "that", "we", "can", "query", "for", "one", "more", "than", "that", "number", "on", "either", "side", "to", "ensure", "that", "we", "ll", "find", "the", "next", "and", "previous", "transactions", "no", "matter", "how", "many", "transactions", "the", "given", "account", "had", "in", "the", "same", "ledger" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/notifications.js#L41-L52
21,611
ripple/ripple-rest
api/notifications.js
getNextAndPreviousTransactions
function getNextAndPreviousTransactions(numTransactionsInLedger, callback) { async.concat([false, true], function(earliestFirst, concat_callback) { var params = { account: notificationDetails.account, max: numTransactionsInLedger + 1, min: numTransactionsInLedger + 1, limit: numTransactionsInLedger + 1, earliestFirst: earliestFirst }; // In rippled -1 corresponds to the first or last ledger // in its database, depending on whether it is the min or max value if (params.earliestFirst) { params.ledger_index_max = -1; params.ledger_index_min = notificationDetails.transaction.ledger_index; } else { params.ledger_index_max = notificationDetails.transaction.ledger_index; params.ledger_index_min = -1; } transactions.getAccountTransactions(api, params, concat_callback); }, callback); }
javascript
function getNextAndPreviousTransactions(numTransactionsInLedger, callback) { async.concat([false, true], function(earliestFirst, concat_callback) { var params = { account: notificationDetails.account, max: numTransactionsInLedger + 1, min: numTransactionsInLedger + 1, limit: numTransactionsInLedger + 1, earliestFirst: earliestFirst }; // In rippled -1 corresponds to the first or last ledger // in its database, depending on whether it is the min or max value if (params.earliestFirst) { params.ledger_index_max = -1; params.ledger_index_min = notificationDetails.transaction.ledger_index; } else { params.ledger_index_max = notificationDetails.transaction.ledger_index; params.ledger_index_min = -1; } transactions.getAccountTransactions(api, params, concat_callback); }, callback); }
[ "function", "getNextAndPreviousTransactions", "(", "numTransactionsInLedger", ",", "callback", ")", "{", "async", ".", "concat", "(", "[", "false", ",", "true", "]", ",", "function", "(", "earliestFirst", ",", "concat_callback", ")", "{", "var", "params", "=", "{", "account", ":", "notificationDetails", ".", "account", ",", "max", ":", "numTransactionsInLedger", "+", "1", ",", "min", ":", "numTransactionsInLedger", "+", "1", ",", "limit", ":", "numTransactionsInLedger", "+", "1", ",", "earliestFirst", ":", "earliestFirst", "}", ";", "// In rippled -1 corresponds to the first or last ledger", "// in its database, depending on whether it is the min or max value", "if", "(", "params", ".", "earliestFirst", ")", "{", "params", ".", "ledger_index_max", "=", "-", "1", ";", "params", ".", "ledger_index_min", "=", "notificationDetails", ".", "transaction", ".", "ledger_index", ";", "}", "else", "{", "params", ".", "ledger_index_max", "=", "notificationDetails", ".", "transaction", ".", "ledger_index", ";", "params", ".", "ledger_index_min", "=", "-", "1", ";", "}", "transactions", ".", "getAccountTransactions", "(", "api", ",", "params", ",", "concat_callback", ")", ";", "}", ",", "callback", ")", ";", "}" ]
Query for one more than the numTransactionsInLedger going forward and backwards to get a range of transactions that will definitely include the next and previous transactions
[ "Query", "for", "one", "more", "than", "the", "numTransactionsInLedger", "going", "forward", "and", "backwards", "to", "get", "a", "range", "of", "transactions", "that", "will", "definitely", "include", "the", "next", "and", "previous", "transactions" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/notifications.js#L62-L86
21,612
ripple/ripple-rest
api/notifications.js
sortTransactions
function sortTransactions(allTransactions, callback) { allTransactions.push(notificationDetails.transaction); var txns = _.uniq(allTransactions, function(tx) { return tx.hash; }); txns.sort(utils.compareTransactions); callback(null, txns); }
javascript
function sortTransactions(allTransactions, callback) { allTransactions.push(notificationDetails.transaction); var txns = _.uniq(allTransactions, function(tx) { return tx.hash; }); txns.sort(utils.compareTransactions); callback(null, txns); }
[ "function", "sortTransactions", "(", "allTransactions", ",", "callback", ")", "{", "allTransactions", ".", "push", "(", "notificationDetails", ".", "transaction", ")", ";", "var", "txns", "=", "_", ".", "uniq", "(", "allTransactions", ",", "function", "(", "tx", ")", "{", "return", "tx", ".", "hash", ";", "}", ")", ";", "txns", ".", "sort", "(", "utils", ".", "compareTransactions", ")", ";", "callback", "(", "null", ",", "txns", ")", ";", "}" ]
Sort the transactions returned by ledger_index and remove duplicates
[ "Sort", "the", "transactions", "returned", "by", "ledger_index", "and", "remove", "duplicates" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/notifications.js#L89-L99
21,613
ripple/ripple-rest
api/notifications.js
findPreviousAndNextTransactions
function findPreviousAndNextTransactions(txns, callback) { // Find the index in the array of the baseTransaction var baseTransactionIndex = _.findIndex(txns, function(possibility) { if (possibility.hash === notificationDetails.transaction.hash) { return true; } else if (possibility.client_resource_id && (possibility.client_resource_id === notificationDetails.transaction.client_resource_id || possibility.client_resource_id === notificationDetails.identifier)) { return true; } return false; }); // The previous transaction is the one with an index in // the array of baseTransactionIndex - 1 if (baseTransactionIndex > 0) { var previous_transaction = txns[baseTransactionIndex - 1]; notificationDetails.previous_transaction_identifier = (previous_transaction.from_local_db ? previous_transaction.client_resource_id : previous_transaction.hash); notificationDetails.previous_hash = previous_transaction.hash; } // The next transaction is the one with an index in // the array of baseTransactionIndex + 1 if (baseTransactionIndex + 1 < txns.length) { var next_transaction = txns[baseTransactionIndex + 1]; notificationDetails.next_transaction_identifier = (next_transaction.from_local_db ? next_transaction.client_resource_id : next_transaction.hash); notificationDetails.next_hash = next_transaction.hash; } callback(null, notificationDetails); }
javascript
function findPreviousAndNextTransactions(txns, callback) { // Find the index in the array of the baseTransaction var baseTransactionIndex = _.findIndex(txns, function(possibility) { if (possibility.hash === notificationDetails.transaction.hash) { return true; } else if (possibility.client_resource_id && (possibility.client_resource_id === notificationDetails.transaction.client_resource_id || possibility.client_resource_id === notificationDetails.identifier)) { return true; } return false; }); // The previous transaction is the one with an index in // the array of baseTransactionIndex - 1 if (baseTransactionIndex > 0) { var previous_transaction = txns[baseTransactionIndex - 1]; notificationDetails.previous_transaction_identifier = (previous_transaction.from_local_db ? previous_transaction.client_resource_id : previous_transaction.hash); notificationDetails.previous_hash = previous_transaction.hash; } // The next transaction is the one with an index in // the array of baseTransactionIndex + 1 if (baseTransactionIndex + 1 < txns.length) { var next_transaction = txns[baseTransactionIndex + 1]; notificationDetails.next_transaction_identifier = (next_transaction.from_local_db ? next_transaction.client_resource_id : next_transaction.hash); notificationDetails.next_hash = next_transaction.hash; } callback(null, notificationDetails); }
[ "function", "findPreviousAndNextTransactions", "(", "txns", ",", "callback", ")", "{", "// Find the index in the array of the baseTransaction", "var", "baseTransactionIndex", "=", "_", ".", "findIndex", "(", "txns", ",", "function", "(", "possibility", ")", "{", "if", "(", "possibility", ".", "hash", "===", "notificationDetails", ".", "transaction", ".", "hash", ")", "{", "return", "true", ";", "}", "else", "if", "(", "possibility", ".", "client_resource_id", "&&", "(", "possibility", ".", "client_resource_id", "===", "notificationDetails", ".", "transaction", ".", "client_resource_id", "||", "possibility", ".", "client_resource_id", "===", "notificationDetails", ".", "identifier", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", ")", ";", "// The previous transaction is the one with an index in", "// the array of baseTransactionIndex - 1", "if", "(", "baseTransactionIndex", ">", "0", ")", "{", "var", "previous_transaction", "=", "txns", "[", "baseTransactionIndex", "-", "1", "]", ";", "notificationDetails", ".", "previous_transaction_identifier", "=", "(", "previous_transaction", ".", "from_local_db", "?", "previous_transaction", ".", "client_resource_id", ":", "previous_transaction", ".", "hash", ")", ";", "notificationDetails", ".", "previous_hash", "=", "previous_transaction", ".", "hash", ";", "}", "// The next transaction is the one with an index in", "// the array of baseTransactionIndex + 1", "if", "(", "baseTransactionIndex", "+", "1", "<", "txns", ".", "length", ")", "{", "var", "next_transaction", "=", "txns", "[", "baseTransactionIndex", "+", "1", "]", ";", "notificationDetails", ".", "next_transaction_identifier", "=", "(", "next_transaction", ".", "from_local_db", "?", "next_transaction", ".", "client_resource_id", ":", "next_transaction", ".", "hash", ")", ";", "notificationDetails", ".", "next_hash", "=", "next_transaction", ".", "hash", ";", "}", "callback", "(", "null", ",", "notificationDetails", ")", ";", "}" ]
Find the baseTransaction amongst the results. Because the transactions have been sorted, the next and previous transactions will be the ones on either side of the base transaction
[ "Find", "the", "baseTransaction", "amongst", "the", "results", ".", "Because", "the", "transactions", "have", "been", "sorted", "the", "next", "and", "previous", "transactions", "will", "be", "the", "ones", "on", "either", "side", "of", "the", "base", "transaction" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/notifications.js#L104-L140
21,614
ripple/ripple-rest
api/notifications.js
getNotificationHelper
function getNotificationHelper(api, account, identifier, urlBase, topCallback) { function getTransaction(callback) { try { transactions.getTransaction(api, account, identifier, {}, callback); } catch(err) { callback(err); } } function checkLedger(baseTransaction, callback) { serverLib.remoteHasLedger(api.remote, baseTransaction.ledger_index, function(error, remoteHasLedger) { if (error) { return callback(error); } if (remoteHasLedger) { callback(null, baseTransaction); } else { callback(new errors.NotFoundError('Cannot Get Notification. ' + 'This transaction is not in the ripple\'s complete ledger set. ' + 'Because there is a gap in the rippled\'s historical database it ' + 'is not possible to determine the transactions that precede this one') ); } }); } function prepareNotificationDetails(baseTransaction, callback) { var notificationDetails = { account: account, identifier: identifier, transaction: baseTransaction }; // Move client_resource_id to notificationDetails from transaction if (baseTransaction.client_resource_id) { notificationDetails.client_resource_id = baseTransaction.client_resource_id; } attachPreviousAndNextTransactionIdentifiers(api, notificationDetails, callback); } // Parse the Notification object from the notificationDetails function parseNotificationDetails(notificationDetails, callback) { callback(null, NotificationParser.parse(notificationDetails, urlBase)); } function formatNotificationResponse(notificationDetails, callback) { var responseBody = { notification: notificationDetails }; // Move client_resource_id to response body instead of inside // the Notification var client_resource_id = responseBody.notification.client_resource_id; delete responseBody.notification.client_resource_id; if (client_resource_id) { responseBody.client_resource_id = client_resource_id; } callback(null, responseBody); } var steps = [ getTransaction, checkLedger, prepareNotificationDetails, parseNotificationDetails, formatNotificationResponse ]; async.waterfall(steps, topCallback); }
javascript
function getNotificationHelper(api, account, identifier, urlBase, topCallback) { function getTransaction(callback) { try { transactions.getTransaction(api, account, identifier, {}, callback); } catch(err) { callback(err); } } function checkLedger(baseTransaction, callback) { serverLib.remoteHasLedger(api.remote, baseTransaction.ledger_index, function(error, remoteHasLedger) { if (error) { return callback(error); } if (remoteHasLedger) { callback(null, baseTransaction); } else { callback(new errors.NotFoundError('Cannot Get Notification. ' + 'This transaction is not in the ripple\'s complete ledger set. ' + 'Because there is a gap in the rippled\'s historical database it ' + 'is not possible to determine the transactions that precede this one') ); } }); } function prepareNotificationDetails(baseTransaction, callback) { var notificationDetails = { account: account, identifier: identifier, transaction: baseTransaction }; // Move client_resource_id to notificationDetails from transaction if (baseTransaction.client_resource_id) { notificationDetails.client_resource_id = baseTransaction.client_resource_id; } attachPreviousAndNextTransactionIdentifiers(api, notificationDetails, callback); } // Parse the Notification object from the notificationDetails function parseNotificationDetails(notificationDetails, callback) { callback(null, NotificationParser.parse(notificationDetails, urlBase)); } function formatNotificationResponse(notificationDetails, callback) { var responseBody = { notification: notificationDetails }; // Move client_resource_id to response body instead of inside // the Notification var client_resource_id = responseBody.notification.client_resource_id; delete responseBody.notification.client_resource_id; if (client_resource_id) { responseBody.client_resource_id = client_resource_id; } callback(null, responseBody); } var steps = [ getTransaction, checkLedger, prepareNotificationDetails, parseNotificationDetails, formatNotificationResponse ]; async.waterfall(steps, topCallback); }
[ "function", "getNotificationHelper", "(", "api", ",", "account", ",", "identifier", ",", "urlBase", ",", "topCallback", ")", "{", "function", "getTransaction", "(", "callback", ")", "{", "try", "{", "transactions", ".", "getTransaction", "(", "api", ",", "account", ",", "identifier", ",", "{", "}", ",", "callback", ")", ";", "}", "catch", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", "}", "function", "checkLedger", "(", "baseTransaction", ",", "callback", ")", "{", "serverLib", ".", "remoteHasLedger", "(", "api", ".", "remote", ",", "baseTransaction", ".", "ledger_index", ",", "function", "(", "error", ",", "remoteHasLedger", ")", "{", "if", "(", "error", ")", "{", "return", "callback", "(", "error", ")", ";", "}", "if", "(", "remoteHasLedger", ")", "{", "callback", "(", "null", ",", "baseTransaction", ")", ";", "}", "else", "{", "callback", "(", "new", "errors", ".", "NotFoundError", "(", "'Cannot Get Notification. '", "+", "'This transaction is not in the ripple\\'s complete ledger set. '", "+", "'Because there is a gap in the rippled\\'s historical database it '", "+", "'is not possible to determine the transactions that precede this one'", ")", ")", ";", "}", "}", ")", ";", "}", "function", "prepareNotificationDetails", "(", "baseTransaction", ",", "callback", ")", "{", "var", "notificationDetails", "=", "{", "account", ":", "account", ",", "identifier", ":", "identifier", ",", "transaction", ":", "baseTransaction", "}", ";", "// Move client_resource_id to notificationDetails from transaction", "if", "(", "baseTransaction", ".", "client_resource_id", ")", "{", "notificationDetails", ".", "client_resource_id", "=", "baseTransaction", ".", "client_resource_id", ";", "}", "attachPreviousAndNextTransactionIdentifiers", "(", "api", ",", "notificationDetails", ",", "callback", ")", ";", "}", "// Parse the Notification object from the notificationDetails", "function", "parseNotificationDetails", "(", "notificationDetails", ",", "callback", ")", "{", "callback", "(", "null", ",", "NotificationParser", ".", "parse", "(", "notificationDetails", ",", "urlBase", ")", ")", ";", "}", "function", "formatNotificationResponse", "(", "notificationDetails", ",", "callback", ")", "{", "var", "responseBody", "=", "{", "notification", ":", "notificationDetails", "}", ";", "// Move client_resource_id to response body instead of inside", "// the Notification", "var", "client_resource_id", "=", "responseBody", ".", "notification", ".", "client_resource_id", ";", "delete", "responseBody", ".", "notification", ".", "client_resource_id", ";", "if", "(", "client_resource_id", ")", "{", "responseBody", ".", "client_resource_id", "=", "client_resource_id", ";", "}", "callback", "(", "null", ",", "responseBody", ")", ";", "}", "var", "steps", "=", "[", "getTransaction", ",", "checkLedger", ",", "prepareNotificationDetails", ",", "parseNotificationDetails", ",", "formatNotificationResponse", "]", ";", "async", ".", "waterfall", "(", "steps", ",", "topCallback", ")", ";", "}" ]
Get a notification corresponding to the specified account and transaction identifier. Send errors back to the client using the res.json method or pass the notification json to the callback function. @param {Remote} $.remote @param {/lib/db-interface} $.dbinterface @param {RippleAddress} req.params.account @param {Hex-encoded String|ResourceId} req.params.identifier @param {Express.js Response} res @param {Function} callback @callback @param {Error} error @param {Notification} notification
[ "Get", "a", "notification", "corresponding", "to", "the", "specified", "account", "and", "transaction", "identifier", ".", "Send", "errors", "back", "to", "the", "client", "using", "the", "res", ".", "json", "method", "or", "pass", "the", "notification", "json", "to", "the", "callback", "function", "." ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/notifications.js#L170-L245
21,615
ripple/ripple-rest
api/notifications.js
getNotification
function getNotification(account, identifier, urlBase, callback) { validate.address(account); validate.paymentIdentifier(identifier); return getNotificationHelper(this, account, identifier, urlBase, callback); }
javascript
function getNotification(account, identifier, urlBase, callback) { validate.address(account); validate.paymentIdentifier(identifier); return getNotificationHelper(this, account, identifier, urlBase, callback); }
[ "function", "getNotification", "(", "account", ",", "identifier", ",", "urlBase", ",", "callback", ")", "{", "validate", ".", "address", "(", "account", ")", ";", "validate", ".", "paymentIdentifier", "(", "identifier", ")", ";", "return", "getNotificationHelper", "(", "this", ",", "account", ",", "identifier", ",", "urlBase", ",", "callback", ")", ";", "}" ]
Get a notification corresponding to the specified account and transaction identifier. Uses the res.json method to send errors or a notification back to the client. @param {Remote} $.remote @param {/lib/db-interface} $.dbinterface @param {/lib/config-loader} $.config @param {RippleAddress} req.params.account @param {Hex-encoded String|ResourceId} req.params.identifier
[ "Get", "a", "notification", "corresponding", "to", "the", "specified", "account", "and", "transaction", "identifier", ".", "Uses", "the", "res", ".", "json", "method", "to", "send", "errors", "or", "a", "notification", "back", "to", "the", "client", "." ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/notifications.js#L258-L263
21,616
ripple/ripple-rest
api/notifications.js
getNotifications
function getNotifications(account, urlBase, options, callback) { validate.address(account); var self = this; function getTransactions(_callback) { var resultsPerPage = options.results_per_page || transactions.DEFAULT_RESULTS_PER_PAGE; var offset = resultsPerPage * ((options.page || 1) - 1); var args = { account: account, direction: options.direction, min: resultsPerPage, max: resultsPerPage, ledger_index_min: options.ledger_min, ledger_index_max: options.ledger_max, offset: offset, earliestFirst: options.earliest_first }; transactions.getAccountTransactions(self, args, _callback); } function parseNotifications(baseTransactions, _callback) { var numTransactions = baseTransactions.length; function parseNotification(transaction, __callback) { var args = { account: account, identifier: transaction.hash, transaction: transaction }; // Attaching previous and next identifiers var idx = baseTransactions.indexOf(transaction); var previous = baseTransactions[idx - 1]; var next = baseTransactions[idx + 1]; if (!options.earliest_first) { args.previous_hash = previous ? previous.hash : undefined; args.next_hash = next ? next.hash : undefined; } else { args.previous_hash = next ? next.hash : undefined; args.next_hash = previous ? previous.hash : undefined; } args.previous_transaction_identifier = args.previous_hash; args.next_transaction_identifier = args.next_hash; var firstAndPaging = options.page && (options.earliest_first ? args.previous_hash === undefined : args.next_hash === undefined); var last = idx === numTransactions - 1; if (firstAndPaging || last) { attachPreviousAndNextTransactionIdentifiers(self, args, function(err, _args) { return __callback(err, NotificationParser.parse(_args, urlBase)); } ); } else { return __callback(null, NotificationParser.parse(args, urlBase)); } } return async.map(baseTransactions, parseNotification, _callback); } function formatResponse(notifications, _callback) { _callback(null, {notifications: notifications}); } var steps = [ getTransactions, _.partial(utils.attachDate, self), parseNotifications, formatResponse ]; return async.waterfall(steps, callback); }
javascript
function getNotifications(account, urlBase, options, callback) { validate.address(account); var self = this; function getTransactions(_callback) { var resultsPerPage = options.results_per_page || transactions.DEFAULT_RESULTS_PER_PAGE; var offset = resultsPerPage * ((options.page || 1) - 1); var args = { account: account, direction: options.direction, min: resultsPerPage, max: resultsPerPage, ledger_index_min: options.ledger_min, ledger_index_max: options.ledger_max, offset: offset, earliestFirst: options.earliest_first }; transactions.getAccountTransactions(self, args, _callback); } function parseNotifications(baseTransactions, _callback) { var numTransactions = baseTransactions.length; function parseNotification(transaction, __callback) { var args = { account: account, identifier: transaction.hash, transaction: transaction }; // Attaching previous and next identifiers var idx = baseTransactions.indexOf(transaction); var previous = baseTransactions[idx - 1]; var next = baseTransactions[idx + 1]; if (!options.earliest_first) { args.previous_hash = previous ? previous.hash : undefined; args.next_hash = next ? next.hash : undefined; } else { args.previous_hash = next ? next.hash : undefined; args.next_hash = previous ? previous.hash : undefined; } args.previous_transaction_identifier = args.previous_hash; args.next_transaction_identifier = args.next_hash; var firstAndPaging = options.page && (options.earliest_first ? args.previous_hash === undefined : args.next_hash === undefined); var last = idx === numTransactions - 1; if (firstAndPaging || last) { attachPreviousAndNextTransactionIdentifiers(self, args, function(err, _args) { return __callback(err, NotificationParser.parse(_args, urlBase)); } ); } else { return __callback(null, NotificationParser.parse(args, urlBase)); } } return async.map(baseTransactions, parseNotification, _callback); } function formatResponse(notifications, _callback) { _callback(null, {notifications: notifications}); } var steps = [ getTransactions, _.partial(utils.attachDate, self), parseNotifications, formatResponse ]; return async.waterfall(steps, callback); }
[ "function", "getNotifications", "(", "account", ",", "urlBase", ",", "options", ",", "callback", ")", "{", "validate", ".", "address", "(", "account", ")", ";", "var", "self", "=", "this", ";", "function", "getTransactions", "(", "_callback", ")", "{", "var", "resultsPerPage", "=", "options", ".", "results_per_page", "||", "transactions", ".", "DEFAULT_RESULTS_PER_PAGE", ";", "var", "offset", "=", "resultsPerPage", "*", "(", "(", "options", ".", "page", "||", "1", ")", "-", "1", ")", ";", "var", "args", "=", "{", "account", ":", "account", ",", "direction", ":", "options", ".", "direction", ",", "min", ":", "resultsPerPage", ",", "max", ":", "resultsPerPage", ",", "ledger_index_min", ":", "options", ".", "ledger_min", ",", "ledger_index_max", ":", "options", ".", "ledger_max", ",", "offset", ":", "offset", ",", "earliestFirst", ":", "options", ".", "earliest_first", "}", ";", "transactions", ".", "getAccountTransactions", "(", "self", ",", "args", ",", "_callback", ")", ";", "}", "function", "parseNotifications", "(", "baseTransactions", ",", "_callback", ")", "{", "var", "numTransactions", "=", "baseTransactions", ".", "length", ";", "function", "parseNotification", "(", "transaction", ",", "__callback", ")", "{", "var", "args", "=", "{", "account", ":", "account", ",", "identifier", ":", "transaction", ".", "hash", ",", "transaction", ":", "transaction", "}", ";", "// Attaching previous and next identifiers", "var", "idx", "=", "baseTransactions", ".", "indexOf", "(", "transaction", ")", ";", "var", "previous", "=", "baseTransactions", "[", "idx", "-", "1", "]", ";", "var", "next", "=", "baseTransactions", "[", "idx", "+", "1", "]", ";", "if", "(", "!", "options", ".", "earliest_first", ")", "{", "args", ".", "previous_hash", "=", "previous", "?", "previous", ".", "hash", ":", "undefined", ";", "args", ".", "next_hash", "=", "next", "?", "next", ".", "hash", ":", "undefined", ";", "}", "else", "{", "args", ".", "previous_hash", "=", "next", "?", "next", ".", "hash", ":", "undefined", ";", "args", ".", "next_hash", "=", "previous", "?", "previous", ".", "hash", ":", "undefined", ";", "}", "args", ".", "previous_transaction_identifier", "=", "args", ".", "previous_hash", ";", "args", ".", "next_transaction_identifier", "=", "args", ".", "next_hash", ";", "var", "firstAndPaging", "=", "options", ".", "page", "&&", "(", "options", ".", "earliest_first", "?", "args", ".", "previous_hash", "===", "undefined", ":", "args", ".", "next_hash", "===", "undefined", ")", ";", "var", "last", "=", "idx", "===", "numTransactions", "-", "1", ";", "if", "(", "firstAndPaging", "||", "last", ")", "{", "attachPreviousAndNextTransactionIdentifiers", "(", "self", ",", "args", ",", "function", "(", "err", ",", "_args", ")", "{", "return", "__callback", "(", "err", ",", "NotificationParser", ".", "parse", "(", "_args", ",", "urlBase", ")", ")", ";", "}", ")", ";", "}", "else", "{", "return", "__callback", "(", "null", ",", "NotificationParser", ".", "parse", "(", "args", ",", "urlBase", ")", ")", ";", "}", "}", "return", "async", ".", "map", "(", "baseTransactions", ",", "parseNotification", ",", "_callback", ")", ";", "}", "function", "formatResponse", "(", "notifications", ",", "_callback", ")", "{", "_callback", "(", "null", ",", "{", "notifications", ":", "notifications", "}", ")", ";", "}", "var", "steps", "=", "[", "getTransactions", ",", "_", ".", "partial", "(", "utils", ".", "attachDate", ",", "self", ")", ",", "parseNotifications", ",", "formatResponse", "]", ";", "return", "async", ".", "waterfall", "(", "steps", ",", "callback", ")", ";", "}" ]
Get a notifications corresponding to the specified account. This function calls transactions.getAccountTransactions recursively to retrieve results_per_page number of transactions and filters the results using client-specified parameters. @param {RippleAddress} account @param {string} urlBase - The url to use for the transaction status URL @param {string} options.source_account @param {Number} options.ledger_min @param {Number} options.ledger_max @param {string} [false] options.earliest_first @param {string[]} options.types - @see transactions.getAccountTransactions TODO: If given ledger range, check for ledger gaps
[ "Get", "a", "notifications", "corresponding", "to", "the", "specified", "account", "." ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/notifications.js#L284-L367
21,617
ripple/ripple-rest
api/settings.js
getSettings
function getSettings(account, callback) { validate.address(account); this.remote.requestAccountInfo({account: account}, function(error, info) { if (error) { return callback(error); } var data = info.account_data; var settings = { account: data.Account, transfer_rate: '0' }; // Attach account flags _.extend(settings, TxToRestConverter.parseFlagsFromResponse(data.Flags, constants.AccountRootFlags)); // Attach account fields _.extend(settings, parseFieldsFromResponse(data, constants.AccountRootFields)); settings.transaction_sequence = String(settings.transaction_sequence); callback(null, {settings: settings}); }); }
javascript
function getSettings(account, callback) { validate.address(account); this.remote.requestAccountInfo({account: account}, function(error, info) { if (error) { return callback(error); } var data = info.account_data; var settings = { account: data.Account, transfer_rate: '0' }; // Attach account flags _.extend(settings, TxToRestConverter.parseFlagsFromResponse(data.Flags, constants.AccountRootFlags)); // Attach account fields _.extend(settings, parseFieldsFromResponse(data, constants.AccountRootFields)); settings.transaction_sequence = String(settings.transaction_sequence); callback(null, {settings: settings}); }); }
[ "function", "getSettings", "(", "account", ",", "callback", ")", "{", "validate", ".", "address", "(", "account", ")", ";", "this", ".", "remote", ".", "requestAccountInfo", "(", "{", "account", ":", "account", "}", ",", "function", "(", "error", ",", "info", ")", "{", "if", "(", "error", ")", "{", "return", "callback", "(", "error", ")", ";", "}", "var", "data", "=", "info", ".", "account_data", ";", "var", "settings", "=", "{", "account", ":", "data", ".", "Account", ",", "transfer_rate", ":", "'0'", "}", ";", "// Attach account flags", "_", ".", "extend", "(", "settings", ",", "TxToRestConverter", ".", "parseFlagsFromResponse", "(", "data", ".", "Flags", ",", "constants", ".", "AccountRootFlags", ")", ")", ";", "// Attach account fields", "_", ".", "extend", "(", "settings", ",", "parseFieldsFromResponse", "(", "data", ",", "constants", ".", "AccountRootFields", ")", ")", ";", "settings", ".", "transaction_sequence", "=", "String", "(", "settings", ".", "transaction_sequence", ")", ";", "callback", "(", "null", ",", "{", "settings", ":", "settings", "}", ")", ";", "}", ")", ";", "}" ]
Retrieves account settings for a given account @url @param {String} request.params.account
[ "Retrieves", "account", "settings", "for", "a", "given", "account" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/settings.js#L34-L60
21,618
ripple/ripple-rest
api/settings.js
changeSettings
function changeSettings(account, settings, secret, options, callback) { var transaction = createSettingsTransaction(account, settings); var converter = _.partial( TxToRestConverter.parseSettingsResponseFromTx, settings); transact(transaction, this, secret, options, converter, callback); }
javascript
function changeSettings(account, settings, secret, options, callback) { var transaction = createSettingsTransaction(account, settings); var converter = _.partial( TxToRestConverter.parseSettingsResponseFromTx, settings); transact(transaction, this, secret, options, converter, callback); }
[ "function", "changeSettings", "(", "account", ",", "settings", ",", "secret", ",", "options", ",", "callback", ")", "{", "var", "transaction", "=", "createSettingsTransaction", "(", "account", ",", "settings", ")", ";", "var", "converter", "=", "_", ".", "partial", "(", "TxToRestConverter", ".", "parseSettingsResponseFromTx", ",", "settings", ")", ";", "transact", "(", "transaction", ",", "this", ",", "secret", ",", "options", ",", "converter", ",", "callback", ")", ";", "}" ]
Change account settings @body @param {Settings} request.body.settings @param {String} request.body.secret @query @param {String "true"|"false"} request.query.validated Used to force request to wait until rippled has finished validating the submitted transaction
[ "Change", "account", "settings" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/settings.js#L74-L79
21,619
ripple/ripple-rest
api/transaction/utils.js
setTransactionBitFlags
function setTransactionBitFlags(transaction, options) { for (var flagName in options.flags) { var flag = options.flags[flagName]; // Set transaction flags if (!(flag.name in options.input)) { continue; } var value = options.input[flag.name]; if (value === options.clear_setting) { value = false; } if (flag.unset) { transaction.setFlags(value ? flag.set : flag.unset); } else if (flag.set && value) { transaction.setFlags(flag.set); } } }
javascript
function setTransactionBitFlags(transaction, options) { for (var flagName in options.flags) { var flag = options.flags[flagName]; // Set transaction flags if (!(flag.name in options.input)) { continue; } var value = options.input[flag.name]; if (value === options.clear_setting) { value = false; } if (flag.unset) { transaction.setFlags(value ? flag.set : flag.unset); } else if (flag.set && value) { transaction.setFlags(flag.set); } } }
[ "function", "setTransactionBitFlags", "(", "transaction", ",", "options", ")", "{", "for", "(", "var", "flagName", "in", "options", ".", "flags", ")", "{", "var", "flag", "=", "options", ".", "flags", "[", "flagName", "]", ";", "// Set transaction flags", "if", "(", "!", "(", "flag", ".", "name", "in", "options", ".", "input", ")", ")", "{", "continue", ";", "}", "var", "value", "=", "options", ".", "input", "[", "flag", ".", "name", "]", ";", "if", "(", "value", "===", "options", ".", "clear_setting", ")", "{", "value", "=", "false", ";", "}", "if", "(", "flag", ".", "unset", ")", "{", "transaction", ".", "setFlags", "(", "value", "?", "flag", ".", "set", ":", "flag", ".", "unset", ")", ";", "}", "else", "if", "(", "flag", ".", "set", "&&", "value", ")", "{", "transaction", ".", "setFlags", "(", "flag", ".", "set", ")", ";", "}", "}", "}" ]
Helper that sets bit flags on transactions @param {Transaction} transaction - Transaction object that is used to submit requests to ripple @param {Object} options @param {Object} options.flags - Holds flag names to set on transaction when parameter values are true or false on input @param {Object} options.input - Holds parameter values @param {String} options.clear_setting - Used to check if parameter values besides false mean false @returns undefined
[ "Helper", "that", "sets", "bit", "flags", "on", "transactions" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/transaction/utils.js#L36-L57
21,620
ripple/ripple-rest
api/payments.js
formatPaymentHelper
function formatPaymentHelper(account, txJSON) { if (!(txJSON && /^payment$/i.test(txJSON.TransactionType))) { throw new InvalidRequestError('Not a payment. The transaction ' + 'corresponding to the given identifier is not a payment.'); } var metadata = { client_resource_id: txJSON.client_resource_id || '', hash: txJSON.hash || '', ledger: String(!_.isUndefined(txJSON.inLedger) ? txJSON.inLedger : txJSON.ledger_index), state: txJSON.validated === true ? 'validated' : 'pending' }; var message = {tx_json: txJSON}; var meta = txJSON.meta; var parsed = TxToRestConverter.parsePaymentFromTx(account, message, meta); return _.assign({payment: parsed.payment}, metadata); }
javascript
function formatPaymentHelper(account, txJSON) { if (!(txJSON && /^payment$/i.test(txJSON.TransactionType))) { throw new InvalidRequestError('Not a payment. The transaction ' + 'corresponding to the given identifier is not a payment.'); } var metadata = { client_resource_id: txJSON.client_resource_id || '', hash: txJSON.hash || '', ledger: String(!_.isUndefined(txJSON.inLedger) ? txJSON.inLedger : txJSON.ledger_index), state: txJSON.validated === true ? 'validated' : 'pending' }; var message = {tx_json: txJSON}; var meta = txJSON.meta; var parsed = TxToRestConverter.parsePaymentFromTx(account, message, meta); return _.assign({payment: parsed.payment}, metadata); }
[ "function", "formatPaymentHelper", "(", "account", ",", "txJSON", ")", "{", "if", "(", "!", "(", "txJSON", "&&", "/", "^payment$", "/", "i", ".", "test", "(", "txJSON", ".", "TransactionType", ")", ")", ")", "{", "throw", "new", "InvalidRequestError", "(", "'Not a payment. The transaction '", "+", "'corresponding to the given identifier is not a payment.'", ")", ";", "}", "var", "metadata", "=", "{", "client_resource_id", ":", "txJSON", ".", "client_resource_id", "||", "''", ",", "hash", ":", "txJSON", ".", "hash", "||", "''", ",", "ledger", ":", "String", "(", "!", "_", ".", "isUndefined", "(", "txJSON", ".", "inLedger", ")", "?", "txJSON", ".", "inLedger", ":", "txJSON", ".", "ledger_index", ")", ",", "state", ":", "txJSON", ".", "validated", "===", "true", "?", "'validated'", ":", "'pending'", "}", ";", "var", "message", "=", "{", "tx_json", ":", "txJSON", "}", ";", "var", "meta", "=", "txJSON", ".", "meta", ";", "var", "parsed", "=", "TxToRestConverter", ".", "parsePaymentFromTx", "(", "account", ",", "message", ",", "meta", ")", ";", "return", "_", ".", "assign", "(", "{", "payment", ":", "parsed", ".", "payment", "}", ",", "metadata", ")", ";", "}" ]
Formats the local database transaction into ripple-rest Payment format @param {RippleAddress} account @param {Transaction} transaction @param {Function} callback @callback @param {Error} error @param {RippleRestTransaction} transaction
[ "Formats", "the", "local", "database", "transaction", "into", "ripple", "-", "rest", "Payment", "format" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/payments.js#L41-L57
21,621
ripple/ripple-rest
api/payments.js
submitPayment
function submitPayment(account, payment, clientResourceID, secret, urlBase, options, callback) { function formatTransactionResponse(message, meta) { if (meta.state === 'validated') { var txJSON = message.tx_json; txJSON.meta = message.metadata; txJSON.validated = message.validated; txJSON.ledger_index = txJSON.inLedger = message.ledger_index; return formatPaymentHelper(payment.source_account, txJSON); } return { client_resource_id: clientResourceID, status_url: urlBase + '/v1/accounts/' + payment.source_account + '/payments/' + clientResourceID }; } function prepareTransaction(_transaction, remote) { validate.client_resource_id(clientResourceID); _transaction.lastLedger(Number(options.last_ledger_sequence || (remote.getLedgerSequence() + transactions.DEFAULT_LEDGER_BUFFER))); if (Number(options.max_fee) >= 0) { _transaction.maxFee(Number(xrpToDrops(options.max_fee))); } if (Number(options.fixed_fee) >= 0) { _transaction.setFixedFee(Number(xrpToDrops(options.fixed_fee))); } _transaction.clientID(clientResourceID); return _transaction; } var isSubmitMode = options.submit !== false; var _options = _.assign({}, options, { clientResourceId: clientResourceID, blockDuplicates: isSubmitMode, saveTransaction: isSubmitMode }); var initialTx = createPaymentTransaction(account, payment); var transaction = isSubmitMode ? prepareTransaction( initialTx, this.remote) : initialTx; var converter = isSubmitMode ? formatTransactionResponse : _.partial(TxToRestConverter.parsePaymentFromTx, account); transact(transaction, this, secret, _options, converter, callback); }
javascript
function submitPayment(account, payment, clientResourceID, secret, urlBase, options, callback) { function formatTransactionResponse(message, meta) { if (meta.state === 'validated') { var txJSON = message.tx_json; txJSON.meta = message.metadata; txJSON.validated = message.validated; txJSON.ledger_index = txJSON.inLedger = message.ledger_index; return formatPaymentHelper(payment.source_account, txJSON); } return { client_resource_id: clientResourceID, status_url: urlBase + '/v1/accounts/' + payment.source_account + '/payments/' + clientResourceID }; } function prepareTransaction(_transaction, remote) { validate.client_resource_id(clientResourceID); _transaction.lastLedger(Number(options.last_ledger_sequence || (remote.getLedgerSequence() + transactions.DEFAULT_LEDGER_BUFFER))); if (Number(options.max_fee) >= 0) { _transaction.maxFee(Number(xrpToDrops(options.max_fee))); } if (Number(options.fixed_fee) >= 0) { _transaction.setFixedFee(Number(xrpToDrops(options.fixed_fee))); } _transaction.clientID(clientResourceID); return _transaction; } var isSubmitMode = options.submit !== false; var _options = _.assign({}, options, { clientResourceId: clientResourceID, blockDuplicates: isSubmitMode, saveTransaction: isSubmitMode }); var initialTx = createPaymentTransaction(account, payment); var transaction = isSubmitMode ? prepareTransaction( initialTx, this.remote) : initialTx; var converter = isSubmitMode ? formatTransactionResponse : _.partial(TxToRestConverter.parsePaymentFromTx, account); transact(transaction, this, secret, _options, converter, callback); }
[ "function", "submitPayment", "(", "account", ",", "payment", ",", "clientResourceID", ",", "secret", ",", "urlBase", ",", "options", ",", "callback", ")", "{", "function", "formatTransactionResponse", "(", "message", ",", "meta", ")", "{", "if", "(", "meta", ".", "state", "===", "'validated'", ")", "{", "var", "txJSON", "=", "message", ".", "tx_json", ";", "txJSON", ".", "meta", "=", "message", ".", "metadata", ";", "txJSON", ".", "validated", "=", "message", ".", "validated", ";", "txJSON", ".", "ledger_index", "=", "txJSON", ".", "inLedger", "=", "message", ".", "ledger_index", ";", "return", "formatPaymentHelper", "(", "payment", ".", "source_account", ",", "txJSON", ")", ";", "}", "return", "{", "client_resource_id", ":", "clientResourceID", ",", "status_url", ":", "urlBase", "+", "'/v1/accounts/'", "+", "payment", ".", "source_account", "+", "'/payments/'", "+", "clientResourceID", "}", ";", "}", "function", "prepareTransaction", "(", "_transaction", ",", "remote", ")", "{", "validate", ".", "client_resource_id", "(", "clientResourceID", ")", ";", "_transaction", ".", "lastLedger", "(", "Number", "(", "options", ".", "last_ledger_sequence", "||", "(", "remote", ".", "getLedgerSequence", "(", ")", "+", "transactions", ".", "DEFAULT_LEDGER_BUFFER", ")", ")", ")", ";", "if", "(", "Number", "(", "options", ".", "max_fee", ")", ">=", "0", ")", "{", "_transaction", ".", "maxFee", "(", "Number", "(", "xrpToDrops", "(", "options", ".", "max_fee", ")", ")", ")", ";", "}", "if", "(", "Number", "(", "options", ".", "fixed_fee", ")", ">=", "0", ")", "{", "_transaction", ".", "setFixedFee", "(", "Number", "(", "xrpToDrops", "(", "options", ".", "fixed_fee", ")", ")", ")", ";", "}", "_transaction", ".", "clientID", "(", "clientResourceID", ")", ";", "return", "_transaction", ";", "}", "var", "isSubmitMode", "=", "options", ".", "submit", "!==", "false", ";", "var", "_options", "=", "_", ".", "assign", "(", "{", "}", ",", "options", ",", "{", "clientResourceId", ":", "clientResourceID", ",", "blockDuplicates", ":", "isSubmitMode", ",", "saveTransaction", ":", "isSubmitMode", "}", ")", ";", "var", "initialTx", "=", "createPaymentTransaction", "(", "account", ",", "payment", ")", ";", "var", "transaction", "=", "isSubmitMode", "?", "prepareTransaction", "(", "initialTx", ",", "this", ".", "remote", ")", ":", "initialTx", ";", "var", "converter", "=", "isSubmitMode", "?", "formatTransactionResponse", ":", "_", ".", "partial", "(", "TxToRestConverter", ".", "parsePaymentFromTx", ",", "account", ")", ";", "transact", "(", "transaction", ",", "this", ",", "secret", ",", "_options", ",", "converter", ",", "callback", ")", ";", "}" ]
Submit a payment in the ripple-rest format. @global @param {/config/config-loader} config @body @param {Payment} request.body.payment @param {String} request.body.secret @param {String} request.body.client_resource_id @param {Number String} req.body.last_ledger_sequence - last ledger sequence that this payment can end up in @param {Number String} req.body.max_fee - maximum fee the payer is willing to pay @param {Number String} req.body.fixed_fee - fixed fee the payer wants to pay the network for accepting this transaction @query @param {String "true"|"false"} request.query.validated - used to force request to wait until rippled has finished validating the submitted transaction
[ "Submit", "a", "payment", "in", "the", "ripple", "-", "rest", "format", "." ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/payments.js#L81-L131
21,622
ripple/ripple-rest
api/payments.js
getPayment
function getPayment(account, identifier, callback) { var self = this; validate.address(account); validate.paymentIdentifier(identifier); // If the transaction was not in the outgoing_transactions db, // get it from rippled function getTransaction(_callback) { transactions.getTransaction(self, account, identifier, {}, _callback); } var steps = [ getTransaction, asyncify(_.partial(formatPaymentHelper, account)) ]; async.waterfall(steps, callback); }
javascript
function getPayment(account, identifier, callback) { var self = this; validate.address(account); validate.paymentIdentifier(identifier); // If the transaction was not in the outgoing_transactions db, // get it from rippled function getTransaction(_callback) { transactions.getTransaction(self, account, identifier, {}, _callback); } var steps = [ getTransaction, asyncify(_.partial(formatPaymentHelper, account)) ]; async.waterfall(steps, callback); }
[ "function", "getPayment", "(", "account", ",", "identifier", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "validate", ".", "address", "(", "account", ")", ";", "validate", ".", "paymentIdentifier", "(", "identifier", ")", ";", "// If the transaction was not in the outgoing_transactions db,", "// get it from rippled", "function", "getTransaction", "(", "_callback", ")", "{", "transactions", ".", "getTransaction", "(", "self", ",", "account", ",", "identifier", ",", "{", "}", ",", "_callback", ")", ";", "}", "var", "steps", "=", "[", "getTransaction", ",", "asyncify", "(", "_", ".", "partial", "(", "formatPaymentHelper", ",", "account", ")", ")", "]", ";", "async", ".", "waterfall", "(", "steps", ",", "callback", ")", ";", "}" ]
Retrieve the details of a particular payment from the Remote or the local database and return it in the ripple-rest Payment format. @param {Remote} remote @param {/lib/db-interface} dbinterface @param {RippleAddress} req.params.account @param {Hex-encoded String|ASCII printable character String} req.params.identifier
[ "Retrieve", "the", "details", "of", "a", "particular", "payment", "from", "the", "Remote", "or", "the", "local", "database", "and", "return", "it", "in", "the", "ripple", "-", "rest", "Payment", "format", "." ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/payments.js#L143-L161
21,623
ripple/ripple-rest
api/payments.js
getAccountPayments
function getAccountPayments(account, source_account, destination_account, direction, options, callback) { var self = this; function getTransactions(_callback) { var args = { account: account, source_account: source_account, destination_account: destination_account, direction: direction, min: options.results_per_page, max: options.results_per_page, offset: (options.results_per_page || DEFAULT_RESULTS_PER_PAGE) * ((options.page || 1) - 1), types: ['payment'], earliestFirst: options.earliest_first }; transactions.getAccountTransactions(self, _.merge(options, args), _callback); } function formatTransactions(_transactions) { return _transactions.map(_.partial(formatPaymentHelper, account)); } function attachResourceId(_transactions, _callback) { async.map(_transactions, function(paymentResult, async_map_callback) { var hash = paymentResult.hash; self.db.getTransaction({hash: hash}, function(error, db_entry) { if (error) { return async_map_callback(error); } var client_resource_id = ''; if (db_entry && db_entry.client_resource_id) { client_resource_id = db_entry.client_resource_id; } paymentResult.client_resource_id = client_resource_id; async_map_callback(null, paymentResult); }); }, _callback); } function formatResponse(_transactions) { return {payments: _transactions}; } var steps = [ getTransactions, _.partial(utils.attachDate, self), asyncify(formatTransactions), attachResourceId, asyncify(formatResponse) ]; async.waterfall(steps, callback); }
javascript
function getAccountPayments(account, source_account, destination_account, direction, options, callback) { var self = this; function getTransactions(_callback) { var args = { account: account, source_account: source_account, destination_account: destination_account, direction: direction, min: options.results_per_page, max: options.results_per_page, offset: (options.results_per_page || DEFAULT_RESULTS_PER_PAGE) * ((options.page || 1) - 1), types: ['payment'], earliestFirst: options.earliest_first }; transactions.getAccountTransactions(self, _.merge(options, args), _callback); } function formatTransactions(_transactions) { return _transactions.map(_.partial(formatPaymentHelper, account)); } function attachResourceId(_transactions, _callback) { async.map(_transactions, function(paymentResult, async_map_callback) { var hash = paymentResult.hash; self.db.getTransaction({hash: hash}, function(error, db_entry) { if (error) { return async_map_callback(error); } var client_resource_id = ''; if (db_entry && db_entry.client_resource_id) { client_resource_id = db_entry.client_resource_id; } paymentResult.client_resource_id = client_resource_id; async_map_callback(null, paymentResult); }); }, _callback); } function formatResponse(_transactions) { return {payments: _transactions}; } var steps = [ getTransactions, _.partial(utils.attachDate, self), asyncify(formatTransactions), attachResourceId, asyncify(formatResponse) ]; async.waterfall(steps, callback); }
[ "function", "getAccountPayments", "(", "account", ",", "source_account", ",", "destination_account", ",", "direction", ",", "options", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "function", "getTransactions", "(", "_callback", ")", "{", "var", "args", "=", "{", "account", ":", "account", ",", "source_account", ":", "source_account", ",", "destination_account", ":", "destination_account", ",", "direction", ":", "direction", ",", "min", ":", "options", ".", "results_per_page", ",", "max", ":", "options", ".", "results_per_page", ",", "offset", ":", "(", "options", ".", "results_per_page", "||", "DEFAULT_RESULTS_PER_PAGE", ")", "*", "(", "(", "options", ".", "page", "||", "1", ")", "-", "1", ")", ",", "types", ":", "[", "'payment'", "]", ",", "earliestFirst", ":", "options", ".", "earliest_first", "}", ";", "transactions", ".", "getAccountTransactions", "(", "self", ",", "_", ".", "merge", "(", "options", ",", "args", ")", ",", "_callback", ")", ";", "}", "function", "formatTransactions", "(", "_transactions", ")", "{", "return", "_transactions", ".", "map", "(", "_", ".", "partial", "(", "formatPaymentHelper", ",", "account", ")", ")", ";", "}", "function", "attachResourceId", "(", "_transactions", ",", "_callback", ")", "{", "async", ".", "map", "(", "_transactions", ",", "function", "(", "paymentResult", ",", "async_map_callback", ")", "{", "var", "hash", "=", "paymentResult", ".", "hash", ";", "self", ".", "db", ".", "getTransaction", "(", "{", "hash", ":", "hash", "}", ",", "function", "(", "error", ",", "db_entry", ")", "{", "if", "(", "error", ")", "{", "return", "async_map_callback", "(", "error", ")", ";", "}", "var", "client_resource_id", "=", "''", ";", "if", "(", "db_entry", "&&", "db_entry", ".", "client_resource_id", ")", "{", "client_resource_id", "=", "db_entry", ".", "client_resource_id", ";", "}", "paymentResult", ".", "client_resource_id", "=", "client_resource_id", ";", "async_map_callback", "(", "null", ",", "paymentResult", ")", ";", "}", ")", ";", "}", ",", "_callback", ")", ";", "}", "function", "formatResponse", "(", "_transactions", ")", "{", "return", "{", "payments", ":", "_transactions", "}", ";", "}", "var", "steps", "=", "[", "getTransactions", ",", "_", ".", "partial", "(", "utils", ".", "attachDate", ",", "self", ")", ",", "asyncify", "(", "formatTransactions", ")", ",", "attachResourceId", ",", "asyncify", "(", "formatResponse", ")", "]", ";", "async", ".", "waterfall", "(", "steps", ",", "callback", ")", ";", "}" ]
Retrieve the details of multiple payments from the Remote and the local database. This function calls transactions.getAccountTransactions recursively to retrieve results_per_page number of transactions and filters the results by type "payment", along with the other client-specified parameters. @param {Remote} remote @param {/lib/db-interface} dbinterface @param {RippleAddress} req.params.account @param {RippleAddress} req.query.source_account @param {RippleAddress} req.query.destination_account @param {String "incoming"|"outgoing"} req.query.direction @param {Number} [-1] req.query.start_ledger @param {Number} [-1] req.query.end_ledger @param {Boolean} [false] req.query.earliest_first @param {Boolean} [false] req.query.exclude_failed @param {Number} [20] req.query.results_per_page @param {Number} [1] req.query.page
[ "Retrieve", "the", "details", "of", "multiple", "payments", "from", "the", "Remote", "and", "the", "local", "database", "." ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/payments.js#L185-L244
21,624
ripple/ripple-rest
api/orders.js
getOrders
function getOrders(account, options, callback) { var self = this; validate.address(account); validate.options(options); function getAccountOrders(prevResult) { var isAggregate = options.limit === 'all'; if (prevResult && (!isAggregate || !prevResult.marker)) { return Promise.resolve(prevResult); } var promise = new Promise(function(resolve, reject) { var accountOrdersRequest; var marker; var ledger; var limit; if (prevResult) { marker = prevResult.marker; limit = prevResult.limit; ledger = prevResult.ledger_index; } else { marker = options.marker; limit = validator.isValid(options.limit, 'UINT32') ? Number(options.limit) : DefaultPageLimit; ledger = utils.parseLedger(options.ledger); } accountOrdersRequest = self.remote.requestAccountOffers({ account: account, marker: marker, limit: limit, ledger: ledger }); accountOrdersRequest.once('error', reject); accountOrdersRequest.once('success', function(nextResult) { nextResult.offers = prevResult ? nextResult.offers.concat(prevResult.offers) : nextResult.offers; resolve(nextResult); }); accountOrdersRequest.request(); }); return promise.then(getAccountOrders); } function getParsedOrders(offers) { return _.reduce(offers, function(orders, off) { var sequence = off.seq; var type = off.flags & ripple.Remote.flags.offer.Sell ? 'sell' : 'buy'; var passive = (off.flags & ripple.Remote.flags.offer.Passive) !== 0; var taker_gets = utils.parseCurrencyAmount(off.taker_gets); var taker_pays = utils.parseCurrencyAmount(off.taker_pays); orders.push({ type: type, taker_gets: taker_gets, taker_pays: taker_pays, sequence: sequence, passive: passive }); return orders; }, []); } function respondWithOrders(result) { var promise = new Promise(function(resolve) { var orders = {}; if (result.marker) { orders.marker = result.marker; } orders.limit = result.limit; orders.ledger = result.ledger_index; orders.validated = result.validated; orders.orders = getParsedOrders(result.offers); resolve(callback(null, orders)); }); return promise; } getAccountOrders() .then(respondWithOrders) .catch(callback); }
javascript
function getOrders(account, options, callback) { var self = this; validate.address(account); validate.options(options); function getAccountOrders(prevResult) { var isAggregate = options.limit === 'all'; if (prevResult && (!isAggregate || !prevResult.marker)) { return Promise.resolve(prevResult); } var promise = new Promise(function(resolve, reject) { var accountOrdersRequest; var marker; var ledger; var limit; if (prevResult) { marker = prevResult.marker; limit = prevResult.limit; ledger = prevResult.ledger_index; } else { marker = options.marker; limit = validator.isValid(options.limit, 'UINT32') ? Number(options.limit) : DefaultPageLimit; ledger = utils.parseLedger(options.ledger); } accountOrdersRequest = self.remote.requestAccountOffers({ account: account, marker: marker, limit: limit, ledger: ledger }); accountOrdersRequest.once('error', reject); accountOrdersRequest.once('success', function(nextResult) { nextResult.offers = prevResult ? nextResult.offers.concat(prevResult.offers) : nextResult.offers; resolve(nextResult); }); accountOrdersRequest.request(); }); return promise.then(getAccountOrders); } function getParsedOrders(offers) { return _.reduce(offers, function(orders, off) { var sequence = off.seq; var type = off.flags & ripple.Remote.flags.offer.Sell ? 'sell' : 'buy'; var passive = (off.flags & ripple.Remote.flags.offer.Passive) !== 0; var taker_gets = utils.parseCurrencyAmount(off.taker_gets); var taker_pays = utils.parseCurrencyAmount(off.taker_pays); orders.push({ type: type, taker_gets: taker_gets, taker_pays: taker_pays, sequence: sequence, passive: passive }); return orders; }, []); } function respondWithOrders(result) { var promise = new Promise(function(resolve) { var orders = {}; if (result.marker) { orders.marker = result.marker; } orders.limit = result.limit; orders.ledger = result.ledger_index; orders.validated = result.validated; orders.orders = getParsedOrders(result.offers); resolve(callback(null, orders)); }); return promise; } getAccountOrders() .then(respondWithOrders) .catch(callback); }
[ "function", "getOrders", "(", "account", ",", "options", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "validate", ".", "address", "(", "account", ")", ";", "validate", ".", "options", "(", "options", ")", ";", "function", "getAccountOrders", "(", "prevResult", ")", "{", "var", "isAggregate", "=", "options", ".", "limit", "===", "'all'", ";", "if", "(", "prevResult", "&&", "(", "!", "isAggregate", "||", "!", "prevResult", ".", "marker", ")", ")", "{", "return", "Promise", ".", "resolve", "(", "prevResult", ")", ";", "}", "var", "promise", "=", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "accountOrdersRequest", ";", "var", "marker", ";", "var", "ledger", ";", "var", "limit", ";", "if", "(", "prevResult", ")", "{", "marker", "=", "prevResult", ".", "marker", ";", "limit", "=", "prevResult", ".", "limit", ";", "ledger", "=", "prevResult", ".", "ledger_index", ";", "}", "else", "{", "marker", "=", "options", ".", "marker", ";", "limit", "=", "validator", ".", "isValid", "(", "options", ".", "limit", ",", "'UINT32'", ")", "?", "Number", "(", "options", ".", "limit", ")", ":", "DefaultPageLimit", ";", "ledger", "=", "utils", ".", "parseLedger", "(", "options", ".", "ledger", ")", ";", "}", "accountOrdersRequest", "=", "self", ".", "remote", ".", "requestAccountOffers", "(", "{", "account", ":", "account", ",", "marker", ":", "marker", ",", "limit", ":", "limit", ",", "ledger", ":", "ledger", "}", ")", ";", "accountOrdersRequest", ".", "once", "(", "'error'", ",", "reject", ")", ";", "accountOrdersRequest", ".", "once", "(", "'success'", ",", "function", "(", "nextResult", ")", "{", "nextResult", ".", "offers", "=", "prevResult", "?", "nextResult", ".", "offers", ".", "concat", "(", "prevResult", ".", "offers", ")", ":", "nextResult", ".", "offers", ";", "resolve", "(", "nextResult", ")", ";", "}", ")", ";", "accountOrdersRequest", ".", "request", "(", ")", ";", "}", ")", ";", "return", "promise", ".", "then", "(", "getAccountOrders", ")", ";", "}", "function", "getParsedOrders", "(", "offers", ")", "{", "return", "_", ".", "reduce", "(", "offers", ",", "function", "(", "orders", ",", "off", ")", "{", "var", "sequence", "=", "off", ".", "seq", ";", "var", "type", "=", "off", ".", "flags", "&", "ripple", ".", "Remote", ".", "flags", ".", "offer", ".", "Sell", "?", "'sell'", ":", "'buy'", ";", "var", "passive", "=", "(", "off", ".", "flags", "&", "ripple", ".", "Remote", ".", "flags", ".", "offer", ".", "Passive", ")", "!==", "0", ";", "var", "taker_gets", "=", "utils", ".", "parseCurrencyAmount", "(", "off", ".", "taker_gets", ")", ";", "var", "taker_pays", "=", "utils", ".", "parseCurrencyAmount", "(", "off", ".", "taker_pays", ")", ";", "orders", ".", "push", "(", "{", "type", ":", "type", ",", "taker_gets", ":", "taker_gets", ",", "taker_pays", ":", "taker_pays", ",", "sequence", ":", "sequence", ",", "passive", ":", "passive", "}", ")", ";", "return", "orders", ";", "}", ",", "[", "]", ")", ";", "}", "function", "respondWithOrders", "(", "result", ")", "{", "var", "promise", "=", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "var", "orders", "=", "{", "}", ";", "if", "(", "result", ".", "marker", ")", "{", "orders", ".", "marker", "=", "result", ".", "marker", ";", "}", "orders", ".", "limit", "=", "result", ".", "limit", ";", "orders", ".", "ledger", "=", "result", ".", "ledger_index", ";", "orders", ".", "validated", "=", "result", ".", "validated", ";", "orders", ".", "orders", "=", "getParsedOrders", "(", "result", ".", "offers", ")", ";", "resolve", "(", "callback", "(", "null", ",", "orders", ")", ")", ";", "}", ")", ";", "return", "promise", ";", "}", "getAccountOrders", "(", ")", ".", "then", "(", "respondWithOrders", ")", ".", "catch", "(", "callback", ")", ";", "}" ]
Get orders from the ripple network @query @param {String} [request.query.limit] - Set a limit to the number of results returned @param {String} [request.query.marker] - Used to paginate results @param {String} [request.query.ledger] - The ledger index to query against - (required if request.query.marker is present) @url @param {RippleAddress} request.params.account - The ripple address to query orders
[ "Get", "orders", "from", "the", "ripple", "network" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/orders.js#L40-L131
21,625
ripple/ripple-rest
api/orders.js
placeOrder
function placeOrder(account, order, secret, options, callback) { var transaction = createOrderTransaction(account, order); var converter = TxToRestConverter.parseSubmitOrderFromTx; transact(transaction, this, secret, options, converter, callback); }
javascript
function placeOrder(account, order, secret, options, callback) { var transaction = createOrderTransaction(account, order); var converter = TxToRestConverter.parseSubmitOrderFromTx; transact(transaction, this, secret, options, converter, callback); }
[ "function", "placeOrder", "(", "account", ",", "order", ",", "secret", ",", "options", ",", "callback", ")", "{", "var", "transaction", "=", "createOrderTransaction", "(", "account", ",", "order", ")", ";", "var", "converter", "=", "TxToRestConverter", ".", "parseSubmitOrderFromTx", ";", "transact", "(", "transaction", ",", "this", ",", "secret", ",", "options", ",", "converter", ",", "callback", ")", ";", "}" ]
Submit an order to the ripple network More information about order flags can be found at https://ripple.com/build/transactions/#offercreate-flags @body @param {Order} request.body.order - Object that holds information about the order @param {String "buy"|"sell"} request.body.order.type - Choose whether to submit a buy or sell order @param {Boolean} [request.body.order.passive] - Set whether order is passive @param {Boolean} [request.body.order.immediate_or_cancel] - Set whether order is immediate or cancel @param {Boolean} [request.body.order.fill_or_kill] - Set whether order is fill or kill @param {String} request.body.order.taker_gets - Amount of a currency the taker receives for consuming this order @param {String} request.body.order.taker_pays - Amount of a currency the taker must pay for consuming this order @param {String} request.body.secret - YOUR secret key. Do NOT submit to an unknown ripple-rest server @query @param {String "true"|"false"} request.query.validated - used to force request to wait until rippled has finished - validating the submitted transaction
[ "Submit", "an", "order", "to", "the", "ripple", "network" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/orders.js#L162-L166
21,626
ripple/ripple-rest
api/orders.js
cancelOrder
function cancelOrder(account, sequence, secret, options, callback) { var transaction = createOrderCancellationTransaction(account, sequence); var converter = TxToRestConverter.parseCancelOrderFromTx; transact(transaction, this, secret, options, converter, callback); }
javascript
function cancelOrder(account, sequence, secret, options, callback) { var transaction = createOrderCancellationTransaction(account, sequence); var converter = TxToRestConverter.parseCancelOrderFromTx; transact(transaction, this, secret, options, converter, callback); }
[ "function", "cancelOrder", "(", "account", ",", "sequence", ",", "secret", ",", "options", ",", "callback", ")", "{", "var", "transaction", "=", "createOrderCancellationTransaction", "(", "account", ",", "sequence", ")", ";", "var", "converter", "=", "TxToRestConverter", ".", "parseCancelOrderFromTx", ";", "transact", "(", "transaction", ",", "this", ",", "secret", ",", "options", ",", "converter", ",", "callback", ")", ";", "}" ]
Cancel an order in the ripple network @url @param {Number String} request.params.sequence - sequence number of order to cancel @query @param {String "true"|"false"} request.query.validated - used to force request to wait until rippled has finished validating the submitted transaction
[ "Cancel", "an", "order", "in", "the", "ripple", "network" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/orders.js#L180-L184
21,627
ripple/ripple-rest
api/transaction/settings.js
padValue
function padValue(value, length) { assert.strictEqual(typeof value, 'string'); assert.strictEqual(typeof length, 'number'); var result = value; while (result.length < length) { result = '0' + result; } return result; }
javascript
function padValue(value, length) { assert.strictEqual(typeof value, 'string'); assert.strictEqual(typeof length, 'number'); var result = value; while (result.length < length) { result = '0' + result; } return result; }
[ "function", "padValue", "(", "value", ",", "length", ")", "{", "assert", ".", "strictEqual", "(", "typeof", "value", ",", "'string'", ")", ";", "assert", ".", "strictEqual", "(", "typeof", "length", ",", "'number'", ")", ";", "var", "result", "=", "value", ";", "while", "(", "result", ".", "length", "<", "length", ")", "{", "result", "=", "'0'", "+", "result", ";", "}", "return", "result", ";", "}" ]
Pad the value of a fixed-length field @param {String} value @param {Number} length @return {String}
[ "Pad", "the", "value", "of", "a", "fixed", "-", "length", "field" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/transaction/settings.js#L23-L34
21,628
ripple/ripple-rest
api/transaction/settings.js
setTransactionIntFlags
function setTransactionIntFlags(transaction, input, flags) { for (var flagName in flags) { var flag = flags[flagName]; if (!input.hasOwnProperty(flag.name)) { continue; } var value = input[flag.name]; if (value) { transaction.tx_json.SetFlag = flag.value; } else { transaction.tx_json.ClearFlag = flag.value; } } }
javascript
function setTransactionIntFlags(transaction, input, flags) { for (var flagName in flags) { var flag = flags[flagName]; if (!input.hasOwnProperty(flag.name)) { continue; } var value = input[flag.name]; if (value) { transaction.tx_json.SetFlag = flag.value; } else { transaction.tx_json.ClearFlag = flag.value; } } }
[ "function", "setTransactionIntFlags", "(", "transaction", ",", "input", ",", "flags", ")", "{", "for", "(", "var", "flagName", "in", "flags", ")", "{", "var", "flag", "=", "flags", "[", "flagName", "]", ";", "if", "(", "!", "input", ".", "hasOwnProperty", "(", "flag", ".", "name", ")", ")", "{", "continue", ";", "}", "var", "value", "=", "input", "[", "flag", ".", "name", "]", ";", "if", "(", "value", ")", "{", "transaction", ".", "tx_json", ".", "SetFlag", "=", "flag", ".", "value", ";", "}", "else", "{", "transaction", ".", "tx_json", ".", "ClearFlag", "=", "flag", ".", "value", ";", "}", "}", "}" ]
Set integer flags on a transaction based on input and a flag map @param {Transaction} transaction @param {Object} input - Object whose properties determine whether to update the transaction's SetFlag or ClearFlag property @param {Object} flags - Object that maps property names to transaction integer flag values @returns undefined
[ "Set", "integer", "flags", "on", "a", "transaction", "based", "on", "input", "and", "a", "flag", "map" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/transaction/settings.js#L47-L63
21,629
ripple/ripple-rest
api/transaction/settings.js
setTransactionFields
function setTransactionFields(transaction, input, fieldSchema) { for (var fieldName in fieldSchema) { var field = fieldSchema[fieldName]; var value = input[field.name]; if (typeof value === 'undefined') { continue; } // The value required to clear an account root field varies if (value === CLEAR_SETTING && field.hasOwnProperty('defaults')) { value = field.defaults; } if (field.encoding === 'hex') { // If the field is supposed to be hex, why don't we do a // toString('hex') on it? if (field.length) { // Field is fixed length, why are we checking here though? // We could move this to validateInputs if (value.length > field.length) { throw new InvalidRequestError( 'Parameter length exceeded: ' + fieldName); } else if (value.length < field.length) { value = padValue(value, field.length); } } else { // Field is variable length. Expecting an ascii string as input. // This is currently only used for Domain field value = new Buffer(value, 'ascii').toString('hex'); } value = value.toUpperCase(); } transaction.tx_json[fieldName] = value; } }
javascript
function setTransactionFields(transaction, input, fieldSchema) { for (var fieldName in fieldSchema) { var field = fieldSchema[fieldName]; var value = input[field.name]; if (typeof value === 'undefined') { continue; } // The value required to clear an account root field varies if (value === CLEAR_SETTING && field.hasOwnProperty('defaults')) { value = field.defaults; } if (field.encoding === 'hex') { // If the field is supposed to be hex, why don't we do a // toString('hex') on it? if (field.length) { // Field is fixed length, why are we checking here though? // We could move this to validateInputs if (value.length > field.length) { throw new InvalidRequestError( 'Parameter length exceeded: ' + fieldName); } else if (value.length < field.length) { value = padValue(value, field.length); } } else { // Field is variable length. Expecting an ascii string as input. // This is currently only used for Domain field value = new Buffer(value, 'ascii').toString('hex'); } value = value.toUpperCase(); } transaction.tx_json[fieldName] = value; } }
[ "function", "setTransactionFields", "(", "transaction", ",", "input", ",", "fieldSchema", ")", "{", "for", "(", "var", "fieldName", "in", "fieldSchema", ")", "{", "var", "field", "=", "fieldSchema", "[", "fieldName", "]", ";", "var", "value", "=", "input", "[", "field", ".", "name", "]", ";", "if", "(", "typeof", "value", "===", "'undefined'", ")", "{", "continue", ";", "}", "// The value required to clear an account root field varies", "if", "(", "value", "===", "CLEAR_SETTING", "&&", "field", ".", "hasOwnProperty", "(", "'defaults'", ")", ")", "{", "value", "=", "field", ".", "defaults", ";", "}", "if", "(", "field", ".", "encoding", "===", "'hex'", ")", "{", "// If the field is supposed to be hex, why don't we do a", "// toString('hex') on it?", "if", "(", "field", ".", "length", ")", "{", "// Field is fixed length, why are we checking here though?", "// We could move this to validateInputs", "if", "(", "value", ".", "length", ">", "field", ".", "length", ")", "{", "throw", "new", "InvalidRequestError", "(", "'Parameter length exceeded: '", "+", "fieldName", ")", ";", "}", "else", "if", "(", "value", ".", "length", "<", "field", ".", "length", ")", "{", "value", "=", "padValue", "(", "value", ",", "field", ".", "length", ")", ";", "}", "}", "else", "{", "// Field is variable length. Expecting an ascii string as input.", "// This is currently only used for Domain field", "value", "=", "new", "Buffer", "(", "value", ",", "'ascii'", ")", ".", "toString", "(", "'hex'", ")", ";", "}", "value", "=", "value", ".", "toUpperCase", "(", ")", ";", "}", "transaction", ".", "tx_json", "[", "fieldName", "]", "=", "value", ";", "}", "}" ]
Set fields on a transaction based on input and fields schema object @param {Transaction} transaction @param {Object} input - Object whose properties are used to set fields on the transaction @param {Object} fieldSchema - Object that holds the schema of each field @returns undefined
[ "Set", "fields", "on", "a", "transaction", "based", "on", "input", "and", "fields", "schema", "object" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/transaction/settings.js#L75-L112
21,630
ripple/ripple-rest
api/lib/tx-to-rest-converter.js
renameCounterpartyToIssuerInOrderChanges
function renameCounterpartyToIssuerInOrderChanges(orderChanges) { return _.mapValues(orderChanges, function(changes) { return _.map(changes, function(change) { return utils.renameCounterpartyToIssuerInOrder(change); }); }); }
javascript
function renameCounterpartyToIssuerInOrderChanges(orderChanges) { return _.mapValues(orderChanges, function(changes) { return _.map(changes, function(change) { return utils.renameCounterpartyToIssuerInOrder(change); }); }); }
[ "function", "renameCounterpartyToIssuerInOrderChanges", "(", "orderChanges", ")", "{", "return", "_", ".", "mapValues", "(", "orderChanges", ",", "function", "(", "changes", ")", "{", "return", "_", ".", "map", "(", "changes", ",", "function", "(", "change", ")", "{", "return", "utils", ".", "renameCounterpartyToIssuerInOrder", "(", "change", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
This is just to support the legacy naming of "counterparty", this function should be removed when "issuer" is eliminated
[ "This", "is", "just", "to", "support", "the", "legacy", "naming", "of", "counterparty", "this", "function", "should", "be", "removed", "when", "issuer", "is", "eliminated" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/lib/tx-to-rest-converter.js#L14-L20
21,631
ripple/ripple-rest
api/lib/tx-to-rest-converter.js
parseFlagsFromResponse
function parseFlagsFromResponse(responseFlags, flags) { var parsedFlags = {}; for (var flagName in flags) { var flag = flags[flagName]; parsedFlags[flag.name] = Boolean(responseFlags & flag.value); } return parsedFlags; }
javascript
function parseFlagsFromResponse(responseFlags, flags) { var parsedFlags = {}; for (var flagName in flags) { var flag = flags[flagName]; parsedFlags[flag.name] = Boolean(responseFlags & flag.value); } return parsedFlags; }
[ "function", "parseFlagsFromResponse", "(", "responseFlags", ",", "flags", ")", "{", "var", "parsedFlags", "=", "{", "}", ";", "for", "(", "var", "flagName", "in", "flags", ")", "{", "var", "flag", "=", "flags", "[", "flagName", "]", ";", "parsedFlags", "[", "flag", ".", "name", "]", "=", "Boolean", "(", "responseFlags", "&", "flag", ".", "value", ")", ";", "}", "return", "parsedFlags", ";", "}" ]
Helper that parses bit flags from ripple response @param {Number} responseFlags - Integer flag on the ripple response @param {Object} flags - Object with parameter name and bit flag value pairs @returns {Object} parsedFlags - Object with parameter name and boolean flags depending on response flag
[ "Helper", "that", "parses", "bit", "flags", "from", "ripple", "response" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/lib/tx-to-rest-converter.js#L39-L48
21,632
ripple/ripple-rest
api/lib/tx-to-rest-converter.js
parseOrderFromTx
function parseOrderFromTx(tx, options) { if (!options.account) { throw new Error('Internal Error. must supply options.account'); } if (tx.TransactionType !== 'OfferCreate' && tx.TransactionType !== 'OfferCancel') { throw new Error('Invalid parameter: identifier. The transaction ' + 'corresponding to the given identifier is not an order'); } if (tx.meta !== undefined && tx.meta.TransactionResult !== undefined) { if (tx.meta.TransactionResult === 'tejSecretInvalid') { throw new Error('Invalid secret provided.'); } } var order; var flags = parseFlagsFromResponse(tx.flags, constants.OfferCreateFlags); var action = tx.TransactionType === 'OfferCreate' ? 'order_create' : 'order_cancel'; var balance_changes = tx.meta ? parseBalanceChanges(tx.meta)[options.account] || [] : []; var timestamp = tx.date ? new Date(ripple.utils.toTimestamp(tx.date)).toISOString() : ''; var order_changes = tx.meta ? parseOrderBookChanges(tx.meta)[options.account] : []; var direction; if (options.account === tx.Account) { direction = 'outgoing'; } else if (balance_changes.length && order_changes.length) { direction = 'incoming'; } else { direction = 'passthrough'; } if (action === 'order_create') { order = { account: tx.Account, taker_pays: utils.parseCurrencyAmount(tx.TakerPays), taker_gets: utils.parseCurrencyAmount(tx.TakerGets), passive: flags.passive, immediate_or_cancel: flags.immediate_or_cancel, fill_or_kill: flags.fill_or_kill, type: flags.sell ? 'sell' : 'buy', sequence: tx.Sequence }; } else { order = { account: tx.Account, type: 'cancel', sequence: tx.Sequence, cancel_sequence: tx.OfferSequence }; } return { hash: tx.hash, ledger: tx.ledger_index, validated: tx.validated, timestamp: timestamp, fee: utils.dropsToXrp(tx.Fee), action: action, direction: direction, order: order, balance_changes: balance_changes, order_changes: order_changes || [] }; }
javascript
function parseOrderFromTx(tx, options) { if (!options.account) { throw new Error('Internal Error. must supply options.account'); } if (tx.TransactionType !== 'OfferCreate' && tx.TransactionType !== 'OfferCancel') { throw new Error('Invalid parameter: identifier. The transaction ' + 'corresponding to the given identifier is not an order'); } if (tx.meta !== undefined && tx.meta.TransactionResult !== undefined) { if (tx.meta.TransactionResult === 'tejSecretInvalid') { throw new Error('Invalid secret provided.'); } } var order; var flags = parseFlagsFromResponse(tx.flags, constants.OfferCreateFlags); var action = tx.TransactionType === 'OfferCreate' ? 'order_create' : 'order_cancel'; var balance_changes = tx.meta ? parseBalanceChanges(tx.meta)[options.account] || [] : []; var timestamp = tx.date ? new Date(ripple.utils.toTimestamp(tx.date)).toISOString() : ''; var order_changes = tx.meta ? parseOrderBookChanges(tx.meta)[options.account] : []; var direction; if (options.account === tx.Account) { direction = 'outgoing'; } else if (balance_changes.length && order_changes.length) { direction = 'incoming'; } else { direction = 'passthrough'; } if (action === 'order_create') { order = { account: tx.Account, taker_pays: utils.parseCurrencyAmount(tx.TakerPays), taker_gets: utils.parseCurrencyAmount(tx.TakerGets), passive: flags.passive, immediate_or_cancel: flags.immediate_or_cancel, fill_or_kill: flags.fill_or_kill, type: flags.sell ? 'sell' : 'buy', sequence: tx.Sequence }; } else { order = { account: tx.Account, type: 'cancel', sequence: tx.Sequence, cancel_sequence: tx.OfferSequence }; } return { hash: tx.hash, ledger: tx.ledger_index, validated: tx.validated, timestamp: timestamp, fee: utils.dropsToXrp(tx.Fee), action: action, direction: direction, order: order, balance_changes: balance_changes, order_changes: order_changes || [] }; }
[ "function", "parseOrderFromTx", "(", "tx", ",", "options", ")", "{", "if", "(", "!", "options", ".", "account", ")", "{", "throw", "new", "Error", "(", "'Internal Error. must supply options.account'", ")", ";", "}", "if", "(", "tx", ".", "TransactionType", "!==", "'OfferCreate'", "&&", "tx", ".", "TransactionType", "!==", "'OfferCancel'", ")", "{", "throw", "new", "Error", "(", "'Invalid parameter: identifier. The transaction '", "+", "'corresponding to the given identifier is not an order'", ")", ";", "}", "if", "(", "tx", ".", "meta", "!==", "undefined", "&&", "tx", ".", "meta", ".", "TransactionResult", "!==", "undefined", ")", "{", "if", "(", "tx", ".", "meta", ".", "TransactionResult", "===", "'tejSecretInvalid'", ")", "{", "throw", "new", "Error", "(", "'Invalid secret provided.'", ")", ";", "}", "}", "var", "order", ";", "var", "flags", "=", "parseFlagsFromResponse", "(", "tx", ".", "flags", ",", "constants", ".", "OfferCreateFlags", ")", ";", "var", "action", "=", "tx", ".", "TransactionType", "===", "'OfferCreate'", "?", "'order_create'", ":", "'order_cancel'", ";", "var", "balance_changes", "=", "tx", ".", "meta", "?", "parseBalanceChanges", "(", "tx", ".", "meta", ")", "[", "options", ".", "account", "]", "||", "[", "]", ":", "[", "]", ";", "var", "timestamp", "=", "tx", ".", "date", "?", "new", "Date", "(", "ripple", ".", "utils", ".", "toTimestamp", "(", "tx", ".", "date", ")", ")", ".", "toISOString", "(", ")", ":", "''", ";", "var", "order_changes", "=", "tx", ".", "meta", "?", "parseOrderBookChanges", "(", "tx", ".", "meta", ")", "[", "options", ".", "account", "]", ":", "[", "]", ";", "var", "direction", ";", "if", "(", "options", ".", "account", "===", "tx", ".", "Account", ")", "{", "direction", "=", "'outgoing'", ";", "}", "else", "if", "(", "balance_changes", ".", "length", "&&", "order_changes", ".", "length", ")", "{", "direction", "=", "'incoming'", ";", "}", "else", "{", "direction", "=", "'passthrough'", ";", "}", "if", "(", "action", "===", "'order_create'", ")", "{", "order", "=", "{", "account", ":", "tx", ".", "Account", ",", "taker_pays", ":", "utils", ".", "parseCurrencyAmount", "(", "tx", ".", "TakerPays", ")", ",", "taker_gets", ":", "utils", ".", "parseCurrencyAmount", "(", "tx", ".", "TakerGets", ")", ",", "passive", ":", "flags", ".", "passive", ",", "immediate_or_cancel", ":", "flags", ".", "immediate_or_cancel", ",", "fill_or_kill", ":", "flags", ".", "fill_or_kill", ",", "type", ":", "flags", ".", "sell", "?", "'sell'", ":", "'buy'", ",", "sequence", ":", "tx", ".", "Sequence", "}", ";", "}", "else", "{", "order", "=", "{", "account", ":", "tx", ".", "Account", ",", "type", ":", "'cancel'", ",", "sequence", ":", "tx", ".", "Sequence", ",", "cancel_sequence", ":", "tx", ".", "OfferSequence", "}", ";", "}", "return", "{", "hash", ":", "tx", ".", "hash", ",", "ledger", ":", "tx", ".", "ledger_index", ",", "validated", ":", "tx", ".", "validated", ",", "timestamp", ":", "timestamp", ",", "fee", ":", "utils", ".", "dropsToXrp", "(", "tx", ".", "Fee", ")", ",", "action", ":", "action", ",", "direction", ":", "direction", ",", "order", ":", "order", ",", "balance_changes", ":", "balance_changes", ",", "order_changes", ":", "order_changes", "||", "[", "]", "}", ";", "}" ]
Convert an OfferCreate or OfferCancel transaction in rippled tx format to a ripple-rest order_change @param {Object} tx @param {Object} options @param {String} options.account - The account to use as perspective when parsing the transaction. @returns {Promise.<Object,Error>} - resolves to a parsed OrderChange transaction or an Error
[ "Convert", "an", "OfferCreate", "or", "OfferCancel", "transaction", "in", "rippled", "tx", "format", "to", "a", "ripple", "-", "rest", "order_change" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/lib/tx-to-rest-converter.js#L181-L248
21,633
ripple/ripple-rest
api/lib/tx-to-rest-converter.js
parsePaymentsFromPathFind
function parsePaymentsFromPathFind(pathfindResults) { return pathfindResults.alternatives.map(function(alternative) { return { source_account: pathfindResults.source_account, source_tag: '', source_amount: (typeof alternative.source_amount === 'string' ? { value: utils.dropsToXrp(alternative.source_amount), currency: 'XRP', issuer: '' } : { value: alternative.source_amount.value, currency: alternative.source_amount.currency, issuer: (typeof alternative.source_amount.issuer !== 'string' || alternative.source_amount.issuer === pathfindResults.source_account ? '' : alternative.source_amount.issuer) }), source_slippage: '0', destination_account: pathfindResults.destination_account, destination_tag: '', destination_amount: ( typeof pathfindResults.destination_amount === 'string' ? { value: utils.dropsToXrp(pathfindResults.destination_amount), currency: 'XRP', issuer: '' } : { value: pathfindResults.destination_amount.value, currency: pathfindResults.destination_amount.currency, issuer: pathfindResults.destination_amount.issuer }), invoice_id: '', paths: JSON.stringify(alternative.paths_computed), partial_payment: false, no_direct_ripple: false }; }); }
javascript
function parsePaymentsFromPathFind(pathfindResults) { return pathfindResults.alternatives.map(function(alternative) { return { source_account: pathfindResults.source_account, source_tag: '', source_amount: (typeof alternative.source_amount === 'string' ? { value: utils.dropsToXrp(alternative.source_amount), currency: 'XRP', issuer: '' } : { value: alternative.source_amount.value, currency: alternative.source_amount.currency, issuer: (typeof alternative.source_amount.issuer !== 'string' || alternative.source_amount.issuer === pathfindResults.source_account ? '' : alternative.source_amount.issuer) }), source_slippage: '0', destination_account: pathfindResults.destination_account, destination_tag: '', destination_amount: ( typeof pathfindResults.destination_amount === 'string' ? { value: utils.dropsToXrp(pathfindResults.destination_amount), currency: 'XRP', issuer: '' } : { value: pathfindResults.destination_amount.value, currency: pathfindResults.destination_amount.currency, issuer: pathfindResults.destination_amount.issuer }), invoice_id: '', paths: JSON.stringify(alternative.paths_computed), partial_payment: false, no_direct_ripple: false }; }); }
[ "function", "parsePaymentsFromPathFind", "(", "pathfindResults", ")", "{", "return", "pathfindResults", ".", "alternatives", ".", "map", "(", "function", "(", "alternative", ")", "{", "return", "{", "source_account", ":", "pathfindResults", ".", "source_account", ",", "source_tag", ":", "''", ",", "source_amount", ":", "(", "typeof", "alternative", ".", "source_amount", "===", "'string'", "?", "{", "value", ":", "utils", ".", "dropsToXrp", "(", "alternative", ".", "source_amount", ")", ",", "currency", ":", "'XRP'", ",", "issuer", ":", "''", "}", ":", "{", "value", ":", "alternative", ".", "source_amount", ".", "value", ",", "currency", ":", "alternative", ".", "source_amount", ".", "currency", ",", "issuer", ":", "(", "typeof", "alternative", ".", "source_amount", ".", "issuer", "!==", "'string'", "||", "alternative", ".", "source_amount", ".", "issuer", "===", "pathfindResults", ".", "source_account", "?", "''", ":", "alternative", ".", "source_amount", ".", "issuer", ")", "}", ")", ",", "source_slippage", ":", "'0'", ",", "destination_account", ":", "pathfindResults", ".", "destination_account", ",", "destination_tag", ":", "''", ",", "destination_amount", ":", "(", "typeof", "pathfindResults", ".", "destination_amount", "===", "'string'", "?", "{", "value", ":", "utils", ".", "dropsToXrp", "(", "pathfindResults", ".", "destination_amount", ")", ",", "currency", ":", "'XRP'", ",", "issuer", ":", "''", "}", ":", "{", "value", ":", "pathfindResults", ".", "destination_amount", ".", "value", ",", "currency", ":", "pathfindResults", ".", "destination_amount", ".", "currency", ",", "issuer", ":", "pathfindResults", ".", "destination_amount", ".", "issuer", "}", ")", ",", "invoice_id", ":", "''", ",", "paths", ":", "JSON", ".", "stringify", "(", "alternative", ".", "paths_computed", ")", ",", "partial_payment", ":", "false", ",", "no_direct_ripple", ":", "false", "}", ";", "}", ")", ";", "}" ]
Convert the pathfind results returned from rippled into an array of payments in the ripple-rest format. The client should be able to submit any of the payments in the array back to ripple-rest. @param {rippled Pathfind results} pathfindResults @param {Amount} options.destination_amount Since this is not returned by rippled in the pathfind results it can either be added to the results or included in the options here @param {RippleAddress} options.source_account Since this is not returned by rippled in the pathfind results it can either be added to the results or included in the options here @returns {Array of Payments} payments
[ "Convert", "the", "pathfind", "results", "returned", "from", "rippled", "into", "an", "array", "of", "payments", "in", "the", "ripple", "-", "rest", "format", ".", "The", "client", "should", "be", "able", "to", "submit", "any", "of", "the", "payments", "in", "the", "array", "back", "to", "ripple", "-", "rest", "." ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/lib/tx-to-rest-converter.js#L265-L304
21,634
ripple/ripple-rest
api/trustlines.js
addTrustLine
function addTrustLine(account, trustline, secret, options, callback) { var transaction = createTrustLineTransaction(account, trustline); var converter = TxToRestConverter.parseTrustResponseFromTx; transact(transaction, this, secret, options, converter, callback); }
javascript
function addTrustLine(account, trustline, secret, options, callback) { var transaction = createTrustLineTransaction(account, trustline); var converter = TxToRestConverter.parseTrustResponseFromTx; transact(transaction, this, secret, options, converter, callback); }
[ "function", "addTrustLine", "(", "account", ",", "trustline", ",", "secret", ",", "options", ",", "callback", ")", "{", "var", "transaction", "=", "createTrustLineTransaction", "(", "account", ",", "trustline", ")", ";", "var", "converter", "=", "TxToRestConverter", ".", "parseTrustResponseFromTx", ";", "transact", "(", "transaction", ",", "this", ",", "secret", ",", "options", ",", "converter", ",", "callback", ")", ";", "}" ]
Grant a trustline to a counterparty @body @param {Trustline} request.body.trustline @param {String} request.body.secret @query @param {String "true"|"false"} request.query.validated Used to force request to wait until rippled has finished validating the submitted transaction
[ "Grant", "a", "trustline", "to", "a", "counterparty" ]
ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8
https://github.com/ripple/ripple-rest/blob/ff295cd1ea9641813369b02ba75bb3bf5ef4c9b8/api/trustlines.js#L149-L153
21,635
RiotGear/rg
dependencies/js/iframify.js
getStylingNodes
function getStylingNodes (selector) { if (typeof queryCache[selector] === 'undefined') { queryCache[selector] = Array.prototype.map.call( document.querySelectorAll(selector), function (stylesheet) { return stylesheet.outerHTML; } ).join(''); } return queryCache[selector]; }
javascript
function getStylingNodes (selector) { if (typeof queryCache[selector] === 'undefined') { queryCache[selector] = Array.prototype.map.call( document.querySelectorAll(selector), function (stylesheet) { return stylesheet.outerHTML; } ).join(''); } return queryCache[selector]; }
[ "function", "getStylingNodes", "(", "selector", ")", "{", "if", "(", "typeof", "queryCache", "[", "selector", "]", "===", "'undefined'", ")", "{", "queryCache", "[", "selector", "]", "=", "Array", ".", "prototype", ".", "map", ".", "call", "(", "document", ".", "querySelectorAll", "(", "selector", ")", ",", "function", "(", "stylesheet", ")", "{", "return", "stylesheet", ".", "outerHTML", ";", "}", ")", ".", "join", "(", "''", ")", ";", "}", "return", "queryCache", "[", "selector", "]", ";", "}" ]
Get the styling nodes to inject in the head of the embedded document @param {String} selector @return {String}
[ "Get", "the", "styling", "nodes", "to", "inject", "in", "the", "head", "of", "the", "embedded", "document" ]
0ff22318073dc475b763f50bb0e9c8d585df9334
https://github.com/RiotGear/rg/blob/0ff22318073dc475b763f50bb0e9c8d585df9334/dependencies/js/iframify.js#L14-L25
21,636
RiotGear/rg
dependencies/js/iframify.js
getIframeContentForNode
function getIframeContentForNode (node, options) { return '<!doctype html>' + '<html ' + options.htmlAttr + '>' + '<head>' + options.metaCharset + options.metaViewport + options.stylesheets + options.styles + '</head>' + '<body ' + options.bodyAttr + '>' + node.innerHTML + '</body>' + '</html>'; }
javascript
function getIframeContentForNode (node, options) { return '<!doctype html>' + '<html ' + options.htmlAttr + '>' + '<head>' + options.metaCharset + options.metaViewport + options.stylesheets + options.styles + '</head>' + '<body ' + options.bodyAttr + '>' + node.innerHTML + '</body>' + '</html>'; }
[ "function", "getIframeContentForNode", "(", "node", ",", "options", ")", "{", "return", "'<!doctype html>'", "+", "'<html '", "+", "options", ".", "htmlAttr", "+", "'>'", "+", "'<head>'", "+", "options", ".", "metaCharset", "+", "options", ".", "metaViewport", "+", "options", ".", "stylesheets", "+", "options", ".", "styles", "+", "'</head>'", "+", "'<body '", "+", "options", ".", "bodyAttr", "+", "'>'", "+", "node", ".", "innerHTML", "+", "'</body>'", "+", "'</html>'", ";", "}" ]
Get the content for the iframified version of a node. @param {HTMLElement} node @param {Object} options @return {String}
[ "Get", "the", "content", "for", "the", "iframified", "version", "of", "a", "node", "." ]
0ff22318073dc475b763f50bb0e9c8d585df9334
https://github.com/RiotGear/rg/blob/0ff22318073dc475b763f50bb0e9c8d585df9334/dependencies/js/iframify.js#L34-L47
21,637
RiotGear/rg
dependencies/js/iframify.js
formatAttributes
function formatAttributes (attrObj) { var attributes = []; for (var attribute in attrObj) { attributes.push(attribute + '="' + attrObj[attribute] + '"'); } return attributes.join(' '); }
javascript
function formatAttributes (attrObj) { var attributes = []; for (var attribute in attrObj) { attributes.push(attribute + '="' + attrObj[attribute] + '"'); } return attributes.join(' '); }
[ "function", "formatAttributes", "(", "attrObj", ")", "{", "var", "attributes", "=", "[", "]", ";", "for", "(", "var", "attribute", "in", "attrObj", ")", "{", "attributes", ".", "push", "(", "attribute", "+", "'=\"'", "+", "attrObj", "[", "attribute", "]", "+", "'\"'", ")", ";", "}", "return", "attributes", ".", "join", "(", "' '", ")", ";", "}" ]
Format an object of attributes into a HTML string @param {Object} attrObj @return {String}
[ "Format", "an", "object", "of", "attributes", "into", "a", "HTML", "string" ]
0ff22318073dc475b763f50bb0e9c8d585df9334
https://github.com/RiotGear/rg/blob/0ff22318073dc475b763f50bb0e9c8d585df9334/dependencies/js/iframify.js#L55-L63
21,638
RiotGear/rg
dependencies/js/iframify.js
iframify
function iframify (node, options) { options = getOptions(options); var iframe = document.createElement('iframe'); var html = getIframeContentForNode(node, options); iframe.srcdoc = html; if (!('srcdoc' in iframe)) { console.log( 'Your browser does not support the `srcdoc` attribute on elements.' + 'Therefore, it is not possible to wrap this node with an iframe due' + 'to CORS policy.' ); return null; } node.parentNode.replaceChild(iframe, node); setTimeout(function () { var iframeDocument = iframe.contentDocument || iframe.contentWindow.document; iframe.height = getDocumentHeight(iframeDocument); }, options.sizingTimeout); return iframe; }
javascript
function iframify (node, options) { options = getOptions(options); var iframe = document.createElement('iframe'); var html = getIframeContentForNode(node, options); iframe.srcdoc = html; if (!('srcdoc' in iframe)) { console.log( 'Your browser does not support the `srcdoc` attribute on elements.' + 'Therefore, it is not possible to wrap this node with an iframe due' + 'to CORS policy.' ); return null; } node.parentNode.replaceChild(iframe, node); setTimeout(function () { var iframeDocument = iframe.contentDocument || iframe.contentWindow.document; iframe.height = getDocumentHeight(iframeDocument); }, options.sizingTimeout); return iframe; }
[ "function", "iframify", "(", "node", ",", "options", ")", "{", "options", "=", "getOptions", "(", "options", ")", ";", "var", "iframe", "=", "document", ".", "createElement", "(", "'iframe'", ")", ";", "var", "html", "=", "getIframeContentForNode", "(", "node", ",", "options", ")", ";", "iframe", ".", "srcdoc", "=", "html", ";", "if", "(", "!", "(", "'srcdoc'", "in", "iframe", ")", ")", "{", "console", ".", "log", "(", "'Your browser does not support the `srcdoc` attribute on elements.'", "+", "'Therefore, it is not possible to wrap this node with an iframe due'", "+", "'to CORS policy.'", ")", ";", "return", "null", ";", "}", "node", ".", "parentNode", ".", "replaceChild", "(", "iframe", ",", "node", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "var", "iframeDocument", "=", "iframe", ".", "contentDocument", "||", "iframe", ".", "contentWindow", ".", "document", ";", "iframe", ".", "height", "=", "getDocumentHeight", "(", "iframeDocument", ")", ";", "}", ",", "options", ".", "sizingTimeout", ")", ";", "return", "iframe", ";", "}" ]
Transform a collection of nodes into an iframe version of themselves including all the styles they need to perform correctly. @param {HTMLElement} nodes @param {Object} options @return undefined
[ "Transform", "a", "collection", "of", "nodes", "into", "an", "iframe", "version", "of", "themselves", "including", "all", "the", "styles", "they", "need", "to", "perform", "correctly", "." ]
0ff22318073dc475b763f50bb0e9c8d585df9334
https://github.com/RiotGear/rg/blob/0ff22318073dc475b763f50bb0e9c8d585df9334/dependencies/js/iframify.js#L103-L128
21,639
adrienjoly/playemjs
playem.js
Loader
function Loader () { var FINAL_STATES = {'loaded': true, 'complete': true, 4: true} var head = document.getElementsByTagName('head')[0] var pending = {} var counter = 0 return { /** * @private * @callback dataCallback * @memberof Loader.prototype * @param {object|string} data JSON object, or string returned by request as `responseText`. */ /** * Loads and returns a JSON resource asynchronously, using XMLHttpRequest (AJAX). * @memberof Loader.prototype * @param {string} src HTTP(S) URL of the JSON resource to load. * @param {dataCallback} cb Callback function with request's data as first parameter. */ loadJSON: function (src, cb) { // if (pending[src]) return cb && cb(); // pending[src] = true; // cross-domain ajax call var xdr = new window.XMLHttpRequest() xdr.onload = function () { var data = xdr.responseText try { data = JSON.parse(data) } catch (e) {}; cb(data) // delete pending[src]; } xdr.open('GET', src, true) xdr.send() }, /** * @private * @callback errorCallback * @memberof Loader.prototype * @param {Error} error Error caught thru the `error` event or `appendChild()` call, if any. */ /** * Loads a JavaScript resource into the page. * @memberof Loader.prototype * @param {string} src HTTP(S) URL of the JavaScript resource to load into the page. * @param {errorCallback} cb Callback function with error as first parameter, if any. */ includeJS: function (src, cb) { var inc, nt if (pending[src]) { if (cb) { nt = setInterval(function () { if (pending[src]) { return console.log('still loading', src, '...') } clearInterval(nt) cb() }, 50) } return } pending[src] = true inc = document.createElement('script') // inc.async = "async"; inc.onload = function () { if (!pending[src]) { return } delete pending[src] cb && setTimeout(cb, 1) delete inc.onload } inc.onerror = function (e) { e.preventDefault() inc.onload(e) } inc.onreadystatechange = function () { if (!inc.readyState || FINAL_STATES[inc.readyState]) { inc.onload() } } try { inc.src = src head.appendChild(inc) } catch (e) { console.error('Error while including', src, e) cb(e) } }, /** * Loads and returns a JSON resource asynchronously, by including it into the page (not AJAX). * @memberof Loader.prototype * @param {string} src HTTP(S) URL of the JSON resource to load. * @param {function} cb Callback function, called by the resource's script. */ loadJSONP: function (src, cb) { var callbackFct = '__loadjsonp__' + (counter++) window[callbackFct] = function () { cb.apply(window, arguments) delete window[callbackFct] } this.includeJS(src + (src.indexOf('?') == -1 ? '?' : '&') + 'callback=' + callbackFct, function () { // if http request fails (e.g. 404 error / no content) setTimeout(window[callbackFct], 10) }) } } }
javascript
function Loader () { var FINAL_STATES = {'loaded': true, 'complete': true, 4: true} var head = document.getElementsByTagName('head')[0] var pending = {} var counter = 0 return { /** * @private * @callback dataCallback * @memberof Loader.prototype * @param {object|string} data JSON object, or string returned by request as `responseText`. */ /** * Loads and returns a JSON resource asynchronously, using XMLHttpRequest (AJAX). * @memberof Loader.prototype * @param {string} src HTTP(S) URL of the JSON resource to load. * @param {dataCallback} cb Callback function with request's data as first parameter. */ loadJSON: function (src, cb) { // if (pending[src]) return cb && cb(); // pending[src] = true; // cross-domain ajax call var xdr = new window.XMLHttpRequest() xdr.onload = function () { var data = xdr.responseText try { data = JSON.parse(data) } catch (e) {}; cb(data) // delete pending[src]; } xdr.open('GET', src, true) xdr.send() }, /** * @private * @callback errorCallback * @memberof Loader.prototype * @param {Error} error Error caught thru the `error` event or `appendChild()` call, if any. */ /** * Loads a JavaScript resource into the page. * @memberof Loader.prototype * @param {string} src HTTP(S) URL of the JavaScript resource to load into the page. * @param {errorCallback} cb Callback function with error as first parameter, if any. */ includeJS: function (src, cb) { var inc, nt if (pending[src]) { if (cb) { nt = setInterval(function () { if (pending[src]) { return console.log('still loading', src, '...') } clearInterval(nt) cb() }, 50) } return } pending[src] = true inc = document.createElement('script') // inc.async = "async"; inc.onload = function () { if (!pending[src]) { return } delete pending[src] cb && setTimeout(cb, 1) delete inc.onload } inc.onerror = function (e) { e.preventDefault() inc.onload(e) } inc.onreadystatechange = function () { if (!inc.readyState || FINAL_STATES[inc.readyState]) { inc.onload() } } try { inc.src = src head.appendChild(inc) } catch (e) { console.error('Error while including', src, e) cb(e) } }, /** * Loads and returns a JSON resource asynchronously, by including it into the page (not AJAX). * @memberof Loader.prototype * @param {string} src HTTP(S) URL of the JSON resource to load. * @param {function} cb Callback function, called by the resource's script. */ loadJSONP: function (src, cb) { var callbackFct = '__loadjsonp__' + (counter++) window[callbackFct] = function () { cb.apply(window, arguments) delete window[callbackFct] } this.includeJS(src + (src.indexOf('?') == -1 ? '?' : '&') + 'callback=' + callbackFct, function () { // if http request fails (e.g. 404 error / no content) setTimeout(window[callbackFct], 10) }) } } }
[ "function", "Loader", "(", ")", "{", "var", "FINAL_STATES", "=", "{", "'loaded'", ":", "true", ",", "'complete'", ":", "true", ",", "4", ":", "true", "}", "var", "head", "=", "document", ".", "getElementsByTagName", "(", "'head'", ")", "[", "0", "]", "var", "pending", "=", "{", "}", "var", "counter", "=", "0", "return", "{", "/**\n * @private\n * @callback dataCallback\n * @memberof Loader.prototype\n * @param {object|string} data JSON object, or string returned by request as `responseText`.\n */", "/**\n * Loads and returns a JSON resource asynchronously, using XMLHttpRequest (AJAX).\n * @memberof Loader.prototype\n * @param {string} src HTTP(S) URL of the JSON resource to load.\n * @param {dataCallback} cb Callback function with request's data as first parameter.\n */", "loadJSON", ":", "function", "(", "src", ",", "cb", ")", "{", "// if (pending[src]) return cb && cb();", "// pending[src] = true;", "// cross-domain ajax call", "var", "xdr", "=", "new", "window", ".", "XMLHttpRequest", "(", ")", "xdr", ".", "onload", "=", "function", "(", ")", "{", "var", "data", "=", "xdr", ".", "responseText", "try", "{", "data", "=", "JSON", ".", "parse", "(", "data", ")", "}", "catch", "(", "e", ")", "{", "}", ";", "cb", "(", "data", ")", "// delete pending[src];", "}", "xdr", ".", "open", "(", "'GET'", ",", "src", ",", "true", ")", "xdr", ".", "send", "(", ")", "}", ",", "/**\n * @private\n * @callback errorCallback\n * @memberof Loader.prototype\n * @param {Error} error Error caught thru the `error` event or `appendChild()` call, if any.\n */", "/**\n * Loads a JavaScript resource into the page.\n * @memberof Loader.prototype\n * @param {string} src HTTP(S) URL of the JavaScript resource to load into the page.\n * @param {errorCallback} cb Callback function with error as first parameter, if any.\n */", "includeJS", ":", "function", "(", "src", ",", "cb", ")", "{", "var", "inc", ",", "nt", "if", "(", "pending", "[", "src", "]", ")", "{", "if", "(", "cb", ")", "{", "nt", "=", "setInterval", "(", "function", "(", ")", "{", "if", "(", "pending", "[", "src", "]", ")", "{", "return", "console", ".", "log", "(", "'still loading'", ",", "src", ",", "'...'", ")", "}", "clearInterval", "(", "nt", ")", "cb", "(", ")", "}", ",", "50", ")", "}", "return", "}", "pending", "[", "src", "]", "=", "true", "inc", "=", "document", ".", "createElement", "(", "'script'", ")", "// inc.async = \"async\";", "inc", ".", "onload", "=", "function", "(", ")", "{", "if", "(", "!", "pending", "[", "src", "]", ")", "{", "return", "}", "delete", "pending", "[", "src", "]", "cb", "&&", "setTimeout", "(", "cb", ",", "1", ")", "delete", "inc", ".", "onload", "}", "inc", ".", "onerror", "=", "function", "(", "e", ")", "{", "e", ".", "preventDefault", "(", ")", "inc", ".", "onload", "(", "e", ")", "}", "inc", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "!", "inc", ".", "readyState", "||", "FINAL_STATES", "[", "inc", ".", "readyState", "]", ")", "{", "inc", ".", "onload", "(", ")", "}", "}", "try", "{", "inc", ".", "src", "=", "src", "head", ".", "appendChild", "(", "inc", ")", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "'Error while including'", ",", "src", ",", "e", ")", "cb", "(", "e", ")", "}", "}", ",", "/**\n * Loads and returns a JSON resource asynchronously, by including it into the page (not AJAX).\n * @memberof Loader.prototype\n * @param {string} src HTTP(S) URL of the JSON resource to load.\n * @param {function} cb Callback function, called by the resource's script.\n */", "loadJSONP", ":", "function", "(", "src", ",", "cb", ")", "{", "var", "callbackFct", "=", "'__loadjsonp__'", "+", "(", "counter", "++", ")", "window", "[", "callbackFct", "]", "=", "function", "(", ")", "{", "cb", ".", "apply", "(", "window", ",", "arguments", ")", "delete", "window", "[", "callbackFct", "]", "}", "this", ".", "includeJS", "(", "src", "+", "(", "src", ".", "indexOf", "(", "'?'", ")", "==", "-", "1", "?", "'?'", ":", "'&'", ")", "+", "'callback='", "+", "callbackFct", ",", "function", "(", ")", "{", "// if http request fails (e.g. 404 error / no content)", "setTimeout", "(", "window", "[", "callbackFct", "]", ",", "10", ")", "}", ")", "}", "}", "}" ]
This class provides helpers to load JavaScript resources and JSON data. @class Loader
[ "This", "class", "provides", "helpers", "to", "load", "JavaScript", "resources", "and", "JSON", "data", "." ]
fe696cc318fb904d9f16515b9a73e56dc4c6198f
https://github.com/adrienjoly/playemjs/blob/fe696cc318fb904d9f16515b9a73e56dc4c6198f/playem.js#L16-L116
21,640
adrienjoly/playemjs
playem.js
createEventHandlers
function createEventHandlers (playemFunctions) { var eventHandlers = { onApiReady: function (player) { // console.log(player.label + " api ready"); if (whenReady && player == whenReady.player) { whenReady.fct() } if (--playersToLoad == 0) { that.emit('onReady') } }, onEmbedReady: function (player) { // console.log("embed ready"); setVolume(volume) }, onBuffering: function (player) { setTimeout(function () { setPlayTimeout() that.emit('onBuffering') }) }, onPlaying: function (player) { // console.log(player.label + ".onPlaying"); // setPlayTimeout(); // removed because soundcloud sends a "onPlaying" event, even for not authorized tracks setVolume(volume) setTimeout(function () { that.emit('onPlay') }, 1) if (player.trackInfo && player.trackInfo.duration) { eventHandlers.onTrackInfo({ position: player.trackInfo.position || 0, duration: player.trackInfo.duration }) } if (progress) { clearInterval(progress) } if (player.getTrackPosition) { // var that = eventHandlers; //this; progress = setInterval(function () { player.getTrackPosition(function (trackPos) { eventHandlers.onTrackInfo({ position: trackPos, duration: player.trackInfo.duration || currentTrack.trackDuration }) }) }, 1000) } }, onTrackInfo: function (trackInfo) { // console.log("ontrackinfo", trackInfo, currentTrack); if (currentTrack && trackInfo) { if (trackInfo.duration) { currentTrack.trackDuration = trackInfo.duration setPlayTimeout() } if (trackInfo.position) { currentTrack.trackPosition = trackInfo.position } } that.emit('onTrackInfo', currentTrack) }, onPaused: function (player) { // console.log(player.label + ".onPaused"); setPlayTimeout() if (progress) { clearInterval(progress) } progress = null // if (!avoidPauseEventPropagation) // that.emit("onPause"); // avoidPauseEventPropagation = false; }, onEnded: function (player) { // console.log(player.label + ".onEnded"); stopTrack() that.emit('onEnd') playemFunctions.next() }, onError: function (player, error) { console.error(player.label + ' error:', ((error || {}).exception || error || {}).stack || error) setPlayTimeout() that.emit('onError', error) } }; // handlers will only be triggered is their associated player is currently active ['onEmbedReady', 'onBuffering', 'onPlaying', 'onPaused', 'onEnded', 'onError'].map(function (evt) { var fct = eventHandlers[evt] eventHandlers[evt] = function (player, x) { if (currentTrack && player == currentTrack.player) { return fct(player, x) } /* else if (evt != "onEmbedReady") console.warn("ignore event:", evt, "from", player, "instead of:", currentTrack.player); */ } }) return eventHandlers }
javascript
function createEventHandlers (playemFunctions) { var eventHandlers = { onApiReady: function (player) { // console.log(player.label + " api ready"); if (whenReady && player == whenReady.player) { whenReady.fct() } if (--playersToLoad == 0) { that.emit('onReady') } }, onEmbedReady: function (player) { // console.log("embed ready"); setVolume(volume) }, onBuffering: function (player) { setTimeout(function () { setPlayTimeout() that.emit('onBuffering') }) }, onPlaying: function (player) { // console.log(player.label + ".onPlaying"); // setPlayTimeout(); // removed because soundcloud sends a "onPlaying" event, even for not authorized tracks setVolume(volume) setTimeout(function () { that.emit('onPlay') }, 1) if (player.trackInfo && player.trackInfo.duration) { eventHandlers.onTrackInfo({ position: player.trackInfo.position || 0, duration: player.trackInfo.duration }) } if (progress) { clearInterval(progress) } if (player.getTrackPosition) { // var that = eventHandlers; //this; progress = setInterval(function () { player.getTrackPosition(function (trackPos) { eventHandlers.onTrackInfo({ position: trackPos, duration: player.trackInfo.duration || currentTrack.trackDuration }) }) }, 1000) } }, onTrackInfo: function (trackInfo) { // console.log("ontrackinfo", trackInfo, currentTrack); if (currentTrack && trackInfo) { if (trackInfo.duration) { currentTrack.trackDuration = trackInfo.duration setPlayTimeout() } if (trackInfo.position) { currentTrack.trackPosition = trackInfo.position } } that.emit('onTrackInfo', currentTrack) }, onPaused: function (player) { // console.log(player.label + ".onPaused"); setPlayTimeout() if (progress) { clearInterval(progress) } progress = null // if (!avoidPauseEventPropagation) // that.emit("onPause"); // avoidPauseEventPropagation = false; }, onEnded: function (player) { // console.log(player.label + ".onEnded"); stopTrack() that.emit('onEnd') playemFunctions.next() }, onError: function (player, error) { console.error(player.label + ' error:', ((error || {}).exception || error || {}).stack || error) setPlayTimeout() that.emit('onError', error) } }; // handlers will only be triggered is their associated player is currently active ['onEmbedReady', 'onBuffering', 'onPlaying', 'onPaused', 'onEnded', 'onError'].map(function (evt) { var fct = eventHandlers[evt] eventHandlers[evt] = function (player, x) { if (currentTrack && player == currentTrack.player) { return fct(player, x) } /* else if (evt != "onEmbedReady") console.warn("ignore event:", evt, "from", player, "instead of:", currentTrack.player); */ } }) return eventHandlers }
[ "function", "createEventHandlers", "(", "playemFunctions", ")", "{", "var", "eventHandlers", "=", "{", "onApiReady", ":", "function", "(", "player", ")", "{", "// console.log(player.label + \" api ready\");", "if", "(", "whenReady", "&&", "player", "==", "whenReady", ".", "player", ")", "{", "whenReady", ".", "fct", "(", ")", "}", "if", "(", "--", "playersToLoad", "==", "0", ")", "{", "that", ".", "emit", "(", "'onReady'", ")", "}", "}", ",", "onEmbedReady", ":", "function", "(", "player", ")", "{", "// console.log(\"embed ready\");", "setVolume", "(", "volume", ")", "}", ",", "onBuffering", ":", "function", "(", "player", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "setPlayTimeout", "(", ")", "that", ".", "emit", "(", "'onBuffering'", ")", "}", ")", "}", ",", "onPlaying", ":", "function", "(", "player", ")", "{", "// console.log(player.label + \".onPlaying\");", "// setPlayTimeout(); // removed because soundcloud sends a \"onPlaying\" event, even for not authorized tracks", "setVolume", "(", "volume", ")", "setTimeout", "(", "function", "(", ")", "{", "that", ".", "emit", "(", "'onPlay'", ")", "}", ",", "1", ")", "if", "(", "player", ".", "trackInfo", "&&", "player", ".", "trackInfo", ".", "duration", ")", "{", "eventHandlers", ".", "onTrackInfo", "(", "{", "position", ":", "player", ".", "trackInfo", ".", "position", "||", "0", ",", "duration", ":", "player", ".", "trackInfo", ".", "duration", "}", ")", "}", "if", "(", "progress", ")", "{", "clearInterval", "(", "progress", ")", "}", "if", "(", "player", ".", "getTrackPosition", ")", "{", "// var that = eventHandlers; //this;", "progress", "=", "setInterval", "(", "function", "(", ")", "{", "player", ".", "getTrackPosition", "(", "function", "(", "trackPos", ")", "{", "eventHandlers", ".", "onTrackInfo", "(", "{", "position", ":", "trackPos", ",", "duration", ":", "player", ".", "trackInfo", ".", "duration", "||", "currentTrack", ".", "trackDuration", "}", ")", "}", ")", "}", ",", "1000", ")", "}", "}", ",", "onTrackInfo", ":", "function", "(", "trackInfo", ")", "{", "// console.log(\"ontrackinfo\", trackInfo, currentTrack);", "if", "(", "currentTrack", "&&", "trackInfo", ")", "{", "if", "(", "trackInfo", ".", "duration", ")", "{", "currentTrack", ".", "trackDuration", "=", "trackInfo", ".", "duration", "setPlayTimeout", "(", ")", "}", "if", "(", "trackInfo", ".", "position", ")", "{", "currentTrack", ".", "trackPosition", "=", "trackInfo", ".", "position", "}", "}", "that", ".", "emit", "(", "'onTrackInfo'", ",", "currentTrack", ")", "}", ",", "onPaused", ":", "function", "(", "player", ")", "{", "// console.log(player.label + \".onPaused\");", "setPlayTimeout", "(", ")", "if", "(", "progress", ")", "{", "clearInterval", "(", "progress", ")", "}", "progress", "=", "null", "// if (!avoidPauseEventPropagation)", "// that.emit(\"onPause\");", "// avoidPauseEventPropagation = false;", "}", ",", "onEnded", ":", "function", "(", "player", ")", "{", "// console.log(player.label + \".onEnded\");", "stopTrack", "(", ")", "that", ".", "emit", "(", "'onEnd'", ")", "playemFunctions", ".", "next", "(", ")", "}", ",", "onError", ":", "function", "(", "player", ",", "error", ")", "{", "console", ".", "error", "(", "player", ".", "label", "+", "' error:'", ",", "(", "(", "error", "||", "{", "}", ")", ".", "exception", "||", "error", "||", "{", "}", ")", ".", "stack", "||", "error", ")", "setPlayTimeout", "(", ")", "that", ".", "emit", "(", "'onError'", ",", "error", ")", "}", "}", ";", "// handlers will only be triggered is their associated player is currently active", "[", "'onEmbedReady'", ",", "'onBuffering'", ",", "'onPlaying'", ",", "'onPaused'", ",", "'onEnded'", ",", "'onError'", "]", ".", "map", "(", "function", "(", "evt", ")", "{", "var", "fct", "=", "eventHandlers", "[", "evt", "]", "eventHandlers", "[", "evt", "]", "=", "function", "(", "player", ",", "x", ")", "{", "if", "(", "currentTrack", "&&", "player", "==", "currentTrack", ".", "player", ")", "{", "return", "fct", "(", "player", ",", "x", ")", "}", "/*\n else if (evt != \"onEmbedReady\")\n console.warn(\"ignore event:\", evt, \"from\", player, \"instead of:\", currentTrack.player);\n */", "}", "}", ")", "return", "eventHandlers", "}" ]
functions that are called by players => to propagate to client
[ "functions", "that", "are", "called", "by", "players", "=", ">", "to", "propagate", "to", "client" ]
fe696cc318fb904d9f16515b9a73e56dc4c6198f
https://github.com/adrienjoly/playemjs/blob/fe696cc318fb904d9f16515b9a73e56dc4c6198f/playem.js#L316-L405
21,641
peteward44/node-svn-ultimate
index.js
function( url, dir, options, callback ) { if ( typeof options === 'function' ) { callback = options; options = null; } options = options || {}; addExtraOptions( [ 'force', 'quiet', 'revision', 'depth', 'ignoreExternals' ], options ); var dirPath = dir; if(typeof options.cwd !== 'undefined') dirPath = path.resolve(options.cwd, dir); if ( !fs.existsSync( dirPath ) ) { fs.mkdirsSync( dirPath ); } executeSvn( [ 'checkout', url, dir ], options, callback ); }
javascript
function( url, dir, options, callback ) { if ( typeof options === 'function' ) { callback = options; options = null; } options = options || {}; addExtraOptions( [ 'force', 'quiet', 'revision', 'depth', 'ignoreExternals' ], options ); var dirPath = dir; if(typeof options.cwd !== 'undefined') dirPath = path.resolve(options.cwd, dir); if ( !fs.existsSync( dirPath ) ) { fs.mkdirsSync( dirPath ); } executeSvn( [ 'checkout', url, dir ], options, callback ); }
[ "function", "(", "url", ",", "dir", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "null", ";", "}", "options", "=", "options", "||", "{", "}", ";", "addExtraOptions", "(", "[", "'force'", ",", "'quiet'", ",", "'revision'", ",", "'depth'", ",", "'ignoreExternals'", "]", ",", "options", ")", ";", "var", "dirPath", "=", "dir", ";", "if", "(", "typeof", "options", ".", "cwd", "!==", "'undefined'", ")", "dirPath", "=", "path", ".", "resolve", "(", "options", ".", "cwd", ",", "dir", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "dirPath", ")", ")", "{", "fs", ".", "mkdirsSync", "(", "dirPath", ")", ";", "}", "executeSvn", "(", "[", "'checkout'", ",", "url", ",", "dir", "]", ",", "options", ",", "callback", ")", ";", "}" ]
Checks out a repository to a working copy @function checkout @memberof commands @param {string} url - Repository URL @param {string} dir - Working copy dir @param {object} [options] - Options object @param {function} [callback] - Complete callback @alias co
[ "Checks", "out", "a", "repository", "to", "a", "working", "copy" ]
06d1aeec895c737265c1689520b63aeaf7eca729
https://github.com/peteward44/node-svn-ultimate/blob/06d1aeec895c737265c1689520b63aeaf7eca729/index.js#L190-L205
21,642
peteward44/node-svn-ultimate
index.js
function( files, options, callback ) { if ( !Array.isArray( files ) ) { files = [files]; } if ( typeof options === 'function' ) { callback = options; options = null; } else if ( typeof options === 'string' ) { options = { msg: options }; } options = options || {}; addExtraOptions( [ 'quiet', 'depth', 'msg' ], options ); executeSvn( [ 'commit' ].concat( files ), options, callback ); }
javascript
function( files, options, callback ) { if ( !Array.isArray( files ) ) { files = [files]; } if ( typeof options === 'function' ) { callback = options; options = null; } else if ( typeof options === 'string' ) { options = { msg: options }; } options = options || {}; addExtraOptions( [ 'quiet', 'depth', 'msg' ], options ); executeSvn( [ 'commit' ].concat( files ), options, callback ); }
[ "function", "(", "files", ",", "options", ",", "callback", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "files", ")", ")", "{", "files", "=", "[", "files", "]", ";", "}", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "null", ";", "}", "else", "if", "(", "typeof", "options", "===", "'string'", ")", "{", "options", "=", "{", "msg", ":", "options", "}", ";", "}", "options", "=", "options", "||", "{", "}", ";", "addExtraOptions", "(", "[", "'quiet'", ",", "'depth'", ",", "'msg'", "]", ",", "options", ")", ";", "executeSvn", "(", "[", "'commit'", "]", ".", "concat", "(", "files", ")", ",", "options", ",", "callback", ")", ";", "}" ]
Commits a working copy to a repository @function commit @memberof commands @param {Array|string} files - Array of files / folders to commit @param {object} [options] - Options object @param {function} [callback] - Complete callback @alias ci
[ "Commits", "a", "working", "copy", "to", "a", "repository" ]
06d1aeec895c737265c1689520b63aeaf7eca729
https://github.com/peteward44/node-svn-ultimate/blob/06d1aeec895c737265c1689520b63aeaf7eca729/index.js#L280-L293
21,643
peteward44/node-svn-ultimate
index.js
function( url, wc, options, callback ) { if ( typeof options === 'function' ) { callback = options; options = null; } options = options || {}; executeSvn( [ 'relocate', url, wc ], options, callback ); }
javascript
function( url, wc, options, callback ) { if ( typeof options === 'function' ) { callback = options; options = null; } options = options || {}; executeSvn( [ 'relocate', url, wc ], options, callback ); }
[ "function", "(", "url", ",", "wc", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "null", ";", "}", "options", "=", "options", "||", "{", "}", ";", "executeSvn", "(", "[", "'relocate'", ",", "url", ",", "wc", "]", ",", "options", ",", "callback", ")", ";", "}" ]
Relocates an svn working copy @function relocate @memberof commands @param {string} url - Relocation URL @param {string} wc - Working copy to relocate @param {object} [options] - Options object @param {function} [callback] - Complete callback
[ "Relocates", "an", "svn", "working", "copy" ]
06d1aeec895c737265c1689520b63aeaf7eca729
https://github.com/peteward44/node-svn-ultimate/blob/06d1aeec895c737265c1689520b63aeaf7eca729/index.js#L706-L713
21,644
peteward44/node-svn-ultimate
index.js
function( wc, options, callback ) { if ( typeof options === 'function' ) { callback = options; options = null; } options = options || {}; addExtraOptions( [ 'quiet', 'depth' ], options ); executeSvnXml( [ 'status', wc ], options, callback ); }
javascript
function( wc, options, callback ) { if ( typeof options === 'function' ) { callback = options; options = null; } options = options || {}; addExtraOptions( [ 'quiet', 'depth' ], options ); executeSvnXml( [ 'status', wc ], options, callback ); }
[ "function", "(", "wc", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "null", ";", "}", "options", "=", "options", "||", "{", "}", ";", "addExtraOptions", "(", "[", "'quiet'", ",", "'depth'", "]", ",", "options", ")", ";", "executeSvnXml", "(", "[", "'status'", ",", "wc", "]", ",", "options", ",", "callback", ")", ";", "}" ]
Performs an svn status command on a working copy @function status @memberof commands @param {string} wc - Working copy target @param {object} [options] - Options object @param {function} [callback] - Complete callback @alias stat @alias st
[ "Performs", "an", "svn", "status", "command", "on", "a", "working", "copy" ]
06d1aeec895c737265c1689520b63aeaf7eca729
https://github.com/peteward44/node-svn-ultimate/blob/06d1aeec895c737265c1689520b63aeaf7eca729/index.js#L748-L756
21,645
peteward44/node-svn-ultimate
index.js
function( wcs, options, callback ) { if ( typeof options === 'function' ) { callback = options; options = null; } if ( !Array.isArray( wcs ) ) { wcs = [wcs]; } options = options || {}; addExtraOptions( [ 'force', 'quiet', 'revision', 'depth', 'ignoreExternals' ], options ); executeSvn( [ 'update' ].concat( wcs ), options, callback ); }
javascript
function( wcs, options, callback ) { if ( typeof options === 'function' ) { callback = options; options = null; } if ( !Array.isArray( wcs ) ) { wcs = [wcs]; } options = options || {}; addExtraOptions( [ 'force', 'quiet', 'revision', 'depth', 'ignoreExternals' ], options ); executeSvn( [ 'update' ].concat( wcs ), options, callback ); }
[ "function", "(", "wcs", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "null", ";", "}", "if", "(", "!", "Array", ".", "isArray", "(", "wcs", ")", ")", "{", "wcs", "=", "[", "wcs", "]", ";", "}", "options", "=", "options", "||", "{", "}", ";", "addExtraOptions", "(", "[", "'force'", ",", "'quiet'", ",", "'revision'", ",", "'depth'", ",", "'ignoreExternals'", "]", ",", "options", ")", ";", "executeSvn", "(", "[", "'update'", "]", ".", "concat", "(", "wcs", ")", ",", "options", ",", "callback", ")", ";", "}" ]
Updates an svn working copy @function update @memberof commands @param {Array|string} wcs - Working copy targets @param {object} [options] - Options object @param {function} [callback] - Complete callback @alias up
[ "Updates", "an", "svn", "working", "copy" ]
06d1aeec895c737265c1689520b63aeaf7eca729
https://github.com/peteward44/node-svn-ultimate/blob/06d1aeec895c737265c1689520b63aeaf7eca729/index.js#L809-L820
21,646
peteward44/node-svn-ultimate
index.js
function( target, options, callback ) { if ( typeof options === "function" ) { callback = options; options = null; } options = options || {}; info( target, options, function( err, data ) { var rev; if ( !err ) { var revString; if ( options.lastChangeRevision ) { if ( data && data.entry && data.entry.commit && data.entry.commit.$ && data.entry.commit.$.revision ) { revString = data.entry.commit.$.revision; } } else { if ( data && data.entry && data.entry.$ && data.entry.$.revision ) { revString = data.entry.$.revision; } } if ( revString !== undefined ) { try { rev = parseInt( revString, 10 ); } catch ( err3 ) { err = 'Invalid revision value [' + revString + ']'; } } else { err = 'Could not parse info result to get revision [' + JSON.stringify( data ) + ']'; } } callback( err, rev ); } ); }
javascript
function( target, options, callback ) { if ( typeof options === "function" ) { callback = options; options = null; } options = options || {}; info( target, options, function( err, data ) { var rev; if ( !err ) { var revString; if ( options.lastChangeRevision ) { if ( data && data.entry && data.entry.commit && data.entry.commit.$ && data.entry.commit.$.revision ) { revString = data.entry.commit.$.revision; } } else { if ( data && data.entry && data.entry.$ && data.entry.$.revision ) { revString = data.entry.$.revision; } } if ( revString !== undefined ) { try { rev = parseInt( revString, 10 ); } catch ( err3 ) { err = 'Invalid revision value [' + revString + ']'; } } else { err = 'Could not parse info result to get revision [' + JSON.stringify( data ) + ']'; } } callback( err, rev ); } ); }
[ "function", "(", "target", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "\"function\"", ")", "{", "callback", "=", "options", ";", "options", "=", "null", ";", "}", "options", "=", "options", "||", "{", "}", ";", "info", "(", "target", ",", "options", ",", "function", "(", "err", ",", "data", ")", "{", "var", "rev", ";", "if", "(", "!", "err", ")", "{", "var", "revString", ";", "if", "(", "options", ".", "lastChangeRevision", ")", "{", "if", "(", "data", "&&", "data", ".", "entry", "&&", "data", ".", "entry", ".", "commit", "&&", "data", ".", "entry", ".", "commit", ".", "$", "&&", "data", ".", "entry", ".", "commit", ".", "$", ".", "revision", ")", "{", "revString", "=", "data", ".", "entry", ".", "commit", ".", "$", ".", "revision", ";", "}", "}", "else", "{", "if", "(", "data", "&&", "data", ".", "entry", "&&", "data", ".", "entry", ".", "$", "&&", "data", ".", "entry", ".", "$", ".", "revision", ")", "{", "revString", "=", "data", ".", "entry", ".", "$", ".", "revision", ";", "}", "}", "if", "(", "revString", "!==", "undefined", ")", "{", "try", "{", "rev", "=", "parseInt", "(", "revString", ",", "10", ")", ";", "}", "catch", "(", "err3", ")", "{", "err", "=", "'Invalid revision value ['", "+", "revString", "+", "']'", ";", "}", "}", "else", "{", "err", "=", "'Could not parse info result to get revision ['", "+", "JSON", ".", "stringify", "(", "data", ")", "+", "']'", ";", "}", "}", "callback", "(", "err", ",", "rev", ")", ";", "}", ")", ";", "}" ]
'lastChangeRevision' option returns the last commit revision, instead of the working copy revision Gets head revision of a given URL @function getRevision @memberof util @param {string} target - Target URL @param {object} [options] - Options object @param {function} [callback] - Complete callback
[ "lastChangeRevision", "option", "returns", "the", "last", "commit", "revision", "instead", "of", "the", "working", "copy", "revision", "Gets", "head", "revision", "of", "a", "given", "URL" ]
06d1aeec895c737265c1689520b63aeaf7eca729
https://github.com/peteward44/node-svn-ultimate/blob/06d1aeec895c737265c1689520b63aeaf7eca729/index.js#L929-L961
21,647
peteward44/node-svn-ultimate
index.js
function( wcDir, options, callback ) { if ( typeof options === "function" ) { callback = options; options = null; } options = options || {}; if ( !Array.isArray( wcDir ) ) { wcDir = [wcDir]; } var args = [ '-n' ]; if ( options.lastChangeRevision ) { args.push( '-c' ); } execSvnVersion( wcDir.concat( args ), options, function( err, data ) { var result; if ( !err ) { var match = data.match( /(\d+):?(\d*)(\w*)/ ); if ( match ) { result = {}; result.low = parseInt( match[1] ); if ( match[2].length > 0 ) { result.high = parseInt( match[2] ); } else { result.high = result.low; } result.flags = match[3]; if ( result.flags.length > 0 ) { result.modified = result.flags.indexOf( 'M' ) >= 0; result.partial = result.flags.indexOf( 'P' ) >= 0; result.switched = result.flags.indexOf( 'S' ) >= 0; } } else { err = data; } } callback( err, result ); } ); }
javascript
function( wcDir, options, callback ) { if ( typeof options === "function" ) { callback = options; options = null; } options = options || {}; if ( !Array.isArray( wcDir ) ) { wcDir = [wcDir]; } var args = [ '-n' ]; if ( options.lastChangeRevision ) { args.push( '-c' ); } execSvnVersion( wcDir.concat( args ), options, function( err, data ) { var result; if ( !err ) { var match = data.match( /(\d+):?(\d*)(\w*)/ ); if ( match ) { result = {}; result.low = parseInt( match[1] ); if ( match[2].length > 0 ) { result.high = parseInt( match[2] ); } else { result.high = result.low; } result.flags = match[3]; if ( result.flags.length > 0 ) { result.modified = result.flags.indexOf( 'M' ) >= 0; result.partial = result.flags.indexOf( 'P' ) >= 0; result.switched = result.flags.indexOf( 'S' ) >= 0; } } else { err = data; } } callback( err, result ); } ); }
[ "function", "(", "wcDir", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "\"function\"", ")", "{", "callback", "=", "options", ";", "options", "=", "null", ";", "}", "options", "=", "options", "||", "{", "}", ";", "if", "(", "!", "Array", ".", "isArray", "(", "wcDir", ")", ")", "{", "wcDir", "=", "[", "wcDir", "]", ";", "}", "var", "args", "=", "[", "'-n'", "]", ";", "if", "(", "options", ".", "lastChangeRevision", ")", "{", "args", ".", "push", "(", "'-c'", ")", ";", "}", "execSvnVersion", "(", "wcDir", ".", "concat", "(", "args", ")", ",", "options", ",", "function", "(", "err", ",", "data", ")", "{", "var", "result", ";", "if", "(", "!", "err", ")", "{", "var", "match", "=", "data", ".", "match", "(", "/", "(\\d+):?(\\d*)(\\w*)", "/", ")", ";", "if", "(", "match", ")", "{", "result", "=", "{", "}", ";", "result", ".", "low", "=", "parseInt", "(", "match", "[", "1", "]", ")", ";", "if", "(", "match", "[", "2", "]", ".", "length", ">", "0", ")", "{", "result", ".", "high", "=", "parseInt", "(", "match", "[", "2", "]", ")", ";", "}", "else", "{", "result", ".", "high", "=", "result", ".", "low", ";", "}", "result", ".", "flags", "=", "match", "[", "3", "]", ";", "if", "(", "result", ".", "flags", ".", "length", ">", "0", ")", "{", "result", ".", "modified", "=", "result", ".", "flags", ".", "indexOf", "(", "'M'", ")", ">=", "0", ";", "result", ".", "partial", "=", "result", ".", "flags", ".", "indexOf", "(", "'P'", ")", ">=", "0", ";", "result", ".", "switched", "=", "result", ".", "flags", ".", "indexOf", "(", "'S'", ")", ">=", "0", ";", "}", "}", "else", "{", "err", "=", "data", ";", "}", "}", "callback", "(", "err", ",", "result", ")", ";", "}", ")", ";", "}" ]
Gets the revision of a working copy. @function getWorkingCopyRevision @memberof util @param {string} wcDir - Working copy folder @param {object} [options] - Options object @param {function} [callback] - Complete callback
[ "Gets", "the", "revision", "of", "a", "working", "copy", "." ]
06d1aeec895c737265c1689520b63aeaf7eca729
https://github.com/peteward44/node-svn-ultimate/blob/06d1aeec895c737265c1689520b63aeaf7eca729/index.js#L972-L1009
21,648
peteward44/node-svn-ultimate
index.js
function( url ) { var trunkMatch = url.match( /(.*)\/(trunk|branches|tags)\/*(.*)\/*(.*)$/i ); if ( trunkMatch ) { var rootUrl = trunkMatch[1]; var projectName = rootUrl.match( /\/([^\/]+)$/ )[1]; return { rootUrl: rootUrl, projectName: projectName, type: trunkMatch[2], typeName: trunkMatch[3], trunkUrl: trunkMatch[1] + "/trunk", tagsUrl: trunkMatch[1] + "/tags", branchesUrl: trunkMatch[1] + "/branches" }; } throw new Error( "parseUrl: Url does not look like an SVN repository" ); }
javascript
function( url ) { var trunkMatch = url.match( /(.*)\/(trunk|branches|tags)\/*(.*)\/*(.*)$/i ); if ( trunkMatch ) { var rootUrl = trunkMatch[1]; var projectName = rootUrl.match( /\/([^\/]+)$/ )[1]; return { rootUrl: rootUrl, projectName: projectName, type: trunkMatch[2], typeName: trunkMatch[3], trunkUrl: trunkMatch[1] + "/trunk", tagsUrl: trunkMatch[1] + "/tags", branchesUrl: trunkMatch[1] + "/branches" }; } throw new Error( "parseUrl: Url does not look like an SVN repository" ); }
[ "function", "(", "url", ")", "{", "var", "trunkMatch", "=", "url", ".", "match", "(", "/", "(.*)\\/(trunk|branches|tags)\\/*(.*)\\/*(.*)$", "/", "i", ")", ";", "if", "(", "trunkMatch", ")", "{", "var", "rootUrl", "=", "trunkMatch", "[", "1", "]", ";", "var", "projectName", "=", "rootUrl", ".", "match", "(", "/", "\\/([^\\/]+)$", "/", ")", "[", "1", "]", ";", "return", "{", "rootUrl", ":", "rootUrl", ",", "projectName", ":", "projectName", ",", "type", ":", "trunkMatch", "[", "2", "]", ",", "typeName", ":", "trunkMatch", "[", "3", "]", ",", "trunkUrl", ":", "trunkMatch", "[", "1", "]", "+", "\"/trunk\"", ",", "tagsUrl", ":", "trunkMatch", "[", "1", "]", "+", "\"/tags\"", ",", "branchesUrl", ":", "trunkMatch", "[", "1", "]", "+", "\"/branches\"", "}", ";", "}", "throw", "new", "Error", "(", "\"parseUrl: Url does not look like an SVN repository\"", ")", ";", "}" ]
Parse a url for an SVN project repository and breaks it apart @function parseUrl @memberof util @param {string} url - URL to parse @returns {object}
[ "Parse", "a", "url", "for", "an", "SVN", "project", "repository", "and", "breaks", "it", "apart" ]
06d1aeec895c737265c1689520b63aeaf7eca729
https://github.com/peteward44/node-svn-ultimate/blob/06d1aeec895c737265c1689520b63aeaf7eca729/index.js#L1019-L1035
21,649
peteward44/node-svn-ultimate
index.js
function( url, options, callback ) { if ( typeof options === "function" ) { callback = options; options = null; } options = options || {}; var tagsUrl = parseUrl( url ).tagsUrl; list( tagsUrl, options, function( err, data ) { var result = []; if ( !err && data && data.list && data.list.entry ) { if ( Array.isArray( data.list.entry ) ) { result = data.list.entry.filter( function( entry ) { return entry && entry.$ && entry.$.kind === "dir"; } ); } else { if ( data.list.entry.$ && data.list.entry.$.kind === "dir" ) { result = [ data.list.entry ]; } } } callback( err, result ); } ); }
javascript
function( url, options, callback ) { if ( typeof options === "function" ) { callback = options; options = null; } options = options || {}; var tagsUrl = parseUrl( url ).tagsUrl; list( tagsUrl, options, function( err, data ) { var result = []; if ( !err && data && data.list && data.list.entry ) { if ( Array.isArray( data.list.entry ) ) { result = data.list.entry.filter( function( entry ) { return entry && entry.$ && entry.$.kind === "dir"; } ); } else { if ( data.list.entry.$ && data.list.entry.$.kind === "dir" ) { result = [ data.list.entry ]; } } } callback( err, result ); } ); }
[ "function", "(", "url", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "\"function\"", ")", "{", "callback", "=", "options", ";", "options", "=", "null", ";", "}", "options", "=", "options", "||", "{", "}", ";", "var", "tagsUrl", "=", "parseUrl", "(", "url", ")", ".", "tagsUrl", ";", "list", "(", "tagsUrl", ",", "options", ",", "function", "(", "err", ",", "data", ")", "{", "var", "result", "=", "[", "]", ";", "if", "(", "!", "err", "&&", "data", "&&", "data", ".", "list", "&&", "data", ".", "list", ".", "entry", ")", "{", "if", "(", "Array", ".", "isArray", "(", "data", ".", "list", ".", "entry", ")", ")", "{", "result", "=", "data", ".", "list", ".", "entry", ".", "filter", "(", "function", "(", "entry", ")", "{", "return", "entry", "&&", "entry", ".", "$", "&&", "entry", ".", "$", ".", "kind", "===", "\"dir\"", ";", "}", ")", ";", "}", "else", "{", "if", "(", "data", ".", "list", ".", "entry", ".", "$", "&&", "data", ".", "list", ".", "entry", ".", "$", ".", "kind", "===", "\"dir\"", ")", "{", "result", "=", "[", "data", ".", "list", ".", "entry", "]", ";", "}", "}", "}", "callback", "(", "err", ",", "result", ")", ";", "}", ")", ";", "}" ]
Gets all available tags for the given svn URL @function getTags @memberof util @param {string} url - Project URL to get tags for @param {object} [options] - Options object @param {function} [callback] - Complete callback
[ "Gets", "all", "available", "tags", "for", "the", "given", "svn", "URL" ]
06d1aeec895c737265c1689520b63aeaf7eca729
https://github.com/peteward44/node-svn-ultimate/blob/06d1aeec895c737265c1689520b63aeaf7eca729/index.js#L1045-L1067
21,650
peteward44/node-svn-ultimate
index.js
function( url, options, callback ) { if ( typeof options === "function" ) { callback = options; options = null; } options = options || {}; getTags( url, options, function( err, tagArray ) { var latest; if ( !err && Array.isArray( tagArray ) && tagArray.length > 0 ) { tagArray.sort( function( a, b ) { try { return semver.rcompare( a.name, b.name ); } catch ( err2 ) { return -1; } } ); latest = tagArray[0]; } callback( err, latest ); } ); }
javascript
function( url, options, callback ) { if ( typeof options === "function" ) { callback = options; options = null; } options = options || {}; getTags( url, options, function( err, tagArray ) { var latest; if ( !err && Array.isArray( tagArray ) && tagArray.length > 0 ) { tagArray.sort( function( a, b ) { try { return semver.rcompare( a.name, b.name ); } catch ( err2 ) { return -1; } } ); latest = tagArray[0]; } callback( err, latest ); } ); }
[ "function", "(", "url", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "\"function\"", ")", "{", "callback", "=", "options", ";", "options", "=", "null", ";", "}", "options", "=", "options", "||", "{", "}", ";", "getTags", "(", "url", ",", "options", ",", "function", "(", "err", ",", "tagArray", ")", "{", "var", "latest", ";", "if", "(", "!", "err", "&&", "Array", ".", "isArray", "(", "tagArray", ")", "&&", "tagArray", ".", "length", ">", "0", ")", "{", "tagArray", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "try", "{", "return", "semver", ".", "rcompare", "(", "a", ".", "name", ",", "b", ".", "name", ")", ";", "}", "catch", "(", "err2", ")", "{", "return", "-", "1", ";", "}", "}", ")", ";", "latest", "=", "tagArray", "[", "0", "]", ";", "}", "callback", "(", "err", ",", "latest", ")", ";", "}", ")", ";", "}" ]
Uses node's semver package to work out the latest tag value @function getLatestTag @memberof util @param {string} url - Project URL to get latest tag for @param {object} options - Options object @param {function} [callback] - Complete callback
[ "Uses", "node", "s", "semver", "package", "to", "work", "out", "the", "latest", "tag", "value" ]
06d1aeec895c737265c1689520b63aeaf7eca729
https://github.com/peteward44/node-svn-ultimate/blob/06d1aeec895c737265c1689520b63aeaf7eca729/index.js#L1078-L1099
21,651
peteward44/node-svn-ultimate
index.js
function( options ) { this._options = options || {}; this._commands = []; this._options.tempFolder = this._options.tempFolder || path.join( os.tmpdir(), 'mucc_' + uuid.v4() ); }
javascript
function( options ) { this._options = options || {}; this._commands = []; this._options.tempFolder = this._options.tempFolder || path.join( os.tmpdir(), 'mucc_' + uuid.v4() ); }
[ "function", "(", "options", ")", "{", "this", ".", "_options", "=", "options", "||", "{", "}", ";", "this", ".", "_commands", "=", "[", "]", ";", "this", ".", "_options", ".", "tempFolder", "=", "this", ".", "_options", ".", "tempFolder", "||", "path", ".", "join", "(", "os", ".", "tmpdir", "(", ")", ",", "'mucc_'", "+", "uuid", ".", "v4", "(", ")", ")", ";", "}" ]
Helper object for using SVNMUCC
[ "Helper", "object", "for", "using", "SVNMUCC" ]
06d1aeec895c737265c1689520b63aeaf7eca729
https://github.com/peteward44/node-svn-ultimate/blob/06d1aeec895c737265c1689520b63aeaf7eca729/index.js#L1137-L1141
21,652
titon/toolkit
js/components/stalker.js
function(element, options) { element = this.setElement(element); options = this.setOptions(options); if (!options.target || !options.marker) { throw new Error('A marker and target is required'); } if (element.css('overflow') === 'auto') { this.container = element; } // Initialize events this.addEvents([ ['scroll', 'container', $.throttle(this.onScroll.bind(this), options.throttle)], ['ready', 'document', 'onScroll'] ]); this.initialize(); // Gather markets and targets this.refresh(); }
javascript
function(element, options) { element = this.setElement(element); options = this.setOptions(options); if (!options.target || !options.marker) { throw new Error('A marker and target is required'); } if (element.css('overflow') === 'auto') { this.container = element; } // Initialize events this.addEvents([ ['scroll', 'container', $.throttle(this.onScroll.bind(this), options.throttle)], ['ready', 'document', 'onScroll'] ]); this.initialize(); // Gather markets and targets this.refresh(); }
[ "function", "(", "element", ",", "options", ")", "{", "element", "=", "this", ".", "setElement", "(", "element", ")", ";", "options", "=", "this", ".", "setOptions", "(", "options", ")", ";", "if", "(", "!", "options", ".", "target", "||", "!", "options", ".", "marker", ")", "{", "throw", "new", "Error", "(", "'A marker and target is required'", ")", ";", "}", "if", "(", "element", ".", "css", "(", "'overflow'", ")", "===", "'auto'", ")", "{", "this", ".", "container", "=", "element", ";", "}", "// Initialize events", "this", ".", "addEvents", "(", "[", "[", "'scroll'", ",", "'container'", ",", "$", ".", "throttle", "(", "this", ".", "onScroll", ".", "bind", "(", "this", ")", ",", "options", ".", "throttle", ")", "]", ",", "[", "'ready'", ",", "'document'", ",", "'onScroll'", "]", "]", ")", ";", "this", ".", "initialize", "(", ")", ";", "// Gather markets and targets", "this", ".", "refresh", "(", ")", ";", "}" ]
Initialize the stalker. @param {jQuery} element @param {Object} [options]
[ "Initialize", "the", "stalker", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/stalker.js#L36-L58
21,653
titon/toolkit
js/components/stalker.js
function(marker, type) { marker = $(marker); // Stop all the unnecessary processing if (type === 'activate' && marker.hasClass('is-stalked')) { return; } else if (type === 'deactivate' && !marker.hasClass('is-stalked')) { return; } var options = this.options, targetBy = options.targetBy, markBy = options.markBy, target = this.targets.filter(function() { return $(this).attr(targetBy).replace('#', '') === marker.attr(markBy); }), before, after, method; if (type === 'activate') { before = 'activating'; after = 'activated'; method = 'addClass'; } else { before = 'deactivating'; after = 'deactivated'; method = 'removeClass'; } this.fireEvent(before, [marker, target]); marker[method]('is-stalked'); target[method]('is-active'); this.fireEvent(after, [marker, target]); }
javascript
function(marker, type) { marker = $(marker); // Stop all the unnecessary processing if (type === 'activate' && marker.hasClass('is-stalked')) { return; } else if (type === 'deactivate' && !marker.hasClass('is-stalked')) { return; } var options = this.options, targetBy = options.targetBy, markBy = options.markBy, target = this.targets.filter(function() { return $(this).attr(targetBy).replace('#', '') === marker.attr(markBy); }), before, after, method; if (type === 'activate') { before = 'activating'; after = 'activated'; method = 'addClass'; } else { before = 'deactivating'; after = 'deactivated'; method = 'removeClass'; } this.fireEvent(before, [marker, target]); marker[method]('is-stalked'); target[method]('is-active'); this.fireEvent(after, [marker, target]); }
[ "function", "(", "marker", ",", "type", ")", "{", "marker", "=", "$", "(", "marker", ")", ";", "// Stop all the unnecessary processing", "if", "(", "type", "===", "'activate'", "&&", "marker", ".", "hasClass", "(", "'is-stalked'", ")", ")", "{", "return", ";", "}", "else", "if", "(", "type", "===", "'deactivate'", "&&", "!", "marker", ".", "hasClass", "(", "'is-stalked'", ")", ")", "{", "return", ";", "}", "var", "options", "=", "this", ".", "options", ",", "targetBy", "=", "options", ".", "targetBy", ",", "markBy", "=", "options", ".", "markBy", ",", "target", "=", "this", ".", "targets", ".", "filter", "(", "function", "(", ")", "{", "return", "$", "(", "this", ")", ".", "attr", "(", "targetBy", ")", ".", "replace", "(", "'#'", ",", "''", ")", "===", "marker", ".", "attr", "(", "markBy", ")", ";", "}", ")", ",", "before", ",", "after", ",", "method", ";", "if", "(", "type", "===", "'activate'", ")", "{", "before", "=", "'activating'", ";", "after", "=", "'activated'", ";", "method", "=", "'addClass'", ";", "}", "else", "{", "before", "=", "'deactivating'", ";", "after", "=", "'deactivated'", ";", "method", "=", "'removeClass'", ";", "}", "this", ".", "fireEvent", "(", "before", ",", "[", "marker", ",", "target", "]", ")", ";", "marker", "[", "method", "]", "(", "'is-stalked'", ")", ";", "target", "[", "method", "]", "(", "'is-active'", ")", ";", "this", ".", "fireEvent", "(", "after", ",", "[", "marker", ",", "target", "]", ")", ";", "}" ]
Either active or deactivate a target based on the marker. @param {Element} marker @param {String} type
[ "Either", "active", "or", "deactivate", "a", "target", "based", "on", "the", "marker", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/stalker.js#L92-L128
21,654
titon/toolkit
js/components/stalker.js
function() { var isWindow = this.container.is(window), eTop = this.element.offset().top, offset, offsets = []; if (this.element.css('overflow') === 'auto' && !this.element.is('body')) { this.element[0].scrollTop = 0; // Set scroll to top so offsets are correct } this.targets = $(this.options.target); this.markers = $(this.options.marker).each(function(index, marker) { offset = $(marker).offset(); if (!isWindow) { offset.top -= eTop; } offsets.push(offset); }); this.offsets = offsets; }
javascript
function() { var isWindow = this.container.is(window), eTop = this.element.offset().top, offset, offsets = []; if (this.element.css('overflow') === 'auto' && !this.element.is('body')) { this.element[0].scrollTop = 0; // Set scroll to top so offsets are correct } this.targets = $(this.options.target); this.markers = $(this.options.marker).each(function(index, marker) { offset = $(marker).offset(); if (!isWindow) { offset.top -= eTop; } offsets.push(offset); }); this.offsets = offsets; }
[ "function", "(", ")", "{", "var", "isWindow", "=", "this", ".", "container", ".", "is", "(", "window", ")", ",", "eTop", "=", "this", ".", "element", ".", "offset", "(", ")", ".", "top", ",", "offset", ",", "offsets", "=", "[", "]", ";", "if", "(", "this", ".", "element", ".", "css", "(", "'overflow'", ")", "===", "'auto'", "&&", "!", "this", ".", "element", ".", "is", "(", "'body'", ")", ")", "{", "this", ".", "element", "[", "0", "]", ".", "scrollTop", "=", "0", ";", "// Set scroll to top so offsets are correct", "}", "this", ".", "targets", "=", "$", "(", "this", ".", "options", ".", "target", ")", ";", "this", ".", "markers", "=", "$", "(", "this", ".", "options", ".", "marker", ")", ".", "each", "(", "function", "(", "index", ",", "marker", ")", "{", "offset", "=", "$", "(", "marker", ")", ".", "offset", "(", ")", ";", "if", "(", "!", "isWindow", ")", "{", "offset", ".", "top", "-=", "eTop", ";", "}", "offsets", ".", "push", "(", "offset", ")", ";", "}", ")", ";", "this", ".", "offsets", "=", "offsets", ";", "}" ]
Gather the targets and markers used for stalking.
[ "Gather", "the", "targets", "and", "markers", "used", "for", "stalking", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/stalker.js#L133-L156
21,655
titon/toolkit
js/components/stalker.js
function() { var scroll = this.container.scrollTop(), offsets = this.offsets, onlyWithin = this.options.onlyWithin, threshold = this.options.threshold; this.markers.each(function(index, marker) { marker = $(marker); var offset = offsets[index], top = offset.top - threshold, bot = offset.top + marker.height() - threshold; // Scroll is within the marker if ( (onlyWithin && scroll >= top && scroll <= bot) || (!onlyWithin && scroll >= top) ) { this.activate(marker); // Scroll went outside the marker } else { this.deactivate(marker); } }.bind(this)); this.fireEvent('scroll'); }
javascript
function() { var scroll = this.container.scrollTop(), offsets = this.offsets, onlyWithin = this.options.onlyWithin, threshold = this.options.threshold; this.markers.each(function(index, marker) { marker = $(marker); var offset = offsets[index], top = offset.top - threshold, bot = offset.top + marker.height() - threshold; // Scroll is within the marker if ( (onlyWithin && scroll >= top && scroll <= bot) || (!onlyWithin && scroll >= top) ) { this.activate(marker); // Scroll went outside the marker } else { this.deactivate(marker); } }.bind(this)); this.fireEvent('scroll'); }
[ "function", "(", ")", "{", "var", "scroll", "=", "this", ".", "container", ".", "scrollTop", "(", ")", ",", "offsets", "=", "this", ".", "offsets", ",", "onlyWithin", "=", "this", ".", "options", ".", "onlyWithin", ",", "threshold", "=", "this", ".", "options", ".", "threshold", ";", "this", ".", "markers", ".", "each", "(", "function", "(", "index", ",", "marker", ")", "{", "marker", "=", "$", "(", "marker", ")", ";", "var", "offset", "=", "offsets", "[", "index", "]", ",", "top", "=", "offset", ".", "top", "-", "threshold", ",", "bot", "=", "offset", ".", "top", "+", "marker", ".", "height", "(", ")", "-", "threshold", ";", "// Scroll is within the marker", "if", "(", "(", "onlyWithin", "&&", "scroll", ">=", "top", "&&", "scroll", "<=", "bot", ")", "||", "(", "!", "onlyWithin", "&&", "scroll", ">=", "top", ")", ")", "{", "this", ".", "activate", "(", "marker", ")", ";", "// Scroll went outside the marker", "}", "else", "{", "this", ".", "deactivate", "(", "marker", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "fireEvent", "(", "'scroll'", ")", ";", "}" ]
While the element is being scrolled, notify the targets when a marker is reached. @private
[ "While", "the", "element", "is", "being", "scrolled", "notify", "the", "targets", "when", "a", "marker", "is", "reached", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/stalker.js#L163-L190
21,656
titon/toolkit
js/components/matrix.js
function(element, options) { this.setElement(element); this.setOptions(options, this.element); // Set events this.addEvent('horizontalresize', 'window', $.debounce(this.onResize.bind(this))); this.initialize(); // Render the matrix this.refresh(); }
javascript
function(element, options) { this.setElement(element); this.setOptions(options, this.element); // Set events this.addEvent('horizontalresize', 'window', $.debounce(this.onResize.bind(this))); this.initialize(); // Render the matrix this.refresh(); }
[ "function", "(", "element", ",", "options", ")", "{", "this", ".", "setElement", "(", "element", ")", ";", "this", ".", "setOptions", "(", "options", ",", "this", ".", "element", ")", ";", "// Set events", "this", ".", "addEvent", "(", "'horizontalresize'", ",", "'window'", ",", "$", ".", "debounce", "(", "this", ".", "onResize", ".", "bind", "(", "this", ")", ")", ")", ";", "this", ".", "initialize", "(", ")", ";", "// Render the matrix", "this", ".", "refresh", "(", ")", ";", "}" ]
Initialize the matrix. @param {jQuery} element @param {Object} [options]
[ "Initialize", "the", "matrix", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/matrix.js#L47-L58
21,657
titon/toolkit
js/components/matrix.js
function() { this.items = this.element.find('> li').each(function() { var self = $(this); // Cache the initial column width self.cache('matrix-column-width', self.outerWidth()); }); if (this.options.defer) { this._deferRender(); } else { this.render(); } }
javascript
function() { this.items = this.element.find('> li').each(function() { var self = $(this); // Cache the initial column width self.cache('matrix-column-width', self.outerWidth()); }); if (this.options.defer) { this._deferRender(); } else { this.render(); } }
[ "function", "(", ")", "{", "this", ".", "items", "=", "this", ".", "element", ".", "find", "(", "'> li'", ")", ".", "each", "(", "function", "(", ")", "{", "var", "self", "=", "$", "(", "this", ")", ";", "// Cache the initial column width", "self", ".", "cache", "(", "'matrix-column-width'", ",", "self", ".", "outerWidth", "(", ")", ")", ";", "}", ")", ";", "if", "(", "this", ".", "options", ".", "defer", ")", "{", "this", ".", "_deferRender", "(", ")", ";", "}", "else", "{", "this", ".", "render", "(", ")", ";", "}", "}" ]
Fetch new items and re-render the grid.
[ "Fetch", "new", "items", "and", "re", "-", "render", "the", "grid", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/matrix.js#L101-L114
21,658
titon/toolkit
js/components/matrix.js
function() { this._calculateColumns(); this.fireEvent('rendering'); var element = this.element, items = this.items; // No items if (!items.length) { element.removeAttr('style'); // Single column } else if (this.colCount <= 1) { element.removeAttr('style').addClass('no-columns'); items.removeAttr('style'); // Multi column } else { element.removeClass('no-columns'); this._organizeItems(); this._positionItems(); } this.fireEvent('rendered'); }
javascript
function() { this._calculateColumns(); this.fireEvent('rendering'); var element = this.element, items = this.items; // No items if (!items.length) { element.removeAttr('style'); // Single column } else if (this.colCount <= 1) { element.removeAttr('style').addClass('no-columns'); items.removeAttr('style'); // Multi column } else { element.removeClass('no-columns'); this._organizeItems(); this._positionItems(); } this.fireEvent('rendered'); }
[ "function", "(", ")", "{", "this", ".", "_calculateColumns", "(", ")", ";", "this", ".", "fireEvent", "(", "'rendering'", ")", ";", "var", "element", "=", "this", ".", "element", ",", "items", "=", "this", ".", "items", ";", "// No items", "if", "(", "!", "items", ".", "length", ")", "{", "element", ".", "removeAttr", "(", "'style'", ")", ";", "// Single column", "}", "else", "if", "(", "this", ".", "colCount", "<=", "1", ")", "{", "element", ".", "removeAttr", "(", "'style'", ")", ".", "addClass", "(", "'no-columns'", ")", ";", "items", ".", "removeAttr", "(", "'style'", ")", ";", "// Multi column", "}", "else", "{", "element", ".", "removeClass", "(", "'no-columns'", ")", ";", "this", ".", "_organizeItems", "(", ")", ";", "this", ".", "_positionItems", "(", ")", ";", "}", "this", ".", "fireEvent", "(", "'rendered'", ")", ";", "}" ]
Calculate and position items in the grid.
[ "Calculate", "and", "position", "items", "in", "the", "grid", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/matrix.js#L135-L161
21,659
titon/toolkit
js/components/matrix.js
function() { var wrapperWidth = this.element.outerWidth(), colWidth = this.options.width, gutter = this.options.gutter, cols = Math.max(Math.floor(wrapperWidth / colWidth), 1), colsWidth = (cols * (colWidth + gutter)) - gutter, diff; if (cols > 1) { if (colsWidth > wrapperWidth) { diff = colsWidth - wrapperWidth; colWidth -= (diff / cols); } else if (colsWidth < wrapperWidth) { diff = wrapperWidth - colsWidth; colWidth += (diff / cols); } } this.wrapperWidth = wrapperWidth; this.colWidth = colWidth; this.colCount = cols; }
javascript
function() { var wrapperWidth = this.element.outerWidth(), colWidth = this.options.width, gutter = this.options.gutter, cols = Math.max(Math.floor(wrapperWidth / colWidth), 1), colsWidth = (cols * (colWidth + gutter)) - gutter, diff; if (cols > 1) { if (colsWidth > wrapperWidth) { diff = colsWidth - wrapperWidth; colWidth -= (diff / cols); } else if (colsWidth < wrapperWidth) { diff = wrapperWidth - colsWidth; colWidth += (diff / cols); } } this.wrapperWidth = wrapperWidth; this.colWidth = colWidth; this.colCount = cols; }
[ "function", "(", ")", "{", "var", "wrapperWidth", "=", "this", ".", "element", ".", "outerWidth", "(", ")", ",", "colWidth", "=", "this", ".", "options", ".", "width", ",", "gutter", "=", "this", ".", "options", ".", "gutter", ",", "cols", "=", "Math", ".", "max", "(", "Math", ".", "floor", "(", "wrapperWidth", "/", "colWidth", ")", ",", "1", ")", ",", "colsWidth", "=", "(", "cols", "*", "(", "colWidth", "+", "gutter", ")", ")", "-", "gutter", ",", "diff", ";", "if", "(", "cols", ">", "1", ")", "{", "if", "(", "colsWidth", ">", "wrapperWidth", ")", "{", "diff", "=", "colsWidth", "-", "wrapperWidth", ";", "colWidth", "-=", "(", "diff", "/", "cols", ")", ";", "}", "else", "if", "(", "colsWidth", "<", "wrapperWidth", ")", "{", "diff", "=", "wrapperWidth", "-", "colsWidth", ";", "colWidth", "+=", "(", "diff", "/", "cols", ")", ";", "}", "}", "this", ".", "wrapperWidth", "=", "wrapperWidth", ";", "this", ".", "colWidth", "=", "colWidth", ";", "this", ".", "colCount", "=", "cols", ";", "}" ]
Calculate how many columns can be supported in the current resolution. Modify the column width to account for gaps on either side. @private
[ "Calculate", "how", "many", "columns", "can", "be", "supported", "in", "the", "current", "resolution", ".", "Modify", "the", "column", "width", "to", "account", "for", "gaps", "on", "either", "side", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/matrix.js#L169-L191
21,660
titon/toolkit
js/components/matrix.js
function() { var promises = []; this.images = this.element.find('img').each(function(index, image) { if (image.complete) { return; // Already loaded } var src = image.src, def = $.Deferred(); image.onload = def.resolve; image.onerror = image.onabort = def.reject; image.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=='; image.src = src; promises.push(def.promise()); }); $.when.apply($, promises).always(this.render.bind(this)); }
javascript
function() { var promises = []; this.images = this.element.find('img').each(function(index, image) { if (image.complete) { return; // Already loaded } var src = image.src, def = $.Deferred(); image.onload = def.resolve; image.onerror = image.onabort = def.reject; image.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=='; image.src = src; promises.push(def.promise()); }); $.when.apply($, promises).always(this.render.bind(this)); }
[ "function", "(", ")", "{", "var", "promises", "=", "[", "]", ";", "this", ".", "images", "=", "this", ".", "element", ".", "find", "(", "'img'", ")", ".", "each", "(", "function", "(", "index", ",", "image", ")", "{", "if", "(", "image", ".", "complete", ")", "{", "return", ";", "// Already loaded", "}", "var", "src", "=", "image", ".", "src", ",", "def", "=", "$", ".", "Deferred", "(", ")", ";", "image", ".", "onload", "=", "def", ".", "resolve", ";", "image", ".", "onerror", "=", "image", ".", "onabort", "=", "def", ".", "reject", ";", "image", ".", "src", "=", "'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=='", ";", "image", ".", "src", "=", "src", ";", "promises", ".", "push", "(", "def", ".", "promise", "(", ")", ")", ";", "}", ")", ";", "$", ".", "when", ".", "apply", "(", "$", ",", "promises", ")", ".", "always", "(", "this", ".", "render", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Fetch all images within the matrix and attach an onload event. This will monitor loaded images and render once all are complete. Uses a src swap trick to force load cached images. @private
[ "Fetch", "all", "images", "within", "the", "matrix", "and", "attach", "an", "onload", "event", ".", "This", "will", "monitor", "loaded", "images", "and", "render", "once", "all", "are", "complete", ".", "Uses", "a", "src", "swap", "trick", "to", "force", "load", "cached", "images", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/matrix.js#L200-L220
21,661
titon/toolkit
js/components/matrix.js
function() { var item, span, size, l = this.items.length; this.matrix = []; for (var i = 0; i < l; i++) { item = this.items.eq(i); size = item.data('matrix-column-width'); // How many columns does this item span? span = Math.max(Math.round(size / this.colWidth), 1); // Span cannot be larger than the total number of columns if (span > this.colCount) { span = this.colCount; } this.matrix.push({ item: item, span: span }); // Multiple columns if (span > 1) { for (var s = 1; s < span; s++) { if (this.matrix) { this.matrix.push({ item: item, span: false // Indicates an empty space }); } } } } }
javascript
function() { var item, span, size, l = this.items.length; this.matrix = []; for (var i = 0; i < l; i++) { item = this.items.eq(i); size = item.data('matrix-column-width'); // How many columns does this item span? span = Math.max(Math.round(size / this.colWidth), 1); // Span cannot be larger than the total number of columns if (span > this.colCount) { span = this.colCount; } this.matrix.push({ item: item, span: span }); // Multiple columns if (span > 1) { for (var s = 1; s < span; s++) { if (this.matrix) { this.matrix.push({ item: item, span: false // Indicates an empty space }); } } } } }
[ "function", "(", ")", "{", "var", "item", ",", "span", ",", "size", ",", "l", "=", "this", ".", "items", ".", "length", ";", "this", ".", "matrix", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "l", ";", "i", "++", ")", "{", "item", "=", "this", ".", "items", ".", "eq", "(", "i", ")", ";", "size", "=", "item", ".", "data", "(", "'matrix-column-width'", ")", ";", "// How many columns does this item span?", "span", "=", "Math", ".", "max", "(", "Math", ".", "round", "(", "size", "/", "this", ".", "colWidth", ")", ",", "1", ")", ";", "// Span cannot be larger than the total number of columns", "if", "(", "span", ">", "this", ".", "colCount", ")", "{", "span", "=", "this", ".", "colCount", ";", "}", "this", ".", "matrix", ".", "push", "(", "{", "item", ":", "item", ",", "span", ":", "span", "}", ")", ";", "// Multiple columns", "if", "(", "span", ">", "1", ")", "{", "for", "(", "var", "s", "=", "1", ";", "s", "<", "span", ";", "s", "++", ")", "{", "if", "(", "this", ".", "matrix", ")", "{", "this", ".", "matrix", ".", "push", "(", "{", "item", ":", "item", ",", "span", ":", "false", "// Indicates an empty space", "}", ")", ";", "}", "}", "}", "}", "}" ]
Organize the items into columns by looping over each item and calculating dimensions. If an item spans multiple columns, account for it by filling with an empty space. @private
[ "Organize", "the", "items", "into", "columns", "by", "looping", "over", "each", "item", "and", "calculating", "dimensions", ".", "If", "an", "item", "spans", "multiple", "columns", "account", "for", "it", "by", "filling", "with", "an", "empty", "space", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/matrix.js#L228-L265
21,662
titon/toolkit
js/components/matrix.js
function() { var gutter = this.options.gutter, items = this.matrix, item, span, dir = this.options.rtl ? 'right' : 'left', y = [], // The top position values indexed by column c = 0, // Current column in the loop h = 0, // Smallest height column i, // Items loop counter l, // Items length s, // Current span column in the loop top, pos = { margin: 0, position: 'absolute' }; for (i = 0; i < this.colCount; i++) { y.push(0); } for (i = 0, l = items.length; i < l; i++) { item = items[i]; span = item.span; // Place the item in the smallest column h = -1; for (s = 0; s < this.colCount; s++) { if (h === -1 || y[s] < h) { h = y[s]; c = s; } } // If the item extends too far out, move it to the next column // Or if the last column has been reached if ((c >= this.colCount) || ((span + c) > this.colCount)) { c = 0; } // Item spans a column or multiple columns if (span) { top = 0; // If the item spans multiple columns // Get the largest height from the previous row for (s = 0; s < span; s++) { if (y[c + s] > top) { top = y[c + s]; } } // Position the item pos.top = top; pos[dir] = (this.colWidth + gutter) * c; pos.width = ((this.colWidth + gutter) * span) - gutter; item.item.css(pos).reveal(); // Loop again to add the value to each columns Y top value // This must be done after positioning so we can calculate a new size for (s = 0; s < span; s++) { y[c + s] = item.item.outerHeight() + gutter + top; } } this.colHeights[c] = y[c]; c++; } // Set height of wrapper this.element.css('height', Math.max.apply(Math, y)); }
javascript
function() { var gutter = this.options.gutter, items = this.matrix, item, span, dir = this.options.rtl ? 'right' : 'left', y = [], // The top position values indexed by column c = 0, // Current column in the loop h = 0, // Smallest height column i, // Items loop counter l, // Items length s, // Current span column in the loop top, pos = { margin: 0, position: 'absolute' }; for (i = 0; i < this.colCount; i++) { y.push(0); } for (i = 0, l = items.length; i < l; i++) { item = items[i]; span = item.span; // Place the item in the smallest column h = -1; for (s = 0; s < this.colCount; s++) { if (h === -1 || y[s] < h) { h = y[s]; c = s; } } // If the item extends too far out, move it to the next column // Or if the last column has been reached if ((c >= this.colCount) || ((span + c) > this.colCount)) { c = 0; } // Item spans a column or multiple columns if (span) { top = 0; // If the item spans multiple columns // Get the largest height from the previous row for (s = 0; s < span; s++) { if (y[c + s] > top) { top = y[c + s]; } } // Position the item pos.top = top; pos[dir] = (this.colWidth + gutter) * c; pos.width = ((this.colWidth + gutter) * span) - gutter; item.item.css(pos).reveal(); // Loop again to add the value to each columns Y top value // This must be done after positioning so we can calculate a new size for (s = 0; s < span; s++) { y[c + s] = item.item.outerHeight() + gutter + top; } } this.colHeights[c] = y[c]; c++; } // Set height of wrapper this.element.css('height', Math.max.apply(Math, y)); }
[ "function", "(", ")", "{", "var", "gutter", "=", "this", ".", "options", ".", "gutter", ",", "items", "=", "this", ".", "matrix", ",", "item", ",", "span", ",", "dir", "=", "this", ".", "options", ".", "rtl", "?", "'right'", ":", "'left'", ",", "y", "=", "[", "]", ",", "// The top position values indexed by column", "c", "=", "0", ",", "// Current column in the loop", "h", "=", "0", ",", "// Smallest height column", "i", ",", "// Items loop counter", "l", ",", "// Items length", "s", ",", "// Current span column in the loop", "top", ",", "pos", "=", "{", "margin", ":", "0", ",", "position", ":", "'absolute'", "}", ";", "for", "(", "i", "=", "0", ";", "i", "<", "this", ".", "colCount", ";", "i", "++", ")", "{", "y", ".", "push", "(", "0", ")", ";", "}", "for", "(", "i", "=", "0", ",", "l", "=", "items", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "item", "=", "items", "[", "i", "]", ";", "span", "=", "item", ".", "span", ";", "// Place the item in the smallest column", "h", "=", "-", "1", ";", "for", "(", "s", "=", "0", ";", "s", "<", "this", ".", "colCount", ";", "s", "++", ")", "{", "if", "(", "h", "===", "-", "1", "||", "y", "[", "s", "]", "<", "h", ")", "{", "h", "=", "y", "[", "s", "]", ";", "c", "=", "s", ";", "}", "}", "// If the item extends too far out, move it to the next column", "// Or if the last column has been reached", "if", "(", "(", "c", ">=", "this", ".", "colCount", ")", "||", "(", "(", "span", "+", "c", ")", ">", "this", ".", "colCount", ")", ")", "{", "c", "=", "0", ";", "}", "// Item spans a column or multiple columns", "if", "(", "span", ")", "{", "top", "=", "0", ";", "// If the item spans multiple columns", "// Get the largest height from the previous row", "for", "(", "s", "=", "0", ";", "s", "<", "span", ";", "s", "++", ")", "{", "if", "(", "y", "[", "c", "+", "s", "]", ">", "top", ")", "{", "top", "=", "y", "[", "c", "+", "s", "]", ";", "}", "}", "// Position the item", "pos", ".", "top", "=", "top", ";", "pos", "[", "dir", "]", "=", "(", "this", ".", "colWidth", "+", "gutter", ")", "*", "c", ";", "pos", ".", "width", "=", "(", "(", "this", ".", "colWidth", "+", "gutter", ")", "*", "span", ")", "-", "gutter", ";", "item", ".", "item", ".", "css", "(", "pos", ")", ".", "reveal", "(", ")", ";", "// Loop again to add the value to each columns Y top value", "// This must be done after positioning so we can calculate a new size", "for", "(", "s", "=", "0", ";", "s", "<", "span", ";", "s", "++", ")", "{", "y", "[", "c", "+", "s", "]", "=", "item", ".", "item", ".", "outerHeight", "(", ")", "+", "gutter", "+", "top", ";", "}", "}", "this", ".", "colHeights", "[", "c", "]", "=", "y", "[", "c", "]", ";", "c", "++", ";", "}", "// Set height of wrapper", "this", ".", "element", ".", "css", "(", "'height'", ",", "Math", ".", "max", ".", "apply", "(", "Math", ",", "y", ")", ")", ";", "}" ]
Loop through the items in each column and position them absolutely. @private
[ "Loop", "through", "the", "items", "in", "each", "column", "and", "position", "them", "absolutely", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/matrix.js#L272-L344
21,663
titon/toolkit
js/components/carousel.js
function(element, options) { var items, self = this; element = this.setElement(element); options = this.setOptions(options, element); // Set animation and ARIA element .aria('live', options.autoCycle ? 'assertive' : 'off') .addClass(options.animation); // Find the item container and disable transitions for initial load this.container = element.find(this.ns('items')) .addClass('no-transition'); // Find all the items and set ARIA attributes this.items = items = this.container.find('> li').each(function(index) { $(this) .attr({ role: 'tabpanel', id: self.id('item', index) }) .data('carousel-index', index) .aria('hidden', (index > 0)); }); // Find all tabs and set ARIA attributes this.tabs = element.find(this.ns('tabs')) .attr('role', 'tablist') .find('a').each(function(index) { $(this) .data('carousel-index', index) .attr({ role: 'tab', id: self.id('tab', index) }) .aria({ controls: self.id('item', index), selected: false, expanded: false }); }); // Set events this.addEvents([ ['resize', 'window', $.throttle(this.calculate.bind(this), 50)], ['keydown', 'window', 'onKeydown'], ['click', 'element', 'onJump', this.ns('tabs') + ' a'], ['click', 'element', 'next', this.ns('next')], ['click', 'element', 'prev', this.ns('prev')], ['click', 'element', 'start', this.ns('start')], ['click', 'element', 'stop', this.ns('stop')] ]); if (options.swipe) { this.addEvents([ ['swipeleft', 'element', 'next'], ['swipeup', 'element', 'next'], ['swiperight', 'element', 'prev'], ['swipedown', 'element', 'prev'] ]); } if (options.stopOnHover) { this.addEvents([ ['mouseenter', 'element', 'stop'], ['mouseleave', 'element', 'start'] ]); } // Initialize this.initialize(); // Prepare the carousel this._setupState(); this._buildClones(); // Start the carousel this.calculate(); this.start(); this.jump(options.defaultIndex); }
javascript
function(element, options) { var items, self = this; element = this.setElement(element); options = this.setOptions(options, element); // Set animation and ARIA element .aria('live', options.autoCycle ? 'assertive' : 'off') .addClass(options.animation); // Find the item container and disable transitions for initial load this.container = element.find(this.ns('items')) .addClass('no-transition'); // Find all the items and set ARIA attributes this.items = items = this.container.find('> li').each(function(index) { $(this) .attr({ role: 'tabpanel', id: self.id('item', index) }) .data('carousel-index', index) .aria('hidden', (index > 0)); }); // Find all tabs and set ARIA attributes this.tabs = element.find(this.ns('tabs')) .attr('role', 'tablist') .find('a').each(function(index) { $(this) .data('carousel-index', index) .attr({ role: 'tab', id: self.id('tab', index) }) .aria({ controls: self.id('item', index), selected: false, expanded: false }); }); // Set events this.addEvents([ ['resize', 'window', $.throttle(this.calculate.bind(this), 50)], ['keydown', 'window', 'onKeydown'], ['click', 'element', 'onJump', this.ns('tabs') + ' a'], ['click', 'element', 'next', this.ns('next')], ['click', 'element', 'prev', this.ns('prev')], ['click', 'element', 'start', this.ns('start')], ['click', 'element', 'stop', this.ns('stop')] ]); if (options.swipe) { this.addEvents([ ['swipeleft', 'element', 'next'], ['swipeup', 'element', 'next'], ['swiperight', 'element', 'prev'], ['swipedown', 'element', 'prev'] ]); } if (options.stopOnHover) { this.addEvents([ ['mouseenter', 'element', 'stop'], ['mouseleave', 'element', 'start'] ]); } // Initialize this.initialize(); // Prepare the carousel this._setupState(); this._buildClones(); // Start the carousel this.calculate(); this.start(); this.jump(options.defaultIndex); }
[ "function", "(", "element", ",", "options", ")", "{", "var", "items", ",", "self", "=", "this", ";", "element", "=", "this", ".", "setElement", "(", "element", ")", ";", "options", "=", "this", ".", "setOptions", "(", "options", ",", "element", ")", ";", "// Set animation and ARIA", "element", ".", "aria", "(", "'live'", ",", "options", ".", "autoCycle", "?", "'assertive'", ":", "'off'", ")", ".", "addClass", "(", "options", ".", "animation", ")", ";", "// Find the item container and disable transitions for initial load", "this", ".", "container", "=", "element", ".", "find", "(", "this", ".", "ns", "(", "'items'", ")", ")", ".", "addClass", "(", "'no-transition'", ")", ";", "// Find all the items and set ARIA attributes", "this", ".", "items", "=", "items", "=", "this", ".", "container", ".", "find", "(", "'> li'", ")", ".", "each", "(", "function", "(", "index", ")", "{", "$", "(", "this", ")", ".", "attr", "(", "{", "role", ":", "'tabpanel'", ",", "id", ":", "self", ".", "id", "(", "'item'", ",", "index", ")", "}", ")", ".", "data", "(", "'carousel-index'", ",", "index", ")", ".", "aria", "(", "'hidden'", ",", "(", "index", ">", "0", ")", ")", ";", "}", ")", ";", "// Find all tabs and set ARIA attributes", "this", ".", "tabs", "=", "element", ".", "find", "(", "this", ".", "ns", "(", "'tabs'", ")", ")", ".", "attr", "(", "'role'", ",", "'tablist'", ")", ".", "find", "(", "'a'", ")", ".", "each", "(", "function", "(", "index", ")", "{", "$", "(", "this", ")", ".", "data", "(", "'carousel-index'", ",", "index", ")", ".", "attr", "(", "{", "role", ":", "'tab'", ",", "id", ":", "self", ".", "id", "(", "'tab'", ",", "index", ")", "}", ")", ".", "aria", "(", "{", "controls", ":", "self", ".", "id", "(", "'item'", ",", "index", ")", ",", "selected", ":", "false", ",", "expanded", ":", "false", "}", ")", ";", "}", ")", ";", "// Set events", "this", ".", "addEvents", "(", "[", "[", "'resize'", ",", "'window'", ",", "$", ".", "throttle", "(", "this", ".", "calculate", ".", "bind", "(", "this", ")", ",", "50", ")", "]", ",", "[", "'keydown'", ",", "'window'", ",", "'onKeydown'", "]", ",", "[", "'click'", ",", "'element'", ",", "'onJump'", ",", "this", ".", "ns", "(", "'tabs'", ")", "+", "' a'", "]", ",", "[", "'click'", ",", "'element'", ",", "'next'", ",", "this", ".", "ns", "(", "'next'", ")", "]", ",", "[", "'click'", ",", "'element'", ",", "'prev'", ",", "this", ".", "ns", "(", "'prev'", ")", "]", ",", "[", "'click'", ",", "'element'", ",", "'start'", ",", "this", ".", "ns", "(", "'start'", ")", "]", ",", "[", "'click'", ",", "'element'", ",", "'stop'", ",", "this", ".", "ns", "(", "'stop'", ")", "]", "]", ")", ";", "if", "(", "options", ".", "swipe", ")", "{", "this", ".", "addEvents", "(", "[", "[", "'swipeleft'", ",", "'element'", ",", "'next'", "]", ",", "[", "'swipeup'", ",", "'element'", ",", "'next'", "]", ",", "[", "'swiperight'", ",", "'element'", ",", "'prev'", "]", ",", "[", "'swipedown'", ",", "'element'", ",", "'prev'", "]", "]", ")", ";", "}", "if", "(", "options", ".", "stopOnHover", ")", "{", "this", ".", "addEvents", "(", "[", "[", "'mouseenter'", ",", "'element'", ",", "'stop'", "]", ",", "[", "'mouseleave'", ",", "'element'", ",", "'start'", "]", "]", ")", ";", "}", "// Initialize", "this", ".", "initialize", "(", ")", ";", "// Prepare the carousel", "this", ".", "_setupState", "(", ")", ";", "this", ".", "_buildClones", "(", ")", ";", "// Start the carousel", "this", ".", "calculate", "(", ")", ";", "this", ".", "start", "(", ")", ";", "this", ".", "jump", "(", "options", ".", "defaultIndex", ")", ";", "}" ]
Initialize the carousel. @param {jQuery} element @param {Object} [options]
[ "Initialize", "the", "carousel", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/carousel.js#L59-L140
21,664
titon/toolkit
js/components/carousel.js
function() { this.stop(); // Go to first item this.jump(0); // Remove clones var dir = this._position || 'left'; this.container.transitionend(function() { $(this) .addClass('no-transition') .css(dir, 0) .find('li.is-cloned') .remove(); }); }
javascript
function() { this.stop(); // Go to first item this.jump(0); // Remove clones var dir = this._position || 'left'; this.container.transitionend(function() { $(this) .addClass('no-transition') .css(dir, 0) .find('li.is-cloned') .remove(); }); }
[ "function", "(", ")", "{", "this", ".", "stop", "(", ")", ";", "// Go to first item", "this", ".", "jump", "(", "0", ")", ";", "// Remove clones", "var", "dir", "=", "this", ".", "_position", "||", "'left'", ";", "this", ".", "container", ".", "transitionend", "(", "function", "(", ")", "{", "$", "(", "this", ")", ".", "addClass", "(", "'no-transition'", ")", ".", "css", "(", "dir", ",", "0", ")", ".", "find", "(", "'li.is-cloned'", ")", ".", "remove", "(", ")", ";", "}", ")", ";", "}" ]
Stop the carousel before destroying.
[ "Stop", "the", "carousel", "before", "destroying", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/carousel.js#L145-L161
21,665
titon/toolkit
js/components/carousel.js
function() { if (this.options.animation === 'fade') { return; } var dimension = this._dimension, // height or width containerSize = 0, sizes = []; this.container.removeAttr('style'); this.items.each(function() { var item = $(this).removeAttr('style'), size = item[dimension](), marginStart = parseInt(item.css('margin-' + (dimension === 'width' ? 'left' : 'top')), 10), marginEnd = parseInt(item.css('margin-' + (dimension === 'width' ? 'right' : 'bottom')), 10), totalSize = size + marginStart + marginEnd; containerSize += totalSize; sizes.push({ size: size, totalSize: totalSize, marginStart: marginStart, marginEnd: marginEnd, clone: item.hasClass('is-cloned') }); // Set the size of the item explicitly item.css(dimension, size); }); // Store the sizes this._sizes = sizes; // Set the container width/height this.container.css(dimension, containerSize); }
javascript
function() { if (this.options.animation === 'fade') { return; } var dimension = this._dimension, // height or width containerSize = 0, sizes = []; this.container.removeAttr('style'); this.items.each(function() { var item = $(this).removeAttr('style'), size = item[dimension](), marginStart = parseInt(item.css('margin-' + (dimension === 'width' ? 'left' : 'top')), 10), marginEnd = parseInt(item.css('margin-' + (dimension === 'width' ? 'right' : 'bottom')), 10), totalSize = size + marginStart + marginEnd; containerSize += totalSize; sizes.push({ size: size, totalSize: totalSize, marginStart: marginStart, marginEnd: marginEnd, clone: item.hasClass('is-cloned') }); // Set the size of the item explicitly item.css(dimension, size); }); // Store the sizes this._sizes = sizes; // Set the container width/height this.container.css(dimension, containerSize); }
[ "function", "(", ")", "{", "if", "(", "this", ".", "options", ".", "animation", "===", "'fade'", ")", "{", "return", ";", "}", "var", "dimension", "=", "this", ".", "_dimension", ",", "// height or width", "containerSize", "=", "0", ",", "sizes", "=", "[", "]", ";", "this", ".", "container", ".", "removeAttr", "(", "'style'", ")", ";", "this", ".", "items", ".", "each", "(", "function", "(", ")", "{", "var", "item", "=", "$", "(", "this", ")", ".", "removeAttr", "(", "'style'", ")", ",", "size", "=", "item", "[", "dimension", "]", "(", ")", ",", "marginStart", "=", "parseInt", "(", "item", ".", "css", "(", "'margin-'", "+", "(", "dimension", "===", "'width'", "?", "'left'", ":", "'top'", ")", ")", ",", "10", ")", ",", "marginEnd", "=", "parseInt", "(", "item", ".", "css", "(", "'margin-'", "+", "(", "dimension", "===", "'width'", "?", "'right'", ":", "'bottom'", ")", ")", ",", "10", ")", ",", "totalSize", "=", "size", "+", "marginStart", "+", "marginEnd", ";", "containerSize", "+=", "totalSize", ";", "sizes", ".", "push", "(", "{", "size", ":", "size", ",", "totalSize", ":", "totalSize", ",", "marginStart", ":", "marginStart", ",", "marginEnd", ":", "marginEnd", ",", "clone", ":", "item", ".", "hasClass", "(", "'is-cloned'", ")", "}", ")", ";", "// Set the size of the item explicitly", "item", ".", "css", "(", "dimension", ",", "size", ")", ";", "}", ")", ";", "// Store the sizes", "this", ".", "_sizes", "=", "sizes", ";", "// Set the container width/height", "this", ".", "container", ".", "css", "(", "dimension", ",", "containerSize", ")", ";", "}" ]
Calculate the widths or heights for the items, the wrapper, and the cycle.
[ "Calculate", "the", "widths", "or", "heights", "for", "the", "items", "the", "wrapper", "and", "the", "cycle", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/carousel.js#L166-L203
21,666
titon/toolkit
js/components/carousel.js
function(index) { if (this.animating) { return; } var indexes = this._getIndex(index), cloneIndex = indexes[0], // The index including clones visualIndex = indexes[1]; // The index excluding clones // Exit early if jumping to same index if (visualIndex === this.index) { return; } this.fireEvent('jumping', [this.index]); // Update tabs and items state this._updateTabs(visualIndex); this._updateItems(cloneIndex); // Animate and move the items this._beforeCycle(); if (this.options.animation === 'fade') { this.items .conceal(true) .eq(visualIndex) .transitionend(this._afterCycle.bind(this)) .reveal(true); } else { this.container .transitionend(this._afterCycle.bind(this)) .css(this._position, -this._getSizeSum(cloneIndex)); } // Store the index this.index = visualIndex; this.reset(); this.fireEvent('jumped', [visualIndex]); }
javascript
function(index) { if (this.animating) { return; } var indexes = this._getIndex(index), cloneIndex = indexes[0], // The index including clones visualIndex = indexes[1]; // The index excluding clones // Exit early if jumping to same index if (visualIndex === this.index) { return; } this.fireEvent('jumping', [this.index]); // Update tabs and items state this._updateTabs(visualIndex); this._updateItems(cloneIndex); // Animate and move the items this._beforeCycle(); if (this.options.animation === 'fade') { this.items .conceal(true) .eq(visualIndex) .transitionend(this._afterCycle.bind(this)) .reveal(true); } else { this.container .transitionend(this._afterCycle.bind(this)) .css(this._position, -this._getSizeSum(cloneIndex)); } // Store the index this.index = visualIndex; this.reset(); this.fireEvent('jumped', [visualIndex]); }
[ "function", "(", "index", ")", "{", "if", "(", "this", ".", "animating", ")", "{", "return", ";", "}", "var", "indexes", "=", "this", ".", "_getIndex", "(", "index", ")", ",", "cloneIndex", "=", "indexes", "[", "0", "]", ",", "// The index including clones", "visualIndex", "=", "indexes", "[", "1", "]", ";", "// The index excluding clones", "// Exit early if jumping to same index", "if", "(", "visualIndex", "===", "this", ".", "index", ")", "{", "return", ";", "}", "this", ".", "fireEvent", "(", "'jumping'", ",", "[", "this", ".", "index", "]", ")", ";", "// Update tabs and items state", "this", ".", "_updateTabs", "(", "visualIndex", ")", ";", "this", ".", "_updateItems", "(", "cloneIndex", ")", ";", "// Animate and move the items", "this", ".", "_beforeCycle", "(", ")", ";", "if", "(", "this", ".", "options", ".", "animation", "===", "'fade'", ")", "{", "this", ".", "items", ".", "conceal", "(", "true", ")", ".", "eq", "(", "visualIndex", ")", ".", "transitionend", "(", "this", ".", "_afterCycle", ".", "bind", "(", "this", ")", ")", ".", "reveal", "(", "true", ")", ";", "}", "else", "{", "this", ".", "container", ".", "transitionend", "(", "this", ".", "_afterCycle", ".", "bind", "(", "this", ")", ")", ".", "css", "(", "this", ".", "_position", ",", "-", "this", ".", "_getSizeSum", "(", "cloneIndex", ")", ")", ";", "}", "// Store the index", "this", ".", "index", "=", "visualIndex", ";", "this", ".", "reset", "(", ")", ";", "this", ".", "fireEvent", "(", "'jumped'", ",", "[", "visualIndex", "]", ")", ";", "}" ]
Go to the item indicated by the index number. @param {Number} index
[ "Go", "to", "the", "item", "indicated", "by", "the", "index", "number", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/carousel.js#L210-L251
21,667
titon/toolkit
js/components/carousel.js
function() { if (this.options.autoCycle) { clearInterval(this.timer); this.timer = setInterval(this.onCycle.bind(this), this.options.duration); } }
javascript
function() { if (this.options.autoCycle) { clearInterval(this.timer); this.timer = setInterval(this.onCycle.bind(this), this.options.duration); } }
[ "function", "(", ")", "{", "if", "(", "this", ".", "options", ".", "autoCycle", ")", "{", "clearInterval", "(", "this", ".", "timer", ")", ";", "this", ".", "timer", "=", "setInterval", "(", "this", ".", "onCycle", ".", "bind", "(", "this", ")", ",", "this", ".", "options", ".", "duration", ")", ";", "}", "}" ]
Reset the timer.
[ "Reset", "the", "timer", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/carousel.js#L270-L275
21,668
titon/toolkit
js/components/carousel.js
function() { this.animating = false; var container = this.container, resetTo = this._resetTo; // Reset the currently shown item to a specific index // This achieves the circular infinite scrolling effect if (resetTo !== null) { container .addClass('no-transition') .css(this._position, -this._getSizeSum(resetTo)); this._updateItems(resetTo); this._resetTo = null; } // Set in a timeout or transition will still occur setTimeout(function() { container.removeClass('no-transition'); this.fireEvent('cycled'); }.bind(this), 15); // IE needs a minimum of 15 }
javascript
function() { this.animating = false; var container = this.container, resetTo = this._resetTo; // Reset the currently shown item to a specific index // This achieves the circular infinite scrolling effect if (resetTo !== null) { container .addClass('no-transition') .css(this._position, -this._getSizeSum(resetTo)); this._updateItems(resetTo); this._resetTo = null; } // Set in a timeout or transition will still occur setTimeout(function() { container.removeClass('no-transition'); this.fireEvent('cycled'); }.bind(this), 15); // IE needs a minimum of 15 }
[ "function", "(", ")", "{", "this", ".", "animating", "=", "false", ";", "var", "container", "=", "this", ".", "container", ",", "resetTo", "=", "this", ".", "_resetTo", ";", "// Reset the currently shown item to a specific index", "// This achieves the circular infinite scrolling effect", "if", "(", "resetTo", "!==", "null", ")", "{", "container", ".", "addClass", "(", "'no-transition'", ")", ".", "css", "(", "this", ".", "_position", ",", "-", "this", ".", "_getSizeSum", "(", "resetTo", ")", ")", ";", "this", ".", "_updateItems", "(", "resetTo", ")", ";", "this", ".", "_resetTo", "=", "null", ";", "}", "// Set in a timeout or transition will still occur", "setTimeout", "(", "function", "(", ")", "{", "container", ".", "removeClass", "(", "'no-transition'", ")", ";", "this", ".", "fireEvent", "(", "'cycled'", ")", ";", "}", ".", "bind", "(", "this", ")", ",", "15", ")", ";", "// IE needs a minimum of 15", "}" ]
Functionality to trigger after a cycle transition has ended. Will set animating to false and re-enable jumping. If `resetTo` is set, then reset the internal DOM index for infinite scrolling. Also clean-up the `no-transition` class from the container. @private
[ "Functionality", "to", "trigger", "after", "a", "cycle", "transition", "has", "ended", ".", "Will", "set", "animating", "to", "false", "and", "re", "-", "enable", "jumping", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/carousel.js#L308-L330
21,669
titon/toolkit
js/components/carousel.js
function() { var options = this.options, items = this.items, container = this.container, itemsToShow = options.itemsToShow; if (!options.infinite) { return; } // Append the first items items.slice(0, itemsToShow) .clone() .addClass('is-cloned') .removeAttr('id') .removeAttr('role') .appendTo(container); // Prepend the last items items.slice(-itemsToShow) .clone() .addClass('is-cloned') .removeAttr('id') .removeAttr('role') .prependTo(container); // Refresh items list this.items = container.find('> li'); }
javascript
function() { var options = this.options, items = this.items, container = this.container, itemsToShow = options.itemsToShow; if (!options.infinite) { return; } // Append the first items items.slice(0, itemsToShow) .clone() .addClass('is-cloned') .removeAttr('id') .removeAttr('role') .appendTo(container); // Prepend the last items items.slice(-itemsToShow) .clone() .addClass('is-cloned') .removeAttr('id') .removeAttr('role') .prependTo(container); // Refresh items list this.items = container.find('> li'); }
[ "function", "(", ")", "{", "var", "options", "=", "this", ".", "options", ",", "items", "=", "this", ".", "items", ",", "container", "=", "this", ".", "container", ",", "itemsToShow", "=", "options", ".", "itemsToShow", ";", "if", "(", "!", "options", ".", "infinite", ")", "{", "return", ";", "}", "// Append the first items", "items", ".", "slice", "(", "0", ",", "itemsToShow", ")", ".", "clone", "(", ")", ".", "addClass", "(", "'is-cloned'", ")", ".", "removeAttr", "(", "'id'", ")", ".", "removeAttr", "(", "'role'", ")", ".", "appendTo", "(", "container", ")", ";", "// Prepend the last items", "items", ".", "slice", "(", "-", "itemsToShow", ")", ".", "clone", "(", ")", ".", "addClass", "(", "'is-cloned'", ")", ".", "removeAttr", "(", "'id'", ")", ".", "removeAttr", "(", "'role'", ")", ".", "prependTo", "(", "container", ")", ";", "// Refresh items list", "this", ".", "items", "=", "container", ".", "find", "(", "'> li'", ")", ";", "}" ]
Create clones to support infinite scrolling. The beginning set of cloned items should be appended to the end, while the end set of cloned items should be prepended to the beginning. @private
[ "Create", "clones", "to", "support", "infinite", "scrolling", ".", "The", "beginning", "set", "of", "cloned", "items", "should", "be", "appended", "to", "the", "end", "while", "the", "end", "set", "of", "cloned", "items", "should", "be", "prepended", "to", "the", "beginning", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/carousel.js#L350-L378
21,670
titon/toolkit
js/components/carousel.js
function(index) { var sum = 0; $.each(this._sizes, function(i, value) { if (i < index) { sum += value.totalSize; } }); return sum; }
javascript
function(index) { var sum = 0; $.each(this._sizes, function(i, value) { if (i < index) { sum += value.totalSize; } }); return sum; }
[ "function", "(", "index", ")", "{", "var", "sum", "=", "0", ";", "$", ".", "each", "(", "this", ".", "_sizes", ",", "function", "(", "i", ",", "value", ")", "{", "if", "(", "i", "<", "index", ")", "{", "sum", "+=", "value", ".", "totalSize", ";", "}", "}", ")", ";", "return", "sum", ";", "}" ]
Calculate the size to cycle width based on the sum of all items up to but not including the defined index. @param {Number} index - Includes the clone index @returns {Number} @private
[ "Calculate", "the", "size", "to", "cycle", "width", "based", "on", "the", "sum", "of", "all", "items", "up", "to", "but", "not", "including", "the", "defined", "index", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/carousel.js#L472-L482
21,671
titon/toolkit
js/components/carousel.js
function() { var options = this.options, animation = options.animation; // Cycling more than the show amount causes unexpected issues if (options.itemsToCycle > options.itemsToShow) { options.itemsToCycle = options.itemsToShow; } // Fade animations can only display 1 at a time if (animation === 'fade') { options.itemsToShow = options.itemsToCycle = 1; options.infinite = false; // Determine the dimension and position based on animation } else if (animation === 'slide-up') { this._dimension = 'height'; this._position = 'top'; } else if (animation === 'slide') { this._dimension = 'width'; this._position = options.rtl ? 'right' : 'left'; } }
javascript
function() { var options = this.options, animation = options.animation; // Cycling more than the show amount causes unexpected issues if (options.itemsToCycle > options.itemsToShow) { options.itemsToCycle = options.itemsToShow; } // Fade animations can only display 1 at a time if (animation === 'fade') { options.itemsToShow = options.itemsToCycle = 1; options.infinite = false; // Determine the dimension and position based on animation } else if (animation === 'slide-up') { this._dimension = 'height'; this._position = 'top'; } else if (animation === 'slide') { this._dimension = 'width'; this._position = options.rtl ? 'right' : 'left'; } }
[ "function", "(", ")", "{", "var", "options", "=", "this", ".", "options", ",", "animation", "=", "options", ".", "animation", ";", "// Cycling more than the show amount causes unexpected issues", "if", "(", "options", ".", "itemsToCycle", ">", "options", ".", "itemsToShow", ")", "{", "options", ".", "itemsToCycle", "=", "options", ".", "itemsToShow", ";", "}", "// Fade animations can only display 1 at a time", "if", "(", "animation", "===", "'fade'", ")", "{", "options", ".", "itemsToShow", "=", "options", ".", "itemsToCycle", "=", "1", ";", "options", ".", "infinite", "=", "false", ";", "// Determine the dimension and position based on animation", "}", "else", "if", "(", "animation", "===", "'slide-up'", ")", "{", "this", ".", "_dimension", "=", "'height'", ";", "this", ".", "_position", "=", "'top'", ";", "}", "else", "if", "(", "animation", "===", "'slide'", ")", "{", "this", ".", "_dimension", "=", "'width'", ";", "this", ".", "_position", "=", "options", ".", "rtl", "?", "'right'", ":", "'left'", ";", "}", "}" ]
Setup the carousel state to introspecting property values and resetting options. @private
[ "Setup", "the", "carousel", "state", "to", "introspecting", "property", "values", "and", "resetting", "options", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/carousel.js#L489-L512
21,672
titon/toolkit
js/components/carousel.js
function(index) { this.items .removeClass('is-active') .aria('hidden', true) .slice(index, index + this.options.itemsToShow) .addClass('is-active') .aria('hidden', false); }
javascript
function(index) { this.items .removeClass('is-active') .aria('hidden', true) .slice(index, index + this.options.itemsToShow) .addClass('is-active') .aria('hidden', false); }
[ "function", "(", "index", ")", "{", "this", ".", "items", ".", "removeClass", "(", "'is-active'", ")", ".", "aria", "(", "'hidden'", ",", "true", ")", ".", "slice", "(", "index", ",", "index", "+", "this", ".", "options", ".", "itemsToShow", ")", ".", "addClass", "(", "'is-active'", ")", ".", "aria", "(", "'hidden'", ",", "false", ")", ";", "}" ]
Update the active state for the items while taking into account cloned elements. @param {Number} index @private
[ "Update", "the", "active", "state", "for", "the", "items", "while", "taking", "into", "account", "cloned", "elements", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/carousel.js#L520-L527
21,673
titon/toolkit
js/components/carousel.js
function(start) { var itemsToShow = this.options.itemsToShow, length = this.items.length, stop = start + itemsToShow, set = $([]), tabs = this.tabs .removeClass('is-active') .aria('toggled', false); if (!tabs.length) { return; } if (this.options.infinite) { length = length - (itemsToShow * 2); } if (start >= 0) { set = set.add(tabs.slice(start, stop)); } else { set = set.add(tabs.slice(0, stop)); set = set.add(tabs.slice(start)); } if (stop > length) { set = set.add(tabs.slice(0, stop - length)); } set .addClass('is-active') .aria('toggled', true); }
javascript
function(start) { var itemsToShow = this.options.itemsToShow, length = this.items.length, stop = start + itemsToShow, set = $([]), tabs = this.tabs .removeClass('is-active') .aria('toggled', false); if (!tabs.length) { return; } if (this.options.infinite) { length = length - (itemsToShow * 2); } if (start >= 0) { set = set.add(tabs.slice(start, stop)); } else { set = set.add(tabs.slice(0, stop)); set = set.add(tabs.slice(start)); } if (stop > length) { set = set.add(tabs.slice(0, stop - length)); } set .addClass('is-active') .aria('toggled', true); }
[ "function", "(", "start", ")", "{", "var", "itemsToShow", "=", "this", ".", "options", ".", "itemsToShow", ",", "length", "=", "this", ".", "items", ".", "length", ",", "stop", "=", "start", "+", "itemsToShow", ",", "set", "=", "$", "(", "[", "]", ")", ",", "tabs", "=", "this", ".", "tabs", ".", "removeClass", "(", "'is-active'", ")", ".", "aria", "(", "'toggled'", ",", "false", ")", ";", "if", "(", "!", "tabs", ".", "length", ")", "{", "return", ";", "}", "if", "(", "this", ".", "options", ".", "infinite", ")", "{", "length", "=", "length", "-", "(", "itemsToShow", "*", "2", ")", ";", "}", "if", "(", "start", ">=", "0", ")", "{", "set", "=", "set", ".", "add", "(", "tabs", ".", "slice", "(", "start", ",", "stop", ")", ")", ";", "}", "else", "{", "set", "=", "set", ".", "add", "(", "tabs", ".", "slice", "(", "0", ",", "stop", ")", ")", ";", "set", "=", "set", ".", "add", "(", "tabs", ".", "slice", "(", "start", ")", ")", ";", "}", "if", "(", "stop", ">", "length", ")", "{", "set", "=", "set", ".", "add", "(", "tabs", ".", "slice", "(", "0", ",", "stop", "-", "length", ")", ")", ";", "}", "set", ".", "addClass", "(", "'is-active'", ")", ".", "aria", "(", "'toggled'", ",", "true", ")", ";", "}" ]
Update the active state for the tab indicators. @param {Number} start @private
[ "Update", "the", "active", "state", "for", "the", "tab", "indicators", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/carousel.js#L535-L566
21,674
titon/toolkit
js/components/showcase.js
function(nodes, options) { var element; options = this.setOptions(options); this.element = element = this.createElement(); // Nodes found in the page on initialization this.nodes = $(nodes); // The wrapping items element this.items = element.find(this.ns('items')); // The wrapping tabs element this.tabs = element.find(this.ns('tabs')); // The caption element this.caption = element.find(this.ns('caption')); // Blackout element if enabled if (options.blackout) { this.blackout = Blackout.instance(); } // Initialize events this.addEvents([ ['keydown', 'window', 'onKeydown'], ['click', 'document', 'onShow', '{selector}'], ['click', 'element', 'hide', this.ns('close')], ['click', 'element', 'next', this.ns('next')], ['click', 'element', 'prev', this.ns('prev')], ['click', 'element', 'onJump', this.ns('tabs') + ' a'] ]); if (options.clickout) { this.addEvents([ ['clickout', 'document', 'onHide', '{selector}'], ['clickout', 'element', 'onHide'] ]); } if (options.swipe) { this.addEvents([ ['swipeleft', 'element', 'next'], ['swiperight', 'element', 'prev'] ]); } // Stop `transitionend` events from bubbling up when the showcase is resized this.addEvent(Toolkit.transitionEnd, 'element', function(e) { e.stopPropagation(); }, this.ns('items')); this.initialize(); }
javascript
function(nodes, options) { var element; options = this.setOptions(options); this.element = element = this.createElement(); // Nodes found in the page on initialization this.nodes = $(nodes); // The wrapping items element this.items = element.find(this.ns('items')); // The wrapping tabs element this.tabs = element.find(this.ns('tabs')); // The caption element this.caption = element.find(this.ns('caption')); // Blackout element if enabled if (options.blackout) { this.blackout = Blackout.instance(); } // Initialize events this.addEvents([ ['keydown', 'window', 'onKeydown'], ['click', 'document', 'onShow', '{selector}'], ['click', 'element', 'hide', this.ns('close')], ['click', 'element', 'next', this.ns('next')], ['click', 'element', 'prev', this.ns('prev')], ['click', 'element', 'onJump', this.ns('tabs') + ' a'] ]); if (options.clickout) { this.addEvents([ ['clickout', 'document', 'onHide', '{selector}'], ['clickout', 'element', 'onHide'] ]); } if (options.swipe) { this.addEvents([ ['swipeleft', 'element', 'next'], ['swiperight', 'element', 'prev'] ]); } // Stop `transitionend` events from bubbling up when the showcase is resized this.addEvent(Toolkit.transitionEnd, 'element', function(e) { e.stopPropagation(); }, this.ns('items')); this.initialize(); }
[ "function", "(", "nodes", ",", "options", ")", "{", "var", "element", ";", "options", "=", "this", ".", "setOptions", "(", "options", ")", ";", "this", ".", "element", "=", "element", "=", "this", ".", "createElement", "(", ")", ";", "// Nodes found in the page on initialization", "this", ".", "nodes", "=", "$", "(", "nodes", ")", ";", "// The wrapping items element", "this", ".", "items", "=", "element", ".", "find", "(", "this", ".", "ns", "(", "'items'", ")", ")", ";", "// The wrapping tabs element", "this", ".", "tabs", "=", "element", ".", "find", "(", "this", ".", "ns", "(", "'tabs'", ")", ")", ";", "// The caption element", "this", ".", "caption", "=", "element", ".", "find", "(", "this", ".", "ns", "(", "'caption'", ")", ")", ";", "// Blackout element if enabled", "if", "(", "options", ".", "blackout", ")", "{", "this", ".", "blackout", "=", "Blackout", ".", "instance", "(", ")", ";", "}", "// Initialize events", "this", ".", "addEvents", "(", "[", "[", "'keydown'", ",", "'window'", ",", "'onKeydown'", "]", ",", "[", "'click'", ",", "'document'", ",", "'onShow'", ",", "'{selector}'", "]", ",", "[", "'click'", ",", "'element'", ",", "'hide'", ",", "this", ".", "ns", "(", "'close'", ")", "]", ",", "[", "'click'", ",", "'element'", ",", "'next'", ",", "this", ".", "ns", "(", "'next'", ")", "]", ",", "[", "'click'", ",", "'element'", ",", "'prev'", ",", "this", ".", "ns", "(", "'prev'", ")", "]", ",", "[", "'click'", ",", "'element'", ",", "'onJump'", ",", "this", ".", "ns", "(", "'tabs'", ")", "+", "' a'", "]", "]", ")", ";", "if", "(", "options", ".", "clickout", ")", "{", "this", ".", "addEvents", "(", "[", "[", "'clickout'", ",", "'document'", ",", "'onHide'", ",", "'{selector}'", "]", ",", "[", "'clickout'", ",", "'element'", ",", "'onHide'", "]", "]", ")", ";", "}", "if", "(", "options", ".", "swipe", ")", "{", "this", ".", "addEvents", "(", "[", "[", "'swipeleft'", ",", "'element'", ",", "'next'", "]", ",", "[", "'swiperight'", ",", "'element'", ",", "'prev'", "]", "]", ")", ";", "}", "// Stop `transitionend` events from bubbling up when the showcase is resized", "this", ".", "addEvent", "(", "Toolkit", ".", "transitionEnd", ",", "'element'", ",", "function", "(", "e", ")", "{", "e", ".", "stopPropagation", "(", ")", ";", "}", ",", "this", ".", "ns", "(", "'items'", ")", ")", ";", "this", ".", "initialize", "(", ")", ";", "}" ]
Initialize the showcase. @param {jQuery} nodes @param {Object} [options]
[ "Initialize", "the", "showcase", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/showcase.js#L50-L103
21,675
titon/toolkit
js/components/showcase.js
function(index) { if (this.animating) { return; } index = $.bound(index, this.data.length); // Exit since transitions don't occur if (index === this.index) { return; } var self = this, element = this.element, caption = this.caption, list = this.items, listItems = list.children('li'), listItem = listItems.eq(index), items = this.data, item = items[index], deferred = $.Deferred(); this.fireEvent('jumping', [this.index]); // Update tabs this.tabs.find('a') .removeClass('is-active') .eq(index) .addClass('is-active'); // Reset previous styles listItems.conceal(true); caption.conceal(true); element .addClass('is-loading') .aria('busy', true) .reveal(); // Setup deferred callbacks this.animating = true; deferred.always(function(width, height) { list.transitionend(function() { caption.html(item.title).reveal(true); listItem.reveal(true); self.position(); self.animating = false; }); self._resize(width, height); element .removeClass('is-loading') .aria('busy', false); listItem .data('width', width) .data('height', height); }); deferred.fail(function() { element.addClass('has-failed'); listItem.html(Toolkit.messages.error); }); // Image already exists if (listItem.data('width')) { deferred.resolve(listItem.data('width'), listItem.data('height')); // Create image and animate } else { var img = new Image(); img.src = item.image; img.onerror = function() { deferred.reject(150, 150); }; img.onload = function() { deferred.resolve(this.width, this.height); listItem.append(img); }; } // Hide loader if (this.blackout) { this.blackout.hideLoader(); } // Save state this.index = index; this.fireEvent('jumped', [index]); }
javascript
function(index) { if (this.animating) { return; } index = $.bound(index, this.data.length); // Exit since transitions don't occur if (index === this.index) { return; } var self = this, element = this.element, caption = this.caption, list = this.items, listItems = list.children('li'), listItem = listItems.eq(index), items = this.data, item = items[index], deferred = $.Deferred(); this.fireEvent('jumping', [this.index]); // Update tabs this.tabs.find('a') .removeClass('is-active') .eq(index) .addClass('is-active'); // Reset previous styles listItems.conceal(true); caption.conceal(true); element .addClass('is-loading') .aria('busy', true) .reveal(); // Setup deferred callbacks this.animating = true; deferred.always(function(width, height) { list.transitionend(function() { caption.html(item.title).reveal(true); listItem.reveal(true); self.position(); self.animating = false; }); self._resize(width, height); element .removeClass('is-loading') .aria('busy', false); listItem .data('width', width) .data('height', height); }); deferred.fail(function() { element.addClass('has-failed'); listItem.html(Toolkit.messages.error); }); // Image already exists if (listItem.data('width')) { deferred.resolve(listItem.data('width'), listItem.data('height')); // Create image and animate } else { var img = new Image(); img.src = item.image; img.onerror = function() { deferred.reject(150, 150); }; img.onload = function() { deferred.resolve(this.width, this.height); listItem.append(img); }; } // Hide loader if (this.blackout) { this.blackout.hideLoader(); } // Save state this.index = index; this.fireEvent('jumped', [index]); }
[ "function", "(", "index", ")", "{", "if", "(", "this", ".", "animating", ")", "{", "return", ";", "}", "index", "=", "$", ".", "bound", "(", "index", ",", "this", ".", "data", ".", "length", ")", ";", "// Exit since transitions don't occur", "if", "(", "index", "===", "this", ".", "index", ")", "{", "return", ";", "}", "var", "self", "=", "this", ",", "element", "=", "this", ".", "element", ",", "caption", "=", "this", ".", "caption", ",", "list", "=", "this", ".", "items", ",", "listItems", "=", "list", ".", "children", "(", "'li'", ")", ",", "listItem", "=", "listItems", ".", "eq", "(", "index", ")", ",", "items", "=", "this", ".", "data", ",", "item", "=", "items", "[", "index", "]", ",", "deferred", "=", "$", ".", "Deferred", "(", ")", ";", "this", ".", "fireEvent", "(", "'jumping'", ",", "[", "this", ".", "index", "]", ")", ";", "// Update tabs", "this", ".", "tabs", ".", "find", "(", "'a'", ")", ".", "removeClass", "(", "'is-active'", ")", ".", "eq", "(", "index", ")", ".", "addClass", "(", "'is-active'", ")", ";", "// Reset previous styles", "listItems", ".", "conceal", "(", "true", ")", ";", "caption", ".", "conceal", "(", "true", ")", ";", "element", ".", "addClass", "(", "'is-loading'", ")", ".", "aria", "(", "'busy'", ",", "true", ")", ".", "reveal", "(", ")", ";", "// Setup deferred callbacks", "this", ".", "animating", "=", "true", ";", "deferred", ".", "always", "(", "function", "(", "width", ",", "height", ")", "{", "list", ".", "transitionend", "(", "function", "(", ")", "{", "caption", ".", "html", "(", "item", ".", "title", ")", ".", "reveal", "(", "true", ")", ";", "listItem", ".", "reveal", "(", "true", ")", ";", "self", ".", "position", "(", ")", ";", "self", ".", "animating", "=", "false", ";", "}", ")", ";", "self", ".", "_resize", "(", "width", ",", "height", ")", ";", "element", ".", "removeClass", "(", "'is-loading'", ")", ".", "aria", "(", "'busy'", ",", "false", ")", ";", "listItem", ".", "data", "(", "'width'", ",", "width", ")", ".", "data", "(", "'height'", ",", "height", ")", ";", "}", ")", ";", "deferred", ".", "fail", "(", "function", "(", ")", "{", "element", ".", "addClass", "(", "'has-failed'", ")", ";", "listItem", ".", "html", "(", "Toolkit", ".", "messages", ".", "error", ")", ";", "}", ")", ";", "// Image already exists", "if", "(", "listItem", ".", "data", "(", "'width'", ")", ")", "{", "deferred", ".", "resolve", "(", "listItem", ".", "data", "(", "'width'", ")", ",", "listItem", ".", "data", "(", "'height'", ")", ")", ";", "// Create image and animate", "}", "else", "{", "var", "img", "=", "new", "Image", "(", ")", ";", "img", ".", "src", "=", "item", ".", "image", ";", "img", ".", "onerror", "=", "function", "(", ")", "{", "deferred", ".", "reject", "(", "150", ",", "150", ")", ";", "}", ";", "img", ".", "onload", "=", "function", "(", ")", "{", "deferred", ".", "resolve", "(", "this", ".", "width", ",", "this", ".", "height", ")", ";", "listItem", ".", "append", "(", "img", ")", ";", "}", ";", "}", "// Hide loader", "if", "(", "this", ".", "blackout", ")", "{", "this", ".", "blackout", ".", "hideLoader", "(", ")", ";", "}", "// Save state", "this", ".", "index", "=", "index", ";", "this", ".", "fireEvent", "(", "'jumped'", ",", "[", "index", "]", ")", ";", "}" ]
Jump to a specific item indicated by the index number. If the index is too large, jump to the beginning. If the index is too small, jump to the end. @param {Number} index
[ "Jump", "to", "a", "specific", "item", "indicated", "by", "the", "index", "number", ".", "If", "the", "index", "is", "too", "large", "jump", "to", "the", "beginning", ".", "If", "the", "index", "is", "too", "small", "jump", "to", "the", "end", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/showcase.js#L138-L229
21,676
titon/toolkit
js/components/showcase.js
function(node) { this.node = node = $(node); this.index = -1; var options = this.inheritOptions(this.options, node), read = this.readValue, category = read(node, options.getCategory), items = [], index = 0; // Multiple items based on category if (category) { for (var i = 0, x = 0, n; n = this.nodes[i]; i++) { if (read(n, options.getCategory) === category) { if (node.is(n)) { index = x; } items.push({ title: read(n, options.getTitle), category: category, image: read(n, options.getImage) }); x++; } } // Single item } else { items.push({ title: read(node, options.getTitle), category: category, image: read(node, options.getImage) }); } if (this.blackout) { this.blackout.show(); } if (options.stopScroll) { $('body').addClass('no-scroll'); } this._buildItems(items); this.jump(index); }
javascript
function(node) { this.node = node = $(node); this.index = -1; var options = this.inheritOptions(this.options, node), read = this.readValue, category = read(node, options.getCategory), items = [], index = 0; // Multiple items based on category if (category) { for (var i = 0, x = 0, n; n = this.nodes[i]; i++) { if (read(n, options.getCategory) === category) { if (node.is(n)) { index = x; } items.push({ title: read(n, options.getTitle), category: category, image: read(n, options.getImage) }); x++; } } // Single item } else { items.push({ title: read(node, options.getTitle), category: category, image: read(node, options.getImage) }); } if (this.blackout) { this.blackout.show(); } if (options.stopScroll) { $('body').addClass('no-scroll'); } this._buildItems(items); this.jump(index); }
[ "function", "(", "node", ")", "{", "this", ".", "node", "=", "node", "=", "$", "(", "node", ")", ";", "this", ".", "index", "=", "-", "1", ";", "var", "options", "=", "this", ".", "inheritOptions", "(", "this", ".", "options", ",", "node", ")", ",", "read", "=", "this", ".", "readValue", ",", "category", "=", "read", "(", "node", ",", "options", ".", "getCategory", ")", ",", "items", "=", "[", "]", ",", "index", "=", "0", ";", "// Multiple items based on category", "if", "(", "category", ")", "{", "for", "(", "var", "i", "=", "0", ",", "x", "=", "0", ",", "n", ";", "n", "=", "this", ".", "nodes", "[", "i", "]", ";", "i", "++", ")", "{", "if", "(", "read", "(", "n", ",", "options", ".", "getCategory", ")", "===", "category", ")", "{", "if", "(", "node", ".", "is", "(", "n", ")", ")", "{", "index", "=", "x", ";", "}", "items", ".", "push", "(", "{", "title", ":", "read", "(", "n", ",", "options", ".", "getTitle", ")", ",", "category", ":", "category", ",", "image", ":", "read", "(", "n", ",", "options", ".", "getImage", ")", "}", ")", ";", "x", "++", ";", "}", "}", "// Single item", "}", "else", "{", "items", ".", "push", "(", "{", "title", ":", "read", "(", "node", ",", "options", ".", "getTitle", ")", ",", "category", ":", "category", ",", "image", ":", "read", "(", "node", ",", "options", ".", "getImage", ")", "}", ")", ";", "}", "if", "(", "this", ".", "blackout", ")", "{", "this", ".", "blackout", ".", "show", "(", ")", ";", "}", "if", "(", "options", ".", "stopScroll", ")", "{", "$", "(", "'body'", ")", ".", "addClass", "(", "'no-scroll'", ")", ";", "}", "this", ".", "_buildItems", "(", "items", ")", ";", "this", ".", "jump", "(", "index", ")", ";", "}" ]
Reveal the showcase after scraping for items data. Will scrape data from the activating node. If a category exists, scrape data from multiple nodes. @param {Element} node
[ "Reveal", "the", "showcase", "after", "scraping", "for", "items", "data", ".", "Will", "scrape", "data", "from", "the", "activating", "node", ".", "If", "a", "category", "exists", "scrape", "data", "from", "multiple", "nodes", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/showcase.js#L267-L314
21,677
titon/toolkit
js/components/showcase.js
function(items) { this.data = items; this.items.empty(); this.tabs.empty(); for (var li, a, item, i = 0; item = items[i]; i++) { li = $('<li/>'); li.appendTo(this.items); a = $('<a/>') .attr('href', 'javascript:;') .data('showcase-index', i); li = $('<li/>'); li.appendTo(this.tabs).append(a); } if (items.length <= 1) { this.element.addClass('is-single'); } this.fireEvent('load', [items]); }
javascript
function(items) { this.data = items; this.items.empty(); this.tabs.empty(); for (var li, a, item, i = 0; item = items[i]; i++) { li = $('<li/>'); li.appendTo(this.items); a = $('<a/>') .attr('href', 'javascript:;') .data('showcase-index', i); li = $('<li/>'); li.appendTo(this.tabs).append(a); } if (items.length <= 1) { this.element.addClass('is-single'); } this.fireEvent('load', [items]); }
[ "function", "(", "items", ")", "{", "this", ".", "data", "=", "items", ";", "this", ".", "items", ".", "empty", "(", ")", ";", "this", ".", "tabs", ".", "empty", "(", ")", ";", "for", "(", "var", "li", ",", "a", ",", "item", ",", "i", "=", "0", ";", "item", "=", "items", "[", "i", "]", ";", "i", "++", ")", "{", "li", "=", "$", "(", "'<li/>'", ")", ";", "li", ".", "appendTo", "(", "this", ".", "items", ")", ";", "a", "=", "$", "(", "'<a/>'", ")", ".", "attr", "(", "'href'", ",", "'javascript:;'", ")", ".", "data", "(", "'showcase-index'", ",", "i", ")", ";", "li", "=", "$", "(", "'<li/>'", ")", ";", "li", ".", "appendTo", "(", "this", ".", "tabs", ")", ".", "append", "(", "a", ")", ";", "}", "if", "(", "items", ".", "length", "<=", "1", ")", "{", "this", ".", "element", ".", "addClass", "(", "'is-single'", ")", ";", "}", "this", ".", "fireEvent", "(", "'load'", ",", "[", "items", "]", ")", ";", "}" ]
Build the list of items and tabs based on the generated data. Determine which elements to show and bind based on the data. @private @param {Array} items
[ "Build", "the", "list", "of", "items", "and", "tabs", "based", "on", "the", "generated", "data", ".", "Determine", "which", "elements", "to", "show", "and", "bind", "based", "on", "the", "data", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/showcase.js#L323-L345
21,678
titon/toolkit
js/components/showcase.js
function(width, height) { var gutter = (this.options.gutter * 2), wWidth = $(window).width() - gutter, wHeight = $(window).height() - gutter, ratio, diff; // Resize if the width is larger if (width > wWidth) { ratio = (width / height); diff = (width - wWidth); width = wWidth; height -= Math.round(diff / ratio); } // Resize again if the height is larger if (height > wHeight) { ratio = (height / width); diff = (height - wHeight); width -= Math.round(diff / ratio); height = wHeight; } this.items.css({ width: width, height: height }); }
javascript
function(width, height) { var gutter = (this.options.gutter * 2), wWidth = $(window).width() - gutter, wHeight = $(window).height() - gutter, ratio, diff; // Resize if the width is larger if (width > wWidth) { ratio = (width / height); diff = (width - wWidth); width = wWidth; height -= Math.round(diff / ratio); } // Resize again if the height is larger if (height > wHeight) { ratio = (height / width); diff = (height - wHeight); width -= Math.round(diff / ratio); height = wHeight; } this.items.css({ width: width, height: height }); }
[ "function", "(", "width", ",", "height", ")", "{", "var", "gutter", "=", "(", "this", ".", "options", ".", "gutter", "*", "2", ")", ",", "wWidth", "=", "$", "(", "window", ")", ".", "width", "(", ")", "-", "gutter", ",", "wHeight", "=", "$", "(", "window", ")", ".", "height", "(", ")", "-", "gutter", ",", "ratio", ",", "diff", ";", "// Resize if the width is larger", "if", "(", "width", ">", "wWidth", ")", "{", "ratio", "=", "(", "width", "/", "height", ")", ";", "diff", "=", "(", "width", "-", "wWidth", ")", ";", "width", "=", "wWidth", ";", "height", "-=", "Math", ".", "round", "(", "diff", "/", "ratio", ")", ";", "}", "// Resize again if the height is larger", "if", "(", "height", ">", "wHeight", ")", "{", "ratio", "=", "(", "height", "/", "width", ")", ";", "diff", "=", "(", "height", "-", "wHeight", ")", ";", "width", "-=", "Math", ".", "round", "(", "diff", "/", "ratio", ")", ";", "height", "=", "wHeight", ";", "}", "this", ".", "items", ".", "css", "(", "{", "width", ":", "width", ",", "height", ":", "height", "}", ")", ";", "}" ]
Resize the showcase modal when it is larger than the current viewport. @private @param {Number} width @param {Number} height
[ "Resize", "the", "showcase", "modal", "when", "it", "is", "larger", "than", "the", "current", "viewport", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/js/components/showcase.js#L354-L383
21,679
titon/toolkit
dist/toolkit.js
function(plugin, callback, collection) { var name = plugin; // Prefix with toolkit to avoid collisions if ($.fn[name]) { name = 'toolkit' + name.charAt(0).toUpperCase() + name.slice(1); } $.fn[name] = collection ? // Apply the instance to a collection of elements function() { var instance = Toolkit.cache[plugin + ':' + this.selector] = callback.apply(this, arguments); return this.each(function() { $(this).cache('toolkit.' + plugin, instance); }); } : // Apply the instance per element function() { var args = arguments; return this.each(function() { $(this).cache('toolkit.' + plugin, callback.apply(this, args)); }); }; }
javascript
function(plugin, callback, collection) { var name = plugin; // Prefix with toolkit to avoid collisions if ($.fn[name]) { name = 'toolkit' + name.charAt(0).toUpperCase() + name.slice(1); } $.fn[name] = collection ? // Apply the instance to a collection of elements function() { var instance = Toolkit.cache[plugin + ':' + this.selector] = callback.apply(this, arguments); return this.each(function() { $(this).cache('toolkit.' + plugin, instance); }); } : // Apply the instance per element function() { var args = arguments; return this.each(function() { $(this).cache('toolkit.' + plugin, callback.apply(this, args)); }); }; }
[ "function", "(", "plugin", ",", "callback", ",", "collection", ")", "{", "var", "name", "=", "plugin", ";", "// Prefix with toolkit to avoid collisions", "if", "(", "$", ".", "fn", "[", "name", "]", ")", "{", "name", "=", "'toolkit'", "+", "name", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "name", ".", "slice", "(", "1", ")", ";", "}", "$", ".", "fn", "[", "name", "]", "=", "collection", "?", "// Apply the instance to a collection of elements", "function", "(", ")", "{", "var", "instance", "=", "Toolkit", ".", "cache", "[", "plugin", "+", "':'", "+", "this", ".", "selector", "]", "=", "callback", ".", "apply", "(", "this", ",", "arguments", ")", ";", "return", "this", ".", "each", "(", "function", "(", ")", "{", "$", "(", "this", ")", ".", "cache", "(", "'toolkit.'", "+", "plugin", ",", "instance", ")", ";", "}", ")", ";", "}", ":", "// Apply the instance per element", "function", "(", ")", "{", "var", "args", "=", "arguments", ";", "return", "this", ".", "each", "(", "function", "(", ")", "{", "$", "(", "this", ")", ".", "cache", "(", "'toolkit.'", "+", "plugin", ",", "callback", ".", "apply", "(", "this", ",", "args", ")", ")", ";", "}", ")", ";", "}", ";", "}" ]
Creates a jQuery plugin by extending the jQuery prototype with a method definition. The Toolkit plugin is only initialized if one has not been already. Plugins are either defined per element, or on a collection of elements. @param {String} plugin @param {Function} callback @param {bool} [collection]
[ "Creates", "a", "jQuery", "plugin", "by", "extending", "the", "jQuery", "prototype", "with", "a", "method", "definition", ".", "The", "Toolkit", "plugin", "is", "only", "initialized", "if", "one", "has", "not", "been", "already", ".", "Plugins", "are", "either", "defined", "per", "element", "or", "on", "a", "collection", "of", "elements", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L155-L182
21,680
titon/toolkit
dist/toolkit.js
function() { var instance = Toolkit.cache[plugin + ':' + this.selector] = callback.apply(this, arguments); return this.each(function() { $(this).cache('toolkit.' + plugin, instance); }); }
javascript
function() { var instance = Toolkit.cache[plugin + ':' + this.selector] = callback.apply(this, arguments); return this.each(function() { $(this).cache('toolkit.' + plugin, instance); }); }
[ "function", "(", ")", "{", "var", "instance", "=", "Toolkit", ".", "cache", "[", "plugin", "+", "':'", "+", "this", ".", "selector", "]", "=", "callback", ".", "apply", "(", "this", ",", "arguments", ")", ";", "return", "this", ".", "each", "(", "function", "(", ")", "{", "$", "(", "this", ")", ".", "cache", "(", "'toolkit.'", "+", "plugin", ",", "instance", ")", ";", "}", ")", ";", "}" ]
Apply the instance to a collection of elements
[ "Apply", "the", "instance", "to", "a", "collection", "of", "elements" ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L166-L172
21,681
titon/toolkit
dist/toolkit.js
function(event, context, callback, selector) { var options = this.options; // Replace tokens if (event === '{mode}') { event = options.mode; } if (selector === '{selector}') { selector = this.nodes ? this.nodes.selector : ''; } // Find and bind the function if ($.type(callback) === 'string') { callback = this[callback].bind(this); } this.__events.push([event, context, callback, selector]); }
javascript
function(event, context, callback, selector) { var options = this.options; // Replace tokens if (event === '{mode}') { event = options.mode; } if (selector === '{selector}') { selector = this.nodes ? this.nodes.selector : ''; } // Find and bind the function if ($.type(callback) === 'string') { callback = this[callback].bind(this); } this.__events.push([event, context, callback, selector]); }
[ "function", "(", "event", ",", "context", ",", "callback", ",", "selector", ")", "{", "var", "options", "=", "this", ".", "options", ";", "// Replace tokens", "if", "(", "event", "===", "'{mode}'", ")", "{", "event", "=", "options", ".", "mode", ";", "}", "if", "(", "selector", "===", "'{selector}'", ")", "{", "selector", "=", "this", ".", "nodes", "?", "this", ".", "nodes", ".", "selector", ":", "''", ";", "}", "// Find and bind the function", "if", "(", "$", ".", "type", "(", "callback", ")", "===", "'string'", ")", "{", "callback", "=", "this", "[", "callback", "]", ".", "bind", "(", "this", ")", ";", "}", "this", ".", "__events", ".", "push", "(", "[", "event", ",", "context", ",", "callback", ",", "selector", "]", ")", ";", "}" ]
Add an event to bind. @param {String} event @param {String} context @param {String|Function} callback @param {String} selector
[ "Add", "an", "event", "to", "bind", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L302-L320
21,682
titon/toolkit
dist/toolkit.js
function(type, callback) { var list = this.__hooks[type] || []; list.push(callback); this.__hooks[type] = list; }
javascript
function(type, callback) { var list = this.__hooks[type] || []; list.push(callback); this.__hooks[type] = list; }
[ "function", "(", "type", ",", "callback", ")", "{", "var", "list", "=", "this", ".", "__hooks", "[", "type", "]", "||", "[", "]", ";", "list", ".", "push", "(", "callback", ")", ";", "this", ".", "__hooks", "[", "type", "]", "=", "list", ";", "}" ]
Add a hook to a specific event type. @param {String} type @param {Function} callback
[ "Add", "a", "hook", "to", "a", "specific", "event", "type", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L339-L344
21,683
titon/toolkit
dist/toolkit.js
function(type, callbacks) { $.each(callbacks, function(i, callback) { this.addHook(type, callback); }.bind(this)); }
javascript
function(type, callbacks) { $.each(callbacks, function(i, callback) { this.addHook(type, callback); }.bind(this)); }
[ "function", "(", "type", ",", "callbacks", ")", "{", "$", ".", "each", "(", "callbacks", ",", "function", "(", "i", ",", "callback", ")", "{", "this", ".", "addHook", "(", "type", ",", "callback", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Add multiple hooks for a type. @param {String} type @param {Array} callbacks
[ "Add", "multiple", "hooks", "for", "a", "type", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L352-L356
21,684
titon/toolkit
dist/toolkit.js
function(type) { var self = this, event, context, func, selector, win = $(window), doc = $(document); $.each(this.__events, function(i, value) { event = value[0]; context = value[1]; func = value[2]; selector = value[3]; // Determine the correct context if (self[context]) { context = self[context]; } else if (context === 'window') { context = win; } else if (context === 'document') { context = doc; } // Ready events if (event === 'ready') { doc.ready(func); // Delegated events } else if (selector) { $(context)[type](event, selector, func); // Regular events } else { $(context)[type](event, func); } }); }
javascript
function(type) { var self = this, event, context, func, selector, win = $(window), doc = $(document); $.each(this.__events, function(i, value) { event = value[0]; context = value[1]; func = value[2]; selector = value[3]; // Determine the correct context if (self[context]) { context = self[context]; } else if (context === 'window') { context = win; } else if (context === 'document') { context = doc; } // Ready events if (event === 'ready') { doc.ready(func); // Delegated events } else if (selector) { $(context)[type](event, selector, func); // Regular events } else { $(context)[type](event, func); } }); }
[ "function", "(", "type", ")", "{", "var", "self", "=", "this", ",", "event", ",", "context", ",", "func", ",", "selector", ",", "win", "=", "$", "(", "window", ")", ",", "doc", "=", "$", "(", "document", ")", ";", "$", ".", "each", "(", "this", ".", "__events", ",", "function", "(", "i", ",", "value", ")", "{", "event", "=", "value", "[", "0", "]", ";", "context", "=", "value", "[", "1", "]", ";", "func", "=", "value", "[", "2", "]", ";", "selector", "=", "value", "[", "3", "]", ";", "// Determine the correct context", "if", "(", "self", "[", "context", "]", ")", "{", "context", "=", "self", "[", "context", "]", ";", "}", "else", "if", "(", "context", "===", "'window'", ")", "{", "context", "=", "win", ";", "}", "else", "if", "(", "context", "===", "'document'", ")", "{", "context", "=", "doc", ";", "}", "// Ready events", "if", "(", "event", "===", "'ready'", ")", "{", "doc", ".", "ready", "(", "func", ")", ";", "// Delegated events", "}", "else", "if", "(", "selector", ")", "{", "$", "(", "context", ")", "[", "type", "]", "(", "event", ",", "selector", ",", "func", ")", ";", "// Regular events", "}", "else", "{", "$", "(", "context", ")", "[", "type", "]", "(", "event", ",", "func", ")", ";", "}", "}", ")", ";", "}" ]
Loop through the events object and attach events to the specified selector in the correct context. Take into account window, document, and delegation. @param {String} type
[ "Loop", "through", "the", "events", "object", "and", "attach", "events", "to", "the", "specified", "selector", "in", "the", "correct", "context", ".", "Take", "into", "account", "window", "document", "and", "delegation", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L364-L403
21,685
titon/toolkit
dist/toolkit.js
function(type, args) { var debug = this.options.debug || Toolkit.debug; if (debug) { console.log(this.name + '#' + this.uid, new Date().getMilliseconds(), type, args || []); if (debug === 'verbose') { console.dir(this); } } var hooks = this.__hooks[type]; if (hooks) { $.each(hooks, function(i, hook) { hook.apply(this, args || []); }.bind(this)); } }
javascript
function(type, args) { var debug = this.options.debug || Toolkit.debug; if (debug) { console.log(this.name + '#' + this.uid, new Date().getMilliseconds(), type, args || []); if (debug === 'verbose') { console.dir(this); } } var hooks = this.__hooks[type]; if (hooks) { $.each(hooks, function(i, hook) { hook.apply(this, args || []); }.bind(this)); } }
[ "function", "(", "type", ",", "args", ")", "{", "var", "debug", "=", "this", ".", "options", ".", "debug", "||", "Toolkit", ".", "debug", ";", "if", "(", "debug", ")", "{", "console", ".", "log", "(", "this", ".", "name", "+", "'#'", "+", "this", ".", "uid", ",", "new", "Date", "(", ")", ".", "getMilliseconds", "(", ")", ",", "type", ",", "args", "||", "[", "]", ")", ";", "if", "(", "debug", "===", "'verbose'", ")", "{", "console", ".", "dir", "(", "this", ")", ";", "}", "}", "var", "hooks", "=", "this", ".", "__hooks", "[", "type", "]", ";", "if", "(", "hooks", ")", "{", "$", ".", "each", "(", "hooks", ",", "function", "(", "i", ",", "hook", ")", "{", "hook", ".", "apply", "(", "this", ",", "args", "||", "[", "]", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}", "}" ]
Trigger all hooks defined by type. @param {String} type @param {Array} [args]
[ "Trigger", "all", "hooks", "defined", "by", "type", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L455-L473
21,686
titon/toolkit
dist/toolkit.js
function(type, callback) { if (!callback) { delete this.__hooks[type]; return; } var hooks = this.__hooks[type]; if (hooks) { $.each(hooks, function(i, hook) { if (hook === callback) { hooks = hooks.splice(i, 1); } }); } }
javascript
function(type, callback) { if (!callback) { delete this.__hooks[type]; return; } var hooks = this.__hooks[type]; if (hooks) { $.each(hooks, function(i, hook) { if (hook === callback) { hooks = hooks.splice(i, 1); } }); } }
[ "function", "(", "type", ",", "callback", ")", "{", "if", "(", "!", "callback", ")", "{", "delete", "this", ".", "__hooks", "[", "type", "]", ";", "return", ";", "}", "var", "hooks", "=", "this", ".", "__hooks", "[", "type", "]", ";", "if", "(", "hooks", ")", "{", "$", ".", "each", "(", "hooks", ",", "function", "(", "i", ",", "hook", ")", "{", "if", "(", "hook", "===", "callback", ")", "{", "hooks", "=", "hooks", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "}", ")", ";", "}", "}" ]
Remove a hook within a type. If the callback is not provided, remove all hooks in that type. @param {String} type @param {Function} [callback]
[ "Remove", "a", "hook", "within", "a", "type", ".", "If", "the", "callback", "is", "not", "provided", "remove", "all", "hooks", "in", "that", "type", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L489-L504
21,687
titon/toolkit
dist/toolkit.js
function(options) { var opts = $.extend(true, {}, Toolkit[this.name].options, options || {}), key; // Inherit options based on responsive media queries if (opts.responsive && window.matchMedia) { $.each(opts.responsive, function(key, resOpts) { if (matchMedia(resOpts.breakpoint).matches) { $.extend(opts, resOpts); } }); } // Set hooks that start with `on` for (key in opts) { if (key.match(/^on[A-Z]/)) { this.addHook(key.substr(2).toLowerCase(), opts[key]); delete opts[key]; } } this.options = opts; return opts; }
javascript
function(options) { var opts = $.extend(true, {}, Toolkit[this.name].options, options || {}), key; // Inherit options based on responsive media queries if (opts.responsive && window.matchMedia) { $.each(opts.responsive, function(key, resOpts) { if (matchMedia(resOpts.breakpoint).matches) { $.extend(opts, resOpts); } }); } // Set hooks that start with `on` for (key in opts) { if (key.match(/^on[A-Z]/)) { this.addHook(key.substr(2).toLowerCase(), opts[key]); delete opts[key]; } } this.options = opts; return opts; }
[ "function", "(", "options", ")", "{", "var", "opts", "=", "$", ".", "extend", "(", "true", ",", "{", "}", ",", "Toolkit", "[", "this", ".", "name", "]", ".", "options", ",", "options", "||", "{", "}", ")", ",", "key", ";", "// Inherit options based on responsive media queries", "if", "(", "opts", ".", "responsive", "&&", "window", ".", "matchMedia", ")", "{", "$", ".", "each", "(", "opts", ".", "responsive", ",", "function", "(", "key", ",", "resOpts", ")", "{", "if", "(", "matchMedia", "(", "resOpts", ".", "breakpoint", ")", ".", "matches", ")", "{", "$", ".", "extend", "(", "opts", ",", "resOpts", ")", ";", "}", "}", ")", ";", "}", "// Set hooks that start with `on`", "for", "(", "key", "in", "opts", ")", "{", "if", "(", "key", ".", "match", "(", "/", "^on[A-Z]", "/", ")", ")", "{", "this", ".", "addHook", "(", "key", ".", "substr", "(", "2", ")", ".", "toLowerCase", "(", ")", ",", "opts", "[", "key", "]", ")", ";", "delete", "opts", "[", "key", "]", ";", "}", "}", "this", ".", "options", "=", "opts", ";", "return", "opts", ";", "}" ]
Set the options by merging with defaults. If the `responsive` option exists, attempt to alter the options based on media query breakpoints. Furthermore, if an option begins with `on`, add it as a hook. @param {Object} [options] @returns {Object}
[ "Set", "the", "options", "by", "merging", "with", "defaults", ".", "If", "the", "responsive", "option", "exists", "attempt", "to", "alter", "the", "options", "based", "on", "media", "query", "breakpoints", ".", "Furthermore", "if", "an", "option", "begins", "with", "on", "add", "it", "as", "a", "hook", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L514-L539
21,688
titon/toolkit
dist/toolkit.js
doAria
function doAria(element, key, value) { if ($.type(value) === 'undefined') { return element.getAttribute('aria-' + key); } if (value === true) { value = 'true'; } else if (value === false) { value = 'false'; } element.setAttribute('aria-' + key, value); }
javascript
function doAria(element, key, value) { if ($.type(value) === 'undefined') { return element.getAttribute('aria-' + key); } if (value === true) { value = 'true'; } else if (value === false) { value = 'false'; } element.setAttribute('aria-' + key, value); }
[ "function", "doAria", "(", "element", ",", "key", ",", "value", ")", "{", "if", "(", "$", ".", "type", "(", "value", ")", "===", "'undefined'", ")", "{", "return", "element", ".", "getAttribute", "(", "'aria-'", "+", "key", ")", ";", "}", "if", "(", "value", "===", "true", ")", "{", "value", "=", "'true'", ";", "}", "else", "if", "(", "value", "===", "false", ")", "{", "value", "=", "'false'", ";", "}", "element", ".", "setAttribute", "(", "'aria-'", "+", "key", ",", "value", ")", ";", "}" ]
A multi-purpose getter and setter for ARIA attributes. Will prefix attribute names and cast values correctly. @param {Element} element @param {String|Object} key @param {*} value
[ "A", "multi", "-", "purpose", "getter", "and", "setter", "for", "ARIA", "attributes", ".", "Will", "prefix", "attribute", "names", "and", "cast", "values", "correctly", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L554-L566
21,689
titon/toolkit
dist/toolkit.js
function(type, args) { Base.prototype.fireEvent.call(this, type, args); var element = this.element, node = this.node, event = $.Event(type + '.toolkit.' + this.keyName); event.context = this; // Trigger event on the element and the node if (element) { element.trigger(event, args || []); } if (node) { node.trigger(event, args || []); } }
javascript
function(type, args) { Base.prototype.fireEvent.call(this, type, args); var element = this.element, node = this.node, event = $.Event(type + '.toolkit.' + this.keyName); event.context = this; // Trigger event on the element and the node if (element) { element.trigger(event, args || []); } if (node) { node.trigger(event, args || []); } }
[ "function", "(", "type", ",", "args", ")", "{", "Base", ".", "prototype", ".", "fireEvent", ".", "call", "(", "this", ",", "type", ",", "args", ")", ";", "var", "element", "=", "this", ".", "element", ",", "node", "=", "this", ".", "node", ",", "event", "=", "$", ".", "Event", "(", "type", "+", "'.toolkit.'", "+", "this", ".", "keyName", ")", ";", "event", ".", "context", "=", "this", ";", "// Trigger event on the element and the node", "if", "(", "element", ")", "{", "element", ".", "trigger", "(", "event", ",", "args", "||", "[", "]", ")", ";", "}", "if", "(", "node", ")", "{", "node", ".", "trigger", "(", "event", ",", "args", "||", "[", "]", ")", ";", "}", "}" ]
Trigger all hooks and any DOM events attached to the `element` or `node`. @param {String} type @param {Array} [args]
[ "Trigger", "all", "hooks", "and", "any", "DOM", "events", "attached", "to", "the", "element", "or", "node", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L702-L718
21,690
titon/toolkit
dist/toolkit.js
function(options, element) { var key, value, obj = {}; for (key in options) { if (key === 'context' || key === 'template') { continue; } value = element.data((this.keyName + '-' + key).toLowerCase()); if ($.type(value) !== 'undefined') { obj[key] = value; } } return $.extend(true, {}, options, obj); }
javascript
function(options, element) { var key, value, obj = {}; for (key in options) { if (key === 'context' || key === 'template') { continue; } value = element.data((this.keyName + '-' + key).toLowerCase()); if ($.type(value) !== 'undefined') { obj[key] = value; } } return $.extend(true, {}, options, obj); }
[ "function", "(", "options", ",", "element", ")", "{", "var", "key", ",", "value", ",", "obj", "=", "{", "}", ";", "for", "(", "key", "in", "options", ")", "{", "if", "(", "key", "===", "'context'", "||", "key", "===", "'template'", ")", "{", "continue", ";", "}", "value", "=", "element", ".", "data", "(", "(", "this", ".", "keyName", "+", "'-'", "+", "key", ")", ".", "toLowerCase", "(", ")", ")", ";", "if", "(", "$", ".", "type", "(", "value", ")", "!==", "'undefined'", ")", "{", "obj", "[", "key", "]", "=", "value", ";", "}", "}", "return", "$", ".", "extend", "(", "true", ",", "{", "}", ",", "options", ",", "obj", ")", ";", "}" ]
Inherit options from the target elements data attributes. @param {Object} options @param {jQuery} element @returns {Object}
[ "Inherit", "options", "from", "the", "target", "elements", "data", "attributes", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L750-L766
21,691
titon/toolkit
dist/toolkit.js
function(element, block) { var selector = 'data-' + (block || this.keyName); if (element) { selector += '-' + element; } if (this.namespace) { selector += '="' + this.namespace + '"'; } return '[' + selector + ']'; }
javascript
function(element, block) { var selector = 'data-' + (block || this.keyName); if (element) { selector += '-' + element; } if (this.namespace) { selector += '="' + this.namespace + '"'; } return '[' + selector + ']'; }
[ "function", "(", "element", ",", "block", ")", "{", "var", "selector", "=", "'data-'", "+", "(", "block", "||", "this", ".", "keyName", ")", ";", "if", "(", "element", ")", "{", "selector", "+=", "'-'", "+", "element", ";", "}", "if", "(", "this", ".", "namespace", ")", "{", "selector", "+=", "'=\"'", "+", "this", ".", "namespace", "+", "'\"'", ";", "}", "return", "'['", "+", "selector", "+", "']'", ";", "}" ]
Generate a valid data attribute selector based on the current component name and namespace. @param {String} [element] @param {String} [block] @returns {string}
[ "Generate", "a", "valid", "data", "attribute", "selector", "based", "on", "the", "current", "component", "name", "and", "namespace", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L812-L824
21,692
titon/toolkit
dist/toolkit.js
function(content) { if (content.callback) { var namespaces = content.callback.split('.'), func = window, prev = func; for (var i = 0; i < namespaces.length; i++) { prev = func; func = func[namespaces[i]]; } func.call(prev, content); } this.fireEvent('process', [content]); this.hide(); }
javascript
function(content) { if (content.callback) { var namespaces = content.callback.split('.'), func = window, prev = func; for (var i = 0; i < namespaces.length; i++) { prev = func; func = func[namespaces[i]]; } func.call(prev, content); } this.fireEvent('process', [content]); this.hide(); }
[ "function", "(", "content", ")", "{", "if", "(", "content", ".", "callback", ")", "{", "var", "namespaces", "=", "content", ".", "callback", ".", "split", "(", "'.'", ")", ",", "func", "=", "window", ",", "prev", "=", "func", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "namespaces", ".", "length", ";", "i", "++", ")", "{", "prev", "=", "func", ";", "func", "=", "func", "[", "namespaces", "[", "i", "]", "]", ";", "}", "func", ".", "call", "(", "prev", ",", "content", ")", ";", "}", "this", ".", "fireEvent", "(", "'process'", ",", "[", "content", "]", ")", ";", "this", ".", "hide", "(", ")", ";", "}" ]
Handle and process non-HTML responses. @param {*} content
[ "Handle", "and", "process", "non", "-", "HTML", "responses", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L840-L856
21,693
titon/toolkit
dist/toolkit.js
function(element, key) { var value = element.data((this.keyName + '-' + key).toLowerCase()); if ($.type(value) === 'undefined') { value = this.options[key]; } return value; }
javascript
function(element, key) { var value = element.data((this.keyName + '-' + key).toLowerCase()); if ($.type(value) === 'undefined') { value = this.options[key]; } return value; }
[ "function", "(", "element", ",", "key", ")", "{", "var", "value", "=", "element", ".", "data", "(", "(", "this", ".", "keyName", "+", "'-'", "+", "key", ")", ".", "toLowerCase", "(", ")", ")", ";", "if", "(", "$", ".", "type", "(", "value", ")", "===", "'undefined'", ")", "{", "value", "=", "this", ".", "options", "[", "key", "]", ";", "}", "return", "value", ";", "}" ]
Read a class option from a data attribute. If no attribute exists, return the option value. @param {jQuery} element @param {String} key @returns {*}
[ "Read", "a", "class", "option", "from", "a", "data", "attribute", ".", "If", "no", "attribute", "exists", "return", "the", "option", "value", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L866-L874
21,694
titon/toolkit
dist/toolkit.js
function(element, query) { if (!query) { return null; } element = $(element); if ($.type(query) === 'function') { return query.call(this, element); } return element.attr(query); }
javascript
function(element, query) { if (!query) { return null; } element = $(element); if ($.type(query) === 'function') { return query.call(this, element); } return element.attr(query); }
[ "function", "(", "element", ",", "query", ")", "{", "if", "(", "!", "query", ")", "{", "return", "null", ";", "}", "element", "=", "$", "(", "element", ")", ";", "if", "(", "$", ".", "type", "(", "query", ")", "===", "'function'", ")", "{", "return", "query", ".", "call", "(", "this", ",", "element", ")", ";", "}", "return", "element", ".", "attr", "(", "query", ")", ";", "}" ]
Attempt to read a value from an element using the query. Query can either be an attribute name, or a callback function. @param {jQuery} element @param {String|Function} query @returns {String}
[ "Attempt", "to", "read", "a", "value", "from", "an", "element", "using", "the", "query", ".", "Query", "can", "either", "be", "an", "attribute", "name", "or", "a", "callback", "function", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L884-L896
21,695
titon/toolkit
dist/toolkit.js
function(options, params) { var ajax = {}; // Determine base options if ($.type(this.options.ajax) === 'object') { ajax = this.options.ajax; } // Set default options if ($.type(options) === 'string') { ajax.url = options; } else { $.extend(ajax, options); } // Prepare XHR object ajax.context = this; ajax.beforeSend = function(xhr) { xhr.url = ajax.url; xhr.cache = ((!ajax.type || ajax.type.toUpperCase() === 'GET') && this.options.cache); xhr.settings = ajax; xhr.params = params || {}; this.onRequestBefore.call(this, xhr); }; return $.ajax(ajax) .done(this.onRequestDone) .fail(this.onRequestFail); }
javascript
function(options, params) { var ajax = {}; // Determine base options if ($.type(this.options.ajax) === 'object') { ajax = this.options.ajax; } // Set default options if ($.type(options) === 'string') { ajax.url = options; } else { $.extend(ajax, options); } // Prepare XHR object ajax.context = this; ajax.beforeSend = function(xhr) { xhr.url = ajax.url; xhr.cache = ((!ajax.type || ajax.type.toUpperCase() === 'GET') && this.options.cache); xhr.settings = ajax; xhr.params = params || {}; this.onRequestBefore.call(this, xhr); }; return $.ajax(ajax) .done(this.onRequestDone) .fail(this.onRequestFail); }
[ "function", "(", "options", ",", "params", ")", "{", "var", "ajax", "=", "{", "}", ";", "// Determine base options", "if", "(", "$", ".", "type", "(", "this", ".", "options", ".", "ajax", ")", "===", "'object'", ")", "{", "ajax", "=", "this", ".", "options", ".", "ajax", ";", "}", "// Set default options", "if", "(", "$", ".", "type", "(", "options", ")", "===", "'string'", ")", "{", "ajax", ".", "url", "=", "options", ";", "}", "else", "{", "$", ".", "extend", "(", "ajax", ",", "options", ")", ";", "}", "// Prepare XHR object", "ajax", ".", "context", "=", "this", ";", "ajax", ".", "beforeSend", "=", "function", "(", "xhr", ")", "{", "xhr", ".", "url", "=", "ajax", ".", "url", ";", "xhr", ".", "cache", "=", "(", "(", "!", "ajax", ".", "type", "||", "ajax", ".", "type", ".", "toUpperCase", "(", ")", "===", "'GET'", ")", "&&", "this", ".", "options", ".", "cache", ")", ";", "xhr", ".", "settings", "=", "ajax", ";", "xhr", ".", "params", "=", "params", "||", "{", "}", ";", "this", ".", "onRequestBefore", ".", "call", "(", "this", ",", "xhr", ")", ";", "}", ";", "return", "$", ".", "ajax", "(", "ajax", ")", ".", "done", "(", "this", ".", "onRequestDone", ")", ".", "fail", "(", "this", ".", "onRequestFail", ")", ";", "}" ]
Request data from a URL and handle all the possible scenarios. @param {Object} options @param {Object} [params] @returns {jQuery.ajax}
[ "Request", "data", "from", "a", "URL", "and", "handle", "all", "the", "possible", "scenarios", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L915-L945
21,696
titon/toolkit
dist/toolkit.js
function(options, inheritFrom) { // Inherit options from a group if the data attribute exists // Do this first so responsive options can be triggered afterwards if (inheritFrom) { var group = this.readOption(inheritFrom, 'group'); if (group && options.groups[group]) { $.extend(options, options.groups[group]); } } var opts = Base.prototype.setOptions.call(this, options); // Inherit options from element data attributes if (inheritFrom) { opts = this.inheritOptions(opts, inheritFrom); } // Convert hover to mouseenter if (opts.mode && opts.mode === 'hover') { opts.mode = Toolkit.isTouch ? 'click' : 'mouseenter'; } this.options = opts; return opts; }
javascript
function(options, inheritFrom) { // Inherit options from a group if the data attribute exists // Do this first so responsive options can be triggered afterwards if (inheritFrom) { var group = this.readOption(inheritFrom, 'group'); if (group && options.groups[group]) { $.extend(options, options.groups[group]); } } var opts = Base.prototype.setOptions.call(this, options); // Inherit options from element data attributes if (inheritFrom) { opts = this.inheritOptions(opts, inheritFrom); } // Convert hover to mouseenter if (opts.mode && opts.mode === 'hover') { opts.mode = Toolkit.isTouch ? 'click' : 'mouseenter'; } this.options = opts; return opts; }
[ "function", "(", "options", ",", "inheritFrom", ")", "{", "// Inherit options from a group if the data attribute exists", "// Do this first so responsive options can be triggered afterwards", "if", "(", "inheritFrom", ")", "{", "var", "group", "=", "this", ".", "readOption", "(", "inheritFrom", ",", "'group'", ")", ";", "if", "(", "group", "&&", "options", ".", "groups", "[", "group", "]", ")", "{", "$", ".", "extend", "(", "options", ",", "options", ".", "groups", "[", "group", "]", ")", ";", "}", "}", "var", "opts", "=", "Base", ".", "prototype", ".", "setOptions", ".", "call", "(", "this", ",", "options", ")", ";", "// Inherit options from element data attributes", "if", "(", "inheritFrom", ")", "{", "opts", "=", "this", ".", "inheritOptions", "(", "opts", ",", "inheritFrom", ")", ";", "}", "// Convert hover to mouseenter", "if", "(", "opts", ".", "mode", "&&", "opts", ".", "mode", "===", "'hover'", ")", "{", "opts", ".", "mode", "=", "Toolkit", ".", "isTouch", "?", "'click'", ":", "'mouseenter'", ";", "}", "this", ".", "options", "=", "opts", ";", "return", "opts", ";", "}" ]
After merging options with the default options, inherit options from an elements data attributes. @param {Object} [options] @param {jQuery} [inheritFrom] @returns {Object}
[ "After", "merging", "options", "with", "the", "default", "options", "inherit", "options", "from", "an", "elements", "data", "attributes", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L970-L997
21,697
titon/toolkit
dist/toolkit.js
function(element, options) { var self = this; element = this.setElement(element).attr('role', 'tablist'); options = this.setOptions(options, element); // Find headers and cache the index of each header and set ARIA attributes this.headers = element.find(this.ns('header')).each(function(index) { $(this) .data('accordion-index', index) .attr({ role: 'tab', id: self.id('header', index) }) .aria({ controls: self.id('section', index), selected: false, expanded: false }); }); // Find sections and cache the height so we can use for sliding and set ARIA attributes this.sections = element.find(this.ns('section')).each(function(index) { $(this) .attr({ role: 'tabpanel', id: self.id('section', index) }) .aria('labelledby', self.id('header', index)) .conceal(); }); // Set events this.addEvents([ ['horizontalresize', 'window', $.debounce(this.calculate.bind(this))], ['{mode}', 'element', 'onShow', this.ns('header')] ]); // Initialize this.initialize(); // Jump to the index on page load this.calculate(); this.jump(options.defaultIndex); }
javascript
function(element, options) { var self = this; element = this.setElement(element).attr('role', 'tablist'); options = this.setOptions(options, element); // Find headers and cache the index of each header and set ARIA attributes this.headers = element.find(this.ns('header')).each(function(index) { $(this) .data('accordion-index', index) .attr({ role: 'tab', id: self.id('header', index) }) .aria({ controls: self.id('section', index), selected: false, expanded: false }); }); // Find sections and cache the height so we can use for sliding and set ARIA attributes this.sections = element.find(this.ns('section')).each(function(index) { $(this) .attr({ role: 'tabpanel', id: self.id('section', index) }) .aria('labelledby', self.id('header', index)) .conceal(); }); // Set events this.addEvents([ ['horizontalresize', 'window', $.debounce(this.calculate.bind(this))], ['{mode}', 'element', 'onShow', this.ns('header')] ]); // Initialize this.initialize(); // Jump to the index on page load this.calculate(); this.jump(options.defaultIndex); }
[ "function", "(", "element", ",", "options", ")", "{", "var", "self", "=", "this", ";", "element", "=", "this", ".", "setElement", "(", "element", ")", ".", "attr", "(", "'role'", ",", "'tablist'", ")", ";", "options", "=", "this", ".", "setOptions", "(", "options", ",", "element", ")", ";", "// Find headers and cache the index of each header and set ARIA attributes", "this", ".", "headers", "=", "element", ".", "find", "(", "this", ".", "ns", "(", "'header'", ")", ")", ".", "each", "(", "function", "(", "index", ")", "{", "$", "(", "this", ")", ".", "data", "(", "'accordion-index'", ",", "index", ")", ".", "attr", "(", "{", "role", ":", "'tab'", ",", "id", ":", "self", ".", "id", "(", "'header'", ",", "index", ")", "}", ")", ".", "aria", "(", "{", "controls", ":", "self", ".", "id", "(", "'section'", ",", "index", ")", ",", "selected", ":", "false", ",", "expanded", ":", "false", "}", ")", ";", "}", ")", ";", "// Find sections and cache the height so we can use for sliding and set ARIA attributes", "this", ".", "sections", "=", "element", ".", "find", "(", "this", ".", "ns", "(", "'section'", ")", ")", ".", "each", "(", "function", "(", "index", ")", "{", "$", "(", "this", ")", ".", "attr", "(", "{", "role", ":", "'tabpanel'", ",", "id", ":", "self", ".", "id", "(", "'section'", ",", "index", ")", "}", ")", ".", "aria", "(", "'labelledby'", ",", "self", ".", "id", "(", "'header'", ",", "index", ")", ")", ".", "conceal", "(", ")", ";", "}", ")", ";", "// Set events", "this", ".", "addEvents", "(", "[", "[", "'horizontalresize'", ",", "'window'", ",", "$", ".", "debounce", "(", "this", ".", "calculate", ".", "bind", "(", "this", ")", ")", "]", ",", "[", "'{mode}'", ",", "'element'", ",", "'onShow'", ",", "this", ".", "ns", "(", "'header'", ")", "]", "]", ")", ";", "// Initialize", "this", ".", "initialize", "(", ")", ";", "// Jump to the index on page load", "this", ".", "calculate", "(", ")", ";", "this", ".", "jump", "(", "options", ".", "defaultIndex", ")", ";", "}" ]
Initialize the accordion. @param {jQuery} element @param {Object} [options]
[ "Initialize", "the", "accordion", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L1197-L1241
21,698
titon/toolkit
dist/toolkit.js
function(options) { options = this.setOptions(options); this.element = this.createElement(); // Generate loader elements this.loader = this.render(options.loaderTemplate).appendTo(this.element); this.message = this.loader.find(this.ns('message', 'loader')); if (options.showLoading) { this.message.html(Toolkit.messages.loading); } // Initialize this.initialize(); }
javascript
function(options) { options = this.setOptions(options); this.element = this.createElement(); // Generate loader elements this.loader = this.render(options.loaderTemplate).appendTo(this.element); this.message = this.loader.find(this.ns('message', 'loader')); if (options.showLoading) { this.message.html(Toolkit.messages.loading); } // Initialize this.initialize(); }
[ "function", "(", "options", ")", "{", "options", "=", "this", ".", "setOptions", "(", "options", ")", ";", "this", ".", "element", "=", "this", ".", "createElement", "(", ")", ";", "// Generate loader elements", "this", ".", "loader", "=", "this", ".", "render", "(", "options", ".", "loaderTemplate", ")", ".", "appendTo", "(", "this", ".", "element", ")", ";", "this", ".", "message", "=", "this", ".", "loader", ".", "find", "(", "this", ".", "ns", "(", "'message'", ",", "'loader'", ")", ")", ";", "if", "(", "options", ".", "showLoading", ")", "{", "this", ".", "message", ".", "html", "(", "Toolkit", ".", "messages", ".", "loading", ")", ";", "}", "// Initialize", "this", ".", "initialize", "(", ")", ";", "}" ]
Create the blackout and loader elements. @param {Object} [options]
[ "Create", "the", "blackout", "and", "loader", "elements", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L1433-L1447
21,699
titon/toolkit
dist/toolkit.js
function() { this.fireEvent('hiding'); var count = this.count - 1; if (count <= 0) { this.count = 0; this.element.conceal(); } else { this.count = count; } this.hideLoader(); this.fireEvent('hidden', [(count <= 0)]); }
javascript
function() { this.fireEvent('hiding'); var count = this.count - 1; if (count <= 0) { this.count = 0; this.element.conceal(); } else { this.count = count; } this.hideLoader(); this.fireEvent('hidden', [(count <= 0)]); }
[ "function", "(", ")", "{", "this", ".", "fireEvent", "(", "'hiding'", ")", ";", "var", "count", "=", "this", ".", "count", "-", "1", ";", "if", "(", "count", "<=", "0", ")", "{", "this", ".", "count", "=", "0", ";", "this", ".", "element", ".", "conceal", "(", ")", ";", "}", "else", "{", "this", ".", "count", "=", "count", ";", "}", "this", ".", "hideLoader", "(", ")", ";", "this", ".", "fireEvent", "(", "'hidden'", ",", "[", "(", "count", "<=", "0", ")", "]", ")", ";", "}" ]
Hide the blackout if count reaches 0.
[ "Hide", "the", "blackout", "if", "count", "reaches", "0", "." ]
f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c
https://github.com/titon/toolkit/blob/f0ed36d14cc6d72a7bdbc09da4b5bf7d3d664f0c/dist/toolkit.js#L1460-L1475