_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q20000
|
createDatepickerInstance
|
train
|
function createDatepickerInstance(template) {
var outputElement = $compile(template)(pageScope);
pageScope.$apply();
ngElement = outputElement[0].tagName == 'MD-DATEPICKER' ?
outputElement : outputElement.find('md-datepicker');
element = ngElement[0];
scope = ngElement.isolateScope();
controller = ngElement.controller('mdDatepicker');
return outputElement;
}
|
javascript
|
{
"resource": ""
}
|
q20001
|
buildJs
|
train
|
function buildJs() {
const jsFiles = config.jsCoreFiles;
config.componentPaths.forEach(component => {
jsFiles.push(path.join(component, '*.js'));
jsFiles.push(path.join(component, '**/*.js'));
});
gutil.log("building js files...");
const jsBuildStream = gulp.src(jsFiles)
.pipe(filterNonCodeFiles())
.pipe(utils.buildNgMaterialDefinition())
.pipe(plumber())
.pipe(ngAnnotate())
.pipe(utils.addJsWrapper(true));
const jsProcess = series(jsBuildStream, themeBuildStream())
.pipe(concat('angular-material.js'))
.pipe(BUILD_MODE.transform())
.pipe(insert.prepend(config.banner))
.pipe(insert.append(';window.ngMaterial={version:{full: "' + VERSION + '"}};'))
.pipe(gulp.dest(config.outputDir))
.pipe(gulpif(!IS_DEV, uglify({output: {comments: 'some'}})))
.pipe(rename({extname: '.min.js'}))
.pipe(gulp.dest(config.outputDir));
return series(jsProcess, deployMaterialMocks());
// Deploy the `angular-material-mocks.js` file to the `dist` directory
function deployMaterialMocks() {
return gulp.src(config.mockFiles)
.pipe(gulp.dest(config.outputDir));
}
}
|
javascript
|
{
"resource": ""
}
|
q20002
|
deployMaterialMocks
|
train
|
function deployMaterialMocks() {
return gulp.src(config.mockFiles)
.pipe(gulp.dest(config.outputDir));
}
|
javascript
|
{
"resource": ""
}
|
q20003
|
themeBuildStream
|
train
|
function themeBuildStream() {
// Make a copy so that we don't modify the actual config that is used by other functions
var paths = config.themeBaseFiles.slice(0);
config.componentPaths.forEach(component => paths.push(path.join(component, '*-theme.scss')));
paths.push(config.themeCore);
return gulp.src(paths)
.pipe(concat('default-theme.scss'))
.pipe(utils.hoistScssVariables())
.pipe(sass())
.pipe(dedupeCss())
// The PostCSS orderedValues plugin modifies the theme color expressions.
.pipe(minifyCss({orderedValues: false}))
.pipe(utils.cssToNgConstant('material.core', '$MD_THEME_CSS'));
}
|
javascript
|
{
"resource": ""
}
|
q20004
|
dedupeCss
|
train
|
function dedupeCss() {
const prefixRegex = /-(webkit|moz|ms|o)-.+/;
return insert.transform(function(contents) {
// Parse the CSS into an AST.
const parsed = postcss.parse(contents);
// Walk through all the rules, skipping comments, media queries etc.
parsed.walk(function(rule) {
// Skip over any comments, media queries and rules that have less than 2 properties.
if (rule.type !== 'rule' || !rule.nodes || rule.nodes.length < 2) return;
// Walk all of the properties within a rule.
rule.walk(function(prop) {
// Check if there's a similar property that comes after the current one.
const hasDuplicate = validateProp(prop) && _.find(rule.nodes, function(otherProp) {
return prop !== otherProp && prop.prop === otherProp.prop && validateProp(otherProp);
});
// Remove the declaration if it's duplicated.
if (hasDuplicate) {
prop.remove();
gutil.log(gutil.colors.yellow(
'Removed duplicate property: "' +
prop.prop + ': ' + prop.value + '" from "' + rule.selector + '"...'
));
}
});
});
// Turn the AST back into CSS.
return parsed.toResult().css;
});
// Checks if a property is a style declaration and that it
// doesn't contain any vendor prefixes.
function validateProp(prop) {
return prop && prop.type === 'decl' && ![prop.prop, prop.value].some(function(value) {
return value.indexOf('-') > -1 && prefixRegex.test(value);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q20005
|
validateProp
|
train
|
function validateProp(prop) {
return prop && prop.type === 'decl' && ![prop.prop, prop.value].some(function(value) {
return value.indexOf('-') > -1 && prefixRegex.test(value);
});
}
|
javascript
|
{
"resource": ""
}
|
q20006
|
add
|
train
|
function add(item, index) {
if (!item) return -1;
if (!angular.isNumber(index)) {
index = _items.length;
}
_items.splice(index, 0, item);
return indexOf(item);
}
|
javascript
|
{
"resource": ""
}
|
q20007
|
findSubsequentItem
|
train
|
function findSubsequentItem(backwards, item, validate, limit) {
validate = validate || trueFn;
var curIndex = indexOf(item);
while (true) {
if (!inRange(curIndex)) return null;
var nextIndex = curIndex + (backwards ? -1 : 1);
var foundItem = null;
if (inRange(nextIndex)) {
foundItem = _items[nextIndex];
} else if (reloop) {
foundItem = backwards ? last() : first();
nextIndex = indexOf(foundItem);
}
if ((foundItem === null) || (nextIndex === limit)) return null;
if (validate(foundItem)) return foundItem;
if (angular.isUndefined(limit)) limit = nextIndex;
curIndex = nextIndex;
}
}
|
javascript
|
{
"resource": ""
}
|
q20008
|
preLink
|
train
|
function preLink(scope, element, attr, ctrls) {
var selectCtrl = ctrls[0];
element.addClass('_md'); // private md component indicator for styling
$mdTheming(element);
element.on('click', clickListener);
element.on('keypress', keyListener);
function keyListener(e) {
if (e.keyCode == 13 || e.keyCode == 32) {
clickListener(e);
}
}
function clickListener(ev) {
var option = $mdUtil.getClosest(ev.target, 'md-option');
var optionCtrl = option && angular.element(option).data('$mdOptionController');
if (!option || !optionCtrl) return;
if (option.hasAttribute('disabled')) {
ev.stopImmediatePropagation();
return false;
}
var optionHashKey = selectCtrl.hashGetter(optionCtrl.value);
var isSelected = angular.isDefined(selectCtrl.selected[optionHashKey]);
scope.$apply(function() {
if (selectCtrl.isMultiple) {
if (isSelected) {
selectCtrl.deselect(optionHashKey);
} else {
selectCtrl.select(optionHashKey, optionCtrl.value);
}
} else {
if (!isSelected) {
selectCtrl.deselect(Object.keys(selectCtrl.selected)[0]);
selectCtrl.select(optionHashKey, optionCtrl.value);
}
}
selectCtrl.refreshViewValue();
});
}
}
|
javascript
|
{
"resource": ""
}
|
q20009
|
cleanElement
|
train
|
function cleanElement() {
destroyListener();
element
.removeClass('md-active')
.attr('aria-hidden', 'true')
.css({
'display': 'none',
'top': '',
'right': '',
'bottom': '',
'left': '',
'font-size': '',
'min-width': ''
});
element.parent().find('md-select-value').removeAttr('aria-hidden');
announceClosed(opts);
if (!opts.$destroy && opts.restoreFocus) {
opts.target.focus();
}
}
|
javascript
|
{
"resource": ""
}
|
q20010
|
mouseOnScrollbar
|
train
|
function mouseOnScrollbar() {
var clickOnScrollbar = false;
if (ev && (ev.currentTarget.children.length > 0)) {
var child = ev.currentTarget.children[0];
var hasScrollbar = child.scrollHeight > child.clientHeight;
if (hasScrollbar && child.children.length > 0) {
var relPosX = ev.pageX - ev.currentTarget.getBoundingClientRect().left;
if (relPosX > child.querySelector('md-option').offsetWidth)
clickOnScrollbar = true;
}
}
return clickOnScrollbar;
}
|
javascript
|
{
"resource": ""
}
|
q20011
|
register
|
train
|
function register(element, handlerName, options) {
var handler = HANDLERS[handlerName.replace(/^\$md./, '')];
if (!handler) {
throw new Error('Failed to register element with handler ' + handlerName + '. ' +
'Available handlers: ' + Object.keys(HANDLERS).join(', '));
}
return handler.registerElement(element, options);
}
|
javascript
|
{
"resource": ""
}
|
q20012
|
train
|
function (ev, pointer) {
if (this.state.isRunning) return;
var parentTarget = this.getNearestParent(ev.target);
// Get the options from the nearest registered parent
var parentTargetOptions = parentTarget && parentTarget.$mdGesture[this.name] || {};
this.state = {
isRunning: true,
// Override the default options with the nearest registered parent's options
options: angular.extend({}, this.options, parentTargetOptions),
// Pass in the registered parent node to the state so the onStart listener can use
registeredParent: parentTarget
};
this.onStart(ev, pointer);
}
|
javascript
|
{
"resource": ""
}
|
|
q20013
|
isInputEventFromLabelClick
|
train
|
function isInputEventFromLabelClick(event) {
return lastLabelClickPos
&& lastLabelClickPos.x == event.x
&& lastLabelClickPos.y == event.y;
}
|
javascript
|
{
"resource": ""
}
|
q20014
|
getEventPoint
|
train
|
function getEventPoint(ev) {
ev = ev.originalEvent || ev; // support jQuery events
return (ev.touches && ev.touches[0]) ||
(ev.changedTouches && ev.changedTouches[0]) ||
ev;
}
|
javascript
|
{
"resource": ""
}
|
q20015
|
canFocus
|
train
|
function canFocus(element) {
return (
!!element &&
element.getAttribute('tabindex') !== '-1' &&
!element.hasAttribute('disabled') &&
(
element.hasAttribute('tabindex') ||
element.hasAttribute('href') ||
element.isContentEditable ||
['INPUT', 'SELECT', 'BUTTON', 'TEXTAREA', 'VIDEO', 'AUDIO'].indexOf(element.nodeName) !== -1
)
);
}
|
javascript
|
{
"resource": ""
}
|
q20016
|
handleDemoIndexFile
|
train
|
function handleDemoIndexFile() {
files.index.contentsPromise.then(function(contents) {
demoContainer = angular.element(
'<div class="demo-content ' + ngModule + '">'
);
var isStandalone = !!ngModule;
var demoScope;
var demoCompileService;
if (isStandalone) {
angular.bootstrap(demoContainer[0], [ngModule]);
demoScope = demoContainer.scope();
demoCompileService = demoContainer.injector().get('$compile');
scope.$on('$destroy', function() {
demoScope.$destroy();
});
} else {
demoScope = scope.$new();
demoCompileService = $compile;
}
// Once everything is loaded, put the demo into the DOM
$q.all([
handleDemoStyles(),
handleDemoTemplates()
]).finally(function() {
demoScope.$evalAsync(function() {
element.append(demoContainer);
demoContainer.html(contents);
demoCompileService(demoContainer.contents())(demoScope);
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q20017
|
handleDemoStyles
|
train
|
function handleDemoStyles() {
return $q.all(files.css.map(function(file) {
return file.contentsPromise;
}))
.then(function(styles) {
styles = styles.join('\n'); // join styles as one string
var styleElement = angular.element('<style>' + styles + '</style>');
document.body.appendChild(styleElement[0]);
scope.$on('$destroy', function() {
styleElement.remove();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q20018
|
handleDemoTemplates
|
train
|
function handleDemoTemplates() {
return $q.all(files.html.map(function(file) {
return file.contentsPromise.then(function(contents) {
// Get the $templateCache instance that goes with the demo's specific ng-app.
var demoTemplateCache = demoContainer.injector().get('$templateCache');
demoTemplateCache.put(file.name, contents);
scope.$on('$destroy', function() {
demoTemplateCache.remove(file.name);
});
});
}));
}
|
javascript
|
{
"resource": ""
}
|
q20019
|
findInstance
|
train
|
function findInstance(handle, shouldWait) {
var instance = $mdComponentRegistry.get(handle);
if (!instance && !shouldWait) {
// Report missing instance
$log.error($mdUtil.supplant(errorMsg, [handle || ""]));
// The component has not registered itself... most like NOT yet created
// return null to indicate that the Sidenav is not in the DOM
return undefined;
}
return instance;
}
|
javascript
|
{
"resource": ""
}
|
q20020
|
toggleOpen
|
train
|
function toggleOpen(isOpen) {
if (scope.isOpen === isOpen) {
return $q.when(true);
} else {
if (scope.isOpen && sidenavCtrl.onCloseCb) sidenavCtrl.onCloseCb();
return $q(function(resolve) {
// Toggle value to force an async `updateIsOpen()` to run
scope.isOpen = isOpen;
$mdUtil.nextTick(function() {
// When the current `updateIsOpen()` animation finishes
promise.then(function(result) {
if (!scope.isOpen && triggeringElement && triggeringInteractionType === 'keyboard') {
// reset focus to originating element (if available) upon close
triggeringElement.focus();
triggeringElement = null;
}
resolve(result);
});
});
});
}
}
|
javascript
|
{
"resource": ""
}
|
q20021
|
onKeyDown
|
train
|
function onKeyDown(ev) {
var isEscape = (ev.keyCode === $mdConstant.KEY_CODE.ESCAPE);
return isEscape ? close(ev) : $q.when(true);
}
|
javascript
|
{
"resource": ""
}
|
q20022
|
mdCalendarMonthBodyDirective
|
train
|
function mdCalendarMonthBodyDirective($compile, $$mdSvgRegistry) {
var ARROW_ICON = $compile('<md-icon md-svg-src="' +
$$mdSvgRegistry.mdTabsArrow + '"></md-icon>')({})[0];
return {
require: ['^^mdCalendar', '^^mdCalendarMonth', 'mdCalendarMonthBody'],
scope: { offset: '=mdMonthOffset' },
controller: CalendarMonthBodyCtrl,
controllerAs: 'mdMonthBodyCtrl',
bindToController: true,
link: function(scope, element, attrs, controllers) {
var calendarCtrl = controllers[0];
var monthCtrl = controllers[1];
var monthBodyCtrl = controllers[2];
monthBodyCtrl.calendarCtrl = calendarCtrl;
monthBodyCtrl.monthCtrl = monthCtrl;
monthBodyCtrl.arrowIcon = ARROW_ICON.cloneNode(true);
// The virtual-repeat re-uses the same DOM elements, so there are only a limited number
// of repeated items that are linked, and then those elements have their bindings updated.
// Since the months are not generated by bindings, we simply regenerate the entire thing
// when the binding (offset) changes.
scope.$watch(function() { return monthBodyCtrl.offset; }, function(offset) {
if (angular.isNumber(offset)) {
monthBodyCtrl.generateContent();
}
});
}
};
}
|
javascript
|
{
"resource": ""
}
|
q20023
|
CalendarMonthBodyCtrl
|
train
|
function CalendarMonthBodyCtrl($element, $$mdDateUtil, $mdDateLocale) {
/** @final {!angular.JQLite} */
this.$element = $element;
/** @final */
this.dateUtil = $$mdDateUtil;
/** @final */
this.dateLocale = $mdDateLocale;
/** @type {Object} Reference to the month view. */
this.monthCtrl = null;
/** @type {Object} Reference to the calendar. */
this.calendarCtrl = null;
/**
* Number of months from the start of the month "items" that the currently rendered month
* occurs. Set via angular data binding.
* @type {number}
*/
this.offset = null;
/**
* Date cell to focus after appending the month to the document.
* @type {HTMLElement}
*/
this.focusAfterAppend = null;
}
|
javascript
|
{
"resource": ""
}
|
q20024
|
mdCalendarYearDirective
|
train
|
function mdCalendarYearDirective() {
return {
require: ['^^mdCalendar', '^^mdCalendarYear', 'mdCalendarYearBody'],
scope: { offset: '=mdYearOffset' },
controller: CalendarYearBodyCtrl,
controllerAs: 'mdYearBodyCtrl',
bindToController: true,
link: function(scope, element, attrs, controllers) {
var calendarCtrl = controllers[0];
var yearCtrl = controllers[1];
var yearBodyCtrl = controllers[2];
yearBodyCtrl.calendarCtrl = calendarCtrl;
yearBodyCtrl.yearCtrl = yearCtrl;
scope.$watch(function() { return yearBodyCtrl.offset; }, function(offset) {
if (angular.isNumber(offset)) {
yearBodyCtrl.generateContent();
}
});
}
};
}
|
javascript
|
{
"resource": ""
}
|
q20025
|
CalendarYearBodyCtrl
|
train
|
function CalendarYearBodyCtrl($element, $$mdDateUtil, $mdDateLocale) {
/** @final {!angular.JQLite} */
this.$element = $element;
/** @final */
this.dateUtil = $$mdDateUtil;
/** @final */
this.dateLocale = $mdDateLocale;
/** @type {Object} Reference to the calendar. */
this.calendarCtrl = null;
/** @type {Object} Reference to the year view. */
this.yearCtrl = null;
/**
* Number of months from the start of the month "items" that the currently rendered month
* occurs. Set via angular data binding.
* @type {number}
*/
this.offset = null;
/**
* Date cell to focus after appending the month to the document.
* @type {HTMLElement}
*/
this.focusAfterAppend = null;
}
|
javascript
|
{
"resource": ""
}
|
q20026
|
setDefaults
|
train
|
function setDefaults(definition) {
providerConfig.optionsFactory = definition.options;
providerConfig.methods = (definition.methods || []).concat(EXPOSED_METHODS);
return provider;
}
|
javascript
|
{
"resource": ""
}
|
q20027
|
addPreset
|
train
|
function addPreset(name, definition) {
definition = definition || {};
definition.methods = definition.methods || [];
definition.options = definition.options || function() { return {}; };
if (/^cancel|hide|show$/.test(name)) {
throw new Error("Preset '" + name + "' in " + interimFactoryName + " is reserved!");
}
if (definition.methods.indexOf('_options') > -1) {
throw new Error("Method '_options' in " + interimFactoryName + " is reserved!");
}
providerConfig.presets[name] = {
methods: definition.methods.concat(EXPOSED_METHODS),
optionsFactory: definition.options,
argOption: definition.argOption
};
return provider;
}
|
javascript
|
{
"resource": ""
}
|
q20028
|
waitForInterim
|
train
|
function waitForInterim(callbackFn) {
return function() {
var fnArguments = arguments;
if (!showingInterims.length) {
// When there are still interim's opening, then wait for the first interim element to
// finish its open animation.
if (showPromises.length) {
return showPromises[0].finally(function () {
return callbackFn.apply(service, fnArguments);
});
}
return $q.when("No interim elements currently showing up.");
}
return callbackFn.apply(service, fnArguments);
};
}
|
javascript
|
{
"resource": ""
}
|
q20029
|
createAndTransitionIn
|
train
|
function createAndTransitionIn() {
return $q(function(resolve, reject) {
// Trigger onCompiling callback before the compilation starts.
// This is useful, when modifying options, which can be influenced by developers.
options.onCompiling && options.onCompiling(options);
compileElement(options)
.then(function(compiledData) {
element = linkElement(compiledData, options);
// Expose the cleanup function from the compiler.
options.cleanupElement = compiledData.cleanup;
showAction = showElement(element, options, compiledData.controller)
.then(resolve, rejectAll);
}).catch(rejectAll);
function rejectAll(fault) {
// Force the '$md<xxx>.show()' promise to reject
self.deferred.reject(fault);
// Continue rejection propagation
reject(fault);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q20030
|
compileElement
|
train
|
function compileElement(options) {
var compiled = !options.skipCompile ? $mdCompiler.compile(options) : null;
return compiled || $q(function (resolve) {
resolve({
locals: {},
link: function () {
return options.element;
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q20031
|
linkElement
|
train
|
function linkElement(compileData, options){
angular.extend(compileData.locals, options);
var element = compileData.link(options.scope);
// Search for parent at insertion time, if not specified
options.element = element;
options.parent = findParent(element, options);
if (options.themable) $mdTheming(element);
return element;
}
|
javascript
|
{
"resource": ""
}
|
q20032
|
findParent
|
train
|
function findParent(element, options) {
var parent = options.parent;
// Search for parent at insertion time, if not specified
if (angular.isFunction(parent)) {
parent = parent(options.scope, element, options);
} else if (angular.isString(parent)) {
parent = angular.element($document[0].querySelector(parent));
} else {
parent = angular.element(parent);
}
// If parent querySelector/getter function fails, or it's just null,
// find a default.
if (!(parent || {}).length) {
var el;
if ($rootElement[0] && $rootElement[0].querySelector) {
el = $rootElement[0].querySelector(':not(svg) > body');
}
if (!el) el = $rootElement[0];
if (el.nodeName == '#comment') {
el = $document[0].body;
}
return angular.element(el);
}
return parent;
}
|
javascript
|
{
"resource": ""
}
|
q20033
|
startAutoHide
|
train
|
function startAutoHide() {
var autoHideTimer, cancelAutoHide = angular.noop;
if (options.hideDelay) {
autoHideTimer = $timeout(service.hide, options.hideDelay) ;
cancelAutoHide = function() {
$timeout.cancel(autoHideTimer);
};
}
// Cache for subsequent use
options.cancelAutoHide = function() {
cancelAutoHide();
options.cancelAutoHide = undefined;
};
}
|
javascript
|
{
"resource": ""
}
|
q20034
|
changeSelectedButton
|
train
|
function changeSelectedButton(parent, increment) {
// Coerce all child radio buttons into an array, then wrap then in an iterator
var buttons = $mdUtil.iterator(parent[0].querySelectorAll('md-radio-button'), true);
if (buttons.count()) {
var validate = function (button) {
// If disabled, then NOT valid
return !angular.element(button).attr("disabled");
};
var selected = parent[0].querySelector('md-radio-button.md-checked');
var target = buttons[increment < 0 ? 'previous' : 'next'](selected, validate) || buttons.first();
// Activate radioButton's click listener (triggerHandler won't create a real click event)
angular.element(target).triggerHandler('click');
}
}
|
javascript
|
{
"resource": ""
}
|
q20035
|
initialize
|
train
|
function initialize() {
if (!rgCtrl) {
throw 'RadioButton: No RadioGroupController could be found.';
}
rgCtrl.add(render);
attr.$observe('value', render);
element
.on('click', listener)
.on('$destroy', function() {
rgCtrl.remove(render);
});
}
|
javascript
|
{
"resource": ""
}
|
q20036
|
listener
|
train
|
function listener(ev) {
if (element[0].hasAttribute('disabled') || rgCtrl.isDisabled()) return;
scope.$apply(function() {
rgCtrl.setViewValue(attr.value, ev && ev.type);
});
}
|
javascript
|
{
"resource": ""
}
|
q20037
|
configureAria
|
train
|
function configureAria(element, scope){
element.attr({
id: attr.id || 'radio_' + $mdUtil.nextUid(),
role: 'radio',
'aria-checked': 'false'
});
$mdAria.expectWithText(element, 'aria-label');
}
|
javascript
|
{
"resource": ""
}
|
q20038
|
fontSet
|
train
|
function fontSet(alias, className) {
config.fontSets.push({
alias: alias,
fontSet: className || alias
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
q20039
|
findRegisteredFontSet
|
train
|
function findRegisteredFontSet(alias) {
var useDefault = angular.isUndefined(alias) || !(alias && alias.length);
if (useDefault) {
return config.defaultFontSet;
}
var result = alias;
angular.forEach(config.fontSets, function(fontSet) {
if (fontSet.alias === alias) {
result = fontSet.fontSet || result;
}
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q20040
|
isIcon
|
train
|
function isIcon(target) {
return angular.isDefined(target.element) && angular.isDefined(target.config);
}
|
javascript
|
{
"resource": ""
}
|
q20041
|
Icon
|
train
|
function Icon(el, config) {
// If the node is a <symbol>, it won't be rendered so we have to convert it into <svg>.
if (el && el.tagName.toLowerCase() === 'symbol') {
var viewbox = el.getAttribute('viewBox');
// // Check if innerHTML is supported as IE11 does not support innerHTML on SVG elements.
if (el.innerHTML) {
el = angular.element('<svg xmlns="http://www.w3.org/2000/svg">')
.html(el.innerHTML)[0];
} else {
el = angular.element('<svg xmlns="http://www.w3.org/2000/svg">')
.append($mdUtil.getInnerHTML(el))[0];
}
if (viewbox) el.setAttribute('viewBox', viewbox);
}
if (el && el.tagName.toLowerCase() !== 'svg') {
el = angular.element(
'<svg xmlns="http://www.w3.org/2000/svg">').append(el.cloneNode(true))[0];
}
// Inject the namespace if not available...
if (!el.getAttribute('xmlns')) {
el.setAttribute('xmlns', "http://www.w3.org/2000/svg");
}
this.element = el;
this.config = config;
this.prepare();
}
|
javascript
|
{
"resource": ""
}
|
q20042
|
prepareAndStyle
|
train
|
function prepareAndStyle() {
var viewBoxSize = this.config ? this.config.viewBoxSize : config.defaultViewBoxSize;
angular.forEach({
'fit': '',
'height': '100%',
'width': '100%',
'preserveAspectRatio': 'xMidYMid meet',
'viewBox': this.element.getAttribute('viewBox') || ('0 0 ' + viewBoxSize + ' ' + viewBoxSize),
'focusable': false // Disable IE11s default behavior to make SVGs focusable
}, function(val, attr) {
this.element.setAttribute(attr, val);
}, this);
}
|
javascript
|
{
"resource": ""
}
|
q20043
|
watchMedia
|
train
|
function watchMedia() {
for (var mediaName in $mdConstant.MEDIA) {
$mdMedia(mediaName); // initialize
$mdMedia.getQuery($mdConstant.MEDIA[mediaName])
.addListener(invalidateLayout);
}
return $mdMedia.watchResponsiveAttributes(
['md-cols', 'md-row-height', 'md-gutter'], attrs, layoutIfMediaMatch);
}
|
javascript
|
{
"resource": ""
}
|
q20044
|
layoutDelegate
|
train
|
function layoutDelegate(tilesInvalidated) {
var tiles = getTileElements();
var props = {
tileSpans: getTileSpans(tiles),
colCount: getColumnCount(),
rowMode: getRowMode(),
rowHeight: getRowHeight(),
gutter: getGutter()
};
if (!tilesInvalidated && angular.equals(props, lastLayoutProps)) {
return;
}
var performance =
$mdGridLayout(props.colCount, props.tileSpans, tiles)
.map(function(tilePositions, rowCount) {
return {
grid: {
element: element,
style: getGridStyle(props.colCount, rowCount,
props.gutter, props.rowMode, props.rowHeight)
},
tiles: tilePositions.map(function(ps, i) {
return {
element: angular.element(tiles[i]),
style: getTileStyle(ps.position, ps.spans,
props.colCount, rowCount,
props.gutter, props.rowMode, props.rowHeight)
};
})
};
})
.reflow()
.performance();
// Report layout
scope.mdOnLayout({
$event: {
performance: performance
}
});
lastLayoutProps = props;
}
|
javascript
|
{
"resource": ""
}
|
q20045
|
getTileStyle
|
train
|
function getTileStyle(position, spans, colCount, rowCount, gutter, rowMode, rowHeight) {
// TODO(shyndman): There are style caching opportunities here.
// Percent of the available horizontal space that one column takes up.
var hShare = (1 / colCount) * 100;
// Fraction of the gutter size that each column takes up.
var hGutterShare = (colCount - 1) / colCount;
// Base horizontal size of a column.
var hUnit = UNIT({share: hShare, gutterShare: hGutterShare, gutter: gutter});
// The width and horizontal position of each tile is always calculated the same way, but the
// height and vertical position depends on the rowMode.
var ltr = document.dir != 'rtl' && document.body.dir != 'rtl';
var style = ltr ? {
left: POSITION({ unit: hUnit, offset: position.col, gutter: gutter }),
width: DIMENSION({ unit: hUnit, span: spans.col, gutter: gutter }),
// resets
paddingTop: '',
marginTop: '',
top: '',
height: ''
} : {
right: POSITION({ unit: hUnit, offset: position.col, gutter: gutter }),
width: DIMENSION({ unit: hUnit, span: spans.col, gutter: gutter }),
// resets
paddingTop: '',
marginTop: '',
top: '',
height: ''
};
switch (rowMode) {
case 'fixed':
// In fixed mode, simply use the given rowHeight.
style.top = POSITION({ unit: rowHeight, offset: position.row, gutter: gutter });
style.height = DIMENSION({ unit: rowHeight, span: spans.row, gutter: gutter });
break;
case 'ratio':
// Percent of the available vertical space that one row takes up. Here, rowHeight holds
// the ratio value. For example, if the width:height ratio is 4:3, rowHeight = 1.333.
var vShare = hShare / rowHeight;
// Base veritcal size of a row.
var vUnit = UNIT({ share: vShare, gutterShare: hGutterShare, gutter: gutter });
// padidngTop and marginTop are used to maintain the given aspect ratio, as
// a percentage-based value for these properties is applied to the *width* of the
// containing block. See http://www.w3.org/TR/CSS2/box.html#margin-properties
style.paddingTop = DIMENSION({ unit: vUnit, span: spans.row, gutter: gutter});
style.marginTop = POSITION({ unit: vUnit, offset: position.row, gutter: gutter });
break;
case 'fit':
// Fraction of the gutter size that each column takes up.
var vGutterShare = (rowCount - 1) / rowCount;
// Percent of the available vertical space that one row takes up.
vShare = (1 / rowCount) * 100;
// Base vertical size of a row.
vUnit = UNIT({share: vShare, gutterShare: vGutterShare, gutter: gutter});
style.top = POSITION({unit: vUnit, offset: position.row, gutter: gutter});
style.height = DIMENSION({unit: vUnit, span: spans.row, gutter: gutter});
break;
}
return style;
}
|
javascript
|
{
"resource": ""
}
|
q20046
|
getTileSpans
|
train
|
function getTileSpans(tileElements) {
return [].map.call(tileElements, function(ele) {
var ctrl = angular.element(ele).controller('mdGridTile');
return {
row: parseInt(
$mdMedia.getResponsiveAttribute(ctrl.$attrs, 'md-rowspan'), 10) || 1,
col: parseInt(
$mdMedia.getResponsiveAttribute(ctrl.$attrs, 'md-colspan'), 10) || 1
};
});
}
|
javascript
|
{
"resource": ""
}
|
q20047
|
GridLayout
|
train
|
function GridLayout(colCount, tileSpans) {
var self, layoutInfo, gridStyles, layoutTime, mapTime, reflowTime;
layoutTime = $mdUtil.time(function() {
layoutInfo = calculateGridFor(colCount, tileSpans);
});
return self = {
/**
* An array of objects describing each tile's position in the grid.
*/
layoutInfo: function() {
return layoutInfo;
},
/**
* Maps grid positioning to an element and a set of styles using the
* provided updateFn.
*/
map: function(updateFn) {
mapTime = $mdUtil.time(function() {
var info = self.layoutInfo();
gridStyles = updateFn(info.positioning, info.rowCount);
});
return self;
},
/**
* Default animator simply sets the element.css( <styles> ). An alternate
* animator can be provided as an argument. The function has the following
* signature:
*
* function({grid: {element: JQLite, style: Object}, tiles: Array<{element: JQLite, style: Object}>)
*/
reflow: function(animatorFn) {
reflowTime = $mdUtil.time(function() {
var animator = animatorFn || defaultAnimator;
animator(gridStyles.grid, gridStyles.tiles);
});
return self;
},
/**
* Timing for the most recent layout run.
*/
performance: function() {
return {
tileCount: tileSpans.length,
layoutTime: layoutTime,
mapTime: mapTime,
reflowTime: reflowTime,
totalTime: layoutTime + mapTime + reflowTime
};
}
};
}
|
javascript
|
{
"resource": ""
}
|
q20048
|
train
|
function(updateFn) {
mapTime = $mdUtil.time(function() {
var info = self.layoutInfo();
gridStyles = updateFn(info.positioning, info.rowCount);
});
return self;
}
|
javascript
|
{
"resource": ""
}
|
|
q20049
|
train
|
function() {
return {
tileCount: tileSpans.length,
layoutTime: layoutTime,
mapTime: mapTime,
reflowTime: reflowTime,
totalTime: layoutTime + mapTime + reflowTime
};
}
|
javascript
|
{
"resource": ""
}
|
|
q20050
|
calculateGridFor
|
train
|
function calculateGridFor(colCount, tileSpans) {
var curCol = 0,
curRow = 0,
spaceTracker = newSpaceTracker();
return {
positioning: tileSpans.map(function(spans, i) {
return {
spans: spans,
position: reserveSpace(spans, i)
};
}),
rowCount: curRow + Math.max.apply(Math, spaceTracker)
};
function reserveSpace(spans, i) {
if (spans.col > colCount) {
throw 'md-grid-list: Tile at position ' + i + ' has a colspan ' +
'(' + spans.col + ') that exceeds the column count ' +
'(' + colCount + ')';
}
var start = 0,
end = 0;
// TODO(shyndman): This loop isn't strictly necessary if you can
// determine the minimum number of rows before a space opens up. To do
// this, recognize that you've iterated across an entire row looking for
// space, and if so fast-forward by the minimum rowSpan count. Repeat
// until the required space opens up.
while (end - start < spans.col) {
if (curCol >= colCount) {
nextRow();
continue;
}
start = spaceTracker.indexOf(0, curCol);
if (start === -1 || (end = findEnd(start + 1)) === -1) {
start = end = 0;
nextRow();
continue;
}
curCol = end + 1;
}
adjustRow(start, spans.col, spans.row);
curCol = start + spans.col;
return {
col: start,
row: curRow
};
}
function nextRow() {
curCol = 0;
curRow++;
adjustRow(0, colCount, -1); // Decrement row spans by one
}
function adjustRow(from, cols, by) {
for (var i = from; i < from + cols; i++) {
spaceTracker[i] = Math.max(spaceTracker[i] + by, 0);
}
}
function findEnd(start) {
var i;
for (i = start; i < spaceTracker.length; i++) {
if (spaceTracker[i] !== 0) {
return i;
}
}
if (i === spaceTracker.length) {
return i;
}
}
function newSpaceTracker() {
var tracker = [];
for (var i = 0; i < colCount; i++) {
tracker.push(0);
}
return tracker;
}
}
|
javascript
|
{
"resource": ""
}
|
q20051
|
validate
|
train
|
function validate () {
if (exec('npm whoami') !== 'angular') {
err('You must be authenticated with npm as "angular" to perform a release.');
} else if (exec('git rev-parse --abbrev-ref HEAD') !== 'staging') {
err('Releases can only performed from "staging" at this time.');
} else {
return true;
}
function err (msg) {
const str = 'Error: ' + msg;
log(str.red);
}
}
|
javascript
|
{
"resource": ""
}
|
q20052
|
checkoutVersionBranch
|
train
|
function checkoutVersionBranch () {
exec(`git branch -q -D release/${newVersion}`);
exec(`git checkout -q -b release/${newVersion}`);
abortCmds.push('git checkout master');
abortCmds.push(`git branch -D release/${newVersion}`);
}
|
javascript
|
{
"resource": ""
}
|
q20053
|
updateVersion
|
train
|
function updateVersion () {
start(`Updating ${"package.json".cyan} version from ${oldVersion.cyan} to ${newVersion.cyan}...`);
pkg.version = newVersion;
fs.writeFileSync('./package.json', JSON.stringify(pkg, null, 2));
done();
abortCmds.push('git checkout package.json');
pushCmds.push('git add package.json');
}
|
javascript
|
{
"resource": ""
}
|
q20054
|
createChangelog
|
train
|
function createChangelog () {
start(`Generating changelog from ${oldVersion.cyan} to ${newVersion.cyan}...`);
exec(`git fetch --tags ${origin}`);
exec(`git checkout CHANGELOG.md`);
exec(`gulp changelog --sha=$(git merge-base v${lastMajorVer} HEAD)`);
done();
abortCmds.push('git checkout CHANGELOG.md');
pushCmds.push('git add CHANGELOG.md');
}
|
javascript
|
{
"resource": ""
}
|
q20055
|
getNewVersion
|
train
|
function getNewVersion () {
header();
const options = getVersionOptions(oldVersion);
let key, version;
log(`The current version is ${oldVersion.cyan}.`);
log('');
log('What should the next version be?');
for (key in options) { log((+key + 1) + ') ' + options[ key ].cyan); }
log('');
write('Please select a new version: ');
const type = prompt();
if (options[ type - 1 ]) version = options[ type - 1 ];
else if (type.match(/^\d+\.\d+\.\d+(-rc\.?\d+)?$/)) version = type;
else throw new Error('Your entry was invalid.');
log('');
log('The new version will be ' + version.cyan + '.');
write(`Is this correct? ${"[yes/no]".cyan} `);
return prompt() === 'yes' ? version : getNewVersion();
function getVersionOptions (version) {
return version.match(/-rc\.?\d+$/)
? [increment(version, 'rc'), increment(version, 'minor')]
: [increment(version, 'patch'), addRC(increment(version, 'minor'))];
function increment (versionString, type) {
const version = parseVersion(versionString);
if (version.rc) {
switch (type) {
case 'minor': version.rc = 0; break;
case 'rc': version.rc++; break;
}
} else {
version[ type ]++;
// reset any version numbers lower than the one changed
switch (type) {
case 'minor': version.patch = 0;
case 'patch': version.rc = 0;
}
}
return getVersionString(version);
function parseVersion (version) {
const parts = version.split(/-rc\.|\./g);
return {
string: version,
major: parts[ 0 ],
minor: parts[ 1 ],
patch: parts[ 2 ],
rc: parts[ 3 ] || 0
};
}
function getVersionString (version) {
let str = version.major + '.' + version.minor + '.' + version.patch;
if (version.rc) str += '-rc.' + version.rc;
return str;
}
}
function addRC (str) {
return str + '-rc.1';
}
}
}
|
javascript
|
{
"resource": ""
}
|
q20056
|
cloneRepo
|
train
|
function cloneRepo (repo) {
start(`Cloning ${repo.cyan} from Github...`);
exec(`rm -rf ${repo}`);
exec(`git clone git@github.com:angular/${repo}.git --depth=1`);
done();
cleanupCmds.push(`rm -rf ${repo}`);
}
|
javascript
|
{
"resource": ""
}
|
q20057
|
writeScript
|
train
|
function writeScript (name, cmds) {
fs.writeFileSync(name, '#!/usr/bin/env bash\n\n' + cmds.join('\n'));
exec('chmod +x ' + name);
}
|
javascript
|
{
"resource": ""
}
|
q20058
|
updateBowerVersion
|
train
|
function updateBowerVersion () {
start('Updating bower version...');
const options = { cwd: './bower-material' };
const bower = require(options.cwd + '/bower.json'),
pkg = require(options.cwd + '/package.json');
// update versions in config files
bower.version = pkg.version = newVersion;
fs.writeFileSync(options.cwd + '/package.json', JSON.stringify(pkg, null, 2));
fs.writeFileSync(options.cwd + '/bower.json', JSON.stringify(bower, null, 2));
done();
start('Building bower files...');
// build files for bower
exec([
'rm -rf dist',
'gulp build',
'gulp build-all-modules --mode=default',
'gulp build-all-modules --mode=closure',
'rm -rf dist/demos'
]);
done();
start('Copy files into bower repo...');
// copy files over to bower repo
exec([
'cp -Rf ../dist/* ./',
'git add -A',
`git commit -m "release: version ${newVersion}"`,
'rm -rf ../dist'
], options);
done();
// add steps to push script
pushCmds.push(
comment('push to bower (master and tag) and publish to npm'),
'cd ' + options.cwd,
'cp ../CHANGELOG.md .',
'git add CHANGELOG.md',
'git commit --amend --no-edit',
`git tag -f v${newVersion}`,
'git pull --rebase --strategy=ours',
'git push',
'git push --tags',
'rm -rf .git/',
'npm publish',
'cd ..'
);
}
|
javascript
|
{
"resource": ""
}
|
q20059
|
updateSite
|
train
|
function updateSite () {
start('Adding new version of the docs site...');
const options = { cwd: './code.material.angularjs.org' };
writeDocsJson();
// build files for bower
exec([
'rm -rf dist',
'gulp docs'
]);
replaceFilePaths();
// copy files over to site repo
exec([
`cp -Rf ../dist/docs ${newVersion}`,
'rm -rf latest && cp -Rf ../dist/docs latest',
'git add -A',
`git commit -m "release: version ${newVersion}"`,
'rm -rf ../dist'
], options);
replaceBaseHref(newVersion);
replaceBaseHref('latest');
// update firebase.json file
updateFirebaseJson();
exec(['git commit --amend --no-edit -a'], options);
done();
// add steps to push script
pushCmds.push(
comment('push the site'),
'cd ' + options.cwd,
'git pull --rebase --strategy=ours',
'git push',
'cd ..'
);
function updateFirebaseJson () {
fs.writeFileSync(options.cwd + '/firebase.json', getFirebaseJson());
function getFirebaseJson () {
const json = require(options.cwd + '/firebase.json');
json.hosting.rewrites = json.hosting.rewrites || [];
const rewrites = json.hosting.rewrites;
switch (rewrites.length) {
case 0:
rewrites.push(getRewrite('HEAD'));
case 1:
rewrites.push(getRewrite('latest'));
default:
rewrites.push(getRewrite(newVersion));
}
return JSON.stringify(json, null, 2);
function getRewrite (str) {
return {
source: '/' + str + '/**/!(*.@(js|html|css|json|svg|png|jpg|jpeg))',
destination: '/' + str + '/index.html'
};
}
}
}
function writeDocsJson () {
const config = require(options.cwd + '/docs.json');
config.versions.unshift(newVersion);
// only set to default if not a release candidate
config.latest = newVersion;
fs.writeFileSync(options.cwd + '/docs.json', JSON.stringify(config, null, 2));
}
}
|
javascript
|
{
"resource": ""
}
|
q20060
|
replaceFilePaths
|
train
|
function replaceFilePaths () {
// handle docs.js
const filePath = path.join(__dirname, '/dist/docs/docs.js');
const file = fs.readFileSync(filePath);
const contents = file.toString()
.replace(/http:\/\/localhost:8080\/angular-material/g, 'https://gitcdn.xyz/cdn/angular/bower-material/v' + newVersion + '/angular-material')
.replace(/http:\/\/localhost:8080\/docs.css/g, 'https://material.angularjs.org/' + newVersion + '/docs.css');
fs.writeFileSync(filePath, contents);
}
|
javascript
|
{
"resource": ""
}
|
q20061
|
replaceBaseHref
|
train
|
function replaceBaseHref (folder) {
// handle index.html
const filePath = path.join(__dirname, '/code.material.angularjs.org/', folder, '/index.html');
const file = fs.readFileSync(filePath);
const contents = file.toString().replace(/base href="\//g, 'base href="/' + folder + '/');
fs.writeFileSync(filePath, contents);
}
|
javascript
|
{
"resource": ""
}
|
q20062
|
updateMaster
|
train
|
function updateMaster () {
pushCmds.push(
comment('update package.json in master'),
'git checkout master',
`git pull --rebase ${origin} master --strategy=theirs`,
`git checkout release/${newVersion} -- CHANGELOG.md`,
`node -e "const newVersion = '${newVersion}'; ${stringifyFunction(buildCommand)}"`,
'git add CHANGELOG.md',
'git add package.json',
`git commit -m "update version number in package.json to ${newVersion}"`,
`git push ${origin} master`
);
function buildCommand () {
require('fs').writeFileSync('package.json', JSON.stringify(getUpdatedJson(), null, 2));
function getUpdatedJson () {
const json = require('./package.json');
json.version = newVersion;
return json;
}
}
function stringifyFunction (method) {
return method
.toString()
.split('\n')
.slice(1, -1)
.map(function (line) { return line.trim(); })
.join(' ')
.replace(/"/g, '\\"');
}
}
|
javascript
|
{
"resource": ""
}
|
q20063
|
center
|
train
|
function center (msg) {
msg = ' ' + msg.trim() + ' ';
const length = msg.length;
const spaces = Math.floor((lineWidth - length) / 2);
return Array(spaces + 1).join('-') + msg.green + Array(lineWidth - msg.length - spaces + 1).join('-');
}
|
javascript
|
{
"resource": ""
}
|
q20064
|
start
|
train
|
function start (msg) {
const msgLength = strip(msg).length,
diff = lineWidth - 4 - msgLength;
write(msg + Array(diff + 1).join(' '));
}
|
javascript
|
{
"resource": ""
}
|
q20065
|
reverseTranslate
|
train
|
function reverseTranslate (newFrom) {
return $animateCss(target, {
to: newFrom || from,
addClass: options.transitionOutClass,
removeClass: options.transitionInClass,
duration: options.duration
}).start();
}
|
javascript
|
{
"resource": ""
}
|
q20066
|
noTransitionFound
|
train
|
function noTransitionFound(styles) {
styles = styles || window.getComputedStyle(element[0]);
return styles.transitionDuration == '0s' || (!styles.transition && !styles.transitionProperty);
}
|
javascript
|
{
"resource": ""
}
|
q20067
|
currentBounds
|
train
|
function currentBounds() {
var cntr = element ? element.parent() : null;
var parent = cntr ? cntr.parent() : null;
return parent ? self.clientRect(parent) : null;
}
|
javascript
|
{
"resource": ""
}
|
q20068
|
train
|
function (element, originator) {
var zoomTemplate = "translate3d( {centerX}px, {centerY}px, 0 ) scale( {scaleX}, {scaleY} )";
var buildZoom = angular.bind(null, $mdUtil.supplant, zoomTemplate);
return buildZoom(self.calculateTransformValues(element, originator));
}
|
javascript
|
{
"resource": ""
}
|
|
q20069
|
train
|
function(raw) {
var css = { };
var lookups = 'left top right bottom width height x y min-width min-height max-width max-height';
angular.forEach(raw, function(value,key) {
if (angular.isUndefined(value)) return;
if (lookups.indexOf(key) >= 0) {
css[key] = value + 'px';
} else {
switch (key) {
case 'transition':
convertToVendor(key, $mdConstant.CSS.TRANSITION, value);
break;
case 'transform':
convertToVendor(key, $mdConstant.CSS.TRANSFORM, value);
break;
case 'transformOrigin':
convertToVendor(key, $mdConstant.CSS.TRANSFORM_ORIGIN, value);
break;
case 'font-size':
css['font-size'] = value; // font sizes aren't always in px
break;
}
}
});
return css;
function convertToVendor(key, vendor, value) {
angular.forEach(vendor.split(' '), function (key) {
css[key] = value;
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q20070
|
train
|
function (element) {
var bounds = angular.element(element)[0].getBoundingClientRect();
var isPositiveSizeClientRect = function (rect) {
return rect && (rect.width > 0) && (rect.height > 0);
};
// If the event origin element has zero size, it has probably been hidden.
return isPositiveSizeClientRect(bounds) ? self.copyRect(bounds) : null;
}
|
javascript
|
{
"resource": ""
}
|
|
q20071
|
train
|
function (targetRect) {
return targetRect ? {
x: Math.round(targetRect.left + (targetRect.width / 2)),
y: Math.round(targetRect.top + (targetRect.height / 2))
} : { x : 0, y : 0 };
}
|
javascript
|
{
"resource": ""
}
|
|
q20072
|
MdToastController
|
train
|
function MdToastController($mdToast, $scope, $log) {
// For compatibility with AngularJS 1.6+, we should always use the $onInit hook in
// interimElements. The $mdCompiler simulates the $onInit hook for all versions.
this.$onInit = function() {
var self = this;
if (self.highlightAction) {
$scope.highlightClasses = [
'md-highlight',
self.highlightClass
];
}
// If an action is defined and no actionKey is specified, then log a warning.
if (self.action && !self.actionKey) {
$log.warn('Toasts with actions should define an actionKey for accessibility.',
'Details: https://material.angularjs.org/latest/api/service/$mdToast#mdtoast-simple');
}
if (self.actionKey && !self.actionHint) {
self.actionHint = 'Press Control-"' + self.actionKey + '" to ';
}
if (!self.dismissHint) {
self.dismissHint = 'Press Escape to dismiss.';
}
$scope.$watch(function() { return activeToastContent; }, function() {
self.content = activeToastContent;
});
this.resolve = function() {
$mdToast.hide(ACTION_RESOLVE);
};
};
}
|
javascript
|
{
"resource": ""
}
|
q20073
|
attachToBody
|
train
|
function attachToBody(el) {
var element = angular.element(el);
angular.element(document.body).append(element);
attachedElements.push(element);
}
|
javascript
|
{
"resource": ""
}
|
q20074
|
hexToRgba
|
train
|
function hexToRgba (color) {
var hex = color[ 0 ] === '#' ? color.substr(1) : color,
dig = hex.length / 3,
red = hex.substr(0, dig),
green = hex.substr(dig, dig),
blue = hex.substr(dig * 2);
if (dig === 1) {
red += red;
green += green;
blue += blue;
}
return 'rgba(' + parseInt(red, 16) + ',' + parseInt(green, 16) + ',' + parseInt(blue, 16) + ',0.1)';
}
|
javascript
|
{
"resource": ""
}
|
q20075
|
rgbaToHex
|
train
|
function rgbaToHex(color) {
color = color.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
var hex = (color && color.length === 4) ? "#" +
("0" + parseInt(color[1],10).toString(16)).slice(-2) +
("0" + parseInt(color[2],10).toString(16)).slice(-2) +
("0" + parseInt(color[3],10).toString(16)).slice(-2) : '';
return hex.toUpperCase();
}
|
javascript
|
{
"resource": ""
}
|
q20076
|
isSameMonthAndYear
|
train
|
function isSameMonthAndYear(d1, d2) {
return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth();
}
|
javascript
|
{
"resource": ""
}
|
q20077
|
getWeekOfMonth
|
train
|
function getWeekOfMonth(date) {
var firstDayOfMonth = getFirstDateOfMonth(date);
return Math.floor((firstDayOfMonth.getDay() + date.getDate() - 1) / 7);
}
|
javascript
|
{
"resource": ""
}
|
q20078
|
incrementDays
|
train
|
function incrementDays(date, numberOfDays) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + numberOfDays);
}
|
javascript
|
{
"resource": ""
}
|
q20079
|
incrementMonths
|
train
|
function incrementMonths(date, numberOfMonths) {
// If the same date in the target month does not actually exist, the Date object will
// automatically advance *another* month by the number of missing days.
// For example, if you try to go from Jan. 30 to Feb. 30, you'll end up on March 2.
// So, we check if the month overflowed and go to the last day of the target month instead.
var dateInTargetMonth = new Date(date.getFullYear(), date.getMonth() + numberOfMonths, 1);
var numberOfDaysInMonth = getNumberOfDaysInMonth(dateInTargetMonth);
if (numberOfDaysInMonth < date.getDate()) {
dateInTargetMonth.setDate(numberOfDaysInMonth);
} else {
dateInTargetMonth.setDate(date.getDate());
}
return dateInTargetMonth;
}
|
javascript
|
{
"resource": ""
}
|
q20080
|
isDateWithinRange
|
train
|
function isDateWithinRange(date, minDate, maxDate) {
var dateAtMidnight = createDateAtMidnight(date);
var minDateAtMidnight = isValidDate(minDate) ? createDateAtMidnight(minDate) : null;
var maxDateAtMidnight = isValidDate(maxDate) ? createDateAtMidnight(maxDate) : null;
return (!minDateAtMidnight || minDateAtMidnight <= dateAtMidnight) &&
(!maxDateAtMidnight || maxDateAtMidnight >= dateAtMidnight);
}
|
javascript
|
{
"resource": ""
}
|
q20081
|
clampDate
|
train
|
function clampDate(date, minDate, maxDate) {
var boundDate = date;
if (minDate && date < minDate) {
boundDate = new Date(minDate.getTime());
}
if (maxDate && date > maxDate) {
boundDate = new Date(maxDate.getTime());
}
return boundDate;
}
|
javascript
|
{
"resource": ""
}
|
q20082
|
isMonthWithinRange
|
train
|
function isMonthWithinRange(date, minDate, maxDate) {
var month = date.getMonth();
var year = date.getFullYear();
return (!minDate || minDate.getFullYear() < year || minDate.getMonth() <= month) &&
(!maxDate || maxDate.getFullYear() > year || maxDate.getMonth() >= month);
}
|
javascript
|
{
"resource": ""
}
|
q20083
|
onScroll
|
train
|
function onScroll() {
var scrollTop = contentEl.prop('scrollTop');
var isScrollingDown = scrollTop > (onScroll.prevScrollTop || 0);
// Store the previous scroll so we know which direction we are scrolling
onScroll.prevScrollTop = scrollTop;
//
// AT TOP (not scrolling)
//
if (scrollTop === 0) {
// If we're at the top, just clear the current item and return
setCurrentItem(null);
return;
}
//
// SCROLLING DOWN (going towards the next item)
//
if (isScrollingDown) {
// If we've scrolled down past the next item's position, sticky it and return
if (self.next && self.next.top <= scrollTop) {
setCurrentItem(self.next);
return;
}
// If the next item is close to the current one, push the current one up out of the way
if (self.current && self.next && self.next.top - scrollTop <= self.next.height) {
translate(self.current, scrollTop + (self.next.top - self.next.height - scrollTop));
return;
}
}
//
// SCROLLING UP (not at the top & not scrolling down; must be scrolling up)
//
if (!isScrollingDown) {
// If we've scrolled up past the previous item's position, sticky it and return
if (self.current && self.prev && scrollTop < self.current.top) {
setCurrentItem(self.prev);
return;
}
// If the next item is close to the current one, pull the current one down into view
if (self.next && self.current && (scrollTop >= (self.next.top - self.current.height))) {
translate(self.current, scrollTop + (self.next.top - scrollTop - self.current.height));
return;
}
}
//
// Otherwise, just move the current item to the proper place (scrolling up or down)
//
if (self.current) {
translate(self.current, scrollTop);
}
}
|
javascript
|
{
"resource": ""
}
|
q20084
|
onRemove
|
train
|
function onRemove(scope, element, opts) {
opts.cleanupInteraction();
opts.cleanupBackdrop();
opts.cleanupResizing();
opts.hideBackdrop();
// Before the menu is closing remove the clickable class.
element.removeClass('md-clickable');
// For navigation $destroy events, do a quick, non-animated removal,
// but for normal closes (from clicks, etc) animate the removal
return (opts.$destroy === true) ? detachAndClean() : animateRemoval().then(detachAndClean);
/**
* For normal closes, animate the removal.
* For forced closes (like $destroy events), skip the animations
*/
function animateRemoval() {
return $animateCss(element, {addClass: 'md-leave'}).start();
}
/**
* Detach the element
*/
function detachAndClean() {
element.removeClass('md-active');
detachElement(element, opts);
opts.alreadyOpen = false;
}
}
|
javascript
|
{
"resource": ""
}
|
q20085
|
showMenu
|
train
|
function showMenu() {
opts.parent.append(element);
element[0].style.display = '';
return $q(function(resolve) {
var position = calculateMenuPosition(element, opts);
element.removeClass('md-leave');
// Animate the menu scaling, and opacity [from its position origin (default == top-left)]
// to normal scale.
$animateCss(element, {
addClass: 'md-active',
from: animator.toCss(position),
to: animator.toCss({transform: ''})
})
.start()
.then(resolve);
});
}
|
javascript
|
{
"resource": ""
}
|
q20086
|
sanitizeAndConfigure
|
train
|
function sanitizeAndConfigure() {
if (!opts.target) {
throw Error(
'$mdMenu.show() expected a target to animate from in options.target'
);
}
angular.extend(opts, {
alreadyOpen: false,
isRemoved: false,
target: angular.element(opts.target), // make sure it's not a naked DOM node
parent: angular.element(opts.parent),
menuContentEl: angular.element(element[0].querySelector('md-menu-content'))
});
}
|
javascript
|
{
"resource": ""
}
|
q20087
|
setupBackdrop
|
train
|
function setupBackdrop() {
if (!opts.backdrop) return angular.noop;
opts.backdrop.on('click', onBackdropClick);
return function() {
opts.backdrop.off('click', onBackdropClick);
};
}
|
javascript
|
{
"resource": ""
}
|
q20088
|
onBackdropClick
|
train
|
function onBackdropClick(event) {
event.preventDefault();
event.stopPropagation();
scope.$apply(function() {
opts.mdMenuCtrl.close(true, { closeAll: true });
});
}
|
javascript
|
{
"resource": ""
}
|
q20089
|
captureClickListener
|
train
|
function captureClickListener(e) {
var target = e.target;
// Traverse up the event until we get to the menuContentEl to see if
// there is an ng-click and that the ng-click is not disabled
do {
if (target == opts.menuContentEl[0]) return;
if ((hasAnyAttribute(target, ['ng-click', 'ng-href', 'ui-sref']) ||
target.nodeName == 'BUTTON' || target.nodeName == 'MD-BUTTON') && !hasAnyAttribute(target, ['md-prevent-menu-close'])) {
var closestMenu = $mdUtil.getClosest(target, 'MD-MENU');
if (!target.hasAttribute('disabled') && (!closestMenu || closestMenu == opts.parent[0])) {
close();
}
break;
}
} while (target = target.parentNode);
function close() {
scope.$apply(function() {
opts.mdMenuCtrl.close(true, { closeAll: true });
});
}
function hasAnyAttribute(target, attrs) {
if (!target) return false;
for (var i = 0, attr; attr = attrs[i]; ++i) {
if (prefixer.hasAttribute(target, attr)) {
return true;
}
}
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q20090
|
firstVisibleChild
|
train
|
function firstVisibleChild() {
for (var i = 0; i < openMenuNode.children.length; ++i) {
if ($window.getComputedStyle(openMenuNode.children[i]).display != 'none') {
return openMenuNode.children[i];
}
}
}
|
javascript
|
{
"resource": ""
}
|
q20091
|
publicDocData
|
train
|
function publicDocData(doc, extraData) {
const options = _.assign(extraData || {}, { hasDemo: (doc.docType === 'directive') });
// This RegEx always retrieves the last source descriptor.
// For example it retrieves from `/opt/material/src/core/services/ripple/ripple.js` the following
// source descriptor: `src/core/`.
// This is needed because components are not only located in `src/components`.
let descriptor = doc.fileInfo.filePath.toString().match(/src\/.*?\//g).pop();
if (descriptor) {
descriptor = descriptor.substring(descriptor.indexOf('/') + 1, descriptor.lastIndexOf('/'));
}
return buildDocData(doc, options, descriptor || 'components');
}
|
javascript
|
{
"resource": ""
}
|
q20092
|
registerGestures
|
train
|
function registerGestures(element, parent) {
var deregister = $mdGesture.register(parent, 'drag', { horizontal: false });
parent.on('$md.dragstart', onDragStart)
.on('$md.drag', onDrag)
.on('$md.dragend', onDragEnd);
return function cleanupGestures() {
deregister();
parent.off('$md.dragstart', onDragStart);
parent.off('$md.drag', onDrag);
parent.off('$md.dragend', onDragEnd);
};
function onDragStart() {
// Disable transitions on transform so that it feels fast
element.css($mdConstant.CSS.TRANSITION_DURATION, '0ms');
}
function onDrag(ev) {
var transform = ev.pointer.distanceY;
if (transform < 5) {
// Slow down drag when trying to drag up, and stop after PADDING
transform = Math.max(-PADDING, transform / 2);
}
element.css($mdConstant.CSS.TRANSFORM, 'translate3d(0,' + (PADDING + transform) + 'px,0)');
}
function onDragEnd(ev) {
if (ev.pointer.distanceY > 0 &&
(ev.pointer.distanceY > 20 || Math.abs(ev.pointer.velocityY) > CLOSING_VELOCITY)) {
var distanceRemaining = element.prop('offsetHeight') - ev.pointer.distanceY;
var transitionDuration = Math.min(distanceRemaining / ev.pointer.velocityY * 0.75, 500);
element.css($mdConstant.CSS.TRANSITION_DURATION, transitionDuration + 'ms');
$mdUtil.nextTick($mdBottomSheet.cancel,true);
} else {
element.css($mdConstant.CSS.TRANSITION_DURATION, '');
element.css($mdConstant.CSS.TRANSFORM, '');
}
}
}
|
javascript
|
{
"resource": ""
}
|
q20093
|
MdDialogController
|
train
|
function MdDialogController($mdDialog, $mdConstant) {
// For compatibility with AngularJS 1.6+, we should always use the $onInit hook in
// interimElements. The $mdCompiler simulates the $onInit hook for all versions.
this.$onInit = function() {
var isPrompt = this.$type == 'prompt';
if (isPrompt && this.initialValue) {
this.result = this.initialValue;
}
this.hide = function() {
$mdDialog.hide(isPrompt ? this.result : true);
};
this.abort = function() {
$mdDialog.cancel();
};
this.keypress = function($event) {
var invalidPrompt = isPrompt && this.required && !angular.isDefined(this.result);
if ($event.keyCode === $mdConstant.KEY_CODE.ENTER && !invalidPrompt) {
$mdDialog.hide(this.result);
}
};
};
}
|
javascript
|
{
"resource": ""
}
|
q20094
|
onShow
|
train
|
function onShow(scope, element, options, controller) {
angular.element($document[0].body).addClass('md-dialog-is-showing');
var dialogElement = element.find('md-dialog');
// Once a dialog has `ng-cloak` applied on his template the dialog animation will not work properly.
// This is a very common problem, so we have to notify the developer about this.
if (dialogElement.hasClass('ng-cloak')) {
var message = '$mdDialog: using `<md-dialog ng-cloak>` will affect the dialog opening animations.';
$log.warn(message, element[0]);
}
captureParentAndFromToElements(options);
configureAria(dialogElement, options);
showBackdrop(scope, element, options);
activateListeners(element, options);
return dialogPopIn(element, options)
.then(function() {
lockScreenReader(element, options);
warnDeprecatedActions();
focusOnOpen();
});
/**
* Check to see if they used the deprecated .md-actions class and log a warning
*/
function warnDeprecatedActions() {
if (element[0].querySelector('.md-actions')) {
$log.warn('Using a class of md-actions is deprecated, please use <md-dialog-actions>.');
}
}
/**
* For alerts, focus on content... otherwise focus on
* the close button (or equivalent)
*/
function focusOnOpen() {
if (options.focusOnOpen) {
var target = $mdUtil.findFocusTarget(element) || findCloseButton() || dialogElement;
target.focus();
}
/**
* If no element with class dialog-close, try to find the last
* button child in md-actions and assume it is a close button.
*
* If we find no actions at all, log a warning to the console.
*/
function findCloseButton() {
return element[0].querySelector('.dialog-close, md-dialog-actions button:last-child');
}
}
}
|
javascript
|
{
"resource": ""
}
|
q20095
|
onRemove
|
train
|
function onRemove(scope, element, options) {
options.deactivateListeners();
options.unlockScreenReader();
options.hideBackdrop(options.$destroy);
// Remove the focus traps that we added earlier for keeping focus within the dialog.
if (topFocusTrap && topFocusTrap.parentNode) {
topFocusTrap.parentNode.removeChild(topFocusTrap);
}
if (bottomFocusTrap && bottomFocusTrap.parentNode) {
bottomFocusTrap.parentNode.removeChild(bottomFocusTrap);
}
// For navigation $destroy events, do a quick, non-animated removal,
// but for normal closes (from clicks, etc) animate the removal
return options.$destroy ? detachAndClean() : animateRemoval().then(detachAndClean);
/**
* For normal closes, animate the removal.
* For forced closes (like $destroy events), skip the animations
*/
function animateRemoval() {
return dialogPopOut(element, options);
}
/**
* Detach the element
*/
function detachAndClean() {
angular.element($document[0].body).removeClass('md-dialog-is-showing');
// Reverse the container stretch if using a content element.
if (options.contentElement) {
options.reverseContainerStretch();
}
// Exposed cleanup function from the $mdCompiler.
options.cleanupElement();
// Restores the focus to the origin element if the last interaction upon opening was a keyboard.
if (!options.$destroy && options.originInteraction === 'keyboard') {
options.origin.focus();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q20096
|
detachAndClean
|
train
|
function detachAndClean() {
angular.element($document[0].body).removeClass('md-dialog-is-showing');
// Reverse the container stretch if using a content element.
if (options.contentElement) {
options.reverseContainerStretch();
}
// Exposed cleanup function from the $mdCompiler.
options.cleanupElement();
// Restores the focus to the origin element if the last interaction upon opening was a keyboard.
if (!options.$destroy && options.originInteraction === 'keyboard') {
options.origin.focus();
}
}
|
javascript
|
{
"resource": ""
}
|
q20097
|
getBoundingClientRect
|
train
|
function getBoundingClientRect (element, orig) {
var source = angular.element((element || {}));
if (source && source.length) {
// Compute and save the target element's bounding rect, so that if the
// element is hidden when the dialog closes, we can shrink the dialog
// back to the same position it expanded from.
//
// Checking if the source is a rect object or a DOM element
var bounds = {top:0,left:0,height:0,width:0};
var hasFn = angular.isFunction(source[0].getBoundingClientRect);
return angular.extend(orig || {}, {
element : hasFn ? source : undefined,
bounds : hasFn ? source[0].getBoundingClientRect() : angular.extend({}, bounds, source[0]),
focus : angular.bind(source, source.focus),
});
}
}
|
javascript
|
{
"resource": ""
}
|
q20098
|
getDomElement
|
train
|
function getDomElement(element, defaultElement) {
if (angular.isString(element)) {
element = $document[0].querySelector(element);
}
// If we have a reference to a raw dom element, always wrap it in jqLite
return angular.element(element || defaultElement);
}
|
javascript
|
{
"resource": ""
}
|
q20099
|
activateListeners
|
train
|
function activateListeners(element, options) {
var window = angular.element($window);
var onWindowResize = $mdUtil.debounce(function() {
stretchDialogContainerToViewport(element, options);
}, 60);
var removeListeners = [];
var smartClose = function() {
// Only 'confirm' dialogs have a cancel button... escape/clickOutside will
// cancel or fallback to hide.
var closeFn = (options.$type == 'alert') ? $mdDialog.hide : $mdDialog.cancel;
$mdUtil.nextTick(closeFn, true);
};
if (options.escapeToClose) {
var parentTarget = options.parent;
var keyHandlerFn = function(ev) {
if (ev.keyCode === $mdConstant.KEY_CODE.ESCAPE) {
ev.stopImmediatePropagation();
ev.preventDefault();
smartClose();
}
};
// Add keydown listeners
element.on('keydown', keyHandlerFn);
parentTarget.on('keydown', keyHandlerFn);
// Queue remove listeners function
removeListeners.push(function() {
element.off('keydown', keyHandlerFn);
parentTarget.off('keydown', keyHandlerFn);
});
}
// Register listener to update dialog on window resize
window.on('resize', onWindowResize);
removeListeners.push(function() {
window.off('resize', onWindowResize);
});
if (options.clickOutsideToClose) {
var target = element;
var sourceElem;
// Keep track of the element on which the mouse originally went down
// so that we can only close the backdrop when the 'click' started on it.
// A simple 'click' handler does not work,
// it sets the target object as the element the mouse went down on.
var mousedownHandler = function(ev) {
sourceElem = ev.target;
};
// We check if our original element and the target is the backdrop
// because if the original was the backdrop and the target was inside the dialog
// we don't want to dialog to close.
var mouseupHandler = function(ev) {
if (sourceElem === target[0] && ev.target === target[0]) {
ev.stopPropagation();
ev.preventDefault();
smartClose();
}
};
// Add listeners
target.on('mousedown', mousedownHandler);
target.on('mouseup', mouseupHandler);
// Queue remove listeners function
removeListeners.push(function() {
target.off('mousedown', mousedownHandler);
target.off('mouseup', mouseupHandler);
});
}
// Attach specific `remove` listener handler
options.deactivateListeners = function() {
removeListeners.forEach(function(removeFn) {
removeFn();
});
options.deactivateListeners = null;
};
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.