code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
this.disableAnimation = function() { options.animate.enabled = false; return this; };
Disable animation @return {object} Instance of the plugin for method chaining
this.disableAnimation ( )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/wel/js/jquery.easypiechart.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/wel/js/jquery.easypiechart.js
Apache-2.0
this.enableAnimation = function() { options.animate.enabled = true; return this; };
Enable animation @return {object} Instance of the plugin for method chaining
this.enableAnimation ( )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/wel/js/jquery.easypiechart.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/wel/js/jquery.easypiechart.js
Apache-2.0
describe( 'Issue 54, publish method', function () { it('should notify all subscribers, even when one is unsubscribed', function( done ){ var topic = TestHelper.getUniqueString(), token1, token1Unsubscribed = false, subscriber1 = function(){ PubSub.unsubscribe(token1); token1Unsubscribed = true; }, spy1 = sinon.spy(subscriber1), spy2 = sinon.spy(), spy3 = sinon.spy(), clock = sinon.useFakeTimers(); token1 = PubSub.subscribe( topic, spy1 ); PubSub.subscribe( topic, spy2 ); PubSub.subscribe( topic, spy3 ); PubSub.publish( topic ); clock.tick(1); assert( token1Unsubscribed === true ); assert( spy1.calledOnce ); assert( spy2.calledOnce ); assert( spy3.calledOnce ); done(); clock.restore(); }); });
This is a test proving that bug 54 has been fixed. See https://github.com/mroderick/PubSubJS/issues/54
(anonymous) ( )
javascript
mroderick/PubSubJS
test/test-issue-54.js
https://github.com/mroderick/PubSubJS/blob/master/test/test-issue-54.js
MIT
describe( 'Bug 9, publish method', function() { it('should notify all subscribers in a hierarchy', function( done ){ var subscriber1 = sinon.spy(), subscriber2 = sinon.spy(), subscriber3 = sinon.spy(), clock = sinon.useFakeTimers(); PubSub.subscribe( 'a.b.c', subscriber1 ); PubSub.subscribe( 'a.b', subscriber2 ); PubSub.subscribe( 'a', subscriber3 ); PubSub.publish( 'a.b.c.d' ); clock.tick(1); assert( subscriber1.calledOnce ); assert( subscriber2.calledOnce ); assert( subscriber3.calledOnce ); done(); clock.restore(); }); it('should notify individual subscribers, even when there are no subscribers further up', function( done ){ var rootTopic = 'a.b.c', subscriber = sinon.spy(), clock = sinon.useFakeTimers(); PubSub.subscribe(rootTopic, subscriber); PubSub.publish(rootTopic + '.d'); clock.tick(1); assert( subscriber.calledOnce ); done(); clock.restore(); }); });
This is a test proving that bug 9 has been fixed. See https://github.com/mroderick/PubSubJS/issues/9
(anonymous) ( )
javascript
mroderick/PubSubJS
test/test-bug-9.js
https://github.com/mroderick/PubSubJS/blob/master/test/test-bug-9.js
MIT
(function (root, factory){ 'use strict'; var PubSub = {}; if (root.PubSub) { PubSub = root.PubSub; console.warn("PubSub already loaded, using existing version"); } else { root.PubSub = PubSub; factory(PubSub); } // CommonJS and Node.js module support if (typeof exports === 'object'){ if (module !== undefined && module.exports) { exports = module.exports = PubSub; // Node.js specific `module.exports` } exports.PubSub = PubSub; // CommonJS module 1.1.1 spec module.exports = exports = PubSub; // CommonJS } // AMD support /* eslint-disable no-undef */ else if (typeof define === 'function' && define.amd){ define(function() { return PubSub; }); /* eslint-enable no-undef */ } }(( typeof window === 'object' && window ) || this || global, function (PubSub){
Copyright (c) 2010,2011,2012,2013,2014 Morgan Roderick http://roderick.dk License: MIT - http://mrgnrdrck.mit-license.org https://github.com/mroderick/PubSubJS
(anonymous) ( root , factory )
javascript
mroderick/PubSubJS
src/pubsub.js
https://github.com/mroderick/PubSubJS/blob/master/src/pubsub.js
MIT
function throwException( ex ){ return function reThrowException(){ throw ex; }; }
Returns a function that throws the passed exception, for use as argument for setTimeout @alias throwException @function @param { Object } ex An Error object
throwException ( ex )
javascript
mroderick/PubSubJS
src/pubsub.js
https://github.com/mroderick/PubSubJS/blob/master/src/pubsub.js
MIT
PubSub.publish = function( message, data ){ return publish( message, data, false, PubSub.immediateExceptions ); };
Publishes the message, passing the data to it's subscribers @function @alias publish @param { String } message The message to publish @param {} data The data to pass to subscribers @return { Boolean }
PubSub.publish ( message , data )
javascript
mroderick/PubSubJS
src/pubsub.js
https://github.com/mroderick/PubSubJS/blob/master/src/pubsub.js
MIT
PubSub.publishSync = function( message, data ){ return publish( message, data, true, PubSub.immediateExceptions ); };
Publishes the message synchronously, passing the data to it's subscribers @function @alias publishSync @param { String } message The message to publish @param {} data The data to pass to subscribers @return { Boolean }
PubSub.publishSync ( message , data )
javascript
mroderick/PubSubJS
src/pubsub.js
https://github.com/mroderick/PubSubJS/blob/master/src/pubsub.js
MIT
PubSub.subscribe = function( message, func ){ if ( typeof func !== 'function'){ return false; } message = (typeof message === 'symbol') ? message.toString() : message; // message is not registered yet if ( !Object.prototype.hasOwnProperty.call( messages, message ) ){ messages[message] = {}; } // forcing token as String, to allow for future expansions without breaking usage // and allow for easy use as key names for the 'messages' object var token = 'uid_' + String(++lastUid); messages[message][token] = func; // return token for unsubscribing return token; };
Subscribes the passed function to the passed message. Every returned token is unique and should be stored if you need to unsubscribe @function @alias subscribe @param { String } message The message to subscribe to @param { Function } func The function to call when a new message is published @return { String }
PubSub.subscribe ( message , func )
javascript
mroderick/PubSubJS
src/pubsub.js
https://github.com/mroderick/PubSubJS/blob/master/src/pubsub.js
MIT
PubSub.subscribeOnce = function( message, func ){ var token = PubSub.subscribe( message, function(){ // before func apply, unsubscribe message PubSub.unsubscribe( token ); func.apply( this, arguments ); }); return PubSub; };
Subscribes the passed function to the passed message once @function @alias subscribeOnce @param { String } message The message to subscribe to @param { Function } func The function to call when a new message is published @return { PubSub }
PubSub.subscribeOnce ( message , func )
javascript
mroderick/PubSubJS
src/pubsub.js
https://github.com/mroderick/PubSubJS/blob/master/src/pubsub.js
MIT
PubSub.clearAllSubscriptions = function clearAllSubscriptions(){ messages = {}; };
Clears all subscriptions @function @public @alias clearAllSubscriptions
clearAllSubscriptions ( )
javascript
mroderick/PubSubJS
src/pubsub.js
https://github.com/mroderick/PubSubJS/blob/master/src/pubsub.js
MIT
PubSub.clearSubscriptions = function clearSubscriptions(topic){ var m; for (m in messages){ if (Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0){ delete messages[m]; } } };
Clear subscriptions by the topic @function @public @alias clearAllSubscriptions @return { int }
clearSubscriptions ( topic )
javascript
mroderick/PubSubJS
src/pubsub.js
https://github.com/mroderick/PubSubJS/blob/master/src/pubsub.js
MIT
PubSub.unsubscribe = function(value){ var descendantTopicExists = function(topic) { var m; for ( m in messages ){ if ( Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0 ){ // a descendant of the topic exists: return true; } } return false; }, isTopic = typeof value === 'string' && ( Object.prototype.hasOwnProperty.call(messages, value) || descendantTopicExists(value) ), isToken = !isTopic && typeof value === 'string', isFunction = typeof value === 'function', result = false, m, message, t; if (isTopic){ PubSub.clearSubscriptions(value); return; } for ( m in messages ){ if ( Object.prototype.hasOwnProperty.call( messages, m ) ){ message = messages[m]; if ( isToken && message[value] ){ delete message[value]; result = value; // tokens are unique, so we can just stop here break; } if (isFunction) { for ( t in message ){ if (Object.prototype.hasOwnProperty.call(message, t) && message[t] === value){ delete message[t]; result = true; } } } } } return result; };
Removes subscriptions - When passed a token, removes a specific subscription. - When passed a function, removes all subscriptions for that function - When passed a topic, removes all subscriptions for that topic (hierarchy) @function @public @alias subscribeOnce @param { String | Function } value A token, function or topic to unsubscribe from @example // Unsubscribing with a token var token = PubSub.subscribe('mytopic', myFunc); PubSub.unsubscribe(token); @example // Unsubscribing with a function PubSub.unsubscribe(myFunc); @example // Unsubscribing from a topic PubSub.unsubscribe('mytopic');
PubSub.unsubscribe ( value )
javascript
mroderick/PubSubJS
src/pubsub.js
https://github.com/mroderick/PubSubJS/blob/master/src/pubsub.js
MIT
function mergeCommaExpressions(ele) { if (ele.expression && ele.expression.expressions) { return `{${ele.expression.expressions .reduce((m, i) => { m.push(i.name || i.value); return m; }, []) .join(', ')}}`; } return ''; }
add comma-delimited expressions like `{ val, number }`
mergeCommaExpressions ( ele )
javascript
i18next/react-i18next
icu.macro.js
https://github.com/i18next/react-i18next/blob/master/icu.macro.js
MIT
function mergeTaggedTemplateExpressions(ele, componentFoundIndex, t, babel) { if (t.isTaggedTemplateExpression(ele.expression)) { const [, text, index] = getTextAndInterpolatedVariables( ele.expression.tag.name, ele.expression, componentFoundIndex, babel, ); return [text, index]; } return ['', componentFoundIndex]; }
this is for supporting complex icu type interpolations date`${variable}` and number`{${varName}, ::percent}` also, plural`{${count}, one { ... } other { ... }}
mergeTaggedTemplateExpressions ( ele , componentFoundIndex , t , babel )
javascript
i18next/react-i18next
icu.macro.js
https://github.com/i18next/react-i18next/blob/master/icu.macro.js
MIT
const processJSXElement = (jsxElement, mem, t) => { const clone = t.clone(jsxElement); clone.children = clone.children.reduce((clonedMem, clonedChild) => { const clonedEle = clonedChild.node ? clonedChild.node : clonedChild; // clean out invalid definitions by replacing `{ catchDate, date, short }` with `{ catchDate }` if (clonedEle.expression && clonedEle.expression.expressions) clonedEle.expression.expressions = [clonedEle.expression.expressions[0]]; clonedMem.push(clonedChild); return clonedMem; }, []); mem.push(jsxElement); };
Common logic for adding a child element of Trans to the list of components to hydrate the translation @param {JSXElement} jsxElement @param {JSXElement[]} mem
processJSXElement
javascript
i18next/react-i18next
icu.macro.js
https://github.com/i18next/react-i18next/blob/master/icu.macro.js
MIT
function getComponents(children, babel) { const t = babel.types; return children.reduce((mem, child) => { const ele = child.node ? child.node : child; if (t.isJSXExpressionContainer(ele)) { // check for date`` and so on if (t.isTaggedTemplateExpression(ele.expression)) { ele.expression.quasi.expressions.forEach((expr) => { // check for sub-expressions. This can happen with plural`` or select`` or selectOrdinal`` // these can have nested components if (t.isTaggedTemplateExpression(expr) && expr.quasi.expressions.length) { mem.push(...getComponents(expr.quasi.expressions, babel)); } if (!t.isJSXElement(expr)) { // ignore anything that is not a component return; } processJSXElement(expr, mem, t); }); } } if (t.isJSXElement(ele)) { processJSXElement(ele, mem, t); } return mem; }, []); }
Extract the React components to pass to Trans as components
getComponents ( children , babel )
javascript
i18next/react-i18next
icu.macro.js
https://github.com/i18next/react-i18next/blob/master/icu.macro.js
MIT
function addImports(state, existingImport, allImportsToAdd, t) { // append imports to existing or add a new react-i18next import for the Trans and icu tagged template literals if (existingImport) { allImportsToAdd.forEach((name) => { if ( existingImport.specifiers.findIndex( (specifier) => specifier.imported && specifier.imported.name === name, ) === -1 ) { existingImport.specifiers.push(t.importSpecifier(t.identifier(name), t.identifier(name))); } }); } else { state.file.path.node.body.unshift( t.importDeclaration( allImportsToAdd.map((name) => t.importSpecifier(t.identifier(name), t.identifier(name))), t.stringLiteral('react-i18next'), ), ); } }
helper split out of addNeededImports to make codeclimate happy This does the work of amending an existing import from "react-i18next", or creating a new one if it doesn't exist
addImports ( state , existingImport , allImportsToAdd , t )
javascript
i18next/react-i18next
icu.macro.js
https://github.com/i18next/react-i18next/blob/master/icu.macro.js
MIT
function addNeededImports(state, babel, references) { const t = babel.types; // check if there is an existing react-i18next import const existingImport = state.file.path.node.body.find( (importNode) => t.isImportDeclaration(importNode) && importNode.source.value === 'react-i18next', ); // check for any of the tagged template literals that are used in the source, and add them const usedRefs = Object.keys(references).filter((importName) => { if (!icuInterpolators.includes(importName)) { return false; } return references[importName].length; }); // combine Trans + any tagged template literals const allImportsToAdd = importsToAdd.concat(usedRefs); addImports(state, existingImport, allImportsToAdd, t); }
Add `import { Trans, number, date, <etc.> } from "react-i18next"` as needed
addNeededImports ( state , babel , references )
javascript
i18next/react-i18next
icu.macro.js
https://github.com/i18next/react-i18next/blob/master/icu.macro.js
MIT
const filterNodes = (node) => { if (node.type === 'Identifier') { // if the node has a name, keep it return node.name; } if (node.type === 'JSXElement' || node.type === 'TaggedTemplateExpression') { // always keep interpolated elements or other tagged template literals like a nested date`` inside a plural`` return true; } if (node.type === 'TemplateElement') { // return the "cooked" (escaped) text for the text in the template literal (`, ::percent` in number`${varname}, ::percent`) return node.value.cooked; } // unknown node type, ignore return false; };
filter the list of nodes within a tagged template literal to the 4 types we can process, and ignore anything else. this is a helper function for `extractVariableNamesFromQuasiNodes`
filterNodes
javascript
i18next/react-i18next
icu.macro.js
https://github.com/i18next/react-i18next/blob/master/icu.macro.js
MIT
function getTextAndInterpolatedVariables(type, primaryNode, index, babel) { throwOnInvalidType(type, primaryNode); const componentFoundIndex = index; const { text, interpolatedVariableNames } = extractVariableNamesFromQuasiNodes( primaryNode, babel, ); const { stringOutput, componentFoundIndex: newIndex } = text .filter(filterNodes) // sort by the order they appear in the source code .sort((a, b) => { if (a.start > b.start) return 1; return -1; }) .reduce(extractNestedTemplatesAndComponents, { babel, componentFoundIndex, stringOutput: [], type, interpolatedVariableNames, }); return [ interpolatedVariableNames, `{${stringOutput.join('')}}`, // return the new component interpolation index newIndex, ]; }
Retrieve the new text to use, and any interpolated variables This is used to process tagged template literals like date`${variable}` and number`${num}, ::percent` for the data example, it will return text of `{variable, date}` with a variable of `variable` for the number example, it will return text of `{num, number, ::percent}` with a variable of `num` @param {string} type the name of the tagged template (`date`, `number`, `plural`, etc. - any valid complex ICU type) @param {TaggedTemplateExpression} primaryNode the template expression node @param {int} index starting index number of components to be used for interpolations like <0> @param {*} babel
getTextAndInterpolatedVariables ( type , primaryNode , index , babel )
javascript
i18next/react-i18next
icu.macro.js
https://github.com/i18next/react-i18next/blob/master/icu.macro.js
MIT
socket.on('login', () => { // Pass the user their user info for display on the frontend const id = socket.request.session.passport.user; getProfile(id).then(userObject => { socket.emit('loginResponse', userObject); }); });
Save the new socket id to the user's session stored in Redis This ensures that on refresh, users still get websockets.
(anonymous)
javascript
freeCodeCamp/mail-for-good
server/config/server/io.js
https://github.com/freeCodeCamp/mail-for-good/blob/master/server/config/server/io.js
BSD-3-Clause
module.exports = () => { // If there are no users then the database is // probably fresh + there is no need to // update anything return User.findAll({ raw: true }) .then(users => { if (users.length) { Campaign.update({ status: 'interrupted' }, { where: { status: 'sending' } }); } return null; }) // If the promise is rejected, the table doesn't exist. This is fine, as it may be the first // time the app was run. We can discard the error. .catch(() => {}); };
Update statuses to correct the database state after shutdown/crash of the app. Example: if a campaign is sending (status: 'sending') when the app stops, the status will still be 'sending' even though sending has been interrupted. In this case, update the status to 'interrupted', allowing the user to resume sending a campaign manually.
module.exports
javascript
freeCodeCamp/mail-for-good
server/config/server/restore-db-state.js
https://github.com/freeCodeCamp/mail-for-good/blob/master/server/config/server/restore-db-state.js
BSD-3-Clause
module.exports = (credentials, callback) => { AWS.config.update({accessKeyId: credentials.accessKey, secretAccessKey: credentials.secretKey, region: credentials.region}); async.waterfall([ async.apply(createSnsTopics, { ses: { email: credentials.email }, sqs: { url: '', arn: '' }, sns: { bounce: { arn: '' }, complaint: { arn: '' } } }), createSqsQueue, subscribeSnsToSqs, subscribeSesToSns ], (err, queueUrl) => { if (err) { callback(err); } else { console.log(`SQS queue created successfully: ${queueUrl}`); callback(null, queueUrl); } }); };
Configure an AWS account for receiving SES feedback notifications (bounces and complaints) through an SNS queue. https://docs.aws.amazon.com/ses/latest/DeveloperGuide/notifications-via-sns.html End configuration: Send emails (SES) -> listen for bounces/complaints (SNS) -> publish to queue (SQS) This makes it possible to poll the SQS queue and receive the stored feedback notifications, then save the bounces/complaints in the db + associate them with CampaignSubcribers using the messageId @param credentials @param callback - Called on success or error, i.e. callback(error, queueUrl)
module.exports
javascript
freeCodeCamp/mail-for-good
server/controllers/settings/configure-aws/configure-aws.js
https://github.com/freeCodeCamp/mail-for-good/blob/master/server/controllers/settings/configure-aws/configure-aws.js
BSD-3-Clause
module.exports = async function (generator, redis, campaignAndListInfo, amazonAccountInfo, io, req) { const { campaignInfo, // See object passed by send-campaign.js, contains info about the campaigns table } = campaignAndListInfo; const { accessKey, // Amazon access key - str secretKey, // Amazon secret key - str region, // Amazon region - str whiteLabelUrl, // URL of a service that serves this app - str quotas // Amazon limits - obj { AvailableToday, MaxSendRate } } = amazonAccountInfo; /** * @description Configure variables & do work prior to starting the email send. */ const startTime = new Date(); // Track the start time so we can tell the user how long sending took const rateLimit = Number(process.env.DEV_SEND_RATE) || quotas.MaxSendRate; // No. of email we can send p/s as established by Amazon const ses = configSes(accessKey, secretKey, region); const addToQueue = CreateQueue(rateLimit, ses); const notificationSentEmails = sendUpdateEmailsSentNotification(campaignInfo, io, req); let cancelCampaignSend = false; // Flag that indicates whether or not a campaign should send await updateCampaignStatus(campaignInfo); redis.subscriber.on('message', (channel, campaignId) => { if (campaignId == campaignInfo.campaignId) { cancelCampaignSend = true; } }); redis.subscriber.subscribe('stop-campaign-sending'); /** * @description Start the campaign send. * We will start by getting all ids of list subscribers that we'll email. We'll store this in memory. * This lets us keep a small footprint on this front, while having certainty over who we will email. */ // let countPerSecond = 0; (function timerFunc() { setTimeout(() => { console.log(countPerSecond); countPerSecond = 0; timerFunc(); }, 1000) })(); // 1. Get plain array of listSubscriberIds e.g. [1, 2, 3] etc. These are the people we will email. const NESTED_ARRAY_LENGTH = 1000; const arrayOfIds = nestArray(NESTED_ARRAY_LENGTH, await getArrayOfEmailIds(campaignInfo)); const LENGTH_OF_LIST_SUBSCRIBER_IDS = arrayOfIds.length; for (let i = 0; i < LENGTH_OF_LIST_SUBSCRIBER_IDS; i++) { if (cancelCampaignSend) { // Break out of loop if the user cancelled this campaign send break; } // 1. Get the getAmazonEmailArray let currentBlockOfEmails = arrayOfIds[i]; let amazonEmailArray = await getAmazonEmailArray(currentBlockOfEmails, campaignInfo, whiteLabelUrl); let LENGTH_OF_AMAZON_EMAIL_ARRAY = amazonEmailArray.length; for (let x = 0; x < LENGTH_OF_AMAZON_EMAIL_ARRAY; x++) { // 2. Add the email to the send queue. Continue when the queue tells us that it has space for our next email. await addToQueue(amazonEmailArray[x], campaignInfo); } notificationSentEmails(); } /** * @description The campaign has now been sent or cancelled. We can do some final work then continue the parent generator */ redis.subscriber.unsubscribe('stop-campaign-sending'); finishCampaignSend(cancelCampaignSend, campaignInfo); // Change the campaign status. Users cannot resend the campaign after this. sendCampaignSuccessEmail(campaignInfo, startTime, ses); // Send an email to the campaign owner notifying them that this finished. const outcome = cancelCampaignSend ? 'cancelled' : 'success'; sendFinalNotification(outcome, campaignInfo, io, req); const didExperienceError = cancelCampaignSend ? 'cancelled' : null; generator.next(didExperienceError); };
@description Starts the process of sending emails
module.exports ( generator , redis , campaignAndListInfo , amazonAccountInfo , io , req )
javascript
freeCodeCamp/mail-for-good
server/controllers/campaign/email/amazon-ses/index.js
https://github.com/freeCodeCamp/mail-for-good/blob/master/server/controllers/campaign/email/amazon-ses/index.js
BSD-3-Clause
module.exports = (outcome, campaignInfo, io, req) => { if (outcome == 'success') { const notification = { message: `Campaign "${campaignInfo.name}" has been sent`, icon: 'fa-envelope', iconColour: 'text-green', }; sendSingleNotification(io, req, notification); } };
@description Send a final notification to the user informing them of the campaign's success @param {string} outcome - The outcome of the email send @param {object} campaignInfo - Information about this campaign @param {object} io - Configured Redis instance @param {object} req - The express request
module.exports
javascript
freeCodeCamp/mail-for-good
server/controllers/campaign/email/amazon-ses/notifications/sendFinalNotification.js
https://github.com/freeCodeCamp/mail-for-good/blob/master/server/controllers/campaign/email/amazon-ses/notifications/sendFinalNotification.js
BSD-3-Clause
module.exports = (length, array) => { if (length <= 0) { return array; } if (length > array.length) { return [array]; } let tempArray = []; const newArray = []; array.forEach((item, index) => { tempArray.push(item); if ((index + 1) % length === 0) { newArray.push(tempArray); tempArray = []; } else if (index === array.length - 1) { newArray.push(tempArray); } }); return newArray; };
@description Converts an array into a nested array where nested array are of the {length} parameter @param {number} length - The length of each nested array @param {array} array - The array to act on @return {array} Nested array @example nestArray(2, [1,2,3,4,5,6,7]) returns [[1,2], [3, 4], [5, 6], [7]]
module.exports
javascript
freeCodeCamp/mail-for-good
server/controllers/campaign/email/amazon-ses/lib/nest-array.js
https://github.com/freeCodeCamp/mail-for-good/blob/master/server/controllers/campaign/email/amazon-ses/lib/nest-array.js
BSD-3-Clause
module.exports = (task, campaignInfo) => { // Ref https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#sendEmail-property const email = { Source: `"${campaignInfo.fromName}" <${campaignInfo.fromEmail}>`, // From email Destination: { // To email ToAddresses: [`<${task.email}>`] // Set name as follows https://docs.aws.amazon.com/ses/latest/DeveloperGuide/email-format.html }, Message: { Body: {}, Subject: { // Subject Data: campaignInfo.emailSubject } } }; if (campaignInfo.type === 'Plaintext') { // Send as plaintext if plaintext, else send as HTML (no other format concerns us) Object.assign(email.Message.Body, { Text: { Data: campaignInfo.emailBody } }); } else { Object.assign(email.Message.Body, { Html: { Data: campaignInfo.emailBody } }); } return { email, task }; };
@description Create an Amazon email based on the SES spec @param {object} task - The email to create @param {object} campaignInfo - Information about this campaign @return {object} Formatted email object
module.exports
javascript
freeCodeCamp/mail-for-good
server/controllers/campaign/email/amazon-ses/lib/amazon.js
https://github.com/freeCodeCamp/mail-for-good/blob/master/server/controllers/campaign/email/amazon-ses/lib/amazon.js
BSD-3-Clause
const arrayCampaignAnalyticsLinks = subscribers.map(subscriber => { return { trackingId: campaignInfo.trackingId, campaignanalyticId: campaignInfo.campaignAnalyticsId, listsubscriberId: subscriber.id, }; });
@description Save a new CampaignAnalyticsLink and CampaignAnalyticsOpen for these subscribers At the end of this, we'll have links[array] and opens[array]
(anonymous)
javascript
freeCodeCamp/mail-for-good
server/controllers/campaign/email/amazon-ses/controllers/getAmazonEmailArray.js
https://github.com/freeCodeCamp/mail-for-good/blob/master/server/controllers/campaign/email/amazon-ses/controllers/getAmazonEmailArray.js
BSD-3-Clause
module.exports = async function (arrayOfIds, campaignInfo, whiteLabelUrl) { const arrayCampaignInfo = arrayOfIds.map(() => Object.assign({}, campaignInfo)); /** * @description Get the list subscriber and join their campaign subscriber information. */ // Get the listsubscriber & join campaignsubscriber const subscribers = await db.listsubscriber.findAll({ where: { id: { in: arrayOfIds }, subscribed: true }, include: [ { model: db.campaignsubscriber, required: true, where: { campaignId: campaignInfo.campaignId } } ], raw: true }); /** * @description Save a new CampaignAnalyticsLink and CampaignAnalyticsOpen for these subscribers * At the end of this, we'll have links[array] and opens[array] */ const arrayCampaignAnalyticsLinks = subscribers.map(subscriber => { return { trackingId: campaignInfo.trackingId, campaignanalyticId: campaignInfo.campaignAnalyticsId, listsubscriberId: subscriber.id, }; }); const caLinks = await CampaignAnalyticsLink.bulkCreate(arrayCampaignAnalyticsLinks); const links = caLinks.map(x => x.get()); const arrayCampaignAnalyticsOpens = subscribers.map(subscriber => { return { campaignanalyticId: campaignInfo.campaignAnalyticsId, listsubscriberId: subscriber.id, }; }); const caOpens = await CampaignAnalyticsOpen.bulkCreate(arrayCampaignAnalyticsOpens); const opens = caOpens.map(x => x.get()); /** * @description Configure the email body based on options enabled for this campaign send. */ // Iterate through both links and opens - adding things where necessary const arrayAmazonEmails = []; for (let i = 0; i < arrayOfIds.length; i++) { // If this campaign has enabled the unsubscribe link, inject it into configuredCampaignInfo if (arrayCampaignInfo[i].unsubscribeLinkEnabled) { arrayCampaignInfo[i].emailBody = insertUnsubscribeLink(arrayCampaignInfo[i].emailBody, subscribers[i].unsubscribeKey, arrayCampaignInfo[i].type, whiteLabelUrl); } // Replace any {{variables}} with data from campaignInfo arrayCampaignInfo[i].emailBody = mailMerge(subscribers[i], arrayCampaignInfo[i]); // If this campaign has enabled tracking links, wrap the links if (arrayCampaignInfo[i].trackLinksEnabled) { arrayCampaignInfo[i].emailBody = wrapLink(arrayCampaignInfo[i].emailBody, links[i].trackingId, arrayCampaignInfo[i].type, whiteLabelUrl); } // If this campaign has enabled the tracking pixel, insert it into the email bdoy if (arrayCampaignInfo[i].trackingPixelEnabled) { arrayCampaignInfo[i].emailBody = insertTrackingPixel(arrayCampaignInfo[i].emailBody, opens[i].trackingId, arrayCampaignInfo[i].type, whiteLabelUrl); } arrayAmazonEmails.push(AmazonEmail(subscribers[i], arrayCampaignInfo[i])); } /** * @description At this stage we've configued the campaignInfo for this email. Now we'll * return the configured email specific to Amazon's SES. This is ready to send using SES. */ return arrayAmazonEmails; };
@description Get a formatted amazonEmail @param {array} arrayOfIds - Array of list subscriber ids pointing to the person we're emailing @param {object} campaignInfo - Information about this campaign @return {array} array of amazonEmail - an email configured to be sent via Amazon's SES SDK (apiVersion: 2010-12-01) @example return object in array: { email: { Source: '"John Doe" <[email protected]>', Destination: { ToAddresses: [Object] }, Message: { Body: [Object], Subject: [Object] } }, task: { id: 1082649, email: '[email protected]', subscribed: true, unsubscribeKey: 'cd8b16c0-70c7-4850-a00c-20737ce0837f', mostRecentStatus: 'unconfirmed', additionalData: { email: '[email protected]' }, createdAt: 2017-03-04T21:30:16.323Z, updatedAt: 2017-03-04T21:30:16.323Z, listId: 5, campaignsubscribers: [ [Object], [Object], [Object] ] } }
module.exports ( arrayOfIds , campaignInfo , whiteLabelUrl )
javascript
freeCodeCamp/mail-for-good
server/controllers/campaign/email/amazon-ses/controllers/getAmazonEmailArray.js
https://github.com/freeCodeCamp/mail-for-good/blob/master/server/controllers/campaign/email/amazon-ses/controllers/getAmazonEmailArray.js
BSD-3-Clause
module.exports = (campaignInfo) => { function updateCampaignStatus() { db.campaign.update({ status: 'sending' }, { where: { id: campaignInfo.campaignId } }).catch(err => {throw err;}); } return updateCampaignStatus(); };
@description Update the campaign status to 'sending' @param {object} campaignInfo - Information about this campaign
module.exports
javascript
freeCodeCamp/mail-for-good
server/controllers/campaign/email/amazon-ses/controllers/updateCampaignStatus.js
https://github.com/freeCodeCamp/mail-for-good/blob/master/server/controllers/campaign/email/amazon-ses/controllers/updateCampaignStatus.js
BSD-3-Clause
module.exports = (cancelCampaignSend, campaignInfo) => { const status = cancelCampaignSend ? 'interrupted' : 'done'; db.campaign.update({ status }, { where: { id: campaignInfo.campaignId } }); };
@description Change the campaign status on finishing a campaign send @param {boolean} cancelCampaignSend - Flag for whether or not this campaign was cancelled @param {object} campaignInfo - Information about this campaign
module.exports
javascript
freeCodeCamp/mail-for-good
server/controllers/campaign/email/amazon-ses/controllers/finishCampaignSend.js
https://github.com/freeCodeCamp/mail-for-good/blob/master/server/controllers/campaign/email/amazon-ses/controllers/finishCampaignSend.js
BSD-3-Clause
module.exports = (campaignInfo) => { function getListSubscriberIds() { return db.listsubscriber.findAll({ where: { listId: campaignInfo.listId, subscribed: true }, include: [{ model: db.campaignsubscriber, where: { campaignId: campaignInfo.campaignId, sent: false } }], attributes: [ 'id' ], raw: true }) .then(instances => { const plainArrayOfIdNumbers = instances.map(x => x.id); return plainArrayOfIdNumbers; }) .catch(err => { // This should never happen - so we can throw an error here if it does. throw new Error('Error getting list subscribers ids in getArrayOfEmailIds - ', err); }); } return getListSubscriberIds(); };
@description Get all the 'listsubscriber' ids we will email @param {object} campaignInfo - Information about this campaign @return {array} Plain array of unique listsubscriber ids {number}, we will email these users.
module.exports
javascript
freeCodeCamp/mail-for-good
server/controllers/campaign/email/amazon-ses/controllers/getArrayOfEmailIds.js
https://github.com/freeCodeCamp/mail-for-good/blob/master/server/controllers/campaign/email/amazon-ses/controllers/getArrayOfEmailIds.js
BSD-3-Clause
function _updateAnalytics(data, task, campaignInfo) { const p1 = CampaignSubscriber.update( { messageId: data.MessageId, sent: true }, { where: { id: task['campaignsubscribers.id'], listsubscriberId: task.id, campaignId: campaignInfo.campaignId }, limit: 1 } ); const p2 = CampaignAnalytics.findById(campaignInfo.campaignAnalyticsId) .then(foundCampaignAnalytics => { return foundCampaignAnalytics.increment('totalSentCount'); }); return Promise.all([p1, p2]); }
@private @description Update the database's analytics tracking for this email @param {object} data - the response from SES @param {object} task - the listsubcriber + campaignsubcriber info @param {object} campaignInfo - Information about this campaign @return {Promise} a promise that resolves when the tracking info has been saved
_updateAnalytics ( data , task , campaignInfo )
javascript
freeCodeCamp/mail-for-good
server/controllers/campaign/email/amazon-ses/queue/sendEmail.js
https://github.com/freeCodeCamp/mail-for-good/blob/master/server/controllers/campaign/email/amazon-ses/queue/sendEmail.js
BSD-3-Clause
module.exports = function(amazonEmail, campaignInfo, ses) { const { email, task } = amazonEmail; const promisifiedSes = Promise.promisify(ses.sendEmail, { context: ses }); /** * @private * @description Update the database's analytics tracking for this email * @param {object} data - the response from SES * @param {object} task - the listsubcriber + campaignsubcriber info * @param {object} campaignInfo - Information about this campaign * @return {Promise} a promise that resolves when the tracking info has been saved */ function _updateAnalytics(data, task, campaignInfo) { const p1 = CampaignSubscriber.update( { messageId: data.MessageId, sent: true }, { where: { id: task['campaignsubscribers.id'], listsubscriberId: task.id, campaignId: campaignInfo.campaignId }, limit: 1 } ); const p2 = CampaignAnalytics.findById(campaignInfo.campaignAnalyticsId) .then(foundCampaignAnalytics => { return foundCampaignAnalytics.increment('totalSentCount'); }); return Promise.all([p1, p2]); } /** * @description Send an email via Amazon SES * @param {object} email - configured amazon email to send * @return {Promise} a promise that resolves when the tracking info has been saved */ return promisifiedSes(email) .then(data => { return _updateAnalytics(data, task, campaignInfo); }) .catch(err => { console.log(err); return; }); };
@description Add an email to the queue. @param {object} email - configured email to send @param {object} campaignInfo - Information about this campaign @param {object} ses - Configured Amazon SES instance used to send this email @return {function} A function to call to add an item to the queue. Check the usage of this below.
module.exports ( amazonEmail , campaignInfo , ses )
javascript
freeCodeCamp/mail-for-good
server/controllers/campaign/email/amazon-ses/queue/sendEmail.js
https://github.com/freeCodeCamp/mail-for-good/blob/master/server/controllers/campaign/email/amazon-ses/queue/sendEmail.js
BSD-3-Clause
function HelloWorld(props){ return ( /** * ✏️ * Instead of returning null you would need to return a React element * Unlike earlier exercise where you returned React.createElement * here you should use JSX to return a div with 'Hello World' */ null ); }
🏆 The goal here is just to say Hello World. It is similar to previous exercise we did except instead of using React.createElement function we want to use JSX
HelloWorld ( props )
javascript
tyroprogrammer/learn-react-app
src/exercise/02-IntroToJSX.js
https://github.com/tyroprogrammer/learn-react-app/blob/master/src/exercise/02-IntroToJSX.js
MIT
const Usage = (props) => { return <HelloWorld /> }
🚨 🚨 DO NOT DELETE OR CHANGE THIS.🚨 🚨 This is how you would use your above component and the output of this code is displayed on the browser
Usage
javascript
tyroprogrammer/learn-react-app
src/exercise/02-IntroToJSX.js
https://github.com/tyroprogrammer/learn-react-app/blob/master/src/exercise/02-IntroToJSX.js
MIT
increment(){ /** * ✏️ * You need to call setState here to update the `counter` state * When user clicks the "+" we need to add 1 to the current state and * set the state with the new value. * We need to use value of current state to derive the new state, * so it's better to use the updater function like * this.setState(function(currentState) { * return newState * }); */ }
💡 This method will be called when the user clicks "+" button to increase the counter
increment ( )
javascript
tyroprogrammer/learn-react-app
src/exercise/05-State.js
https://github.com/tyroprogrammer/learn-react-app/blob/master/src/exercise/05-State.js
MIT
decrement(){ /** * ✏️ * You need to call setState here to update the `counter` state * When user clicks the "-" we need to subtract 1 to the current state and * set the state with the new value. * We need to use value of current state to derive the new state, * so it's better for us to use the updater function like * this.setState(function(currentState) { * return newState * }); */ }
💡 This method will be called when the user clicks "-" button to decrease the counter
decrement ( )
javascript
tyroprogrammer/learn-react-app
src/exercise/05-State.js
https://github.com/tyroprogrammer/learn-react-app/blob/master/src/exercise/05-State.js
MIT
componentDidMount() { }
✏️ We need to use componentDidMount lifecycle method to fetch company profile information for given stock ticker using the DataAPI provided 🧭 Add lifecycle method called componentDidMount 🧭 Inside that method you need to use the DataAPI that's already imported. Make a call to `getCompanyProfile()` method and pass the `stockTicker` from the props. This method will return a promise that resolves into `companyProfile` info 🧭 Using the data from the promise use `setState` to set companyProfileInfo like - `this.setState({ companyProfileInfo: data })` 🧭 What if the promise resolves into an error? You might want to catch the error and do something with it (Remember .catch in Promise). For example below I'm catching an error and just logging it in console. You can do the same for the sake of this exercise: Api.getData() .then(data => doSth(data)) .catch(error => console.log(error)) *
componentDidMount ( )
javascript
tyroprogrammer/learn-react-app
src/exercise/06-LifecycleMethods.js
https://github.com/tyroprogrammer/learn-react-app/blob/master/src/exercise/06-LifecycleMethods.js
MIT
function CompanyProfile(props) { /** * 💡 some variables to store mock data * We will use these data to display the company profile information */ const stockTicker = 'AAPL'; const companyProfileInfo = { 'Company Name': 'Apple Inc.', 'Price': 150, 'Exchange': "Nasdaq Global Select", 'Industry': "Computer Hardware", 'CEO': 'Timothy D. Cook' } return ( <div> <div>Profile of: {/**✏️ display stock ticker here*/}</div> <hr/> <div> { /** * ✏️ * This block is surrounded by curly braces {} so * we can really execute any Javascript stuff here. * * Loop through the keys of companyProfileInfo * object to render one div per key/value pair. The div should * render key followed by a colon followed by value. * * 🧭 Object.keys(obj) can be used to loop through the object * eg: * const obj = { 'key1': 'value1', 'key2': 'value2'}; * Object.keys(obj) will return ['key1', 'key2'] * 🧭 You can use Array.map() to map any key to a div element * eg: * ['a', 'b', 'c'].map(d => <div>{d}</div>) * 🧭 Remember to use curly braces inside the div to render * any text content you want */ } </div> </div> ); }
🏆 The goal here is to get you more familiar with JSX. You will use javascript code inside JSX to loop through object keys and render a div element for each element in that object
CompanyProfile ( props )
javascript
tyroprogrammer/learn-react-app
src/exercise/03-PowerOfJSX.js
https://github.com/tyroprogrammer/learn-react-app/blob/master/src/exercise/03-PowerOfJSX.js
MIT
function HelloWorld(props) { return ( /** * ✏️ * Instead of returning null you would need to return a React element * Use the React.createElement function to display a div * and Hello World text inside the div */ null ); }
🏆 The goal here is just to say Hello World. Follow the instruction inside return statement
HelloWorld ( props )
javascript
tyroprogrammer/learn-react-app
src/exercise/01-HelloWorld.js
https://github.com/tyroprogrammer/learn-react-app/blob/master/src/exercise/01-HelloWorld.js
MIT
handleChange(e) { }
✏️ Need to get the value of the input and set it to the state 🧭 Get the value of the input from the synthetic event You can get the value by using event.target.value. 🧭 Set the value to the state `inputValue` by calling `setState`
handleChange ( e )
javascript
tyroprogrammer/learn-react-app
src/exercise/07-HandlingEvents.js
https://github.com/tyroprogrammer/learn-react-app/blob/master/src/exercise/07-HandlingEvents.js
MIT
const Usage = (props) => { return <FancyInput /> }
🚨 🚨 DO NOT DELETE OR CHANGE THIS.🚨 🚨 This is how you would use your above component The output of this code is displayed on the browser on the left hand side
Usage
javascript
tyroprogrammer/learn-react-app
src/exercise/07-HandlingEvents.js
https://github.com/tyroprogrammer/learn-react-app/blob/master/src/exercise/07-HandlingEvents.js
MIT
function template(string, ...args) { if (args.length === 1 && typeof args[0] === 'object') { args = args[0] } if (!args || !args.hasOwnProperty) { args = {} } return string.replace(RE_NARGS, (match, prefix, i, index) => { let result if (string[index - 1] === '{' && string[index + match.length] === '}') { return i } else { result = hasOwn(args, i) ? args[i] : null if (result === null || result === undefined) { return '' } return result } }) }
template @param {String} string @param {Array} ...args @return {String}
template ( string , ... args )
javascript
hug-sun/element3
packages/website/src/locale/format.js
https://github.com/hug-sun/element3/blob/master/packages/website/src/locale/format.js
MIT
export default function () { /** * template * * @param {String} string * @param {Array} ...args * @return {String} */ function template(string, ...args) { if (args.length === 1 && typeof args[0] === 'object') { args = args[0] } if (!args || !args.hasOwnProperty) { args = {} } return string.replace(RE_NARGS, (match, prefix, i, index) => { let result if (string[index - 1] === '{' && string[index + match.length] === '}') { return i } else { result = hasOwn(args, i) ? args[i] : null if (result === null || result === undefined) { return '' } return result } }) } return template }
String format template - Inspired: https://github.com/Matt-Esch/string-template/index.js
(anonymous) ( )
javascript
hug-sun/element3
packages/website/src/locale/format.js
https://github.com/hug-sun/element3/blob/master/packages/website/src/locale/format.js
MIT
constructor(list, defaultNodeKey = {}, defaultNodeValue = {}) { this.isUpdateRaw = true this.raw = list this.injectAction = createAction(this) // The core method is injected with interceptor functions, the insert RowNode is automatically converted to TreeNode this.root = new TreeNode( Date.now(), 'root', [], defaultNodeValue, this.injectAction ) this.defaultNodeKey = Object.assign( { id: 'id', label: 'label', childNodes: 'childNodes', isDisabled: 'isDisabled', isAsync: 'isAsync', isChecked: 'isChecked', isVisable: 'isVisable', isExpanded: 'isExpanded' }, defaultNodeKey ) this.defaultNodeValue = Object.assign({}, defaultNodeValue) // this.checked = [] // this.expanded = [] this.initRoot() }
@param {object[]} list @param {object} defaultNodeKey The incoming Node proprtry name maps to the default name
constructor ( list , defaultNodeKey = { } , defaultNodeValue = { } )
javascript
hug-sun/element3
packages/element3/packages/tree/entity/Tree.js
https://github.com/hug-sun/element3/blob/master/packages/element3/packages/tree/entity/Tree.js
MIT
depthEach(upToDownCallBack = () => false, downToUpCallBack = () => false) {
from current node start, down each @param {Function} callback( node:TreeNode, parentNode:TreeNode, deep: number) if returns true then stop each, else not stop
downToUpCallBack
javascript
hug-sun/element3
packages/element3/packages/tree/entity/TreeNode.js
https://github.com/hug-sun/element3/blob/master/packages/element3/packages/tree/entity/TreeNode.js
MIT
export function transitionObjectKey(obj, keyMap = {}) { const transitionKeyList = Object.keys(keyMap) transitionKeyList.forEach((key) => { if (key !== keyMap[key]) { obj[key] = obj[keyMap[key]] delete obj[keyMap[key]] } }) return obj }
Modify the property name of the object @param {object} obj @param {object} keyMap newKey mapping oldKey
transitionObjectKey ( obj , keyMap = { } )
javascript
hug-sun/element3
packages/element3/packages/tree/libs/util.js
https://github.com/hug-sun/element3/blob/master/packages/element3/packages/tree/libs/util.js
MIT
function isChildComponent(componentChild, componentParent) { const parentUId = componentParent.uid while (componentChild && componentChild?.parent?.uid !== parentUId) { componentChild = componentChild.parent } return Boolean(componentChild) }
check componentChild is componentParent child components @param {*} componentChild @param {*} componentParent
isChildComponent ( componentChild , componentParent )
javascript
hug-sun/element3
packages/element3/src/composables/emitter.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/composables/emitter.js
MIT
export function useGlobalOptions() { const instance = getCurrentInstance() if (!instance) { console.warn('useGlobalOptions must be call in setup function') return } return instance.appContext.config.globalProperties.$ELEMENT || {} }
get globalOptions $ELEMENT config object
useGlobalOptions ( )
javascript
hug-sun/element3
packages/element3/src/composables/globalConfig.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/composables/globalConfig.js
MIT
export function createComponent(Component, props, children) { const vnode = h(Component, { ...props, ref: MOUNT_COMPONENT_REF }, children) const container = document.createElement('div') vnode[COMPONENT_CONTAINER_SYMBOL] = container render(vnode, container) return vnode.component }
创建组件实例对象 返回的实例和调用 getCurrentComponent() 返回的一致 @param {*} Component
createComponent ( Component , props , children )
javascript
hug-sun/element3
packages/element3/src/composables/component.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/composables/component.js
MIT
export function unmountComponent(ComponnetInstance) { render(undefined, ComponnetInstance.vnode[COMPONENT_CONTAINER_SYMBOL]) }
销毁组件实例对象 @param {*} ComponnetInstance 通过createComponent方法得到的组件实例对象
unmountComponent ( ComponnetInstance )
javascript
hug-sun/element3
packages/element3/src/composables/component.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/composables/component.js
MIT
export default function (instance, callback, speed = 300, once = false) { if (!instance || !callback) { throw new Error('instance & callback is required') } let called = false const afterLeaveCallback = function () { if (called) { return } called = true if (callback) { callback.apply(null, arguments) } } const emitters = useEmitter(instance.$) if (once) { emitters.once('after-leave', afterLeaveCallback) } else { emitters.on('after-leave', afterLeaveCallback) } setTimeout(() => { afterLeaveCallback() }, speed + 100) }
Bind after-leave event for vue instance. Make sure after-leave is called in any browsers. @param {Vue} instance Vue instance. @param {Function} callback callback of after-leave event @param {Number} speed the speed of transition, default value is 300ms @param {Boolean} once weather bind after-leave once. default value is false.
(anonymous) ( instance , callback , speed = 300 , once = false )
javascript
hug-sun/element3
packages/element3/src/utils/after-leave.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/after-leave.js
MIT
Popper.prototype.destroy = function () { this._popper.removeAttribute('x-placement') this._popper.style.left = '' this._popper.style.position = '' this._popper.style.top = '' this._popper.style[getSupportedPropertyName('transform')] = '' this._removeEventListeners() // remove the popper if user explicity asked for the deletion on destroy if (this._options.removeOnDestroy) { this._popper.remove() } return this }
Destroy the popper @method @memberof Popper
Popper.prototype.destroy ( )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
Popper.prototype.update = function () { var data = { instance: this, styles: {} } // store placement inside the data object, modifiers will be able to edit `placement` if needed // and refer to _originalPlacement to know the original value data.placement = this._options.placement data._originalPlacement = this._options.placement // compute the popper and reference offsets and put them inside data.offsets data.offsets = this._getOffsets(this._popper, this._reference, data.placement) // get boundaries data.boundaries = this._getBoundaries( data, this._options.boundariesPadding, this._options.boundariesElement ) data = this.runModifiers(data, this._options.modifiers) if (typeof this.state.updateCallback === 'function') { this.state.updateCallback(data) } }
Updates the position of the popper, computing the new offsets and applying the new style @method @memberof Popper
Popper.prototype.update ( )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
Popper.prototype.onCreate = function (callback) { // the createCallbacks return as first argument the popper instance callback(this) return this }
If a function is passed, it will be executed after the initialization of popper with as first argument the Popper instance. @method @memberof Popper @param {Function} callback
Popper.prototype.onCreate ( callback )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
Popper.prototype.onUpdate = function (callback) { this.state.updateCallback = callback return this }
If a function is passed, it will be executed after each update of popper with as first argument the set of coordinates and informations used to style popper and its arrow. NOTE: it doesn't get fired on the first call of the `Popper.update()` method inside the `Popper` constructor! @method @memberof Popper @param {Function} callback
Popper.prototype.onUpdate ( callback )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
function addClassNames(element, classNames) { classNames.forEach(function (className) { element.classList.add(className) }) }
Adds class names to the given element @function @ignore @param {HTMLElement} target @param {Array} classes
addClassNames ( element , classNames )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
function addAttributes(element, attributes) { attributes.forEach(function (attribute) { element.setAttribute( attribute.split(':')[0], attribute.split(':')[1] || '' ) }) }
Adds attributes to the given element @function @ignore @param {HTMLElement} target @param {Array} attributes @example addAttributes(element, [ 'data-info:foobar' ]);
addAttributes ( element , attributes )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
Popper.prototype._getOffsets = function (popper, reference, placement) { placement = placement.split('-')[0] var popperOffsets = {} popperOffsets.position = this.state.position var isParentFixed = popperOffsets.position === 'fixed' // // Get reference element position // var referenceOffsets = getOffsetRectRelativeToCustomParent( reference, getOffsetParent(popper), isParentFixed ) // // Get popper sizes // var popperRect = getOuterSizes(popper) // // Compute offsets of popper // // depending by the popper placement we have to compute its offsets slightly differently if (['right', 'left'].indexOf(placement) !== -1) { popperOffsets.top = referenceOffsets.top + referenceOffsets.height / 2 - popperRect.height / 2 if (placement === 'left') { popperOffsets.left = referenceOffsets.left - popperRect.width } else { popperOffsets.left = referenceOffsets.right } } else { popperOffsets.left = referenceOffsets.left + referenceOffsets.width / 2 - popperRect.width / 2 if (placement === 'top') { popperOffsets.top = referenceOffsets.top - popperRect.height } else { popperOffsets.top = referenceOffsets.bottom } } // Add width and height to our offsets object popperOffsets.width = popperRect.width popperOffsets.height = popperRect.height return { popper: popperOffsets, reference: referenceOffsets } }
Get offsets to the popper @method @memberof Popper @access private @param {Element} popper - the popper element @param {Element} reference - the reference element (the popper will be relative to this) @returns {Object} An object containing the offsets which will be applied to the popper
'fixed' ( popper , reference , placement )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
Popper.prototype._setupEventListeners = function () { // NOTE: 1 DOM access here this.state.updateBound = this.update.bind(this) root.addEventListener('resize', this.state.updateBound) // if the boundariesElement is window we don't need to listen for the scroll event if (this._options.boundariesElement !== 'window') { var target = getScrollParent(this._reference) // here it could be both `body` or `documentElement` thanks to Firefox, we then check both if ( target === root.document.body || target === root.document.documentElement ) { target = root } target.addEventListener('scroll', this.state.updateBound) this.state.scrollTarget = target } }
Setup needed event listeners used to update the popper position @method @memberof Popper @access private
Popper.prototype._setupEventListeners ( )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
Popper.prototype._removeEventListeners = function () { // NOTE: 1 DOM access here root.removeEventListener('resize', this.state.updateBound) if (this._options.boundariesElement !== 'window' && this.state.scrollTarget) { this.state.scrollTarget.removeEventListener( 'scroll', this.state.updateBound ) this.state.scrollTarget = null } this.state.updateBound = null }
Remove event listeners used to update the popper position @method @memberof Popper @access private
Popper.prototype._removeEventListeners ( )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
Popper.prototype.runModifiers = function (data, modifiers, ends) { var modifiersToRun = modifiers.slice() if (ends !== undefined) { modifiersToRun = this._options.modifiers.slice( 0, getArrayKeyIndex(this._options.modifiers, ends) ) } modifiersToRun.forEach( function (modifier) { if (isFunction(modifier)) { data = modifier.call(this, data) } }.bind(this) ) return data }
Loop trough the list of modifiers and run them in order, each of them will then edit the data object @method @memberof Popper @access public @param {Object} data @param {Array} modifiers @param {Function} ends
Popper.prototype.runModifiers ( data , modifiers , ends )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
Popper.prototype.isModifierRequired = function (requesting, requested) { var index = getArrayKeyIndex(this._options.modifiers, requesting) return !!this._options.modifiers.slice(0, index).filter(function (modifier) { return modifier === requested }).length }
Helper used to know if the given modifier depends from another one. @method @memberof Popper @param {String} requesting - name of requesting modifier @param {String} requested - name of requested modifier @returns {Boolean}
Popper.prototype.isModifierRequired ( requesting , requested )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
Popper.prototype.modifiers.applyStyle = function (data) { // apply the final offsets to the popper // NOTE: 1 DOM access here var styles = { position: data.offsets.popper.position } // round top and left to avoid blurry text var left = Math.round(data.offsets.popper.left) var top = Math.round(data.offsets.popper.top) // if gpuAcceleration is set to true and transform is supported, we use `translate3d` to apply the position to the popper // we automatically use the supported prefixed version if needed var prefixedProperty if ( this._options.gpuAcceleration && (prefixedProperty = getSupportedPropertyName('transform')) ) { styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)' styles.top = 0 styles.left = 0 } // othwerise, we use the standard `left` and `top` properties else { styles.left = left styles.top = top } // any property present in `data.styles` will be applied to the popper, // in this way we can make the 3rd party modifiers add custom styles to it // Be aware, modifiers could override the properties defined in the previous // lines of this modifier! Object.assign(styles, data.styles) setStyle(this._popper, styles) // set an attribute which will be useful to style the tooltip (use it to properly position its arrow) // NOTE: 1 DOM access here this._popper.setAttribute('x-placement', data.placement) // if the arrow modifier is required and the arrow style has been computed, apply the arrow style if ( this.isModifierRequired(this.modifiers.applyStyle, this.modifiers.arrow) && data.offsets.arrow ) { setStyle(data.arrowElement, data.offsets.arrow) } return data }
Apply the computed styles to the popper element @method @memberof Popper.modifiers @argument {Object} data - The data object generated by `update` method @returns {Object} The same data object
Popper.prototype.modifiers.applyStyle ( data )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
Popper.prototype.modifiers.shift = function (data) { var placement = data.placement var basePlacement = placement.split('-')[0] var shiftVariation = placement.split('-')[1] // if shift shiftVariation is specified, run the modifier if (shiftVariation) { var reference = data.offsets.reference var popper = getPopperClientRect(data.offsets.popper) var shiftOffsets = { y: { start: { top: reference.top }, end: { top: reference.top + reference.height - popper.height } }, x: { start: { left: reference.left }, end: { left: reference.left + reference.width - popper.width } } } var axis = ['bottom', 'top'].indexOf(basePlacement) !== -1 ? 'x' : 'y' data.offsets.popper = Object.assign( popper, shiftOffsets[axis][shiftVariation] ) } return data }
Modifier used to shift the popper on the start or end of its reference element side @method @memberof Popper.modifiers @argument {Object} data - The data object generated by `update` method @returns {Object} The data object, properly modified
Popper.prototype.modifiers.shift ( data )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
Popper.prototype.modifiers.preventOverflow = function (data) { var order = this._options.preventOverflowOrder var popper = getPopperClientRect(data.offsets.popper) var check = { left: function () { var left = popper.left if (popper.left < data.boundaries.left) { left = Math.max(popper.left, data.boundaries.left) } return { left: left } }, right: function () { var left = popper.left if (popper.right > data.boundaries.right) { left = Math.min(popper.left, data.boundaries.right - popper.width) } return { left: left } }, top: function () { var top = popper.top if (popper.top < data.boundaries.top) { top = Math.max(popper.top, data.boundaries.top) } return { top: top } }, bottom: function () { var top = popper.top if (popper.bottom > data.boundaries.bottom) { top = Math.min(popper.top, data.boundaries.bottom - popper.height) } return { top: top } } } order.forEach(function (direction) { data.offsets.popper = Object.assign(popper, check[direction]()) }) return data }
Modifier used to make sure the popper does not overflows from it's boundaries @method @memberof Popper.modifiers @argument {Object} data - The data object generated by `update` method @returns {Object} The data object, properly modified
Popper.prototype.modifiers.preventOverflow ( data )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
Popper.prototype.modifiers.keepTogether = function (data) { var popper = getPopperClientRect(data.offsets.popper) var reference = data.offsets.reference var f = Math.floor if (popper.right < f(reference.left)) { data.offsets.popper.left = f(reference.left) - popper.width } if (popper.left > f(reference.right)) { data.offsets.popper.left = f(reference.right) } if (popper.bottom < f(reference.top)) { data.offsets.popper.top = f(reference.top) - popper.height } if (popper.top > f(reference.bottom)) { data.offsets.popper.top = f(reference.bottom) } return data }
Modifier used to make sure the popper is always near its reference @method @memberof Popper.modifiers @argument {Object} data - The data object generated by _update method @returns {Object} The data object, properly modified
Popper.prototype.modifiers.keepTogether ( data )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
Popper.prototype.modifiers.flip = function (data) { // check if preventOverflow is in the list of modifiers before the flip modifier. // otherwise flip would not work as expected. if ( !this.isModifierRequired( this.modifiers.flip, this.modifiers.preventOverflow ) ) { console.warn( 'WARNING: preventOverflow modifier is required by flip modifier in order to work, be sure to include it before flip!' ) return data } if (data.flipped && data.placement === data._originalPlacement) { // seems like flip is trying to loop, probably there's not enough space on any of the flippable sides return data } var placement = data.placement.split('-')[0] var placementOpposite = getOppositePlacement(placement) var variation = data.placement.split('-')[1] || '' var flipOrder = [] if (this._options.flipBehavior === 'flip') { flipOrder = [placement, placementOpposite] } else { flipOrder = this._options.flipBehavior } flipOrder.forEach( function (step, index) { if (placement !== step || flipOrder.length === index + 1) { return } placement = data.placement.split('-')[0] placementOpposite = getOppositePlacement(placement) var popperOffsets = getPopperClientRect(data.offsets.popper) // this boolean is used to distinguish right and bottom from top and left // they need different computations to get flipped var a = ['right', 'bottom'].indexOf(placement) !== -1 // using Math.floor because the reference offsets may contain decimals we are not going to consider here if ( (a && Math.floor(data.offsets.reference[placement]) > Math.floor(popperOffsets[placementOpposite])) || (!a && Math.floor(data.offsets.reference[placement]) < Math.floor(popperOffsets[placementOpposite])) ) { // we'll use this boolean to detect any flip loop data.flipped = true data.placement = flipOrder[index + 1] if (variation) { data.placement += '-' + variation } data.offsets.popper = this._getOffsets( this._popper, this._reference, data.placement ).popper data = this.runModifiers(data, this._options.modifiers, this._flip) } }.bind(this) ) return data }
Modifier used to flip the placement of the popper when the latter is starting overlapping its reference element. Requires the `preventOverflow` modifier before it in order to work. **NOTE:** This modifier will run all its previous modifiers everytime it tries to flip the popper! @method @memberof Popper.modifiers @argument {Object} data - The data object generated by _update method @returns {Object} The data object, properly modified
Popper.prototype.modifiers.flip ( data )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
Popper.prototype.modifiers.offset = function (data) { var offset = this._options.offset var popper = data.offsets.popper if (data.placement.indexOf('left') !== -1) { popper.top -= offset } else if (data.placement.indexOf('right') !== -1) { popper.top += offset } else if (data.placement.indexOf('top') !== -1) { popper.left -= offset } else if (data.placement.indexOf('bottom') !== -1) { popper.left += offset } return data }
Modifier used to add an offset to the popper, useful if you more granularity positioning your popper. The offsets will shift the popper on the side of its reference element. @method @memberof Popper.modifiers @argument {Object} data - The data object generated by _update method @returns {Object} The data object, properly modified
Popper.prototype.modifiers.offset ( data )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
Popper.prototype.modifiers.arrow = function (data) { var arrow = this._options.arrowElement var arrowOffset = this._options.arrowOffset // if the arrowElement is a string, suppose it's a CSS selector if (typeof arrow === 'string') { arrow = this._popper.querySelector(arrow) } // if arrow element is not found, don't run the modifier if (!arrow) { return data } // the arrow element must be child of its popper if (!this._popper.contains(arrow)) { console.warn('WARNING: `arrowElement` must be child of its popper element!') return data } // arrow depends on keepTogether in order to work if ( !this.isModifierRequired(this.modifiers.arrow, this.modifiers.keepTogether) ) { console.warn( 'WARNING: keepTogether modifier is required by arrow modifier in order to work, be sure to include it before arrow!' ) return data } var arrowStyle = {} var placement = data.placement.split('-')[0] var popper = getPopperClientRect(data.offsets.popper) var reference = data.offsets.reference var isVertical = ['left', 'right'].indexOf(placement) !== -1 var len = isVertical ? 'height' : 'width' var side = isVertical ? 'top' : 'left' var altSide = isVertical ? 'left' : 'top' var opSide = isVertical ? 'bottom' : 'right' var arrowSize = getOuterSizes(arrow)[len] // // extends keepTogether behavior making sure the popper and its reference have enough pixels in conjuction // // top/left side if (reference[opSide] - arrowSize < popper[side]) { data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowSize) } // bottom/right side if (reference[side] + arrowSize > popper[opSide]) { data.offsets.popper[side] += reference[side] + arrowSize - popper[opSide] } // compute center of the popper var center = reference[side] + (arrowOffset || reference[len] / 2 - arrowSize / 2) var sideValue = center - popper[side] // prevent arrow from being placed not contiguously to its popper sideValue = Math.max(Math.min(popper[len] - arrowSize - 8, sideValue), 8) arrowStyle[side] = sideValue arrowStyle[altSide] = '' // make sure to remove any old style from the arrow data.offsets.arrow = arrowStyle data.arrowElement = arrow return data }
Modifier used to move the arrows on the edge of the popper to make sure them are always between the popper and the reference element It will use the CSS outer size of the arrow element to know how many pixels of conjuction are needed @method @memberof Popper.modifiers @argument {Object} data - The data object generated by _update method @returns {Object} The data object, properly modified
Popper.prototype.modifiers.arrow ( data )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
function getOuterSizes(element) { // NOTE: 1 DOM access here var _display = element.style.display, _visibility = element.style.visibility element.style.display = 'block' element.style.visibility = 'hidden' // original method var styles = root.getComputedStyle(element) var x = parseFloat(styles.marginTop) + parseFloat(styles.marginBottom) var y = parseFloat(styles.marginLeft) + parseFloat(styles.marginRight) var result = { width: element.offsetWidth + y, height: element.offsetHeight + x } // reset element styles element.style.display = _display element.style.visibility = _visibility return result }
Get the outer sizes of the given element (offset size + margins) @function @ignore @argument {Element} element @returns {Object} object containing width and height properties
getOuterSizes ( element )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
function getOppositePlacement(placement) { var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' } return placement.replace(/left|right|bottom|top/g, function (matched) { return hash[matched] }) }
Get the opposite placement of the given one/ @function @ignore @argument {String} placement @returns {String} flipped placement
getOppositePlacement ( placement )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
function getPopperClientRect(popperOffsets) { var offsets = Object.assign({}, popperOffsets) offsets.right = offsets.left + offsets.width offsets.bottom = offsets.top + offsets.height return offsets }
Given the popper offsets, generate an output similar to getBoundingClientRect @function @ignore @argument {Object} popperOffsets @returns {Object} ClientRect like output
getPopperClientRect ( popperOffsets )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
function getArrayKeyIndex(arr, keyToFind) { var i = 0, key for (key in arr) { if (arr[key] === keyToFind) { return i } i++ } return null }
Given an array and the key to find, returns its index @function @ignore @argument {Array} arr @argument keyToFind @returns index or null
getArrayKeyIndex ( arr , keyToFind )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
function getStyleComputedProperty(element, property) { // NOTE: 1 DOM access here var css = root.getComputedStyle(element, null) return css[property] }
Get CSS computed property of the given element @function @ignore @argument {Eement} element @argument {String} property
getStyleComputedProperty ( element , property )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
function isFunction(functionToCheck) { var getType = {} return ( functionToCheck && getType.toString.call(functionToCheck) === '[object Function]' ) }
Check if the given variable is a function @function @ignore @argument {*} functionToCheck - variable to check @returns {Boolean} answer to: is a function?
isFunction ( functionToCheck )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
function getOffsetRect(element) { var elementRect = { width: element.offsetWidth, height: element.offsetHeight, left: element.offsetLeft, top: element.offsetTop } elementRect.right = elementRect.left + elementRect.width elementRect.bottom = elementRect.top + elementRect.height // position return elementRect }
Get the position of the given element, relative to its offset parent @function @ignore @param {Element} element @return {Object} position - Coordinates of the element and its `scrollTop`
getOffsetRect ( element )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
function getBoundingClientRect(element) { var rect = element.getBoundingClientRect() // whether the IE version is lower than 11 var isIE = navigator.userAgent.indexOf('MSIE') != -1 // fix ie document bounding top always 0 bug var rectTop = isIE && element.tagName === 'HTML' ? -element.scrollTop : rect.top return { left: rect.left, top: rectTop, right: rect.right, bottom: rect.bottom, width: rect.right - rect.left, height: rect.bottom - rectTop } }
Get bounding client rect of given element @function @ignore @param {HTMLElement} element @return {Object} client rect
getBoundingClientRect ( element )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
function getOffsetRectRelativeToCustomParent(element, parent, fixed) { var elementRect = getBoundingClientRect(element) var parentRect = getBoundingClientRect(parent) if (fixed) { var scrollParent = getScrollParent(parent) parentRect.top += scrollParent.scrollTop parentRect.bottom += scrollParent.scrollTop parentRect.left += scrollParent.scrollLeft parentRect.right += scrollParent.scrollLeft } var rect = { top: elementRect.top - parentRect.top, left: elementRect.left - parentRect.left, bottom: elementRect.top - parentRect.top + elementRect.height, right: elementRect.left - parentRect.left + elementRect.width, width: elementRect.width, height: elementRect.height } return rect }
Given an element and one of its parents, return the offset @function @ignore @param {HTMLElement} element @param {HTMLElement} parent @return {Object} rect
getOffsetRectRelativeToCustomParent ( element , parent , fixed )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
function getSupportedPropertyName(property) { var prefixes = ['', 'ms', 'webkit', 'moz', 'o'] for (var i = 0; i < prefixes.length; i++) { var toCheck = prefixes[i] ? prefixes[i] + property.charAt(0).toUpperCase() + property.slice(1) : property if (typeof root.document.body.style[toCheck] !== 'undefined') { return toCheck } } return null }
Get the prefixed supported property name @function @ignore @argument {String} property (camelCase) @returns {String} prefixed property (camelCase)
getSupportedPropertyName ( property )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
function isFixed(element) { if (element === root.document.body) { return false } if (getStyleComputedProperty(element, 'position') === 'fixed') { return true } return element.parentNode ? isFixed(element.parentNode) : element } /** * Set the style to the given popper * @function * @ignore * @argument {Element} element - Element to apply the style to * @argument {Object} styles - Object with a list of properties and values which will be applied to the element */ function setStyle(element, styles) { function is_numeric(n) { return n !== '' && !isNaN(parseFloat(n)) && isFinite(n) } Object.keys(styles).forEach(function (prop) { var unit = '' // add unit if the value is numeric and is one of the following if ( ['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && is_numeric(styles[prop]) ) { unit = 'px' } element.style[prop] = styles[prop] + unit }) } /** * Check if the given variable is a function * @function * @ignore * @argument {*} functionToCheck - variable to check * @returns {Boolean} answer to: is a function? */ function isFunction(functionToCheck) { var getType = {} return ( functionToCheck && getType.toString.call(functionToCheck) === '[object Function]' ) } /** * Get the position of the given element, relative to its offset parent * @function * @ignore * @param {Element} element * @return {Object} position - Coordinates of the element and its `scrollTop` */ function getOffsetRect(element) { var elementRect = { width: element.offsetWidth, height: element.offsetHeight, left: element.offsetLeft, top: element.offsetTop } elementRect.right = elementRect.left + elementRect.width elementRect.bottom = elementRect.top + elementRect.height // position return elementRect } /** * Get bounding client rect of given element * @function * @ignore * @param {HTMLElement} element * @return {Object} client rect */ function getBoundingClientRect(element) { var rect = element.getBoundingClientRect() // whether the IE version is lower than 11 var isIE = navigator.userAgent.indexOf('MSIE') != -1 // fix ie document bounding top always 0 bug var rectTop = isIE && element.tagName === 'HTML' ? -element.scrollTop : rect.top return { left: rect.left, top: rectTop, right: rect.right, bottom: rect.bottom, width: rect.right - rect.left, height: rect.bottom - rectTop } } /** * Given an element and one of its parents, return the offset * @function * @ignore * @param {HTMLElement} element * @param {HTMLElement} parent * @return {Object} rect */ function getOffsetRectRelativeToCustomParent(element, parent, fixed) { var elementRect = getBoundingClientRect(element) var parentRect = getBoundingClientRect(parent) if (fixed) { var scrollParent = getScrollParent(parent) parentRect.top += scrollParent.scrollTop parentRect.bottom += scrollParent.scrollTop parentRect.left += scrollParent.scrollLeft parentRect.right += scrollParent.scrollLeft } var rect = { top: elementRect.top - parentRect.top, left: elementRect.left - parentRect.left, bottom: elementRect.top - parentRect.top + elementRect.height, right: elementRect.left - parentRect.left + elementRect.width, width: elementRect.width, height: elementRect.height } return rect } /** * Get the prefixed supported property name * @function * @ignore * @argument {String} property (camelCase) * @returns {String} prefixed property (camelCase) */ function getSupportedPropertyName(property) { var prefixes = ['', 'ms', 'webkit', 'moz', 'o'] for (var i = 0; i < prefixes.length; i++) { var toCheck = prefixes[i] ? prefixes[i] + property.charAt(0).toUpperCase() + property.slice(1) : property if (typeof root.document.body.style[toCheck] !== 'undefined') { return toCheck } } return null } /** * The Object.assign() method is used to copy the values of all enumerable own properties from one or more source * objects to a target object. It will return the target object. * This polyfill doesn't support symbol properties, since ES5 doesn't have symbols anyway * Source: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign * @function * @ignore */ if (!Object.assign) { Object.defineProperty(Object, 'assign', { enumerable: false, configurable: true, writable: true, value: function (target) { if (target === undefined || target === null) { throw new TypeError('Cannot convert first argument to object') } var to = Object(target) for (var i = 1; i < arguments.length; i++) { var nextSource = arguments[i] if (nextSource === undefined || nextSource === null) { continue } nextSource = Object(nextSource) var keysArray = Object.keys(nextSource) for ( var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++ ) { var nextKey = keysArray[nextIndex] var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey) if (desc !== undefined && desc.enumerable) { to[nextKey] = nextSource[nextKey] } } } return to } }) }
Check if the given element is fixed or is inside a fixed parent @function @ignore @argument {Element} element @argument {Element} customContainer @returns {Boolean} answer to "isFixed?"
isFixed ( element )
javascript
hug-sun/element3
packages/element3/src/utils/new-popper.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/new-popper.js
MIT
aria.Utils.focusFirstDescendant = function (element) { for (var i = 0; i < element.childNodes.length; i++) { var child = element.childNodes[i] if ( aria.Utils.attemptFocus(child) || aria.Utils.focusFirstDescendant(child) ) { return true } } return false }
@desc Set focus on descendant nodes until the first focusable element is found. @param element DOM node for which to find the first focusable descendant. @returns true if a focusable element is found and focus is set.
aria.Utils.focusFirstDescendant ( element )
javascript
hug-sun/element3
packages/element3/src/utils/aria-utils.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/aria-utils.js
MIT
aria.Utils.focusLastDescendant = function (element) { for (var i = element.childNodes.length - 1; i >= 0; i--) { var child = element.childNodes[i] if ( aria.Utils.attemptFocus(child) || aria.Utils.focusLastDescendant(child) ) { return true } } return false }
@desc Find the last descendant node that is focusable. @param element DOM node for which to find the last focusable descendant. @returns true if a focusable element is found and focus is set.
aria.Utils.focusLastDescendant ( element )
javascript
hug-sun/element3
packages/element3/src/utils/aria-utils.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/aria-utils.js
MIT
aria.Utils.attemptFocus = function (element) { if (!aria.Utils.isFocusable(element)) { return false } aria.Utils.IgnoreUtilFocusChanges = true if (element && element.focus) { element.focus() } aria.Utils.IgnoreUtilFocusChanges = false return document.activeElement === element }
@desc Set Attempt to set focus on the current node. @param element The node to attempt to focus on. @returns true if element is focused.
aria.Utils.attemptFocus ( element )
javascript
hug-sun/element3
packages/element3/src/utils/aria-utils.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/aria-utils.js
MIT
aria.Utils.triggerEvent = function (elm, name, ...opts) { let eventName if (/^mouse|click/.test(name)) { eventName = 'MouseEvents' } else if (/^key/.test(name)) { eventName = 'KeyboardEvent' } else { eventName = 'HTMLEvents' } const evt = document.createEvent(eventName) evt.initEvent(name, ...opts) elm.dispatchEvent ? elm.dispatchEvent(evt) : elm.fireEvent('on' + name, evt) return elm }
触发一个事件 mouseenter, mouseleave, mouseover, keyup, change, click 等 @param {Element} elm @param {String} name @param {*} opts
'A' ( elm , name , ... opts )
javascript
hug-sun/element3
packages/element3/src/utils/aria-utils.js
https://github.com/hug-sun/element3/blob/master/packages/element3/src/utils/aria-utils.js
MIT
Array.prototype.each = function (fn) { var l = this.length; for (var i = 0; i < l; i++) { var e = this[i]; if (e) { fn(e, i); } } };
Faster than .forEach @param {(function())} fn The function to call
Array.prototype.each ( fn )
javascript
terwanerik/ScrollTrigger
dist/ScrollTrigger.js
https://github.com/terwanerik/ScrollTrigger/blob/master/dist/ScrollTrigger.js
MIT
function Trigger(element, options) { _classCallCheck(this, Trigger); this.element = element; options = extend_default()(new DefaultOptions().trigger, options); this.offset = options.offset; this.toggle = options.toggle; this.once = options.once; this.visible = null; this.active = true; }
Creates a new Trigger from the given element and options @param {Element|HTMLElement} element @param {DefaultOptions.trigger} [options=DefaultOptions.trigger] options
Trigger ( element , options )
javascript
terwanerik/ScrollTrigger
dist/ScrollTrigger.js
https://github.com/terwanerik/ScrollTrigger/blob/master/dist/ScrollTrigger.js
MIT
function TriggerCollection(triggers) { TriggerCollection_classCallCheck(this, TriggerCollection); /** * @member {Trigger[]} */ this.triggers = triggers instanceof Array ? triggers : []; }
Initializes the collection @param {Trigger[]} [triggers=[]] triggers A set of triggers to init with, optional
TriggerCollection ( triggers )
javascript
terwanerik/ScrollTrigger
dist/ScrollTrigger.js
https://github.com/terwanerik/ScrollTrigger/blob/master/dist/ScrollTrigger.js
MIT
function ScrollAnimationLoop(options, callback) { ScrollAnimationLoop_classCallCheck(this, ScrollAnimationLoop); this._parseOptions(options); if (typeof callback === 'function') { this.callback = callback; } this.direction = 'none'; this.position = this.getPosition(); this.lastAction = this._getTimestamp(); this._startRun(); this._boundListener = this._didScroll.bind(this); this.element.addEventListener('scroll', this._boundListener); }
ScrollAnimationLoop constructor. Starts a requestAnimationFrame loop as long as the user has scrolled the scrollElement. Stops after a certain time. @param {DefaultOptions.scroll} [options=DefaultOptions.scroll] options The options for the loop @param {ScrollCallback} callback [loop=null] The loop callback
ScrollAnimationLoop ( options , callback )
javascript
terwanerik/ScrollTrigger
dist/ScrollTrigger.js
https://github.com/terwanerik/ScrollTrigger/blob/master/dist/ScrollTrigger.js
MIT
function ScrollTrigger(options) { ScrollTrigger_classCallCheck(this, ScrollTrigger); this._parseOptions(options); this._initCollection(); this._initLoop(); }
Constructor for the scroll trigger @param {DefaultOptions} [options=DefaultOptions] options
ScrollTrigger ( options )
javascript
terwanerik/ScrollTrigger
dist/ScrollTrigger.js
https://github.com/terwanerik/ScrollTrigger/blob/master/dist/ScrollTrigger.js
MIT
_parseOptions(options) { options = extend(new DefaultOptions(), options) this.defaultTrigger = options.trigger this.scrollOptions = options.scroll }
Parses the options @param {DefaultOptions} [options=DefaultOptions] options @private
_parseOptions ( options )
javascript
terwanerik/ScrollTrigger
src/ScrollTrigger.js
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
MIT
_initCollection() { const scrollAttributes = document.querySelectorAll('[data-scroll]') let elements = [] if (scrollAttributes.length > 0) { elements = this.createTriggers(scrollAttributes) } this.collection = new TriggerCollection(elements) }
Initializes the collection, picks all [data-scroll] elements as initial elements @private
_initCollection ( )
javascript
terwanerik/ScrollTrigger
src/ScrollTrigger.js
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
MIT
_scrollCallback(position, direction) { this.collection.call((trigger) => { trigger.checkVisibility(this.scrollOptions.element, direction) }) this.scrollOptions.callback(position, direction) }
Callback for checking triggers @param {{x: number, y: number}} position @param {string} direction @private
_scrollCallback ( position , direction )
javascript
terwanerik/ScrollTrigger
src/ScrollTrigger.js
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
MIT
_scrollDirectionChange(direction) { this.scrollOptions.directionChange(direction) }
When the direction changes @param {string} direction @private
_scrollDirectionChange ( direction )
javascript
terwanerik/ScrollTrigger
src/ScrollTrigger.js
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
MIT
createTrigger(element, options) { return new Trigger(element, extend(this.defaultTrigger, options)) }
Creates a Trigger object from a given element and optional option set @param {HTMLElement} element @param {DefaultOptions.trigger} [options=DefaultOptions.trigger] options @returns Trigger
createTrigger ( element , options )
javascript
terwanerik/ScrollTrigger
src/ScrollTrigger.js
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
MIT
createTriggers(elements, options) { let triggers = [] elements.each((element) => { triggers.push(this.createTrigger(element, options)) }) return triggers }
Creates an array of triggers @param {HTMLElement[]|NodeList} elements @param {Object} [options=null] options @returns {Trigger[]} Array of triggers
createTriggers ( elements , options )
javascript
terwanerik/ScrollTrigger
src/ScrollTrigger.js
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
MIT
add(objects, options) { if (objects instanceof HTMLElement) { this.collection.add(this.createTrigger(objects, options)) return this } if (objects instanceof Trigger) { this.collection.add(objects) return this } if (objects instanceof NodeList) { this.collection.add(this.createTriggers(objects, options)) return this } if (Array.isArray(objects) && objects.length && objects[0] instanceof Trigger) { this.collection.add(objects) return this } if (Array.isArray(objects) && objects.length && objects[0] instanceof HTMLElement) { this.collection.add(this.createTriggers(objects, options)) return this } // assume it's a query string this.collection.add(this.createTriggers(document.querySelectorAll(objects), options)) return this }
Adds triggers @param {string|HTMLElement|NodeList|Trigger|Trigger[]} objects A list of objects or a query @param {Object} [options=null] options @returns {ScrollTrigger}
add ( objects , options )
javascript
terwanerik/ScrollTrigger
src/ScrollTrigger.js
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
MIT
remove(objects) { if (objects instanceof Trigger) { this.collection.remove(objects) return this } if (Array.isArray(objects) && objects.length && objects[0] instanceof Trigger) { this.collection.remove(objects) return this } if (objects instanceof HTMLElement) { this.collection.remove(this.search(objects)) return this } if (Array.isArray(objects) && objects.length && objects[0] instanceof HTMLElement) { this.collection.remove(this.search(objects)) return this } if (objects instanceof NodeList) { this.collection.remove(this.search(objects)) return this } if (Array.isArray(objects) && objects.length && objects[0] instanceof Trigger) { this.collection.remove(objects) return this } // assume it's a query string this.collection.remove(this.query(objects.toString())) return this }
Removes triggers @param {string|HTMLElement|NodeList|Trigger|Trigger[]} objects A list of objects or a query @returns {ScrollTrigger}
remove ( objects )
javascript
terwanerik/ScrollTrigger
src/ScrollTrigger.js
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
MIT