code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
function deopt(deoptPath) {
return {
confident: false,
deoptPath
};
} | Handle when binding is created inside a parent block and
the corresponding parent is removed by other plugins
if (false) { var a } -> var a | deopt | javascript | babel/minify | packages/babel-helper-evaluate-path/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-helper-evaluate-path/src/index.js | MIT |
function isAncestor(nodeParent, path) {
return !!path.findParent(parent => parent.node === nodeParent);
} | is nodeParent an ancestor of path | isAncestor | javascript | babel/minify | packages/babel-helper-evaluate-path/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-helper-evaluate-path/src/index.js | MIT |
function dotsToObject(input) {
const dots = Object.keys(input).map(key => [
...key.split(DELIMITTER),
input[key]
]);
// sort to ensure dot notation occurs after parent key
dots.sort((a, b) => {
if (a.length === b.length) {
return a[0] > b[0];
}
return a.length > b.length;
});
const obj = {};
for (const parts of dots) {
add(obj, ...parts);
}
// make object
function add(o, first, ...rest) {
if (rest.length < 1) {
// something went wrong
throw new Error("Option Parse Error");
} else if (rest.length === 1) {
// there is only a key and a value
// for example: mangle: true
o[first] = rest[0];
} else {
// create the current path and recurse if the plugin is enabled
if (!hop(o, first) || o[first] === true) {
// if the plugin is enabled
o[first] = {};
}
if (o[first] !== false) {
// if the plugin is NOT disabled then recurse
add(o[first], ...rest);
}
}
}
return obj;
} | Converts and Object of the form - {key<dot-notation>: value} to deep object
following rules of minify preset options
A preset option can be `true` | `object` which enables the particular plugin
`false` disables the plugin
@param input - An Object with dot-notation keys | dotsToObject | javascript | babel/minify | packages/babel-minify/src/options-parser.js | https://github.com/babel/minify/blob/master/packages/babel-minify/src/options-parser.js | MIT |
function add(o, first, ...rest) {
if (rest.length < 1) {
// something went wrong
throw new Error("Option Parse Error");
} else if (rest.length === 1) {
// there is only a key and a value
// for example: mangle: true
o[first] = rest[0];
} else {
// create the current path and recurse if the plugin is enabled
if (!hop(o, first) || o[first] === true) {
// if the plugin is enabled
o[first] = {};
}
if (o[first] !== false) {
// if the plugin is NOT disabled then recurse
add(o[first], ...rest);
}
}
} | Converts and Object of the form - {key<dot-notation>: value} to deep object
following rules of minify preset options
A preset option can be `true` | `object` which enables the particular plugin
`false` disables the plugin
@param input - An Object with dot-notation keys | add | javascript | babel/minify | packages/babel-minify/src/options-parser.js | https://github.com/babel/minify/blob/master/packages/babel-minify/src/options-parser.js | MIT |
function hop(o, key) {
return Object.prototype.hasOwnProperty.call(o, key);
} | Converts and Object of the form - {key<dot-notation>: value} to deep object
following rules of minify preset options
A preset option can be `true` | `object` which enables the particular plugin
`false` disables the plugin
@param input - An Object with dot-notation keys | hop | javascript | babel/minify | packages/babel-minify/src/options-parser.js | https://github.com/babel/minify/blob/master/packages/babel-minify/src/options-parser.js | MIT |
function memberToString(memberExprNode) {
const { object, property } = memberExprNode;
let result = "";
if (t.isIdentifier(object)) result += object.name;
if (t.isMemberExpression(object)) result += memberToString(object);
if (t.isIdentifier(property)) result += property.name;
return result;
} | Here, we validate a case where there is a local binding of
one of Math, String or Number. Here we have to get the
global Math instead of using the local one - so we do the
following transformation
var _Mathmax = Math.max;
to
var _Mathmax = (0, eval)("this").Math.max; | memberToString | javascript | babel/minify | packages/babel-plugin-minify-builtins/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-builtins/src/index.js | MIT |
function isBuiltInComputed(memberExprNode) {
const { object, computed } = memberExprNode;
return (
computed &&
t.isIdentifier(object) &&
VALID_CALLEES.indexOf(object.name) >= 0
);
} | Here, we validate a case where there is a local binding of
one of Math, String or Number. Here we have to get the
global Math instead of using the local one - so we do the
following transformation
var _Mathmax = Math.max;
to
var _Mathmax = (0, eval)("this").Math.max; | isBuiltInComputed | javascript | babel/minify | packages/babel-plugin-minify-builtins/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-builtins/src/index.js | MIT |
function isBuiltin(memberExprNode) {
const { object, property } = memberExprNode;
if (
t.isIdentifier(object) &&
t.isIdentifier(property) &&
VALID_CALLEES.indexOf(object.name) >= 0 &&
INVALID_METHODS.indexOf(property.name) < 0
) {
return true;
}
return false;
} | Here, we validate a case where there is a local binding of
one of Math, String or Number. Here we have to get the
global Math instead of using the local one - so we do the
following transformation
var _Mathmax = Math.max;
to
var _Mathmax = (0, eval)("this").Math.max; | isBuiltin | javascript | babel/minify | packages/babel-plugin-minify-builtins/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-builtins/src/index.js | MIT |
function getSegmentedSubPaths(paths) {
let segments = new Map();
// Get earliest Path in tree where paths intersect
paths[0].getDeepestCommonAncestorFrom(
paths,
(lastCommon, index, ancestries) => {
// found the LCA
if (!lastCommon.isProgram()) {
let fnParent;
if (
lastCommon.isFunction() &&
t.isBlockStatement(lastCommon.node.body)
) {
segments.set(lastCommon, paths);
return;
} else if (
!(fnParent = getFunctionParent(lastCommon)).isProgram() &&
t.isBlockStatement(fnParent.node.body)
) {
segments.set(fnParent, paths);
return;
}
}
// Deopt and construct segments otherwise
for (const ancestor of ancestries) {
const fnPath = getChildFuncion(ancestor);
if (fnPath === void 0) {
continue;
}
const validDescendants = paths.filter(p => {
return p.isDescendant(fnPath);
});
segments.set(fnPath, validDescendants);
}
}
);
return segments;
} | Here, we validate a case where there is a local binding of
one of Math, String or Number. Here we have to get the
global Math instead of using the local one - so we do the
following transformation
var _Mathmax = Math.max;
to
var _Mathmax = (0, eval)("this").Math.max; | getSegmentedSubPaths | javascript | babel/minify | packages/babel-plugin-minify-builtins/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-builtins/src/index.js | MIT |
function getChildFuncion(ancestors = []) {
for (const path of ancestors) {
if (path.isFunction() && t.isBlockStatement(path.node.body)) {
return path;
}
}
} | Here, we validate a case where there is a local binding of
one of Math, String or Number. Here we have to get the
global Math instead of using the local one - so we do the
following transformation
var _Mathmax = Math.max;
to
var _Mathmax = (0, eval)("this").Math.max; | getChildFuncion | javascript | babel/minify | packages/babel-plugin-minify-builtins/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-builtins/src/index.js | MIT |
function getFunctionParent(path) {
return (path.scope.getFunctionParent() || path.scope.getProgramParent()).path;
} | Babel-7 returns null if there is no function parent
and uses getProgramParent to get Program | getFunctionParent | javascript | babel/minify | packages/babel-plugin-minify-builtins/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-builtins/src/index.js | MIT |
exit(path, { opts: { tdz = false } = {} }) {
const consequent = path.get("consequent");
const alternate = path.get("alternate");
const test = path.get("test");
const evalResult = evaluate(test, { tdz });
const isPure = test.isPure();
const replacements = [];
if (evalResult.confident && !isPure && test.isSequenceExpression()) {
replacements.push(
t.expressionStatement(extractSequenceImpure(test))
);
}
// we can check if a test will be truthy 100% and if so then we can inline
// the consequent and completely ignore the alternate
//
// if (true) { foo; } -> { foo; }
// if ("foo") { foo; } -> { foo; }
//
if (evalResult.confident && evalResult.value) {
path.replaceWithMultiple([
...replacements,
...toStatements(consequent),
...extractVars(alternate)
]);
return;
}
// we can check if a test will be falsy 100% and if so we can inline the
// alternate if there is one and completely remove the consequent
//
// if ("") { bar; } else { foo; } -> { foo; }
// if ("") { bar; } ->
//
if (evalResult.confident && !evalResult.value) {
if (alternate.node) {
path.replaceWithMultiple([
...replacements,
...toStatements(alternate),
...extractVars(consequent)
]);
return;
} else {
path.replaceWithMultiple([
...replacements,
...extractVars(consequent)
]);
}
}
// remove alternate blocks that are empty
//
// if (foo) { foo; } else {} -> if (foo) { foo; }
//
if (alternate.isBlockStatement() && !alternate.node.body.length) {
alternate.remove();
// For if-statements babel-traverse replaces with an empty block
path.node.alternate = null;
}
// if the consequent block is empty turn alternate blocks into a consequent
// and flip the test
//
// if (foo) {} else { bar; } -> if (!foo) { bar; }
//
if (
consequent.isBlockStatement() &&
!consequent.node.body.length &&
alternate.isBlockStatement() &&
alternate.node.body.length
) {
consequent.replaceWith(alternate.node);
alternate.remove();
// For if-statements babel-traverse replaces with an empty block
path.node.alternate = null;
test.replaceWith(t.unaryExpression("!", test.node, true));
}
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | exit | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
EmptyStatement(path) {
if (path.parentPath.isBlockStatement() || path.parentPath.isProgram()) {
path.remove();
}
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | EmptyStatement | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
exit(
path,
{
opts: {
// set defaults
optimizeRawSize = false,
keepFnName = false,
keepClassName = false,
keepFnArgs = false,
tdz = false
} = {}
} = {}
) {
(traverse.clearCache || traverse.cache.clear)();
path.scope.crawl();
markEvalScopes(path);
// We need to run this plugin in isolation.
path.traverse(main, {
functionToBindings: new Map(),
optimizeRawSize,
keepFnName,
keepClassName,
keepFnArgs,
tdz
});
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | exit | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
function toStatements(path) {
const { node } = path;
if (path.isBlockStatement()) {
let hasBlockScoped = false;
for (let i = 0; i < node.body.length; i++) {
const bodyNode = node.body[i];
if (t.isBlockScoped(bodyNode)) {
hasBlockScoped = true;
}
}
if (!hasBlockScoped) {
return node.body;
}
}
return [node];
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | toStatements | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
function extractVars(path) {
const declarators = [];
if (path.isVariableDeclaration({ kind: "var" })) {
for (const decl of path.node.declarations) {
const bindingIds = Object.keys(t.getBindingIdentifiers(decl.id));
declarators.push(
...bindingIds.map(name => t.variableDeclarator(t.identifier(name)))
);
}
} else {
path.traverse({
VariableDeclaration(varPath) {
if (!varPath.isVariableDeclaration({ kind: "var" })) return;
if (!isSameFunctionScope(varPath, path)) return;
for (const decl of varPath.node.declarations) {
const bindingIds = Object.keys(t.getBindingIdentifiers(decl.id));
declarators.push(
...bindingIds.map(name =>
t.variableDeclarator(t.identifier(name))
)
);
}
}
});
}
if (declarators.length <= 0) return [];
return [t.variableDeclaration("var", declarators)];
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | extractVars | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
VariableDeclaration(varPath) {
if (!varPath.isVariableDeclaration({ kind: "var" })) return;
if (!isSameFunctionScope(varPath, path)) return;
for (const decl of varPath.node.declarations) {
const bindingIds = Object.keys(t.getBindingIdentifiers(decl.id));
declarators.push(
...bindingIds.map(name =>
t.variableDeclarator(t.identifier(name))
)
);
}
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | VariableDeclaration | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
function replace(path, options) {
const { replacement, replacementPath, scope, binding } = options;
// Same name, different binding.
if (scope.getBinding(path.node.name) !== binding) {
return;
}
// We don't want to move code around to different scopes because:
// 1. Original bindings that is referenced could be shadowed
// 2. Moving defintions to potentially hot code is bad
if (scope !== path.scope) {
if (t.isClass(replacement) || t.isFunction(replacement)) {
return;
}
let bail = false;
traverse(
replacement,
{
Function(path) {
if (bail) {
return;
}
bail = true;
path.stop();
}
},
scope
);
if (bail) {
return;
}
}
// Avoid recursion.
if (path.find(({ node }) => node === replacement)) {
return;
}
// https://github.com/babel/minify/issues/611
// this is valid only for FunctionDeclaration where we convert
// function declaration to expression in the next step
if (replacementPath.isFunctionDeclaration()) {
const fnName = replacementPath.get("id").node.name;
for (let name in replacementPath.scope.bindings) {
if (name === fnName) {
return;
}
}
}
// https://github.com/babel/minify/issues/130
if (!t.isExpression(replacement)) {
t.toExpression(replacement);
}
// We don't remove fn name here, we let the FnExpr & ClassExpr visitors
// check its references and remove unreferenced ones
// if (t.isFunction(replacement)) {
// replacement.id = null;
// }
path.replaceWith(replacement);
return true;
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | replace | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
Function(path) {
if (bail) {
return;
}
bail = true;
path.stop();
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | Function | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
function updateReferences(fnToDeletePath) {
if (!fnToDeletePath.isFunction()) {
return;
}
fnToDeletePath.traverse({
ReferencedIdentifier(path) {
const { node, scope } = path;
const binding = scope.getBinding(node.name);
if (
!binding ||
!binding.path.isFunction() ||
binding.scope === scope ||
!binding.constant
) {
return;
}
const index = binding.referencePaths.indexOf(path);
if (index === -1) {
return;
}
binding.references--;
binding.referencePaths.splice(index, 1);
if (binding.references === 0) {
binding.referenced = false;
}
if (binding.references <= 1 && binding.scope.path.node) {
binding.scope.path.node[shouldRevisit] = true;
}
}
});
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | updateReferences | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
ReferencedIdentifier(path) {
const { node, scope } = path;
const binding = scope.getBinding(node.name);
if (
!binding ||
!binding.path.isFunction() ||
binding.scope === scope ||
!binding.constant
) {
return;
}
const index = binding.referencePaths.indexOf(path);
if (index === -1) {
return;
}
binding.references--;
binding.referencePaths.splice(index, 1);
if (binding.references === 0) {
binding.referenced = false;
}
if (binding.references <= 1 && binding.scope.path.node) {
binding.scope.path.node[shouldRevisit] = true;
}
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | ReferencedIdentifier | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
function removeUnreferencedId(path) {
const id = path.get("id").node;
if (!id) {
return;
}
const { node, scope } = path;
const binding = scope.getBinding(id.name);
// Check if shadowed or is not referenced.
if (binding && (binding.path.node !== node || !binding.referenced)) {
node.id = null;
}
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | removeUnreferencedId | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
function isAncestor(path1, path2) {
return !!path2.findParent(parent => parent === path1);
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | isAncestor | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
function isSameFunctionScope(path1, path2) {
return path1.scope.getFunctionParent() === path2.scope.getFunctionParent();
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | isSameFunctionScope | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
function isBreaking(stmt, path) {
return isControlTransfer(stmt, path, "break");
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | isBreaking | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
function isContinuing(stmt, path) {
return isControlTransfer(stmt, path, "continue");
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | isContinuing | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
function isControlTransfer(stmt, path, control = "break") {
const { [control]: type } = {
break: "BreakStatement",
continue: "ContinueStatement"
};
if (!type) {
throw new Error("Can only handle break and continue statements");
}
const checker = `is${type}`;
if (stmt[checker]()) {
return _isControlTransfer(stmt, path);
}
let isTransferred = false;
let result = {
[control]: false,
bail: false
};
stmt.traverse({
[type](cPath) {
// if we already detected a break/continue statement,
if (isTransferred) return;
result = _isControlTransfer(cPath, path);
if (result.bail || result[control]) {
isTransferred = true;
}
}
});
return result;
function _isControlTransfer(cPath, path) {
const label = cPath.get("label");
if (label.node !== null) {
// labels are fn scoped and not accessible by inner functions
// path is the switch statement
if (!isSameFunctionScope(path, cPath)) {
// we don't have to worry about this break statement
return {
break: false,
bail: false
};
}
// here we handle the break labels
// if they are outside switch, we bail out
// if they are within the case, we keep them
let labelPath;
if (path.scope.getLabel) {
labelPath = getLabel(label.node.name, path);
} else {
labelPath = path.scope.getBinding(label.node.name).path;
}
const _isAncestor = isAncestor(labelPath, path);
return {
bail: _isAncestor,
[control]: _isAncestor
};
}
// set the flag that it is indeed breaking
let isCTransfer = true;
// this flag is to capture
// switch(0) { case 0: while(1) if (x) break; }
let possibleRunTimeControlTransfer = false;
// and compute if it's breaking the correct thing
let parent = cPath.parentPath;
while (parent !== stmt.parentPath) {
// loops and nested switch cases
if (parent.isLoop() || parent.isSwitchCase()) {
// invalidate all the possible runtime breaks captured
// while (1) { if (x) break; }
possibleRunTimeControlTransfer = false;
// and set that it's not breaking our switch statement
isCTransfer = false;
break;
}
//
// this is a special case and depends on
// the fact that SwitchStatement is handled in the
// exit hook of the traverse
//
// switch (0) {
// case 0: if (x) break;
// }
//
// here `x` is runtime only.
// in this case, we need to bail out. So we depend on exit hook
// of switch so that, it would have visited the IfStatement first
// before the SwitchStatement and would have removed the
// IfStatement if it was a compile time determined
//
if (parent.isIfStatement()) {
possibleRunTimeControlTransfer = true;
}
parent = parent.parentPath;
}
return {
[control]: possibleRunTimeControlTransfer || isCTransfer,
bail: possibleRunTimeControlTransfer
};
}
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | isControlTransfer | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
function _isControlTransfer(cPath, path) {
const label = cPath.get("label");
if (label.node !== null) {
// labels are fn scoped and not accessible by inner functions
// path is the switch statement
if (!isSameFunctionScope(path, cPath)) {
// we don't have to worry about this break statement
return {
break: false,
bail: false
};
}
// here we handle the break labels
// if they are outside switch, we bail out
// if they are within the case, we keep them
let labelPath;
if (path.scope.getLabel) {
labelPath = getLabel(label.node.name, path);
} else {
labelPath = path.scope.getBinding(label.node.name).path;
}
const _isAncestor = isAncestor(labelPath, path);
return {
bail: _isAncestor,
[control]: _isAncestor
};
}
// set the flag that it is indeed breaking
let isCTransfer = true;
// this flag is to capture
// switch(0) { case 0: while(1) if (x) break; }
let possibleRunTimeControlTransfer = false;
// and compute if it's breaking the correct thing
let parent = cPath.parentPath;
while (parent !== stmt.parentPath) {
// loops and nested switch cases
if (parent.isLoop() || parent.isSwitchCase()) {
// invalidate all the possible runtime breaks captured
// while (1) { if (x) break; }
possibleRunTimeControlTransfer = false;
// and set that it's not breaking our switch statement
isCTransfer = false;
break;
}
//
// this is a special case and depends on
// the fact that SwitchStatement is handled in the
// exit hook of the traverse
//
// switch (0) {
// case 0: if (x) break;
// }
//
// here `x` is runtime only.
// in this case, we need to bail out. So we depend on exit hook
// of switch so that, it would have visited the IfStatement first
// before the SwitchStatement and would have removed the
// IfStatement if it was a compile time determined
//
if (parent.isIfStatement()) {
possibleRunTimeControlTransfer = true;
}
parent = parent.parentPath;
}
return {
[control]: possibleRunTimeControlTransfer || isCTransfer,
bail: possibleRunTimeControlTransfer
};
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | _isControlTransfer | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
function canExistAfterCompletion(path) {
return (
path.isFunctionDeclaration() ||
path.isVariableDeclaration({ kind: "var" })
);
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | canExistAfterCompletion | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
function getLabel(name, _path) {
let label,
path = _path;
do {
label = path.scope.getLabel(name);
if (label) {
return label;
}
} while ((path = path.parentPath));
return null;
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | getLabel | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
function hasLoopParent(path) {
let parent = path;
do {
if (parent.isLoop()) {
return true;
}
} while ((parent = parent.parentPath));
return false;
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | hasLoopParent | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
function extractSequenceImpure(seq) {
const expressions = seq.get("expressions");
const result = [];
for (let i = 0; i < expressions.length; i++) {
if (!expressions[i].isPure()) {
result.push(expressions[i].node);
}
}
return t.sequenceExpression(result);
} | Use exit handler to traverse in a dfs post-order fashion
to remove use strict | extractSequenceImpure | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js | MIT |
function removeUseStrict(block) {
if (!block.isBlockStatement()) {
throw new Error(
`Received ${block.type}. Expected BlockStatement. ` +
`Please report at ${newIssueUrl}`
);
}
const useStricts = getUseStrictDirectives(block);
// early exit
if (useStricts.length < 1) return;
// only keep the first use strict
if (useStricts.length > 1) {
for (let i = 1; i < useStricts.length; i++) {
useStricts[i].remove();
}
}
// check if parent has an use strict
if (hasStrictParent(block)) {
useStricts[0].remove();
}
} | Remove redundant use strict
If the parent has a "use strict" directive, it is not required in
the children
@param {NodePath} block BlockStatement | removeUseStrict | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/remove-use-strict.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/remove-use-strict.js | MIT |
function hasStrictParent(path) {
return path.findParent(
parent => parent.isBlockStatement() && isStrict(parent)
);
} | Remove redundant use strict
If the parent has a "use strict" directive, it is not required in
the children
@param {NodePath} block BlockStatement | hasStrictParent | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/remove-use-strict.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/remove-use-strict.js | MIT |
function isStrict(block) {
return getUseStrictDirectives(block).length > 0;
} | Remove redundant use strict
If the parent has a "use strict" directive, it is not required in
the children
@param {NodePath} block BlockStatement | isStrict | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/remove-use-strict.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/remove-use-strict.js | MIT |
function getUseStrictDirectives(block) {
var dir = block.get("directives");
return Array.isArray(dir)
? dir.filter(function(directive) {
return directive.node.value.value === useStrict;
})
: [];
} | Remove redundant use strict
If the parent has a "use strict" directive, it is not required in
the children
@param {NodePath} block BlockStatement | getUseStrictDirectives | javascript | babel/minify | packages/babel-plugin-minify-dead-code-elimination/src/remove-use-strict.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/remove-use-strict.js | MIT |
isExcluded(name) {
return hop.call(this.exclude, name) && this.exclude[name];
} | Tells if a variable name is excluded
@param {String} name | isExcluded | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
crawlScope() {
(traverse.clearCache || traverse.cache.clear)();
this.program.scope.crawl();
} | Clears traverse cache and recrawls the AST
to recompute the bindings, references, other scope information
and paths because the other transformations in the same pipeline
(other plugins and presets) changes the AST and does NOT update
the scope objects | crawlScope | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
collect() {
const mangler = this;
const { scopeTracker } = mangler;
scopeTracker.addScope(this.program.scope);
/**
* Same usage as in DCE, whichever runs first
*/
if (!isEvalScopesMarked(mangler.program)) {
markEvalScopes(mangler.program);
}
/**
* The visitors to be used in traversal.
*
* Note: BFS traversal supports only the `enter` handlers, `exit`
* handlers are simply dropped without Errors
*
* Collects items defined in the ScopeTracker
*/
const collectVisitor = {
Scopable({ scope }) {
scopeTracker.addScope(scope);
// Collect bindings defined in the scope
Object.keys(scope.bindings).forEach(name => {
scopeTracker.addBinding(scope.bindings[name]);
// add all constant violations as references
scope.bindings[name].constantViolations.forEach(() => {
scopeTracker.addReference(scope, scope.bindings[name], name);
});
});
},
/**
* This is required because after function name transformation
* plugin (part of es2015), the function name is NOT added to the
* scope's bindings. So to fix this issue, we simply add a hack to
* handle that case - fix it to the scope tree.
*
* Related:
* - https://github.com/babel/minify/issues/829
*/
BindingIdentifier(path) {
if (
// the parent has this id as the name
(path.parentPath.isFunctionExpression({ id: path.node }) ||
path.parentPath.isClassExpression({ id: path.node })) &&
// and the id isn't yet added to the scope
!hop.call(path.parentPath.scope.bindings, path.node.name)
) {
path.parentPath.scope.registerBinding("local", path.parentPath);
}
},
/**
* This is necessary because, in Babel, the scope.references
* does NOT contain the references in that scope. Only the program
* scope (top most level) contains all the references.
*
* We collect the references in a fashion where all the scopes between
* and including the referenced scope and scope where it is declared
* is considered as scope referencing that identifier
*/
ReferencedIdentifier(path) {
if (isLabelIdentifier(path)) {
return;
}
const {
scope,
node: { name }
} = path;
const binding = scope.getBinding(name);
if (!binding) {
// Do not collect globals as they are already available via
// babel's API
if (scope.hasGlobal(name)) {
return;
}
// This should NOT happen ultimately. Panic if this code block is
// reached
throw new Error(
`Binding not found for ReferencedIdentifier "${name}" ` +
`present in "${path.parentPath.type}". ` +
`Please report this at ${newIssueUrl}`
);
} else {
// Add it to our scope tracker if everything is fine
scopeTracker.addReference(scope, binding, name);
}
}
};
/**
* These visitors are for collecting the Characters used in the program
* to measure the frequency and generate variable names for mangling so
* as to improve the gzip compression - as gzip likes repetition
*/
if (this.charset.shouldConsider) {
collectVisitor.Identifier = function Identifer(path) {
const { node } = path;
// We don't mangle properties, so we collect them as they contribute
// to the frequency of characters
if (
path.parentPath.isMemberExpression({ property: node }) ||
path.parentPath.isObjectProperty({ key: node })
) {
mangler.charset.consider(node.name);
}
};
collectVisitor.Literal = function Literal({ node }) {
mangler.charset.consider(String(node.value));
};
}
// Traverse the AST
bfsTraverse(mangler.program, collectVisitor);
} | A single pass through the AST to collect info for
1. Scope Tracker
2. Unsafe Scopes (direct eval scopes)
3. Charset considerations for better gzip compression
Traversed in the same fashion(BFS) the mangling is done | collect | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
Scopable({ scope }) {
scopeTracker.addScope(scope);
// Collect bindings defined in the scope
Object.keys(scope.bindings).forEach(name => {
scopeTracker.addBinding(scope.bindings[name]);
// add all constant violations as references
scope.bindings[name].constantViolations.forEach(() => {
scopeTracker.addReference(scope, scope.bindings[name], name);
});
});
} | The visitors to be used in traversal.
Note: BFS traversal supports only the `enter` handlers, `exit`
handlers are simply dropped without Errors
Collects items defined in the ScopeTracker | Scopable | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
BindingIdentifier(path) {
if (
// the parent has this id as the name
(path.parentPath.isFunctionExpression({ id: path.node }) ||
path.parentPath.isClassExpression({ id: path.node })) &&
// and the id isn't yet added to the scope
!hop.call(path.parentPath.scope.bindings, path.node.name)
) {
path.parentPath.scope.registerBinding("local", path.parentPath);
}
} | This is required because after function name transformation
plugin (part of es2015), the function name is NOT added to the
scope's bindings. So to fix this issue, we simply add a hack to
handle that case - fix it to the scope tree.
Related:
- https://github.com/babel/minify/issues/829 | BindingIdentifier | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
ReferencedIdentifier(path) {
if (isLabelIdentifier(path)) {
return;
}
const {
scope,
node: { name }
} = path;
const binding = scope.getBinding(name);
if (!binding) {
// Do not collect globals as they are already available via
// babel's API
if (scope.hasGlobal(name)) {
return;
}
// This should NOT happen ultimately. Panic if this code block is
// reached
throw new Error(
`Binding not found for ReferencedIdentifier "${name}" ` +
`present in "${path.parentPath.type}". ` +
`Please report this at ${newIssueUrl}`
);
} else {
// Add it to our scope tracker if everything is fine
scopeTracker.addReference(scope, binding, name);
}
} | This is necessary because, in Babel, the scope.references
does NOT contain the references in that scope. Only the program
scope (top most level) contains all the references.
We collect the references in a fashion where all the scopes between
and including the referenced scope and scope where it is declared
is considered as scope referencing that identifier | ReferencedIdentifier | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
isExportedWithName(binding) {
// short circuit
if (!this.topLevel) {
return false;
}
const refs = binding.referencePaths;
for (const ref of refs) {
if (ref.isExportNamedDeclaration()) {
return true;
}
}
// default
return false;
} | Tells if a binding is exported as a NamedExport - so as to NOT mangle
Babel treats NamedExports as a binding referenced by this NamedExport decl
@param {Binding} binding | isExportedWithName | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
canMangle(oldName, binding, scope) {
const cannotMangle =
// arguments - for non-strict mode
oldName === "arguments" ||
// labels
binding.path.isLabeledStatement() ||
// ClassDeclaration has binding in two scopes
// 1. The scope in which it is declared
// 2. The class's own scope
(binding.path.isClassDeclaration() && binding.path === scope.path) ||
// excluded
this.isExcluded(oldName) ||
// function names
(this.keepFnName ? isFunction(binding.path) : false) ||
// class names
(this.keepClassName ? isClass(binding.path) : false) ||
// named export
this.isExportedWithName(binding);
return !cannotMangle;
} | Tells if the name can be mangled in the current observed scope with
the input binding
@param {string} oldName the old name that needs to be mangled
@param {Binding} binding Binding of the name
@param {Scope} scope The current scope the mangler is run | canMangle | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
isValidName(newName, binding, scope) {
return (
t.isValidIdentifier(newName) &&
!this.scopeTracker.hasBinding(scope, newName) &&
!scope.hasGlobal(newName) &&
!this.scopeTracker.hasReference(scope, newName) &&
this.scopeTracker.canUseInReferencedScopes(binding, newName)
);
} | Tells if the newName can be used as a valid name for the input binding
in the input scope
@param {string} newName the old name that needs to be mangled
@param {Binding} binding Binding of the name that this new name will replace
@param {Scope} scope The current scope the mangler is run | isValidName | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
mangleScope(scope) {
const mangler = this;
const { scopeTracker } = mangler;
// Unsafe Scope
if (!mangler.eval && hasEval(scope)) {
return;
}
// Already visited
// This is because for a function, in Babel, the function and
// the function body's BlockStatement has the same scope, and will
// be visited twice by the Scopable handler, and we want to mangle
// it only once
if (mangler.visitedScopes.has(scope)) {
return;
}
mangler.visitedScopes.add(scope);
const bindings = scopeTracker.bindings.get(scope);
const names = [...bindings.keys()];
// A counter to generate names and reset
// so we can reuse removed names
let counter = 0;
/**
* 1. Iterate through the list of BindingIdentifiers
* 2. Rename each of them in-place
* 3. Update the scope tree.
*
* We cannot use a for..of loop over bindings.keys()
* because (2) we rename in place and update the bindings
* as we traverse through the keys
*/
for (const oldName of names) {
const binding = bindings.get(oldName);
if (mangler.canMangle(oldName, binding, scope)) {
let next;
do {
next = mangler.charset.getIdentifier(counter++);
} while (!mangler.isValidName(next, binding, scope));
// Reset so variables which are removed can be reused
//
// the following is an assumtion (for perf)
// the length 3 is an assumption that if the oldName isn't
// 1 or 2 characters, then probably we are not going to find
// a name - because for almost all usecases we have 1 or 2
// character new names only. And for the edge cases where
// one scope has lots and lots of variables, it's okay to
// name something with 3 characters instead of 1
if (oldName.length < 3) {
counter = 0;
}
// Once we detected a valid `next` Identifier which could be used,
// call the renamer
mangler.rename(scope, binding, oldName, next);
}
}
} | Mangle the scope
@param {Scope} scope | mangleScope | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
mangle() {
const mangler = this;
bfsTraverse(this.program, {
Scopable(path) {
if (!path.isProgram() || mangler.topLevel)
mangler.mangleScope(path.scope);
}
});
} | The mangle function that traverses through all the Scopes in a BFS
fashion - calls mangleScope | mangle | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
Scopable(path) {
if (!path.isProgram() || mangler.topLevel)
mangler.mangleScope(path.scope);
} | The mangle function that traverses through all the Scopes in a BFS
fashion - calls mangleScope | Scopable | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
renameBindingIds(path, oldName, newName, predicate = () => true) {
const bindingIds = path.getBindingIdentifierPaths(true, false);
for (const name in bindingIds) {
if (name !== oldName) continue;
for (const idPath of bindingIds[name]) {
if (predicate(idPath)) {
idPath.node.name = newName;
// babel-7 don't requeue
// idPath.replaceWith(t.identifier(newName));
this.renamedNodes.add(idPath.node);
}
}
}
} | Given a NodePath, collects all the Identifiers which are BindingIdentifiers
and replaces them with the new name
For example,
var a = 1, { b } = c; // a and b are BindingIdentifiers
@param {NodePath} path
@param {String} oldName
@param {String} newName
@param {Function} predicate | renameBindingIds | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
rename(scope, binding, oldName, newName) {
const mangler = this;
const { scopeTracker } = mangler;
// rename at the declaration level
this.renameBindingIds(
binding.path,
oldName,
newName,
idPath => idPath.node === binding.identifier
);
// update mangler's ScopeTracker
scopeTracker.renameBinding(scope, oldName, newName);
// update all constant violations
const violations = binding.constantViolations;
for (let i = 0; i < violations.length; i++) {
if (violations[i].isLabeledStatement()) continue;
this.renameBindingIds(violations[i], oldName, newName);
scopeTracker.updateReference(
violations[i].scope,
binding,
oldName,
newName
);
}
// update all referenced places
const refs = binding.referencePaths;
for (let i = 0; i < refs.length; i++) {
const path = refs[i];
const { node } = path;
if (!path.isIdentifier()) {
// Ideally, this should not happen
// it happens in these places now -
// case 1: Export Statements
// This is a bug in babel
// https://github.com/babel/babel/pull/3629
// case 2: Replacements in other plugins
// eg: https://github.com/babel/minify/issues/122
// replacement in dce from `x` to `!x` gives referencePath as `!x`
path.traverse({
ReferencedIdentifier(refPath) {
if (refPath.node.name !== oldName) {
return;
}
const actualBinding = refPath.scope.getBinding(oldName);
if (actualBinding !== binding) {
return;
}
refPath.node.name = newName;
// babel-7 don't requeue
// refPath.replaceWith(t.identifier(newName));
mangler.renamedNodes.add(refPath.node);
scopeTracker.updateReference(
refPath.scope,
binding,
oldName,
newName
);
}
});
} else if (!isLabelIdentifier(path)) {
if (path.node.name === oldName) {
path.node.name = newName;
// babel-7 don't requeue
// path.replaceWith(t.identifier(newName));
mangler.renamedNodes.add(path.node);
scopeTracker.updateReference(path.scope, binding, oldName, newName);
} else if (mangler.renamedNodes.has(path.node)) {
// already renamed,
// just update the references
scopeTracker.updateReference(path.scope, binding, oldName, newName);
} else {
throw new Error(
`Unexpected Rename Error: ` +
`Trying to replace "${
node.name
}": from "${oldName}" to "${newName}". ` +
`Please report it at ${newIssueUrl}`
);
}
}
// else label identifier - silently ignore
}
// update babel's internal tracking
binding.identifier.name = newName;
// update babel's internal scope tracking
const { bindings } = scope;
bindings[newName] = binding;
delete bindings[oldName];
} | The Renamer:
Renames the following for one Binding in a Scope
1. Binding in that Scope
2. All the Binding's constant violations
3. All its References
4. Updates mangler.scopeTracker
5. Updates Babel's Scope tracking
@param {Scope} scope
@param {Binding} binding
@param {String} oldName
@param {String} newName | rename | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
ReferencedIdentifier(refPath) {
if (refPath.node.name !== oldName) {
return;
}
const actualBinding = refPath.scope.getBinding(oldName);
if (actualBinding !== binding) {
return;
}
refPath.node.name = newName;
// babel-7 don't requeue
// refPath.replaceWith(t.identifier(newName));
mangler.renamedNodes.add(refPath.node);
scopeTracker.updateReference(
refPath.scope,
binding,
oldName,
newName
);
} | The Renamer:
Renames the following for one Binding in a Scope
1. Binding in that Scope
2. All the Binding's constant violations
3. All its References
4. Updates mangler.scopeTracker
5. Updates Babel's Scope tracking
@param {Scope} scope
@param {Binding} binding
@param {String} oldName
@param {String} newName | ReferencedIdentifier | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
exit(path) {
// If the source code is small then we're going to assume that the user
// is running on this on single files before bundling. Therefore we
// need to achieve as much determinisim and we will not do any frequency
// sorting on the character set. Currently the number is pretty arbitrary.
const shouldConsiderSource = path.getSource().length > 70000;
const charset = new Charset(shouldConsiderSource);
const mangler = new Mangler(charset, path, this.opts);
mangler.run();
} | Mangler is run as a single pass. It's the same pattern as used in DCE | exit | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
function toObject(value) {
if (!Array.isArray(value)) {
return value;
}
const map = {};
for (let i = 0; i < value.length; i++) {
map[value[i]] = true;
}
return map;
} | Mangler is run as a single pass. It's the same pattern as used in DCE | toObject | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
function isFunction(path) {
return path.isFunctionExpression() || path.isFunctionDeclaration();
} | Mangler is run as a single pass. It's the same pattern as used in DCE | isFunction | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
function isClass(path) {
return path.isClassExpression() || path.isClassDeclaration();
} | Mangler is run as a single pass. It's the same pattern as used in DCE | isClass | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/index.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/index.js | MIT |
constructor() {
this.references = new Map();
this.bindings = new Map();
} | ScopeTracker
references: Map<Scope, CountedSet<String> >
bindings: Map<Scope, Map<String, Binding> > | constructor | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | MIT |
addScope(scope) {
if (!this.references.has(scope)) {
this.references.set(scope, new CountedSet());
}
if (!this.bindings.has(scope)) {
this.bindings.set(scope, new Map());
}
} | Register a new Scope and initiliaze it with empty sets
@param {Scope} scope | addScope | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | MIT |
addReference(scope, binding, name) {
let parent = scope;
do {
this.references.get(parent).add(name);
if (!binding) {
throw new Error(
`Binding Not Found for ${name} during scopeTracker.addRefernce. ` +
`Please report at ${newIssueUrl}`
);
}
if (binding.scope === parent) break;
} while ((parent = parent.parent));
} | Add reference to all Scopes between and including the ReferencedScope
and Binding's Scope
@param {Scope} scope
@param {Binding} binding
@param {String} name | addReference | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | MIT |
hasReference(scope, name) {
return this.references.get(scope).has(name);
} | has a Reference in the given {Scope} or a child Scope
Refer {addReference} to know why the following call will be valid
for detecting references in child Scopes
@param {Scope} scope
@param {String} name | hasReference | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | MIT |
updateReference(scope, binding, oldName, newName) {
let parent = scope;
do {
const ref = this.references.get(parent);
ref.delete(oldName);
ref.add(newName);
if (!binding) {
// Something went wrong - panic
throw new Error(
"Binding Not Found during scopeTracker.updateRefernce " +
`while updating "${oldName}" to "${newName}". ` +
`Please report at ${newIssueUrl}`
);
}
if (binding.scope === parent) break;
} while ((parent = parent.parent));
} | Update reference count in all scopes between and including the
Referenced Scope and the Binding's Scope
@param {Scope} scope
@param {Binding} binding
@param {String} oldName
@param {String} newName | updateReference | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | MIT |
hasBindingOrReference(scope, binding, name) {
return this.hasReference(scope, name) || this.hasBinding(scope, name);
} | has either a Binding or a Reference
@param {Scope} scope
@param {Binding} binding
@param {String} name | hasBindingOrReference | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | MIT |
canUseInReferencedScopes(binding, next) {
const tracker = this;
if (tracker.hasBindingOrReference(binding.scope, binding, next)) {
return false;
}
// Safari raises a syntax error for a `let` or `const` declaration in a
// `for` loop initialization that shadows a parent function's parameter.
// https://github.com/babel/minify/issues/559
// https://bugs.webkit.org/show_bug.cgi?id=171041
// https://trac.webkit.org/changeset/217200/webkit/trunk/Source
const maybeDecl = binding.path.parentPath;
const isBlockScoped =
maybeDecl.isVariableDeclaration({ kind: "let" }) ||
maybeDecl.isVariableDeclaration({ kind: "const" });
if (isBlockScoped) {
const maybeFor = maybeDecl.parentPath;
const isForLoopBinding =
maybeFor.isForStatement({ init: maybeDecl.node }) ||
maybeFor.isForXStatement({ left: maybeDecl.node });
if (isForLoopBinding) {
const fnParent = getFunctionParent(maybeFor);
if (fnParent.isFunction({ body: maybeFor.parent })) {
const parentFunctionBinding = this.bindings
.get(fnParent.scope)
.get(next);
if (parentFunctionBinding) {
const parentFunctionHasParamBinding =
parentFunctionBinding.kind === "param";
if (parentFunctionHasParamBinding) {
return false;
}
}
}
}
}
for (let i = 0; i < binding.constantViolations.length; i++) {
const violation = binding.constantViolations[i];
if (tracker.hasBindingOrReference(violation.scope, binding, next)) {
return false;
}
}
for (let i = 0; i < binding.referencePaths.length; i++) {
const ref = binding.referencePaths[i];
if (!ref.isIdentifier()) {
let canUse = true;
ref.traverse({
ReferencedIdentifier(path) {
if (path.node.name !== next) return;
if (tracker.hasBindingOrReference(path.scope, binding, next)) {
canUse = false;
}
}
});
if (!canUse) {
return canUse;
}
} else if (!isLabelIdentifier(ref)) {
if (tracker.hasBindingOrReference(ref.scope, binding, next)) {
return false;
}
}
}
return true;
} | For a Binding visit all places where the Binding is used and detect
if the newName {next} can be used in all these places
1. binding's own scope
2. constant violations' scopes
3. referencePaths' scopes
@param {Binding} binding
@param {String} next | canUseInReferencedScopes | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | MIT |
ReferencedIdentifier(path) {
if (path.node.name !== next) return;
if (tracker.hasBindingOrReference(path.scope, binding, next)) {
canUse = false;
}
} | For a Binding visit all places where the Binding is used and detect
if the newName {next} can be used in all these places
1. binding's own scope
2. constant violations' scopes
3. referencePaths' scopes
@param {Binding} binding
@param {String} next | ReferencedIdentifier | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | MIT |
addBinding(binding) {
if (!binding) {
return;
}
const bindings = this.bindings.get(binding.scope);
const existingBinding = bindings.get(binding.identifier.name);
if (existingBinding && existingBinding !== binding) {
throw new Error(
`scopeTracker.addBinding: ` +
`Binding "${existingBinding.identifier.name}" already exists. ` +
`Trying to add "${binding.identifier.name}" again.`
);
}
bindings.set(binding.identifier.name, binding);
} | Add a binding to Tracker in binding's own Scope
@param {Binding} binding | addBinding | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | MIT |
moveBinding(binding, toScope) {
this.bindings.get(binding.scope).delete(binding.identifier.name);
this.bindings.get(toScope).set(binding.identifier.name, binding);
} | Moves Binding from it's own Scope to {@param toScope}
required for fixup-var-scope
@param {Binding} binding
@param {Scope} toScope | moveBinding | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | MIT |
hasBinding(scope, name) {
return this.bindings.get(scope).has(name);
} | has a Binding in the current {Scope}
@param {Scope} scope
@param {String} name | hasBinding | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | MIT |
renameBinding(scope, oldName, newName) {
const bindings = this.bindings.get(scope);
bindings.set(newName, bindings.get(oldName));
bindings.delete(oldName);
} | Update the ScopeTracker on rename
@param {Scope} scope
@param {String} oldName
@param {String} newName | renameBinding | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | MIT |
function getFunctionParent(path) {
return (path.scope.getFunctionParent() || path.scope.getProgramParent()).path;
} | Babel-7 returns null if there is no function parent
and uses getProgramParent to get Program | getFunctionParent | javascript | babel/minify | packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/scope-tracker.js | MIT |
function pathJoin(...parts) {
if (path.isAbsolute(parts[0])) {
return path.join(...parts);
}
return "." + path.sep + path.join(...parts);
} | Jest changes __dirname to relative path and the require of relative path
that doesn't start with "." will be a module require -
require("./packages/babel-plugin...") vs require("packages/babel-plugin..");
So we start the path with a "./" | pathJoin | javascript | babel/minify | utils/test-runner/src/index.js | https://github.com/babel/minify/blob/master/utils/test-runner/src/index.js | MIT |
function testRunner(dir) {
const pkgDir = pathJoin(dir, "../");
const packageJson = JSON.parse(
fs.readFileSync(pathJoin(pkgDir, "package.json"))
);
const pkgName = packageJson.name;
const fixturesDir = pathJoin(pkgDir, "__tests__/fixtures");
const fixtures = fs
.readdirSync(fixturesDir)
.filter(dir => fs.isDirectorySync(pathJoin(fixturesDir, dir)));
const flags = parseArgs(process.argv);
const updateFixtures =
!!process.env.OVERWRITE || Boolean(flags["update-fixtures"]);
describe(pkgName, () => {
for (const fixture of fixtures) {
const actualFile = pathJoin(fixturesDir, fixture, "actual.js");
const expectedFile = pathJoin(fixturesDir, fixture, "expected.js");
const skipFile = pathJoin(fixturesDir, fixture, "skip");
const optionsFile = pathJoin(fixturesDir, fixture, "options.json");
const babelOptionsFile = pathJoin(fixturesDir, fixture, "babel.json");
if (fs.isFileSync(skipFile)) {
test.skip(fixture, () => {});
continue;
}
test(fixture, async () => {
const actual = await fs.readFile(actualFile);
let options = {};
if (await fs.isFile(optionsFile)) {
options = JSON.parse(await fs.readFile(optionsFile));
}
let babelOpts = {
// set the default sourcetype to be script
sourceType: "script"
};
if (await fs.isFile(babelOptionsFile)) {
Object.assign(
babelOpts,
JSON.parse(await fs.readFile(babelOptionsFile))
);
}
const currentPlugin = pathJoin(pkgDir, "src/index.js");
if (Array.isArray(babelOpts.plugins)) {
babelOpts.plugins = [[currentPlugin, options], ...babelOpts.plugins];
} else {
babelOpts.plugins = [[currentPlugin, options]];
}
// don't consider the project's babel.config.js
babelOpts.configFile = false;
const actualTransformed = babel.transformSync(actual, babelOpts).code;
if (!(await fs.isFile(expectedFile))) {
await fs.writeFile(expectedFile, actualTransformed);
console.warn("Created fixture's expected file - " + expectedFile);
} else if (updateFixtures) {
const expected = await fs.readFile(expectedFile);
if (expected !== actualTransformed) {
await fs.writeFile(expectedFile, actualTransformed);
console.warn("Updated fixture's expected file - " + expectedFile);
}
} else {
const expected = await fs.readFile(expectedFile);
expect(actualTransformed).toBe(expected);
}
});
}
});
} | Jest changes __dirname to relative path and the require of relative path
that doesn't start with "." will be a module require -
require("./packages/babel-plugin...") vs require("packages/babel-plugin..");
So we start the path with a "./" | testRunner | javascript | babel/minify | utils/test-runner/src/index.js | https://github.com/babel/minify/blob/master/utils/test-runner/src/index.js | MIT |
function inArray(o, arr) {
return arr.indexOf(o) > -1;
} | Check in array
@param {*} o
@param {Array} arr
@returns {Boolean} | inArray | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
} | Check is array
@param {*} o
@returns {Boolean} | isArray | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function isObject(o) {
return Object.prototype.toString.call(o) === '[object Object]';
} | Check is object
@param {*} o
@returns {Boolean} | isObject | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function hasClass(el, cls) {
return el.className.match(new RegExp('(\\s|^)(' + cls + ')(\\s|$)'));
} | @param {HTMLElement} el
@param {String} cls
@returns {Array|{index: number, input: string}} | hasClass | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function addClass(el, cls) {
if (!hasClass(el, cls)) {
el.className += ' ' + cls;
}
} | @param {HTMLElement} el
@param {String} cls | addClass | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function removeClass(el, cls) {
if (hasClass(el, cls)) {
el.className = el.className.replace(RegExp('(\\s|^)(' + cls + ')(\\s|$)'), '$3');
}
} | @param {HTMLElement} el
@param {String} cls | removeClass | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function isUrl(url) {
if (/<\/?[^>]*>/.test(url))
return false;
return /^(?:(https|http|ftp|rtsp|mms):)?(\/\/)?(\w+:{0,1}\w*@)?([^\?#:\/]+\.[a-z]+|\d+\.\d+\.\d+\.\d+)?(:[0-9]+)?((?:\.?\/)?([^\?#]*)?(\?[^#]+)?(#.+)?)?$/.test(url);
} | Check is url
@param {String} url
@returns {Boolean} | isUrl | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function isDom(obj) {
try {
return obj instanceof HTMLElement;
}
catch (e) {
return (typeof obj === "object") &&
(obj.nodeType === 1) && (typeof obj.style === "object") &&
(typeof obj.ownerDocument === "object");
}
} | Check is dom object
@param {object} dom
@returns {Boolean} | isDom | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function _A(a) {
return Array.prototype.slice.apply(a, Array.prototype.slice.call(arguments, 1));
} | Parse arguments to array
@param {Arguments} a
@param {Number|null} start
@param {Number|null} end
@returns {Array} | _A | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function IU(word) {
return word.replace(/^[a-z]/, function (t) {
return t.toUpperCase();
});
} | Parse arguments to array
@param {Arguments} a
@param {Number|null} start
@param {Number|null} end
@returns {Array} | IU | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
iSlider = function () {
var args = _A(arguments, 0, 3);
if (!args.length) {
throw new Error('Parameters required!');
}
var opts = isObject(args.slice(-1)[0]) ? args.pop() : {};
switch (args.length) {
case 2:
opts.data = opts.data || args[1];
case 1:
opts.dom = opts.dom || args[0];
}
if (!opts.dom) {
throw new Error('Container can not be empty!');
}
else if (!isDom(opts.dom)) {
throw new Error('Container must be a HTMLElement instance!');
}
if (!opts.data || !opts.data.length) {
throw new Error('Data must be an array and must have more than one element!');
}
/**
* Options
* @private
*/
this._opts = opts;
opts = null, args = null;
this._setting();
this.fire('initialize');
this._renderWrapper();
this._initPlugins();
this._bindHandler();
this.fire('initialized');
// Autoplay mode
this._autoPlay();
} | @constructor
iSlider([[{HTMLElement} container,] {Array} datalist,] {Object} options)
@param {HTMLElement} container
@param {Array} datalist
@param {Object} options
@description
options.dom > container
options.data > datalist | iSlider | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function normal(dom, axis, scale, i, offset) {
iSlider.setStyle(dom, 'transform', 'translateZ(0) translate' + axis + '(' + (offset + scale * (i - 1)) + 'px)');
} | @type {Object}
@param {HTMLElement} dom The wrapper <li> element
@param {String} axis Animate direction
@param {Number} scale Outer wrapper
@param {Number} i Wrapper's index
@param {Number} offset Move distance
@protected | normal | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
insertImg = function renderItemInsertImg() {
var simg = ' src="' + item.content + '"';
// auto scale to full screen
if (item.height / item.width > self.ratio) {
simg += ' height="100%"';
} else {
simg += ' width="100%"';
}
if (self.isOverspread) {
el.style.cssText += 'background-image:url(' + item.content + ');background-repeat:no-repeat;background-position:50% 50%;background-size:cover';
simg += ' style="display:block;opacity:0;height:100%;width:100%;"';
}
// for right button, save picture
el.innerHTML = '<img' + simg + ' />';
} | render single item html by idx
@param {HTMLElement} el ..
@param {Number} dataIndex ..
@private | insertImg | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
loadImg = function (index) {
var item = data[index];
if (self._itemType(item) === 'pic' && !item.load) {
var preloadImg = new Image();
preloadImg.src = item.content;
preloadImg.onload = function () {
item.width = preloadImg.width;
item.height = preloadImg.height;
item.load = 2;
};
preloadImg.onerror = function () {
item.load = -1;
}
item.load = 1;
}
} | Preload img when slideChange
From current index +2, -2 scene
@param {Number} dataIndex means which image will be load
@private | loadImg | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function dispatchLink(el) {
if (el != null) {
if (el.tagName === 'A') {
if (el.href) {
if (el.getAttribute('target') === '_blank') {
global.open(el.href);
} else {
global.location.href = el.href;
}
evt.preventDefault();
return false;
}
}
else if (el.tagName === 'LI' && el.className.search(/^islider\-/) > -1) {
return false;
}
else {
dispatchLink(el.parentNode);
}
}
} | touchend callback
@param {Object} evt event object
@public | dispatchLink | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function delegatedEventCallbackHandle(e) {
var evt = global.event ? global.event : e;
var target = evt.target;
var eleArr = document.querySelectorAll(selector);
for (var i = 0; i < eleArr.length; i++) {
if (target === eleArr[i]) {
callback.call(target);
break;
}
}
} | simple event delegate method
@param {String} evtType event name
@param {String} selector the simple css selector like jQuery
@param {Function} callback event callback
@public
@alias iSliderPrototype.bind | delegatedEventCallbackHandle | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function rotate(dom, axis, scale, i, offset, direct) {
var rotateDirect = (axis === 'X') ? 'Y' : 'X';
if (this.isVertical) {
offset = -offset;
if (Math.abs(direct) > 1) {
direct = -direct;
}
}
var outer = dom.parentElement;
iSlider.setStyle(outer, 'perspective', scale * 4);
dom.style.visibility = 'visible';
if (direct > 0 && i === 2) {
dom.style.visibility = 'hidden';
}
if (direct < 0 && i === 0) {
dom.style.visibility = 'hidden';
}
dom.style.zIndex = i === 1 ? 1 : 0;
dom.style.cssText += iSlider.styleProp('backface-visibility') + ':hidden;' + iSlider.styleProp('transform-style') + ':preserve-3d;' + 'position:absolute;';
// TODO: overflow... I dont understand why there are many differences between ios and desktop. Maybe they have different interpretations of Perspective
iSlider.setStyle(dom, 'transform', 'rotate' + rotateDirect + '(' + 90 * (offset / scale + i - 1) + 'deg) translateZ(' + (0.889 * scale / 2) + 'px) scale(0.889)');
} | More animations
@file animate.js
@author BE-FE Team
xieyu33333 [email protected]
shinate [email protected] | rotate | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function flip(dom, axis, scale, i, offset, direct) {
if (this.isVertical) {
offset = -offset;
}
var outer = dom.parentElement;
iSlider.setStyle(outer, 'perspective', scale * 4);
dom.style.visibility = 'visible';
if (direct > 0 && i === 2) {
dom.style.visibility = 'hidden';
}
if (direct < 0 && i === 0) {
dom.style.visibility = 'hidden';
}
dom.style.cssText += 'position:absolute;' + iSlider.styleProp('backface-visibility') + ':hidden';
iSlider.setStyle(dom, 'transform', 'translateZ(' + (scale / 2) + 'px) rotate' + ((axis === 'X') ? 'Y' : 'X') + '(' + 180 * (offset / scale + i - 1) + 'deg) scale(0.875)');
} | More animations
@file animate.js
@author BE-FE Team
xieyu33333 [email protected]
shinate [email protected] | flip | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function depth(dom, axis, scale, i, offset, direct) {
var zoomScale = (4 - Math.abs(i - 1)) * 0.18;
var outer = dom.parentElement;
iSlider.setStyle(outer, 'perspective', scale * 4);
dom.style.zIndex = i === 1 ? 1 : 0;
iSlider.setStyle(dom, 'transform', 'scale(' + zoomScale + ') translateZ(0) translate' + axis + '(' + (offset + 1.3 * scale * (i - 1)) + 'px)');
} | More animations
@file animate.js
@author BE-FE Team
xieyu33333 [email protected]
shinate [email protected] | depth | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function flow(dom, axis, scale, i, offset, direct) {
var absoluteOffset = Math.abs(offset);
var rotateDirect = (axis === 'X') ? 'Y' : 'X';
var directAmend = (axis === 'X') ? 1 : -1;
var offsetRatio = Math.abs(offset / scale);
var outer = dom.parentElement;
iSlider.setStyle(outer, 'perspective', scale * 4);
if (i === 1) {
dom.style.zIndex = scale - absoluteOffset;
}
else {
dom.style.zIndex = (offset > 0) ? (1 - i) * absoluteOffset : (i - 1) * absoluteOffset;
}
iSlider.setStyle(dom, 'transform', 'scale(0.7, 0.7) translateZ(' + (offsetRatio * 150 - 150) * Math.abs(i - 1) + 'px)' + 'translate' + axis + '(' + (offset + scale * (i - 1)) + 'px)' + 'rotate' + rotateDirect + '(' + directAmend * (30 - offsetRatio * 30) * (1 - i) + 'deg)');
} | More animations
@file animate.js
@author BE-FE Team
xieyu33333 [email protected]
shinate [email protected] | flow | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function card(dom, axis, scale, i, offset, direct) {
var absoluteOffset = Math.abs(offset);
var zoomScale = 1;
var z = 1;
if (absoluteOffset > 0) {
if (i === 1) {
zoomScale = 1 - 0.2 * Math.abs(i - 1) - Math.abs(0.2 * offset / scale).toFixed(6);
z = 0;
}
} else {
if (i !== 1) {
if ((direct > 0 && i === 0) || (direct < 0 && i === 2)) {
zoomScale = 1 - 0.2 * Math.abs(i - 1);
}
z = 0;
}
}
dom.style.zIndex = z;
iSlider.setStyle(dom, 'transform', 'scale(' + zoomScale + ') translateZ(0) translate' + axis + '(' + ((1 + Math.abs(i - 1) * 0.2) * offset + scale * (i - 1)) + 'px)');
} | More animations
@file animate.js
@author BE-FE Team
xieyu33333 [email protected]
shinate [email protected] | card | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function fade(dom, axis, scale, i, offset, direct) {
dom.style.zIndex = i === 1 ? 1 : 0;
offset = Math.abs(offset);
if (i === 1) {
dom.style.opacity = 1 - (offset / scale);
} else {
dom.style.opacity = offset / scale;
}
} | More animations
@file animate.js
@author BE-FE Team
xieyu33333 [email protected]
shinate [email protected] | fade | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function zoomout(dom, axis, scale, i, offset) {
var z, o, s;
var oa = offset / scale;
switch (i) {
case 0:
lsn && window.clearTimeout(lsn);
o = oa < 1 ? oa : 1;
s = 2 - (0.5 * oa);
z = 2;
var at = parseInt(window.getComputedStyle(dom)[iSlider.styleProp('transitionDuration', 1)]) * 1000;
if (at > 0) {
lsn = window.setTimeout(function () {
dom.style.zIndex = 0;
}, at);
}
break;
case 1:
o = 1 - oa;
s = 1 - (0.5 * oa);
z = 1;
break;
case 2:
o = oa > 0 ? oa : 0;
s = 0.5 - (0.5 * oa);
z = 0;
break;
}
dom.style.cssText += 'z-index:' + z + ';opacity:' + o + ';' + iSlider.styleProp('transform') + ':scale(' + s + ');';
} | More animations
@file animate.js
@author BE-FE Team
xieyu33333 [email protected]
shinate [email protected] | zoomout | javascript | be-fe/iSlider | build/index.bundle.js | https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js | MIT |
function rotate(dom, axis, scale, i, offset, direct) {
var rotateDirect = (axis === 'X') ? 'Y' : 'X';
if (this.isVertical) {
offset = -offset;
if (Math.abs(direct) > 1) {
direct = -direct;
}
}
var outer = dom.parentElement;
iSlider.setStyle(outer, 'perspective', scale * 4);
dom.style.visibility = 'visible';
if (direct > 0 && i === 2) {
dom.style.visibility = 'hidden';
}
if (direct < 0 && i === 0) {
dom.style.visibility = 'hidden';
}
dom.style.zIndex = i === 1 ? 1 : 0;
dom.style.cssText += iSlider.styleProp('backface-visibility') + ':hidden;' + iSlider.styleProp('transform-style') + ':preserve-3d;' + 'position:absolute;';
// TODO: overflow... I dont understand why there are many differences between ios and desktop. Maybe they have different interpretations of Perspective
iSlider.setStyle(dom, 'transform', 'rotate' + rotateDirect + '(' + 90 * (offset / scale + i - 1) + 'deg) translateZ(' + (0.889 * scale / 2) + 'px) scale(0.889)');
} | More animations
@file animate.js
@author BE-FE Team
xieyu33333 [email protected]
shinate [email protected] | rotate | javascript | be-fe/iSlider | build/iSlider.animate.js | https://github.com/be-fe/iSlider/blob/master/build/iSlider.animate.js | MIT |
function flip(dom, axis, scale, i, offset, direct) {
if (this.isVertical) {
offset = -offset;
}
var outer = dom.parentElement;
iSlider.setStyle(outer, 'perspective', scale * 4);
dom.style.visibility = 'visible';
if (direct > 0 && i === 2) {
dom.style.visibility = 'hidden';
}
if (direct < 0 && i === 0) {
dom.style.visibility = 'hidden';
}
dom.style.cssText += 'position:absolute;' + iSlider.styleProp('backface-visibility') + ':hidden';
iSlider.setStyle(dom, 'transform', 'translateZ(' + (scale / 2) + 'px) rotate' + ((axis === 'X') ? 'Y' : 'X') + '(' + 180 * (offset / scale + i - 1) + 'deg) scale(0.875)');
} | More animations
@file animate.js
@author BE-FE Team
xieyu33333 [email protected]
shinate [email protected] | flip | javascript | be-fe/iSlider | build/iSlider.animate.js | https://github.com/be-fe/iSlider/blob/master/build/iSlider.animate.js | MIT |
function depth(dom, axis, scale, i, offset, direct) {
var zoomScale = (4 - Math.abs(i - 1)) * 0.18;
var outer = dom.parentElement;
iSlider.setStyle(outer, 'perspective', scale * 4);
dom.style.zIndex = i === 1 ? 1 : 0;
iSlider.setStyle(dom, 'transform', 'scale(' + zoomScale + ') translateZ(0) translate' + axis + '(' + (offset + 1.3 * scale * (i - 1)) + 'px)');
} | More animations
@file animate.js
@author BE-FE Team
xieyu33333 [email protected]
shinate [email protected] | depth | javascript | be-fe/iSlider | build/iSlider.animate.js | https://github.com/be-fe/iSlider/blob/master/build/iSlider.animate.js | MIT |
function flow(dom, axis, scale, i, offset, direct) {
var absoluteOffset = Math.abs(offset);
var rotateDirect = (axis === 'X') ? 'Y' : 'X';
var directAmend = (axis === 'X') ? 1 : -1;
var offsetRatio = Math.abs(offset / scale);
var outer = dom.parentElement;
iSlider.setStyle(outer, 'perspective', scale * 4);
if (i === 1) {
dom.style.zIndex = scale - absoluteOffset;
}
else {
dom.style.zIndex = (offset > 0) ? (1 - i) * absoluteOffset : (i - 1) * absoluteOffset;
}
iSlider.setStyle(dom, 'transform', 'scale(0.7, 0.7) translateZ(' + (offsetRatio * 150 - 150) * Math.abs(i - 1) + 'px)' + 'translate' + axis + '(' + (offset + scale * (i - 1)) + 'px)' + 'rotate' + rotateDirect + '(' + directAmend * (30 - offsetRatio * 30) * (1 - i) + 'deg)');
} | More animations
@file animate.js
@author BE-FE Team
xieyu33333 [email protected]
shinate [email protected] | flow | javascript | be-fe/iSlider | build/iSlider.animate.js | https://github.com/be-fe/iSlider/blob/master/build/iSlider.animate.js | MIT |
function card(dom, axis, scale, i, offset, direct) {
var absoluteOffset = Math.abs(offset);
var zoomScale = 1;
var z = 1;
if (absoluteOffset > 0) {
if (i === 1) {
zoomScale = 1 - 0.2 * Math.abs(i - 1) - Math.abs(0.2 * offset / scale).toFixed(6);
z = 0;
}
} else {
if (i !== 1) {
if ((direct > 0 && i === 0) || (direct < 0 && i === 2)) {
zoomScale = 1 - 0.2 * Math.abs(i - 1);
}
z = 0;
}
}
dom.style.zIndex = z;
iSlider.setStyle(dom, 'transform', 'scale(' + zoomScale + ') translateZ(0) translate' + axis + '(' + ((1 + Math.abs(i - 1) * 0.2) * offset + scale * (i - 1)) + 'px)');
} | More animations
@file animate.js
@author BE-FE Team
xieyu33333 [email protected]
shinate [email protected] | card | javascript | be-fe/iSlider | build/iSlider.animate.js | https://github.com/be-fe/iSlider/blob/master/build/iSlider.animate.js | MIT |
function fade(dom, axis, scale, i, offset, direct) {
dom.style.zIndex = i === 1 ? 1 : 0;
offset = Math.abs(offset);
if (i === 1) {
dom.style.opacity = 1 - (offset / scale);
} else {
dom.style.opacity = offset / scale;
}
} | More animations
@file animate.js
@author BE-FE Team
xieyu33333 [email protected]
shinate [email protected] | fade | javascript | be-fe/iSlider | build/iSlider.animate.js | https://github.com/be-fe/iSlider/blob/master/build/iSlider.animate.js | MIT |
function zoomout(dom, axis, scale, i, offset) {
var z, o, s;
var oa = offset / scale;
switch (i) {
case 0:
lsn && window.clearTimeout(lsn);
o = oa < 1 ? oa : 1;
s = 2 - (0.5 * oa);
z = 2;
var at = parseInt(window.getComputedStyle(dom)[iSlider.styleProp('transitionDuration', 1)]) * 1000;
if (at > 0) {
lsn = window.setTimeout(function () {
dom.style.zIndex = 0;
}, at);
}
break;
case 1:
o = 1 - oa;
s = 1 - (0.5 * oa);
z = 1;
break;
case 2:
o = oa > 0 ? oa : 0;
s = 0.5 - (0.5 * oa);
z = 0;
break;
}
dom.style.cssText += 'z-index:' + z + ';opacity:' + o + ';' + iSlider.styleProp('transform') + ':scale(' + s + ');';
} | More animations
@file animate.js
@author BE-FE Team
xieyu33333 [email protected]
shinate [email protected] | zoomout | javascript | be-fe/iSlider | build/iSlider.animate.js | https://github.com/be-fe/iSlider/blob/master/build/iSlider.animate.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.