code
stringlengths 28
313k
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
74
| language
stringclasses 1
value | repo
stringlengths 5
60
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
function Toast(options) {
_classCallCheck(this, Toast);
/**
* Options for the toast
* @member Toast#options
*/
this.options = $.extend({}, Toast.defaults, options);
this.message = this.options.html;
/**
* Describes current pan state toast
* @type {Boolean}
*/
this.panning = false;
/**
* Time remaining until toast is removed
*/
this.timeRemaining = this.options.displayLength;
if (Toast._toasts.length === 0) {
Toast._createContainer();
}
// Create new toast
Toast._toasts.push(this);
var toastElement = this._createToast();
toastElement.M_Toast = this;
this.el = toastElement;
this.$el = $(toastElement);
this._animateIn();
this._setTimer();
}
|
Attach Waves to an input element (or any element which doesn't
bubble mouseup/mousedown events).
Intended to be used with dynamically loaded forms/inputs, or
where the user doesn't want a delegated click handler.
|
Toast
|
javascript
|
Dogfalo/materialize
|
dist/js/materialize.js
|
https://github.com/Dogfalo/materialize/blob/master/dist/js/materialize.js
|
MIT
|
function Sidenav(el, options) {
_classCallCheck(this, Sidenav);
var _this31 = _possibleConstructorReturn(this, (Sidenav.__proto__ || Object.getPrototypeOf(Sidenav)).call(this, Sidenav, el, options));
_this31.el.M_Sidenav = _this31;
_this31.id = _this31.$el.attr('id');
/**
* Options for the Sidenav
* @member Sidenav#options
* @prop {String} [edge='left'] - Side of screen on which Sidenav appears
* @prop {Boolean} [draggable=true] - Allow swipe gestures to open/close Sidenav
* @prop {Number} [inDuration=250] - Length in ms of enter transition
* @prop {Number} [outDuration=200] - Length in ms of exit transition
* @prop {Function} onOpenStart - Function called when sidenav starts entering
* @prop {Function} onOpenEnd - Function called when sidenav finishes entering
* @prop {Function} onCloseStart - Function called when sidenav starts exiting
* @prop {Function} onCloseEnd - Function called when sidenav finishes exiting
*/
_this31.options = $.extend({}, Sidenav.defaults, options);
/**
* Describes open/close state of Sidenav
* @type {Boolean}
*/
_this31.isOpen = false;
/**
* Describes if Sidenav is fixed
* @type {Boolean}
*/
_this31.isFixed = _this31.el.classList.contains('sidenav-fixed');
/**
* Describes if Sidenav is being draggeed
* @type {Boolean}
*/
_this31.isDragged = false;
// Window size variables for window resize checks
_this31.lastWindowWidth = window.innerWidth;
_this31.lastWindowHeight = window.innerHeight;
_this31._createOverlay();
_this31._createDragTarget();
_this31._setupEventHandlers();
_this31._setupClasses();
_this31._setupFixed();
Sidenav._sidenavs.push(_this31);
return _this31;
}
|
Construct Sidenav instance and set up overlay
@constructor
@param {Element} el
@param {Object} options
|
Sidenav
|
javascript
|
Dogfalo/materialize
|
dist/js/materialize.js
|
https://github.com/Dogfalo/materialize/blob/master/dist/js/materialize.js
|
MIT
|
function ScrollSpy(el, options) {
_classCallCheck(this, ScrollSpy);
var _this35 = _possibleConstructorReturn(this, (ScrollSpy.__proto__ || Object.getPrototypeOf(ScrollSpy)).call(this, ScrollSpy, el, options));
_this35.el.M_ScrollSpy = _this35;
/**
* Options for the modal
* @member Modal#options
* @prop {Number} [throttle=100] - Throttle of scroll handler
* @prop {Number} [scrollOffset=200] - Offset for centering element when scrolled to
* @prop {String} [activeClass='active'] - Class applied to active elements
* @prop {Function} [getActiveElement] - Used to find active element
*/
_this35.options = $.extend({}, ScrollSpy.defaults, options);
// setup
ScrollSpy._elements.push(_this35);
ScrollSpy._count++;
ScrollSpy._increment++;
_this35.tickId = -1;
_this35.id = ScrollSpy._increment;
_this35._setupEventHandlers();
_this35._handleWindowScroll();
return _this35;
}
|
Construct ScrollSpy instance
@constructor
@param {Element} el
@param {Object} options
|
ScrollSpy
|
javascript
|
Dogfalo/materialize
|
dist/js/materialize.js
|
https://github.com/Dogfalo/materialize/blob/master/dist/js/materialize.js
|
MIT
|
function Autocomplete(el, options) {
_classCallCheck(this, Autocomplete);
var _this37 = _possibleConstructorReturn(this, (Autocomplete.__proto__ || Object.getPrototypeOf(Autocomplete)).call(this, Autocomplete, el, options));
_this37.el.M_Autocomplete = _this37;
/**
* Options for the autocomplete
* @member Autocomplete#options
* @prop {Number} duration
* @prop {Number} dist
* @prop {number} shift
* @prop {number} padding
* @prop {Boolean} fullWidth
* @prop {Boolean} indicators
* @prop {Boolean} noWrap
* @prop {Function} onCycleTo
*/
_this37.options = $.extend({}, Autocomplete.defaults, options);
// Setup
_this37.isOpen = false;
_this37.count = 0;
_this37.activeIndex = -1;
_this37.oldVal;
_this37.$inputField = _this37.$el.closest('.input-field');
_this37.$active = $();
_this37._mousedown = false;
_this37._setupDropdown();
_this37._setupEventHandlers();
return _this37;
}
|
Construct Autocomplete instance
@constructor
@param {Element} el
@param {Object} options
|
Autocomplete
|
javascript
|
Dogfalo/materialize
|
dist/js/materialize.js
|
https://github.com/Dogfalo/materialize/blob/master/dist/js/materialize.js
|
MIT
|
sortFunctionBound = function (a, b) {
return _this39.options.sortFunction(a.key.toLowerCase(), b.key.toLowerCase(), val.toLowerCase());
}
|
Render dropdown content
@param {Object} data data set
@param {String} val current input value
|
sortFunctionBound
|
javascript
|
Dogfalo/materialize
|
dist/js/materialize.js
|
https://github.com/Dogfalo/materialize/blob/master/dist/js/materialize.js
|
MIT
|
function Slider(el, options) {
_classCallCheck(this, Slider);
var _this40 = _possibleConstructorReturn(this, (Slider.__proto__ || Object.getPrototypeOf(Slider)).call(this, Slider, el, options));
_this40.el.M_Slider = _this40;
/**
* Options for the modal
* @member Slider#options
* @prop {Boolean} [indicators=true] - Show indicators
* @prop {Number} [height=400] - height of slider
* @prop {Number} [duration=500] - Length in ms of slide transition
* @prop {Number} [interval=6000] - Length in ms of slide interval
*/
_this40.options = $.extend({}, Slider.defaults, options);
// setup
_this40.$slider = _this40.$el.find('.slides');
_this40.$slides = _this40.$slider.children('li');
_this40.activeIndex = _this40.$slides.filter(function (item) {
return $(item).hasClass('active');
}).first().index();
if (_this40.activeIndex != -1) {
_this40.$active = _this40.$slides.eq(_this40.activeIndex);
}
_this40._setSliderHeight();
// Set initial positions of captions
_this40.$slides.find('.caption').each(function (el) {
_this40._animateCaptionIn(el, 0);
});
// Move img src into background-image
_this40.$slides.find('img').each(function (el) {
var placeholderBase64 = 'data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
if ($(el).attr('src') !== placeholderBase64) {
$(el).css('background-image', 'url("' + $(el).attr('src') + '")');
$(el).attr('src', placeholderBase64);
}
});
_this40._setupIndicators();
// Show active slide
if (_this40.$active) {
_this40.$active.css('display', 'block');
} else {
_this40.$slides.first().addClass('active');
anim({
targets: _this40.$slides.first()[0],
opacity: 1,
duration: _this40.options.duration,
easing: 'easeOutQuad'
});
_this40.activeIndex = 0;
_this40.$active = _this40.$slides.eq(_this40.activeIndex);
// Update indicators
if (_this40.options.indicators) {
_this40.$indicators.eq(_this40.activeIndex).addClass('active');
}
}
// Adjust height to current slide
_this40.$active.find('img').each(function (el) {
anim({
targets: _this40.$active.find('.caption')[0],
opacity: 1,
translateX: 0,
translateY: 0,
duration: _this40.options.duration,
easing: 'easeOutQuad'
});
});
_this40._setupEventHandlers();
// auto scroll
_this40.start();
return _this40;
}
|
Construct Slider instance and set up overlay
@constructor
@param {Element} el
@param {Object} options
|
Slider
|
javascript
|
Dogfalo/materialize
|
dist/js/materialize.js
|
https://github.com/Dogfalo/materialize/blob/master/dist/js/materialize.js
|
MIT
|
function Chips(el, options) {
_classCallCheck(this, Chips);
var _this45 = _possibleConstructorReturn(this, (Chips.__proto__ || Object.getPrototypeOf(Chips)).call(this, Chips, el, options));
_this45.el.M_Chips = _this45;
/**
* Options for the modal
* @member Chips#options
* @prop {Array} data
* @prop {String} placeholder
* @prop {String} secondaryPlaceholder
* @prop {Object} autocompleteOptions
*/
_this45.options = $.extend({}, Chips.defaults, options);
_this45.$el.addClass('chips input-field');
_this45.chipsData = [];
_this45.$chips = $();
_this45._setupInput();
_this45.hasAutocomplete = Object.keys(_this45.options.autocompleteOptions).length > 0;
// Set input id
if (!_this45.$input.attr('id')) {
_this45.$input.attr('id', M.guid());
}
// Render initial chips
if (_this45.options.data.length) {
_this45.chipsData = _this45.options.data;
_this45._renderChips(_this45.chipsData);
}
// Setup autocomplete if needed
if (_this45.hasAutocomplete) {
_this45._setupAutocomplete();
}
_this45._setPlaceholder();
_this45._setupLabel();
_this45._setupEventHandlers();
return _this45;
}
|
Construct Chips instance and set up overlay
@constructor
@param {Element} el
@param {Object} options
|
Chips
|
javascript
|
Dogfalo/materialize
|
dist/js/materialize.js
|
https://github.com/Dogfalo/materialize/blob/master/dist/js/materialize.js
|
MIT
|
function Pushpin(el, options) {
_classCallCheck(this, Pushpin);
var _this47 = _possibleConstructorReturn(this, (Pushpin.__proto__ || Object.getPrototypeOf(Pushpin)).call(this, Pushpin, el, options));
_this47.el.M_Pushpin = _this47;
/**
* Options for the modal
* @member Pushpin#options
*/
_this47.options = $.extend({}, Pushpin.defaults, options);
_this47.originalOffset = _this47.el.offsetTop;
Pushpin._pushpins.push(_this47);
_this47._setupEventHandlers();
_this47._updatePosition();
return _this47;
}
|
Construct Pushpin instance
@constructor
@param {Element} el
@param {Object} options
|
Pushpin
|
javascript
|
Dogfalo/materialize
|
dist/js/materialize.js
|
https://github.com/Dogfalo/materialize/blob/master/dist/js/materialize.js
|
MIT
|
function FloatingActionButton(el, options) {
_classCallCheck(this, FloatingActionButton);
var _this48 = _possibleConstructorReturn(this, (FloatingActionButton.__proto__ || Object.getPrototypeOf(FloatingActionButton)).call(this, FloatingActionButton, el, options));
_this48.el.M_FloatingActionButton = _this48;
/**
* Options for the fab
* @member FloatingActionButton#options
* @prop {Boolean} [direction] - Direction fab menu opens
* @prop {Boolean} [hoverEnabled=true] - Enable hover vs click
* @prop {Boolean} [toolbarEnabled=false] - Enable toolbar transition
*/
_this48.options = $.extend({}, FloatingActionButton.defaults, options);
_this48.isOpen = false;
_this48.$anchor = _this48.$el.children('a').first();
_this48.$menu = _this48.$el.children('ul').first();
_this48.$floatingBtns = _this48.$el.find('ul .btn-floating');
_this48.$floatingBtnsReverse = _this48.$el.find('ul .btn-floating').reverse();
_this48.offsetY = 0;
_this48.offsetX = 0;
_this48.$el.addClass("direction-" + _this48.options.direction);
if (_this48.options.direction === 'top') {
_this48.offsetY = 40;
} else if (_this48.options.direction === 'right') {
_this48.offsetX = -40;
} else if (_this48.options.direction === 'bottom') {
_this48.offsetY = -40;
} else {
_this48.offsetX = 40;
}
_this48._setupEventHandlers();
return _this48;
}
|
Construct FloatingActionButton instance
@constructor
@param {Element} el
@param {Object} options
|
FloatingActionButton
|
javascript
|
Dogfalo/materialize
|
dist/js/materialize.js
|
https://github.com/Dogfalo/materialize/blob/master/dist/js/materialize.js
|
MIT
|
function Datepicker(el, options) {
_classCallCheck(this, Datepicker);
var _this53 = _possibleConstructorReturn(this, (Datepicker.__proto__ || Object.getPrototypeOf(Datepicker)).call(this, Datepicker, el, options));
_this53.el.M_Datepicker = _this53;
_this53.options = $.extend({}, Datepicker.defaults, options);
// make sure i18n defaults are not lost when only few i18n option properties are passed
if (!!options && options.hasOwnProperty('i18n') && typeof options.i18n === 'object') {
_this53.options.i18n = $.extend({}, Datepicker.defaults.i18n, options.i18n);
}
// Remove time component from minDate and maxDate options
if (_this53.options.minDate) _this53.options.minDate.setHours(0, 0, 0, 0);
if (_this53.options.maxDate) _this53.options.maxDate.setHours(0, 0, 0, 0);
_this53.id = M.guid();
_this53._setupVariables();
_this53._insertHTMLIntoDOM();
_this53._setupModal();
_this53._setupEventHandlers();
if (!_this53.options.defaultDate) {
_this53.options.defaultDate = new Date(Date.parse(_this53.el.value));
}
var defDate = _this53.options.defaultDate;
if (Datepicker._isDate(defDate)) {
if (_this53.options.setDefaultDate) {
_this53.setDate(defDate, true);
_this53.setInputValue();
} else {
_this53.gotoDate(defDate);
}
} else {
_this53.gotoDate(new Date());
}
/**
* Describes open/close state of datepicker
* @type {Boolean}
*/
_this53.isOpen = false;
return _this53;
}
|
Construct Datepicker instance and set up overlay
@constructor
@param {Element} el
@param {Object} options
|
Datepicker
|
javascript
|
Dogfalo/materialize
|
dist/js/materialize.js
|
https://github.com/Dogfalo/materialize/blob/master/dist/js/materialize.js
|
MIT
|
function CharacterCounter(el, options) {
_classCallCheck(this, CharacterCounter);
var _this61 = _possibleConstructorReturn(this, (CharacterCounter.__proto__ || Object.getPrototypeOf(CharacterCounter)).call(this, CharacterCounter, el, options));
_this61.el.M_CharacterCounter = _this61;
/**
* Options for the character counter
*/
_this61.options = $.extend({}, CharacterCounter.defaults, options);
_this61.isInvalid = false;
_this61.isValidLength = false;
_this61._setupCounter();
_this61._setupEventHandlers();
return _this61;
}
|
Construct CharacterCounter instance
@constructor
@param {Element} el
@param {Object} options
|
CharacterCounter
|
javascript
|
Dogfalo/materialize
|
dist/js/materialize.js
|
https://github.com/Dogfalo/materialize/blob/master/dist/js/materialize.js
|
MIT
|
function Carousel(el, options) {
_classCallCheck(this, Carousel);
var _this62 = _possibleConstructorReturn(this, (Carousel.__proto__ || Object.getPrototypeOf(Carousel)).call(this, Carousel, el, options));
_this62.el.M_Carousel = _this62;
/**
* Options for the carousel
* @member Carousel#options
* @prop {Number} duration
* @prop {Number} dist
* @prop {Number} shift
* @prop {Number} padding
* @prop {Number} numVisible
* @prop {Boolean} fullWidth
* @prop {Boolean} indicators
* @prop {Boolean} noWrap
* @prop {Function} onCycleTo
*/
_this62.options = $.extend({}, Carousel.defaults, options);
// Setup
_this62.hasMultipleSlides = _this62.$el.find('.carousel-item').length > 1;
_this62.showIndicators = _this62.options.indicators && _this62.hasMultipleSlides;
_this62.noWrap = _this62.options.noWrap || !_this62.hasMultipleSlides;
_this62.pressed = false;
_this62.dragged = false;
_this62.offset = _this62.target = 0;
_this62.images = [];
_this62.itemWidth = _this62.$el.find('.carousel-item').first().innerWidth();
_this62.itemHeight = _this62.$el.find('.carousel-item').first().innerHeight();
_this62.dim = _this62.itemWidth * 2 + _this62.options.padding || 1; // Make sure dim is non zero for divisions.
_this62._autoScrollBound = _this62._autoScroll.bind(_this62);
_this62._trackBound = _this62._track.bind(_this62);
// Full Width carousel setup
if (_this62.options.fullWidth) {
_this62.options.dist = 0;
_this62._setCarouselHeight();
// Offset fixed items when indicators.
if (_this62.showIndicators) {
_this62.$el.find('.carousel-fixed-item').addClass('with-indicators');
}
}
// Iterate through slides
_this62.$indicators = $('<ul class="indicators"></ul>');
_this62.$el.find('.carousel-item').each(function (el, i) {
_this62.images.push(el);
if (_this62.showIndicators) {
var $indicator = $('<li class="indicator-item"></li>');
// Add active to first by default.
if (i === 0) {
$indicator[0].classList.add('active');
}
_this62.$indicators.append($indicator);
}
});
if (_this62.showIndicators) {
_this62.$el.append(_this62.$indicators);
}
_this62.count = _this62.images.length;
// Cap numVisible at count
_this62.options.numVisible = Math.min(_this62.count, _this62.options.numVisible);
// Setup cross browser string
_this62.xform = 'transform';
['webkit', 'Moz', 'O', 'ms'].every(function (prefix) {
var e = prefix + 'Transform';
if (typeof document.body.style[e] !== 'undefined') {
_this62.xform = e;
return false;
}
return true;
});
_this62._setupEventHandlers();
_this62._scroll(_this62.offset);
return _this62;
}
|
Construct Carousel instance
@constructor
@param {Element} el
@param {Object} options
|
Carousel
|
javascript
|
Dogfalo/materialize
|
dist/js/materialize.js
|
https://github.com/Dogfalo/materialize/blob/master/dist/js/materialize.js
|
MIT
|
function TapTarget(el, options) {
_classCallCheck(this, TapTarget);
var _this67 = _possibleConstructorReturn(this, (TapTarget.__proto__ || Object.getPrototypeOf(TapTarget)).call(this, TapTarget, el, options));
_this67.el.M_TapTarget = _this67;
/**
* Options for the select
* @member TapTarget#options
* @prop {Function} onOpen - Callback function called when feature discovery is opened
* @prop {Function} onClose - Callback function called when feature discovery is closed
*/
_this67.options = $.extend({}, TapTarget.defaults, options);
_this67.isOpen = false;
// setup
_this67.$origin = $('#' + _this67.$el.attr('data-target'));
_this67._setup();
_this67._calculatePositioning();
_this67._setupEventHandlers();
return _this67;
}
|
Construct TapTarget instance
@constructor
@param {Element} el
@param {Object} options
|
TapTarget
|
javascript
|
Dogfalo/materialize
|
dist/js/materialize.js
|
https://github.com/Dogfalo/materialize/blob/master/dist/js/materialize.js
|
MIT
|
function FormSelect(el, options) {
_classCallCheck(this, FormSelect);
// Don't init if browser default version
var _this68 = _possibleConstructorReturn(this, (FormSelect.__proto__ || Object.getPrototypeOf(FormSelect)).call(this, FormSelect, el, options));
if (_this68.$el.hasClass('browser-default')) {
return _possibleConstructorReturn(_this68);
}
_this68.el.M_FormSelect = _this68;
/**
* Options for the select
* @member FormSelect#options
*/
_this68.options = $.extend({}, FormSelect.defaults, options);
_this68.isMultiple = _this68.$el.prop('multiple');
// Setup
_this68.el.tabIndex = -1;
_this68._keysSelected = {};
_this68._valueDict = {}; // Maps key to original and generated option element.
_this68._setupDropdown();
_this68._setupEventHandlers();
return _this68;
}
|
Construct FormSelect instance
@constructor
@param {Element} el
@param {Object} options
|
FormSelect
|
javascript
|
Dogfalo/materialize
|
dist/js/materialize.js
|
https://github.com/Dogfalo/materialize/blob/master/dist/js/materialize.js
|
MIT
|
function Range(el, options) {
_classCallCheck(this, Range);
var _this72 = _possibleConstructorReturn(this, (Range.__proto__ || Object.getPrototypeOf(Range)).call(this, Range, el, options));
_this72.el.M_Range = _this72;
/**
* Options for the range
* @member Range#options
*/
_this72.options = $.extend({}, Range.defaults, options);
_this72._mousedown = false;
// Setup
_this72._setupThumb();
_this72._setupEventHandlers();
return _this72;
}
|
Construct Range instance
@constructor
@param {Element} el
@param {Object} options
|
Range
|
javascript
|
Dogfalo/materialize
|
dist/js/materialize.js
|
https://github.com/Dogfalo/materialize/blob/master/dist/js/materialize.js
|
MIT
|
static get defaults() {
return _defaults;
}
|
Options for the autocomplete
@member Autocomplete#options
@prop {Number} duration
@prop {Number} dist
@prop {number} shift
@prop {number} padding
@prop {Boolean} fullWidth
@prop {Boolean} indicators
@prop {Boolean} noWrap
@prop {Function} onCycleTo
|
defaults
|
javascript
|
Dogfalo/materialize
|
js/autocomplete.js
|
https://github.com/Dogfalo/materialize/blob/master/js/autocomplete.js
|
MIT
|
_handleInputKeyupAndFocus(e) {
if (e.type === 'keyup') {
Autocomplete._keydown = false;
}
this.count = 0;
let val = this.el.value.toLowerCase();
// Don't capture enter or arrow key usage.
if (e.keyCode === 13 || e.keyCode === 38 || e.keyCode === 40) {
return;
}
// Check if the input isn't empty
// Check if focus triggered by tab
if (this.oldVal !== val && (M.tabPressed || e.type !== 'focus')) {
this.open();
}
// Update oldVal
this.oldVal = val;
}
|
Handle Input Keyup and Focus
@param {Event} e
|
_handleInputKeyupAndFocus
|
javascript
|
Dogfalo/materialize
|
js/autocomplete.js
|
https://github.com/Dogfalo/materialize/blob/master/js/autocomplete.js
|
MIT
|
_handleContainerMousedownAndTouchstart(e) {
this._mousedown = true;
}
|
Handle Container Mousedown and Touchstart
@param {Event} e
|
_handleContainerMousedownAndTouchstart
|
javascript
|
Dogfalo/materialize
|
js/autocomplete.js
|
https://github.com/Dogfalo/materialize/blob/master/js/autocomplete.js
|
MIT
|
_handleContainerMouseupAndTouchend(e) {
this._mousedown = false;
}
|
Handle Container Mouseup and Touchend
@param {Event} e
|
_handleContainerMouseupAndTouchend
|
javascript
|
Dogfalo/materialize
|
js/autocomplete.js
|
https://github.com/Dogfalo/materialize/blob/master/js/autocomplete.js
|
MIT
|
selectOption(el) {
let text = el.text().trim();
this.el.value = text;
this.$el.trigger('change');
this._resetAutocomplete();
this.close();
// Handle onAutocomplete callback.
if (typeof this.options.onAutocomplete === 'function') {
this.options.onAutocomplete.call(this, text);
}
}
|
Select autocomplete option
@param {Element} el Autocomplete option list item element
|
selectOption
|
javascript
|
Dogfalo/materialize
|
js/autocomplete.js
|
https://github.com/Dogfalo/materialize/blob/master/js/autocomplete.js
|
MIT
|
static init(els, options) {
return super.init(this, els, options);
}
|
Options for the fab
@member FloatingActionButton#options
@prop {Boolean} [direction] - Direction fab menu opens
@prop {Boolean} [hoverEnabled=true] - Enable hover vs click
@prop {Boolean} [toolbarEnabled=false] - Enable toolbar transition
|
init
|
javascript
|
Dogfalo/materialize
|
js/buttons.js
|
https://github.com/Dogfalo/materialize/blob/master/js/buttons.js
|
MIT
|
_setCarouselHeight(imageOnly) {
let firstSlide = this.$el.find('.carousel-item.active').length
? this.$el.find('.carousel-item.active').first()
: this.$el.find('.carousel-item').first();
let firstImage = firstSlide.find('img').first();
if (firstImage.length) {
if (firstImage[0].complete) {
// If image won't trigger the load event
let imageHeight = firstImage.height();
if (imageHeight > 0) {
this.$el.css('height', imageHeight + 'px');
} else {
// If image still has no height, use the natural dimensions to calculate
let naturalWidth = firstImage[0].naturalWidth;
let naturalHeight = firstImage[0].naturalHeight;
let adjustedHeight = this.$el.width() / naturalWidth * naturalHeight;
this.$el.css('height', adjustedHeight + 'px');
}
} else {
// Get height when image is loaded normally
firstImage.one('load', (el, i) => {
this.$el.css('height', el.offsetHeight + 'px');
});
}
} else if (!imageOnly) {
let slideHeight = firstSlide.height();
this.$el.css('height', slideHeight + 'px');
}
}
|
Set carousel height based on first slide
@param {Booleam} imageOnly - true for image slides
|
_setCarouselHeight
|
javascript
|
Dogfalo/materialize
|
js/carousel.js
|
https://github.com/Dogfalo/materialize/blob/master/js/carousel.js
|
MIT
|
_xpos(e) {
// touch event
if (e.targetTouches && e.targetTouches.length >= 1) {
return e.targetTouches[0].clientX;
}
// mouse event
return e.clientX;
}
|
Get x position from event
@param {Event} e
|
_xpos
|
javascript
|
Dogfalo/materialize
|
js/carousel.js
|
https://github.com/Dogfalo/materialize/blob/master/js/carousel.js
|
MIT
|
_ypos(e) {
// touch event
if (e.targetTouches && e.targetTouches.length >= 1) {
return e.targetTouches[0].clientY;
}
// mouse event
return e.clientY;
}
|
Get y position from event
@param {Event} e
|
_ypos
|
javascript
|
Dogfalo/materialize
|
js/carousel.js
|
https://github.com/Dogfalo/materialize/blob/master/js/carousel.js
|
MIT
|
_autoScroll() {
let elapsed, delta;
if (this.amplitude) {
elapsed = Date.now() - this.timestamp;
delta = this.amplitude * Math.exp(-elapsed / this.options.duration);
if (delta > 2 || delta < -2) {
this._scroll(this.target - delta);
requestAnimationFrame(this._autoScrollBound);
} else {
this._scroll(this.target);
}
}
}
|
Auto scrolls to nearest carousel item.
|
_autoScroll
|
javascript
|
Dogfalo/materialize
|
js/carousel.js
|
https://github.com/Dogfalo/materialize/blob/master/js/carousel.js
|
MIT
|
_updateItemStyle(el, opacity, zIndex, transform) {
el.style[this.xform] = transform;
el.style.zIndex = zIndex;
el.style.opacity = opacity;
el.style.visibility = 'visible';
}
|
Cycle to target
@param {Element} el
@param {Number} opacity
@param {Number} zIndex
@param {String} transform
|
_updateItemStyle
|
javascript
|
Dogfalo/materialize
|
js/carousel.js
|
https://github.com/Dogfalo/materialize/blob/master/js/carousel.js
|
MIT
|
_cycleTo(n, callback) {
let diff = this.center % this.count - n;
// Account for wraparound.
if (!this.noWrap) {
if (diff < 0) {
if (Math.abs(diff + this.count) < Math.abs(diff)) {
diff += this.count;
}
} else if (diff > 0) {
if (Math.abs(diff - this.count) < diff) {
diff -= this.count;
}
}
}
this.target = this.dim * Math.round(this.offset / this.dim);
// Next
if (diff < 0) {
this.target += this.dim * Math.abs(diff);
// Prev
} else if (diff > 0) {
this.target -= this.dim * diff;
}
// Set one time callback
if (typeof callback === 'function') {
this.oneTimeCallback = callback;
}
// Scroll
if (this.offset !== this.target) {
this.amplitude = this.target - this.offset;
this.timestamp = Date.now();
requestAnimationFrame(this._autoScrollBound);
}
}
|
Cycle to target
@param {Number} n
@param {Function} callback
|
_cycleTo
|
javascript
|
Dogfalo/materialize
|
js/carousel.js
|
https://github.com/Dogfalo/materialize/blob/master/js/carousel.js
|
MIT
|
next(n) {
if (n === undefined || isNaN(n)) {
n = 1;
}
let index = this.center + n;
if (index >= this.count || index < 0) {
if (this.noWrap) {
return;
}
index = this._wrap(index);
}
this._cycleTo(index);
}
|
Cycle to next item
@param {Number} [n]
|
next
|
javascript
|
Dogfalo/materialize
|
js/carousel.js
|
https://github.com/Dogfalo/materialize/blob/master/js/carousel.js
|
MIT
|
prev(n) {
if (n === undefined || isNaN(n)) {
n = 1;
}
let index = this.center - n;
if (index >= this.count || index < 0) {
if (this.noWrap) {
return;
}
index = this._wrap(index);
}
this._cycleTo(index);
}
|
Cycle to previous item
@param {Number} [n]
|
prev
|
javascript
|
Dogfalo/materialize
|
js/carousel.js
|
https://github.com/Dogfalo/materialize/blob/master/js/carousel.js
|
MIT
|
set(n, callback) {
if (n === undefined || isNaN(n)) {
n = 0;
}
if (n > this.count || n < 0) {
if (this.noWrap) {
return;
}
n = this._wrap(n);
}
this._cycleTo(n, callback);
}
|
Cycle to nth item
@param {Number} [n]
@param {Function} callback
|
set
|
javascript
|
Dogfalo/materialize
|
js/carousel.js
|
https://github.com/Dogfalo/materialize/blob/master/js/carousel.js
|
MIT
|
_renderChip(chip) {
if (!chip.tag) {
return;
}
let renderedChip = document.createElement('div');
let closeIcon = document.createElement('i');
renderedChip.classList.add('chip');
renderedChip.textContent = chip.tag;
renderedChip.setAttribute('tabindex', 0);
$(closeIcon).addClass('material-icons close');
closeIcon.textContent = 'close';
// attach image if needed
if (chip.image) {
let img = document.createElement('img');
img.setAttribute('src', chip.image);
renderedChip.insertBefore(img, renderedChip.firstChild);
}
renderedChip.appendChild(closeIcon);
return renderedChip;
}
|
Render Chip
@param {chip} chip
@return {Element}
|
_renderChip
|
javascript
|
Dogfalo/materialize
|
js/chips.js
|
https://github.com/Dogfalo/materialize/blob/master/js/chips.js
|
MIT
|
_isValid(chip) {
if (chip.hasOwnProperty('tag') && chip.tag !== '') {
let exists = false;
for (let i = 0; i < this.chipsData.length; i++) {
if (this.chipsData[i].tag === chip.tag) {
exists = true;
break;
}
}
return !exists;
}
return false;
}
|
Check if chip is valid
@param {chip} chip
|
_isValid
|
javascript
|
Dogfalo/materialize
|
js/chips.js
|
https://github.com/Dogfalo/materialize/blob/master/js/chips.js
|
MIT
|
_animateIn(index) {
let $collapsibleLi = this.$el.children('li').eq(index);
if ($collapsibleLi.length) {
let $body = $collapsibleLi.children('.collapsible-body');
anim.remove($body[0]);
$body.css({
display: 'block',
overflow: 'hidden',
height: 0,
paddingTop: '',
paddingBottom: ''
});
let pTop = $body.css('padding-top');
let pBottom = $body.css('padding-bottom');
let finalHeight = $body[0].scrollHeight;
$body.css({
paddingTop: 0,
paddingBottom: 0
});
anim({
targets: $body[0],
height: finalHeight,
paddingTop: pTop,
paddingBottom: pBottom,
duration: this.options.inDuration,
easing: 'easeInOutCubic',
complete: (anim) => {
$body.css({
overflow: '',
paddingTop: '',
paddingBottom: '',
height: ''
});
// onOpenEnd callback
if (typeof this.options.onOpenEnd === 'function') {
this.options.onOpenEnd.call(this, $collapsibleLi[0]);
}
}
});
}
}
|
Animate in collapsible slide
@param {Number} index - 0th index of slide
|
_animateIn
|
javascript
|
Dogfalo/materialize
|
js/collapsible.js
|
https://github.com/Dogfalo/materialize/blob/master/js/collapsible.js
|
MIT
|
_animateOut(index) {
let $collapsibleLi = this.$el.children('li').eq(index);
if ($collapsibleLi.length) {
let $body = $collapsibleLi.children('.collapsible-body');
anim.remove($body[0]);
$body.css('overflow', 'hidden');
anim({
targets: $body[0],
height: 0,
paddingTop: 0,
paddingBottom: 0,
duration: this.options.outDuration,
easing: 'easeInOutCubic',
complete: () => {
$body.css({
height: '',
overflow: '',
padding: '',
display: ''
});
// onCloseEnd callback
if (typeof this.options.onCloseEnd === 'function') {
this.options.onCloseEnd.call(this, $collapsibleLi[0]);
}
}
});
}
}
|
Animate out collapsible slide
@param {Number} index - 0th index of slide to open
|
_animateOut
|
javascript
|
Dogfalo/materialize
|
js/collapsible.js
|
https://github.com/Dogfalo/materialize/blob/master/js/collapsible.js
|
MIT
|
open(index) {
let $collapsibleLi = this.$el.children('li').eq(index);
if ($collapsibleLi.length && !$collapsibleLi[0].classList.contains('active')) {
// onOpenStart callback
if (typeof this.options.onOpenStart === 'function') {
this.options.onOpenStart.call(this, $collapsibleLi[0]);
}
// Handle accordion behavior
if (this.options.accordion) {
let $collapsibleLis = this.$el.children('li');
let $activeLis = this.$el.children('li.active');
$activeLis.each((el) => {
let index = $collapsibleLis.index($(el));
this.close(index);
});
}
// Animate in
$collapsibleLi[0].classList.add('active');
this._animateIn(index);
}
}
|
Open Collapsible
@param {Number} index - 0th index of slide
|
open
|
javascript
|
Dogfalo/materialize
|
js/collapsible.js
|
https://github.com/Dogfalo/materialize/blob/master/js/collapsible.js
|
MIT
|
close(index) {
let $collapsibleLi = this.$el.children('li').eq(index);
if ($collapsibleLi.length && $collapsibleLi[0].classList.contains('active')) {
// onCloseStart callback
if (typeof this.options.onCloseStart === 'function') {
this.options.onCloseStart.call(this, $collapsibleLi[0]);
}
// Animate out
$collapsibleLi[0].classList.remove('active');
this._animateOut(index);
}
}
|
Close Collapsible
@param {Number} index - 0th index of slide
|
close
|
javascript
|
Dogfalo/materialize
|
js/collapsible.js
|
https://github.com/Dogfalo/materialize/blob/master/js/collapsible.js
|
MIT
|
static init(classDef, els, options) {
let instances = null;
if (els instanceof Element) {
instances = new classDef(els, options);
} else if (!!els && (els.jquery || els.cash || els instanceof NodeList)) {
let instancesArr = [];
for (let i = 0; i < els.length; i++) {
instancesArr.push(new classDef(els[i], options));
}
instances = instancesArr;
}
return instances;
}
|
Initializes components
@param {class} classDef
@param {Element | NodeList | jQuery} els
@param {Object} options
|
init
|
javascript
|
Dogfalo/materialize
|
js/component.js
|
https://github.com/Dogfalo/materialize/blob/master/js/component.js
|
MIT
|
static _isDate(obj) {
return /Date/.test(Object.prototype.toString.call(obj)) && !isNaN(obj.getTime());
}
|
Describes open/close state of datepicker
@type {Boolean}
|
_isDate
|
javascript
|
Dogfalo/materialize
|
js/datepicker.js
|
https://github.com/Dogfalo/materialize/blob/master/js/datepicker.js
|
MIT
|
gotoMonth(month) {
if (!isNaN(month)) {
this.calendars[0].month = parseInt(month, 10);
this.adjustCalendars();
}
}
|
change view to a specific month (zero-index, e.g. 0: January)
|
gotoMonth
|
javascript
|
Dogfalo/materialize
|
js/datepicker.js
|
https://github.com/Dogfalo/materialize/blob/master/js/datepicker.js
|
MIT
|
gotoYear(year) {
if (!isNaN(year)) {
this.calendars[0].year = parseInt(year, 10);
this.adjustCalendars();
}
}
|
change view to a specific full year (e.g. "2012")
|
gotoYear
|
javascript
|
Dogfalo/materialize
|
js/datepicker.js
|
https://github.com/Dogfalo/materialize/blob/master/js/datepicker.js
|
MIT
|
_finishSelection() {
this.setInputValue();
this.close();
}
|
Set input value to the selected date and close Datepicker
|
_finishSelection
|
javascript
|
Dogfalo/materialize
|
js/datepicker.js
|
https://github.com/Dogfalo/materialize/blob/master/js/datepicker.js
|
MIT
|
_makeAncestorsOverflowVisible() {
this.ancestorsChanged = $();
let ancestor = this.placeholder[0].parentNode;
while (ancestor !== null && !$(ancestor).is(document)) {
let curr = $(ancestor);
if (curr.css('overflow') !== 'visible') {
curr.css('overflow', 'visible');
if (this.ancestorsChanged === undefined) {
this.ancestorsChanged = curr;
} else {
this.ancestorsChanged = this.ancestorsChanged.add(curr);
}
}
ancestor = ancestor.parentNode;
}
}
|
Find ancestors with overflow: hidden; and make visible
|
_makeAncestorsOverflowVisible
|
javascript
|
Dogfalo/materialize
|
js/materialbox.js
|
https://github.com/Dogfalo/materialize/blob/master/js/materialbox.js
|
MIT
|
_handleModalCloseClick(e) {
let $closeTrigger = $(e.target).closest('.modal-close');
if ($closeTrigger.length) {
this.close();
}
}
|
Handle Modal Close Click
@param {Event} e
|
_handleModalCloseClick
|
javascript
|
Dogfalo/materialize
|
js/modal.js
|
https://github.com/Dogfalo/materialize/blob/master/js/modal.js
|
MIT
|
_handleRangeMousedownTouchstart(e) {
// Set indicator value
$(this.value).html(this.$el.val());
this._mousedown = true;
this.$el.addClass('active');
if (!$(this.thumb).hasClass('active')) {
this._showRangeBubble();
}
if (e.type !== 'input') {
let offsetLeft = this._calcRangeOffset();
$(this.thumb)
.addClass('active')
.css('left', offsetLeft + 'px');
}
}
|
Handle Range Mousedown and Touchstart
@param {Event} e
|
_handleRangeMousedownTouchstart
|
javascript
|
Dogfalo/materialize
|
js/range.js
|
https://github.com/Dogfalo/materialize/blob/master/js/range.js
|
MIT
|
_handleRangeInputMousemoveTouchmove() {
if (this._mousedown) {
if (!$(this.thumb).hasClass('active')) {
this._showRangeBubble();
}
let offsetLeft = this._calcRangeOffset();
$(this.thumb)
.addClass('active')
.css('left', offsetLeft + 'px');
$(this.value).html(this.$el.val());
}
}
|
Handle Range Input, Mousemove and Touchmove
|
_handleRangeInputMousemoveTouchmove
|
javascript
|
Dogfalo/materialize
|
js/range.js
|
https://github.com/Dogfalo/materialize/blob/master/js/range.js
|
MIT
|
_handleRangeBlurMouseoutTouchleave() {
if (!this._mousedown) {
let paddingLeft = parseInt(this.$el.css('padding-left'));
let marginLeft = 7 + paddingLeft + 'px';
if ($(this.thumb).hasClass('active')) {
anim.remove(this.thumb);
anim({
targets: this.thumb,
height: 0,
width: 0,
top: 10,
easing: 'easeOutQuad',
marginLeft: marginLeft,
duration: 100
});
}
$(this.thumb).removeClass('active');
}
}
|
Handle Range Blur, Mouseout and Touchleave
|
_handleRangeBlurMouseoutTouchleave
|
javascript
|
Dogfalo/materialize
|
js/range.js
|
https://github.com/Dogfalo/materialize/blob/master/js/range.js
|
MIT
|
_calcRangeOffset() {
let width = this.$el.width() - 15;
let max = parseFloat(this.$el.attr('max')) || 100; // Range default max
let min = parseFloat(this.$el.attr('min')) || 0; // Range default min
let percent = (parseFloat(this.$el.val()) - min) / (max - min);
return percent * width;
}
|
Calculate the offset of the thumb
@return {Number} offset in pixels
|
_calcRangeOffset
|
javascript
|
Dogfalo/materialize
|
js/range.js
|
https://github.com/Dogfalo/materialize/blob/master/js/range.js
|
MIT
|
static _findElements(top, right, bottom, left) {
let hits = [];
for (let i = 0; i < ScrollSpy._elements.length; i++) {
let scrollspy = ScrollSpy._elements[i];
let currTop = top + scrollspy.options.scrollOffset || 200;
if (scrollspy.$el.height() > 0) {
let elTop = scrollspy.$el.offset().top,
elLeft = scrollspy.$el.offset().left,
elRight = elLeft + scrollspy.$el.width(),
elBottom = elTop + scrollspy.$el.height();
let isIntersect = !(
elLeft > right ||
elRight < left ||
elTop > bottom ||
elBottom < currTop
);
if (isIntersect) {
hits.push(scrollspy);
}
}
}
return hits;
}
|
Find elements that are within the boundary
@param {number} top
@param {number} right
@param {number} bottom
@param {number} left
@return {Array.<ScrollSpy>} A collection of elements
|
_findElements
|
javascript
|
Dogfalo/materialize
|
js/scrollspy.js
|
https://github.com/Dogfalo/materialize/blob/master/js/scrollspy.js
|
MIT
|
_addOptionToValueDict(el, optionEl) {
let index = Object.keys(this._valueDict).length;
let key = this.dropdownOptions.id + index;
let obj = {};
optionEl.id = key;
obj.el = el;
obj.optionEl = optionEl;
this._valueDict[key] = obj;
}
|
Add option to value dict
@param {Element} el original option element
@param {Element} optionEl generated option element
|
_addOptionToValueDict
|
javascript
|
Dogfalo/materialize
|
js/select.js
|
https://github.com/Dogfalo/materialize/blob/master/js/select.js
|
MIT
|
_appendOptionWithIcon(select, option, type) {
// Add disabled attr if disabled
let disabledClass = option.disabled ? 'disabled ' : '';
let optgroupClass = type === 'optgroup-option' ? 'optgroup-option ' : '';
let multipleCheckbox = this.isMultiple
? `<label><input type="checkbox"${disabledClass}"/><span>${option.innerHTML}</span></label>`
: option.innerHTML;
let liEl = $('<li></li>');
let spanEl = $('<span></span>');
spanEl.html(multipleCheckbox);
liEl.addClass(`${disabledClass} ${optgroupClass}`);
liEl.append(spanEl);
// add icons
let iconUrl = option.getAttribute('data-icon');
if (!!iconUrl) {
let imgEl = $(`<img alt="" src="${iconUrl}">`);
liEl.prepend(imgEl);
}
// Check for multiple type.
$(this.dropdownOptions).append(liEl[0]);
return liEl[0];
}
|
Setup dropdown
@param {Element} select select element
@param {Element} option option element from select
@param {String} type
@return {Element} option element added
|
_appendOptionWithIcon
|
javascript
|
Dogfalo/materialize
|
js/select.js
|
https://github.com/Dogfalo/materialize/blob/master/js/select.js
|
MIT
|
_toggleEntryFromArray(key) {
let notAdded = !this._keysSelected.hasOwnProperty(key);
let $optionLi = $(this._valueDict[key].optionEl);
if (notAdded) {
this._keysSelected[key] = true;
} else {
delete this._keysSelected[key];
}
$optionLi.toggleClass('selected', notAdded);
// Set checkbox checked value
$optionLi.find('input[type="checkbox"]').prop('checked', notAdded);
// use notAdded instead of true (to detect if the option is selected or not)
$optionLi.prop('selected', notAdded);
return notAdded;
}
|
Toggle entry from option
@param {String} key Option key
@return {Boolean} if entry was added or removed
|
_toggleEntryFromArray
|
javascript
|
Dogfalo/materialize
|
js/select.js
|
https://github.com/Dogfalo/materialize/blob/master/js/select.js
|
MIT
|
_setSelectedStates() {
this._keysSelected = {};
for (let key in this._valueDict) {
let option = this._valueDict[key];
let optionIsSelected = $(option.el).prop('selected');
$(option.optionEl)
.find('input[type="checkbox"]')
.prop('checked', optionIsSelected);
if (optionIsSelected) {
this._activateOption($(this.dropdownOptions), $(option.optionEl));
this._keysSelected[key] = true;
} else {
$(option.optionEl).removeClass('selected');
}
}
}
|
Set selected state of dropdown to match actual select element
|
_setSelectedStates
|
javascript
|
Dogfalo/materialize
|
js/select.js
|
https://github.com/Dogfalo/materialize/blob/master/js/select.js
|
MIT
|
_activateOption(collection, newOption) {
if (newOption) {
if (!this.isMultiple) {
collection.find('li.selected').removeClass('selected');
}
let option = $(newOption);
option.addClass('selected');
}
}
|
Make option as selected and scroll to selected position
@param {jQuery} collection Select options jQuery element
@param {Element} newOption element of the new option
|
_activateOption
|
javascript
|
Dogfalo/materialize
|
js/select.js
|
https://github.com/Dogfalo/materialize/blob/master/js/select.js
|
MIT
|
getSelectedValues() {
let selectedValues = [];
for (let key in this._keysSelected) {
selectedValues.push(this._valueDict[key].el.value);
}
return selectedValues;
}
|
Get Selected Values
@return {Array} Array of selected values
|
getSelectedValues
|
javascript
|
Dogfalo/materialize
|
js/select.js
|
https://github.com/Dogfalo/materialize/blob/master/js/select.js
|
MIT
|
_startDrag(e) {
let clientX = e.targetTouches[0].clientX;
this.isDragged = true;
this._startingXpos = clientX;
this._xPos = this._startingXpos;
this._time = Date.now();
this._width = this.el.getBoundingClientRect().width;
this._overlay.style.display = 'block';
this._initialScrollTop = this.isOpen ? this.el.scrollTop : M.getDocumentScrollTop();
this._verticallyScrolling = false;
anim.remove(this.el);
anim.remove(this._overlay);
}
|
Set variables needed at the beggining of drag
and stop any current transition.
@param {Event} e
|
_startDrag
|
javascript
|
Dogfalo/materialize
|
js/sidenav.js
|
https://github.com/Dogfalo/materialize/blob/master/js/sidenav.js
|
MIT
|
_dragMoveUpdate(e) {
let clientX = e.targetTouches[0].clientX;
let currentScrollTop = this.isOpen ? this.el.scrollTop : M.getDocumentScrollTop();
this.deltaX = Math.abs(this._xPos - clientX);
this._xPos = clientX;
this.velocityX = this.deltaX / (Date.now() - this._time);
this._time = Date.now();
if (this._initialScrollTop !== currentScrollTop) {
this._verticallyScrolling = true;
}
}
|
Set variables needed at each drag move update tick
@param {Event} e
|
_dragMoveUpdate
|
javascript
|
Dogfalo/materialize
|
js/sidenav.js
|
https://github.com/Dogfalo/materialize/blob/master/js/sidenav.js
|
MIT
|
_handleDragTargetDrag(e) {
// Check if draggable
if (!this.options.draggable || this._isCurrentlyFixed() || this._verticallyScrolling) {
return;
}
// If not being dragged, set initial drag start variables
if (!this.isDragged) {
this._startDrag(e);
}
// Run touchmove updates
this._dragMoveUpdate(e);
// Calculate raw deltaX
let totalDeltaX = this._xPos - this._startingXpos;
// dragDirection is the attempted user drag direction
let dragDirection = totalDeltaX > 0 ? 'right' : 'left';
// Don't allow totalDeltaX to exceed Sidenav width or be dragged in the opposite direction
totalDeltaX = Math.min(this._width, Math.abs(totalDeltaX));
if (this.options.edge === dragDirection) {
totalDeltaX = 0;
}
/**
* transformX is the drag displacement
* transformPrefix is the initial transform placement
* Invert values if Sidenav is right edge
*/
let transformX = totalDeltaX;
let transformPrefix = 'translateX(-100%)';
if (this.options.edge === 'right') {
transformPrefix = 'translateX(100%)';
transformX = -transformX;
}
// Calculate open/close percentage of sidenav, with open = 1 and close = 0
this.percentOpen = Math.min(1, totalDeltaX / this._width);
// Set transform and opacity styles
this.el.style.transform = `${transformPrefix} translateX(${transformX}px)`;
this._overlay.style.opacity = this.percentOpen;
}
|
Handles Dragging of Sidenav
@param {Event} e
|
_handleDragTargetDrag
|
javascript
|
Dogfalo/materialize
|
js/sidenav.js
|
https://github.com/Dogfalo/materialize/blob/master/js/sidenav.js
|
MIT
|
_handleCloseTriggerClick(e) {
let $closeTrigger = $(e.target).closest('.sidenav-close');
if ($closeTrigger.length && !this._isCurrentlyFixed()) {
this.close();
}
}
|
Handles closing of Sidenav when element with class .sidenav-close
|
_handleCloseTriggerClick
|
javascript
|
Dogfalo/materialize
|
js/sidenav.js
|
https://github.com/Dogfalo/materialize/blob/master/js/sidenav.js
|
MIT
|
_animateCaptionIn(caption, duration) {
let animOptions = {
targets: caption,
opacity: 0,
duration: duration,
easing: 'easeOutQuad'
};
if ($(caption).hasClass('center-align')) {
animOptions.translateY = -100;
} else if ($(caption).hasClass('right-align')) {
animOptions.translateX = 100;
} else if ($(caption).hasClass('left-align')) {
animOptions.translateX = -100;
}
anim(animOptions);
}
|
Animate in caption
@param {Element} caption
@param {Number} duration
|
_animateCaptionIn
|
javascript
|
Dogfalo/materialize
|
js/slider.js
|
https://github.com/Dogfalo/materialize/blob/master/js/slider.js
|
MIT
|
set(index) {
// Wrap around indices.
if (index >= this.$slides.length) index = 0;
else if (index < 0) index = this.$slides.length - 1;
// Only do if index changes
if (this.activeIndex != index) {
this.$active = this.$slides.eq(this.activeIndex);
let $caption = this.$active.find('.caption');
this.$active.removeClass('active');
anim({
targets: this.$active[0],
opacity: 0,
duration: this.options.duration,
easing: 'easeOutQuad',
complete: () => {
this.$slides.not('.active').each((el) => {
anim({
targets: el,
opacity: 0,
translateX: 0,
translateY: 0,
duration: 0,
easing: 'easeOutQuad'
});
});
}
});
this._animateCaptionIn($caption[0], this.options.duration);
// Update indicators
if (this.options.indicators) {
this.$indicators.eq(this.activeIndex).removeClass('active');
this.$indicators.eq(index).addClass('active');
}
anim({
targets: this.$slides.eq(index)[0],
opacity: 1,
duration: this.options.duration,
easing: 'easeOutQuad'
});
anim({
targets: this.$slides.eq(index).find('.caption')[0],
opacity: 1,
translateX: 0,
translateY: 0,
duration: this.options.duration,
delay: this.options.duration,
easing: 'easeOutQuad'
});
this.$slides.eq(index).addClass('active');
this.activeIndex = index;
// Reset interval
this.start();
}
}
|
Cycle to nth item
@param {Number} index
|
set
|
javascript
|
Dogfalo/materialize
|
js/slider.js
|
https://github.com/Dogfalo/materialize/blob/master/js/slider.js
|
MIT
|
_calcRightPos(el) {
return Math.ceil(this.tabsWidth - el.position().left - el[0].getBoundingClientRect().width);
}
|
Finds right attribute for indicator based on active tab.
@param {cash} el
|
_calcRightPos
|
javascript
|
Dogfalo/materialize
|
js/tabs.js
|
https://github.com/Dogfalo/materialize/blob/master/js/tabs.js
|
MIT
|
_calcLeftPos(el) {
return Math.floor(el.position().left);
}
|
Finds left attribute for indicator based on active tab.
@param {cash} el
|
_calcLeftPos
|
javascript
|
Dogfalo/materialize
|
js/tabs.js
|
https://github.com/Dogfalo/materialize/blob/master/js/tabs.js
|
MIT
|
_animateIndicator(prevIndex) {
let leftDelay = 0,
rightDelay = 0;
if (this.index - prevIndex >= 0) {
leftDelay = 90;
} else {
rightDelay = 90;
}
// Animate
let animOptions = {
targets: this._indicator,
left: {
value: this._calcLeftPos(this.$activeTabLink),
delay: leftDelay
},
right: {
value: this._calcRightPos(this.$activeTabLink),
delay: rightDelay
},
duration: this.options.duration,
easing: 'easeOutQuad'
};
anim.remove(this._indicator);
anim(animOptions);
}
|
Animates Indicator to active tab.
@param {Number} prevIndex
|
_animateIndicator
|
javascript
|
Dogfalo/materialize
|
js/tabs.js
|
https://github.com/Dogfalo/materialize/blob/master/js/tabs.js
|
MIT
|
static _Pos(e) {
if (e.targetTouches && e.targetTouches.length >= 1) {
return { x: e.targetTouches[0].clientX, y: e.targetTouches[0].clientY };
}
// mouse event
return { x: e.clientX, y: e.clientY };
}
|
Get x position of mouse or touch event
@param {Event} e
@return {Point} x and y location
|
_Pos
|
javascript
|
Dogfalo/materialize
|
js/timepicker.js
|
https://github.com/Dogfalo/materialize/blob/master/js/timepicker.js
|
MIT
|
static _createContainer() {
let container = document.createElement('div');
container.setAttribute('id', 'toast-container');
// Add event handler
container.addEventListener('touchstart', Toast._onDragStart);
container.addEventListener('touchmove', Toast._onDragMove);
container.addEventListener('touchend', Toast._onDragEnd);
container.addEventListener('mousedown', Toast._onDragStart);
document.addEventListener('mousemove', Toast._onDragMove);
document.addEventListener('mouseup', Toast._onDragEnd);
document.body.appendChild(container);
Toast._container = container;
}
|
Append toast container and add event handlers
|
_createContainer
|
javascript
|
Dogfalo/materialize
|
js/toasts.js
|
https://github.com/Dogfalo/materialize/blob/master/js/toasts.js
|
MIT
|
static _removeContainer() {
// Add event handler
document.removeEventListener('mousemove', Toast._onDragMove);
document.removeEventListener('mouseup', Toast._onDragEnd);
$(Toast._container).remove();
Toast._container = null;
}
|
Remove toast container and event handlers
|
_removeContainer
|
javascript
|
Dogfalo/materialize
|
js/toasts.js
|
https://github.com/Dogfalo/materialize/blob/master/js/toasts.js
|
MIT
|
static _xPos(e) {
if (e.targetTouches && e.targetTouches.length >= 1) {
return e.targetTouches[0].clientX;
}
// mouse event
return e.clientX;
}
|
Get x position of mouse or touch event
@param {Event} e
|
_xPos
|
javascript
|
Dogfalo/materialize
|
js/toasts.js
|
https://github.com/Dogfalo/materialize/blob/master/js/toasts.js
|
MIT
|
_createToast() {
let toast = document.createElement('div');
toast.classList.add('toast');
// Add custom classes onto toast
if (!!this.options.classes.length) {
$(toast).addClass(this.options.classes);
}
// Set content
if (
typeof HTMLElement === 'object'
? this.message instanceof HTMLElement
: this.message &&
typeof this.message === 'object' &&
this.message !== null &&
this.message.nodeType === 1 &&
typeof this.message.nodeName === 'string'
) {
toast.appendChild(this.message);
// Check if it is jQuery object
} else if (!!this.message.jquery) {
$(toast).append(this.message[0]);
// Insert as html;
} else {
toast.innerHTML = this.message;
}
// Append toasft
Toast._container.appendChild(toast);
return toast;
}
|
Create toast and append it to toast container
|
_createToast
|
javascript
|
Dogfalo/materialize
|
js/toasts.js
|
https://github.com/Dogfalo/materialize/blob/master/js/toasts.js
|
MIT
|
_setTimer() {
if (this.timeRemaining !== Infinity) {
this.counterInterval = setInterval(() => {
// If toast is not being dragged, decrease its time remaining
if (!this.panning) {
this.timeRemaining -= 20;
}
// Animate toast out
if (this.timeRemaining <= 0) {
this.dismiss();
}
}, 20);
}
}
|
Create setInterval which automatically removes toast when timeRemaining >= 0
has been reached
|
_setTimer
|
javascript
|
Dogfalo/materialize
|
js/toasts.js
|
https://github.com/Dogfalo/materialize/blob/master/js/toasts.js
|
MIT
|
_setExitDelayTimeout() {
clearTimeout(this._exitDelayTimeout);
this._exitDelayTimeout = setTimeout(() => {
if (this.isHovered || this.isFocused) {
return;
}
this._animateOut();
}, this.options.exitDelay);
}
|
Create timeout which delays when the tooltip closes
|
_setExitDelayTimeout
|
javascript
|
Dogfalo/materialize
|
js/tooltip.js
|
https://github.com/Dogfalo/materialize/blob/master/js/tooltip.js
|
MIT
|
_setEnterDelayTimeout(isManual) {
clearTimeout(this._enterDelayTimeout);
this._enterDelayTimeout = setTimeout(() => {
if (!this.isHovered && !this.isFocused && !isManual) {
return;
}
this._animateIn();
}, this.options.enterDelay);
}
|
Create timeout which delays when the toast closes
|
_setEnterDelayTimeout
|
javascript
|
Dogfalo/materialize
|
js/tooltip.js
|
https://github.com/Dogfalo/materialize/blob/master/js/tooltip.js
|
MIT
|
function compareBindingAndReference({ binding, refPath, stmts }) {
const state = {
binding: null,
reference: null
};
for (const [idx, stmt] of stmts.entries()) {
if (isAncestor(stmt, binding.path)) {
state.binding = { idx };
}
for (const ref of binding.referencePaths) {
if (ref === refPath && isAncestor(stmt, ref)) {
state.reference = {
idx,
scope: binding.path.scope === ref.scope ? "current" : "other"
};
break;
}
}
}
return state;
}
|
Handle when binding is created inside a parent block and
the corresponding parent is removed by other plugins
if (false) { var a } -> var a
|
compareBindingAndReference
|
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 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 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
|
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
|
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
|
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
|
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
|
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
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.