code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
function sampleVariance(x) {
if (x.length < 2) {
throw new Error("sampleVariance requires at least two data points");
}
const sumSquaredDeviationsValue = sumNthPowerDeviations(x, 2);
// this is Bessels' Correction: an adjustment made to sample statistics
// that allows for the reduced degree of freedom entailed in calculating
// values from samples rather than complete populations.
const besselsCorrection = x.length - 1;
// Find the mean value of that list
return sumSquaredDeviationsValue / besselsCorrection;
} | The [sample variance](https://en.wikipedia.org/wiki/Variance#Sample_variance)
is the sum of squared deviations from the mean. The sample variance
is distinguished from the variance by the usage of [Bessel's Correction](https://en.wikipedia.org/wiki/Bessel's_correction):
instead of dividing the sum of squared deviations by the length of the input,
it is divided by the length minus one. This corrects the bias in estimating
a value from a set that you don't know if full.
References:
* [Wolfram MathWorld on Sample Variance](http://mathworld.wolfram.com/SampleVariance.html)
@param {Array<number>} x a sample of two or more data points
@throws {Error} if the length of x is less than 2
@return {number} sample variance
@example
sampleVariance([1, 2, 3, 4, 5]); // => 2.5 | sampleVariance ( x ) | javascript | simple-statistics/simple-statistics | src/sample_variance.js | https://github.com/simple-statistics/simple-statistics/blob/master/src/sample_variance.js | ISC |
function silhouetteMetric(points, labels) {
const values = silhouette(points, labels);
return max(values);
} | Calculate the [silhouette metric](https://en.wikipedia.org/wiki/Silhouette_(clustering))
for a set of N-dimensional points arranged in groups. The metric is the largest
individual silhouette value for the data.
@param {Array<Array<number>>} points N-dimensional coordinates of points.
@param {Array<number>} labels Labels of points. This must be the same length as `points`,
and values must lie in [0..G-1], where G is the number of groups.
@return {number} The silhouette metric for the groupings.
@example
silhouetteMetric([[0.25], [0.75]], [0, 0]); // => 1.0 | silhouetteMetric ( points , labels ) | javascript | simple-statistics/simple-statistics | src/silhouette_metric.js | https://github.com/simple-statistics/simple-statistics/blob/master/src/silhouette_metric.js | ISC |
function sampleRankCorrelation(x, y) {
const xIndexes = x
.map((value, index) => [value, index])
.sort((a, b) => a[0] - b[0])
.map((pair) => pair[1]);
const yIndexes = y
.map((value, index) => [value, index])
.sort((a, b) => a[0] - b[0])
.map((pair) => pair[1]);
// At this step, we have an array of indexes
// that map from sorted numbers to their original indexes. We reverse
// that so that it is an array of the sorted destination index.
const xRanks = Array(xIndexes.length);
const yRanks = Array(xIndexes.length);
for (let i = 0; i < xIndexes.length; i++) {
xRanks[xIndexes[i]] = i;
yRanks[yIndexes[i]] = i;
}
return sampleCorrelation(xRanks, yRanks);
} | The [rank correlation](https://en.wikipedia.org/wiki/Rank_correlation) is
a measure of the strength of monotonic relationship between two arrays
@param {Array<number>} x first input
@param {Array<number>} y second input
@returns {number} sample rank correlation | sampleRankCorrelation ( x , y ) | javascript | simple-statistics/simple-statistics | src/sample_rank_correlation.js | https://github.com/simple-statistics/simple-statistics/blob/master/src/sample_rank_correlation.js | ISC |
const yallLoad = function(element, env) {
if (element.tagName === "IMG") {
let parentElement = element.parentNode;
if (parentElement.tagName === "PICTURE") {
[].slice.call(parentElement.querySelectorAll("source")).forEach((source) => {
for (let dataAttribute in source.dataset) {
if (env.acceptedDataAttributes.indexOf(`data-${dataAttribute}`) !== -1) {
source.setAttribute(dataAttribute, source.dataset[dataAttribute]);
source.removeAttribute(`data-${dataAttribute}`);
}
}
});
}
let newImageElement = new Image();
if (typeof element.dataset.srcset !== "undefined") {
newImageElement.srcset = element.dataset.srcset;
}
newImageElement.src = element.dataset.src;
if (env.asyncDecodeSupport === true) {
newImageElement.decode().then(() => {
for (let i = 0; i < element.attributes.length; i++) {
let attrName = element.attributes[i].name;
let attrValue = element.attributes[i].value;
if (env.ignoredImgAttributes.indexOf(attrName) === -1) {
newImageElement.setAttribute(attrName, attrValue);
}
}
element.replaceWith(newImageElement);
});
} else {
for (let dataAttribute in element.dataset) {
if (env.acceptedDataAttributes.indexOf(`data-${dataAttribute}`) !== -1) {
element.setAttribute(dataAttribute, element.dataset[dataAttribute]);
element.removeAttribute(`data-${dataAttribute}`);
}
}
}
}
if (element.tagName === "VIDEO") {
[].slice.call(element.querySelectorAll("source")).forEach((source) => {
for (let dataAttribute in source.dataset) {
if (env.acceptedDataAttributes.indexOf(`data-${dataAttribute}`) !== -1) {
source.setAttribute(dataAttribute, source.dataset[dataAttribute]);
source.removeAttribute(`data-${dataAttribute}`);
}
}
});
element.load();
}
if (element.tagName === "IFRAME") {
element.src = element.dataset.src;
element.removeAttribute("data-src");
}
}; | yall.js version 2.0.1
Yet Another Lazy loader
* | yallLoad ( element , env ) | javascript | sylvainpolletvillard/ObjectModel | docs/v3/lib/yall.js | https://github.com/sylvainpolletvillard/ObjectModel/blob/master/docs/v3/lib/yall.js | MIT |
export function run(input, output, userOptions={}) {
userOptions = Object.assign(userOptions, FORCED_OPTIONS);
const staticDoc = document.implementation.createHTMLDocument('New Document');
staticDoc.documentElement.innerHTML = input;
const options = new capo.options.Options(userOptions);
const io = new capo.io.IO(staticDoc.documentElement, options, output);
io.init();
logging.validateHead(io, capo.validation);
logging.logWeights(io, capo.validation, capo.rules);
} | Interface for the capo.js web client.
For configuration options see:
https://rviscomi.github.io/capo.js/user/config/#configuring-the-snippet
@param input HTML string
@param output Mock console implementation
@param options Capo options | run ( input , output , userOptions = { } ) | javascript | rviscomi/capo.js | src/web/capo.js | https://github.com/rviscomi/capo.js/blob/master/src/web/capo.js | Apache-2.0 |
constructor (name, content, reactions, index) {
this.name = name
this.content = content
this.reactions = reactions
this.index = index
} | Creates a menu page.
@param {string} name The name of this page, used as a destination for reactions.
@param {import('discord.js').MessageEmbed} content The MessageEmbed content of this page.
@param {Object.<string, string | function>} reactions The reactions that'll be added to this page.
@param {number} index The index of this page in the Menu | constructor ( name , content , reactions , index ) | javascript | jowsey/discord.js-menu | index.js | https://github.com/jowsey/discord.js-menu/blob/master/index.js | MIT |
constructor (channel, userID, pages, ms = 180000) {
super()
this.channel = channel
this.userID = userID
this.ms = ms
const missingPerms = []
// this usually means it's a dm channel that hasn't been created
if (!this.channel) {
this.channel.client.users.cache.get(this.userID).createDM(true)
}
if (this.channel.type !== 'dm') {
requiredPerms.forEach(perm => {
if (!this.channel.permissionsFor(this.channel.client.user).toArray().includes(perm)) {
missingPerms.push(perm)
}
})
if (missingPerms.length) console.log(`\x1B[96m[discord.js-menu]\x1B[0m Looks like you're missing ${missingPerms.join(', ')} in #${this.channel.name} (${this.channel.guild.name}). This perm is needed for basic menu operation. You'll probably experience problems sending menus in this channel.`)
} else {
console.log(`\x1B[96m[discord.js-menu]\x1B[0m Looks like you're trying to send a menu as a DM (to ${this.channel.recipient.tag}). DMs don't allow removing other people's reactions, making the menu fundamentally broken. The menu will still send, but you have been warned that what you're doing almost certainly won't work, so don't come complaining to me.`)
}
/**
* List of pages available to the Menu.
* @type {Page[]}
*/
this.pages = []
let i = 0
pages.forEach(page => {
this.pages.push(new Page(page.name, page.content, page.reactions, i))
i++
})
/**
* The page the Menu is currently displaying in chat.
* @type {Page}
*/
this.currentPage = this.pages[0]
/**
* The index of the Pages array we're currently on.
* @type {Number}
*/
this.pageIndex = 0
} | Creates a menu.
@param {import('discord.js').TextChannel} channel The text channel you want to send the menu in.
@param {String} userID The ID of the user you want to let control the menu.
@param {Object[]} pages An array of page objects with a name, content MessageEmbed and a set of reactions with page names which lead to said pages.
@param {String} pages.name The page's name, used as a destination for reactions.
@param {import('discord.js').MessageEmbed} pages.content The page's embed content.
@param {Object.<string, string | function>} pages.reactions The reaction options that the page has.
@param {Number} ms The number of milliseconds the menu will collect reactions for before it stops to save resources. (seconds * 1000)
@remarks
Blacklisted page names are: `first, last, previous, next, stop, delete`.
These names perform special functions and should only be used as reaction destinations. | constructor ( channel , userID , pages , ms = 180000 ) | javascript | jowsey/discord.js-menu | index.js | https://github.com/jowsey/discord.js-menu/blob/master/index.js | MIT |
start () {
// TODO: Sort out documenting this as a TSDoc event.
this.emit('pageChange', this.currentPage)
this.channel.send(this.currentPage.content).then(menu => {
this.menu = menu
this.addReactions()
this.awaitReactions()
}).catch(error => {
if (this.channel.type === 'dm') {
console.log(`\x1B[96m[discord.js-menu]\x1B[0m ${error.toString()} (whilst trying to send menu message in DMs) | The person you're trying to DM (${this.channel.client.users.cache.get(this.userID).tag}) probably has DMs turned off.`)
} else {
console.log(`\x1B[96m[discord.js-menu]\x1B[0m ${error.toString()} (whilst trying to send menu message) | You're probably missing 'SEND_MESSAGES' or 'EMBED_LINKS' in #${this.channel.name} (${this.channel.guild.name}), needed for sending the menu message.`)
}
})
} | Send the Menu and begin listening for reactions. | start ( ) | javascript | jowsey/discord.js-menu | index.js | https://github.com/jowsey/discord.js-menu/blob/master/index.js | MIT |
clearReactions () {
if (this.menu) {
return this.menu.reactions.removeAll().catch(error => {
if (this.channel.type === 'dm') {
console.log(`\x1B[96m[discord.js-menu]\x1B[0m ${error.toString()} (whilst trying to remove message reactions) | Told you so.`)
} else {
console.log(`\x1B[96m[discord.js-menu]\x1B[0m ${error.toString()} (whilst trying to remove message reactions) | You're probably missing 'MANAGE_MESSAGES' in #${this.channel.name} (${this.channel.guild.name}), needed for removing reactions when changing pages.`)
}
})
}
} | Remove all reactions from the menu message. | clearReactions ( ) | javascript | jowsey/discord.js-menu | index.js | https://github.com/jowsey/discord.js-menu/blob/master/index.js | MIT |
setPage (page = 0) {
this.emit('pageChange', this.pages[page])
this.pageIndex = page
this.currentPage = this.pages[this.pageIndex]
this.menu.edit(this.currentPage.content)
this.reactionCollector.stop()
this.addReactions()
this.awaitReactions()
} | Jump to a new page in the Menu.
@param {Number} page The index of the page the Menu should jump to. | setPage ( page = 0 ) | javascript | jowsey/discord.js-menu | index.js | https://github.com/jowsey/discord.js-menu/blob/master/index.js | MIT |
addReactions () {
for (const reaction in this.currentPage.reactions) {
this.menu.react(reaction).catch(error => {
if (error.toString().indexOf('Unknown Emoji') >= 0) {
console.log(`\x1B[96m[discord.js-menu]\x1B[0m ${error.toString()} (whilst trying to add reactions to message) | The emoji you were trying to add to page "${this.currentPage.name}" (${reaction}) probably doesn't exist. You probably entered the ID wrong when adding a custom emoji.`)
} else {
console.log(`\x1B[96m[discord.js-menu]\x1B[0m ${error.toString()} (whilst trying to add reactions to message) | You're probably missing 'ADD_REACTIONS' in #${this.channel.name} (${this.channel.guild.name}), needed for adding reactions to the page.`)
}
})
}
} | React to the new page with all of it's defined reactions | addReactions ( ) | javascript | jowsey/discord.js-menu | index.js | https://github.com/jowsey/discord.js-menu/blob/master/index.js | MIT |
this.config = function(newConfig) {
config = angular.extend(config, newConfig);
}; | @ngdoc method
@name $ariaProvider#config
@param {object} config object to enable/disable specific ARIA attributes
- **ariaHidden** β `{boolean}` β Enables/disables aria-hidden tags
- **ariaChecked** β `{boolean}` β Enables/disables aria-checked tags
- **ariaDisabled** β `{boolean}` β Enables/disables aria-disabled tags
- **ariaRequired** β `{boolean}` β Enables/disables aria-required tags
- **ariaInvalid** β `{boolean}` β Enables/disables aria-invalid tags
- **ariaMultiline** β `{boolean}` β Enables/disables aria-multiline tags
- **ariaValue** β `{boolean}` β Enables/disables aria-valuemin, aria-valuemax and aria-valuenow tags
- **tabindex** β `{boolean}` β Enables/disables tabindex tags
- **bindKeypress** β `{boolean}` β Enables/disables keypress event binding on `<div>` and
`<li>` elements with ng-click
- **bindRoleForClick** β `{boolean}` β Adds role=button to non-interactive elements like `div`
using ng-click, making them more accessible to users of assistive technologies
@description
Enables/disables various ARIA attributes | this.config ( newConfig ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-aria.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-aria.js | MIT |
this.$get = function() {
return {
config: function(key) {
return config[key];
},
$$watchExpr: watchExpr
};
}; | @ngdoc service
@name $aria
@description
@priority 200
The $aria service contains helper methods for applying common
[ARIA](http://www.w3.org/TR/wai-aria/) attributes to HTML directives.
ngAria injects common accessibility attributes that tell assistive technologies when HTML
elements are enabled, selected, hidden, and more. To see how this is performed with ngAria,
let's review a code snippet from ngAria itself:
```js
ngAriaModule.directive('ngDisabled', ['$aria', function($aria) {
return $aria.$$watchExpr('ngDisabled', 'aria-disabled');
}])
```
Shown above, the ngAria module creates a directive with the same signature as the
traditional `ng-disabled` directive. But this ngAria version is dedicated to
solely managing accessibility attributes. The internal `$aria` service is used to watch the
boolean attribute `ngDisabled`. If it has not been explicitly set by the developer,
`aria-disabled` is injected as an attribute with its value synchronized to the value in
`ngDisabled`.
Because ngAria hooks into the `ng-disabled` directive, developers do not have to do
anything to enable this feature. The `aria-disabled` attribute is automatically managed
simply as a silent side-effect of using `ng-disabled` with the ngAria module.
The full list of directives that interface with ngAria:
* **ngModel**
* **ngShow**
* **ngHide**
* **ngClick**
* **ngDblclick**
* **ngMessages**
* **ngDisabled**
Read the {@link guide/accessibility ngAria Developer Guide} for a thorough explanation of each
directive.
## Dependencies
Requires the {@link ngAria} module to be installed. | this.$get ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-aria.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-aria.js | MIT |
function $AriaProvider() {
var config = {
ariaHidden: true,
ariaChecked: true,
ariaDisabled: true,
ariaRequired: true,
ariaInvalid: true,
ariaMultiline: true,
ariaValue: true,
tabindex: true,
bindKeypress: true,
bindRoleForClick: true
};
/**
* @ngdoc method
* @name $ariaProvider#config
*
* @param {object} config object to enable/disable specific ARIA attributes
*
* - **ariaHidden** β `{boolean}` β Enables/disables aria-hidden tags
* - **ariaChecked** β `{boolean}` β Enables/disables aria-checked tags
* - **ariaDisabled** β `{boolean}` β Enables/disables aria-disabled tags
* - **ariaRequired** β `{boolean}` β Enables/disables aria-required tags
* - **ariaInvalid** β `{boolean}` β Enables/disables aria-invalid tags
* - **ariaMultiline** β `{boolean}` β Enables/disables aria-multiline tags
* - **ariaValue** β `{boolean}` β Enables/disables aria-valuemin, aria-valuemax and aria-valuenow tags
* - **tabindex** β `{boolean}` β Enables/disables tabindex tags
* - **bindKeypress** β `{boolean}` β Enables/disables keypress event binding on `<div>` and
* `<li>` elements with ng-click
* - **bindRoleForClick** β `{boolean}` β Adds role=button to non-interactive elements like `div`
* using ng-click, making them more accessible to users of assistive technologies
*
* @description
* Enables/disables various ARIA attributes
*/
this.config = function(newConfig) {
config = angular.extend(config, newConfig);
};
function watchExpr(attrName, ariaAttr, nodeBlackList, negate) {
return function(scope, elem, attr) {
var ariaCamelName = attr.$normalize(ariaAttr);
if (config[ariaCamelName] && !isNodeOneOf(elem, nodeBlackList) && !attr[ariaCamelName]) {
scope.$watch(attr[attrName], function(boolVal) {
// ensure boolean value
boolVal = negate ? !boolVal : !!boolVal;
elem.attr(ariaAttr, boolVal);
});
}
};
}
/**
* @ngdoc service
* @name $aria
*
* @description
* @priority 200
*
* The $aria service contains helper methods for applying common
* [ARIA](http://www.w3.org/TR/wai-aria/) attributes to HTML directives.
*
* ngAria injects common accessibility attributes that tell assistive technologies when HTML
* elements are enabled, selected, hidden, and more. To see how this is performed with ngAria,
* let's review a code snippet from ngAria itself:
*
*```js
* ngAriaModule.directive('ngDisabled', ['$aria', function($aria) {
* return $aria.$$watchExpr('ngDisabled', 'aria-disabled');
* }])
*```
* Shown above, the ngAria module creates a directive with the same signature as the
* traditional `ng-disabled` directive. But this ngAria version is dedicated to
* solely managing accessibility attributes. The internal `$aria` service is used to watch the
* boolean attribute `ngDisabled`. If it has not been explicitly set by the developer,
* `aria-disabled` is injected as an attribute with its value synchronized to the value in
* `ngDisabled`.
*
* Because ngAria hooks into the `ng-disabled` directive, developers do not have to do
* anything to enable this feature. The `aria-disabled` attribute is automatically managed
* simply as a silent side-effect of using `ng-disabled` with the ngAria module.
*
* The full list of directives that interface with ngAria:
* * **ngModel**
* * **ngShow**
* * **ngHide**
* * **ngClick**
* * **ngDblclick**
* * **ngMessages**
* * **ngDisabled**
*
* Read the {@link guide/accessibility ngAria Developer Guide} for a thorough explanation of each
* directive.
*
*
* ## Dependencies
* Requires the {@link ngAria} module to be installed.
*/
this.$get = function() {
return {
config: function(key) {
return config[key];
},
$$watchExpr: watchExpr
};
};
} | @ngdoc provider
@name $ariaProvider
@description
Used for configuring the ARIA attributes injected and managed by ngAria.
```js
angular.module('myApp', ['ngAria'], function config($ariaProvider) {
$ariaProvider.config({
ariaValue: true,
tabindex: false
});
});
```
## Dependencies
Requires the {@link ngAria} module to be installed. | $AriaProvider ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-aria.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-aria.js | MIT |
bind: function(element, eventHandlers, pointerTypes) {
// Absolute total movement, used to control swipe vs. scroll.
var totalX, totalY;
// Coordinates of the start position.
var startCoords;
// Last event's position.
var lastPos;
// Whether a swipe is active.
var active = false;
pointerTypes = pointerTypes || ['mouse', 'touch'];
element.on(getEvents(pointerTypes, 'start'), function(event) {
startCoords = getCoordinates(event);
active = true;
totalX = 0;
totalY = 0;
lastPos = startCoords;
eventHandlers['start'] && eventHandlers['start'](startCoords, event);
});
var events = getEvents(pointerTypes, 'cancel');
if (events) {
element.on(events, function(event) {
active = false;
eventHandlers['cancel'] && eventHandlers['cancel'](event);
});
}
element.on(getEvents(pointerTypes, 'move'), function(event) {
if (!active) return;
// Android will send a touchcancel if it thinks we're starting to scroll.
// So when the total distance (+ or - or both) exceeds 10px in either direction,
// we either:
// - On totalX > totalY, we send preventDefault() and treat this as a swipe.
// - On totalY > totalX, we let the browser handle it as a scroll.
if (!startCoords) return;
var coords = getCoordinates(event);
totalX += Math.abs(coords.x - lastPos.x);
totalY += Math.abs(coords.y - lastPos.y);
lastPos = coords;
if (totalX < MOVE_BUFFER_RADIUS && totalY < MOVE_BUFFER_RADIUS) {
return;
}
// One of totalX or totalY has exceeded the buffer, so decide on swipe vs. scroll.
if (totalY > totalX) {
// Allow native scrolling to take over.
active = false;
eventHandlers['cancel'] && eventHandlers['cancel'](event);
return;
} else {
// Prevent the browser from scrolling.
event.preventDefault();
eventHandlers['move'] && eventHandlers['move'](coords, event);
}
});
element.on(getEvents(pointerTypes, 'end'), function(event) {
if (!active) return;
active = false;
eventHandlers['end'] && eventHandlers['end'](getCoordinates(event), event);
});
} | @ngdoc method
@name $swipe#bind
@description
The main method of `$swipe`. It takes an element to be watched for swipe motions, and an
object containing event handlers.
The pointer types that should be used can be specified via the optional
third argument, which is an array of strings `'mouse'` and `'touch'`. By default,
`$swipe` will listen for `mouse` and `touch` events.
The four events are `start`, `move`, `end`, and `cancel`. `start`, `move`, and `end`
receive as a parameter a coordinates object of the form `{ x: 150, y: 310 }` and the raw
`event`. `cancel` receives the raw `event` as its single parameter.
`start` is called on either `mousedown` or `touchstart`. After this event, `$swipe` is
watching for `touchmove` or `mousemove` events. These events are ignored until the total
distance moved in either dimension exceeds a small threshold.
Once this threshold is exceeded, either the horizontal or vertical delta is greater.
- If the horizontal distance is greater, this is a swipe and `move` and `end` events follow.
- If the vertical distance is greater, this is a scroll, and we let the browser take over.
A `cancel` event is sent.
`move` is called on `mousemove` and `touchmove` after the above logic has determined that
a swipe is in progress.
`end` is called when a swipe is successfully completed with a `touchend` or `mouseup`.
`cancel` is called either on a `touchcancel` from the browser, or when we begin scrolling
as described above. | bind ( element , eventHandlers , pointerTypes ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-touch.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-touch.js | MIT |
ngTouch.factory('$swipe', [function() {
// The total distance in any direction before we make the call on swipe vs. scroll.
var MOVE_BUFFER_RADIUS = 10;
var POINTER_EVENTS = {
'mouse': {
start: 'mousedown',
move: 'mousemove',
end: 'mouseup'
},
'touch': {
start: 'touchstart',
move: 'touchmove',
end: 'touchend',
cancel: 'touchcancel'
}
};
function getCoordinates(event) {
var originalEvent = event.originalEvent || event;
var touches = originalEvent.touches && originalEvent.touches.length ? originalEvent.touches : [originalEvent];
var e = (originalEvent.changedTouches && originalEvent.changedTouches[0]) || touches[0];
return {
x: e.clientX,
y: e.clientY
};
}
function getEvents(pointerTypes, eventType) {
var res = [];
angular.forEach(pointerTypes, function(pointerType) {
var eventName = POINTER_EVENTS[pointerType][eventType];
if (eventName) {
res.push(eventName);
}
});
return res.join(' ');
}
return {
/**
* @ngdoc method
* @name $swipe#bind
*
* @description
* The main method of `$swipe`. It takes an element to be watched for swipe motions, and an
* object containing event handlers.
* The pointer types that should be used can be specified via the optional
* third argument, which is an array of strings `'mouse'` and `'touch'`. By default,
* `$swipe` will listen for `mouse` and `touch` events.
*
* The four events are `start`, `move`, `end`, and `cancel`. `start`, `move`, and `end`
* receive as a parameter a coordinates object of the form `{ x: 150, y: 310 }` and the raw
* `event`. `cancel` receives the raw `event` as its single parameter.
*
* `start` is called on either `mousedown` or `touchstart`. After this event, `$swipe` is
* watching for `touchmove` or `mousemove` events. These events are ignored until the total
* distance moved in either dimension exceeds a small threshold.
*
* Once this threshold is exceeded, either the horizontal or vertical delta is greater.
* - If the horizontal distance is greater, this is a swipe and `move` and `end` events follow.
* - If the vertical distance is greater, this is a scroll, and we let the browser take over.
* A `cancel` event is sent.
*
* `move` is called on `mousemove` and `touchmove` after the above logic has determined that
* a swipe is in progress.
*
* `end` is called when a swipe is successfully completed with a `touchend` or `mouseup`.
*
* `cancel` is called either on a `touchcancel` from the browser, or when we begin scrolling
* as described above.
*
*/
bind: function(element, eventHandlers, pointerTypes) {
// Absolute total movement, used to control swipe vs. scroll.
var totalX, totalY;
// Coordinates of the start position.
var startCoords;
// Last event's position.
var lastPos;
// Whether a swipe is active.
var active = false;
pointerTypes = pointerTypes || ['mouse', 'touch'];
element.on(getEvents(pointerTypes, 'start'), function(event) {
startCoords = getCoordinates(event);
active = true;
totalX = 0;
totalY = 0;
lastPos = startCoords;
eventHandlers['start'] && eventHandlers['start'](startCoords, event);
});
var events = getEvents(pointerTypes, 'cancel');
if (events) {
element.on(events, function(event) {
active = false;
eventHandlers['cancel'] && eventHandlers['cancel'](event);
});
}
element.on(getEvents(pointerTypes, 'move'), function(event) {
if (!active) return;
// Android will send a touchcancel if it thinks we're starting to scroll.
// So when the total distance (+ or - or both) exceeds 10px in either direction,
// we either:
// - On totalX > totalY, we send preventDefault() and treat this as a swipe.
// - On totalY > totalX, we let the browser handle it as a scroll.
if (!startCoords) return;
var coords = getCoordinates(event);
totalX += Math.abs(coords.x - lastPos.x);
totalY += Math.abs(coords.y - lastPos.y);
lastPos = coords;
if (totalX < MOVE_BUFFER_RADIUS && totalY < MOVE_BUFFER_RADIUS) {
return;
}
// One of totalX or totalY has exceeded the buffer, so decide on swipe vs. scroll.
if (totalY > totalX) {
// Allow native scrolling to take over.
active = false;
eventHandlers['cancel'] && eventHandlers['cancel'](event);
return;
} else {
// Prevent the browser from scrolling.
event.preventDefault();
eventHandlers['move'] && eventHandlers['move'](coords, event);
}
});
element.on(getEvents(pointerTypes, 'end'), function(event) {
if (!active) return;
active = false;
eventHandlers['end'] && eventHandlers['end'](getCoordinates(event), event);
});
}
};
}]); | @ngdoc service
@name $swipe
@description
The `$swipe` service is a service that abstracts the messier details of hold-and-drag swipe
behavior, to make implementing swipe-related directives more convenient.
Requires the {@link ngTouch `ngTouch`} module to be installed.
`$swipe` is used by the `ngSwipeLeft` and `ngSwipeRight` directives in `ngTouch`, and by
`ngCarousel` in a separate component.
# Usage
The `$swipe` service is an object with a single method: `bind`. `bind` takes an element
which is to be watched for swipes, and an object with four handler functions. See the
documentation for `bind` below. | (anonymous) ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-touch.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-touch.js | MIT |
function SelectMessage(expressionFn, choices) {
MessageSelectorBase.call(this, expressionFn, choices);
} | @constructor
@extends MessageSelectorBase
@private | SelectMessage ( expressionFn , choices ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-message-format.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-message-format.js | MIT |
var $$MessageFormatFactory = ['$parse', '$locale', '$sce', '$exceptionHandler', function $$messageFormat(
$parse, $locale, $sce, $exceptionHandler) {
function getStringifier(trustedContext, allOrNothing, text) {
return function stringifier(value) {
try {
value = trustedContext ? $sce['getTrusted'](trustedContext, value) : $sce['valueOf'](value);
return allOrNothing && (value === void 0) ? value : stringify(value);
} catch (err) {
$exceptionHandler($interpolateMinErr['interr'](text, err));
}
};
}
function interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
var stringifier = getStringifier(trustedContext, allOrNothing, text);
var parser = new MessageFormatParser(text, 0, $parse, $locale['pluralCat'], stringifier,
mustHaveExpression, trustedContext, allOrNothing);
parser.run(parser.ruleInterpolate);
return parser.parsedFn;
}
return {
'interpolate': interpolate
};
}]; | @ngdoc service
@name $$messageFormat
@description
Angular internal service to recognize MessageFormat extensions in interpolation expressions.
For more information, see:
https://docs.google.com/a/google.com/document/d/1pbtW2yvtmFBikfRrJd8VAsabiFkKezmYZ_PbgdjQOVU/edit
## Example
<example name="ngMessageFormat-example" module="msgFmtExample" deps="angular-message-format.min.js">
<file name="index.html">
<div ng-controller="AppController">
<button ng-click="decreaseRecipients()" id="decreaseRecipients">decreaseRecipients</button><br>
<span>{{recipients.length, plural, offset:1
=0 {{{sender.name}} gave no gifts (\#=#)}
=1 {{{sender.name}} gave one gift to {{recipients[0].name}} (\#=#)}
one {{{sender.name}} gave {{recipients[0].name}} and one other person a gift (\#=#)}
other {{{sender.name}} gave {{recipients[0].name}} and # other people a gift (\#=#)}
}}</span>
</div>
</file>
<file name="script.js">
function Person(name, gender) {
this.name = name;
this.gender = gender;
}
var alice = new Person("Alice", "female"),
bob = new Person("Bob", "male"),
charlie = new Person("Charlie", "male"),
harry = new Person("Harry Potter", "male");
angular.module('msgFmtExample', ['ngMessageFormat'])
.controller('AppController', ['$scope', function($scope) {
$scope.recipients = [alice, bob, charlie];
$scope.sender = harry;
$scope.decreaseRecipients = function() {
--$scope.recipients.length;
};
}]);
</file>
<file name="protractor.js" type="protractor">
describe('MessageFormat plural', function() {
it('should pluralize initial values', function() {
var messageElem = element(by.binding('recipients.length')), decreaseRecipientsBtn = element(by.id('decreaseRecipients'));
expect(messageElem.getText()).toEqual('Harry Potter gave Alice and 2 other people a gift (#=2)');
decreaseRecipientsBtn.click();
expect(messageElem.getText()).toEqual('Harry Potter gave Alice and one other person a gift (#=1)');
decreaseRecipientsBtn.click();
expect(messageElem.getText()).toEqual('Harry Potter gave one gift to Alice (#=0)');
decreaseRecipientsBtn.click();
expect(messageElem.getText()).toEqual('Harry Potter gave no gifts (#=-1)');
});
});
</file>
</example> | $messageFormat ( $parse , $locale , $sce , $exceptionHandler ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-message-format.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-message-format.js | MIT |
.directive('ngMessages', ['$animate', function($animate) {
var ACTIVE_CLASS = 'ng-active';
var INACTIVE_CLASS = 'ng-inactive';
return {
require: 'ngMessages',
restrict: 'AE',
controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
var ctrl = this;
var latestKey = 0;
var nextAttachId = 0;
this.getAttachId = function getAttachId() { return nextAttachId++; };
var messages = this.messages = {};
var renderLater, cachedCollection;
this.render = function(collection) {
collection = collection || {};
renderLater = false;
cachedCollection = collection;
// this is true if the attribute is empty or if the attribute value is truthy
var multiple = isAttrTruthy($scope, $attrs.ngMessagesMultiple) ||
isAttrTruthy($scope, $attrs.multiple);
var unmatchedMessages = [];
var matchedKeys = {};
var messageItem = ctrl.head;
var messageFound = false;
var totalMessages = 0;
// we use != instead of !== to allow for both undefined and null values
while (messageItem != null) {
totalMessages++;
var messageCtrl = messageItem.message;
var messageUsed = false;
if (!messageFound) {
forEach(collection, function(value, key) {
if (!messageUsed && truthy(value) && messageCtrl.test(key)) {
// this is to prevent the same error name from showing up twice
if (matchedKeys[key]) return;
matchedKeys[key] = true;
messageUsed = true;
messageCtrl.attach();
}
});
}
if (messageUsed) {
// unless we want to display multiple messages then we should
// set a flag here to avoid displaying the next message in the list
messageFound = !multiple;
} else {
unmatchedMessages.push(messageCtrl);
}
messageItem = messageItem.next;
}
forEach(unmatchedMessages, function(messageCtrl) {
messageCtrl.detach();
});
unmatchedMessages.length !== totalMessages
? $animate.setClass($element, ACTIVE_CLASS, INACTIVE_CLASS)
: $animate.setClass($element, INACTIVE_CLASS, ACTIVE_CLASS);
};
$scope.$watchCollection($attrs.ngMessages || $attrs['for'], ctrl.render);
this.reRender = function() {
if (!renderLater) {
renderLater = true;
$scope.$evalAsync(function() {
if (renderLater) {
cachedCollection && ctrl.render(cachedCollection);
}
});
}
};
this.register = function(comment, messageCtrl) {
var nextKey = latestKey.toString();
messages[nextKey] = {
message: messageCtrl
};
insertMessageNode($element[0], comment, nextKey);
comment.$$ngMessageNode = nextKey;
latestKey++;
ctrl.reRender();
};
this.deregister = function(comment) {
var key = comment.$$ngMessageNode;
delete comment.$$ngMessageNode;
removeMessageNode($element[0], comment, key);
delete messages[key];
ctrl.reRender();
};
function findPreviousMessage(parent, comment) {
var prevNode = comment;
var parentLookup = [];
while (prevNode && prevNode !== parent) {
var prevKey = prevNode.$$ngMessageNode;
if (prevKey && prevKey.length) {
return messages[prevKey];
}
// dive deeper into the DOM and examine its children for any ngMessage
// comments that may be in an element that appears deeper in the list
if (prevNode.childNodes.length && parentLookup.indexOf(prevNode) == -1) {
parentLookup.push(prevNode);
prevNode = prevNode.childNodes[prevNode.childNodes.length - 1];
} else {
prevNode = prevNode.previousSibling || prevNode.parentNode;
}
}
}
function insertMessageNode(parent, comment, key) {
var messageNode = messages[key];
if (!ctrl.head) {
ctrl.head = messageNode;
} else {
var match = findPreviousMessage(parent, comment);
if (match) {
messageNode.next = match.next;
match.next = messageNode;
} else {
messageNode.next = ctrl.head;
ctrl.head = messageNode;
}
}
}
function removeMessageNode(parent, comment, key) {
var messageNode = messages[key];
var match = findPreviousMessage(parent, comment);
if (match) {
match.next = messageNode.next;
} else {
ctrl.head = messageNode.next;
}
}
}]
};
function isAttrTruthy(scope, attr) {
return (isString(attr) && attr.length === 0) || //empty attribute
truthy(scope.$eval(attr));
}
function truthy(val) {
return isString(val) ? val.length : !!val;
}
}]) | @ngdoc directive
@module ngMessages
@name ngMessages
@restrict AE
@description
`ngMessages` is a directive that is designed to show and hide messages based on the state
of a key/value object that it listens on. The directive itself complements error message
reporting with the `ngModel` $error object (which stores a key/value state of validation errors).
`ngMessages` manages the state of internal messages within its container element. The internal
messages use the `ngMessage` directive and will be inserted/removed from the page depending
on if they're present within the key/value object. By default, only one message will be displayed
at a time and this depends on the prioritization of the messages within the template. (This can
be changed by using the `ng-messages-multiple` or `multiple` attribute on the directive container.)
A remote template can also be used to promote message reusability and messages can also be
overridden.
{@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`.
@usage
```html
<!-- using attribute directives -->
<ANY ng-messages="expression" role="alert">
<ANY ng-message="stringValue">...</ANY>
<ANY ng-message="stringValue1, stringValue2, ...">...</ANY>
<ANY ng-message-exp="expressionValue">...</ANY>
</ANY>
<!-- or by using element directives -->
<ng-messages for="expression" role="alert">
<ng-message when="stringValue">...</ng-message>
<ng-message when="stringValue1, stringValue2, ...">...</ng-message>
<ng-message when-exp="expressionValue">...</ng-message>
</ng-messages>
```
@param {string} ngMessages an angular expression evaluating to a key/value object
(this is typically the $error object on an ngModel instance).
@param {string=} ngMessagesMultiple|multiple when set, all messages will be displayed with true
@example
<example name="ngMessages-directive" module="ngMessagesExample"
deps="angular-messages.js"
animations="true" fixBase="true">
<file name="index.html">
<form name="myForm">
<label>
Enter your name:
<input type="text"
name="myName"
ng-model="name"
ng-minlength="5"
ng-maxlength="20"
required />
</label>
<pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>
<div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
<div ng-message="required">You did not enter a field</div>
<div ng-message="minlength">Your field is too short</div>
<div ng-message="maxlength">Your field is too long</div>
</div>
</form>
</file>
<file name="script.js">
angular.module('ngMessagesExample', ['ngMessages']);
</file>
</example> | (anonymous) ( $animate ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-messages.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-messages.js | MIT |
(function(window, angular, undefined) {'use strict';
/* jshint ignore:start */
// this code is in the core, but not in angular-messages.js
var isArray = angular.isArray;
var forEach = angular.forEach;
var isString = angular.isString;
var jqLite = angular.element;
/* jshint ignore:end */
/**
* @ngdoc module
* @name ngMessages
* @description
*
* The `ngMessages` module provides enhanced support for displaying messages within templates
* (typically within forms or when rendering message objects that return key/value data).
* Instead of relying on JavaScript code and/or complex ng-if statements within your form template to
* show and hide error messages specific to the state of an input field, the `ngMessages` and
* `ngMessage` directives are designed to handle the complexity, inheritance and priority
* sequencing based on the order of how the messages are defined in the template.
*
* Currently, the ngMessages module only contains the code for the `ngMessages`, `ngMessagesInclude`
* `ngMessage` and `ngMessageExp` directives.
*
* # Usage
* The `ngMessages` directive listens on a key/value collection which is set on the ngMessages attribute.
* Since the {@link ngModel ngModel} directive exposes an `$error` object, this error object can be
* used with `ngMessages` to display control error messages in an easier way than with just regular angular
* template directives.
*
* ```html
* <form name="myForm">
* <label>
* Enter text:
* <input type="text" ng-model="field" name="myField" required minlength="5" />
* </label>
* <div ng-messages="myForm.myField.$error" role="alert">
* <div ng-message="required">You did not enter a field</div>
* <div ng-message="minlength, maxlength">
* Your email must be between 5 and 100 characters long
* </div>
* </div>
* </form>
* ```
*
* Now whatever key/value entries are present within the provided object (in this case `$error`) then
* the ngMessages directive will render the inner first ngMessage directive (depending if the key values
* match the attribute value present on each ngMessage directive). In other words, if your errors
* object contains the following data:
*
* ```javascript
* <!-- keep in mind that ngModel automatically sets these error flags -->
* myField.$error = { minlength : true, required : true };
* ```
*
* Then the `required` message will be displayed first. When required is false then the `minlength` message
* will be displayed right after (since these messages are ordered this way in the template HTML code).
* The prioritization of each message is determined by what order they're present in the DOM.
* Therefore, instead of having custom JavaScript code determine the priority of what errors are
* present before others, the presentation of the errors are handled within the template.
*
* By default, ngMessages will only display one error at a time. However, if you wish to display all
* messages then the `ng-messages-multiple` attribute flag can be used on the element containing the
* ngMessages directive to make this happen.
*
* ```html
* <!-- attribute-style usage -->
* <div ng-messages="myForm.myField.$error" ng-messages-multiple>...</div>
*
* <!-- element-style usage -->
* <ng-messages for="myForm.myField.$error" multiple>...</ng-messages>
* ```
*
* ## Reusing and Overriding Messages
* In addition to prioritization, ngMessages also allows for including messages from a remote or an inline
* template. This allows for generic collection of messages to be reused across multiple parts of an
* application.
*
* ```html
* <script type="text/ng-template" id="error-messages">
* <div ng-message="required">This field is required</div>
* <div ng-message="minlength">This field is too short</div>
* </script>
*
* <div ng-messages="myForm.myField.$error" role="alert">
* <div ng-messages-include="error-messages"></div>
* </div>
* ```
*
* However, including generic messages may not be useful enough to match all input fields, therefore,
* `ngMessages` provides the ability to override messages defined in the remote template by redefining
* them within the directive container.
*
* ```html
* <!-- a generic template of error messages known as "my-custom-messages" -->
* <script type="text/ng-template" id="my-custom-messages">
* <div ng-message="required">This field is required</div>
* <div ng-message="minlength">This field is too short</div>
* </script>
*
* <form name="myForm">
* <label>
* Email address
* <input type="email"
* id="email"
* name="myEmail"
* ng-model="email"
* minlength="5"
* required />
* </label>
* <!-- any ng-message elements that appear BEFORE the ng-messages-include will
* override the messages present in the ng-messages-include template -->
* <div ng-messages="myForm.myEmail.$error" role="alert">
* <!-- this required message has overridden the template message -->
* <div ng-message="required">You did not enter your email address</div>
*
* <!-- this is a brand new message and will appear last in the prioritization -->
* <div ng-message="email">Your email address is invalid</div>
*
* <!-- and here are the generic error messages -->
* <div ng-messages-include="my-custom-messages"></div>
* </div>
* </form>
* ```
*
* In the example HTML code above the message that is set on required will override the corresponding
* required message defined within the remote template. Therefore, with particular input fields (such
* email addresses, date fields, autocomplete inputs, etc...), specialized error messages can be applied
* while more generic messages can be used to handle other, more general input errors.
*
* ## Dynamic Messaging
* ngMessages also supports using expressions to dynamically change key values. Using arrays and
* repeaters to list messages is also supported. This means that the code below will be able to
* fully adapt itself and display the appropriate message when any of the expression data changes:
*
* ```html
* <form name="myForm">
* <label>
* Email address
* <input type="email"
* name="myEmail"
* ng-model="email"
* minlength="5"
* required />
* </label>
* <div ng-messages="myForm.myEmail.$error" role="alert">
* <div ng-message="required">You did not enter your email address</div>
* <div ng-repeat="errorMessage in errorMessages">
* <!-- use ng-message-exp for a message whose key is given by an expression -->
* <div ng-message-exp="errorMessage.type">{{ errorMessage.text }}</div>
* </div>
* </div>
* </form>
* ```
*
* The `errorMessage.type` expression can be a string value or it can be an array so
* that multiple errors can be associated with a single error message:
*
* ```html
* <label>
* Email address
* <input type="email"
* ng-model="data.email"
* name="myEmail"
* ng-minlength="5"
* ng-maxlength="100"
* required />
* </label>
* <div ng-messages="myForm.myEmail.$error" role="alert">
* <div ng-message-exp="'required'">You did not enter your email address</div>
* <div ng-message-exp="['minlength', 'maxlength']">
* Your email must be between 5 and 100 characters long
* </div>
* </div>
* ```
*
* Feel free to use other structural directives such as ng-if and ng-switch to further control
* what messages are active and when. Be careful, if you place ng-message on the same element
* as these structural directives, Angular may not be able to determine if a message is active
* or not. Therefore it is best to place the ng-message on a child element of the structural
* directive.
*
* ```html
* <div ng-messages="myForm.myEmail.$error" role="alert">
* <div ng-if="showRequiredError">
* <div ng-message="required">Please enter something</div>
* </div>
* </div>
* ```
*
* ## Animations
* If the `ngAnimate` module is active within the application then the `ngMessages`, `ngMessage` and
* `ngMessageExp` directives will trigger animations whenever any messages are added and removed from
* the DOM by the `ngMessages` directive.
*
* Whenever the `ngMessages` directive contains one or more visible messages then the `.ng-active` CSS
* class will be added to the element. The `.ng-inactive` CSS class will be applied when there are no
* messages present. Therefore, CSS transitions and keyframes as well as JavaScript animations can
* hook into the animations whenever these classes are added/removed.
*
* Let's say that our HTML code for our messages container looks like so:
*
* ```html
* <div ng-messages="myMessages" class="my-messages" role="alert">
* <div ng-message="alert" class="some-message">...</div>
* <div ng-message="fail" class="some-message">...</div>
* </div>
* ```
*
* Then the CSS animation code for the message container looks like so:
*
* ```css
* .my-messages {
* transition:1s linear all;
* }
* .my-messages.ng-active {
* // messages are visible
* }
* .my-messages.ng-inactive {
* // messages are hidden
* }
* ```
*
* Whenever an inner message is attached (becomes visible) or removed (becomes hidden) then the enter
* and leave animation is triggered for each particular element bound to the `ngMessage` directive.
*
* Therefore, the CSS code for the inner messages looks like so:
*
* ```css
* .some-message {
* transition:1s linear all;
* }
*
* .some-message.ng-enter {}
* .some-message.ng-enter.ng-enter-active {}
*
* .some-message.ng-leave {}
* .some-message.ng-leave.ng-leave-active {}
* ```
*
* {@link ngAnimate Click here} to learn how to use JavaScript animations or to learn more about ngAnimate.
*/
angular.module('ngMessages', [])
/**
* @ngdoc directive
* @module ngMessages
* @name ngMessages
* @restrict AE
*
* @description
* `ngMessages` is a directive that is designed to show and hide messages based on the state
* of a key/value object that it listens on. The directive itself complements error message
* reporting with the `ngModel` $error object (which stores a key/value state of validation errors).
*
* `ngMessages` manages the state of internal messages within its container element. The internal
* messages use the `ngMessage` directive and will be inserted/removed from the page depending
* on if they're present within the key/value object. By default, only one message will be displayed
* at a time and this depends on the prioritization of the messages within the template. (This can
* be changed by using the `ng-messages-multiple` or `multiple` attribute on the directive container.)
*
* A remote template can also be used to promote message reusability and messages can also be
* overridden.
*
* {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`.
*
* @usage
* ```html
* <!-- using attribute directives -->
* <ANY ng-messages="expression" role="alert">
* <ANY ng-message="stringValue">...</ANY>
* <ANY ng-message="stringValue1, stringValue2, ...">...</ANY>
* <ANY ng-message-exp="expressionValue">...</ANY>
* </ANY>
*
* <!-- or by using element directives -->
* <ng-messages for="expression" role="alert">
* <ng-message when="stringValue">...</ng-message>
* <ng-message when="stringValue1, stringValue2, ...">...</ng-message>
* <ng-message when-exp="expressionValue">...</ng-message>
* </ng-messages>
* ```
*
* @param {string} ngMessages an angular expression evaluating to a key/value object
* (this is typically the $error object on an ngModel instance).
* @param {string=} ngMessagesMultiple|multiple when set, all messages will be displayed with true
*
* @example
* <example name="ngMessages-directive" module="ngMessagesExample"
* deps="angular-messages.js"
* animations="true" fixBase="true">
* <file name="index.html">
* <form name="myForm">
* <label>
* Enter your name:
* <input type="text"
* name="myName"
* ng-model="name"
* ng-minlength="5"
* ng-maxlength="20"
* required />
* </label>
* <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>
*
* <div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
* <div ng-message="required">You did not enter a field</div>
* <div ng-message="minlength">Your field is too short</div>
* <div ng-message="maxlength">Your field is too long</div>
* </div>
* </form>
* </file>
* <file name="script.js">
* angular.module('ngMessagesExample', ['ngMessages']);
* </file>
* </example>
*/
.directive('ngMessages', ['$animate', function($animate) {
var ACTIVE_CLASS = 'ng-active';
var INACTIVE_CLASS = 'ng-inactive';
return {
require: 'ngMessages',
restrict: 'AE',
controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
var ctrl = this;
var latestKey = 0;
var nextAttachId = 0;
this.getAttachId = function getAttachId() { return nextAttachId++; };
var messages = this.messages = {};
var renderLater, cachedCollection;
this.render = function(collection) {
collection = collection || {};
renderLater = false;
cachedCollection = collection;
// this is true if the attribute is empty or if the attribute value is truthy
var multiple = isAttrTruthy($scope, $attrs.ngMessagesMultiple) ||
isAttrTruthy($scope, $attrs.multiple);
var unmatchedMessages = [];
var matchedKeys = {};
var messageItem = ctrl.head;
var messageFound = false;
var totalMessages = 0;
// we use != instead of !== to allow for both undefined and null values
while (messageItem != null) {
totalMessages++;
var messageCtrl = messageItem.message;
var messageUsed = false;
if (!messageFound) {
forEach(collection, function(value, key) {
if (!messageUsed && truthy(value) && messageCtrl.test(key)) {
// this is to prevent the same error name from showing up twice
if (matchedKeys[key]) return;
matchedKeys[key] = true;
messageUsed = true;
messageCtrl.attach();
}
});
}
if (messageUsed) {
// unless we want to display multiple messages then we should
// set a flag here to avoid displaying the next message in the list
messageFound = !multiple;
} else {
unmatchedMessages.push(messageCtrl);
}
messageItem = messageItem.next;
}
forEach(unmatchedMessages, function(messageCtrl) {
messageCtrl.detach();
});
unmatchedMessages.length !== totalMessages
? $animate.setClass($element, ACTIVE_CLASS, INACTIVE_CLASS)
: $animate.setClass($element, INACTIVE_CLASS, ACTIVE_CLASS);
};
$scope.$watchCollection($attrs.ngMessages || $attrs['for'], ctrl.render);
this.reRender = function() {
if (!renderLater) {
renderLater = true;
$scope.$evalAsync(function() {
if (renderLater) {
cachedCollection && ctrl.render(cachedCollection);
}
});
}
};
this.register = function(comment, messageCtrl) {
var nextKey = latestKey.toString();
messages[nextKey] = {
message: messageCtrl
};
insertMessageNode($element[0], comment, nextKey);
comment.$$ngMessageNode = nextKey;
latestKey++;
ctrl.reRender();
};
this.deregister = function(comment) {
var key = comment.$$ngMessageNode;
delete comment.$$ngMessageNode;
removeMessageNode($element[0], comment, key);
delete messages[key];
ctrl.reRender();
};
function findPreviousMessage(parent, comment) {
var prevNode = comment;
var parentLookup = [];
while (prevNode && prevNode !== parent) {
var prevKey = prevNode.$$ngMessageNode;
if (prevKey && prevKey.length) {
return messages[prevKey];
}
// dive deeper into the DOM and examine its children for any ngMessage
// comments that may be in an element that appears deeper in the list
if (prevNode.childNodes.length && parentLookup.indexOf(prevNode) == -1) {
parentLookup.push(prevNode);
prevNode = prevNode.childNodes[prevNode.childNodes.length - 1];
} else {
prevNode = prevNode.previousSibling || prevNode.parentNode;
}
}
}
function insertMessageNode(parent, comment, key) {
var messageNode = messages[key];
if (!ctrl.head) {
ctrl.head = messageNode;
} else {
var match = findPreviousMessage(parent, comment);
if (match) {
messageNode.next = match.next;
match.next = messageNode;
} else {
messageNode.next = ctrl.head;
ctrl.head = messageNode;
}
}
}
function removeMessageNode(parent, comment, key) {
var messageNode = messages[key];
var match = findPreviousMessage(parent, comment);
if (match) {
match.next = messageNode.next;
} else {
ctrl.head = messageNode.next;
}
}
}]
};
function isAttrTruthy(scope, attr) {
return (isString(attr) && attr.length === 0) || //empty attribute
truthy(scope.$eval(attr));
}
function truthy(val) {
return isString(val) ? val.length : !!val;
}
}])
/**
* @ngdoc directive
* @name ngMessagesInclude
* @restrict AE
* @scope
*
* @description
* `ngMessagesInclude` is a directive with the purpose to import existing ngMessage template
* code from a remote template and place the downloaded template code into the exact spot
* that the ngMessagesInclude directive is placed within the ngMessages container. This allows
* for a series of pre-defined messages to be reused and also allows for the developer to
* determine what messages are overridden due to the placement of the ngMessagesInclude directive.
*
* @usage
* ```html
* <!-- using attribute directives -->
* <ANY ng-messages="expression" role="alert">
* <ANY ng-messages-include="remoteTplString">...</ANY>
* </ANY>
*
* <!-- or by using element directives -->
* <ng-messages for="expression" role="alert">
* <ng-messages-include src="expressionValue1">...</ng-messages-include>
* </ng-messages>
* ```
*
* {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`.
*
* @param {string} ngMessagesInclude|src a string value corresponding to the remote template.
*/
.directive('ngMessagesInclude',
['$templateRequest', '$document', '$compile', function($templateRequest, $document, $compile) {
return {
restrict: 'AE',
require: '^^ngMessages', // we only require this for validation sake
link: function($scope, element, attrs) {
var src = attrs.ngMessagesInclude || attrs.src;
$templateRequest(src).then(function(html) {
$compile(html)($scope, function(contents) {
element.after(contents);
// the anchor is placed for debugging purposes
var anchor = jqLite($document[0].createComment(' ngMessagesInclude: ' + src + ' '));
element.after(anchor);
// we don't want to pollute the DOM anymore by keeping an empty directive element
element.remove();
});
});
}
};
}])
/**
* @ngdoc directive
* @name ngMessage
* @restrict AE
* @scope
*
* @description
* `ngMessage` is a directive with the purpose to show and hide a particular message.
* For `ngMessage` to operate, a parent `ngMessages` directive on a parent DOM element
* must be situated since it determines which messages are visible based on the state
* of the provided key/value map that `ngMessages` listens on.
*
* More information about using `ngMessage` can be found in the
* {@link module:ngMessages `ngMessages` module documentation}.
*
* @usage
* ```html
* <!-- using attribute directives -->
* <ANY ng-messages="expression" role="alert">
* <ANY ng-message="stringValue">...</ANY>
* <ANY ng-message="stringValue1, stringValue2, ...">...</ANY>
* </ANY>
*
* <!-- or by using element directives -->
* <ng-messages for="expression" role="alert">
* <ng-message when="stringValue">...</ng-message>
* <ng-message when="stringValue1, stringValue2, ...">...</ng-message>
* </ng-messages>
* ```
*
* @param {expression} ngMessage|when a string value corresponding to the message key.
*/
.directive('ngMessage', ngMessageDirectiveFactory('AE'))
/**
* @ngdoc directive
* @name ngMessageExp
* @restrict AE
* @scope
*
* @description
* `ngMessageExp` is a directive with the purpose to show and hide a particular message.
* For `ngMessageExp` to operate, a parent `ngMessages` directive on a parent DOM element
* must be situated since it determines which messages are visible based on the state
* of the provided key/value map that `ngMessages` listens on.
*
* @usage
* ```html
* <!-- using attribute directives -->
* <ANY ng-messages="expression">
* <ANY ng-message-exp="expressionValue">...</ANY>
* </ANY>
*
* <!-- or by using element directives -->
* <ng-messages for="expression">
* <ng-message when-exp="expressionValue">...</ng-message>
* </ng-messages>
* ```
*
* {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`.
*
* @param {expression} ngMessageExp|whenExp an expression value corresponding to the message key.
*/
.directive('ngMessageExp', ngMessageDirectiveFactory('A'));
function ngMessageDirectiveFactory(restrict) {
return ['$animate', function($animate) {
return {
restrict: 'AE',
transclude: 'element',
terminal: true,
require: '^^ngMessages',
link: function(scope, element, attrs, ngMessagesCtrl, $transclude) {
var commentNode = element[0];
var records;
var staticExp = attrs.ngMessage || attrs.when;
var dynamicExp = attrs.ngMessageExp || attrs.whenExp;
var assignRecords = function(items) {
records = items
? (isArray(items)
? items
: items.split(/[\s,]+/))
: null;
ngMessagesCtrl.reRender();
};
if (dynamicExp) {
assignRecords(scope.$eval(dynamicExp));
scope.$watchCollection(dynamicExp, assignRecords);
} else {
assignRecords(staticExp);
}
var currentElement, messageCtrl;
ngMessagesCtrl.register(commentNode, messageCtrl = {
test: function(name) {
return contains(records, name);
},
attach: function() {
if (!currentElement) {
$transclude(scope, function(elm) {
$animate.enter(elm, null, element);
currentElement = elm;
// Each time we attach this node to a message we get a new id that we can match
// when we are destroying the node later.
var $$attachId = currentElement.$$attachId = ngMessagesCtrl.getAttachId();
// in the event that the parent element is destroyed
// by any other structural directive then it's time
// to deregister the message from the controller
currentElement.on('$destroy', function() {
if (currentElement && currentElement.$$attachId === $$attachId) {
ngMessagesCtrl.deregister(commentNode);
messageCtrl.detach();
}
});
});
}
},
detach: function() {
if (currentElement) {
var elm = currentElement;
currentElement = null;
$animate.leave(elm);
}
}
});
}
};
}];
function contains(collection, key) {
if (collection) {
return isArray(collection)
? collection.indexOf(key) >= 0
: collection.hasOwnProperty(key);
}
}
}
})(window, window.angular); | @license AngularJS v1.4.8
(c) 2010-2015 Google, Inc. http://angularjs.org
License: MIT | (anonymous) ( window , angular , undefined ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-messages.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-messages.js | MIT |
this.when = function(path, route) {
//copy original route object to preserve params inherited from proto chain
var routeCopy = angular.copy(route);
if (angular.isUndefined(routeCopy.reloadOnSearch)) {
routeCopy.reloadOnSearch = true;
}
if (angular.isUndefined(routeCopy.caseInsensitiveMatch)) {
routeCopy.caseInsensitiveMatch = this.caseInsensitiveMatch;
}
routes[path] = angular.extend(
routeCopy,
path && pathRegExp(path, routeCopy)
);
// create redirection for trailing slashes
if (path) {
var redirectPath = (path[path.length - 1] == '/')
? path.substr(0, path.length - 1)
: path + '/';
routes[redirectPath] = angular.extend(
{redirectTo: path},
pathRegExp(redirectPath, routeCopy)
);
}
return this;
}; | @ngdoc method
@name $routeProvider#when
@param {string} path Route path (matched against `$location.path`). If `$location.path`
contains redundant trailing slash or is missing one, the route will still match and the
`$location.path` will be updated to add or drop the trailing slash to exactly match the
route definition.
* `path` can contain named groups starting with a colon: e.g. `:name`. All characters up
to the next slash are matched and stored in `$routeParams` under the given `name`
when the route matches.
* `path` can contain named groups starting with a colon and ending with a star:
e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name`
when the route matches.
* `path` can contain optional named groups with a question mark: e.g.`:name?`.
For example, routes like `/color/:color/largecode/:largecode*\/edit` will match
`/color/brown/largecode/code/with/slashes/edit` and extract:
* `color: brown`
* `largecode: code/with/slashes`.
@param {Object} route Mapping information to be assigned to `$route.current` on route
match.
Object properties:
- `controller` β `{(string|function()=}` β Controller fn that should be associated with
newly created scope or the name of a {@link angular.Module#controller registered
controller} if passed as a string.
- `controllerAs` β `{string=}` β An identifier name for a reference to the controller.
If present, the controller will be published to scope under the `controllerAs` name.
- `template` β `{string=|function()=}` β html template as a string or a function that
returns an html template as a string which should be used by {@link
ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives.
This property takes precedence over `templateUrl`.
If `template` is a function, it will be called with the following parameters:
- `{Array.<Object>}` - route parameters extracted from the current
`$location.path()` by applying the current route
- `templateUrl` β `{string=|function()=}` β path or function that returns a path to an html
template that should be used by {@link ngRoute.directive:ngView ngView}.
If `templateUrl` is a function, it will be called with the following parameters:
- `{Array.<Object>}` - route parameters extracted from the current
`$location.path()` by applying the current route
- `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
be injected into the controller. If any of these dependencies are promises, the router
will wait for them all to be resolved or one to be rejected before the controller is
instantiated.
If all the promises are resolved successfully, the values of the resolved promises are
injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is
fired. If any of the promises are rejected the
{@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object
is:
- `key` β `{string}`: a name of a dependency to be injected into the controller.
- `factory` - `{string|function}`: If `string` then it is an alias for a service.
Otherwise if function, then it is {@link auto.$injector#invoke injected}
and the return value is treated as the dependency. If the result is a promise, it is
resolved before its value is injected into the controller. Be aware that
`ngRoute.$routeParams` will still refer to the previous route within these resolve
functions. Use `$route.current.params` to access the new route parameters, instead.
- `redirectTo` β {(string|function())=} β value to update
{@link ng.$location $location} path with and trigger route redirection.
If `redirectTo` is a function, it will be called with the following parameters:
- `{Object.<string>}` - route parameters extracted from the current
`$location.path()` by applying the current route templateUrl.
- `{string}` - current `$location.path()`
- `{Object}` - current `$location.search()`
The custom `redirectTo` function is expected to return a string which will be used
to update `$location.path()` and `$location.search()`.
- `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()`
or `$location.hash()` changes.
If the option is set to `false` and url in the browser changes, then
`$routeUpdate` event is broadcasted on the root scope.
- `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive
If the option is set to `true`, then the particular route can be matched without being
case sensitive
@returns {Object} self
@description
Adds a new route definition to the `$route` service. | this.when ( path , route ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-route.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-route.js | MIT |
run: function(block) {
runBlocks.push(block);
return this;
} | @ngdoc method
@name angular.Module#run
@module ng
@param {Function} initializationFn Execute this function after injector creation.
Useful for application initialization.
@description
Use this method to register work which should be performed when the injector is done
loading all modules. | run ( block ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | MIT |
function invokeLater(provider, method, insertMethod, queue) {
if (!queue) queue = invokeQueue;
return function() {
queue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
};
} | @param {string} provider
@param {string} method
@param {String=} insertMethod
@returns {angular.Module} | invokeLater ( provider , method , insertMethod , queue ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | MIT |
function invokeLaterAndSetModuleName(provider, method) {
return function(recipeName, factoryFunction) {
if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
invokeQueue.push([provider, method, arguments]);
return moduleInstance;
};
} | @param {string} provider
@param {string} method
@returns {angular.Module} | invokeLaterAndSetModuleName ( provider , method ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | MIT |
directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @module ng
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
* For more about how to configure services, see
* {@link providers#provider-recipe Provider Recipe}.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @module ng
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which should be performed when the injector is done
* loading all modules.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod, queue) {
if (!queue) queue = invokeQueue;
return function() {
queue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
};
}
/**
* @param {string} provider
* @param {string} method
* @returns {angular.Module}
*/
function invokeLaterAndSetModuleName(provider, method) {
return function(recipeName, factoryFunction) {
if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
invokeQueue.push([provider, method, arguments]);
return moduleInstance;
};
}
}); | @ngdoc method
@name angular.Module#directive
@module ng
@param {string|Object} name Directive name, or an object map of directives where the
keys are the names and the values are the factories.
@param {Function} directiveFactory Factory function for creating new instance of
directives.
@description
See {@link ng.$compileProvider#directive $compileProvider.directive()}. | invokeLaterAndSetModuleName ( '$compileProvider' , 'directive' ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | MIT |
controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @module ng
* @param {string|Object} name Directive name, or an object map of directives where the
* keys are the names and the values are the factories.
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider#directive $compileProvider.directive()}.
*/
directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @module ng
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
* For more about how to configure services, see
* {@link providers#provider-recipe Provider Recipe}.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @module ng
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which should be performed when the injector is done
* loading all modules.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod, queue) {
if (!queue) queue = invokeQueue;
return function() {
queue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
};
}
/**
* @param {string} provider
* @param {string} method
* @returns {angular.Module}
*/
function invokeLaterAndSetModuleName(provider, method) {
return function(recipeName, factoryFunction) {
if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
invokeQueue.push([provider, method, arguments]);
return moduleInstance;
};
}
});
}; | @ngdoc method
@name angular.Module#controller
@module ng
@param {string|Object} name Controller name, or an object map of controllers where the
keys are the names and the values are the constructors.
@param {Function} constructor Controller constructor function.
@description
See {@link ng.$controllerProvider#register $controllerProvider.register()}. | invokeLaterAndSetModuleName ( '$controllerProvider' , 'register' ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | MIT |
filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @module ng
* @param {string|Object} name Controller name, or an object map of controllers where the
* keys are the names and the values are the constructors.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @module ng
* @param {string|Object} name Directive name, or an object map of directives where the
* keys are the names and the values are the factories.
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider#directive $compileProvider.directive()}.
*/
directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @module ng
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
* For more about how to configure services, see
* {@link providers#provider-recipe Provider Recipe}.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @module ng
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which should be performed when the injector is done
* loading all modules.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod, queue) {
if (!queue) queue = invokeQueue;
return function() {
queue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
};
}
/**
* @param {string} provider
* @param {string} method
* @returns {angular.Module}
*/
function invokeLaterAndSetModuleName(provider, method) {
return function(recipeName, factoryFunction) {
if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
invokeQueue.push([provider, method, arguments]);
return moduleInstance;
};
}
});
};
}); | @ngdoc method
@name angular.Module#filter
@module ng
@param {string} name Filter name - this must be a valid angular expression identifier
@param {Function} filterFactory Factory function for creating new instance of filter.
@description
See {@link ng.$filterProvider#register $filterProvider.register()}.
<div class="alert alert-warning">
**Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
(`myapp_subsection_filterx`).
</div> | invokeLaterAndSetModuleName ( '$filterProvider' , 'register' ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | MIT |
animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#filter
* @module ng
* @param {string} name Filter name - this must be a valid angular expression identifier
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*
* <div class="alert alert-warning">
* **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
* Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
* your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
* (`myapp_subsection_filterx`).
* </div>
*/
filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @module ng
* @param {string|Object} name Controller name, or an object map of controllers where the
* keys are the names and the values are the constructors.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @module ng
* @param {string|Object} name Directive name, or an object map of directives where the
* keys are the names and the values are the factories.
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider#directive $compileProvider.directive()}.
*/
directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @module ng
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
* For more about how to configure services, see
* {@link providers#provider-recipe Provider Recipe}.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @module ng
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which should be performed when the injector is done
* loading all modules.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod, queue) {
if (!queue) queue = invokeQueue;
return function() {
queue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
};
}
/**
* @param {string} provider
* @param {string} method
* @returns {angular.Module}
*/
function invokeLaterAndSetModuleName(provider, method) {
return function(recipeName, factoryFunction) {
if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
invokeQueue.push([provider, method, arguments]);
return moduleInstance;
};
}
});
};
});
} | @ngdoc method
@name angular.Module#animation
@module ng
@param {string} name animation name
@param {Function} animationFactory Factory function for creating new instance of an
animation.
@description
**NOTE**: animations take effect only if the **ngAnimate** module is loaded.
Defines an animation hook that can be later used with
{@link $animate $animate} service and directives that use this service.
```js
module.animation('.animation-name', function($inject1, $inject2) {
return {
eventName : function(element, done) {
//code to run the animation
//once complete, then run done()
return function cancellationFunction(element) {
//code to cancel the animation
}
}
}
})
```
See {@link ng.$animateProvider#register $animateProvider.register()} and
{@link ngAnimate ngAnimate module} for more information. | invokeLaterAndSetModuleName ( '$animateProvider' , 'register' ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | MIT |
decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
/**
* @ngdoc method
* @name angular.Module#animation
* @module ng
* @param {string} name animation name
* @param {Function} animationFactory Factory function for creating new instance of an
* animation.
* @description
*
* **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
*
*
* Defines an animation hook that can be later used with
* {@link $animate $animate} service and directives that use this service.
*
* ```js
* module.animation('.animation-name', function($inject1, $inject2) {
* return {
* eventName : function(element, done) {
* //code to run the animation
* //once complete, then run done()
* return function cancellationFunction(element) {
* //code to cancel the animation
* }
* }
* }
* })
* ```
*
* See {@link ng.$animateProvider#register $animateProvider.register()} and
* {@link ngAnimate ngAnimate module} for more information.
*/
animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#filter
* @module ng
* @param {string} name Filter name - this must be a valid angular expression identifier
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*
* <div class="alert alert-warning">
* **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
* Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
* your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
* (`myapp_subsection_filterx`).
* </div>
*/
filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @module ng
* @param {string|Object} name Controller name, or an object map of controllers where the
* keys are the names and the values are the constructors.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @module ng
* @param {string|Object} name Directive name, or an object map of directives where the
* keys are the names and the values are the factories.
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider#directive $compileProvider.directive()}.
*/
directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @module ng
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
* For more about how to configure services, see
* {@link providers#provider-recipe Provider Recipe}.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @module ng
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which should be performed when the injector is done
* loading all modules.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod, queue) {
if (!queue) queue = invokeQueue;
return function() {
queue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
};
}
/**
* @param {string} provider
* @param {string} method
* @returns {angular.Module}
*/
function invokeLaterAndSetModuleName(provider, method) {
return function(recipeName, factoryFunction) {
if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
invokeQueue.push([provider, method, arguments]);
return moduleInstance;
};
}
});
};
});
}
setupModuleLoader(window);
})(window); | @ngdoc method
@name angular.Module#decorator
@module ng
@param {string} The name of the service to decorate.
@param {Function} This function will be invoked when the service needs to be
instantiated and should return the decorated service instance.
@description
See {@link auto.$provide#decorator $provide.decorator()}. | invokeLaterAndSetModuleName ( '$provide' , 'decorator' ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | MIT |
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#decorator
* @module ng
* @param {string} The name of the service to decorate.
* @param {Function} This function will be invoked when the service needs to be
* instantiated and should return the decorated service instance.
* @description
* See {@link auto.$provide#decorator $provide.decorator()}.
*/
decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
/**
* @ngdoc method
* @name angular.Module#animation
* @module ng
* @param {string} name animation name
* @param {Function} animationFactory Factory function for creating new instance of an
* animation.
* @description
*
* **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
*
*
* Defines an animation hook that can be later used with
* {@link $animate $animate} service and directives that use this service.
*
* ```js
* module.animation('.animation-name', function($inject1, $inject2) {
* return {
* eventName : function(element, done) {
* //code to run the animation
* //once complete, then run done()
* return function cancellationFunction(element) {
* //code to cancel the animation
* }
* }
* }
* })
* ```
*
* See {@link ng.$animateProvider#register $animateProvider.register()} and
* {@link ngAnimate ngAnimate module} for more information.
*/
animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#filter
* @module ng
* @param {string} name Filter name - this must be a valid angular expression identifier
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*
* <div class="alert alert-warning">
* **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
* Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
* your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
* (`myapp_subsection_filterx`).
* </div>
*/
filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @module ng
* @param {string|Object} name Controller name, or an object map of controllers where the
* keys are the names and the values are the constructors.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @module ng
* @param {string|Object} name Directive name, or an object map of directives where the
* keys are the names and the values are the factories.
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider#directive $compileProvider.directive()}.
*/
directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @module ng
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
* For more about how to configure services, see
* {@link providers#provider-recipe Provider Recipe}.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @module ng
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which should be performed when the injector is done
* loading all modules.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod, queue) {
if (!queue) queue = invokeQueue;
return function() {
queue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
};
}
/**
* @param {string} provider
* @param {string} method
* @returns {angular.Module}
*/
function invokeLaterAndSetModuleName(provider, method) {
return function(recipeName, factoryFunction) {
if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
invokeQueue.push([provider, method, arguments]);
return moduleInstance;
};
}
});
};
});
}
setupModuleLoader(window);
})(window); | @ngdoc method
@name angular.Module#constant
@module ng
@param {string} name constant name
@param {*} object Constant value.
@description
Because the constants are fixed, they get applied before other provide methods.
See {@link auto.$provide#constant $provide.constant()}. | invokeLater ( '$provide' , 'constant' , 'unshift' ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-loader.js | MIT |
get: function(key) {
return $$cookieReader()[key];
}, | @ngdoc method
@name $cookies#get
@description
Returns the value of given cookie key
@param {string} key Id to use for lookup.
@returns {string} Raw cookie value. | get ( key ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | MIT |
getObject: function(key) {
var value = this.get(key);
return value ? angular.fromJson(value) : value;
}, | @ngdoc method
@name $cookies#getObject
@description
Returns the deserialized value of given cookie key
@param {string} key Id to use for lookup.
@returns {Object} Deserialized cookie value. | getObject ( key ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | MIT |
getAll: function() {
return $$cookieReader();
}, | @ngdoc method
@name $cookies#getAll
@description
Returns a key value object with all the cookies
@returns {Object} All cookies | getAll ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | MIT |
put: function(key, value, options) {
$$cookieWriter(key, value, calcOptions(options));
}, | @ngdoc method
@name $cookies#put
@description
Sets a value for given cookie key
@param {string} key Id for the `value`.
@param {string} value Raw value to be stored.
@param {Object=} options Options object.
See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults} | put ( key , value , options ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | MIT |
putObject: function(key, value, options) {
this.put(key, angular.toJson(value), options);
}, | @ngdoc method
@name $cookies#putObject
@description
Serializes and sets a value for given cookie key
@param {string} key Id for the `value`.
@param {Object} value Value to be stored.
@param {Object=} options Options object.
See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults} | putObject ( key , value , options ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | MIT |
remove: function(key, options) {
$$cookieWriter(key, undefined, calcOptions(options));
} | @ngdoc method
@name $cookies#remove
@description
Remove given cookie
@param {string} key Id of the key-value pair to delete.
@param {Object=} options Options object.
See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults} | remove ( key , options ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | MIT |
this.$get = ['$$cookieReader', '$$cookieWriter', function($$cookieReader, $$cookieWriter) {
return {
/**
* @ngdoc method
* @name $cookies#get
*
* @description
* Returns the value of given cookie key
*
* @param {string} key Id to use for lookup.
* @returns {string} Raw cookie value.
*/
get: function(key) {
return $$cookieReader()[key];
},
/**
* @ngdoc method
* @name $cookies#getObject
*
* @description
* Returns the deserialized value of given cookie key
*
* @param {string} key Id to use for lookup.
* @returns {Object} Deserialized cookie value.
*/
getObject: function(key) {
var value = this.get(key);
return value ? angular.fromJson(value) : value;
},
/**
* @ngdoc method
* @name $cookies#getAll
*
* @description
* Returns a key value object with all the cookies
*
* @returns {Object} All cookies
*/
getAll: function() {
return $$cookieReader();
},
/**
* @ngdoc method
* @name $cookies#put
*
* @description
* Sets a value for given cookie key
*
* @param {string} key Id for the `value`.
* @param {string} value Raw value to be stored.
* @param {Object=} options Options object.
* See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults}
*/
put: function(key, value, options) {
$$cookieWriter(key, value, calcOptions(options));
},
/**
* @ngdoc method
* @name $cookies#putObject
*
* @description
* Serializes and sets a value for given cookie key
*
* @param {string} key Id for the `value`.
* @param {Object} value Value to be stored.
* @param {Object=} options Options object.
* See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults}
*/
putObject: function(key, value, options) {
this.put(key, angular.toJson(value), options);
},
/**
* @ngdoc method
* @name $cookies#remove
*
* @description
* Remove given cookie
*
* @param {string} key Id of the key-value pair to delete.
* @param {Object=} options Options object.
* See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults}
*/
remove: function(key, options) {
$$cookieWriter(key, undefined, calcOptions(options));
}
};
}]; | @ngdoc service
@name $cookies
@description
Provides read/write access to browser's cookies.
<div class="alert alert-info">
Up until Angular 1.3, `$cookies` exposed properties that represented the
current browser cookie values. In version 1.4, this behavior has changed, and
`$cookies` now provides a standard api of getters, setters etc.
</div>
Requires the {@link ngCookies `ngCookies`} module to be installed.
@example
```js
angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
// Retrieving a cookie
var favoriteCookie = $cookies.get('myFavorite');
// Setting a cookie
$cookies.put('myFavorite', 'oatmeal');
}]);
``` | this.$get ( $ $cookieReader , $ $cookieWriter ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | MIT |
provider('$cookies', [function $CookiesProvider() {
/**
* @ngdoc property
* @name $cookiesProvider#defaults
* @description
*
* Object containing default options to pass when setting cookies.
*
* The object may have following properties:
*
* - **path** - `{string}` - The cookie will be available only for this path and its
* sub-paths. By default, this would be the URL that appears in your base tag.
* - **domain** - `{string}` - The cookie will be available only for this domain and
* its sub-domains. For obvious security reasons the user agent will not accept the
* cookie if the current domain is not a sub domain or equals to the requested domain.
* - **expires** - `{string|Date}` - String of the form "Wdy, DD Mon YYYY HH:MM:SS GMT"
* or a Date object indicating the exact date/time this cookie will expire.
* - **secure** - `{boolean}` - The cookie will be available only in secured connection.
*
* Note: by default the address that appears in your `<base>` tag will be used as path.
* This is important so that cookies will be visible for all routes in case html5mode is enabled
*
**/
var defaults = this.defaults = {};
function calcOptions(options) {
return options ? angular.extend({}, defaults, options) : defaults;
}
/**
* @ngdoc service
* @name $cookies
*
* @description
* Provides read/write access to browser's cookies.
*
* <div class="alert alert-info">
* Up until Angular 1.3, `$cookies` exposed properties that represented the
* current browser cookie values. In version 1.4, this behavior has changed, and
* `$cookies` now provides a standard api of getters, setters etc.
* </div>
*
* Requires the {@link ngCookies `ngCookies`} module to be installed.
*
* @example
*
* ```js
* angular.module('cookiesExample', ['ngCookies'])
* .controller('ExampleController', ['$cookies', function($cookies) {
* // Retrieving a cookie
* var favoriteCookie = $cookies.get('myFavorite');
* // Setting a cookie
* $cookies.put('myFavorite', 'oatmeal');
* }]);
* ```
*/
this.$get = ['$$cookieReader', '$$cookieWriter', function($$cookieReader, $$cookieWriter) {
return {
/**
* @ngdoc method
* @name $cookies#get
*
* @description
* Returns the value of given cookie key
*
* @param {string} key Id to use for lookup.
* @returns {string} Raw cookie value.
*/
get: function(key) {
return $$cookieReader()[key];
},
/**
* @ngdoc method
* @name $cookies#getObject
*
* @description
* Returns the deserialized value of given cookie key
*
* @param {string} key Id to use for lookup.
* @returns {Object} Deserialized cookie value.
*/
getObject: function(key) {
var value = this.get(key);
return value ? angular.fromJson(value) : value;
},
/**
* @ngdoc method
* @name $cookies#getAll
*
* @description
* Returns a key value object with all the cookies
*
* @returns {Object} All cookies
*/
getAll: function() {
return $$cookieReader();
},
/**
* @ngdoc method
* @name $cookies#put
*
* @description
* Sets a value for given cookie key
*
* @param {string} key Id for the `value`.
* @param {string} value Raw value to be stored.
* @param {Object=} options Options object.
* See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults}
*/
put: function(key, value, options) {
$$cookieWriter(key, value, calcOptions(options));
},
/**
* @ngdoc method
* @name $cookies#putObject
*
* @description
* Serializes and sets a value for given cookie key
*
* @param {string} key Id for the `value`.
* @param {Object} value Value to be stored.
* @param {Object=} options Options object.
* See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults}
*/
putObject: function(key, value, options) {
this.put(key, angular.toJson(value), options);
},
/**
* @ngdoc method
* @name $cookies#remove
*
* @description
* Remove given cookie
*
* @param {string} key Id of the key-value pair to delete.
* @param {Object=} options Options object.
* See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults}
*/
remove: function(key, options) {
$$cookieWriter(key, undefined, calcOptions(options));
}
};
}];
}]); | @ngdoc provider
@name $cookiesProvider
@description
Use `$cookiesProvider` to change the default behavior of the {@link ngCookies.$cookies $cookies} service.
* | $CookiesProvider ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | MIT |
get: function(key) {
return $cookies.getObject(key);
}, | @ngdoc method
@name $cookieStore#get
@description
Returns the value of given cookie key
@param {string} key Id to use for lookup.
@returns {Object} Deserialized cookie value, undefined if the cookie does not exist. | get ( key ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | MIT |
put: function(key, value) {
$cookies.putObject(key, value);
}, | @ngdoc method
@name $cookieStore#put
@description
Sets a value for given cookie key
@param {string} key Id for the `value`.
@param {Object} value Value to be stored. | put ( key , value ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | MIT |
remove: function(key) {
$cookies.remove(key);
} | @ngdoc method
@name $cookieStore#remove
@description
Remove given cookie
@param {string} key Id of the key-value pair to delete. | remove ( key ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | MIT |
factory('$cookieStore', ['$cookies', function($cookies) {
return {
/**
* @ngdoc method
* @name $cookieStore#get
*
* @description
* Returns the value of given cookie key
*
* @param {string} key Id to use for lookup.
* @returns {Object} Deserialized cookie value, undefined if the cookie does not exist.
*/
get: function(key) {
return $cookies.getObject(key);
},
/**
* @ngdoc method
* @name $cookieStore#put
*
* @description
* Sets a value for given cookie key
*
* @param {string} key Id for the `value`.
* @param {Object} value Value to be stored.
*/
put: function(key, value) {
$cookies.putObject(key, value);
},
/**
* @ngdoc method
* @name $cookieStore#remove
*
* @description
* Remove given cookie
*
* @param {string} key Id of the key-value pair to delete.
*/
remove: function(key) {
$cookies.remove(key);
}
};
}]); | @ngdoc service
@name $cookieStore
@deprecated
@requires $cookies
@description
Provides a key-value (string-object) storage, that is backed by session cookies.
Objects put or retrieved from this storage are automatically serialized or
deserialized by angular's toJson/fromJson.
Requires the {@link ngCookies `ngCookies`} module to be installed.
<div class="alert alert-danger">
**Note:** The $cookieStore service is **deprecated**.
Please use the {@link ngCookies.$cookies `$cookies`} service instead.
</div>
@example
```js
angular.module('cookieStoreExample', ['ngCookies'])
.controller('ExampleController', ['$cookieStore', function($cookieStore) {
// Put cookie
$cookieStore.put('myFavorite','oatmeal');
// Get cookie
var favoriteCookie = $cookieStore.get('myFavorite');
// Removing a cookie
$cookieStore.remove('myFavorite');
}]);
``` | (anonymous) ( $cookies ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | MIT |
function $$CookieWriter($document, $log, $browser) {
var cookiePath = $browser.baseHref();
var rawDocument = $document[0];
function buildCookieString(name, value, options) {
var path, expires;
options = options || {};
expires = options.expires;
path = angular.isDefined(options.path) ? options.path : cookiePath;
if (angular.isUndefined(value)) {
expires = 'Thu, 01 Jan 1970 00:00:00 GMT';
value = '';
}
if (angular.isString(expires)) {
expires = new Date(expires);
}
var str = encodeURIComponent(name) + '=' + encodeURIComponent(value);
str += path ? ';path=' + path : '';
str += options.domain ? ';domain=' + options.domain : '';
str += expires ? ';expires=' + expires.toUTCString() : '';
str += options.secure ? ';secure' : '';
// per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
// - 300 cookies
// - 20 cookies per unique domain
// - 4096 bytes per cookie
var cookieLength = str.length + 1;
if (cookieLength > 4096) {
$log.warn("Cookie '" + name +
"' possibly not set or overflowed because it was too large (" +
cookieLength + " > 4096 bytes)!");
}
return str;
}
return function(name, value, options) {
rawDocument.cookie = buildCookieString(name, value, options);
};
} | @name $$cookieWriter
@requires $document
@description
This is a private service for writing cookies
@param {string} name Cookie name
@param {string=} value Cookie value (if undefined, cookie will be deleted)
@param {Object=} options Object with options that need to be stored for the cookie. | $CookieWriter ( $document , $log , $browser ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-cookies.js | MIT |
function snake_case(name) {
var regexp = /[A-Z]/g;
var separator = '-';
return name.replace(regexp, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
/**
* Returns the actual instance of the $tooltip service.
* TODO support multiple triggers
*/
this.$get = ['$window', '$compile', '$timeout', '$document', '$uibPosition', '$interpolate', '$rootScope', '$parse', '$$stackedMap', function($window, $compile, $timeout, $document, $position, $interpolate, $rootScope, $parse, $$stackedMap) {
var openedTooltips = $$stackedMap.createNew();
$document.on('keypress', function(e) {
if (e.which === 27) {
var last = openedTooltips.top();
if (last) {
last.value.close();
openedTooltips.removeTop();
last = null;
}
}
});
return function $tooltip(ttType, prefix, defaultTriggerShow, options) {
options = angular.extend({}, defaultOptions, globalOptions, options);
/**
* Returns an object of show and hide triggers.
*
* If a trigger is supplied,
* it is used to show the tooltip; otherwise, it will use the `trigger`
* option passed to the `$tooltipProvider.options` method; else it will
* default to the trigger supplied to this directive factory.
*
* The hide trigger is based on the show trigger. If the `trigger` option
* was passed to the `$tooltipProvider.options` method, it will use the
* mapped trigger from `triggerMap` or the passed trigger if the map is
* undefined; otherwise, it uses the `triggerMap` value of the show
* trigger; else it will just use the show trigger.
*/
function getTriggers(trigger) {
var show = (trigger || options.trigger || defaultTriggerShow).split(' ');
var hide = show.map(function(trigger) {
return triggerMap[trigger] || trigger;
});
return {
show: show,
hide: hide
};
}
var directiveName = snake_case(ttType);
var startSym = $interpolate.startSymbol();
var endSym = $interpolate.endSymbol();
var template =
'<div '+ directiveName + '-popup '+
'title="' + startSym + 'title' + endSym + '" '+
(options.useContentExp ?
'content-exp="contentExp()" ' :
'content="' + startSym + 'content' + endSym + '" ') +
'placement="' + startSym + 'placement' + endSym + '" '+
'popup-class="' + startSym + 'popupClass' + endSym + '" '+
'animation="animation" ' +
'is-open="isOpen"' +
'origin-scope="origScope" ' +
'style="visibility: hidden; display: block; top: -9999px; left: -9999px;"' +
'>' +
'</div>';
return {
compile: function(tElem, tAttrs) {
var tooltipLinker = $compile(template);
return function link(scope, element, attrs, tooltipCtrl) {
var tooltip;
var tooltipLinkedScope;
var transitionTimeout;
var showTimeout;
var hideTimeout;
var positionTimeout;
var appendToBody = angular.isDefined(options.appendToBody) ? options.appendToBody : false;
var triggers = getTriggers(undefined);
var hasEnableExp = angular.isDefined(attrs[prefix + 'Enable']);
var ttScope = scope.$new(true);
var repositionScheduled = false;
var isOpenParse = angular.isDefined(attrs[prefix + 'IsOpen']) ? $parse(attrs[prefix + 'IsOpen']) : false;
var contentParse = options.useContentExp ? $parse(attrs[ttType]) : false;
var observers = [];
var positionTooltip = function() {
// check if tooltip exists and is not empty
if (!tooltip || !tooltip.html()) { return; }
if (!positionTimeout) {
positionTimeout = $timeout(function() {
// Reset the positioning.
tooltip.css({ top: 0, left: 0 });
// Now set the calculated positioning.
var ttCss = $position.positionElements(element, tooltip, ttScope.placement, appendToBody);
ttCss.top += 'px';
ttCss.left += 'px';
ttCss.visibility = 'visible';
tooltip.css(ttCss);
positionTimeout = null;
}, 0, false);
}
};
// Set up the correct scope to allow transclusion later
ttScope.origScope = scope;
// By default, the tooltip is not open.
// TODO add ability to start tooltip opened
ttScope.isOpen = false;
openedTooltips.add(ttScope, {
close: hide
});
function toggleTooltipBind() {
if (!ttScope.isOpen) {
showTooltipBind();
} else {
hideTooltipBind();
}
}
// Show the tooltip with delay if specified, otherwise show it immediately
function showTooltipBind() {
if (hasEnableExp && !scope.$eval(attrs[prefix + 'Enable'])) {
return;
}
cancelHide();
prepareTooltip();
if (ttScope.popupDelay) {
// Do nothing if the tooltip was already scheduled to pop-up.
// This happens if show is triggered multiple times before any hide is triggered.
if (!showTimeout) {
showTimeout = $timeout(show, ttScope.popupDelay, false);
}
} else {
show();
}
}
function hideTooltipBind() {
cancelShow();
if (ttScope.popupCloseDelay) {
if (!hideTimeout) {
hideTimeout = $timeout(hide, ttScope.popupCloseDelay, false);
}
} else {
hide();
}
}
// Show the tooltip popup element.
function show() {
cancelShow();
cancelHide();
// Don't show empty tooltips.
if (!ttScope.content) {
return angular.noop;
}
createTooltip();
// And show the tooltip.
ttScope.$evalAsync(function() {
ttScope.isOpen = true;
assignIsOpen(true);
positionTooltip();
});
}
function cancelShow() {
if (showTimeout) {
$timeout.cancel(showTimeout);
showTimeout = null;
}
if (positionTimeout) {
$timeout.cancel(positionTimeout);
positionTimeout = null;
}
}
// Hide the tooltip popup element.
function hide() {
cancelShow();
cancelHide();
if (!ttScope) {
return;
}
// First things first: we don't show it anymore.
ttScope.$evalAsync(function() {
ttScope.isOpen = false;
assignIsOpen(false);
// And now we remove it from the DOM. However, if we have animation, we
// need to wait for it to expire beforehand.
// FIXME: this is a placeholder for a port of the transitions library.
// The fade transition in TWBS is 150ms.
if (ttScope.animation) {
if (!transitionTimeout) {
transitionTimeout = $timeout(removeTooltip, 150, false);
}
} else {
removeTooltip();
}
});
}
function cancelHide() {
if (hideTimeout) {
$timeout.cancel(hideTimeout);
hideTimeout = null;
}
if (transitionTimeout) {
$timeout.cancel(transitionTimeout);
transitionTimeout = null;
}
}
function createTooltip() {
// There can only be one tooltip element per directive shown at once.
if (tooltip) {
return;
}
tooltipLinkedScope = ttScope.$new();
tooltip = tooltipLinker(tooltipLinkedScope, function(tooltip) {
if (appendToBody) {
$document.find('body').append(tooltip);
} else {
element.after(tooltip);
}
});
prepObservers();
}
function removeTooltip() {
unregisterObservers();
transitionTimeout = null;
if (tooltip) {
tooltip.remove();
tooltip = null;
}
if (tooltipLinkedScope) {
tooltipLinkedScope.$destroy();
tooltipLinkedScope = null;
}
}
/**
* Set the inital scope values. Once
* the tooltip is created, the observers
* will be added to keep things in synch.
*/
function prepareTooltip() {
ttScope.title = attrs[prefix + 'Title'];
if (contentParse) {
ttScope.content = contentParse(scope);
} else {
ttScope.content = attrs[ttType];
}
ttScope.popupClass = attrs[prefix + 'Class'];
ttScope.placement = angular.isDefined(attrs[prefix + 'Placement']) ? attrs[prefix + 'Placement'] : options.placement;
var delay = parseInt(attrs[prefix + 'PopupDelay'], 10);
var closeDelay = parseInt(attrs[prefix + 'PopupCloseDelay'], 10);
ttScope.popupDelay = !isNaN(delay) ? delay : options.popupDelay;
ttScope.popupCloseDelay = !isNaN(closeDelay) ? closeDelay : options.popupCloseDelay;
}
function assignIsOpen(isOpen) {
if (isOpenParse && angular.isFunction(isOpenParse.assign)) {
isOpenParse.assign(scope, isOpen);
}
}
ttScope.contentExp = function() {
return ttScope.content;
};
/**
* Observe the relevant attributes.
*/
attrs.$observe('disabled', function(val) {
if (val) {
cancelShow();
}
if (val && ttScope.isOpen) {
hide();
}
});
if (isOpenParse) {
scope.$watch(isOpenParse, function(val) {
/*jshint -W018 */
if (ttScope && !val === ttScope.isOpen) {
toggleTooltipBind();
}
/*jshint +W018 */
});
}
function prepObservers() {
observers.length = 0;
if (contentParse) {
observers.push(
scope.$watch(contentParse, function(val) {
ttScope.content = val;
if (!val && ttScope.isOpen) {
hide();
}
})
);
observers.push(
tooltipLinkedScope.$watch(function() {
if (!repositionScheduled) {
repositionScheduled = true;
tooltipLinkedScope.$$postDigest(function() {
repositionScheduled = false;
if (ttScope && ttScope.isOpen) {
positionTooltip();
}
});
}
})
);
} else {
observers.push(
attrs.$observe(ttType, function(val) {
ttScope.content = val;
if (!val && ttScope.isOpen) {
hide();
} else {
positionTooltip();
}
})
);
}
observers.push(
attrs.$observe(prefix + 'Title', function(val) {
ttScope.title = val;
if (ttScope.isOpen) {
positionTooltip();
}
})
);
observers.push(
attrs.$observe(prefix + 'Placement', function(val) {
ttScope.placement = val ? val : options.placement;
if (ttScope.isOpen) {
positionTooltip();
}
})
);
}
function unregisterObservers() {
if (observers.length) {
angular.forEach(observers, function(observer) {
observer();
});
observers.length = 0;
}
}
var unregisterTriggers = function() {
triggers.show.forEach(function(trigger) {
element.unbind(trigger, showTooltipBind);
});
triggers.hide.forEach(function(trigger) {
trigger.split(' ').forEach(function(hideTrigger) {
element[0].removeEventListener(hideTrigger, hideTooltipBind);
});
});
};
function prepTriggers() {
var val = attrs[prefix + 'Trigger'];
unregisterTriggers();
triggers = getTriggers(val);
if (triggers.show !== 'none') {
triggers.show.forEach(function(trigger, idx) {
// Using raw addEventListener due to jqLite/jQuery bug - #4060
if (trigger === triggers.hide[idx]) {
element[0].addEventListener(trigger, toggleTooltipBind);
} else if (trigger) {
element[0].addEventListener(trigger, showTooltipBind);
triggers.hide[idx].split(' ').forEach(function(trigger) {
element[0].addEventListener(trigger, hideTooltipBind);
});
}
element.on('keypress', function(e) {
if (e.which === 27) {
hideTooltipBind();
}
});
});
}
}
prepTriggers();
var animation = scope.$eval(attrs[prefix + 'Animation']);
ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation;
var appendToBodyVal = scope.$eval(attrs[prefix + 'AppendToBody']);
appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody;
// if a tooltip is attached to <body> we need to remove it on
// location change as its parent scope will probably not be destroyed
// by the change.
if (appendToBody) {
scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess() {
if (ttScope.isOpen) {
hide();
}
});
}
// Make sure tooltip is destroyed and removed.
scope.$on('$destroy', function onDestroyTooltip() {
cancelShow();
cancelHide();
unregisterTriggers();
removeTooltip();
openedTooltips.remove(ttScope);
ttScope = null;
});
};
}
};
};
}];
}) | This is a helper function for translating camel-case to snake-case. | snake_case ( name ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-bootstrap-tpls.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-bootstrap-tpls.js | MIT |
angular.module('ui.alias', []).config(['$compileProvider', 'uiAliasConfig', function($compileProvider, uiAliasConfig){
'use strict';
uiAliasConfig = uiAliasConfig || {};
angular.forEach(uiAliasConfig, function(config, alias){
if (angular.isString(config)) {
config = {
replace: true,
template: config
};
}
$compileProvider.directive(alias, function(){
return config;
});
});
}]); | angular-ui-utils - Swiss-Army-Knife of AngularJS tools (with no external dependencies!)
@version v0.2.3 - 2015-03-30
@link http://angular-ui.github.com
@license MIT License, http://www.opensource.org/licenses/MIT | (anonymous) ( $compileProvider , uiAliasConfig ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | MIT |
angular.module('ui.format',[]).filter('format', function(){
'use strict';
return function(value, replace) {
var target = value;
if (angular.isString(target) && replace !== undefined) {
if (!angular.isArray(replace) && !angular.isObject(replace)) {
replace = [replace];
}
if (angular.isArray(replace)) {
var rlen = replace.length;
var rfx = function (str, i) {
i = parseInt(i, 10);
return (i >= 0 && i < rlen) ? replace[i] : str;
};
target = target.replace(/\$([0-9]+)/g, rfx);
}
else {
angular.forEach(replace, function(value, key){
target = target.split(':' + key).join(value);
});
}
}
return target;
};
}); | A replacement utility for internationalization very similar to sprintf.
@param replace {mixed} The tokens to replace depends on type
string: all instances of $0 will be replaced
array: each instance of $0, $1, $2 etc. will be placed with each array item in corresponding order
object: all attributes will be iterated through, with :key being replaced with its corresponding value
@return string
@example: 'Hello :name, how are you :day'.format({ name:'John', day:'Today' })
@example: 'Records $0 to $1 out of $2 total'.format(['10', '20', '3000'])
@example: '$0 agrees to all mentions $0 makes in the event that $0 hits a tree while $0 is driving drunk'.format('Bob') | (anonymous) ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | MIT |
angular.module('ui.highlight',[]).filter('highlight', function () {
'use strict';
return function (text, search, caseSensitive) {
if (text && (search || angular.isNumber(search))) {
text = text.toString();
search = search.toString();
if (caseSensitive) {
return text.split(search).join('<span class="ui-match">' + search + '</span>');
} else {
return text.replace(new RegExp(search, 'gi'), '<span class="ui-match">$&</span>');
}
} else {
return text;
}
};
}); | Wraps the
@param text {string} haystack to search through
@param search {string} needle to search for
@param [caseSensitive] {boolean} optional boolean to use case-sensitive searching | (anonymous) ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | MIT |
angular.module('ui.inflector',[]).filter('inflector', function () {
'use strict';
function tokenize(text) {
text = text.replace(/([A-Z])|([\-|\_])/g, function(_, $1) { return ' ' + ($1 || ''); });
return text.replace(/\s\s+/g, ' ').trim().toLowerCase().split(' ');
}
function capitalizeTokens(tokens) {
var result = [];
angular.forEach(tokens, function(token) {
result.push(token.charAt(0).toUpperCase() + token.substr(1));
});
return result;
}
var inflectors = {
humanize: function (value) {
return capitalizeTokens(tokenize(value)).join(' ');
},
underscore: function (value) {
return tokenize(value).join('_');
},
variable: function (value) {
value = tokenize(value);
value = value[0] + capitalizeTokens(value.slice(1)).join('');
return value;
}
};
return function (text, inflector) {
if (inflector !== false && angular.isString(text)) {
inflector = inflector || 'humanize';
return inflectors[inflector](text);
} else {
return text;
}
};
}); | Converts variable-esque naming conventions to something presentational, capitalized words separated by space.
@param {String} value The value to be parsed and prettified.
@param {String} [inflector] The inflector to use. Default: humanize.
@return {String}
@example {{ 'Here Is my_phoneNumber' | inflector:'humanize' }} => Here Is My Phone Number
{{ 'Here Is my_phoneNumber' | inflector:'underscore' }} => here_is_my_phone_number
{{ 'Here Is my_phoneNumber' | inflector:'variable' }} => hereIsMyPhoneNumber | (anonymous) ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | MIT |
angular.module('ui.keypress').directive('uiKeydown', ['keypressHelper', function(keypressHelper){
'use strict';
return {
link: function (scope, elm, attrs) {
keypressHelper('keydown', scope, elm, attrs);
}
};
}]); | Bind one or more handlers to particular keys or their combination
@param hash {mixed} keyBindings Can be an object or string where keybinding expression of keys or keys combinations and AngularJS Exspressions are set. Object syntax: "{ keys1: expression1 [, keys2: expression2 [ , ... ]]}". String syntax: ""expression1 on keys1 [ and expression2 on keys2 [ and ... ]]"". Expression is an AngularJS Expression, and key(s) are dash-separated combinations of keys and modifiers (one or many, if any. Order does not matter). Supported modifiers are 'ctrl', 'shift', 'alt' and key can be used either via its keyCode (13 for Return) or name. Named keys are 'backspace', 'tab', 'enter', 'esc', 'space', 'pageup', 'pagedown', 'end', 'home', 'left', 'up', 'right', 'down', 'insert', 'delete'.
@example <input ui-keypress="{enter:'x = 1', 'ctrl-shift-space':'foo()', 'shift-13':'bar()'}" /> <input ui-keypress="foo = 2 on ctrl-13 and bar('hello') on shift-esc" />
* | (anonymous) ( keypressHelper ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | MIT |
angular.module('ui.reset',[]).value('uiResetConfig',null).directive('uiReset', ['uiResetConfig', function (uiResetConfig) {
'use strict';
var resetValue = null;
if (uiResetConfig !== undefined){
resetValue = uiResetConfig;
}
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
var aElement;
aElement = angular.element('<a class="ui-reset" />');
elm.wrap('<span class="ui-resetwrap" />').after(aElement);
aElement.bind('click', function (e) {
e.preventDefault();
scope.$apply(function () {
if (attrs.uiReset){
ctrl.$setViewValue(scope.$eval(attrs.uiReset));
}else{
ctrl.$setViewValue(resetValue);
}
ctrl.$render();
});
});
}
};
}]); | Add a clear button to form inputs to reset their value | (anonymous) ( uiResetConfig ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | MIT |
angular.module('ui.scrollfix',[]).directive('uiScrollfix', ['$window', function ($window) {
'use strict';
function getWindowScrollTop() {
if (angular.isDefined($window.pageYOffset)) {
return $window.pageYOffset;
} else {
var iebody = (document.compatMode && document.compatMode !== 'BackCompat') ? document.documentElement : document.body;
return iebody.scrollTop;
}
}
return {
require: '^?uiScrollfixTarget',
link: function (scope, elm, attrs, uiScrollfixTarget) {
var absolute = true,
shift = 0,
fixLimit,
$target = uiScrollfixTarget && uiScrollfixTarget.$element || angular.element($window);
if (!attrs.uiScrollfix) {
absolute = false;
} else if (typeof(attrs.uiScrollfix) === 'string') {
// charAt is generally faster than indexOf: http://jsperf.com/indexof-vs-charat
if (attrs.uiScrollfix.charAt(0) === '-') {
absolute = false;
shift = - parseFloat(attrs.uiScrollfix.substr(1));
} else if (attrs.uiScrollfix.charAt(0) === '+') {
absolute = false;
shift = parseFloat(attrs.uiScrollfix.substr(1));
}
}
fixLimit = absolute ? attrs.uiScrollfix : elm[0].offsetTop + shift;
function onScroll() {
var limit = absolute ? attrs.uiScrollfix : elm[0].offsetTop + shift;
// if pageYOffset is defined use it, otherwise use other crap for IE
var offset = uiScrollfixTarget ? $target[0].scrollTop : getWindowScrollTop();
if (!elm.hasClass('ui-scrollfix') && offset > limit) {
elm.addClass('ui-scrollfix');
fixLimit = limit;
} else if (elm.hasClass('ui-scrollfix') && offset < fixLimit) {
elm.removeClass('ui-scrollfix');
}
}
$target.on('scroll', onScroll);
// Unbind scroll event handler when directive is removed
scope.$on('$destroy', function() {
$target.off('scroll', onScroll);
});
}
};
}]).directive('uiScrollfixTarget', [function () { | Adds a 'ui-scrollfix' class to the element when the page scrolls past it's position.
@param [offset] {int} optional Y-offset to override the detected offset.
Takes 300 (absolute) or -300 or +300 (relative to detected) | (anonymous) ( $window ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | MIT |
.directive('uiHide', [function () {
'use strict';
return function (scope, elm, attrs) {
scope.$watch(attrs.uiHide, function (newVal) {
if (newVal) {
elm.addClass('ui-hide');
} else {
elm.removeClass('ui-hide');
}
});
};
}]) | uiHide Directive
Adds a 'ui-hide' class to the element instead of display:block
Created to allow tighter control of CSS without bulkier directives
@param expression {boolean} evaluated expression to determine if the class should be added | (anonymous) ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | MIT |
.directive('uiToggle', [function () {
'use strict';
return function (scope, elm, attrs) {
scope.$watch(attrs.uiToggle, function (newVal) {
if (newVal) {
elm.removeClass('ui-hide').addClass('ui-show');
} else {
elm.removeClass('ui-show').addClass('ui-hide');
}
});
};
}]); | uiToggle Directive
Adds a class 'ui-show' if true, and a 'ui-hide' if false to the element instead of display:block/display:none
Created to allow tighter control of CSS without bulkier directives. This also allows you to override the
default visibility of the element using either class.
@param expression {boolean} evaluated expression to determine if the class should be added | (anonymous) ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | MIT |
angular.module('ui.validate',[]).directive('uiValidate', function () {
'use strict';
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
var validateFn, validators = {},
validateExpr = scope.$eval(attrs.uiValidate);
if (!validateExpr){ return;}
if (angular.isString(validateExpr)) {
validateExpr = { validator: validateExpr };
}
angular.forEach(validateExpr, function (exprssn, key) {
validateFn = function (valueToValidate) {
var expression = scope.$eval(exprssn, { '$value' : valueToValidate });
if (angular.isObject(expression) && angular.isFunction(expression.then)) {
// expression is a promise
expression.then(function(){
ctrl.$setValidity(key, true);
}, function(){
ctrl.$setValidity(key, false);
});
return valueToValidate;
} else if (expression) {
// expression is true
ctrl.$setValidity(key, true);
return valueToValidate;
} else {
// expression is false
ctrl.$setValidity(key, false);
return valueToValidate;
}
};
validators[key] = validateFn;
ctrl.$formatters.push(validateFn);
ctrl.$parsers.push(validateFn);
});
function apply_watch(watch)
{
//string - update all validators on expression change
if (angular.isString(watch))
{
scope.$watch(watch, function(){
angular.forEach(validators, function(validatorFn){
validatorFn(ctrl.$modelValue);
});
});
return;
}
//array - update all validators on change of any expression
if (angular.isArray(watch))
{
angular.forEach(watch, function(expression){
scope.$watch(expression, function()
{
angular.forEach(validators, function(validatorFn){
validatorFn(ctrl.$modelValue);
});
});
});
return;
}
//object - update appropriate validator
if (angular.isObject(watch))
{
angular.forEach(watch, function(expression, validatorKey)
{
//value is string - look after one expression
if (angular.isString(expression))
{
scope.$watch(expression, function(){
validators[validatorKey](ctrl.$modelValue);
});
}
//value is array - look after all expressions in array
if (angular.isArray(expression))
{
angular.forEach(expression, function(intExpression)
{
scope.$watch(intExpression, function(){
validators[validatorKey](ctrl.$modelValue);
});
});
}
});
}
}
// Support for ui-validate-watch
if (attrs.uiValidateWatch){
apply_watch( scope.$eval(attrs.uiValidateWatch) );
}
}
};
}); | General-purpose validator for ngModel.
angular.js comes with several built-in validation mechanism for input fields (ngRequired, ngPattern etc.) but using
an arbitrary validation function requires creation of a custom formatters and / or parsers.
The ui-validate directive makes it easy to use any function(s) defined in scope as a validator function(s).
A validator function will trigger validation on both model and input changes.
@example <input ui-validate=" 'myValidatorFunction($value)' ">
@example <input ui-validate="{ foo : '$value > anotherModel', bar : 'validateFoo($value)' }">
@example <input ui-validate="{ foo : '$value > anotherModel' }" ui-validate-watch=" 'anotherModel' ">
@example <input ui-validate="{ foo : '$value > anotherModel', bar : 'validateFoo($value)' }" ui-validate-watch=" { foo : 'anotherModel' } ">
@param ui-validate {string|object literal} If strings is passed it should be a scope's function to be used as a validator.
If an object literal is passed a key denotes a validation error key while a value should be a validator function.
In both cases validator function should take a value to validate as its argument and should return true/false indicating a validation result. | (anonymous) ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/angular-ui/ui-utils.js | MIT |
(function(root, factory) {
/* CommonJS */
if (typeof exports == 'object') module.exports = factory()
/* AMD module */
else if (typeof define == 'function' && define.amd) define(factory)
/* Browser global */
else root.Spinner = factory()
} | Copyright (c) 2011-2014 Felix Gnass
Licensed under the MIT license | (anonymous) ( root , factory ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | MIT |
function createEl(tag, prop) {
var el = document.createElement(tag || 'div')
, n
for(n in prop) el[n] = prop[n]
return el
} | Utility function to create elements. If no tag name is given,
a DIV is created. Optionally properties can be passed. | createEl ( tag , prop ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | MIT |
function ins(parent /* child1, child2, ...*/) {
for (var i=1, n=arguments.length; i<n; i++)
parent.appendChild(arguments[i])
return parent
} | Appends children and returns the parent. | ins ( parent ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | MIT |
var sheet = (function() {
var el = createEl('style', {type : 'text/css'})
ins(document.getElementsByTagName('head')[0], el)
return el.sheet || el.styleSheet
}()) | Insert a new stylesheet to hold the @keyframe or VML rules. | (anonymous) ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | MIT |
function addAnimation(alpha, trail, i, lines) {
var name = ['opacity', trail, ~~(alpha*100), i, lines].join('-')
, start = 0.01 + i/lines * 100
, z = Math.max(1 - (1-alpha) / trail * (100-start), alpha)
, prefix = useCssAnimations.substring(0, useCssAnimations.indexOf('Animation')).toLowerCase()
, pre = prefix && '-' + prefix + '-' || ''
if (!animations[name]) {
sheet.insertRule(
'@' + pre + 'keyframes ' + name + '{' +
'0%{opacity:' + z + '}' +
start + '%{opacity:' + alpha + '}' +
(start+0.01) + '%{opacity:1}' +
(start+trail) % 100 + '%{opacity:' + alpha + '}' +
'100%{opacity:' + z + '}' +
'}', sheet.cssRules.length)
animations[name] = 1
}
return name
} | Creates an opacity keyframe animation rule and returns its name.
Since most mobile Webkits have timing issues with animation-delay,
we create separate rules for each line/segment. | addAnimation ( alpha , trail , i , lines ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | MIT |
function vendor(el, prop) {
var s = el.style
, pp
, i
prop = prop.charAt(0).toUpperCase() + prop.slice(1)
for(i=0; i<prefixes.length; i++) {
pp = prefixes[i]+prop
if(s[pp] !== undefined) return pp
}
if(s[prop] !== undefined) return prop
} | Tries various vendor prefixes and returns the first supported property. | vendor ( el , prop ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | MIT |
function css(el, prop) {
for (var n in prop)
el.style[vendor(el, n)||n] = prop[n]
return el
} | Sets multiple style properties at once. | css ( el , prop ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | MIT |
function pos(el) {
var o = { x:el.offsetLeft, y:el.offsetTop }
while((el = el.offsetParent))
o.x+=el.offsetLeft, o.y+=el.offsetTop
return o
} | Returns the absolute page-offset of the given element. | pos ( el ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | MIT |
spin: function(target) {
this.stop()
var self = this
, o = self.opts
, el = self.el = css(createEl(0, {className: o.className}), {position: o.position, width: 0, zIndex: o.zIndex})
, mid = o.radius+o.length+o.width
if (target) {
target.insertBefore(el, target.firstChild||null)
css(el, {
left: o.left,
top: o.top
})
}
el.setAttribute('role', 'progressbar')
self.lines(el, self.opts)
if (!useCssAnimations) {
// No CSS animation support, use setTimeout() instead
var i = 0
, start = (o.lines - 1) * (1 - o.direction) / 2
, alpha
, fps = o.fps
, f = fps/o.speed
, ostep = (1-o.opacity) / (f*o.trail / 100)
, astep = f/o.lines
;(function anim() {
i++;
for (var j = 0; j < o.lines; j++) {
alpha = Math.max(1 - (i + (o.lines - j) * astep) % f * ostep, o.opacity)
self.opacity(el, j * o.direction + start, alpha, o)
}
self.timeout = self.el && setTimeout(anim, ~~(1000/fps))
})()
}
return self
}, | Adds the spinner to the given target element. If this instance is already
spinning, it is automatically removed from its previous target b calling
stop() internally. | spin ( target ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | MIT |
opacity: function(el, i, val) {
if (i < el.childNodes.length) el.childNodes[i].style.opacity = val
} | Internal method that adjusts the opacity of a single line.
Will be overwritten in VML fallback mode below. | opacity ( el , i , val ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/BackgroundJobAndNotificationsDemo/BackgroundJobAndNotificationsDemo.Web/Scripts/others/spinjs/spin.js | MIT |
function bowerTask() {
var json = JSON.stringify({
name: package.name,
description: package.description,
homepage: package.homepage,
license: package.license,
version: package.version,
main: outDir + "Chart.js",
ignore: [
'.github',
'.codeclimate.yml',
'.gitignore',
'.npmignore',
'.travis.yml',
'scripts'
]
}, null, 2);
return file('bower.json', json, { src: true })
.pipe(gulp.dest('./'));
} | Generates the bower.json manifest file which will be pushed along release tags.
Specs: https://github.com/bower/spec/blob/master/json.md | bowerTask ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/gulpfile.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/gulpfile.js | MIT |
getStackIndex: function(datasetIndex) {
return this.getStackCount(datasetIndex) - 1;
}, | Returns the stack index for the given dataset based on groups and bar visibility.
@private | getStackIndex ( datasetIndex ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | MIT |
function getNearestItems(chart, position, intersect, distanceMetric) {
var minDistance = Number.POSITIVE_INFINITY;
var nearestItems = [];
if (!distanceMetric) {
distanceMetric = helpers.distanceBetweenPoints;
}
parseVisibleItems(chart, function(element) {
if (intersect && !element.inRange(position.x, position.y)) {
return;
}
var center = element.getCenterPoint();
var distance = distanceMetric(position, center);
if (distance < minDistance) {
nearestItems = [element];
minDistance = distance;
} else if (distance === minDistance) {
// Can have multiple items at the same distance in which case we sort by size
nearestItems.push(element);
}
});
return nearestItems;
} | Helper function to get the items nearest to the event position considering all visible items in teh chart
@param chart {Chart} the chart to look at elements from
@param position {Point} the point to be nearest to
@param intersect {Boolean} if true, only consider items that intersect the position
@param distanceMetric {Function} Optional function to provide the distance between
@return {ChartElement[]} the nearest items | getNearestItems ( chart , position , intersect , distanceMetric ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | MIT |
linear: function(generationOptions, dataRange) {
var ticks = [];
// To get a "nice" value for the tick spacing, we will use the appropriately named
// "nice number" algorithm. See http://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
// for details.
var spacing;
if (generationOptions.stepSize && generationOptions.stepSize > 0) {
spacing = generationOptions.stepSize;
} else {
var niceRange = helpers.niceNum(dataRange.max - dataRange.min, false);
spacing = helpers.niceNum(niceRange / (generationOptions.maxTicks - 1), true);
}
var niceMin = Math.floor(dataRange.min / spacing) * spacing;
var niceMax = Math.ceil(dataRange.max / spacing) * spacing;
// If min, max and stepSize is set and they make an evenly spaced scale use it.
if (generationOptions.min && generationOptions.max && generationOptions.stepSize) {
// If very close to our whole number, use it.
if (helpers.almostWhole((generationOptions.max - generationOptions.min) / generationOptions.stepSize, spacing / 1000)) {
niceMin = generationOptions.min;
niceMax = generationOptions.max;
}
}
var numSpaces = (niceMax - niceMin) / spacing;
// If very close to our rounded value, use it.
if (helpers.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
numSpaces = Math.round(numSpaces);
} else {
numSpaces = Math.ceil(numSpaces);
}
// Put the values into the ticks array
ticks.push(generationOptions.min !== undefined ? generationOptions.min : niceMin);
for (var j = 1; j < numSpaces; ++j) {
ticks.push(niceMin + (j * spacing));
}
ticks.push(generationOptions.max !== undefined ? generationOptions.max : niceMax);
return ticks;
},
/**
* Generate a set of logarithmic ticks
* @method Chart.Ticks.generators.logarithmic
* @param generationOptions {INumericTickGenerationOptions} the options used to generate the ticks
* @param dataRange {IRange} the range of the data
* @returns {Array<Number>} array of tick values
*/
logarithmic: function(generationOptions, dataRange) {
var ticks = [];
var getValueOrDefault = helpers.getValueOrDefault;
// Figure out what the max number of ticks we can support it is based on the size of
// the axis area. For now, we say that the minimum tick spacing in pixels must be 50
// We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
// the graph
var tickVal = getValueOrDefault(generationOptions.min, Math.pow(10, Math.floor(helpers.log10(dataRange.min))));
var endExp = Math.floor(helpers.log10(dataRange.max));
var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
var exp;
var significand;
if (tickVal === 0) {
exp = Math.floor(helpers.log10(dataRange.minNotZero));
significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
ticks.push(tickVal);
tickVal = significand * Math.pow(10, exp);
} else {
exp = Math.floor(helpers.log10(tickVal));
significand = Math.floor(tickVal / Math.pow(10, exp));
}
do {
ticks.push(tickVal);
++significand;
if (significand === 10) {
significand = 1;
++exp;
}
tickVal = significand * Math.pow(10, exp);
} while (exp < endExp || (exp === endExp && significand < endSignificand));
var lastTick = getValueOrDefault(generationOptions.max, tickVal);
ticks.push(lastTick);
return ticks;
}
},
/**
* Namespace to hold formatters for different types of ticks
* @namespace Chart.Ticks.formatters
*/
formatters: {
/**
* Formatter for value labels
* @method Chart.Ticks.formatters.values
* @param value the value to display
* @return {String|Array} the label to display
*/
values: function(value) {
return helpers.isArray(value) ? value : '' + value;
},
/**
* Formatter for linear numeric ticks
* @method Chart.Ticks.formatters.linear
* @param tickValue {Number} the value to be formatted
* @param index {Number} the position of the tickValue parameter in the ticks array
* @param ticks {Array<Number>} the list of ticks being converted
* @return {String} string representation of the tickValue parameter
*/
linear: function(tickValue, index, ticks) {
// If we have lots of ticks, don't use the ones
var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
// If we have a number like 2.5 as the delta, figure out how many decimal places we need
if (Math.abs(delta) > 1) {
if (tickValue !== Math.floor(tickValue)) {
// not an integer
delta = tickValue - Math.floor(tickValue);
}
}
var logDelta = helpers.log10(Math.abs(delta));
var tickString = '';
if (tickValue !== 0) {
var numDecimal = -1 * Math.floor(logDelta);
numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
tickString = tickValue.toFixed(numDecimal);
} else {
tickString = '0'; // never show decimal places for 0
}
return tickString;
},
logarithmic: function(tickValue, index, ticks) {
var remain = tickValue / (Math.pow(10, Math.floor(helpers.log10(tickValue))));
if (tickValue === 0) {
return '0';
} else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
return tickValue.toExponential();
}
return '';
}
}
};
};
},{}],34:[function(require,module,exports){ | Generate a set of linear ticks
@method Chart.Ticks.generators.linear
@param generationOptions {INumericTickGenerationOptions} the options used to generate the ticks
@param dataRange {IRange} the range of the data
@returns {Array<Number>} array of tick values | linear ( generationOptions , dataRange ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | MIT |
function getBackgroundPoint(vm, size, alignment) {
// Background Position
var x = vm.x;
var y = vm.y;
var caretSize = vm.caretSize,
caretPadding = vm.caretPadding,
cornerRadius = vm.cornerRadius,
xAlign = alignment.xAlign,
yAlign = alignment.yAlign,
paddingAndSize = caretSize + caretPadding,
radiusAndPadding = cornerRadius + caretPadding;
if (xAlign === 'right') {
x -= size.width;
} else if (xAlign === 'center') {
x -= (size.width / 2);
}
if (yAlign === 'top') {
y += paddingAndSize;
} else if (yAlign === 'bottom') {
y -= size.height + paddingAndSize;
} else {
y -= (size.height / 2);
}
if (yAlign === 'center') {
if (xAlign === 'left') {
x += paddingAndSize;
} else if (xAlign === 'right') {
x -= paddingAndSize;
}
} else if (xAlign === 'left') {
x -= radiusAndPadding;
} else if (xAlign === 'right') {
x += radiusAndPadding;
}
return {
x: x,
y: y
};
} | @Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment | getBackgroundPoint ( vm , size , alignment ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | MIT |
average: function(elements) {
if (!elements.length) {
return false;
}
var i, len;
var x = 0;
var y = 0;
var count = 0;
for (i = 0, len = elements.length; i < len; ++i) {
var el = elements[i];
if (el && el.hasValue()) {
var pos = el.tooltipPosition();
x += pos.x;
y += pos.y;
++count;
}
}
return {
x: Math.round(x / count),
y: Math.round(y / count)
};
},
/**
* Gets the tooltip position nearest of the item nearest to the event position
* @function Chart.Tooltip.positioners.nearest
* @param elements {Chart.Element[]} the tooltip elements
* @param eventPosition {Point} the position of the event in canvas coordinates
* @returns {Point} the tooltip position
*/
nearest: function(elements, eventPosition) {
var x = eventPosition.x;
var y = eventPosition.y;
var nearestElement;
var minDistance = Number.POSITIVE_INFINITY;
var i, len;
for (i = 0, len = elements.length; i < len; ++i) {
var el = elements[i];
if (el && el.hasValue()) {
var center = el.getCenterPoint();
var d = helpers.distanceBetweenPoints(eventPosition, center);
if (d < minDistance) {
minDistance = d;
nearestElement = el;
}
}
}
if (nearestElement) {
var tp = nearestElement.tooltipPosition();
x = tp.x;
y = tp.y;
}
return {
x: x,
y: y
};
}
};
};
},{}],35:[function(require,module,exports){ | Average mode places the tooltip at the average position of the elements shown
@function Chart.Tooltip.positioners.average
@param elements {ChartElement[]} the elements being displayed in the tooltip
@returns {Point} tooltip position | average ( elements ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | MIT |
function getBarBounds(bar) {
var vm = bar._view;
var x1, x2, y1, y2;
if (isVertical(bar)) {
// vertical
var halfWidth = vm.width / 2;
x1 = vm.x - halfWidth;
x2 = vm.x + halfWidth;
y1 = Math.min(vm.y, vm.base);
y2 = Math.max(vm.y, vm.base);
} else {
// horizontal bar
var halfHeight = vm.height / 2;
x1 = Math.min(vm.x, vm.base);
x2 = Math.max(vm.x, vm.base);
y1 = vm.y - halfHeight;
y2 = vm.y + halfHeight;
}
return {
left: x1,
top: y1,
right: x2,
bottom: y2
};
} | Helper function to get the bounds of the bar regardless of the orientation
@private
@param bar {Chart.Element.Rectangle} the bar
@return {Bounds} bounds of the bar | getBarBounds ( bar ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | MIT |
function parseTime(axis, label) {
var timeOpts = axis.options.time;
if (typeof timeOpts.parser === 'string') {
return moment(label, timeOpts.parser);
}
if (typeof timeOpts.parser === 'function') {
return timeOpts.parser(label);
}
if (typeof label.getMonth === 'function' || typeof label === 'number') {
// Date objects
return moment(label);
}
if (label.isValid && label.isValid()) {
// Moment support
return label;
}
var format = timeOpts.format;
if (typeof format !== 'string' && format.call) {
// Custom parsing (return an instance of moment)
console.warn('options.time.format is deprecated and replaced by options.time.parser.');
return format(label);
}
// Moment format parsing
return moment(label, format);
} | Helper function to parse time to a moment object
@param axis {TimeAxis} the time axis
@param label {Date|string|number|Moment} The thing to parse
@return {Moment} parsed time | parseTime ( axis , label ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | MIT |
function determineUnit(minUnit, min, max, maxTicks) {
var units = Object.keys(interval);
var unit;
var numUnits = units.length;
for (var i = units.indexOf(minUnit); i < numUnits; i++) {
unit = units[i];
var unitDetails = interval[unit];
var steps = (unitDetails.steps && unitDetails.steps[unitDetails.steps.length - 1]) || unitDetails.maxStep;
if (steps === undefined || Math.ceil((max - min) / (steps * unitDetails.size)) <= maxTicks) {
break;
}
}
return unit;
} | Figure out which is the best unit for the scale
@param minUnit {String} minimum unit to use
@param min {Number} scale minimum
@param max {Number} scale maximum
@return {String} the unit to use | determineUnit ( minUnit , min , max , maxTicks ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | MIT |
function determineStepSize(min, max, unit, maxTicks) {
// Using our unit, figoure out what we need to scale as
var unitDefinition = interval[unit];
var unitSizeInMilliSeconds = unitDefinition.size;
var sizeInUnits = Math.ceil((max - min) / unitSizeInMilliSeconds);
var multiplier = 1;
var range = max - min;
if (unitDefinition.steps) {
// Have an array of steps
var numSteps = unitDefinition.steps.length;
for (var i = 0; i < numSteps && sizeInUnits > maxTicks; i++) {
multiplier = unitDefinition.steps[i];
sizeInUnits = Math.ceil(range / (unitSizeInMilliSeconds * multiplier));
}
} else {
while (sizeInUnits > maxTicks && maxTicks > 0) {
++multiplier;
sizeInUnits = Math.ceil(range / (unitSizeInMilliSeconds * multiplier));
}
}
return multiplier;
} | Determines how we scale the unit
@param min {Number} the scale minimum
@param max {Number} the scale maximum
@param unit {String} the unit determined by the {@see determineUnit} method
@return {Number} the axis step size as a multiple of unit | determineStepSize ( min , max , unit , maxTicks ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | MIT |
Chart.Ticks.generators.time = function(options, dataRange) {
var niceMin;
var niceMax;
var isoWeekday = options.isoWeekday;
if (options.unit === 'week' && isoWeekday !== false) {
niceMin = moment(dataRange.min).startOf('isoWeek').isoWeekday(isoWeekday).valueOf();
niceMax = moment(dataRange.max).startOf('isoWeek').isoWeekday(isoWeekday);
if (dataRange.max - niceMax > 0) {
niceMax.add(1, 'week');
}
niceMax = niceMax.valueOf();
} else {
niceMin = moment(dataRange.min).startOf(options.unit).valueOf();
niceMax = moment(dataRange.max).startOf(options.unit);
if (dataRange.max - niceMax > 0) {
niceMax.add(1, options.unit);
}
niceMax = niceMax.valueOf();
}
return generateTicks(options, dataRange, {
min: niceMin,
max: niceMax
});
}; | @function Chart.Ticks.generators.time
@param options {ITimeGeneratorOptions} the options for generation
@param dataRange {IRange} the data range
@return {Number[]} ticks | Chart.Ticks.generators.time ( options , dataRange ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/dist/Chart.js | MIT |
function acquireChart(config, options) {
var wrapper = document.createElement('div');
var canvas = document.createElement('canvas');
var chart, key;
config = config || {};
options = options || {};
options.canvas = options.canvas || {height: 512, width: 512};
options.wrapper = options.wrapper || {class: 'chartjs-wrapper'};
for (key in options.canvas) {
if (options.canvas.hasOwnProperty(key)) {
canvas.setAttribute(key, options.canvas[key]);
}
}
for (key in options.wrapper) {
if (options.wrapper.hasOwnProperty(key)) {
wrapper.setAttribute(key, options.wrapper[key]);
}
}
// by default, remove chart animation and auto resize
config.options = config.options || {};
config.options.animation = config.options.animation === undefined? false : config.options.animation;
config.options.responsive = config.options.responsive === undefined? false : config.options.responsive;
config.options.defaultFontFamily = config.options.defaultFontFamily || 'Arial';
wrapper.appendChild(canvas);
window.document.body.appendChild(wrapper);
chart = new Chart(canvas.getContext('2d'), config);
chart.$test = {
persistent: options.persistent,
wrapper: wrapper
};
return chart;
} | Injects a new canvas (and div wrapper) and creates teh associated Chart instance
using the given config. Additional options allow tweaking elements generation.
@param {object} config - Chart config.
@param {object} options - Chart acquisition options.
@param {object} options.canvas - Canvas attributes.
@param {object} options.wrapper - Canvas wrapper attributes.
@param {boolean} options.persistent - If true, the chart will not be released after the spec. | acquireChart ( config , options ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/test/jasmine.utils.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/chart.js/test/jasmine.utils.js | MIT |
(function (global, factory) {
'use strict';
/* Use AMD */
if (typeof define === 'function' && define.amd) {
define(function () {
return new (factory(global, global.document))();
});
}
/* Use CommonJS */
else if (typeof module !== 'undefined' && module.exports) {
module.exports = new (factory(global, global.document))();
}
/* Use Browser */
else {
global.Push = new (factory(global, global.document))();
}
})(typeof window !== 'undefined' ? window : this, function (w, d) { | Push
=======
A compact, cross-browser solution for the JavaScript Notifications API
Credits
-------
Tsvetan Tsvetkov (ttsvetko)
Alex Gibson (alexgibson)
License
-------
The MIT License (MIT)
Copyright (c) 2015-2017 Tyler Nickerson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@preserve | (anonymous) ( global , factory ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | MIT |
closeNotification = function (id) {
var errored = false,
notification = notifications[id];
if (typeof notification !== 'undefined') {
/* Safari 6+, Chrome 23+ */
if (notification.close) {
notification.close();
/* Legacy webkit browsers */
} else if (notification.cancel) {
notification.cancel();
/* IE9+ */
} else if (w.external && w.external.msIsSiteMode) {
w.external.msSiteModeClearIconOverlay();
} else {
errored = true;
throw new Error('Unable to close notification: unknown interface');
}
if (!errored) {
return removeNotification(id);
}
}
return false;
}, | Closes a notification
@param {Notification} notification
@return {Boolean} boolean denoting whether the operation was successful | closeNotification ( id ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | MIT |
addNotification = function (notification) {
var id = currentId;
notifications[id] = notification;
currentId++;
return id;
}, | Adds a notification to the global dictionary of notifications
@param {Notification} notification
@return {Integer} Dictionary key of the notification | addNotification ( notification ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | MIT |
removeNotification = function (id) {
var dict = {},
success = false,
key;
for (key in notifications) {
if (notifications.hasOwnProperty(key)) {
if (key != id) {
dict[key] = notifications[key];
} else {
// We're successful if we omit the given ID from the new array
success = true;
}
}
}
// Overwrite the current notifications dictionary with the filtered one
notifications = dict;
return success;
}, | Removes a notification with the given ID
@param {Integer} id - Dictionary key/ID of the notification to remove
@return {Boolean} boolean denoting success | removeNotification ( id ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | MIT |
self.Permission.request = function (onGranted, onDenied) {
var existing = self.Permission.get();
/* Return if Push not supported */
if (!self.isSupported) {
throw new Error(incompatibilityErrorMessage);
}
/* Default callback */
callback = function (result) {
switch (result) {
case self.Permission.GRANTED:
hasPermission = true;
if (onGranted) onGranted();
break;
case self.Permission.DENIED:
hasPermission = false;
if (onDenied) onDenied();
break;
}
};
/* Permissions already set */
if (existing !== self.Permission.DEFAULT) {
callback(existing);
}
/* Safari 6+, Chrome 23+ */
else if (w.Notification && w.Notification.requestPermission) {
Notification.requestPermission(callback);
}
/* Legacy webkit browsers */
else if (w.webkitNotifications && w.webkitNotifications.checkPermission) {
w.webkitNotifications.requestPermission(callback);
} else {
throw new Error(incompatibilityErrorMessage);
}
}; | Requests permission for desktop notifications
@param {Function} callback - Function to execute once permission is granted
@return {void} | self.Permission.request ( onGranted , onDenied ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | MIT |
self.Permission.has = function () {
return hasPermission;
}; | Returns whether Push has been granted permission to run
@return {Boolean} | self.Permission.has ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | MIT |
self.Permission.get = function () {
var permission;
/* Return if Push not supported */
if (!self.isSupported) { throw new Error(incompatibilityErrorMessage); }
/* Safari 6+, Chrome 23+ */
if (w.Notification && w.Notification.permissionLevel) {
permission = w.Notification.permissionLevel;
/* Legacy webkit browsers */
} else if (w.webkitNotifications && w.webkitNotifications.checkPermission) {
permission = Permissions[w.webkitNotifications.checkPermission()];
/* Firefox 23+ */
} else if (w.Notification && w.Notification.permission) {
permission = w.Notification.permission;
/* Firefox Mobile */
} else if (navigator.mozNotification) {
permission = Permission.GRANTED;
/* IE9+ */
} else if (w.external && w.external.msIsSiteMode() !== undefined) {
permission = w.external.msIsSiteMode() ? Permission.GRANTED : Permission.DEFAULT;
} else {
throw new Error(incompatibilityErrorMessage);
}
return permission;
}; | Gets the permission level
@return {Permission} The permission level | self.Permission.get ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | MIT |
self.isSupported = (function () {
var isSupported = false;
try {
isSupported =
/* Safari, Chrome */
!!(w.Notification ||
/* Chrome & ff-html5notifications plugin */
w.webkitNotifications ||
/* Firefox Mobile */
navigator.mozNotification ||
/* IE9+ */
(w.external && w.external.msIsSiteMode() !== undefined));
} catch (e) {}
return isSupported;
})(); | Detects whether the user's browser supports notifications
@return {Boolean} | (anonymous) ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | MIT |
self.create = function (title, options) {
var promiseCallback;
/* Fail if the browser is not supported */
if (!self.isSupported) {
throw new Error(incompatibilityErrorMessage);
}
/* Fail if no or an invalid title is provided */
if (!isString(title)) {
throw new Error('PushError: Title of notification must be a string');
}
/* Request permission if it isn't granted */
if (!self.Permission.has()) {
promiseCallback = function(resolve, reject) {
self.Permission.request(function() {
try {
createCallback(title, options, resolve);
} catch (e) {
reject(e);
}
}, function() {
reject("Permission request declined");
});
};
} else {
promiseCallback = function(resolve, reject) {
try {
createCallback(title, options, resolve);
} catch (e) {
reject(e);
}
};
}
return new Promise(promiseCallback);
}; | Creates and displays a new notification
@param {Array} options
@return {Promise} | self.create ( title , options ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | MIT |
self.count = function () {
var count = 0,
key;
for (key in notifications)
count++;
return count;
}, | Returns the notification count
@return {Integer} The notification count | self.count ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | MIT |
self.__lastWorkerPath = function () {
return self.lastWorkerPath;
}, | Internal function that returns the path of the last service worker used
For testing purposes only
@return {String} The service worker path | self.__lastWorkerPath ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | MIT |
self.close = function (tag) {
var key;
for (key in notifications) {
notification = notifications[key];
/* Run only if the tags match */
if (notification.tag === tag) {
/* Call the notification's close() method */
return closeNotification(key);
}
}
}; | Closes a notification with the given tag
@param {String} tag - Tag of the notification to close
@return {Boolean} boolean denoting success | self.close ( tag ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | MIT |
self.clear = function () {
var success = true;
for (key in notifications)
success = success && closeNotification(key);
return success;
}; | Clears all notifications
@return {void} | self.clear ( ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/push.js/push.js | MIT |
abp.utils.buildQueryString = function (parameterInfos, includeQuestionMark) {
if (includeQuestionMark === undefined) {
includeQuestionMark = true;
}
var qs = '';
function addSeperator() {
if (!qs.length) {
if (includeQuestionMark) {
qs = qs + '?';
}
} else {
qs = qs + '&';
}
}
for (var i = 0; i < parameterInfos.length; ++i) {
var parameterInfo = parameterInfos[i];
if (parameterInfo.value === undefined) {
continue;
}
if (parameterInfo.value === null) {
parameterInfo.value = '';
}
addSeperator();
if (parameterInfo.value.toJSON && typeof parameterInfo.value.toJSON === "function") {
qs = qs + parameterInfo.name + '=' + encodeURIComponent(parameterInfo.value.toJSON());
} else if (Array.isArray(parameterInfo.value) && parameterInfo.value.length) {
for (var j = 0; j < parameterInfo.value.length; j++) {
if (j > 0) {
addSeperator();
}
qs = qs + parameterInfo.name + '[' + j + ']=' + encodeURIComponent(parameterInfo.value[j]);
}
} else {
qs = qs + parameterInfo.name + '=' + encodeURIComponent(parameterInfo.value);
}
}
return qs;
} | parameterInfos should be an array of { name, value } objects
where name is query string parameter name and value is it's value.
includeQuestionMark is true by default. | abp.utils.buildQueryString ( parameterInfos , includeQuestionMark ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/abp-web-resources/Abp/Framework/scripts/abp.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/abp-web-resources/Abp/Framework/scripts/abp.js | MIT |
abp.utils.setCookieValue = function (key, value, expireDate, path, domain) {
var cookieValue = encodeURIComponent(key) + '=';
if (value) {
cookieValue = cookieValue + encodeURIComponent(value);
}
if (expireDate) {
cookieValue = cookieValue + "; expires=" + expireDate.toUTCString();
}
if (path) {
cookieValue = cookieValue + "; path=" + path;
}
if (domain) {
cookieValue = cookieValue + "; domain=" + domain;
}
document.cookie = cookieValue;
}; | Sets a cookie value for given key.
This is a simple implementation created to be used by ABP.
Please use a complete cookie library if you need.
@param {string} key
@param {string} value
@param {Date} expireDate (optional). If not specified the cookie will expire at the end of session.
@param {string} path (optional) | abp.utils.setCookieValue ( key , value , expireDate , path , domain ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/abp-web-resources/Abp/Framework/scripts/abp.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/abp-web-resources/Abp/Framework/scripts/abp.js | MIT |
abp.utils.getCookieValue = function (key) {
var equalities = document.cookie.split('; ');
for (var i = 0; i < equalities.length; i++) {
if (!equalities[i]) {
continue;
}
var splitted = equalities[i].split('=');
if (splitted.length != 2) {
continue;
}
if (decodeURIComponent(splitted[0]) === key) {
return decodeURIComponent(splitted[1] || '');
}
}
return null;
}; | Gets a cookie with given key.
This is a simple implementation created to be used by ABP.
Please use a complete cookie library if you need.
@param {string} key
@returns {string} Cookie value or null | abp.utils.getCookieValue ( key ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/abp-web-resources/Abp/Framework/scripts/abp.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/abp-web-resources/Abp/Framework/scripts/abp.js | MIT |
abp.utils.deleteCookie = function (key, path) {
var cookieValue = encodeURIComponent(key) + '=';
cookieValue = cookieValue + "; expires=" + (new Date(new Date().getTime() - 86400000)).toUTCString();
if (path) {
cookieValue = cookieValue + "; path=" + path;
}
document.cookie = cookieValue;
} | Deletes cookie for given key.
This is a simple implementation created to be used by ABP.
Please use a complete cookie library if you need.
@param {string} key
@param {string} path (optional) | abp.utils.deleteCookie ( key , path ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/abp-web-resources/Abp/Framework/scripts/abp.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/abp-web-resources/Abp/Framework/scripts/abp.js | MIT |
abp.utils.getDomain = function (url) {
var domainRegex = /(https?:){0,1}\/\/((?:[\w\d-]+\.)+[\w\d]{2,})/i;
var matches = domainRegex.exec(url);
return (matches && matches[2]) ? matches[2] : '';
}
/* TIMING *****************************************/
abp.timing = abp.timing || {};
abp.timing.utcClockProvider = (function () {
var toUtc = function (date) {
return Date.UTC(
date.getUTCFullYear()
, date.getUTCMonth()
, date.getUTCDate()
, date.getUTCHours()
, date.getUTCMinutes()
, date.getUTCSeconds()
, date.getUTCMilliseconds()
);
}
var now = function () {
return new Date();
};
var normalize = function (date) {
if (!date) {
return date;
}
return new Date(toUtc(date));
};
// Public interface ///////////////////////////////////////////////////
return {
now: now,
normalize: normalize,
supportsMultipleTimezone: true
};
})();
abp.timing.localClockProvider = (function () {
var toLocal = function (date) {
return new Date(
date.getFullYear()
, date.getMonth()
, date.getDate()
, date.getHours()
, date.getMinutes()
, date.getSeconds()
, date.getMilliseconds()
);
}
var now = function () {
return toLocal(new Date());
}
var normalize = function (date) {
if (!date) {
return date;
}
return toLocal(date);
}
// Public interface ///////////////////////////////////////////////////
return {
now: now,
normalize: normalize,
supportsMultipleTimezone: false
};
})();
abp.timing.unspecifiedClockProvider = (function () {
var now = function () {
return new Date();
}
var normalize = function (date) {
return date;
}
// Public interface ///////////////////////////////////////////////////
return {
now: now,
normalize: normalize,
supportsMultipleTimezone: false
};
})();
abp.timing.convertToUserTimezone = function (date) {
var localTime = date.getTime();
var utcTime = localTime + (date.getTimezoneOffset() * 60000);
var targetTime = parseInt(utcTime) + parseInt(abp.timing.timeZoneInfo.windows.currentUtcOffsetInMilliseconds);
return new Date(targetTime);
};
/* CLOCK *****************************************/
abp.clock = abp.clock || {};
abp.clock.now = function () {
if (abp.clock.provider) {
return abp.clock.provider.now();
}
return new Date();
}
abp.clock.normalize = function (date) {
if (abp.clock.provider) {
return abp.clock.provider.normalize(date);
}
return date;
}
abp.clock.provider = abp.timing.unspecifiedClockProvider;
/* SECURITY ***************************************/
abp.security = abp.security || {};
abp.security.antiForgery = abp.security.antiForgery || {};
abp.security.antiForgery.tokenCookieName = 'XSRF-TOKEN';
abp.security.antiForgery.tokenHeaderName = 'X-XSRF-TOKEN';
abp.security.antiForgery.getToken = function () {
return abp.utils.getCookieValue(abp.security.antiForgery.tokenCookieName);
};
abp.security.antiForgery.shouldSendToken = function (settings) {
if (settings.crossDomain === undefined || settings.crossDomain === null) {
return abp.utils.getDomain(location.href) === abp.utils.getDomain(settings.url);
}
return !settings.crossDomain;
};
})(jQuery); | Gets the domain of given url
@param {string} url
@returns {string} | abp.utils.getDomain ( url ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/abp-web-resources/Abp/Framework/scripts/abp.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/abp-web-resources/Abp/Framework/scripts/abp.js | MIT |
setSelected: function (index, selected, $lis) {
if (!$lis) {
this.togglePlaceholder(); // check if setSelected is being called by changing the value of the select
$lis = this.findLis().eq(this.liObj[index]);
}
$lis.toggleClass('selected', selected).find('a').attr('aria-selected', selected);
}, | @param {number} index - the index of the option that is being changed
@param {boolean} selected - true if the option is being selected, false if being deselected
@param {JQuery} $lis - the 'li' element that is being modified | setSelected ( index , selected , $lis ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/bootstrap-select/dist/js/bootstrap-select.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/bootstrap-select/dist/js/bootstrap-select.js | MIT |
setDisabled: function (index, disabled, $lis) {
if (!$lis) {
$lis = this.findLis().eq(this.liObj[index]);
}
if (disabled) {
$lis.addClass('disabled').children('a').attr('href', '#').attr('tabindex', -1).attr('aria-disabled', true);
} else {
$lis.removeClass('disabled').children('a').removeAttr('href').attr('tabindex', 0).attr('aria-disabled', false);
}
}, | @param {number} index - the index of the option that is being disabled
@param {boolean} disabled - true if the option is being disabled, false if being enabled
@param {JQuery} $lis - the 'li' element that is being modified | setDisabled ( index , disabled , $lis ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/bootstrap-select/dist/js/bootstrap-select.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/bootstrap-select/dist/js/bootstrap-select.js | MIT |
$.validator.addMethod( "giroaccountNL", function( value, element ) {
return this.optional( element ) || /^[0-9]{1,7}$/.test( value );
}, "Please specify a valid giro account number" ); | Dutch giro account numbers (not bank numbers) have max 7 digits | (anonymous) ( value , element ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/jquery-validation/src/additional/giroaccountNL.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/jquery-validation/src/additional/giroaccountNL.js | MIT |
$.validator.addMethod( "currency", function( value, element, param ) {
var isParamString = typeof param === "string",
symbol = isParamString ? param : param[ 0 ],
soft = isParamString ? true : param[ 1 ],
regex;
symbol = symbol.replace( /,/g, "" );
symbol = soft ? symbol + "]" : symbol + "]?";
regex = "^[" + symbol + "([1-9]{1}[0-9]{0,2}(\\,[0-9]{3})*(\\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\\.[0-9]{0,2})?|0(\\.[0-9]{0,2})?|(\\.[0-9]{1,2})?)$";
regex = new RegExp( regex );
return this.optional( element ) || regex.test( value );
}, "Please specify a valid currency" ); | Validates currencies with any given symbols by @jameslouiz
Symbols can be optional or required. Symbols required by default
Usage examples:
currency: ["Β£", false] - Use false for soft currency validation
currency: ["$", false]
currency: ["RM", false] - also works with text based symbols such as "RM" - Malaysia Ringgit etc
<input class="currencyInput" name="currencyInput">
Soft symbol checking
currencyInput: {
currency: ["$", false]
}
Strict symbol checking (default)
currencyInput: {
currency: "$"
//OR
currency: ["$", true]
}
Multiple Symbols
currencyInput: {
currency: "$,Β£,Β’"
} | (anonymous) ( value , element , param ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/jquery-validation/src/additional/currency.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/jquery-validation/src/additional/currency.js | MIT |
$.validator.addMethod( "phoneUS", function( phone_number, element ) {
phone_number = phone_number.replace( /\s+/g, "" );
return this.optional( element ) || phone_number.length > 9 &&
phone_number.match( /^(\+?1-?)?(\([2-9]([02-9]\d|1[02-9])\)|[2-9]([02-9]\d|1[02-9]))-?[2-9]([02-9]\d|1[02-9])-?\d{4}$/ );
}, "Please specify a valid phone number" ); | Matches US phone number format
where the area code may not start with 1 and the prefix may not start with 1
allows '-' or ' ' as a separator and allows parens around area code
some people may want to put a '1' in front of their number
1(212)-999-2345 or
212 999 2344 or
212-999-0983
but not
111-123-5434
and not
212 123 4567 | (anonymous) ( phone_number , element ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/jquery-validation/src/additional/phoneUS.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/jquery-validation/src/additional/phoneUS.js | MIT |
$.validator.addMethod( "vinUS", function( v ) {
if ( v.length !== 17 ) {
return false;
}
var LL = [ "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ],
VL = [ 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 7, 9, 2, 3, 4, 5, 6, 7, 8, 9 ],
FL = [ 8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2 ],
rs = 0,
i, n, d, f, cd, cdv;
for ( i = 0; i < 17; i++ ) {
f = FL[ i ];
d = v.slice( i, i + 1 );
if ( i === 8 ) {
cdv = d;
}
if ( !isNaN( d ) ) {
d *= f;
} else {
for ( n = 0; n < LL.length; n++ ) {
if ( d.toUpperCase() === LL[ n ] ) {
d = VL[ n ];
d *= f;
if ( isNaN( cdv ) && n === 8 ) {
cdv = LL[ n ];
}
break;
}
}
}
rs += d;
}
cd = rs % 11;
if ( cd === 10 ) {
cd = "X";
}
if ( cd === cdv ) {
return true;
}
return false;
}, "The specified vehicle identification number (VIN) is invalid." ); | Return true, if the value is a valid vehicle identification number (VIN).
Works with all kind of text inputs.
@example <input type="text" size="20" name="VehicleID" class="{required:true,vinUS:true}" />
@desc Declares a required input element whose value must be a valid vehicle identification number.
@name $.validator.methods.vinUS
@type Boolean
@cat Plugins/Validate/Methods | (anonymous) ( v ) | javascript | aspnetboilerplate/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/jquery-validation/src/additional/vinUS.js | https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/wwwroot/lib/jquery-validation/src/additional/vinUS.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.