code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
function scrollToX(destX, animate)
{
var percentScrolled = destX / (contentWidth - paneWidth);
positionDragX(percentScrolled * dragMaxX, animate);
}
|
`fail` will execute when the request fails
|
scrollToX
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function scrollToElement(ele, stickToTop, animate)
{
var e, eleHeight, eleWidth, eleTop = 0, eleLeft = 0, viewportTop, viewportLeft, maxVisibleEleTop, maxVisibleEleLeft, destY, destX;
// Legal hash values aren't necessarily legal jQuery selectors so we need to catch any
// errors from the lookup...
try {
e = $(ele);
} catch (err) {
return;
}
eleHeight = e.outerHeight();
eleWidth= e.outerWidth();
container.scrollTop(0);
container.scrollLeft(0);
// loop through parents adding the offset top of any elements that are relatively positioned between
// the focused element and the jspPane so we can get the true distance from the top
// of the focused element to the top of the scrollpane...
while (!e.is('.jspPane')) {
eleTop += e.position().top;
eleLeft += e.position().left;
e = e.offsetParent();
if (/^body|html$/i.test(e[0].nodeName)) {
// we ended up too high in the document structure. Quit!
return;
}
}
viewportTop = contentPositionY();
maxVisibleEleTop = viewportTop + paneHeight;
if (eleTop < viewportTop || stickToTop) { // element is above viewport
destY = eleTop - settings.verticalGutter;
} else if (eleTop + eleHeight > maxVisibleEleTop) { // element is below viewport
destY = eleTop - paneHeight + eleHeight + settings.verticalGutter;
}
if (destY) {
scrollToY(destY, animate);
}
viewportLeft = contentPositionX();
maxVisibleEleLeft = viewportLeft + paneWidth;
if (eleLeft < viewportLeft || stickToTop) { // element is to the left of viewport
destX = eleLeft - settings.horizontalGutter;
} else if (eleLeft + eleWidth > maxVisibleEleLeft) { // element is to the right viewport
destX = eleLeft - paneWidth + eleWidth + settings.horizontalGutter;
}
if (destX) {
scrollToX(destX, animate);
}
}
|
`fail` will execute when the request fails
|
scrollToElement
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function contentPositionX()
{
return -pane.position().left;
}
|
`fail` will execute when the request fails
|
contentPositionX
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function contentPositionY()
{
return -pane.position().top;
}
|
`fail` will execute when the request fails
|
contentPositionY
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function isCloseToBottom()
{
var scrollableHeight = contentHeight - paneHeight;
return (scrollableHeight > 20) && (scrollableHeight - contentPositionY() < 10);
}
|
`fail` will execute when the request fails
|
isCloseToBottom
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function isCloseToRight()
{
var scrollableWidth = contentWidth - paneWidth;
return (scrollableWidth > 20) && (scrollableWidth - contentPositionX() < 10);
}
|
`fail` will execute when the request fails
|
isCloseToRight
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function initMousewheel()
{
container.unbind(mwEvent).bind(
mwEvent,
function (event, delta, deltaX, deltaY) {
var dX = horizontalDragPosition, dY = verticalDragPosition;
jsp.scrollBy(deltaX * settings.mouseWheelSpeed, -deltaY * settings.mouseWheelSpeed, false);
// return true if there was no movement so rest of screen can scroll
return dX == horizontalDragPosition && dY == verticalDragPosition;
}
);
}
|
`fail` will execute when the request fails
|
initMousewheel
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function removeMousewheel()
{
container.unbind(mwEvent);
}
|
`fail` will execute when the request fails
|
removeMousewheel
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function nil()
{
return false;
}
|
`fail` will execute when the request fails
|
nil
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function initFocusHandler()
{
pane.find(':input,a').unbind('focus.jsp').bind(
'focus.jsp',
function(e)
{
scrollToElement(e.target, false);
}
);
}
|
`fail` will execute when the request fails
|
initFocusHandler
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function removeFocusHandler()
{
pane.find(':input,a').unbind('focus.jsp');
}
|
`fail` will execute when the request fails
|
removeFocusHandler
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function initKeyboardNav()
{
var keyDown, elementHasScrolled, validParents = [];
isScrollableH && validParents.push(horizontalBar[0]);
isScrollableV && validParents.push(verticalBar[0]);
// IE also focuses elements that don't have tabindex set.
pane.focus(
function()
{
elem.focus();
}
);
elem.attr('tabindex', 0)
.unbind('keydown.jsp keypress.jsp')
.bind(
'keydown.jsp',
function(e)
{
if (e.target !== this && !(validParents.length && $(e.target).closest(validParents).length)){
return;
}
var dX = horizontalDragPosition, dY = verticalDragPosition;
switch(e.keyCode) {
case 40: // down
case 38: // up
case 34: // page down
case 32: // space
case 33: // page up
case 39: // right
case 37: // left
keyDown = e.keyCode;
keyDownHandler();
break;
case 35: // end
scrollToY(contentHeight - paneHeight);
keyDown = null;
break;
case 36: // home
scrollToY(0);
keyDown = null;
break;
}
elementHasScrolled = e.keyCode == keyDown && dX != horizontalDragPosition || dY != verticalDragPosition;
return !elementHasScrolled;
}
).bind(
'keypress.jsp', // For FF/ OSX so that we can cancel the repeat key presses if the JSP scrolls...
function(e)
{
if (e.keyCode == keyDown) {
keyDownHandler();
}
return !elementHasScrolled;
}
);
if (settings.hideFocus) {
elem.css('outline', 'none');
if ('hideFocus' in container[0]){
elem.attr('hideFocus', true);
}
} else {
elem.css('outline', '');
if ('hideFocus' in container[0]){
elem.attr('hideFocus', false);
}
}
function keyDownHandler()
{
var dX = horizontalDragPosition, dY = verticalDragPosition;
switch(keyDown) {
case 40: // down
jsp.scrollByY(settings.keyboardSpeed, false);
break;
case 38: // up
jsp.scrollByY(-settings.keyboardSpeed, false);
break;
case 34: // page down
case 32: // space
jsp.scrollByY(paneHeight * settings.scrollPagePercent, false);
break;
case 33: // page up
jsp.scrollByY(-paneHeight * settings.scrollPagePercent, false);
break;
case 39: // right
jsp.scrollByX(settings.keyboardSpeed, false);
break;
case 37: // left
jsp.scrollByX(-settings.keyboardSpeed, false);
break;
}
elementHasScrolled = dX != horizontalDragPosition || dY != verticalDragPosition;
return elementHasScrolled;
}
}
|
`fail` will execute when the request fails
|
initKeyboardNav
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function keyDownHandler()
{
var dX = horizontalDragPosition, dY = verticalDragPosition;
switch(keyDown) {
case 40: // down
jsp.scrollByY(settings.keyboardSpeed, false);
break;
case 38: // up
jsp.scrollByY(-settings.keyboardSpeed, false);
break;
case 34: // page down
case 32: // space
jsp.scrollByY(paneHeight * settings.scrollPagePercent, false);
break;
case 33: // page up
jsp.scrollByY(-paneHeight * settings.scrollPagePercent, false);
break;
case 39: // right
jsp.scrollByX(settings.keyboardSpeed, false);
break;
case 37: // left
jsp.scrollByX(-settings.keyboardSpeed, false);
break;
}
elementHasScrolled = dX != horizontalDragPosition || dY != verticalDragPosition;
return elementHasScrolled;
}
|
`fail` will execute when the request fails
|
keyDownHandler
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function removeKeyboardNav()
{
elem.attr('tabindex', '-1')
.removeAttr('tabindex')
.unbind('keydown.jsp keypress.jsp');
}
|
`fail` will execute when the request fails
|
removeKeyboardNav
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function observeHash()
{
if (location.hash && location.hash.length > 1) {
var e,
retryInt,
hash = escape(location.hash.substr(1)) // hash must be escaped to prevent XSS
;
try {
e = $('#' + hash + ', a[name="' + hash + '"]');
} catch (err) {
return;
}
if (e.length && pane.find(hash)) {
// nasty workaround but it appears to take a little while before the hash has done its thing
// to the rendered page so we just wait until the container's scrollTop has been messed up.
if (container.scrollTop() === 0) {
retryInt = setInterval(
function()
{
if (container.scrollTop() > 0) {
scrollToElement(e, true);
$(document).scrollTop(container.position().top);
clearInterval(retryInt);
}
},
50
);
} else {
scrollToElement(e, true);
$(document).scrollTop(container.position().top);
}
}
}
}
|
`fail` will execute when the request fails
|
observeHash
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function hijackInternalLinks()
{
// only register the link handler once
if ($(document.body).data('jspHijack')) {
return;
}
// remember that the handler was bound
$(document.body).data('jspHijack', true);
// use live handler to also capture newly created links
$(document.body).delegate('a[href*=#]', 'click', function(event) {
// does the link point to the same page?
// this also takes care of cases with a <base>-Tag or Links not starting with the hash #
// e.g. <a href="index.html#test"> when the current url already is index.html
var href = this.href.substr(0, this.href.indexOf('#')),
locationHref = location.href,
hash,
element,
container,
jsp,
scrollTop,
elementTop;
if (location.href.indexOf('#') !== -1) {
locationHref = location.href.substr(0, location.href.indexOf('#'));
}
if (href !== locationHref) {
// the link points to another page
return;
}
// check if jScrollPane should handle this click event
hash = escape(this.href.substr(this.href.indexOf('#') + 1));
// find the element on the page
element;
try {
element = $('#' + hash + ', a[name="' + hash + '"]');
} catch (e) {
// hash is not a valid jQuery identifier
return;
}
if (!element.length) {
// this link does not point to an element on this page
return;
}
container = element.closest('.jspScrollable');
jsp = container.data('jsp');
// jsp might be another jsp instance than the one, that bound this event
// remember: this event is only bound once for all instances.
jsp.scrollToElement(element, true);
if (container[0].scrollIntoView) {
// also scroll to the top of the container (if it is not visible)
scrollTop = $(window).scrollTop();
elementTop = element.offset().top;
if (elementTop < scrollTop || elementTop > scrollTop + $(window).height()) {
container[0].scrollIntoView();
}
}
// jsp handled this event, prevent the browser default (scrolling :P)
event.preventDefault();
});
}
|
`fail` will execute when the request fails
|
hijackInternalLinks
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function initTouch()
{
var startX,
startY,
touchStartX,
touchStartY,
moved,
moving = false;
container.unbind('touchstart.jsp touchmove.jsp touchend.jsp click.jsp-touchclick').bind(
'touchstart.jsp',
function(e)
{
var touch = e.originalEvent.touches[0];
startX = contentPositionX();
startY = contentPositionY();
touchStartX = touch.pageX;
touchStartY = touch.pageY;
moved = false;
moving = true;
}
).bind(
'touchmove.jsp',
function(ev)
{
if(!moving) {
return;
}
var touchPos = ev.originalEvent.touches[0],
dX = horizontalDragPosition, dY = verticalDragPosition;
jsp.scrollTo(startX + touchStartX - touchPos.pageX, startY + touchStartY - touchPos.pageY);
moved = moved || Math.abs(touchStartX - touchPos.pageX) > 5 || Math.abs(touchStartY - touchPos.pageY) > 5;
// return true if there was no movement so rest of screen can scroll
return dX == horizontalDragPosition && dY == verticalDragPosition;
}
).bind(
'touchend.jsp',
function(e)
{
moving = false;
/*if(moved) {
return false;
}*/
}
).bind(
'click.jsp-touchclick',
function(e)
{
if(moved) {
moved = false;
return false;
}
}
);
}
|
`fail` will execute when the request fails
|
initTouch
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function destroy(){
var currentY = contentPositionY(),
currentX = contentPositionX();
elem.removeClass('jspScrollable').unbind('.jsp');
elem.replaceWith(originalElement.append(pane.children()));
originalElement.scrollTop(currentY);
originalElement.scrollLeft(currentX);
// clear reinitialize timer if active
if (reinitialiseInterval) {
clearInterval(reinitialiseInterval);
}
}
|
`fail` will execute when the request fails
|
destroy
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function handler(event) {
var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; }
if ( orgEvent.detail ) { delta = -orgEvent.detail/3; }
// New school multidimensional scroll (touchpads) deltas
deltaY = delta;
// Gecko
if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
deltaY = 0;
deltaX = -1*delta;
}
// Webkit
if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
|
`fail` will execute when the request fails
|
handler
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function decodeCssEscape(s) {
var i = parseInt(s.substring(1), 16);
// If parseInt didn't find a hex diigt, it returns NaN so return the
// escaped character.
// Otherwise, parseInt will stop at the first non-hex digit so there's no
// need to worry about trailing whitespace.
if (i > 0xffff) {
// A supplemental codepoint.
return i -= 0x10000,
String.fromCharCode(
0xd800 + (i >> 10),
0xdc00 + (i & 0x3FF));
} else if (i == i) {
return String.fromCharCode(i);
} else if (s[1] < ' ') {
// "a backslash followed by a newline is ignored".
return '';
} else {
return s[1];
}
}
|
Decodes an escape sequence as specified in CSS3 section 4.1.
http://www.w3.org/TR/css3-syntax/#characters
@private
|
decodeCssEscape
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function escapeCssString(s, replacer) {
return '"' + s.replace(/[\u0000-\u001f\\\"<>]/g, replacer) + '"';
}
|
Returns an equivalent CSS string literal given plain text: foo -> "foo".
@private
|
escapeCssString
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function escapeCssStrChar(ch) {
return cssStrChars[ch]
|| (cssStrChars[ch] = '\\' + ch.charCodeAt(0).toString(16) + ' ');
}
|
Maps chars to CSS escaped equivalents: "\n" -> "\\a ".
@private
|
escapeCssStrChar
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function escapeCssUrlChar(ch) {
return cssUrlChars[ch]
|| (cssUrlChars[ch] = (ch < '\x10' ? '%0' : '%')
+ ch.charCodeAt(0).toString(16));
}
|
Maps chars to URI escaped equivalents: "\n" -> "%0a".
@private
|
escapeCssUrlChar
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function parse(uriStr) {
var m = ('' + uriStr).match(URI_RE_);
if (!m) { return null; }
return new URI(
nullIfAbsent(m[1]),
nullIfAbsent(m[2]),
nullIfAbsent(m[3]),
nullIfAbsent(m[4]),
nullIfAbsent(m[5]),
nullIfAbsent(m[6]),
nullIfAbsent(m[7]));
}
|
creates a uri from the string form. The parser is relaxed, so special
characters that aren't escaped but don't cause ambiguities will not cause
parse failures.
@return {URI|null}
|
parse
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function create(scheme, credentials, domain, port, path, query, fragment) {
var uri = new URI(
encodeIfExists2(scheme, URI_DISALLOWED_IN_SCHEME_OR_CREDENTIALS_),
encodeIfExists2(
credentials, URI_DISALLOWED_IN_SCHEME_OR_CREDENTIALS_),
encodeIfExists(domain),
port > 0 ? port.toString() : null,
encodeIfExists2(path, URI_DISALLOWED_IN_PATH_),
null,
encodeIfExists(fragment));
if (query) {
if ('string' === typeof query) {
uri.setRawQuery(query.replace(/[^?&=0-9A-Za-z_\-~.%]/g, encodeOne));
} else {
uri.setAllParameters(query);
}
}
return uri;
}
|
creates a uri from the given parts.
@param scheme {string} an unencoded scheme such as "http" or null
@param credentials {string} unencoded user credentials or null
@param domain {string} an unencoded domain name or null
@param port {number} a port number in [1, 32768].
-1 indicates no port, as does null.
@param path {string} an unencoded path
@param query {Array.<string>|string|null} a list of unencoded cgi
parameters where even values are keys and odds the corresponding values
or an unencoded query.
@param fragment {string} an unencoded fragment without the "#" or null.
@return {URI}
|
create
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function encodeIfExists(unescapedPart) {
if ('string' == typeof unescapedPart) {
return encodeURIComponent(unescapedPart);
}
return null;
}
|
creates a uri from the given parts.
@param scheme {string} an unencoded scheme such as "http" or null
@param credentials {string} unencoded user credentials or null
@param domain {string} an unencoded domain name or null
@param port {number} a port number in [1, 32768].
-1 indicates no port, as does null.
@param path {string} an unencoded path
@param query {Array.<string>|string|null} a list of unencoded cgi
parameters where even values are keys and odds the corresponding values
or an unencoded query.
@param fragment {string} an unencoded fragment without the "#" or null.
@return {URI}
|
encodeIfExists
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function encodeIfExists2(unescapedPart, extra) {
if ('string' == typeof unescapedPart) {
return encodeURI(unescapedPart).replace(extra, encodeOne);
}
return null;
}
|
if unescapedPart is non null, then escapes any characters in it that aren't
valid characters in a url and also escapes any special characters that
appear in extra.
@param unescapedPart {string}
@param extra {RegExp} a character set of characters in [\01-\177].
@return {string|null} null iff unescapedPart == null.
|
encodeIfExists2
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function encodeOne(ch) {
var n = ch.charCodeAt(0);
return '%' + '0123456789ABCDEF'.charAt((n >> 4) & 0xf) +
'0123456789ABCDEF'.charAt(n & 0xf);
}
|
converts a character in [\01-\177] to its url encoded equivalent.
|
encodeOne
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function normPath(path) {
return path.replace(/(^|\/)\.(?:\/|$)/g, '$1').replace(/\/{2,}/g, '/');
}
|
{@updoc
$ normPath('foo/./bar')
# 'foo/bar'
$ normPath('./foo')
# 'foo'
$ normPath('foo/.')
# 'foo'
$ normPath('foo//bar')
# 'foo/bar'
}
|
normPath
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function collapse_dots(path) {
if (path === null) { return null; }
var p = normPath(path);
// Only /../ left to flatten
var r = PARENT_DIRECTORY_HANDLER_RE;
// We replace with $1 which matches a / before the .. because this
// guarantees that:
// (1) we have at most 1 / between the adjacent place,
// (2) always have a slash if there is a preceding path section, and
// (3) we never turn a relative path into an absolute path.
for (var q; (q = p.replace(r, '$1')) != p; p = q) {};
return p;
}
|
Normalizes its input path and collapses all . and .. sequences except for
.. sequences that would take it above the root of the current parent
directory.
{@updoc
$ collapse_dots('foo/../bar')
# 'bar'
$ collapse_dots('foo/./bar')
# 'foo/bar'
$ collapse_dots('foo/../bar/./../../baz')
# 'baz'
$ collapse_dots('../foo')
# '../foo'
$ collapse_dots('../foo').replace(EXTRA_PARENT_PATHS_RE, '')
# 'foo'
}
|
collapse_dots
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function resolve(baseUri, relativeUri) {
// there are several kinds of relative urls:
// 1. //foo - replaces everything from the domain on. foo is a domain name
// 2. foo - replaces the last part of the path, the whole query and fragment
// 3. /foo - replaces the the path, the query and fragment
// 4. ?foo - replace the query and fragment
// 5. #foo - replace the fragment only
var absoluteUri = baseUri.clone();
// we satisfy these conditions by looking for the first part of relativeUri
// that is not blank and applying defaults to the rest
var overridden = relativeUri.hasScheme();
if (overridden) {
absoluteUri.setRawScheme(relativeUri.getRawScheme());
} else {
overridden = relativeUri.hasCredentials();
}
if (overridden) {
absoluteUri.setRawCredentials(relativeUri.getRawCredentials());
} else {
overridden = relativeUri.hasDomain();
}
if (overridden) {
absoluteUri.setRawDomain(relativeUri.getRawDomain());
} else {
overridden = relativeUri.hasPort();
}
var rawPath = relativeUri.getRawPath();
var simplifiedPath = collapse_dots(rawPath);
if (overridden) {
absoluteUri.setPort(relativeUri.getPort());
simplifiedPath = simplifiedPath
&& simplifiedPath.replace(EXTRA_PARENT_PATHS_RE, '');
} else {
overridden = !!rawPath;
if (overridden) {
// resolve path properly
if (simplifiedPath.charCodeAt(0) !== 0x2f /* / */) { // path is relative
var absRawPath = collapse_dots(absoluteUri.getRawPath() || '')
.replace(EXTRA_PARENT_PATHS_RE, '');
var slash = absRawPath.lastIndexOf('/') + 1;
simplifiedPath = collapse_dots(
(slash ? absRawPath.substring(0, slash) : '')
+ collapse_dots(rawPath))
.replace(EXTRA_PARENT_PATHS_RE, '');
}
} else {
simplifiedPath = simplifiedPath
&& simplifiedPath.replace(EXTRA_PARENT_PATHS_RE, '');
if (simplifiedPath !== rawPath) {
absoluteUri.setRawPath(simplifiedPath);
}
}
}
if (overridden) {
absoluteUri.setRawPath(simplifiedPath);
} else {
overridden = relativeUri.hasQuery();
}
if (overridden) {
absoluteUri.setRawQuery(relativeUri.getRawQuery());
} else {
overridden = relativeUri.hasFragment();
}
if (overridden) {
absoluteUri.setRawFragment(relativeUri.getRawFragment());
}
return absoluteUri;
}
|
resolves a relative url string to a base uri.
@return {URI}
|
resolve
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function URI(
rawScheme,
rawCredentials, rawDomain, port,
rawPath, rawQuery, rawFragment) {
this.scheme_ = rawScheme;
this.credentials_ = rawCredentials;
this.domain_ = rawDomain;
this.port_ = port;
this.path_ = rawPath;
this.query_ = rawQuery;
this.fragment_ = rawFragment;
/**
* @type {Array|null}
*/
this.paramCache_ = null;
}
|
a mutable URI.
This class contains setters and getters for the parts of the URI.
The <tt>getXYZ</tt>/<tt>setXYZ</tt> methods return the decoded part -- so
<code>uri.parse('/foo%20bar').getPath()</code> will return the decoded path,
<tt>/foo bar</tt>.
<p>The raw versions of fields are available too.
<code>uri.parse('/foo%20bar').getRawPath()</code> will return the raw path,
<tt>/foo%20bar</tt>. Use the raw setters with care, since
<code>URI::toString</code> is not guaranteed to return a valid url if a
raw setter was used.
<p>All setters return <tt>this</tt> and so may be chained, a la
<code>uri.parse('/foo').setFragment('part').toString()</code>.
<p>You should not use this constructor directly -- please prefer the factory
functions {@link uri.parse}, {@link uri.create}, {@link uri.resolve}
instead.</p>
<p>The parameters are all raw (assumed to be properly escaped) parts, and
any (but not all) may be null. Undefined is not allowed.</p>
@constructor
|
URI
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function nullIfAbsent(matchPart) {
return ('string' == typeof matchPart) && (matchPart.length > 0)
? matchPart
: null;
}
|
returns the first value for a given cgi parameter or null if the given
parameter name does not appear in the query string.
If the given parameter name does appear, but has no '<tt>=</tt>' following
it, then the empty string will be returned.
@return {string|null}
|
nullIfAbsent
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function unionArrays(arrs) {
var map = {};
for (var i = arrs.length; --i >= 0;) {
var arr = arrs[i];
for (var j = arr.length; --j >= 0;) {
map[arr[j]] = ALLOWED_LITERAL;
}
}
return map;
}
|
Given a series of normalized CSS tokens, applies a property schema, as
defined in CssPropertyPatterns.java, and sanitizes the tokens in place.
@param property a property name.
@param tokens as parsed by lexCss. Modified in place.
@param opt_naiveUriRewriter a URI rewriter; an object with a "rewrite"
function that takes a URL and returns a safe URL.
@param opt_baseURI a URI against which all relative URLs in tokens will
be resolved.
@param opt_idSuffix {string} appended to all IDs to scope them.
|
unionArrays
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function sanitizeFunctionCall(tokens, start) {
var parenDepth = 1, end = start + 1, n = tokens.length;
while (end < n && parenDepth) {
var token = tokens[end++];
// Decrement if we see a close parenthesis, and increment if we
// see a function. Since url(...) are whole tokens, they will not
// affect the token scanning.
parenDepth += (token === ')' ? -1 : /^[^"']*\($/.test(token));
}
// Allow error-recovery from unclosed functions by ignoring the call and
// so allowing resumption at the next ';'.
if (!parenDepth) {
var fnToken = tokens[start].toLowerCase();
var bareFnToken = withoutVendorPrefix(fnToken);
// Cut out the originals, so the caller can step by one token.
var fnTokens = tokens.splice(start, end - start, '');
var fns = propertySchema['cssFns'];
// Look for a function that matches the name.
for (var i = 0, nFns = fns.length; i < nFns; ++i) {
if (fns[i].substring(0, bareFnToken.length) == bareFnToken) {
fnTokens[0] = fnTokens[fnTokens.length - 1] = '';
// Recurse and sanitize the function parameters.
sanitize(
fns[i],
// The actual parameters to the function.
fnTokens,
opt_naiveUriRewriter, opt_baseUri);
// Reconstitute the function from its parameter tokens.
return fnToken + fnTokens.join(' ') + ')';
}
}
}
return '';
}
|
Recurse to apply the appropriate function schema to the function call
that starts at {@code tokens[start]}.
@param {Array.<string>} tokens an array of CSS token that is modified
in place so that all tokens involved in the function call
(from {@code tokens[start]} to a close parenthesis) are folded to
one token.
@param {number} start an index into tokens of a function token like
{@code 'name('}.
@return the replacement function or the empty string if the function
call is not both well-formed and allowed.
|
sanitizeFunctionCall
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function processComplexSelector(start, end) {
// Space around commas is not an operator.
if (selectors[start] === ' ') { ++start; }
if (end-1 !== start && selectors[end] === ' ') { --end; }
// Split the selector into element selectors, content around
// space (ancestor operator) and '>' (descendant operator).
var out = [];
var lastOperator = start;
var valid = true; // True iff out contains a valid complex selector.
for (var i = start; valid && i < end; ++i) {
var tok = selectors[i];
if (COMBINATOR[tok] === COMBINATOR || tok === ' ') {
// We've found the end of a single link in the selector chain.
if (!processCompoundSelector(lastOperator, i, tok)) {
valid = false;
} else {
lastOperator = i+1;
}
}
}
if (!processCompoundSelector(lastOperator, end, '')) {
valid = false;
}
function processCompoundSelector(start, end, combinator) {
// Split the element selector into four parts.
// DIV.foo#bar[href]:hover
// ^ ^ ^
// el classes attrs pseudo
var element, classId, attrs, pseudoSelector,
tok, // The current token
// valid implies the parts above comprise a sanitized selector.
valid = true;
element = '';
if (start < end) {
tok = selectors[start];
if (tok === '*') {
++start;
element = tok;
} else if (/^[a-zA-Z]/.test(tok)) { // is an element selector
var decision = tagPolicy(tok.toLowerCase(), []);
if (decision) {
if ('tagName' in decision) {
tok = decision['tagName'];
}
++start;
element = tok;
}
}
}
classId = '';
attrs = '';
pseudoSelector = '';
for (;valid && start < end; ++start) {
tok = selectors[start];
if (tok.charAt(0) === '#') {
if (/^#_|__$|[^\w#:\-]/.test(tok)) {
valid = false;
} else {
// Rewrite ID elements to include the suffix.
classId += tok + idSuffix;
}
} else if (tok === '.') {
if (++start < end
&& /^[0-9A-Za-z:_\-]+$/.test(tok = selectors[start])
&& !/^_|__$/.test(tok)) {
classId += '.' + tok;
} else {
valid = false;
}
} else if (start + 1 < end && selectors[start] === '[') {
++start;
var vAttr = selectors[start++].toLowerCase();
// Schema lookup for type information
var atype = html4.ATTRIBS[element + '::' + vAttr];
if (atype !== +atype) { atype = html4.ATTRIBS['*::' + vAttr]; }
var rAttr;
// Consult policy
// TODO(kpreid): Making this optional is a kludge to avoid changing
// the public interface until we have a more well-structured design.
if (virtualization.virtualizeAttrName) {
rAttr = virtualization.virtualizeAttrName(element, vAttr);
if (typeof rAttr !== 'string') {
// rejected
valid = false;
rAttr = vAttr;
}
// don't reject even if not in schema
if (valid && atype !== +atype) {
atype = html4.atype['NONE'];
}
} else {
rAttr = vAttr;
if (atype !== +atype) { // not permitted according to schema
valid = false;
}
}
var op = '', value = '', ignoreCase = false;
if (/^[~^$*|]?=$/.test(selectors[start])) {
op = selectors[start++];
value = selectors[start++];
// Quote identifier values.
if (/^[0-9A-Za-z:_\-]+$/.test(value)) {
value = '"' + value + '"';
} else if (value === ']') {
value = '""';
--start;
}
// Reject unquoted values.
if (!/^"([^\"\\]|\\.)*"$/.test(value)) {
valid = false;
}
ignoreCase = selectors[start] === "i";
if (ignoreCase) { ++start; }
}
if (selectors[start] !== ']') {
++start;
valid = false;
}
// TODO: replace this with a lookup table that also provides a
// function from operator and value to testable value.
switch (atype) {
case html4.atype['CLASSES']:
case html4.atype['LOCAL_NAME']:
case html4.atype['NONE']:
break;
case html4.atype['GLOBAL_NAME']:
case html4.atype['ID']:
case html4.atype['IDREF']:
if ((op === '=' || op === '~=' || op === '$=')
&& value != '""' && !ignoreCase) {
// The suffix is case-sensitive, so we can't translate case
// ignoring matches.
value = '"'
+ value.substring(1, value.length-1) + idSuffix
+ '"';
} else if (op === '|=' || op === '') {
// Ok. a|=b -> a == b || a.startsWith(b + "-") and since we
// use "-" to separate the suffix from the identifier, we can
// allow this through unmodified.
// Existence checks are also ok.
} else {
// Can't correctly handle prefix and substring operators
// without leaking information about the suffix.
valid = false;
}
break;
case html4.atype['URI']:
case html4.atype['URI_FRAGMENT']:
// URIs are rewritten, so we can't meanginfully translate URI
// selectors besides the common a[href] one that is used to
// distinguish links from naming anchors.
if (op !== '') { valid = false; }
break;
// TODO: IDREFS
default:
valid = false;
}
if (valid) {
attrs += '[' + rAttr.replace(/[^\w-]/g, '\\$&') + op + value +
(ignoreCase ? ' i]' : ']');
}
} else if (start < end && selectors[start] === ':') {
tok = selectors[++start];
if (PSEUDO_SELECTOR_WHITELIST.test(tok)) {
pseudoSelector += ':' + tok;
} else {
break;
}
} else {
break; // Unrecognized token.
}
}
if (start !== end) { // Tokens not consumed.
valid = false;
}
if (valid) {
// ':' is allowed in identifiers, but is also the
// pseudo-selector separator, so ':' in preceding parts needs to
// be escaped.
var selector = (element + classId).replace(/[^ .*#\w-]/g, '\\$&')
+ attrs + pseudoSelector + combinator;
if (selector) { out.push(selector); }
}
return valid;
}
if (valid) {
if (out.length) {
var safeSelector = out.join('');
// Namespace the selector so that it only matches under
// a node with suffix in its CLASS attribute.
if (containerClass !== null) {
safeSelector = '.' + containerClass + ' ' + safeSelector;
}
sanitized.push(safeSelector);
} // else nothing there.
return true;
} else {
return !opt_onUntranslatableSelector
|| opt_onUntranslatableSelector(selectors.slice(start, end));
}
}
|
Given a series of tokens, returns a list of sanitized selectors.
@param {Array.<string>} selectors In the form produced by csslexer.js.
@param {{
containerClass: ?string,
idSuffix: string,
tagPolicy: function(string, Array.<string>): ?Array.<string>,
virtualizeAttrName: ?function(string, string): ?string
}} virtualization An object like <pre<{
containerClass: class name prepended to all selectors to scope them (if
not null)
idSuffix: appended to all IDs to scope them
tagPolicy: As in html-sanitizer, used for rewriting element names.
virtualizeAttrName: Rewrite a single attribute name for attribute
selectors, or return null if not possible. Should be consistent
with tagPolicy if possible.
}</pre>
If containerClass is {@code "sfx"} and idSuffix is {@code "-sfx"}, the
selector
{@code ["a", "#foo", " ", "b", ".bar"]} will be namespaced to
{@code [".sfx", " ", "a", "#foo-sfx", " ", "b", ".bar"]}.
@param {function(Array.<string>): boolean} opt_onUntranslatableSelector
When a selector cannot be translated, this function is called with the
non-whitespace/comment tokens comprising the selector and returns a
value indicating whether to continue processing the selector list.
If it returns falsey, then processing is aborted and null is returned.
If not present or it returns truthy, then the complex selector is
dropped from the selector list.
@return {Array.<string>}? an array of sanitized selectors.
Null when the untraslatable compound selector handler aborts processing.
|
processComplexSelector
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function processCompoundSelector(start, end, combinator) {
// Split the element selector into four parts.
// DIV.foo#bar[href]:hover
// ^ ^ ^
// el classes attrs pseudo
var element, classId, attrs, pseudoSelector,
tok, // The current token
// valid implies the parts above comprise a sanitized selector.
valid = true;
element = '';
if (start < end) {
tok = selectors[start];
if (tok === '*') {
++start;
element = tok;
} else if (/^[a-zA-Z]/.test(tok)) { // is an element selector
var decision = tagPolicy(tok.toLowerCase(), []);
if (decision) {
if ('tagName' in decision) {
tok = decision['tagName'];
}
++start;
element = tok;
}
}
}
classId = '';
attrs = '';
pseudoSelector = '';
for (;valid && start < end; ++start) {
tok = selectors[start];
if (tok.charAt(0) === '#') {
if (/^#_|__$|[^\w#:\-]/.test(tok)) {
valid = false;
} else {
// Rewrite ID elements to include the suffix.
classId += tok + idSuffix;
}
} else if (tok === '.') {
if (++start < end
&& /^[0-9A-Za-z:_\-]+$/.test(tok = selectors[start])
&& !/^_|__$/.test(tok)) {
classId += '.' + tok;
} else {
valid = false;
}
} else if (start + 1 < end && selectors[start] === '[') {
++start;
var vAttr = selectors[start++].toLowerCase();
// Schema lookup for type information
var atype = html4.ATTRIBS[element + '::' + vAttr];
if (atype !== +atype) { atype = html4.ATTRIBS['*::' + vAttr]; }
var rAttr;
// Consult policy
// TODO(kpreid): Making this optional is a kludge to avoid changing
// the public interface until we have a more well-structured design.
if (virtualization.virtualizeAttrName) {
rAttr = virtualization.virtualizeAttrName(element, vAttr);
if (typeof rAttr !== 'string') {
// rejected
valid = false;
rAttr = vAttr;
}
// don't reject even if not in schema
if (valid && atype !== +atype) {
atype = html4.atype['NONE'];
}
} else {
rAttr = vAttr;
if (atype !== +atype) { // not permitted according to schema
valid = false;
}
}
var op = '', value = '', ignoreCase = false;
if (/^[~^$*|]?=$/.test(selectors[start])) {
op = selectors[start++];
value = selectors[start++];
// Quote identifier values.
if (/^[0-9A-Za-z:_\-]+$/.test(value)) {
value = '"' + value + '"';
} else if (value === ']') {
value = '""';
--start;
}
// Reject unquoted values.
if (!/^"([^\"\\]|\\.)*"$/.test(value)) {
valid = false;
}
ignoreCase = selectors[start] === "i";
if (ignoreCase) { ++start; }
}
if (selectors[start] !== ']') {
++start;
valid = false;
}
// TODO: replace this with a lookup table that also provides a
// function from operator and value to testable value.
switch (atype) {
case html4.atype['CLASSES']:
case html4.atype['LOCAL_NAME']:
case html4.atype['NONE']:
break;
case html4.atype['GLOBAL_NAME']:
case html4.atype['ID']:
case html4.atype['IDREF']:
if ((op === '=' || op === '~=' || op === '$=')
&& value != '""' && !ignoreCase) {
// The suffix is case-sensitive, so we can't translate case
// ignoring matches.
value = '"'
+ value.substring(1, value.length-1) + idSuffix
+ '"';
} else if (op === '|=' || op === '') {
// Ok. a|=b -> a == b || a.startsWith(b + "-") and since we
// use "-" to separate the suffix from the identifier, we can
// allow this through unmodified.
// Existence checks are also ok.
} else {
// Can't correctly handle prefix and substring operators
// without leaking information about the suffix.
valid = false;
}
break;
case html4.atype['URI']:
case html4.atype['URI_FRAGMENT']:
// URIs are rewritten, so we can't meanginfully translate URI
// selectors besides the common a[href] one that is used to
// distinguish links from naming anchors.
if (op !== '') { valid = false; }
break;
// TODO: IDREFS
default:
valid = false;
}
if (valid) {
attrs += '[' + rAttr.replace(/[^\w-]/g, '\\$&') + op + value +
(ignoreCase ? ' i]' : ']');
}
} else if (start < end && selectors[start] === ':') {
tok = selectors[++start];
if (PSEUDO_SELECTOR_WHITELIST.test(tok)) {
pseudoSelector += ':' + tok;
} else {
break;
}
} else {
break; // Unrecognized token.
}
}
if (start !== end) { // Tokens not consumed.
valid = false;
}
if (valid) {
// ':' is allowed in identifiers, but is also the
// pseudo-selector separator, so ':' in preceding parts needs to
// be escaped.
var selector = (element + classId).replace(/[^ .*#\w-]/g, '\\$&')
+ attrs + pseudoSelector + combinator;
if (selector) { out.push(selector); }
}
return valid;
}
|
Given a series of tokens, returns a list of sanitized selectors.
@param {Array.<string>} selectors In the form produced by csslexer.js.
@param {{
containerClass: ?string,
idSuffix: string,
tagPolicy: function(string, Array.<string>): ?Array.<string>,
virtualizeAttrName: ?function(string, string): ?string
}} virtualization An object like <pre<{
containerClass: class name prepended to all selectors to scope them (if
not null)
idSuffix: appended to all IDs to scope them
tagPolicy: As in html-sanitizer, used for rewriting element names.
virtualizeAttrName: Rewrite a single attribute name for attribute
selectors, or return null if not possible. Should be consistent
with tagPolicy if possible.
}</pre>
If containerClass is {@code "sfx"} and idSuffix is {@code "-sfx"}, the
selector
{@code ["a", "#foo", " ", "b", ".bar"]} will be namespaced to
{@code [".sfx", " ", "a", "#foo-sfx", " ", "b", ".bar"]}.
@param {function(Array.<string>): boolean} opt_onUntranslatableSelector
When a selector cannot be translated, this function is called with the
non-whitespace/comment tokens comprising the selector and returns a
value indicating whether to continue processing the selector list.
If it returns falsey, then processing is aborted and null is returned.
If not present or it returns truthy, then the complex selector is
dropped from the selector list.
@return {Array.<string>}? an array of sanitized selectors.
Null when the untraslatable compound selector handler aborts processing.
|
processCompoundSelector
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function cssParseUri(candidate) {
var string1 = /^\s*["]([^"]*)["]\s*$/;
var string2 = /^\s*[']([^']*)[']\s*$/;
var url1 = /^\s*url\s*[(]["]([^"]*)["][)]\s*$/;
var url2 = /^\s*url\s*[(][']([^']*)['][)]\s*$/;
// Not officially part of the CSS2.1 grammar
// but supported by Chrome
var url3 = /^\s*url\s*[(]([^)]*)[)]\s*$/;
var match;
if ((match = string1.exec(candidate))) {
return match[1];
} else if ((match = string2.exec(candidate))) {
return match[1];
} else if ((match = url1.exec(candidate))) {
return match[1];
} else if ((match = url2.exec(candidate))) {
return match[1];
} else if ((match = url3.exec(candidate))) {
return match[1];
}
return null;
}
|
Extracts a url out of an at-import rule of the form:
\@import "mystyle.css";
\@import url("mystyle.css");
Returns null if no valid url was found.
|
cssParseUri
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function sanitizeStylesheetInternal(
baseUri, cssText, virtualization, naiveUriRewriter, naiveUriFetcher,
continuation, opt_importCount) {
var safeCss = void 0;
// Return a result with moreToCome===true when the last import has been
// sanitized.
var importCount = opt_importCount || [0];
// A stack describing the { ... } regions.
// Null elements indicate blocks that should not be emitted.
var blockStack = [];
// True when the content of the current block should be left off safeCss.
var elide = false;
parseCssStylesheet(
cssText,
{
'startStylesheet': function () {
safeCss = [];
},
'endStylesheet': function () {
},
'startAtrule': function (atIdent, headerArray) {
if (elide) {
atIdent = null;
} else if (atIdent === '@media') {
safeCss.push('@media', ' ', sanitizeMediaQuery(headerArray));
} else if (atIdent === '@keyframes'
|| atIdent === '@-webkit-keyframes') {
var animationId = headerArray[0];
if (headerArray.length === 1
&& !/__$|[^\w\-]/.test(animationId)) {
safeCss.push(
atIdent, ' ', animationId + virtualization.idSuffix);
atIdent = '@keyframes';
} else {
atIdent = null;
}
} else {
if (atIdent === '@import' && headerArray.length > 0) {
atIdent = null;
if ('function' === typeof continuation) {
var mediaQuery = sanitizeMediaQuery(headerArray.slice(1));
if (mediaQuery !== 'not all') {
++importCount[0];
var placeholder = [];
safeCss.push(placeholder);
var cssUrl = safeUri(
resolveUri(baseUri, cssParseUri(headerArray[0])),
function(result) {
var sanitized = sanitizeStylesheetInternal(
cssUrl, result.html, virtualization,
naiveUriRewriter, naiveUriFetcher,
continuation, importCount);
--importCount[0];
var safeImportedCss = mediaQuery
? {
toString: function () {
return (
'@media ' + mediaQuery + ' {'
+ sanitized.result + '}'
);
}
}
: sanitized.result;
placeholder[0] = safeImportedCss;
continuation(safeImportedCss, !!importCount[0]);
},
naiveUriFetcher);
}
} else {
// TODO: Use a logger instead.
if (window.console) {
window.console.log(
'@import ' + headerArray.join(' ') + ' elided');
}
}
}
}
elide = !atIdent;
blockStack.push(atIdent);
},
'endAtrule': function () {
blockStack.pop();
if (!elide) {
safeCss.push(';');
}
checkElide();
},
'startBlock': function () {
// There are no bare blocks in CSS, so we do not change the
// block stack here, but instead in the events that bracket
// blocks.
if (!elide) {
safeCss.push('{');
}
},
'endBlock': function () {
if (!elide) {
safeCss.push('}');
elide = true; // skip any semicolon from endAtRule.
}
},
'startRuleset': function (selectorArray) {
if (!elide) {
var selector = void 0;
if (blockStack[blockStack.length - 1] === '@keyframes') {
// Allow [from | to | <percentage>]
selector = selectorArray.join(' ')
.match(/^ *(?:from|to|\d+(?:\.\d+)?%) *(?:, *(?:from|to|\d+(?:\.\d+)?%) *)*$/i);
elide = !selector;
if (selector) { selector = selector[0].replace(/ +/g, ''); }
} else {
var selectors = sanitizeCssSelectorList(
selectorArray, virtualization);
if (!selectors || !selectors.length) {
elide = true;
} else {
selector = selectors.join(', ');
}
}
if (!elide) {
safeCss.push(selector, '{');
}
}
blockStack.push(null);
},
'endRuleset': function () {
blockStack.pop();
if (!elide) {
safeCss.push('}');
}
checkElide();
},
'declaration': function (property, valueArray) {
if (!elide) {
var isImportant = false;
var nValues = valueArray.length;
if (nValues >= 2
&& valueArray[nValues - 2] === '!'
&& valueArray[nValues - 1].toLowerCase() === 'important') {
isImportant = true;
valueArray.length -= 2;
}
sanitizeCssProperty(
property, valueArray, naiveUriRewriter, baseUri,
virtualization.idSuffix);
if (valueArray.length) {
safeCss.push(
property, ':', valueArray.join(' '),
isImportant ? ' !important;' : ';');
}
}
}
});
function checkElide() {
elide = blockStack.length && blockStack[blockStack.length-1] === null;
}
return {
result : { toString: function () { return safeCss.join(''); } },
moreToCome : !!importCount[0]
};
}
|
@param {string} baseUri a string against which relative urls are
resolved.
@param {string} cssText a string containing a CSS stylesheet.
@param {{
containerClass: ?string,
idSuffix: string,
tagPolicy: function(string, Array.<string>): ?Array.<string>,
virtualizeAttrName: ?function(string, string): ?string
}} virtualization An object like <pre<{
containerClass: class name prepended to all selectors to scope them (if
not null)
idSuffix: appended to all IDs to scope them
tagPolicy: As in html-sanitizer, used for rewriting element names.
virtualizeAttrName: Rewrite a single attribute name for attribute
selectors, or return null if not possible. Should be consistent
with tagPolicy if possible. Optional.
}</pre>
If containerClass is {@code "sfx"} and idSuffix is {@code "-sfx"}, the
selector
{@code ["a", "#foo", " ", "b", ".bar"]} will be namespaced to
{@code [".sfx", " ", "a", "#foo-sfx", " ", "b", ".bar"]}.
@param {function(string, string)} naiveUriRewriter maps URLs of media
(images, sounds) that appear as CSS property values to sanitized
URLs or null if the URL should not be allowed as an external media
file in sanitized CSS.
@param {undefined|function({toString: function ():string}, boolean)}
continuation
callback that receives the result of loading imported CSS.
The callback is called with
(cssContent : function ():string, moreToCome : boolean)
where cssContent is the CSS at the imported URL, and moreToCome is
true when the external URL itself loaded other external URLs.
If the output of the original call is stringified when moreToCome is
false, then it will be complete.
@param {Array.<number>} opt_importCount the number of imports that need
to be satisfied before there is no more pending content.
@return {{result:{toString:function ():string},moreToCome:boolean}}
the CSS text, and a flag that indicates whether there are pending
imports that will be passed to continuation.
|
sanitizeStylesheetInternal
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function checkElide() {
elide = blockStack.length && blockStack[blockStack.length-1] === null;
}
|
@param {string} baseUri a string against which relative urls are
resolved.
@param {string} cssText a string containing a CSS stylesheet.
@param {{
containerClass: ?string,
idSuffix: string,
tagPolicy: function(string, Array.<string>): ?Array.<string>,
virtualizeAttrName: ?function(string, string): ?string
}} virtualization An object like <pre<{
containerClass: class name prepended to all selectors to scope them (if
not null)
idSuffix: appended to all IDs to scope them
tagPolicy: As in html-sanitizer, used for rewriting element names.
virtualizeAttrName: Rewrite a single attribute name for attribute
selectors, or return null if not possible. Should be consistent
with tagPolicy if possible. Optional.
}</pre>
If containerClass is {@code "sfx"} and idSuffix is {@code "-sfx"}, the
selector
{@code ["a", "#foo", " ", "b", ".bar"]} will be namespaced to
{@code [".sfx", " ", "a", "#foo-sfx", " ", "b", ".bar"]}.
@param {function(string, string)} naiveUriRewriter maps URLs of media
(images, sounds) that appear as CSS property values to sanitized
URLs or null if the URL should not be allowed as an external media
file in sanitized CSS.
@param {undefined|function({toString: function ():string}, boolean)}
continuation
callback that receives the result of loading imported CSS.
The callback is called with
(cssContent : function ():string, moreToCome : boolean)
where cssContent is the CSS at the imported URL, and moreToCome is
true when the external URL itself loaded other external URLs.
If the output of the original call is stringified when moreToCome is
false, then it will be complete.
@param {Array.<number>} opt_importCount the number of imports that need
to be satisfied before there is no more pending content.
@return {{result:{toString:function ():string},moreToCome:boolean}}
the CSS text, and a flag that indicates whether there are pending
imports that will be passed to continuation.
|
checkElide
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function statement(toks, i, n, handler) {
if (i < n) {
var tok = toks[i];
if (tok.charAt(0) === '@') {
return atrule(toks, i, n, handler, true);
} else {
return ruleset(toks, i, n, handler);
}
} else {
return i;
}
}
|
parseCssDeclarations parses a run of declaration productions as seen in the
body of the HTML5 {@code style} attribute.
@param {string} cssText CSS3 content to parse as a run of declarations.
@param {Object} handler An object like <pre>{
declaration: function (property, valueArray) { ... },
}</pre>
|
statement
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function atrule(toks, i, n, handler, blockok) {
var start = i++;
while (i < n && toks[i] !== '{' && toks[i] !== ';') {
++i;
}
if (i < n && (blockok || toks[i] === ';')) {
var s = start+1, e = i;
if (s < n && toks[s] === ' ') { ++s; }
if (e > s && toks[e-1] === ' ') { --e; }
if (handler['startAtrule']) {
handler['startAtrule'](toks[start].toLowerCase(), toks.slice(s, e));
}
i = (toks[i] === '{')
? block(toks, i, n, handler)
: i+1; // Skip over ';'
if (handler['endAtrule']) {
handler['endAtrule']();
}
}
// Else we reached end of input or are missing a semicolon.
// Drop the rule on the floor.
return i;
}
|
parseCssDeclarations parses a run of declaration productions as seen in the
body of the HTML5 {@code style} attribute.
@param {string} cssText CSS3 content to parse as a run of declarations.
@param {Object} handler An object like <pre>{
declaration: function (property, valueArray) { ... },
}</pre>
|
atrule
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function block(toks, i, n, handler) {
++i; // skip over '{'
if (handler['startBlock']) { handler['startBlock'](); }
while (i < n) {
var ch = toks[i].charAt(0);
if (ch == '}') {
++i;
break;
}
if (ch === ' ' || ch === ';') {
i = i+1;
} else if (ch === '@') {
i = atrule(toks, i, n, handler, false);
} else if (ch === '{') {
i = block(toks, i, n, handler);
} else {
// Instead of using (any* block) to subsume ruleset we allow either
// blocks or rulesets with a non-blank selector.
// This is more restrictive but does not require atrule specific
// parse tree fixup to realize that the contents of the block in
// @media print { ... }
// is a ruleset. We just don't care about any block carrying at-rules
// whose body content is not ruleset content.
i = ruleset(toks, i, n, handler);
}
}
if (handler['endBlock']) { handler['endBlock'](); }
return i;
}
|
parseCssDeclarations parses a run of declaration productions as seen in the
body of the HTML5 {@code style} attribute.
@param {string} cssText CSS3 content to parse as a run of declarations.
@param {Object} handler An object like <pre>{
declaration: function (property, valueArray) { ... },
}</pre>
|
block
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function ruleset(toks, i, n, handler) {
// toks[s:e] are the selector tokens including internal whitespace.
var s = i, e = selector(toks, i, n, true);
if (e < 0) {
// Skip malformed content per selector calling convention.
e = ~e;
// Make sure we skip at least one token.
return e === s ? e+1 : e;
}
var tok = toks[e];
if (tok !== '{') {
// Make sure we skip at least one token.
return e === s ? e+1 : e;
}
i = e+1; // Skip over '{'
// Don't include any trailing space in the selector slice.
if (e > s && toks[e-1] === ' ') { --e; }
if (handler['startRuleset']) {
handler['startRuleset'](toks.slice(s, e));
}
while (i < n) {
tok = toks[i];
if (tok === '}') {
++i;
break;
}
if (tok === ' ') {
i = i+1;
} else {
i = declaration(toks, i, n, handler);
}
}
if (handler['endRuleset']) {
handler['endRuleset']();
}
return i;
}
|
parseCssDeclarations parses a run of declaration productions as seen in the
body of the HTML5 {@code style} attribute.
@param {string} cssText CSS3 content to parse as a run of declarations.
@param {Object} handler An object like <pre>{
declaration: function (property, valueArray) { ... },
}</pre>
|
ruleset
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function selector(toks, i, n, allowSemi) {
var s = i;
// The definition of any above can be summed up as
// "any run of token except ('[', ']', '(', ')', ':', ';', '{', '}')
// or nested runs of parenthesized tokens or square bracketed tokens".
// Spaces are significant in the selector.
// Selector is used as (selector?) so the below looks for (any*) for
// simplicity.
var tok;
// Keeping a stack pointer actually causes this to minify better since
// ".length" and ".push" are a lo of chars.
var brackets = [], stackLast = -1;
for (;i < n; ++i) {
tok = toks[i].charAt(0);
if (tok === '[' || tok === '(') {
brackets[++stackLast] = tok;
} else if ((tok === ']' && brackets[stackLast] === '[') ||
(tok === ')' && brackets[stackLast] === '(')) {
--stackLast;
} else if (tok === '{' || tok === '}' || tok === ';' || tok === '@'
|| (tok === ':' && !allowSemi)) {
break;
}
}
if (stackLast >= 0) {
// Returns the bitwise inverse of i+1 to indicate an error in the
// token stream so that clients can ignore it.
i = ~(i+1);
}
return i;
}
|
parseCssDeclarations parses a run of declaration productions as seen in the
body of the HTML5 {@code style} attribute.
@param {string} cssText CSS3 content to parse as a run of declarations.
@param {Object} handler An object like <pre>{
declaration: function (property, valueArray) { ... },
}</pre>
|
selector
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function skipDeclaration(toks, i, n) {
// TODO(felix8a): maybe skip balanced pairs of {}
while (i < n && toks[i] !== ';' && toks[i] !== '}') { ++i; }
return i < n && toks[i] === ';' ? i+1 : i;
}
|
parseCssDeclarations parses a run of declaration productions as seen in the
body of the HTML5 {@code style} attribute.
@param {string} cssText CSS3 content to parse as a run of declarations.
@param {Object} handler An object like <pre>{
declaration: function (property, valueArray) { ... },
}</pre>
|
skipDeclaration
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function declaration(toks, i, n, handler) {
var property = toks[i++];
if (!ident.test(property)) {
return skipDeclaration(toks, i, n);
}
var tok;
if (i < n && toks[i] === ' ') { ++i; }
if (i == n || toks[i] !== ':') {
return skipDeclaration(toks, i, n);
}
++i;
if (i < n && toks[i] === ' ') { ++i; }
// None of the rules we care about want atrules or blocks in value, so
// we look for any+ but that is the same as selector but not zero-length.
// This gets us the benefit of not emitting any value with mismatched
// brackets.
var s = i, e = selector(toks, i, n, false);
if (e < 0) {
// Skip malformed content per selector calling convention.
e = ~e;
} else {
var value = [], valuelen = 0;
for (var j = s; j < e; ++j) {
tok = toks[j];
if (tok !== ' ') {
value[valuelen++] = tok;
}
}
// One of the following is now true:
// (1) e is flush with the end of the tokens as in <... style="x:y">.
// (2) tok[e] points to a ';' in which case we need to consume the semi.
// (3) tok[e] points to a '}' in which case we don't consume it.
// (4) else there is bogus unparsed value content at toks[e:].
// Allow declaration flush with end for style attr body.
if (e < n) { // 2, 3, or 4
do {
tok = toks[e];
if (tok === ';' || tok === '}') { break; }
// Don't emit the property if there is questionable trailing content.
valuelen = 0;
} while (++e < n);
if (tok === ';') {
++e;
}
}
if (valuelen && handler['declaration']) {
// TODO: coerce non-keyword ident tokens to quoted strings.
handler['declaration'](property.toLowerCase(), value);
}
}
return e;
}
|
parseCssDeclarations parses a run of declaration productions as seen in the
body of the HTML5 {@code style} attribute.
@param {string} cssText CSS3 content to parse as a run of declarations.
@param {Object} handler An object like <pre>{
declaration: function (property, valueArray) { ... },
}</pre>
|
declaration
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function lookupEntity(name) {
// TODO: entity lookup as specified by HTML5 actually depends on the
// presence of the ";".
if (ENTITIES.hasOwnProperty(name)) { return ENTITIES[name]; }
var m = name.match(decimalEscapeRe);
if (m) {
return String.fromCharCode(parseInt(m[1], 10));
} else if (!!(m = name.match(hexEscapeRe))) {
return String.fromCharCode(parseInt(m[1], 16));
} else if (entityLookupElement && safeEntityNameRe.test(name)) {
entityLookupElement.innerHTML = '&' + name + ';';
var text = entityLookupElement.textContent;
ENTITIES[name] = text;
return text;
} else {
return '&' + name + ';';
}
}
|
Decodes an HTML entity.
{\@updoc
$ lookupEntity('lt')
# '<'
$ lookupEntity('GT')
# '>'
$ lookupEntity('amp')
# '&'
$ lookupEntity('nbsp')
# '\xA0'
$ lookupEntity('apos')
# "'"
$ lookupEntity('quot')
# '"'
$ lookupEntity('#xa')
# '\n'
$ lookupEntity('#10')
# '\n'
$ lookupEntity('#x0a')
# '\n'
$ lookupEntity('#010')
# '\n'
$ lookupEntity('#x00A')
# '\n'
$ lookupEntity('Pi') // Known failure
# '\u03A0'
$ lookupEntity('pi') // Known failure
# '\u03C0'
}
@param {string} name the content between the '&' and the ';'.
@return {string} a single unicode code-point as a string.
|
lookupEntity
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function decodeOneEntity(_, name) {
return lookupEntity(name);
}
|
Decodes an HTML entity.
{\@updoc
$ lookupEntity('lt')
# '<'
$ lookupEntity('GT')
# '>'
$ lookupEntity('amp')
# '&'
$ lookupEntity('nbsp')
# '\xA0'
$ lookupEntity('apos')
# "'"
$ lookupEntity('quot')
# '"'
$ lookupEntity('#xa')
# '\n'
$ lookupEntity('#10')
# '\n'
$ lookupEntity('#x0a')
# '\n'
$ lookupEntity('#010')
# '\n'
$ lookupEntity('#x00A')
# '\n'
$ lookupEntity('Pi') // Known failure
# '\u03A0'
$ lookupEntity('pi') // Known failure
# '\u03C0'
}
@param {string} name the content between the '&' and the ';'.
@return {string} a single unicode code-point as a string.
|
decodeOneEntity
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function stripNULs(s) {
return s.replace(nulRe, '');
}
|
Decodes an HTML entity.
{\@updoc
$ lookupEntity('lt')
# '<'
$ lookupEntity('GT')
# '>'
$ lookupEntity('amp')
# '&'
$ lookupEntity('nbsp')
# '\xA0'
$ lookupEntity('apos')
# "'"
$ lookupEntity('quot')
# '"'
$ lookupEntity('#xa')
# '\n'
$ lookupEntity('#10')
# '\n'
$ lookupEntity('#x0a')
# '\n'
$ lookupEntity('#010')
# '\n'
$ lookupEntity('#x00A')
# '\n'
$ lookupEntity('Pi') // Known failure
# '\u03A0'
$ lookupEntity('pi') // Known failure
# '\u03C0'
}
@param {string} name the content between the '&' and the ';'.
@return {string} a single unicode code-point as a string.
|
stripNULs
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function unescapeEntities(s) {
return s.replace(ENTITY_RE_1, decodeOneEntity);
}
|
The plain text of a chunk of HTML CDATA which possibly containing.
{\@updoc
$ unescapeEntities('')
# ''
$ unescapeEntities('hello World!')
# 'hello World!'
$ unescapeEntities('1 < 2 && 4 > 3 ')
# '1 < 2 && 4 > 3\n'
$ unescapeEntities('<< <- unfinished entity>')
# '<< <- unfinished entity>'
$ unescapeEntities('/foo?bar=baz©=true') // & often unescaped in URLS
# '/foo?bar=baz©=true'
$ unescapeEntities('pi=ππ, Pi=Π\u03A0') // FIXME: known failure
# 'pi=\u03C0\u03c0, Pi=\u03A0\u03A0'
}
@param {string} s a chunk of HTML CDATA. It must not start or end inside
an HTML entity.
|
unescapeEntities
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function escapeAttrib(s) {
return ('' + s).replace(ampRe, '&').replace(ltRe, '<')
.replace(gtRe, '>').replace(quotRe, '"');
}
|
Escapes HTML special characters in attribute values.
{\@updoc
$ escapeAttrib('')
# ''
$ escapeAttrib('"<<&==&>>"') // Do not just escape the first occurrence.
# '"<<&==&>>"'
$ escapeAttrib('Hello <World>!')
# 'Hello <World>!'
}
|
escapeAttrib
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function normalizeRCData(rcdata) {
return rcdata
.replace(looseAmpRe, '&$1')
.replace(ltRe, '<')
.replace(gtRe, '>');
}
|
Escape entities in RCDATA that can be escaped without changing the meaning.
{\@updoc
$ normalizeRCData('1 < 2 && 3 > 4 && 5 < 7&8')
# '1 < 2 && 3 > 4 && 5 < 7&8'
}
|
normalizeRCData
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function makeSaxParser(handler) {
// Accept quoted or unquoted keys (Closure compat)
var hcopy = {
cdata: handler.cdata || handler['cdata'],
comment: handler.comment || handler['comment'],
endDoc: handler.endDoc || handler['endDoc'],
endTag: handler.endTag || handler['endTag'],
pcdata: handler.pcdata || handler['pcdata'],
rcdata: handler.rcdata || handler['rcdata'],
startDoc: handler.startDoc || handler['startDoc'],
startTag: handler.startTag || handler['startTag']
};
return function(htmlText, param) {
return parse(htmlText, hcopy, param);
};
}
|
Given a SAX-like event handler, produce a function that feeds those
events and a parameter to the event handler.
The event handler has the form:{@code
{
// Name is an upper-case HTML tag name. Attribs is an array of
// alternating upper-case attribute names, and attribute values. The
// attribs array is reused by the parser. Param is the value passed to
// the saxParser.
startTag: function (name, attribs, param) { ... },
endTag: function (name, param) { ... },
pcdata: function (text, param) { ... },
rcdata: function (text, param) { ... },
cdata: function (text, param) { ... },
startDoc: function (param) { ... },
endDoc: function (param) { ... }
}}
@param {Object} handler a record containing event handlers.
@return {function(string, Object)} A function that takes a chunk of HTML
and a parameter. The parameter is passed on to the handler methods.
|
makeSaxParser
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function parse(htmlText, handler, param) {
var m, p, tagName;
var parts = htmlSplit(htmlText);
var state = {
noMoreGT: false,
noMoreEndComments: false
};
parseCPS(handler, parts, 0, state, param);
}
|
Given a SAX-like event handler, produce a function that feeds those
events and a parameter to the event handler.
The event handler has the form:{@code
{
// Name is an upper-case HTML tag name. Attribs is an array of
// alternating upper-case attribute names, and attribute values. The
// attribs array is reused by the parser. Param is the value passed to
// the saxParser.
startTag: function (name, attribs, param) { ... },
endTag: function (name, param) { ... },
pcdata: function (text, param) { ... },
rcdata: function (text, param) { ... },
cdata: function (text, param) { ... },
startDoc: function (param) { ... },
endDoc: function (param) { ... }
}}
@param {Object} handler a record containing event handlers.
@return {function(string, Object)} A function that takes a chunk of HTML
and a parameter. The parameter is passed on to the handler methods.
|
parse
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function continuationMaker(h, parts, initial, state, param) {
return function () {
parseCPS(h, parts, initial, state, param);
};
}
|
Given a SAX-like event handler, produce a function that feeds those
events and a parameter to the event handler.
The event handler has the form:{@code
{
// Name is an upper-case HTML tag name. Attribs is an array of
// alternating upper-case attribute names, and attribute values. The
// attribs array is reused by the parser. Param is the value passed to
// the saxParser.
startTag: function (name, attribs, param) { ... },
endTag: function (name, param) { ... },
pcdata: function (text, param) { ... },
rcdata: function (text, param) { ... },
cdata: function (text, param) { ... },
startDoc: function (param) { ... },
endDoc: function (param) { ... }
}}
@param {Object} handler a record containing event handlers.
@return {function(string, Object)} A function that takes a chunk of HTML
and a parameter. The parameter is passed on to the handler methods.
|
continuationMaker
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function parseCPS(h, parts, initial, state, param) {
try {
if (h.startDoc && initial == 0) { h.startDoc(param); }
var m, p, tagName;
for (var pos = initial, end = parts.length; pos < end;) {
var current = parts[pos++];
var next = parts[pos];
switch (current) {
case '&':
if (ENTITY_RE_2.test(next)) {
if (h.pcdata) {
h.pcdata('&' + next, param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
pos++;
} else {
if (h.pcdata) { h.pcdata("&", param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
}
break;
case '<\/':
if ((m = /^([-\w:]+)[^\'\"]*/.exec(next))) {
if (m[0].length === next.length && parts[pos + 1] === '>') {
// fast case, no attribute parsing needed
pos += 2;
tagName = m[1].toLowerCase();
if (h.endTag) {
h.endTag(tagName, param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
} else {
// slow case, need to parse attributes
// TODO(felix8a): do we really care about misparsing this?
pos = parseEndTag(
parts, pos, h, param, continuationMarker, state);
}
} else {
if (h.pcdata) {
h.pcdata('</', param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
}
break;
case '<':
if (m = /^([-\w:]+)\s*\/?/.exec(next)) {
if (m[0].length === next.length && parts[pos + 1] === '>') {
// fast case, no attribute parsing needed
pos += 2;
tagName = m[1].toLowerCase();
if (h.startTag) {
h.startTag(tagName, [], param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
// tags like <script> and <textarea> have special parsing
var eflags = html4.ELEMENTS[tagName];
if (eflags & EFLAGS_TEXT) {
var tag = { name: tagName, next: pos, eflags: eflags };
pos = parseText(
parts, tag, h, param, continuationMarker, state);
}
} else {
// slow case, need to parse attributes
pos = parseStartTag(
parts, pos, h, param, continuationMarker, state);
}
} else {
if (h.pcdata) {
h.pcdata('<', param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
}
break;
case '<\!--':
// The pathological case is n copies of '<\!--' without '-->', and
// repeated failure to find '-->' is quadratic. We avoid that by
// remembering when search for '-->' fails.
if (!state.noMoreEndComments) {
// A comment <\!--x--> is split into three tokens:
// '<\!--', 'x--', '>'
// We want to find the next '>' token that has a preceding '--'.
// pos is at the 'x--'.
for (p = pos + 1; p < end; p++) {
if (parts[p] === '>' && /--$/.test(parts[p - 1])) { break; }
}
if (p < end) {
if (h.comment) {
var comment = parts.slice(pos, p).join('');
h.comment(
comment.substr(0, comment.length - 2), param,
continuationMarker,
continuationMaker(h, parts, p + 1, state, param));
}
pos = p + 1;
} else {
state.noMoreEndComments = true;
}
}
if (state.noMoreEndComments) {
if (h.pcdata) {
h.pcdata('<!--', param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
}
break;
case '<\!':
if (!/^\w/.test(next)) {
if (h.pcdata) {
h.pcdata('<!', param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
} else {
// similar to noMoreEndComment logic
if (!state.noMoreGT) {
for (p = pos + 1; p < end; p++) {
if (parts[p] === '>') { break; }
}
if (p < end) {
pos = p + 1;
} else {
state.noMoreGT = true;
}
}
if (state.noMoreGT) {
if (h.pcdata) {
h.pcdata('<!', param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
}
}
break;
case '<?':
// similar to noMoreEndComment logic
if (!state.noMoreGT) {
for (p = pos + 1; p < end; p++) {
if (parts[p] === '>') { break; }
}
if (p < end) {
pos = p + 1;
} else {
state.noMoreGT = true;
}
}
if (state.noMoreGT) {
if (h.pcdata) {
h.pcdata('<?', param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
}
break;
case '>':
if (h.pcdata) {
h.pcdata(">", param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
break;
case '':
break;
default:
if (h.pcdata) {
h.pcdata(current, param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
break;
}
}
if (h.endDoc) { h.endDoc(param); }
} catch (e) {
if (e !== continuationMarker) { throw e; }
}
}
|
Given a SAX-like event handler, produce a function that feeds those
events and a parameter to the event handler.
The event handler has the form:{@code
{
// Name is an upper-case HTML tag name. Attribs is an array of
// alternating upper-case attribute names, and attribute values. The
// attribs array is reused by the parser. Param is the value passed to
// the saxParser.
startTag: function (name, attribs, param) { ... },
endTag: function (name, param) { ... },
pcdata: function (text, param) { ... },
rcdata: function (text, param) { ... },
cdata: function (text, param) { ... },
startDoc: function (param) { ... },
endDoc: function (param) { ... }
}}
@param {Object} handler a record containing event handlers.
@return {function(string, Object)} A function that takes a chunk of HTML
and a parameter. The parameter is passed on to the handler methods.
|
parseCPS
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function htmlSplit(str) {
// can't hoist this out of the function because of the re.exec loop.
var re = /(<\/|<\!--|<[!?]|[&<>])/g;
str += '';
if (splitWillCapture) {
return str.split(re);
} else {
var parts = [];
var lastPos = 0;
var m;
while ((m = re.exec(str)) !== null) {
parts.push(str.substring(lastPos, m.index));
parts.push(m[0]);
lastPos = m.index + m[0].length;
}
parts.push(str.substring(lastPos));
return parts;
}
}
|
Given a SAX-like event handler, produce a function that feeds those
events and a parameter to the event handler.
The event handler has the form:{@code
{
// Name is an upper-case HTML tag name. Attribs is an array of
// alternating upper-case attribute names, and attribute values. The
// attribs array is reused by the parser. Param is the value passed to
// the saxParser.
startTag: function (name, attribs, param) { ... },
endTag: function (name, param) { ... },
pcdata: function (text, param) { ... },
rcdata: function (text, param) { ... },
cdata: function (text, param) { ... },
startDoc: function (param) { ... },
endDoc: function (param) { ... }
}}
@param {Object} handler a record containing event handlers.
@return {function(string, Object)} A function that takes a chunk of HTML
and a parameter. The parameter is passed on to the handler methods.
|
htmlSplit
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function parseEndTag(parts, pos, h, param, continuationMarker, state) {
var tag = parseTagAndAttrs(parts, pos);
// drop unclosed tags
if (!tag) { return parts.length; }
if (h.endTag) {
h.endTag(tag.name, param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
return tag.next;
}
|
Given a SAX-like event handler, produce a function that feeds those
events and a parameter to the event handler.
The event handler has the form:{@code
{
// Name is an upper-case HTML tag name. Attribs is an array of
// alternating upper-case attribute names, and attribute values. The
// attribs array is reused by the parser. Param is the value passed to
// the saxParser.
startTag: function (name, attribs, param) { ... },
endTag: function (name, param) { ... },
pcdata: function (text, param) { ... },
rcdata: function (text, param) { ... },
cdata: function (text, param) { ... },
startDoc: function (param) { ... },
endDoc: function (param) { ... }
}}
@param {Object} handler a record containing event handlers.
@return {function(string, Object)} A function that takes a chunk of HTML
and a parameter. The parameter is passed on to the handler methods.
|
parseEndTag
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function parseStartTag(parts, pos, h, param, continuationMarker, state) {
var tag = parseTagAndAttrs(parts, pos);
// drop unclosed tags
if (!tag) { return parts.length; }
if (h.startTag) {
h.startTag(tag.name, tag.attrs, param, continuationMarker,
continuationMaker(h, parts, tag.next, state, param));
}
// tags like <script> and <textarea> have special parsing
if (tag.eflags & EFLAGS_TEXT) {
return parseText(parts, tag, h, param, continuationMarker, state);
} else {
return tag.next;
}
}
|
Given a SAX-like event handler, produce a function that feeds those
events and a parameter to the event handler.
The event handler has the form:{@code
{
// Name is an upper-case HTML tag name. Attribs is an array of
// alternating upper-case attribute names, and attribute values. The
// attribs array is reused by the parser. Param is the value passed to
// the saxParser.
startTag: function (name, attribs, param) { ... },
endTag: function (name, param) { ... },
pcdata: function (text, param) { ... },
rcdata: function (text, param) { ... },
cdata: function (text, param) { ... },
startDoc: function (param) { ... },
endDoc: function (param) { ... }
}}
@param {Object} handler a record containing event handlers.
@return {function(string, Object)} A function that takes a chunk of HTML
and a parameter. The parameter is passed on to the handler methods.
|
parseStartTag
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function parseText(parts, tag, h, param, continuationMarker, state) {
var end = parts.length;
if (!endTagRe.hasOwnProperty(tag.name)) {
endTagRe[tag.name] = new RegExp('^' + tag.name + '(?:[\\s\\/]|$)', 'i');
}
var re = endTagRe[tag.name];
var first = tag.next;
var p = tag.next + 1;
for (; p < end; p++) {
if (parts[p - 1] === '<\/' && re.test(parts[p])) { break; }
}
if (p < end) { p -= 1; }
var buf = parts.slice(first, p).join('');
if (tag.eflags & html4.eflags['CDATA']) {
if (h.cdata) {
h.cdata(buf, param, continuationMarker,
continuationMaker(h, parts, p, state, param));
}
} else if (tag.eflags & html4.eflags['RCDATA']) {
if (h.rcdata) {
h.rcdata(normalizeRCData(buf), param, continuationMarker,
continuationMaker(h, parts, p, state, param));
}
} else {
throw new Error('bug');
}
return p;
}
|
Given a SAX-like event handler, produce a function that feeds those
events and a parameter to the event handler.
The event handler has the form:{@code
{
// Name is an upper-case HTML tag name. Attribs is an array of
// alternating upper-case attribute names, and attribute values. The
// attribs array is reused by the parser. Param is the value passed to
// the saxParser.
startTag: function (name, attribs, param) { ... },
endTag: function (name, param) { ... },
pcdata: function (text, param) { ... },
rcdata: function (text, param) { ... },
cdata: function (text, param) { ... },
startDoc: function (param) { ... },
endDoc: function (param) { ... }
}}
@param {Object} handler a record containing event handlers.
@return {function(string, Object)} A function that takes a chunk of HTML
and a parameter. The parameter is passed on to the handler methods.
|
parseText
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function parseTagAndAttrs(parts, pos) {
var m = /^([-\w:]+)/.exec(parts[pos]);
var tag = {};
tag.name = m[1].toLowerCase();
tag.eflags = html4.ELEMENTS[tag.name];
var buf = parts[pos].substr(m[0].length);
// Find the next '>'. We optimistically assume this '>' is not in a
// quoted context, and further down we fix things up if it turns out to
// be quoted.
var p = pos + 1;
var end = parts.length;
for (; p < end; p++) {
if (parts[p] === '>') { break; }
buf += parts[p];
}
if (end <= p) { return void 0; }
var attrs = [];
while (buf !== '') {
m = ATTR_RE.exec(buf);
if (!m) {
// No attribute found: skip garbage
buf = buf.replace(/^[\s\S][^a-z\s]*/, '');
} else if ((m[4] && !m[5]) || (m[6] && !m[7])) {
// Unterminated quote: slurp to the next unquoted '>'
var quote = m[4] || m[6];
var sawQuote = false;
var abuf = [buf, parts[p++]];
for (; p < end; p++) {
if (sawQuote) {
if (parts[p] === '>') { break; }
} else if (0 <= parts[p].indexOf(quote)) {
sawQuote = true;
}
abuf.push(parts[p]);
}
// Slurp failed: lose the garbage
if (end <= p) { break; }
// Otherwise retry attribute parsing
buf = abuf.join('');
continue;
} else {
// We have an attribute
var aName = m[1].toLowerCase();
var aValue = m[2] ? decodeValue(m[3]) : '';
attrs.push(aName, aValue);
buf = buf.substr(m[0].length);
}
}
tag.attrs = attrs;
tag.next = p + 1;
return tag;
}
|
Given a SAX-like event handler, produce a function that feeds those
events and a parameter to the event handler.
The event handler has the form:{@code
{
// Name is an upper-case HTML tag name. Attribs is an array of
// alternating upper-case attribute names, and attribute values. The
// attribs array is reused by the parser. Param is the value passed to
// the saxParser.
startTag: function (name, attribs, param) { ... },
endTag: function (name, param) { ... },
pcdata: function (text, param) { ... },
rcdata: function (text, param) { ... },
cdata: function (text, param) { ... },
startDoc: function (param) { ... },
endDoc: function (param) { ... }
}}
@param {Object} handler a record containing event handlers.
@return {function(string, Object)} A function that takes a chunk of HTML
and a parameter. The parameter is passed on to the handler methods.
|
parseTagAndAttrs
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function decodeValue(v) {
var q = v.charCodeAt(0);
if (q === 0x22 || q === 0x27) { // " or '
v = v.substr(1, v.length - 2);
}
return unescapeEntities(stripNULs(v));
}
|
Given a SAX-like event handler, produce a function that feeds those
events and a parameter to the event handler.
The event handler has the form:{@code
{
// Name is an upper-case HTML tag name. Attribs is an array of
// alternating upper-case attribute names, and attribute values. The
// attribs array is reused by the parser. Param is the value passed to
// the saxParser.
startTag: function (name, attribs, param) { ... },
endTag: function (name, param) { ... },
pcdata: function (text, param) { ... },
rcdata: function (text, param) { ... },
cdata: function (text, param) { ... },
startDoc: function (param) { ... },
endDoc: function (param) { ... }
}}
@param {Object} handler a record containing event handlers.
@return {function(string, Object)} A function that takes a chunk of HTML
and a parameter. The parameter is passed on to the handler methods.
|
decodeValue
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function makeHtmlSanitizer(tagPolicy) {
var stack;
var ignoring;
var emit = function (text, out) {
if (!ignoring) { out.push(text); }
};
return makeSaxParser({
'startDoc': function(_) {
stack = [];
ignoring = false;
},
'startTag': function(tagNameOrig, attribs, out) {
if (ignoring) { return; }
if (!html4.ELEMENTS.hasOwnProperty(tagNameOrig)) { return; }
var eflagsOrig = html4.ELEMENTS[tagNameOrig];
if (eflagsOrig & html4.eflags['FOLDABLE']) {
return;
}
var decision = tagPolicy(tagNameOrig, attribs);
if (!decision) {
ignoring = !(eflagsOrig & html4.eflags['EMPTY']);
return;
} else if (typeof decision !== 'object') {
throw new Error('tagPolicy did not return object (old API?)');
}
if ('attribs' in decision) {
attribs = decision['attribs'];
} else {
throw new Error('tagPolicy gave no attribs');
}
var eflagsRep;
var tagNameRep;
if ('tagName' in decision) {
tagNameRep = decision['tagName'];
eflagsRep = html4.ELEMENTS[tagNameRep];
} else {
tagNameRep = tagNameOrig;
eflagsRep = eflagsOrig;
}
// TODO(mikesamuel): relying on tagPolicy not to insert unsafe
// attribute names.
// If this is an optional-end-tag element and either this element or its
// previous like sibling was rewritten, then insert a close tag to
// preserve structure.
if (eflagsOrig & html4.eflags['OPTIONAL_ENDTAG']) {
var onStack = stack[stack.length - 1];
if (onStack && onStack.orig === tagNameOrig &&
(onStack.rep !== tagNameRep || tagNameOrig !== tagNameRep)) {
out.push('<\/', onStack.rep, '>');
}
}
if (!(eflagsOrig & html4.eflags['EMPTY'])) {
stack.push({orig: tagNameOrig, rep: tagNameRep});
}
out.push('<', tagNameRep);
for (var i = 0, n = attribs.length; i < n; i += 2) {
var attribName = attribs[i],
value = attribs[i + 1];
if (value !== null && value !== void 0) {
out.push(' ', attribName, '="', escapeAttrib(value), '"');
}
}
out.push('>');
if ((eflagsOrig & html4.eflags['EMPTY'])
&& !(eflagsRep & html4.eflags['EMPTY'])) {
// replacement is non-empty, synthesize end tag
out.push('<\/', tagNameRep, '>');
}
},
'endTag': function(tagName, out) {
if (ignoring) {
ignoring = false;
return;
}
if (!html4.ELEMENTS.hasOwnProperty(tagName)) { return; }
var eflags = html4.ELEMENTS[tagName];
if (!(eflags & (html4.eflags['EMPTY'] | html4.eflags['FOLDABLE']))) {
var index;
if (eflags & html4.eflags['OPTIONAL_ENDTAG']) {
for (index = stack.length; --index >= 0;) {
var stackElOrigTag = stack[index].orig;
if (stackElOrigTag === tagName) { break; }
if (!(html4.ELEMENTS[stackElOrigTag] &
html4.eflags['OPTIONAL_ENDTAG'])) {
// Don't pop non optional end tags looking for a match.
return;
}
}
} else {
for (index = stack.length; --index >= 0;) {
if (stack[index].orig === tagName) { break; }
}
}
if (index < 0) { return; } // Not opened.
for (var i = stack.length; --i > index;) {
var stackElRepTag = stack[i].rep;
if (!(html4.ELEMENTS[stackElRepTag] &
html4.eflags['OPTIONAL_ENDTAG'])) {
out.push('<\/', stackElRepTag, '>');
}
}
if (index < stack.length) {
tagName = stack[index].rep;
}
stack.length = index;
out.push('<\/', tagName, '>');
}
},
'pcdata': emit,
'rcdata': emit,
'cdata': emit,
'endDoc': function(out) {
for (; stack.length; stack.length--) {
out.push('<\/', stack[stack.length - 1].rep, '>');
}
}
});
}
|
Returns a function that strips unsafe tags and attributes from html.
@param {function(string, Array.<string>): ?Array.<string>} tagPolicy
A function that takes (tagName, attribs[]), where tagName is a key in
html4.ELEMENTS and attribs is an array of alternating attribute names
and values. It should return a record (as follows), or null to delete
the element. It's okay for tagPolicy to modify the attribs array,
but the same array is reused, so it should not be held between calls.
Record keys:
attribs: (required) Sanitized attributes array.
tagName: Replacement tag name.
@return {function(string, Array)} A function that sanitizes a string of
HTML and appends result strings to the second argument, an array.
|
makeHtmlSanitizer
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
emit = function (text, out) {
if (!ignoring) { out.push(text); }
}
|
Returns a function that strips unsafe tags and attributes from html.
@param {function(string, Array.<string>): ?Array.<string>} tagPolicy
A function that takes (tagName, attribs[]), where tagName is a key in
html4.ELEMENTS and attribs is an array of alternating attribute names
and values. It should return a record (as follows), or null to delete
the element. It's okay for tagPolicy to modify the attribs array,
but the same array is reused, so it should not be held between calls.
Record keys:
attribs: (required) Sanitized attributes array.
tagName: Replacement tag name.
@return {function(string, Array)} A function that sanitizes a string of
HTML and appends result strings to the second argument, an array.
|
emit
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function safeUri(uri, effect, ltype, hints, naiveUriRewriter) {
if (!naiveUriRewriter) { return null; }
try {
var parsed = URI.parse('' + uri);
if (parsed) {
if (!parsed.hasScheme() ||
ALLOWED_URI_SCHEMES.test(parsed.getScheme())) {
var safe = naiveUriRewriter(parsed, effect, ltype, hints);
return safe ? safe.toString() : null;
}
}
} catch (e) {
return null;
}
return null;
}
|
Returns a function that strips unsafe tags and attributes from html.
@param {function(string, Array.<string>): ?Array.<string>} tagPolicy
A function that takes (tagName, attribs[]), where tagName is a key in
html4.ELEMENTS and attribs is an array of alternating attribute names
and values. It should return a record (as follows), or null to delete
the element. It's okay for tagPolicy to modify the attribs array,
but the same array is reused, so it should not be held between calls.
Record keys:
attribs: (required) Sanitized attributes array.
tagName: Replacement tag name.
@return {function(string, Array)} A function that sanitizes a string of
HTML and appends result strings to the second argument, an array.
|
safeUri
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function log(logger, tagName, attribName, oldValue, newValue) {
if (!attribName) {
logger(tagName + " removed", {
change: "removed",
tagName: tagName
});
}
if (oldValue !== newValue) {
var changed = "changed";
if (oldValue && !newValue) {
changed = "removed";
} else if (!oldValue && newValue) {
changed = "added";
}
logger(tagName + "." + attribName + " " + changed, {
change: changed,
tagName: tagName,
attribName: attribName,
oldValue: oldValue,
newValue: newValue
});
}
}
|
Returns a function that strips unsafe tags and attributes from html.
@param {function(string, Array.<string>): ?Array.<string>} tagPolicy
A function that takes (tagName, attribs[]), where tagName is a key in
html4.ELEMENTS and attribs is an array of alternating attribute names
and values. It should return a record (as follows), or null to delete
the element. It's okay for tagPolicy to modify the attribs array,
but the same array is reused, so it should not be held between calls.
Record keys:
attribs: (required) Sanitized attributes array.
tagName: Replacement tag name.
@return {function(string, Array)} A function that sanitizes a string of
HTML and appends result strings to the second argument, an array.
|
log
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function lookupAttribute(map, tagName, attribName) {
var attribKey;
attribKey = tagName + '::' + attribName;
if (map.hasOwnProperty(attribKey)) {
return map[attribKey];
}
attribKey = '*::' + attribName;
if (map.hasOwnProperty(attribKey)) {
return map[attribKey];
}
return void 0;
}
|
Returns a function that strips unsafe tags and attributes from html.
@param {function(string, Array.<string>): ?Array.<string>} tagPolicy
A function that takes (tagName, attribs[]), where tagName is a key in
html4.ELEMENTS and attribs is an array of alternating attribute names
and values. It should return a record (as follows), or null to delete
the element. It's okay for tagPolicy to modify the attribs array,
but the same array is reused, so it should not be held between calls.
Record keys:
attribs: (required) Sanitized attributes array.
tagName: Replacement tag name.
@return {function(string, Array)} A function that sanitizes a string of
HTML and appends result strings to the second argument, an array.
|
lookupAttribute
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function getAttributeType(tagName, attribName) {
return lookupAttribute(html4.ATTRIBS, tagName, attribName);
}
|
Returns a function that strips unsafe tags and attributes from html.
@param {function(string, Array.<string>): ?Array.<string>} tagPolicy
A function that takes (tagName, attribs[]), where tagName is a key in
html4.ELEMENTS and attribs is an array of alternating attribute names
and values. It should return a record (as follows), or null to delete
the element. It's okay for tagPolicy to modify the attribs array,
but the same array is reused, so it should not be held between calls.
Record keys:
attribs: (required) Sanitized attributes array.
tagName: Replacement tag name.
@return {function(string, Array)} A function that sanitizes a string of
HTML and appends result strings to the second argument, an array.
|
getAttributeType
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function getLoaderType(tagName, attribName) {
return lookupAttribute(html4.LOADERTYPES, tagName, attribName);
}
|
Returns a function that strips unsafe tags and attributes from html.
@param {function(string, Array.<string>): ?Array.<string>} tagPolicy
A function that takes (tagName, attribs[]), where tagName is a key in
html4.ELEMENTS and attribs is an array of alternating attribute names
and values. It should return a record (as follows), or null to delete
the element. It's okay for tagPolicy to modify the attribs array,
but the same array is reused, so it should not be held between calls.
Record keys:
attribs: (required) Sanitized attributes array.
tagName: Replacement tag name.
@return {function(string, Array)} A function that sanitizes a string of
HTML and appends result strings to the second argument, an array.
|
getLoaderType
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function getUriEffect(tagName, attribName) {
return lookupAttribute(html4.URIEFFECTS, tagName, attribName);
}
|
Returns a function that strips unsafe tags and attributes from html.
@param {function(string, Array.<string>): ?Array.<string>} tagPolicy
A function that takes (tagName, attribs[]), where tagName is a key in
html4.ELEMENTS and attribs is an array of alternating attribute names
and values. It should return a record (as follows), or null to delete
the element. It's okay for tagPolicy to modify the attribs array,
but the same array is reused, so it should not be held between calls.
Record keys:
attribs: (required) Sanitized attributes array.
tagName: Replacement tag name.
@return {function(string, Array)} A function that sanitizes a string of
HTML and appends result strings to the second argument, an array.
|
getUriEffect
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function sanitizeWithPolicy(inputHtml, tagPolicy) {
var outputArray = [];
makeHtmlSanitizer(tagPolicy)(inputHtml, outputArray);
return outputArray.join('');
}
|
Sanitizes HTML tags and attributes according to a given policy.
@param {string} inputHtml The HTML to sanitize.
@param {function(string, Array.<?string>)} tagPolicy A function that
decides which tags to accept and sanitizes their attributes (see
makeHtmlSanitizer above for details).
@return {string} The sanitized HTML.
|
sanitizeWithPolicy
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function sanitize(inputHtml,
opt_naiveUriRewriter, opt_nmTokenPolicy, opt_logger) {
var tagPolicy = makeTagPolicy(
opt_naiveUriRewriter, opt_nmTokenPolicy, opt_logger);
return sanitizeWithPolicy(inputHtml, tagPolicy);
}
|
Strips unsafe tags and attributes from HTML.
@param {string} inputHtml The HTML to sanitize.
@param {?function(?string): ?string} opt_naiveUriRewriter A transform to
apply to URI attributes. If not given, URI attributes are deleted.
@param {function(?string): ?string} opt_nmTokenPolicy A transform to apply
to attributes containing HTML names, element IDs, and space-separated
lists of classes. If not given, such attributes are left unchanged.
|
sanitize
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
next = function() {
var script = document.createElement('script');
script.src = prefix + cdb.files[c];
document.body.appendChild(script);
++c;
if(c == cdb.files.length) {
if(ready) {
script.onload = ready;
}
} else {
script.onload = next;
}
}
|
load all the javascript files. For testing, do not use in production
|
next
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
superMethod = function(method, options) {
var result = null;
if (this.parent != null) {
var currentParent = this.parent;
// we need to change the parent of "this", because
// since we are going to call the elder (super) method
// in the context of "this", if the super method has
// another call to elder (super), we need to provide a way of
// redirecting to the grandparent
this.parent = this.parent.parent;
var options = Array.prototype.slice.call(arguments, 1);
if (currentParent.hasOwnProperty(method)) {
result = currentParent[method].apply(this, options);
} else {
options.splice(0,0, method);
result = currentParent.elder.apply(this, options);
}
this.parent = currentParent;
}
return result;
}
|
Adds .elder method to call for the same method of the parent class
usage:
insanceOfClass.elder('name_of_the_method');
|
superMethod
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
extend = function(protoProps, classProps) {
var child = backboneExtend.call(this, protoProps, classProps);
child.prototype.parent = this.prototype;
child.prototype.elder = function(method) {
var options = Array.prototype.slice.call(arguments, 1);
if (method) {
options.splice(0,0, method)
return superMethod.apply(this, options);
} else {
return child.prototype.parent;
}
}
return child;
}
|
Adds .elder method to call for the same method of the parent class
usage:
insanceOfClass.elder('name_of_the_method');
|
extend
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
decorate = function(objectToDecorate) {
objectToDecorate.extend = extend;
objectToDecorate.prototype.elder = function() {};
objectToDecorate.prototype.parent = null;
}
|
Adds .elder method to call for the same method of the parent class
usage:
insanceOfClass.elder('name_of_the_method');
|
decorate
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function Metric(name) {
this.t0 = null;
this.name = name;
this.count = 0;
}
|
contains all error for the application
|
Metric
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function detectIE() {
var msie = ua.indexOf('MSIE ');
var trident = ua.indexOf('Trident/');
if (msie > -1 || trident > -1) return true;
return false;
}
|
search for views in a view and check if they are added as subviews
|
detectIE
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function getIEVersion(){
if (!document.compatMode) return 5
if (!window.XMLHttpRequest) return 6
if (!document.querySelector) return 7;
if (!document.addEventListener) return 8;
if (!window.atob) return 9;
if (document.all) return 10;
else return 11;
}
|
search for views in a view and check if they are added as subviews
|
getIEVersion
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
|
View to know which is the map zoom.
Usage:
var zoomInfo = new cdb.geo.ui.ZoomInfo({ model: map });
mapWrapper.$el.append(zoomInfo.render().$el);
|
componentToHex
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function SubLayerBase(_parent, position) {
this._parent = _parent;
this._position = position;
this._added = true;
}
|
FullScreen widget:
var widget = new cdb.ui.common.FullScreen({
doc: ".container", // optional; if not specified, we do the fullscreen of the whole window
template: this.getTemplate("table/views/fullscreen")
});
|
SubLayerBase
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
_bindSignal = function(signal, signalAlias) {
signalAlias = signalAlias || signal;
self._parent.on(signal, function() {
var args = Array.prototype.slice.call(arguments);
if (parseInt(args[args.length - 1], 10) == self._position) {
self.trigger.apply(self, [signalAlias].concat(args));
}
}, self);
}
|
FullScreen widget:
var widget = new cdb.ui.common.FullScreen({
doc: ".container", // optional; if not specified, we do the fullscreen of the whole window
template: this.getTemplate("table/views/fullscreen")
});
|
_bindSignal
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function CartoDBSubLayer(layer, position) {
SubLayerBase.call(this, layer, position);
this._bindInteraction();
var layer = this._parent.getLayer(this._position);
// TODO: Test this
if (Backbone.Model && layer) {
this.infowindow = new Backbone.Model(layer.infowindow);
this.infowindow.bind('change', function() {
layer.infowindow = this.infowindow.toJSON();
this._parent.setLayer(this._position, layer);
}, this);
}
}
|
FullScreen widget:
var widget = new cdb.ui.common.FullScreen({
doc: ".container", // optional; if not specified, we do the fullscreen of the whole window
template: this.getTemplate("table/views/fullscreen")
});
|
CartoDBSubLayer
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function HttpSubLayer(layer, position) {
SubLayerBase.call(this, layer, position);
}
|
FullScreen widget:
var widget = new cdb.ui.common.FullScreen({
doc: ".container", // optional; if not specified, we do the fullscreen of the whole window
template: this.getTemplate("table/views/fullscreen")
});
|
HttpSubLayer
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function MapProperties(mapProperties) {
this.mapProperties = mapProperties;
}
|
Wrapper for map properties returned by the tiler
|
MapProperties
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function MapBase(options) {
var self = this;
this.options = _.defaults(options, {
ajax: window.$ ? window.$.ajax : reqwest.compat,
pngParams: ['map_key', 'api_key', 'cache_policy', 'updated_at'],
gridParams: ['map_key', 'api_key', 'cache_policy', 'updated_at'],
cors: cdb.core.util.isCORSSupported(),
MAX_GET_SIZE: 2033,
force_cors: false,
instanciateCallback: function() {
return '_cdbc_' + self._callbackName();
}
});
this.mapProperties = null;
this.urls = null;
this.silent = false;
this.interactionEnabled = []; //TODO: refactor, include inside layer
this._timeout = -1;
this._createMapCallsStack = [];
this._createMapCallbacks = [];
this._waiting = false;
this.lastTimeUpdated = null;
this._refreshTimer = -1;
// build template url
if (!this.options.maps_api_template) {
this._buildMapsApiTemplate(this.options);
}
}
|
Returns the index of a layer of a given type, as the tiler kwows it.
@param {string|array} types - Type or types of layers
|
MapBase
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function invokeStackedCallbacks(data, err) {
var fn;
while(fn = self._createMapCallbacks.pop()) {
fn(data, err);
}
}
|
Returns the index of a layer of a given type, as the tiler kwows it.
@param {string|array} types - Type or types of layers
|
invokeStackedCallbacks
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function LayerDefinition(layerDefinition, options) {
MapBase.call(this, options);
this.endPoint = MapBase.BASE_URL;
this.setLayerDefinition(layerDefinition, { silent: true });
}
|
return the layer number by index taking into
account the hidden layers.
|
LayerDefinition
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function NamedMap(named_map, options) {
MapBase.call(this, options);
this.options.pngParams.push('auth_token')
this.options.gridParams.push('auth_token')
this.setLayerDefinition(named_map, options)
this.stat_tag = named_map.stat_tag;
}
|
adds a new sublayer to the layer with the sql and cartocss params
|
NamedMap
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function CartoDBLayerCommon() {
this.visible = true;
}
|
adds a new sublayer to the layer with the sql and cartocss params
|
CartoDBLayerCommon
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
LeafLetLayerView = function(layerModel, leafletLayer, leafletMap) {
this.leafletLayer = leafletLayer;
this.leafletMap = leafletMap;
this.model = layerModel;
this.setModel(layerModel);
this.type = layerModel.get('type') || layerModel.get('kind');
this.type = this.type.toLowerCase();
}
|
base layer for all leaflet layers
|
LeafLetLayerView
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
stamenSubstitute = function stamenSubstitute(type) {
return {
url: 'http://{s}.basemaps.cartocdn.com/'+ type +'_all/{z}/{x}/{y}.png',
subdomains: 'abcd',
minZoom: 0,
maxZoom: 18,
attribution: 'Map designs by <a href="http://stamen.com/">Stamen</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, Provided by <a href="https://carto.com">CARTO</a>'
};
}
|
this is a dummy layer class that modifies the leaflet DOM element background
instead of creating a layer with div
|
stamenSubstitute
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
finish = function(e) {
var s = this.tileStats && this.tileStats[e.tile.src];
s && s.end();
}
|
this is a dummy layer class that modifies the leaflet DOM element background
instead of creating a layer with div
|
finish
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function layerView(base) {
var layerViewClass = base.extend({
includes: [
cdb.geo.LeafLetLayerView.prototype,
Backbone.Events
],
initialize: function(layerModel, leafletMap) {
var self = this;
var hovers = [];
var opts = _.clone(layerModel.attributes);
opts.map = leafletMap;
var // preserve the user's callbacks
_featureOver = opts.featureOver,
_featureOut = opts.featureOut,
_featureClick = opts.featureClick;
var previousEvent;
var eventTimeout = -1;
opts.featureOver = function(e, latlon, pxPos, data, layer) {
if (!hovers[layer]) {
self.trigger('layerenter', e, latlon, pxPos, data, layer);
}
hovers[layer] = 1;
_featureOver && _featureOver.apply(this, arguments);
self.featureOver && self.featureOver.apply(self, arguments);
// if the event is the same than before just cancel the event
// firing because there is a layer on top of it
if (e.timeStamp === previousEvent) {
clearTimeout(eventTimeout);
}
eventTimeout = setTimeout(function() {
self.trigger('mouseover', e, latlon, pxPos, data, layer);
self.trigger('layermouseover', e, latlon, pxPos, data, layer);
}, 0);
previousEvent = e.timeStamp;
};
opts.featureOut = function(m, layer) {
if (hovers[layer]) {
self.trigger('layermouseout', layer);
}
hovers[layer] = 0;
if(!_.any(hovers)) {
self.trigger('mouseout');
}
_featureOut && _featureOut.apply(this, arguments);
self.featureOut && self.featureOut.apply(self, arguments);
};
opts.featureClick = _.debounce(function() {
_featureClick && _featureClick.apply(self, arguments);
self.featureClick && self.featureClick.apply(self, arguments);
}, 10);
base.prototype.initialize.call(this, opts);
cdb.geo.LeafLetLayerView.call(this, layerModel, this, leafletMap);
},
featureOver: function(e, latlon, pixelPos, data, layer) {
// dont pass leaflet lat/lon
this.trigger('featureOver', e, [latlon.lat, latlon.lng], pixelPos, data, layer);
},
featureOut: function(e, layer) {
this.trigger('featureOut', e, layer);
},
featureClick: function(e, latlon, pixelPos, data, layer) {
// dont pass leaflet lat/lon
this.trigger('featureClick', e, [latlon.lat, latlon.lng], pixelPos, data, layer);
},
error: function(e) {
this.trigger('error', e ? (e.errors || e) : 'unknown error');
this.model.trigger('error', e?e.errors:'unknown error');
},
ok: function(e) {
this.model.trigger('tileOk');
},
onLayerDefinitionUpdated: function() {
this.__update();
}
});
return layerViewClass;
}
|
Creates an instance of a Leaflet Point
|
layerView
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
function PathView(geometryModel) {
var self = this;
// events to link
var events = [
'click',
'dblclick',
'mousedown',
'mouseover',
'mouseout',
];
this._eventHandlers = {};
this.model = geometryModel;
this.points = [];
this.geom = L.GeoJSON.geometryToLayer(geometryModel.get('geojson'));
this.geom.setStyle(geometryModel.get('style'));
/*for(var i = 0; i < events.length; ++i) {
var e = events[i];
this.geom.on(e, self._eventHandler(e));
}*/
}
|
view for other geometries (polygons/lines)
|
PathView
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
GMapsLayerView = function(layerModel, gmapsLayer, gmapsMap) {
this.gmapsLayer = gmapsLayer;
this.map = this.gmapsMap = gmapsMap;
this.model = layerModel;
this.model.bind('change', this._update, this);
this.type = layerModel.get('type') || layerModel.get('kind');
this.type = this.type.toLowerCase();
}
|
base layer for all google maps
|
GMapsLayerView
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
GMapsBaseLayerView = function(layerModel, gmapsMap) {
cdb.geo.GMapsLayerView.call(this, layerModel, null, gmapsMap);
}
|
remove layer from the map and unbind events
|
GMapsBaseLayerView
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
GMapsPlainLayerView = function(layerModel, gmapsMap) {
this.color = layerModel.get('color')
cdb.geo.GMapsLayerView.call(this, layerModel, this, gmapsMap);
}
|
remove layer from the map and unbind events
|
GMapsPlainLayerView
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
GMapsTiledLayerView = function(layerModel, gmapsMap) {
cdb.geo.GMapsLayerView.call(this, layerModel, this, gmapsMap);
this.tileSize = new google.maps.Size(256, 256);
this.opacity = 1.0;
this.isPng = true;
this.maxZoom = 22;
this.minZoom = 0;
this.name= 'cartodb tiled layer';
google.maps.ImageMapType.call(this, this);
}
|
remove layer from the map and unbind events
|
GMapsTiledLayerView
|
javascript
|
CartoDB/cartodb
|
vendor/assets/javascripts/cartodb.uncompressed.js
|
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/cartodb.uncompressed.js
|
BSD-3-Clause
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.