id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
|---|---|---|---|---|---|---|---|---|---|---|---|
16,600
|
camptocamp/ngeo
|
src/grid/component.js
|
isPlatformModifierKeyOnly
|
function isPlatformModifierKeyOnly(event) {
return !event.altKey &&
(olHas.MAC ? event.metaKey : event.ctrlKey) &&
!event.shiftKey;
}
|
javascript
|
function isPlatformModifierKeyOnly(event) {
return !event.altKey &&
(olHas.MAC ? event.metaKey : event.ctrlKey) &&
!event.shiftKey;
}
|
[
"function",
"isPlatformModifierKeyOnly",
"(",
"event",
")",
"{",
"return",
"!",
"event",
".",
"altKey",
"&&",
"(",
"olHas",
".",
"MAC",
"?",
"event",
".",
"metaKey",
":",
"event",
".",
"ctrlKey",
")",
"&&",
"!",
"event",
".",
"shiftKey",
";",
"}"
] |
Same as `ol.events.condition.platformModifierKeyOnly`.
@param {JQueryEventObject} event Event.
@return {boolean} True if only the platform modifier key is pressed.
@private
|
[
"Same",
"as",
"ol",
".",
"events",
".",
"condition",
".",
"platformModifierKeyOnly",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/grid/component.js#L292-L296
|
16,601
|
camptocamp/ngeo
|
src/grid/component.js
|
isShiftKeyOnly
|
function isShiftKeyOnly(event) {
return (
!event.altKey &&
!(event.metaKey || event.ctrlKey) &&
event.shiftKey);
}
|
javascript
|
function isShiftKeyOnly(event) {
return (
!event.altKey &&
!(event.metaKey || event.ctrlKey) &&
event.shiftKey);
}
|
[
"function",
"isShiftKeyOnly",
"(",
"event",
")",
"{",
"return",
"(",
"!",
"event",
".",
"altKey",
"&&",
"!",
"(",
"event",
".",
"metaKey",
"||",
"event",
".",
"ctrlKey",
")",
"&&",
"event",
".",
"shiftKey",
")",
";",
"}"
] |
Same as `ol.events.condition.shiftKeyOnly`.
@param {JQueryEventObject} event Event.
@return {boolean} True if only the shift key is pressed.
@private
|
[
"Same",
"as",
"ol",
".",
"events",
".",
"condition",
".",
"shiftKeyOnly",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/grid/component.js#L305-L310
|
16,602
|
camptocamp/ngeo
|
src/message/popoverComponent.js
|
messagePopoverComponent
|
function messagePopoverComponent() {
return {
restrict: 'A',
scope: true,
controller: 'NgeoPopoverController as popoverCtrl',
link: (scope, elem, attrs, ngeoPopoverCtrl) => {
if (!ngeoPopoverCtrl) {
throw new Error('Missing ngeoPopoverCtrl');
}
ngeoPopoverCtrl.anchorElm.on('inserted.bs.popover', () => {
ngeoPopoverCtrl.bodyElm.show();
ngeoPopoverCtrl.shown = true;
});
ngeoPopoverCtrl.anchorElm.popover({
container: 'body',
html: true,
content: ngeoPopoverCtrl.bodyElm,
boundary: 'viewport',
placement: attrs['ngeoPopoverPlacement'] || 'right'
});
if (attrs['ngeoPopoverDismiss']) {
$(attrs['ngeoPopoverDismiss']).on('scroll', () => {
ngeoPopoverCtrl.dismissPopover();
});
}
scope.$on('$destroy', () => {
ngeoPopoverCtrl.anchorElm.popover('dispose');
ngeoPopoverCtrl.anchorElm.unbind('inserted.bs.popover');
ngeoPopoverCtrl.anchorElm.unbind('hidden.bs.popover');
});
}
};
}
|
javascript
|
function messagePopoverComponent() {
return {
restrict: 'A',
scope: true,
controller: 'NgeoPopoverController as popoverCtrl',
link: (scope, elem, attrs, ngeoPopoverCtrl) => {
if (!ngeoPopoverCtrl) {
throw new Error('Missing ngeoPopoverCtrl');
}
ngeoPopoverCtrl.anchorElm.on('inserted.bs.popover', () => {
ngeoPopoverCtrl.bodyElm.show();
ngeoPopoverCtrl.shown = true;
});
ngeoPopoverCtrl.anchorElm.popover({
container: 'body',
html: true,
content: ngeoPopoverCtrl.bodyElm,
boundary: 'viewport',
placement: attrs['ngeoPopoverPlacement'] || 'right'
});
if (attrs['ngeoPopoverDismiss']) {
$(attrs['ngeoPopoverDismiss']).on('scroll', () => {
ngeoPopoverCtrl.dismissPopover();
});
}
scope.$on('$destroy', () => {
ngeoPopoverCtrl.anchorElm.popover('dispose');
ngeoPopoverCtrl.anchorElm.unbind('inserted.bs.popover');
ngeoPopoverCtrl.anchorElm.unbind('hidden.bs.popover');
});
}
};
}
|
[
"function",
"messagePopoverComponent",
"(",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"scope",
":",
"true",
",",
"controller",
":",
"'NgeoPopoverController as popoverCtrl'",
",",
"link",
":",
"(",
"scope",
",",
"elem",
",",
"attrs",
",",
"ngeoPopoverCtrl",
")",
"=>",
"{",
"if",
"(",
"!",
"ngeoPopoverCtrl",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing ngeoPopoverCtrl'",
")",
";",
"}",
"ngeoPopoverCtrl",
".",
"anchorElm",
".",
"on",
"(",
"'inserted.bs.popover'",
",",
"(",
")",
"=>",
"{",
"ngeoPopoverCtrl",
".",
"bodyElm",
".",
"show",
"(",
")",
";",
"ngeoPopoverCtrl",
".",
"shown",
"=",
"true",
";",
"}",
")",
";",
"ngeoPopoverCtrl",
".",
"anchorElm",
".",
"popover",
"(",
"{",
"container",
":",
"'body'",
",",
"html",
":",
"true",
",",
"content",
":",
"ngeoPopoverCtrl",
".",
"bodyElm",
",",
"boundary",
":",
"'viewport'",
",",
"placement",
":",
"attrs",
"[",
"'ngeoPopoverPlacement'",
"]",
"||",
"'right'",
"}",
")",
";",
"if",
"(",
"attrs",
"[",
"'ngeoPopoverDismiss'",
"]",
")",
"{",
"$",
"(",
"attrs",
"[",
"'ngeoPopoverDismiss'",
"]",
")",
".",
"on",
"(",
"'scroll'",
",",
"(",
")",
"=>",
"{",
"ngeoPopoverCtrl",
".",
"dismissPopover",
"(",
")",
";",
"}",
")",
";",
"}",
"scope",
".",
"$on",
"(",
"'$destroy'",
",",
"(",
")",
"=>",
"{",
"ngeoPopoverCtrl",
".",
"anchorElm",
".",
"popover",
"(",
"'dispose'",
")",
";",
"ngeoPopoverCtrl",
".",
"anchorElm",
".",
"unbind",
"(",
"'inserted.bs.popover'",
")",
";",
"ngeoPopoverCtrl",
".",
"anchorElm",
".",
"unbind",
"(",
"'hidden.bs.popover'",
")",
";",
"}",
")",
";",
"}",
"}",
";",
"}"
] |
Provides a directive used to display a Bootstrap popover.
<div ngeo-popover>
<a ngeo-popover-anchor class="btn btn-info">anchor 1</a>
<div ngeo-popover-body>
<ul>
<li>action 1:
<input type="range"/>
</li>
</ul>
</div>
</div>
@ngdoc directive
@ngInject
@ngname ngeoPopover
@return {angular.IDirective} The Directive Definition Object.
|
[
"Provides",
"a",
"directive",
"used",
"to",
"display",
"a",
"Bootstrap",
"popover",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/message/popoverComponent.js#L32-L68
|
16,603
|
camptocamp/ngeo
|
src/message/popoverComponent.js
|
PopoverController
|
function PopoverController($scope) {
/**
* The state of the popover (displayed or not)
* @type {boolean}
*/
this.shown = false;
/**
* @type {?JQuery}
*/
this.anchorElm = null;
/**
* @type {?JQuery}
*/
this.bodyElm = null;
const clickHandler = (clickEvent) => {
if (!this.anchorElm) {
throw new Error('Missing anchorElm');
}
if (!this.bodyElm) {
throw new Error('Missing bodyElm');
}
if (this.anchorElm[0] !== clickEvent.target &&
this.bodyElm.parent()[0] !== clickEvent.target &&
this.bodyElm.parent().find(clickEvent.target).length === 0 && this.shown) {
this.dismissPopover();
}
};
document.body.addEventListener('click', clickHandler);
$scope.$on('$destroy', () => {
document.body.removeEventListener('click', clickHandler);
});
}
|
javascript
|
function PopoverController($scope) {
/**
* The state of the popover (displayed or not)
* @type {boolean}
*/
this.shown = false;
/**
* @type {?JQuery}
*/
this.anchorElm = null;
/**
* @type {?JQuery}
*/
this.bodyElm = null;
const clickHandler = (clickEvent) => {
if (!this.anchorElm) {
throw new Error('Missing anchorElm');
}
if (!this.bodyElm) {
throw new Error('Missing bodyElm');
}
if (this.anchorElm[0] !== clickEvent.target &&
this.bodyElm.parent()[0] !== clickEvent.target &&
this.bodyElm.parent().find(clickEvent.target).length === 0 && this.shown) {
this.dismissPopover();
}
};
document.body.addEventListener('click', clickHandler);
$scope.$on('$destroy', () => {
document.body.removeEventListener('click', clickHandler);
});
}
|
[
"function",
"PopoverController",
"(",
"$scope",
")",
"{",
"/**\n * The state of the popover (displayed or not)\n * @type {boolean}\n */",
"this",
".",
"shown",
"=",
"false",
";",
"/**\n * @type {?JQuery}\n */",
"this",
".",
"anchorElm",
"=",
"null",
";",
"/**\n * @type {?JQuery}\n */",
"this",
".",
"bodyElm",
"=",
"null",
";",
"const",
"clickHandler",
"=",
"(",
"clickEvent",
")",
"=>",
"{",
"if",
"(",
"!",
"this",
".",
"anchorElm",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing anchorElm'",
")",
";",
"}",
"if",
"(",
"!",
"this",
".",
"bodyElm",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing bodyElm'",
")",
";",
"}",
"if",
"(",
"this",
".",
"anchorElm",
"[",
"0",
"]",
"!==",
"clickEvent",
".",
"target",
"&&",
"this",
".",
"bodyElm",
".",
"parent",
"(",
")",
"[",
"0",
"]",
"!==",
"clickEvent",
".",
"target",
"&&",
"this",
".",
"bodyElm",
".",
"parent",
"(",
")",
".",
"find",
"(",
"clickEvent",
".",
"target",
")",
".",
"length",
"===",
"0",
"&&",
"this",
".",
"shown",
")",
"{",
"this",
".",
"dismissPopover",
"(",
")",
";",
"}",
"}",
";",
"document",
".",
"body",
".",
"addEventListener",
"(",
"'click'",
",",
"clickHandler",
")",
";",
"$scope",
".",
"$on",
"(",
"'$destroy'",
",",
"(",
")",
"=>",
"{",
"document",
".",
"body",
".",
"removeEventListener",
"(",
"'click'",
",",
"clickHandler",
")",
";",
"}",
")",
";",
"}"
] |
The controller for the 'popover' directive.
@constructor
@ngInject
@ngdoc controller
@ngname NgeoPopoverController
@param {angular.IScope} $scope Scope.
@private
@hidden
|
[
"The",
"controller",
"for",
"the",
"popover",
"directive",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/message/popoverComponent.js#L119-L155
|
16,604
|
camptocamp/ngeo
|
src/format/FeatureHash.js
|
encodeNumber_
|
function encodeNumber_(num) {
let encodedNumber = '';
while (num >= 0x20) {
encodedNumber += CHAR64_.charAt(
0x20 | (num & 0x1f));
num >>= 5;
}
encodedNumber += CHAR64_.charAt(num);
return encodedNumber;
}
|
javascript
|
function encodeNumber_(num) {
let encodedNumber = '';
while (num >= 0x20) {
encodedNumber += CHAR64_.charAt(
0x20 | (num & 0x1f));
num >>= 5;
}
encodedNumber += CHAR64_.charAt(num);
return encodedNumber;
}
|
[
"function",
"encodeNumber_",
"(",
"num",
")",
"{",
"let",
"encodedNumber",
"=",
"''",
";",
"while",
"(",
"num",
">=",
"0x20",
")",
"{",
"encodedNumber",
"+=",
"CHAR64_",
".",
"charAt",
"(",
"0x20",
"|",
"(",
"num",
"&",
"0x1f",
")",
")",
";",
"num",
">>=",
"5",
";",
"}",
"encodedNumber",
"+=",
"CHAR64_",
".",
"charAt",
"(",
"num",
")",
";",
"return",
"encodedNumber",
";",
"}"
] |
Transform a number into a logical sequence of characters.
@param {number} num Number.
@return {string} String.
@private
@hidden
|
[
"Transform",
"a",
"number",
"into",
"a",
"logical",
"sequence",
"of",
"characters",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/format/FeatureHash.js#L521-L530
|
16,605
|
camptocamp/ngeo
|
src/format/FeatureHash.js
|
setStyleProperties_
|
function setStyleProperties_(text, feature) {
const properties = getStyleProperties_(text, feature);
const geometry = feature.getGeometry();
// Deal with legacy properties
if (geometry instanceof olGeomPoint) {
if (properties.isLabel ||
properties[ngeoFormatFeatureProperties.IS_TEXT]) {
delete properties.strokeColor;
delete properties.fillColor;
} else {
delete properties.fontColor;
delete properties.fontSize;
}
} else {
delete properties.fontColor;
if (geometry instanceof olGeomLineString) {
delete properties.fillColor;
delete properties.fillOpacity;
}
}
// Convert font size from px to pt
if (properties.fontSize) {
const fontSizeStr = /** @type {string} */(properties.fontSize);
/** @type {number} */
let fontSize = parseFloat(fontSizeStr);
if (fontSizeStr.indexOf('px') !== -1) {
fontSize = Math.round(fontSize / 1.333333);
}
properties.fontSize = fontSize;
}
// Convert legacy properties
const clone = {};
for (const key in properties) {
const value = properties[key];
if (LegacyProperties_[key]) {
clone[LegacyProperties_[key]] = value;
} else {
clone[key] = value;
}
}
feature.setProperties(clone);
}
|
javascript
|
function setStyleProperties_(text, feature) {
const properties = getStyleProperties_(text, feature);
const geometry = feature.getGeometry();
// Deal with legacy properties
if (geometry instanceof olGeomPoint) {
if (properties.isLabel ||
properties[ngeoFormatFeatureProperties.IS_TEXT]) {
delete properties.strokeColor;
delete properties.fillColor;
} else {
delete properties.fontColor;
delete properties.fontSize;
}
} else {
delete properties.fontColor;
if (geometry instanceof olGeomLineString) {
delete properties.fillColor;
delete properties.fillOpacity;
}
}
// Convert font size from px to pt
if (properties.fontSize) {
const fontSizeStr = /** @type {string} */(properties.fontSize);
/** @type {number} */
let fontSize = parseFloat(fontSizeStr);
if (fontSizeStr.indexOf('px') !== -1) {
fontSize = Math.round(fontSize / 1.333333);
}
properties.fontSize = fontSize;
}
// Convert legacy properties
const clone = {};
for (const key in properties) {
const value = properties[key];
if (LegacyProperties_[key]) {
clone[LegacyProperties_[key]] = value;
} else {
clone[key] = value;
}
}
feature.setProperties(clone);
}
|
[
"function",
"setStyleProperties_",
"(",
"text",
",",
"feature",
")",
"{",
"const",
"properties",
"=",
"getStyleProperties_",
"(",
"text",
",",
"feature",
")",
";",
"const",
"geometry",
"=",
"feature",
".",
"getGeometry",
"(",
")",
";",
"// Deal with legacy properties",
"if",
"(",
"geometry",
"instanceof",
"olGeomPoint",
")",
"{",
"if",
"(",
"properties",
".",
"isLabel",
"||",
"properties",
"[",
"ngeoFormatFeatureProperties",
".",
"IS_TEXT",
"]",
")",
"{",
"delete",
"properties",
".",
"strokeColor",
";",
"delete",
"properties",
".",
"fillColor",
";",
"}",
"else",
"{",
"delete",
"properties",
".",
"fontColor",
";",
"delete",
"properties",
".",
"fontSize",
";",
"}",
"}",
"else",
"{",
"delete",
"properties",
".",
"fontColor",
";",
"if",
"(",
"geometry",
"instanceof",
"olGeomLineString",
")",
"{",
"delete",
"properties",
".",
"fillColor",
";",
"delete",
"properties",
".",
"fillOpacity",
";",
"}",
"}",
"// Convert font size from px to pt",
"if",
"(",
"properties",
".",
"fontSize",
")",
"{",
"const",
"fontSizeStr",
"=",
"/** @type {string} */",
"(",
"properties",
".",
"fontSize",
")",
";",
"/** @type {number} */",
"let",
"fontSize",
"=",
"parseFloat",
"(",
"fontSizeStr",
")",
";",
"if",
"(",
"fontSizeStr",
".",
"indexOf",
"(",
"'px'",
")",
"!==",
"-",
"1",
")",
"{",
"fontSize",
"=",
"Math",
".",
"round",
"(",
"fontSize",
"/",
"1.333333",
")",
";",
"}",
"properties",
".",
"fontSize",
"=",
"fontSize",
";",
"}",
"// Convert legacy properties",
"const",
"clone",
"=",
"{",
"}",
";",
"for",
"(",
"const",
"key",
"in",
"properties",
")",
"{",
"const",
"value",
"=",
"properties",
"[",
"key",
"]",
";",
"if",
"(",
"LegacyProperties_",
"[",
"key",
"]",
")",
"{",
"clone",
"[",
"LegacyProperties_",
"[",
"key",
"]",
"]",
"=",
"value",
";",
"}",
"else",
"{",
"clone",
"[",
"key",
"]",
"=",
"value",
";",
"}",
"}",
"feature",
".",
"setProperties",
"(",
"clone",
")",
";",
"}"
] |
Read a logical sequence of characters and apply the decoded result as
style properties for the feature. Legacy keys are converted to the new ones
for compatibility.
@param {string} text Text.
@param {import("ol/Feature.js").default} feature Feature.
@private
@hidden
|
[
"Read",
"a",
"logical",
"sequence",
"of",
"characters",
"and",
"apply",
"the",
"decoded",
"result",
"as",
"style",
"properties",
"for",
"the",
"feature",
".",
"Legacy",
"keys",
"are",
"converted",
"to",
"the",
"new",
"ones",
"for",
"compatibility",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/format/FeatureHash.js#L940-L987
|
16,606
|
camptocamp/ngeo
|
src/format/FeatureHash.js
|
castValue_
|
function castValue_(key, value) {
const numProperties = [
ngeoFormatFeatureProperties.ANGLE,
ngeoFormatFeatureProperties.OPACITY,
ngeoFormatFeatureProperties.SIZE,
ngeoFormatFeatureProperties.STROKE,
'pointRadius',
'strokeWidth'
];
const boolProperties = [
ngeoFormatFeatureProperties.IS_CIRCLE,
ngeoFormatFeatureProperties.IS_RECTANGLE,
ngeoFormatFeatureProperties.IS_TEXT,
ngeoFormatFeatureProperties.SHOW_MEASURE,
ngeoFormatFeatureProperties.SHOW_LABEL,
'isCircle',
'isRectangle',
'isLabel',
'showMeasure',
'showLabel'
];
if (numProperties.includes(key)) {
return +value;
} else if (boolProperties.includes(key)) {
return (value === 'true') ? true : false;
} else {
return value;
}
}
|
javascript
|
function castValue_(key, value) {
const numProperties = [
ngeoFormatFeatureProperties.ANGLE,
ngeoFormatFeatureProperties.OPACITY,
ngeoFormatFeatureProperties.SIZE,
ngeoFormatFeatureProperties.STROKE,
'pointRadius',
'strokeWidth'
];
const boolProperties = [
ngeoFormatFeatureProperties.IS_CIRCLE,
ngeoFormatFeatureProperties.IS_RECTANGLE,
ngeoFormatFeatureProperties.IS_TEXT,
ngeoFormatFeatureProperties.SHOW_MEASURE,
ngeoFormatFeatureProperties.SHOW_LABEL,
'isCircle',
'isRectangle',
'isLabel',
'showMeasure',
'showLabel'
];
if (numProperties.includes(key)) {
return +value;
} else if (boolProperties.includes(key)) {
return (value === 'true') ? true : false;
} else {
return value;
}
}
|
[
"function",
"castValue_",
"(",
"key",
",",
"value",
")",
"{",
"const",
"numProperties",
"=",
"[",
"ngeoFormatFeatureProperties",
".",
"ANGLE",
",",
"ngeoFormatFeatureProperties",
".",
"OPACITY",
",",
"ngeoFormatFeatureProperties",
".",
"SIZE",
",",
"ngeoFormatFeatureProperties",
".",
"STROKE",
",",
"'pointRadius'",
",",
"'strokeWidth'",
"]",
";",
"const",
"boolProperties",
"=",
"[",
"ngeoFormatFeatureProperties",
".",
"IS_CIRCLE",
",",
"ngeoFormatFeatureProperties",
".",
"IS_RECTANGLE",
",",
"ngeoFormatFeatureProperties",
".",
"IS_TEXT",
",",
"ngeoFormatFeatureProperties",
".",
"SHOW_MEASURE",
",",
"ngeoFormatFeatureProperties",
".",
"SHOW_LABEL",
",",
"'isCircle'",
",",
"'isRectangle'",
",",
"'isLabel'",
",",
"'showMeasure'",
",",
"'showLabel'",
"]",
";",
"if",
"(",
"numProperties",
".",
"includes",
"(",
"key",
")",
")",
"{",
"return",
"+",
"value",
";",
"}",
"else",
"if",
"(",
"boolProperties",
".",
"includes",
"(",
"key",
")",
")",
"{",
"return",
"(",
"value",
"===",
"'true'",
")",
"?",
"true",
":",
"false",
";",
"}",
"else",
"{",
"return",
"value",
";",
"}",
"}"
] |
Cast values in the correct type depending on the property.
@param {string} key Key.
@param {string} value Value.
@return {number|boolean|string} The casted value corresponding to the key.
@private
@hidden
@hidden
|
[
"Cast",
"values",
"in",
"the",
"correct",
"type",
"depending",
"on",
"the",
"property",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/format/FeatureHash.js#L998-L1027
|
16,607
|
camptocamp/ngeo
|
src/format/FeatureHash.js
|
getStyleProperties_
|
function getStyleProperties_(text, feature) {
const parts = text.split('\'');
/** @type {Object<string, boolean|number|string>} */
const properties = {};
for (let i = 0; i < parts.length; ++i) {
const part = decodeURIComponent(parts[i]);
const keyVal = part.split('*');
console.assert(keyVal.length === 2);
const key = keyVal[0];
const val = keyVal[1];
properties[key] = castValue_(key, val);
}
return properties;
}
|
javascript
|
function getStyleProperties_(text, feature) {
const parts = text.split('\'');
/** @type {Object<string, boolean|number|string>} */
const properties = {};
for (let i = 0; i < parts.length; ++i) {
const part = decodeURIComponent(parts[i]);
const keyVal = part.split('*');
console.assert(keyVal.length === 2);
const key = keyVal[0];
const val = keyVal[1];
properties[key] = castValue_(key, val);
}
return properties;
}
|
[
"function",
"getStyleProperties_",
"(",
"text",
",",
"feature",
")",
"{",
"const",
"parts",
"=",
"text",
".",
"split",
"(",
"'\\''",
")",
";",
"/** @type {Object<string, boolean|number|string>} */",
"const",
"properties",
"=",
"{",
"}",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"parts",
".",
"length",
";",
"++",
"i",
")",
"{",
"const",
"part",
"=",
"decodeURIComponent",
"(",
"parts",
"[",
"i",
"]",
")",
";",
"const",
"keyVal",
"=",
"part",
".",
"split",
"(",
"'*'",
")",
";",
"console",
".",
"assert",
"(",
"keyVal",
".",
"length",
"===",
"2",
")",
";",
"const",
"key",
"=",
"keyVal",
"[",
"0",
"]",
";",
"const",
"val",
"=",
"keyVal",
"[",
"1",
"]",
";",
"properties",
"[",
"key",
"]",
"=",
"castValue_",
"(",
"key",
",",
"val",
")",
";",
"}",
"return",
"properties",
";",
"}"
] |
From a logical sequence of characters, create and return an object of
style properties for a feature. The values are cast in the correct type
depending on the property. Some properties are also deleted when they don't
match the geometry of the feature.
@param {string} text Text.
@param {import("ol/Feature.js").default} feature Feature.
@return {Object<string, boolean|number|string|undefined>} The style properties for the feature.
@private
@hidden
|
[
"From",
"a",
"logical",
"sequence",
"of",
"characters",
"create",
"and",
"return",
"an",
"object",
"of",
"style",
"properties",
"for",
"a",
"feature",
".",
"The",
"values",
"are",
"cast",
"in",
"the",
"correct",
"type",
"depending",
"on",
"the",
"property",
".",
"Some",
"properties",
"are",
"also",
"deleted",
"when",
"they",
"don",
"t",
"match",
"the",
"geometry",
"of",
"the",
"feature",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/format/FeatureHash.js#L1040-L1056
|
16,608
|
camptocamp/ngeo
|
contribs/gmf/src/mobile/measure/lengthComponent.js
|
mobileMeasureLenthComponent
|
function mobileMeasureLenthComponent(gmfMobileMeasureLengthTemplateUrl) {
return {
restrict: 'A',
scope: {
'active': '=gmfMobileMeasurelengthActive',
'precision': '<?gmfMobileMeasurelengthPrecision',
'map': '=gmfMobileMeasurelengthMap',
'sketchStyle': '=?gmfMobileMeasurelengthSketchstyle'
},
controller: 'GmfMobileMeasureLengthController as ctrl',
bindToController: true,
templateUrl: gmfMobileMeasureLengthTemplateUrl,
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
* @param {angular.IController=} controller Controller.
*/
link: (scope, element, attrs, controller) => {
if (!controller) {
throw new Error('Missing controller');
}
controller.init();
}
};
}
|
javascript
|
function mobileMeasureLenthComponent(gmfMobileMeasureLengthTemplateUrl) {
return {
restrict: 'A',
scope: {
'active': '=gmfMobileMeasurelengthActive',
'precision': '<?gmfMobileMeasurelengthPrecision',
'map': '=gmfMobileMeasurelengthMap',
'sketchStyle': '=?gmfMobileMeasurelengthSketchstyle'
},
controller: 'GmfMobileMeasureLengthController as ctrl',
bindToController: true,
templateUrl: gmfMobileMeasureLengthTemplateUrl,
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
* @param {angular.IController=} controller Controller.
*/
link: (scope, element, attrs, controller) => {
if (!controller) {
throw new Error('Missing controller');
}
controller.init();
}
};
}
|
[
"function",
"mobileMeasureLenthComponent",
"(",
"gmfMobileMeasureLengthTemplateUrl",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"scope",
":",
"{",
"'active'",
":",
"'=gmfMobileMeasurelengthActive'",
",",
"'precision'",
":",
"'<?gmfMobileMeasurelengthPrecision'",
",",
"'map'",
":",
"'=gmfMobileMeasurelengthMap'",
",",
"'sketchStyle'",
":",
"'=?gmfMobileMeasurelengthSketchstyle'",
"}",
",",
"controller",
":",
"'GmfMobileMeasureLengthController as ctrl'",
",",
"bindToController",
":",
"true",
",",
"templateUrl",
":",
"gmfMobileMeasureLengthTemplateUrl",
",",
"/**\n * @param {angular.IScope} scope Scope.\n * @param {JQuery} element Element.\n * @param {angular.IAttributes} attrs Attributes.\n * @param {angular.IController=} controller Controller.\n */",
"link",
":",
"(",
"scope",
",",
"element",
",",
"attrs",
",",
"controller",
")",
"=>",
"{",
"if",
"(",
"!",
"controller",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing controller'",
")",
";",
"}",
"controller",
".",
"init",
"(",
")",
";",
"}",
"}",
";",
"}"
] |
Provide a directive to do a length measure on the mobile devices.
Example:
<div gmf-mobile-measurelength
gmf-mobile-measurelength-active="ctrl.measureLengthActive"
gmf-mobile-measurelength-map="::ctrl.map">
</div>
@htmlAttribute {boolean} gmf-mobile-measurelength-active Used to active
or deactivate the component.
@htmlAttribute {number=} gmf-mobile-measurelength-precision the number of significant digits to display.
@htmlAttribute {import("ol/Map.js").default} gmf-mobile-measurelength-map The map.
@htmlAttribute {import("ol/style/Style.js").StyleLike=}
gmf-mobile-measurelength-sketchstyle A style for the measure length.
@param {string|function(!JQuery=, !angular.IAttributes=):string}
gmfMobileMeasureLengthTemplateUrl Template URL for the directive.
@return {angular.IDirective} The Directive Definition Object.
@ngInject
@ngdoc directive
@ngname gmfMobileMeasureLength
|
[
"Provide",
"a",
"directive",
"to",
"do",
"a",
"length",
"measure",
"on",
"the",
"mobile",
"devices",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/contribs/gmf/src/mobile/measure/lengthComponent.js#L57-L82
|
16,609
|
camptocamp/ngeo
|
contribs/gmf/src/contextualdata/component.js
|
contextualDataComponent
|
function contextualDataComponent() {
return {
restrict: 'A',
scope: false,
controller: 'GmfContextualdataController as cdCtrl',
bindToController: {
'map': '<gmfContextualdataMap',
'projections': '<gmfContextualdataProjections',
'callback': '<gmfContextualdataCallback'
},
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
* @param {angular.IController=} controller Controller.
*/
link: (scope, element, attrs, controller) => {
if (!controller) {
throw new Error('Missing controller');
}
controller.init();
}
};
}
|
javascript
|
function contextualDataComponent() {
return {
restrict: 'A',
scope: false,
controller: 'GmfContextualdataController as cdCtrl',
bindToController: {
'map': '<gmfContextualdataMap',
'projections': '<gmfContextualdataProjections',
'callback': '<gmfContextualdataCallback'
},
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
* @param {angular.IController=} controller Controller.
*/
link: (scope, element, attrs, controller) => {
if (!controller) {
throw new Error('Missing controller');
}
controller.init();
}
};
}
|
[
"function",
"contextualDataComponent",
"(",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"scope",
":",
"false",
",",
"controller",
":",
"'GmfContextualdataController as cdCtrl'",
",",
"bindToController",
":",
"{",
"'map'",
":",
"'<gmfContextualdataMap'",
",",
"'projections'",
":",
"'<gmfContextualdataProjections'",
",",
"'callback'",
":",
"'<gmfContextualdataCallback'",
"}",
",",
"/**\n * @param {angular.IScope} scope Scope.\n * @param {JQuery} element Element.\n * @param {angular.IAttributes} attrs Attributes.\n * @param {angular.IController=} controller Controller.\n */",
"link",
":",
"(",
"scope",
",",
"element",
",",
"attrs",
",",
"controller",
")",
"=>",
"{",
"if",
"(",
"!",
"controller",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing controller'",
")",
";",
"}",
"controller",
".",
"init",
"(",
")",
";",
"}",
"}",
";",
"}"
] |
Provide a directive responsible of displaying contextual data after a right
click on the map.
This directive doesn't require being rendered in a visible DOM element.
It's usually added to the element where the map directive is also added.
Example:
<gmf-map gmf-map-map="mainCtrl.map"
gmf-contextualdata
gmf-contextualdata-map="::mainCtrl.map"
gmf-contextualdata-projections="::[21781,4326]">
The content of the popover is managed in a partial that must be defined
using the `gmfContextualdatacontentTemplateUrl` value. See
{@link import("gmf/contextualdatacontentDirective.js").default} for more details.
One can also provide a `gmf-contextualdata-callback` attribute in order to
do some additional computing on the coordinate or the values received for
the raster service. The callback function is called with the coordinate of
the clicked point and the response data from the server. It is intended to
return an object of additional properties to add to the scope.
See the [../examples/contribs/gmf/contextualdata.html](../examples/contribs/gmf/contextualdata.html)
example for a usage sample.
@htmlAttribute {import("ol/Map.js").default} map The map.
@htmlAttribute {Array<number>} projections The list of projections.
@htmlAttribute {Function} callback A function called after server
(raster) data is received in case some additional computing is required.
Optional.
@return {angular.IDirective} The directive specs.
@ngdoc directive
@ngname gmfContextualdata
|
[
"Provide",
"a",
"directive",
"responsible",
"of",
"displaying",
"contextual",
"data",
"after",
"a",
"right",
"click",
"on",
"the",
"map",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/contribs/gmf/src/contextualdata/component.js#L51-L74
|
16,610
|
camptocamp/ngeo
|
src/message/popupComponent.js
|
messagePopopComponent
|
function messagePopopComponent(ngeoPopupTemplateUrl) {
return {
restrict: 'A',
templateUrl: ngeoPopupTemplateUrl,
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
*/
link: (scope, element, attrs) => {
element.addClass('popover');
/**
* @param {JQueryEventObject} evt Event.
*/
scope['close'] = function(evt) {
if (evt) {
evt.stopPropagation();
evt.preventDefault();
}
element.addClass('hidden');
};
// Watch the open property
scope.$watch('open', (newVal, oldVal) => {
element.css('display', newVal ? 'block' : 'none');
});
}
};
}
|
javascript
|
function messagePopopComponent(ngeoPopupTemplateUrl) {
return {
restrict: 'A',
templateUrl: ngeoPopupTemplateUrl,
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
*/
link: (scope, element, attrs) => {
element.addClass('popover');
/**
* @param {JQueryEventObject} evt Event.
*/
scope['close'] = function(evt) {
if (evt) {
evt.stopPropagation();
evt.preventDefault();
}
element.addClass('hidden');
};
// Watch the open property
scope.$watch('open', (newVal, oldVal) => {
element.css('display', newVal ? 'block' : 'none');
});
}
};
}
|
[
"function",
"messagePopopComponent",
"(",
"ngeoPopupTemplateUrl",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"templateUrl",
":",
"ngeoPopupTemplateUrl",
",",
"/**\n * @param {angular.IScope} scope Scope.\n * @param {JQuery} element Element.\n * @param {angular.IAttributes} attrs Attributes.\n */",
"link",
":",
"(",
"scope",
",",
"element",
",",
"attrs",
")",
"=>",
"{",
"element",
".",
"addClass",
"(",
"'popover'",
")",
";",
"/**\n * @param {JQueryEventObject} evt Event.\n */",
"scope",
"[",
"'close'",
"]",
"=",
"function",
"(",
"evt",
")",
"{",
"if",
"(",
"evt",
")",
"{",
"evt",
".",
"stopPropagation",
"(",
")",
";",
"evt",
".",
"preventDefault",
"(",
")",
";",
"}",
"element",
".",
"addClass",
"(",
"'hidden'",
")",
";",
"}",
";",
"// Watch the open property",
"scope",
".",
"$watch",
"(",
"'open'",
",",
"(",
"newVal",
",",
"oldVal",
")",
"=>",
"{",
"element",
".",
"css",
"(",
"'display'",
",",
"newVal",
"?",
"'block'",
":",
"'none'",
")",
";",
"}",
")",
";",
"}",
"}",
";",
"}"
] |
Provides a directive used to show a popup over the page with
a title and content.
Things to know about this directive:
- This directive is intended to be used along with the popup service.
- By default the directive uses "popup.html" as its templateUrl. This can be
changed by redefining the "ngeoPopupTemplateUrl" value.
- The directive doesn't create any scope but relies on its parent scope.
Properties like 'content', 'title' or 'open' come from the parent scope.
@param {string} ngeoPopupTemplateUrl URL to popup template.
@return {angular.IDirective} Directive Definition Object.
@ngInject
@ngdoc directive
@ngname ngeoPopup
|
[
"Provides",
"a",
"directive",
"used",
"to",
"show",
"a",
"popup",
"over",
"the",
"page",
"with",
"a",
"title",
"and",
"content",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/message/popupComponent.js#L53-L82
|
16,611
|
camptocamp/ngeo
|
src/query/mapQueryComponent.js
|
queryMapComponent
|
function queryMapComponent(ngeoMapQuerent, ngeoQueryKeyboard, $injector) {
return {
restrict: 'A',
scope: false,
link: (scope, elem, attrs) => {
const map = scope.$eval(attrs['ngeoMapQueryMap']);
/** @type {Array<import('ol/events.js').EventsKey>} */
const listenerKeys_ = [];
/**
* Called when the map is clicked while this controller is active. Issue
* a request to the query service using the coordinate that was clicked.
* @param {Event|import("ol/events/Event.js").default} evt The map browser event being fired.
*/
const handleMapClick_ = function(evt) {
if (evt instanceof MapBrowserEvent) {
const action = ngeoQueryKeyboard.action;
const coordinate = evt.coordinate;
ngeoMapQuerent.issue({
action,
coordinate,
map
});
}
};
/**
* Called when the pointer is moved while this controller is active.
* Change the mouse pointer when hovering a non-transparent pixel on the
* map.
* @param {Event|import("ol/events/Event.js").default} evt The map browser event being fired.
*/
const handlePointerMove_ = function(evt) {
if (evt instanceof MapBrowserEvent && !evt.dragging) {
const pixel = map.getEventPixel(evt.originalEvent);
const queryable = function(layer) {
const visible = layer.get('visible');
const sourceids = layer.get('querySourceIds');
return visible && !!sourceids;
};
const hit = map.forEachLayerAtPixel(pixel, () => true, undefined, queryable);
map.getTargetElement().style.cursor = hit ? 'pointer' : '';
}
};
/**
* Listen to the map events.
*/
const activate_ = function() {
listenerKeys_.push(
olEventsListen(map, 'singleclick', handleMapClick_)
);
const queryOptions = /** @type {import('ngeo/query/MapQuerent.js').QueryOptions} */ (
$injector.has('ngeoQueryOptions') ? $injector.get('ngeoQueryOptions') : {}
);
if (queryOptions.cursorHover) {
listenerKeys_.push(
olEventsListen(map, 'pointermove', handlePointerMove_)
);
}
};
/**
* Unlisten the map events.
*/
const deactivate_ = function() {
for (const lk of listenerKeys_) {
olEventsUnlistenByKey(lk);
}
listenerKeys_.length = 0;
if (scope.$eval(attrs['ngeoMapQueryAutoclear']) !== false) {
ngeoMapQuerent.clear();
}
};
// watch 'active' property -> activate/deactivate accordingly
scope.$watch(attrs['ngeoMapQueryActive'],
(newVal, oldVal) => {
if (newVal) {
activate_();
} else {
deactivate_();
}
}
);
}
};
}
|
javascript
|
function queryMapComponent(ngeoMapQuerent, ngeoQueryKeyboard, $injector) {
return {
restrict: 'A',
scope: false,
link: (scope, elem, attrs) => {
const map = scope.$eval(attrs['ngeoMapQueryMap']);
/** @type {Array<import('ol/events.js').EventsKey>} */
const listenerKeys_ = [];
/**
* Called when the map is clicked while this controller is active. Issue
* a request to the query service using the coordinate that was clicked.
* @param {Event|import("ol/events/Event.js").default} evt The map browser event being fired.
*/
const handleMapClick_ = function(evt) {
if (evt instanceof MapBrowserEvent) {
const action = ngeoQueryKeyboard.action;
const coordinate = evt.coordinate;
ngeoMapQuerent.issue({
action,
coordinate,
map
});
}
};
/**
* Called when the pointer is moved while this controller is active.
* Change the mouse pointer when hovering a non-transparent pixel on the
* map.
* @param {Event|import("ol/events/Event.js").default} evt The map browser event being fired.
*/
const handlePointerMove_ = function(evt) {
if (evt instanceof MapBrowserEvent && !evt.dragging) {
const pixel = map.getEventPixel(evt.originalEvent);
const queryable = function(layer) {
const visible = layer.get('visible');
const sourceids = layer.get('querySourceIds');
return visible && !!sourceids;
};
const hit = map.forEachLayerAtPixel(pixel, () => true, undefined, queryable);
map.getTargetElement().style.cursor = hit ? 'pointer' : '';
}
};
/**
* Listen to the map events.
*/
const activate_ = function() {
listenerKeys_.push(
olEventsListen(map, 'singleclick', handleMapClick_)
);
const queryOptions = /** @type {import('ngeo/query/MapQuerent.js').QueryOptions} */ (
$injector.has('ngeoQueryOptions') ? $injector.get('ngeoQueryOptions') : {}
);
if (queryOptions.cursorHover) {
listenerKeys_.push(
olEventsListen(map, 'pointermove', handlePointerMove_)
);
}
};
/**
* Unlisten the map events.
*/
const deactivate_ = function() {
for (const lk of listenerKeys_) {
olEventsUnlistenByKey(lk);
}
listenerKeys_.length = 0;
if (scope.$eval(attrs['ngeoMapQueryAutoclear']) !== false) {
ngeoMapQuerent.clear();
}
};
// watch 'active' property -> activate/deactivate accordingly
scope.$watch(attrs['ngeoMapQueryActive'],
(newVal, oldVal) => {
if (newVal) {
activate_();
} else {
deactivate_();
}
}
);
}
};
}
|
[
"function",
"queryMapComponent",
"(",
"ngeoMapQuerent",
",",
"ngeoQueryKeyboard",
",",
"$injector",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"scope",
":",
"false",
",",
"link",
":",
"(",
"scope",
",",
"elem",
",",
"attrs",
")",
"=>",
"{",
"const",
"map",
"=",
"scope",
".",
"$eval",
"(",
"attrs",
"[",
"'ngeoMapQueryMap'",
"]",
")",
";",
"/** @type {Array<import('ol/events.js').EventsKey>} */",
"const",
"listenerKeys_",
"=",
"[",
"]",
";",
"/**\n * Called when the map is clicked while this controller is active. Issue\n * a request to the query service using the coordinate that was clicked.\n * @param {Event|import(\"ol/events/Event.js\").default} evt The map browser event being fired.\n */",
"const",
"handleMapClick_",
"=",
"function",
"(",
"evt",
")",
"{",
"if",
"(",
"evt",
"instanceof",
"MapBrowserEvent",
")",
"{",
"const",
"action",
"=",
"ngeoQueryKeyboard",
".",
"action",
";",
"const",
"coordinate",
"=",
"evt",
".",
"coordinate",
";",
"ngeoMapQuerent",
".",
"issue",
"(",
"{",
"action",
",",
"coordinate",
",",
"map",
"}",
")",
";",
"}",
"}",
";",
"/**\n * Called when the pointer is moved while this controller is active.\n * Change the mouse pointer when hovering a non-transparent pixel on the\n * map.\n * @param {Event|import(\"ol/events/Event.js\").default} evt The map browser event being fired.\n */",
"const",
"handlePointerMove_",
"=",
"function",
"(",
"evt",
")",
"{",
"if",
"(",
"evt",
"instanceof",
"MapBrowserEvent",
"&&",
"!",
"evt",
".",
"dragging",
")",
"{",
"const",
"pixel",
"=",
"map",
".",
"getEventPixel",
"(",
"evt",
".",
"originalEvent",
")",
";",
"const",
"queryable",
"=",
"function",
"(",
"layer",
")",
"{",
"const",
"visible",
"=",
"layer",
".",
"get",
"(",
"'visible'",
")",
";",
"const",
"sourceids",
"=",
"layer",
".",
"get",
"(",
"'querySourceIds'",
")",
";",
"return",
"visible",
"&&",
"!",
"!",
"sourceids",
";",
"}",
";",
"const",
"hit",
"=",
"map",
".",
"forEachLayerAtPixel",
"(",
"pixel",
",",
"(",
")",
"=>",
"true",
",",
"undefined",
",",
"queryable",
")",
";",
"map",
".",
"getTargetElement",
"(",
")",
".",
"style",
".",
"cursor",
"=",
"hit",
"?",
"'pointer'",
":",
"''",
";",
"}",
"}",
";",
"/**\n * Listen to the map events.\n */",
"const",
"activate_",
"=",
"function",
"(",
")",
"{",
"listenerKeys_",
".",
"push",
"(",
"olEventsListen",
"(",
"map",
",",
"'singleclick'",
",",
"handleMapClick_",
")",
")",
";",
"const",
"queryOptions",
"=",
"/** @type {import('ngeo/query/MapQuerent.js').QueryOptions} */",
"(",
"$injector",
".",
"has",
"(",
"'ngeoQueryOptions'",
")",
"?",
"$injector",
".",
"get",
"(",
"'ngeoQueryOptions'",
")",
":",
"{",
"}",
")",
";",
"if",
"(",
"queryOptions",
".",
"cursorHover",
")",
"{",
"listenerKeys_",
".",
"push",
"(",
"olEventsListen",
"(",
"map",
",",
"'pointermove'",
",",
"handlePointerMove_",
")",
")",
";",
"}",
"}",
";",
"/**\n * Unlisten the map events.\n */",
"const",
"deactivate_",
"=",
"function",
"(",
")",
"{",
"for",
"(",
"const",
"lk",
"of",
"listenerKeys_",
")",
"{",
"olEventsUnlistenByKey",
"(",
"lk",
")",
";",
"}",
"listenerKeys_",
".",
"length",
"=",
"0",
";",
"if",
"(",
"scope",
".",
"$eval",
"(",
"attrs",
"[",
"'ngeoMapQueryAutoclear'",
"]",
")",
"!==",
"false",
")",
"{",
"ngeoMapQuerent",
".",
"clear",
"(",
")",
";",
"}",
"}",
";",
"// watch 'active' property -> activate/deactivate accordingly",
"scope",
".",
"$watch",
"(",
"attrs",
"[",
"'ngeoMapQueryActive'",
"]",
",",
"(",
"newVal",
",",
"oldVal",
")",
"=>",
"{",
"if",
"(",
"newVal",
")",
"{",
"activate_",
"(",
")",
";",
"}",
"else",
"{",
"deactivate_",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
";",
"}"
] |
Provides a "map query" directive.
This directive is responsible of binding a map and the ngeo query service
together. While active, clicks made on the map are listened by the directive
and a request gets issued to the query service.
This directive doesn't require to be rendered in a visible DOM element, but
it could be used with a ngeo-btn to manage the activation of the directive.
See below an example without any use of UI:
Example:
<span
ngeo-map-query=""
ngeo-map-query-map="::ctrl.map"
ngeo-map-query-active="ctrl.queryActive"
ngeo-map-query-autoclear="ctrl.queryAutoClear">
</span>
See our live example: [../examples/mapquery.html](../examples/mapquery.html)
@param {import("ngeo/query/MapQuerent.js").MapQuerent} ngeoMapQuerent The ngeo map querent service.
@param {import("ngeo/query/Keyboard.js").QueryKeyboard} ngeoQueryKeyboard The ngeo query keyboard service.
@param {angular.auto.IInjectorService} $injector Main injector.
@return {angular.IDirective} The Directive Definition Object.
@ngInject
@ngdoc directive
@ngname ngeoMapQuery
|
[
"Provides",
"a",
"map",
"query",
"directive",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/query/mapQueryComponent.js#L52-L139
|
16,612
|
camptocamp/ngeo
|
src/query/mapQueryComponent.js
|
function(evt) {
if (evt instanceof MapBrowserEvent) {
const action = ngeoQueryKeyboard.action;
const coordinate = evt.coordinate;
ngeoMapQuerent.issue({
action,
coordinate,
map
});
}
}
|
javascript
|
function(evt) {
if (evt instanceof MapBrowserEvent) {
const action = ngeoQueryKeyboard.action;
const coordinate = evt.coordinate;
ngeoMapQuerent.issue({
action,
coordinate,
map
});
}
}
|
[
"function",
"(",
"evt",
")",
"{",
"if",
"(",
"evt",
"instanceof",
"MapBrowserEvent",
")",
"{",
"const",
"action",
"=",
"ngeoQueryKeyboard",
".",
"action",
";",
"const",
"coordinate",
"=",
"evt",
".",
"coordinate",
";",
"ngeoMapQuerent",
".",
"issue",
"(",
"{",
"action",
",",
"coordinate",
",",
"map",
"}",
")",
";",
"}",
"}"
] |
Called when the map is clicked while this controller is active. Issue
a request to the query service using the coordinate that was clicked.
@param {Event|import("ol/events/Event.js").default} evt The map browser event being fired.
|
[
"Called",
"when",
"the",
"map",
"is",
"clicked",
"while",
"this",
"controller",
"is",
"active",
".",
"Issue",
"a",
"request",
"to",
"the",
"query",
"service",
"using",
"the",
"coordinate",
"that",
"was",
"clicked",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/query/mapQueryComponent.js#L66-L76
|
|
16,613
|
camptocamp/ngeo
|
src/query/mapQueryComponent.js
|
function(evt) {
if (evt instanceof MapBrowserEvent && !evt.dragging) {
const pixel = map.getEventPixel(evt.originalEvent);
const queryable = function(layer) {
const visible = layer.get('visible');
const sourceids = layer.get('querySourceIds');
return visible && !!sourceids;
};
const hit = map.forEachLayerAtPixel(pixel, () => true, undefined, queryable);
map.getTargetElement().style.cursor = hit ? 'pointer' : '';
}
}
|
javascript
|
function(evt) {
if (evt instanceof MapBrowserEvent && !evt.dragging) {
const pixel = map.getEventPixel(evt.originalEvent);
const queryable = function(layer) {
const visible = layer.get('visible');
const sourceids = layer.get('querySourceIds');
return visible && !!sourceids;
};
const hit = map.forEachLayerAtPixel(pixel, () => true, undefined, queryable);
map.getTargetElement().style.cursor = hit ? 'pointer' : '';
}
}
|
[
"function",
"(",
"evt",
")",
"{",
"if",
"(",
"evt",
"instanceof",
"MapBrowserEvent",
"&&",
"!",
"evt",
".",
"dragging",
")",
"{",
"const",
"pixel",
"=",
"map",
".",
"getEventPixel",
"(",
"evt",
".",
"originalEvent",
")",
";",
"const",
"queryable",
"=",
"function",
"(",
"layer",
")",
"{",
"const",
"visible",
"=",
"layer",
".",
"get",
"(",
"'visible'",
")",
";",
"const",
"sourceids",
"=",
"layer",
".",
"get",
"(",
"'querySourceIds'",
")",
";",
"return",
"visible",
"&&",
"!",
"!",
"sourceids",
";",
"}",
";",
"const",
"hit",
"=",
"map",
".",
"forEachLayerAtPixel",
"(",
"pixel",
",",
"(",
")",
"=>",
"true",
",",
"undefined",
",",
"queryable",
")",
";",
"map",
".",
"getTargetElement",
"(",
")",
".",
"style",
".",
"cursor",
"=",
"hit",
"?",
"'pointer'",
":",
"''",
";",
"}",
"}"
] |
Called when the pointer is moved while this controller is active.
Change the mouse pointer when hovering a non-transparent pixel on the
map.
@param {Event|import("ol/events/Event.js").default} evt The map browser event being fired.
|
[
"Called",
"when",
"the",
"pointer",
"is",
"moved",
"while",
"this",
"controller",
"is",
"active",
".",
"Change",
"the",
"mouse",
"pointer",
"when",
"hovering",
"a",
"non",
"-",
"transparent",
"pixel",
"on",
"the",
"map",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/query/mapQueryComponent.js#L84-L95
|
|
16,614
|
camptocamp/ngeo
|
src/query/mapQueryComponent.js
|
function() {
listenerKeys_.push(
olEventsListen(map, 'singleclick', handleMapClick_)
);
const queryOptions = /** @type {import('ngeo/query/MapQuerent.js').QueryOptions} */ (
$injector.has('ngeoQueryOptions') ? $injector.get('ngeoQueryOptions') : {}
);
if (queryOptions.cursorHover) {
listenerKeys_.push(
olEventsListen(map, 'pointermove', handlePointerMove_)
);
}
}
|
javascript
|
function() {
listenerKeys_.push(
olEventsListen(map, 'singleclick', handleMapClick_)
);
const queryOptions = /** @type {import('ngeo/query/MapQuerent.js').QueryOptions} */ (
$injector.has('ngeoQueryOptions') ? $injector.get('ngeoQueryOptions') : {}
);
if (queryOptions.cursorHover) {
listenerKeys_.push(
olEventsListen(map, 'pointermove', handlePointerMove_)
);
}
}
|
[
"function",
"(",
")",
"{",
"listenerKeys_",
".",
"push",
"(",
"olEventsListen",
"(",
"map",
",",
"'singleclick'",
",",
"handleMapClick_",
")",
")",
";",
"const",
"queryOptions",
"=",
"/** @type {import('ngeo/query/MapQuerent.js').QueryOptions} */",
"(",
"$injector",
".",
"has",
"(",
"'ngeoQueryOptions'",
")",
"?",
"$injector",
".",
"get",
"(",
"'ngeoQueryOptions'",
")",
":",
"{",
"}",
")",
";",
"if",
"(",
"queryOptions",
".",
"cursorHover",
")",
"{",
"listenerKeys_",
".",
"push",
"(",
"olEventsListen",
"(",
"map",
",",
"'pointermove'",
",",
"handlePointerMove_",
")",
")",
";",
"}",
"}"
] |
Listen to the map events.
|
[
"Listen",
"to",
"the",
"map",
"events",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/query/mapQueryComponent.js#L100-L112
|
|
16,615
|
camptocamp/ngeo
|
src/query/mapQueryComponent.js
|
function() {
for (const lk of listenerKeys_) {
olEventsUnlistenByKey(lk);
}
listenerKeys_.length = 0;
if (scope.$eval(attrs['ngeoMapQueryAutoclear']) !== false) {
ngeoMapQuerent.clear();
}
}
|
javascript
|
function() {
for (const lk of listenerKeys_) {
olEventsUnlistenByKey(lk);
}
listenerKeys_.length = 0;
if (scope.$eval(attrs['ngeoMapQueryAutoclear']) !== false) {
ngeoMapQuerent.clear();
}
}
|
[
"function",
"(",
")",
"{",
"for",
"(",
"const",
"lk",
"of",
"listenerKeys_",
")",
"{",
"olEventsUnlistenByKey",
"(",
"lk",
")",
";",
"}",
"listenerKeys_",
".",
"length",
"=",
"0",
";",
"if",
"(",
"scope",
".",
"$eval",
"(",
"attrs",
"[",
"'ngeoMapQueryAutoclear'",
"]",
")",
"!==",
"false",
")",
"{",
"ngeoMapQuerent",
".",
"clear",
"(",
")",
";",
"}",
"}"
] |
Unlisten the map events.
|
[
"Unlisten",
"the",
"map",
"events",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/query/mapQueryComponent.js#L117-L125
|
|
16,616
|
camptocamp/ngeo
|
contribs/gmf/src/objectediting/Query.js
|
getQueryableLayersInfoFromThemes
|
function getQueryableLayersInfoFromThemes(
themes, ogcServers
) {
const queryableLayersInfo = [];
let theme;
let group;
let nodes;
for (let i = 0, ii = themes.length; i < ii; i++) {
theme = /** @type {import('gmf/themes.js').GmfTheme} */ (themes[i]);
for (let j = 0, jj = theme.children.length; j < jj; j++) {
group = /** @type {import('gmf/themes.js').GmfGroup} */ (theme.children[j]);
// Skip groups that don't have an ogcServer set
if (!group.ogcServer) {
continue;
}
nodes = [];
getFlatNodes(group, nodes);
for (let k = 0, kk = nodes.length; k < kk; k++) {
const nodeGroup = /** @type {import('gmf/themes.js').GmfGroup} */ (nodes[k]);
// Skip groups within groups
if (nodeGroup.children && nodeGroup.children.length) {
continue;
}
const nodeWMS = /** @type {import('gmf/themes.js').GmfLayerWMS} */ (nodes[k]);
if (nodeWMS.childLayers &&
nodeWMS.childLayers[0] &&
nodeWMS.childLayers[0].queryable
) {
queryableLayersInfo.push({
layerNode: nodeWMS,
ogcServer: ogcServers[group.ogcServer]
});
}
}
}
}
return queryableLayersInfo;
}
|
javascript
|
function getQueryableLayersInfoFromThemes(
themes, ogcServers
) {
const queryableLayersInfo = [];
let theme;
let group;
let nodes;
for (let i = 0, ii = themes.length; i < ii; i++) {
theme = /** @type {import('gmf/themes.js').GmfTheme} */ (themes[i]);
for (let j = 0, jj = theme.children.length; j < jj; j++) {
group = /** @type {import('gmf/themes.js').GmfGroup} */ (theme.children[j]);
// Skip groups that don't have an ogcServer set
if (!group.ogcServer) {
continue;
}
nodes = [];
getFlatNodes(group, nodes);
for (let k = 0, kk = nodes.length; k < kk; k++) {
const nodeGroup = /** @type {import('gmf/themes.js').GmfGroup} */ (nodes[k]);
// Skip groups within groups
if (nodeGroup.children && nodeGroup.children.length) {
continue;
}
const nodeWMS = /** @type {import('gmf/themes.js').GmfLayerWMS} */ (nodes[k]);
if (nodeWMS.childLayers &&
nodeWMS.childLayers[0] &&
nodeWMS.childLayers[0].queryable
) {
queryableLayersInfo.push({
layerNode: nodeWMS,
ogcServer: ogcServers[group.ogcServer]
});
}
}
}
}
return queryableLayersInfo;
}
|
[
"function",
"getQueryableLayersInfoFromThemes",
"(",
"themes",
",",
"ogcServers",
")",
"{",
"const",
"queryableLayersInfo",
"=",
"[",
"]",
";",
"let",
"theme",
";",
"let",
"group",
";",
"let",
"nodes",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"ii",
"=",
"themes",
".",
"length",
";",
"i",
"<",
"ii",
";",
"i",
"++",
")",
"{",
"theme",
"=",
"/** @type {import('gmf/themes.js').GmfTheme} */",
"(",
"themes",
"[",
"i",
"]",
")",
";",
"for",
"(",
"let",
"j",
"=",
"0",
",",
"jj",
"=",
"theme",
".",
"children",
".",
"length",
";",
"j",
"<",
"jj",
";",
"j",
"++",
")",
"{",
"group",
"=",
"/** @type {import('gmf/themes.js').GmfGroup} */",
"(",
"theme",
".",
"children",
"[",
"j",
"]",
")",
";",
"// Skip groups that don't have an ogcServer set",
"if",
"(",
"!",
"group",
".",
"ogcServer",
")",
"{",
"continue",
";",
"}",
"nodes",
"=",
"[",
"]",
";",
"getFlatNodes",
"(",
"group",
",",
"nodes",
")",
";",
"for",
"(",
"let",
"k",
"=",
"0",
",",
"kk",
"=",
"nodes",
".",
"length",
";",
"k",
"<",
"kk",
";",
"k",
"++",
")",
"{",
"const",
"nodeGroup",
"=",
"/** @type {import('gmf/themes.js').GmfGroup} */",
"(",
"nodes",
"[",
"k",
"]",
")",
";",
"// Skip groups within groups",
"if",
"(",
"nodeGroup",
".",
"children",
"&&",
"nodeGroup",
".",
"children",
".",
"length",
")",
"{",
"continue",
";",
"}",
"const",
"nodeWMS",
"=",
"/** @type {import('gmf/themes.js').GmfLayerWMS} */",
"(",
"nodes",
"[",
"k",
"]",
")",
";",
"if",
"(",
"nodeWMS",
".",
"childLayers",
"&&",
"nodeWMS",
".",
"childLayers",
"[",
"0",
"]",
"&&",
"nodeWMS",
".",
"childLayers",
"[",
"0",
"]",
".",
"queryable",
")",
"{",
"queryableLayersInfo",
".",
"push",
"(",
"{",
"layerNode",
":",
"nodeWMS",
",",
"ogcServer",
":",
"ogcServers",
"[",
"group",
".",
"ogcServer",
"]",
"}",
")",
";",
"}",
"}",
"}",
"}",
"return",
"queryableLayersInfo",
";",
"}"
] |
From a list of theme nodes, collect all WMS layer nodes that are queryable.
A list of OGC servers is given in order to bind each queryable layer node
to its associated server and be able to build requests.
@param {Array.<import('gmf/themes.js').GmfTheme>} themes List of theme nodes.
@param {import('gmf/themes.js').GmfOgcServers} ogcServers List of ogc servers
@return {Array.<import('gmf/objectediting/toolsComponent.js').ObjectEditingQueryableLayerInfo>} List of
queryable layers information.
@private
@hidden
|
[
"From",
"a",
"list",
"of",
"theme",
"nodes",
"collect",
"all",
"WMS",
"layer",
"nodes",
"that",
"are",
"queryable",
".",
"A",
"list",
"of",
"OGC",
"servers",
"is",
"given",
"in",
"order",
"to",
"bind",
"each",
"queryable",
"layer",
"node",
"to",
"its",
"associated",
"server",
"and",
"be",
"able",
"to",
"build",
"requests",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/contribs/gmf/src/objectediting/Query.js#L102-L146
|
16,617
|
camptocamp/ngeo
|
src/misc/datepickerComponent.js
|
datePickerComponent
|
function datePickerComponent(ngeoDatePickerTemplateUrl, $timeout) {
return {
scope: {
onDateSelected: '&',
time: '='
},
bindToController: true,
controller: 'ngeoDatePickerController as datepickerCtrl',
restrict: 'AE',
templateUrl: ngeoDatePickerTemplateUrl,
link: (scope, element, attrs, ctrl) => {
if (!ctrl) {
throw new Error('Missing ctrl');
}
ctrl.init();
const lang = ctrl.gettextCatalog_.getCurrentLanguage();
$.datepicker.setDefaults($.datepicker.regional[lang]);
ctrl.sdateOptions = angular.extend({}, ctrl.sdateOptions, {
'minDate': ctrl.initialMinDate,
'maxDate': ctrl.initialMaxDate,
'onClose': (selectedDate) => {
if (selectedDate) {
$(element[0]).find('input[name="edate"]').datepicker('option', 'minDate', selectedDate);
}
}
});
ctrl.edateOptions = angular.extend({}, ctrl.edateOptions, {
'minDate': ctrl.initialMinDate,
'maxDate': ctrl.initialMaxDate,
'onClose': (selectedDate) => {
if (selectedDate) {
$(element[0]).find('input[name="sdate"]').datepicker('option', 'maxDate', selectedDate);
}
}
});
angular.element('body').on('hidden.bs.popover', () => {
const dp = angular.element('#ui-datepicker-div');
if (dp && dp.css('display') === 'block') {
$(element[0]).find('input[name$="date"]').datepicker('hide');
}
});
$timeout(() => {
angular.element('#ui-datepicker-div').on('click', (e) => {
e.stopPropagation();
});
});
}
};
}
|
javascript
|
function datePickerComponent(ngeoDatePickerTemplateUrl, $timeout) {
return {
scope: {
onDateSelected: '&',
time: '='
},
bindToController: true,
controller: 'ngeoDatePickerController as datepickerCtrl',
restrict: 'AE',
templateUrl: ngeoDatePickerTemplateUrl,
link: (scope, element, attrs, ctrl) => {
if (!ctrl) {
throw new Error('Missing ctrl');
}
ctrl.init();
const lang = ctrl.gettextCatalog_.getCurrentLanguage();
$.datepicker.setDefaults($.datepicker.regional[lang]);
ctrl.sdateOptions = angular.extend({}, ctrl.sdateOptions, {
'minDate': ctrl.initialMinDate,
'maxDate': ctrl.initialMaxDate,
'onClose': (selectedDate) => {
if (selectedDate) {
$(element[0]).find('input[name="edate"]').datepicker('option', 'minDate', selectedDate);
}
}
});
ctrl.edateOptions = angular.extend({}, ctrl.edateOptions, {
'minDate': ctrl.initialMinDate,
'maxDate': ctrl.initialMaxDate,
'onClose': (selectedDate) => {
if (selectedDate) {
$(element[0]).find('input[name="sdate"]').datepicker('option', 'maxDate', selectedDate);
}
}
});
angular.element('body').on('hidden.bs.popover', () => {
const dp = angular.element('#ui-datepicker-div');
if (dp && dp.css('display') === 'block') {
$(element[0]).find('input[name$="date"]').datepicker('hide');
}
});
$timeout(() => {
angular.element('#ui-datepicker-div').on('click', (e) => {
e.stopPropagation();
});
});
}
};
}
|
[
"function",
"datePickerComponent",
"(",
"ngeoDatePickerTemplateUrl",
",",
"$timeout",
")",
"{",
"return",
"{",
"scope",
":",
"{",
"onDateSelected",
":",
"'&'",
",",
"time",
":",
"'='",
"}",
",",
"bindToController",
":",
"true",
",",
"controller",
":",
"'ngeoDatePickerController as datepickerCtrl'",
",",
"restrict",
":",
"'AE'",
",",
"templateUrl",
":",
"ngeoDatePickerTemplateUrl",
",",
"link",
":",
"(",
"scope",
",",
"element",
",",
"attrs",
",",
"ctrl",
")",
"=>",
"{",
"if",
"(",
"!",
"ctrl",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing ctrl'",
")",
";",
"}",
"ctrl",
".",
"init",
"(",
")",
";",
"const",
"lang",
"=",
"ctrl",
".",
"gettextCatalog_",
".",
"getCurrentLanguage",
"(",
")",
";",
"$",
".",
"datepicker",
".",
"setDefaults",
"(",
"$",
".",
"datepicker",
".",
"regional",
"[",
"lang",
"]",
")",
";",
"ctrl",
".",
"sdateOptions",
"=",
"angular",
".",
"extend",
"(",
"{",
"}",
",",
"ctrl",
".",
"sdateOptions",
",",
"{",
"'minDate'",
":",
"ctrl",
".",
"initialMinDate",
",",
"'maxDate'",
":",
"ctrl",
".",
"initialMaxDate",
",",
"'onClose'",
":",
"(",
"selectedDate",
")",
"=>",
"{",
"if",
"(",
"selectedDate",
")",
"{",
"$",
"(",
"element",
"[",
"0",
"]",
")",
".",
"find",
"(",
"'input[name=\"edate\"]'",
")",
".",
"datepicker",
"(",
"'option'",
",",
"'minDate'",
",",
"selectedDate",
")",
";",
"}",
"}",
"}",
")",
";",
"ctrl",
".",
"edateOptions",
"=",
"angular",
".",
"extend",
"(",
"{",
"}",
",",
"ctrl",
".",
"edateOptions",
",",
"{",
"'minDate'",
":",
"ctrl",
".",
"initialMinDate",
",",
"'maxDate'",
":",
"ctrl",
".",
"initialMaxDate",
",",
"'onClose'",
":",
"(",
"selectedDate",
")",
"=>",
"{",
"if",
"(",
"selectedDate",
")",
"{",
"$",
"(",
"element",
"[",
"0",
"]",
")",
".",
"find",
"(",
"'input[name=\"sdate\"]'",
")",
".",
"datepicker",
"(",
"'option'",
",",
"'maxDate'",
",",
"selectedDate",
")",
";",
"}",
"}",
"}",
")",
";",
"angular",
".",
"element",
"(",
"'body'",
")",
".",
"on",
"(",
"'hidden.bs.popover'",
",",
"(",
")",
"=>",
"{",
"const",
"dp",
"=",
"angular",
".",
"element",
"(",
"'#ui-datepicker-div'",
")",
";",
"if",
"(",
"dp",
"&&",
"dp",
".",
"css",
"(",
"'display'",
")",
"===",
"'block'",
")",
"{",
"$",
"(",
"element",
"[",
"0",
"]",
")",
".",
"find",
"(",
"'input[name$=\"date\"]'",
")",
".",
"datepicker",
"(",
"'hide'",
")",
";",
"}",
"}",
")",
";",
"$timeout",
"(",
"(",
")",
"=>",
"{",
"angular",
".",
"element",
"(",
"'#ui-datepicker-div'",
")",
".",
"on",
"(",
"'click'",
",",
"(",
"e",
")",
"=>",
"{",
"e",
".",
"stopPropagation",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"}",
";",
"}"
] |
Provide a directive to select a single date or a range of dates. Requires
jQuery UI for the 'datepicker' widget.
@param {string|function(!JQuery=, !angular.IAttributes=): string}
ngeoDatePickerTemplateUrl Template for the directive.
@param {angular.ITimeoutService} $timeout angular timeout service
@return {angular.IDirective} The directive specs.
@ngInject
@ngdoc directive
@ngname ngeoDatePicker
|
[
"Provide",
"a",
"directive",
"to",
"select",
"a",
"single",
"date",
"or",
"a",
"range",
"of",
"dates",
".",
"Requires",
"jQuery",
"UI",
"for",
"the",
"datepicker",
"widget",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/misc/datepickerComponent.js#L54-L107
|
16,618
|
camptocamp/ngeo
|
src/misc/datepickerComponent.js
|
Controller
|
function Controller($scope, ngeoTime, gettextCatalog) {
/**
* @type {import("ngeo/misc/Time.js").Time}
* @private
*/
this.ngeoTime_ = ngeoTime;
/**
* @type {?import('ngeo/datasource/OGC.js').TimeProperty}
*/
this.time = null;
/**
* The gettext catalog
* @type {!angular.gettext.gettextCatalog}
* @private
*/
this.gettextCatalog_ = gettextCatalog;
/**
* If the component is used to select a date range
* @type {boolean}
*/
this.isModeRange = false;
/**
* Function called after date(s) changed/selected
* @type {?function({time: {start: number, end: ?number}}): void}
*/
this.onDateSelected = null;
/**
* Initial min date for the datepicker
* @type {?Date}
*/
this.initialMinDate = null;
/**
* Initial max date for the datepickeronDateSelected
* @type {?Date}
*/
this.initialMaxDate = null;
/**
* Datepicker options for the second datepicker (only for range mode)
* @type {Object}
*/
this.edateOptions = {
'changeMonth': true,
'changeYear': true
};
/**
* Datepicker options for the first datepicker
* @type {Object}
*/
this.sdateOptions = {
'changeMonth': true,
'changeYear': true
};
/**
* Start date model for the first date picker
* @type {?Date}
*/
this.sdate = null;
/**
* End date model for the second datepicker (only for range mode)
* @type {?Date}
*/
this.edate = null;
$scope.$watchGroup(['datepickerCtrl.sdate', 'datepickerCtrl.edate'], (newDates, oldDates) => {
if (!this.onDateSelected) {
throw new Error('Missing onDateSelected');
}
const sDate = newDates[0];
const eDate = newDates[1];
if (angular.isDate(sDate) && (!this.isModeRange || angular.isDate(eDate))) {
const start = this.ngeoTime_.getTime(sDate);
const end = this.ngeoTime_.getTime(eDate);
if (!start) {
throw new Error('Missing start');
}
this.onDateSelected({
time: {
start,
end,
}
});
}
});
}
|
javascript
|
function Controller($scope, ngeoTime, gettextCatalog) {
/**
* @type {import("ngeo/misc/Time.js").Time}
* @private
*/
this.ngeoTime_ = ngeoTime;
/**
* @type {?import('ngeo/datasource/OGC.js').TimeProperty}
*/
this.time = null;
/**
* The gettext catalog
* @type {!angular.gettext.gettextCatalog}
* @private
*/
this.gettextCatalog_ = gettextCatalog;
/**
* If the component is used to select a date range
* @type {boolean}
*/
this.isModeRange = false;
/**
* Function called after date(s) changed/selected
* @type {?function({time: {start: number, end: ?number}}): void}
*/
this.onDateSelected = null;
/**
* Initial min date for the datepicker
* @type {?Date}
*/
this.initialMinDate = null;
/**
* Initial max date for the datepickeronDateSelected
* @type {?Date}
*/
this.initialMaxDate = null;
/**
* Datepicker options for the second datepicker (only for range mode)
* @type {Object}
*/
this.edateOptions = {
'changeMonth': true,
'changeYear': true
};
/**
* Datepicker options for the first datepicker
* @type {Object}
*/
this.sdateOptions = {
'changeMonth': true,
'changeYear': true
};
/**
* Start date model for the first date picker
* @type {?Date}
*/
this.sdate = null;
/**
* End date model for the second datepicker (only for range mode)
* @type {?Date}
*/
this.edate = null;
$scope.$watchGroup(['datepickerCtrl.sdate', 'datepickerCtrl.edate'], (newDates, oldDates) => {
if (!this.onDateSelected) {
throw new Error('Missing onDateSelected');
}
const sDate = newDates[0];
const eDate = newDates[1];
if (angular.isDate(sDate) && (!this.isModeRange || angular.isDate(eDate))) {
const start = this.ngeoTime_.getTime(sDate);
const end = this.ngeoTime_.getTime(eDate);
if (!start) {
throw new Error('Missing start');
}
this.onDateSelected({
time: {
start,
end,
}
});
}
});
}
|
[
"function",
"Controller",
"(",
"$scope",
",",
"ngeoTime",
",",
"gettextCatalog",
")",
"{",
"/**\n * @type {import(\"ngeo/misc/Time.js\").Time}\n * @private\n */",
"this",
".",
"ngeoTime_",
"=",
"ngeoTime",
";",
"/**\n * @type {?import('ngeo/datasource/OGC.js').TimeProperty}\n */",
"this",
".",
"time",
"=",
"null",
";",
"/**\n * The gettext catalog\n * @type {!angular.gettext.gettextCatalog}\n * @private\n */",
"this",
".",
"gettextCatalog_",
"=",
"gettextCatalog",
";",
"/**\n * If the component is used to select a date range\n * @type {boolean}\n */",
"this",
".",
"isModeRange",
"=",
"false",
";",
"/**\n * Function called after date(s) changed/selected\n * @type {?function({time: {start: number, end: ?number}}): void}\n */",
"this",
".",
"onDateSelected",
"=",
"null",
";",
"/**\n * Initial min date for the datepicker\n * @type {?Date}\n */",
"this",
".",
"initialMinDate",
"=",
"null",
";",
"/**\n * Initial max date for the datepickeronDateSelected\n * @type {?Date}\n */",
"this",
".",
"initialMaxDate",
"=",
"null",
";",
"/**\n * Datepicker options for the second datepicker (only for range mode)\n * @type {Object}\n */",
"this",
".",
"edateOptions",
"=",
"{",
"'changeMonth'",
":",
"true",
",",
"'changeYear'",
":",
"true",
"}",
";",
"/**\n * Datepicker options for the first datepicker\n * @type {Object}\n */",
"this",
".",
"sdateOptions",
"=",
"{",
"'changeMonth'",
":",
"true",
",",
"'changeYear'",
":",
"true",
"}",
";",
"/**\n * Start date model for the first date picker\n * @type {?Date}\n */",
"this",
".",
"sdate",
"=",
"null",
";",
"/**\n * End date model for the second datepicker (only for range mode)\n * @type {?Date}\n */",
"this",
".",
"edate",
"=",
"null",
";",
"$scope",
".",
"$watchGroup",
"(",
"[",
"'datepickerCtrl.sdate'",
",",
"'datepickerCtrl.edate'",
"]",
",",
"(",
"newDates",
",",
"oldDates",
")",
"=>",
"{",
"if",
"(",
"!",
"this",
".",
"onDateSelected",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing onDateSelected'",
")",
";",
"}",
"const",
"sDate",
"=",
"newDates",
"[",
"0",
"]",
";",
"const",
"eDate",
"=",
"newDates",
"[",
"1",
"]",
";",
"if",
"(",
"angular",
".",
"isDate",
"(",
"sDate",
")",
"&&",
"(",
"!",
"this",
".",
"isModeRange",
"||",
"angular",
".",
"isDate",
"(",
"eDate",
")",
")",
")",
"{",
"const",
"start",
"=",
"this",
".",
"ngeoTime_",
".",
"getTime",
"(",
"sDate",
")",
";",
"const",
"end",
"=",
"this",
".",
"ngeoTime_",
".",
"getTime",
"(",
"eDate",
")",
";",
"if",
"(",
"!",
"start",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing start'",
")",
";",
"}",
"this",
".",
"onDateSelected",
"(",
"{",
"time",
":",
"{",
"start",
",",
"end",
",",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] |
DatePickerController - directive conttroller
@param {!angular.IScope} $scope Angular scope.
@param {!import("ngeo/misc/Time.js").Time} ngeoTime time service.
@param {!angular.gettext.gettextCatalog} gettextCatalog service.
@constructor
@private
@hidden
@ngInject
@ngdoc controller
@ngname ngeoDatePickerController
|
[
"DatePickerController",
"-",
"directive",
"conttroller"
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/misc/datepickerComponent.js#L124-L222
|
16,619
|
camptocamp/ngeo
|
examples/elevationProfile.js
|
function(type, key, opt_childKey) {
return (
/**
* @param {Object} item
* @return {any}
*/
function(item) {
if (opt_childKey !== undefined) {
item = item[opt_childKey];
}
return item[key];
});
}
|
javascript
|
function(type, key, opt_childKey) {
return (
/**
* @param {Object} item
* @return {any}
*/
function(item) {
if (opt_childKey !== undefined) {
item = item[opt_childKey];
}
return item[key];
});
}
|
[
"function",
"(",
"type",
",",
"key",
",",
"opt_childKey",
")",
"{",
"return",
"(",
"/**\n * @param {Object} item\n * @return {any}\n */",
"function",
"(",
"item",
")",
"{",
"if",
"(",
"opt_childKey",
"!==",
"undefined",
")",
"{",
"item",
"=",
"item",
"[",
"opt_childKey",
"]",
";",
"}",
"return",
"item",
"[",
"key",
"]",
";",
"}",
")",
";",
"}"
] |
Factory for creating simple getter functions for extractors.
If the value is in a child property, the opt_childKey must be defined.
The type parameter is used by closure to type the returned function.
@param {any} type An object of the expected result type.
@param {string} key Key used for retrieving the value.
@param {string=} opt_childKey Key of a child object.
@return {function(Object): any} Getter function.
|
[
"Factory",
"for",
"creating",
"simple",
"getter",
"functions",
"for",
"extractors",
".",
"If",
"the",
"value",
"is",
"in",
"a",
"child",
"property",
"the",
"opt_childKey",
"must",
"be",
"defined",
".",
"The",
"type",
"parameter",
"is",
"used",
"by",
"closure",
"to",
"type",
"the",
"returned",
"function",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/examples/elevationProfile.js#L143-L155
|
|
16,620
|
camptocamp/ngeo
|
src/profile/elevationComponent.js
|
profileElevationComponent
|
function profileElevationComponent(ngeoDebounce) {
return {
restrict: 'A',
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
*/
link: (scope, element, attrs) => {
const optionsAttr = attrs['ngeoProfileOptions'];
console.assert(optionsAttr !== undefined);
const selection = d3select(element[0]);
let profile, elevationData, poiData;
scope.$watchCollection(optionsAttr, (newVal) => {
/** @type {ProfileOptions} */
const options = Object.assign({}, newVal);
if (options !== undefined) {
// proxy the hoverCallback and outCallbackin order to be able to
// call $applyAsync
//
// We're using $applyAsync here because the callback may be
// called inside the Angular context. For example, it's the case
// when the user hover's the line geometry on the map and the
// profileHighlight property is changed.
//
// For that reason we use $applyAsync instead of $apply here.
if (options.hoverCallback !== undefined) {
const origHoverCallback = options.hoverCallback;
options.hoverCallback = function(...args) {
origHoverCallback(...args);
scope.$applyAsync();
};
}
if (options.outCallback !== undefined) {
const origOutCallback = options.outCallback;
options.outCallback = function() {
origOutCallback();
scope.$applyAsync();
};
}
profile = ngeoProfileD3Elevation(options);
refreshData();
}
});
scope.$watch(attrs['ngeoProfile'], (newVal, oldVal) => {
elevationData = newVal;
refreshData();
});
scope.$watch(attrs['ngeoProfilePois'], (newVal, oldVal) => {
poiData = newVal;
refreshData();
});
scope.$watch(attrs['ngeoProfileHighlight'],
(newVal, oldVal) => {
if (newVal === undefined) {
return;
}
if (newVal > 0) {
profile.highlight(newVal);
} else {
profile.clearHighlight();
}
});
olEvents.listen(window, 'resize', ngeoDebounce(refreshData, 50, true));
/**
* @param {Event|import("ol/events/Event.js").default=} evt Event
*/
function refreshData(evt) {
if (profile !== undefined) {
selection.datum(elevationData).call(profile);
if (elevationData !== undefined) {
profile.showPois(poiData);
}
}
}
}
};
}
|
javascript
|
function profileElevationComponent(ngeoDebounce) {
return {
restrict: 'A',
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
*/
link: (scope, element, attrs) => {
const optionsAttr = attrs['ngeoProfileOptions'];
console.assert(optionsAttr !== undefined);
const selection = d3select(element[0]);
let profile, elevationData, poiData;
scope.$watchCollection(optionsAttr, (newVal) => {
/** @type {ProfileOptions} */
const options = Object.assign({}, newVal);
if (options !== undefined) {
// proxy the hoverCallback and outCallbackin order to be able to
// call $applyAsync
//
// We're using $applyAsync here because the callback may be
// called inside the Angular context. For example, it's the case
// when the user hover's the line geometry on the map and the
// profileHighlight property is changed.
//
// For that reason we use $applyAsync instead of $apply here.
if (options.hoverCallback !== undefined) {
const origHoverCallback = options.hoverCallback;
options.hoverCallback = function(...args) {
origHoverCallback(...args);
scope.$applyAsync();
};
}
if (options.outCallback !== undefined) {
const origOutCallback = options.outCallback;
options.outCallback = function() {
origOutCallback();
scope.$applyAsync();
};
}
profile = ngeoProfileD3Elevation(options);
refreshData();
}
});
scope.$watch(attrs['ngeoProfile'], (newVal, oldVal) => {
elevationData = newVal;
refreshData();
});
scope.$watch(attrs['ngeoProfilePois'], (newVal, oldVal) => {
poiData = newVal;
refreshData();
});
scope.$watch(attrs['ngeoProfileHighlight'],
(newVal, oldVal) => {
if (newVal === undefined) {
return;
}
if (newVal > 0) {
profile.highlight(newVal);
} else {
profile.clearHighlight();
}
});
olEvents.listen(window, 'resize', ngeoDebounce(refreshData, 50, true));
/**
* @param {Event|import("ol/events/Event.js").default=} evt Event
*/
function refreshData(evt) {
if (profile !== undefined) {
selection.datum(elevationData).call(profile);
if (elevationData !== undefined) {
profile.showPois(poiData);
}
}
}
}
};
}
|
[
"function",
"profileElevationComponent",
"(",
"ngeoDebounce",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"/**\n * @param {angular.IScope} scope Scope.\n * @param {JQuery} element Element.\n * @param {angular.IAttributes} attrs Attributes.\n */",
"link",
":",
"(",
"scope",
",",
"element",
",",
"attrs",
")",
"=>",
"{",
"const",
"optionsAttr",
"=",
"attrs",
"[",
"'ngeoProfileOptions'",
"]",
";",
"console",
".",
"assert",
"(",
"optionsAttr",
"!==",
"undefined",
")",
";",
"const",
"selection",
"=",
"d3select",
"(",
"element",
"[",
"0",
"]",
")",
";",
"let",
"profile",
",",
"elevationData",
",",
"poiData",
";",
"scope",
".",
"$watchCollection",
"(",
"optionsAttr",
",",
"(",
"newVal",
")",
"=>",
"{",
"/** @type {ProfileOptions} */",
"const",
"options",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"newVal",
")",
";",
"if",
"(",
"options",
"!==",
"undefined",
")",
"{",
"// proxy the hoverCallback and outCallbackin order to be able to",
"// call $applyAsync",
"//",
"// We're using $applyAsync here because the callback may be",
"// called inside the Angular context. For example, it's the case",
"// when the user hover's the line geometry on the map and the",
"// profileHighlight property is changed.",
"//",
"// For that reason we use $applyAsync instead of $apply here.",
"if",
"(",
"options",
".",
"hoverCallback",
"!==",
"undefined",
")",
"{",
"const",
"origHoverCallback",
"=",
"options",
".",
"hoverCallback",
";",
"options",
".",
"hoverCallback",
"=",
"function",
"(",
"...",
"args",
")",
"{",
"origHoverCallback",
"(",
"...",
"args",
")",
";",
"scope",
".",
"$applyAsync",
"(",
")",
";",
"}",
";",
"}",
"if",
"(",
"options",
".",
"outCallback",
"!==",
"undefined",
")",
"{",
"const",
"origOutCallback",
"=",
"options",
".",
"outCallback",
";",
"options",
".",
"outCallback",
"=",
"function",
"(",
")",
"{",
"origOutCallback",
"(",
")",
";",
"scope",
".",
"$applyAsync",
"(",
")",
";",
"}",
";",
"}",
"profile",
"=",
"ngeoProfileD3Elevation",
"(",
"options",
")",
";",
"refreshData",
"(",
")",
";",
"}",
"}",
")",
";",
"scope",
".",
"$watch",
"(",
"attrs",
"[",
"'ngeoProfile'",
"]",
",",
"(",
"newVal",
",",
"oldVal",
")",
"=>",
"{",
"elevationData",
"=",
"newVal",
";",
"refreshData",
"(",
")",
";",
"}",
")",
";",
"scope",
".",
"$watch",
"(",
"attrs",
"[",
"'ngeoProfilePois'",
"]",
",",
"(",
"newVal",
",",
"oldVal",
")",
"=>",
"{",
"poiData",
"=",
"newVal",
";",
"refreshData",
"(",
")",
";",
"}",
")",
";",
"scope",
".",
"$watch",
"(",
"attrs",
"[",
"'ngeoProfileHighlight'",
"]",
",",
"(",
"newVal",
",",
"oldVal",
")",
"=>",
"{",
"if",
"(",
"newVal",
"===",
"undefined",
")",
"{",
"return",
";",
"}",
"if",
"(",
"newVal",
">",
"0",
")",
"{",
"profile",
".",
"highlight",
"(",
"newVal",
")",
";",
"}",
"else",
"{",
"profile",
".",
"clearHighlight",
"(",
")",
";",
"}",
"}",
")",
";",
"olEvents",
".",
"listen",
"(",
"window",
",",
"'resize'",
",",
"ngeoDebounce",
"(",
"refreshData",
",",
"50",
",",
"true",
")",
")",
";",
"/**\n * @param {Event|import(\"ol/events/Event.js\").default=} evt Event\n */",
"function",
"refreshData",
"(",
"evt",
")",
"{",
"if",
"(",
"profile",
"!==",
"undefined",
")",
"{",
"selection",
".",
"datum",
"(",
"elevationData",
")",
".",
"call",
"(",
"profile",
")",
";",
"if",
"(",
"elevationData",
"!==",
"undefined",
")",
"{",
"profile",
".",
"showPois",
"(",
"poiData",
")",
";",
"}",
"}",
"}",
"}",
"}",
";",
"}"
] |
Provides a directive used to insert an elevation profile chart
in the DOM.
Example:
<div ngeo-profile="ctrl.profileData"
ngeo-profile-options="ctrl.profileOptions"
ngeo-profile-pois="ctrl.profilePois">
</div>
Where `ctrl.profileOptions` is of type {@link ProfileOptions}; `ctrl.profileData` and `ctrl.profilePois`
are arrays which will be processed by `distanceExtractor` `{function(Object): number}`,
`linesConfiguration` `{Object.<string, LineConfiguration>}` {@link LineConfiguration} and
{@link PoiExtractor}.
See our live example: [../examples/profile.html](../examples/profile.html)
@htmlAttribute {?Object} ngeo-profile The profile data.
@htmlAttribute {ProfileOptions} ngeo-profile-options The options.
@htmlAttribute {?Array} ngeo-profile-pois The data for POIs.
@htmlAttribute {*} ngeo-profile-highlight Any property on the scope which
evaluated value may correspond to distance from origin.
@param {import("ngeo/misc/debounce.js").miscDebounce<function((Event|import('ol/events/Event.js').default)): void>} ngeoDebounce
ngeo Debounce factory.
@return {angular.IDirective} Directive Definition Object.
@ngInject
@ngdoc directive
@ngname ngeoProfile
|
[
"Provides",
"a",
"directive",
"used",
"to",
"insert",
"an",
"elevation",
"profile",
"chart",
"in",
"the",
"DOM",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/profile/elevationComponent.js#L113-L203
|
16,621
|
camptocamp/ngeo
|
src/misc/sortableComponent.js
|
sortableComponent
|
function sortableComponent($timeout) {
return {
restrict: 'A',
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
*/
link: (scope, element, attrs) => {
const sortable = /** @type {Array} */
(scope.$eval(attrs['ngeoSortable'])) || [];
console.assert(Array.isArray(sortable));
scope.$watchCollection(() => sortable, () => {
sortable.length && $timeout(resetUpDragDrop, 0);
});
const optionsObject = scope.$eval(attrs['ngeoSortableOptions']);
const options = getOptions(optionsObject);
const callbackFn = scope.$eval(attrs['ngeoSortableCallback']);
const callbackCtx = scope.$eval(attrs['ngeoSortableCallbackCtx']);
/**
* This function resets drag&drop for the list. It is called each
* time the sortable array changes (see $watchCollection above).
*/
function resetUpDragDrop() {
// Add an index to the sortable to allow sorting of the
// underlying data.
const children = element.children();
for (let i = 0; i < children.length; ++i) {
angular.element(children[i]).data('idx', i);
}
const sortableElement = $(element);
// the element is already sortable; reset it.
if (sortableElement.data('ui-sortable')) {
sortableElement.off('sortupdate');
sortableElement.sortable('destroy');
}
const sortableOptions = {
'axis': 'y',
'classes': {
'ui-sortable-helper': options['draggerClassName']
}
};
// CSS class of the handle
if (options['handleClassName']) {
sortableOptions['handle'] = `.${options['handleClassName']}`;
}
// Placeholder for the item being dragged in the sortable list
if (options['placeholderClassName']) {
sortableOptions['placeholder'] = options['placeholderClassName'];
sortableOptions['forcePlaceholderSize'] = true;
}
sortableElement.sortable(sortableOptions);
// This event is triggered when the user stopped sorting and
// the DOM position (i.e. order in the sortable list) has changed.
sortableElement.on('sortupdate', (event, ui) => {
const oldIndex = $(ui.item[0]).data('idx');
const newIndex = ui.item.index();
// Update (data)-index on dom element to its new position
$(ui.item[0]).data('idx', newIndex);
// Move dragged item to new position
scope.$apply(() => {
sortable.splice(newIndex, 0, sortable.splice(oldIndex, 1)[0]);
});
// Call the callback function if it exists.
if (callbackFn instanceof Function) {
callbackFn.apply(callbackCtx, [element, sortable]);
}
});
}
/**
* @param {?} options Options after expression evaluation.
* @return {!miscSortableOptions} Options object.
* @private
*/
function getOptions(options) {
let ret;
const defaultHandleClassName = 'ngeo-sortable-handle';
if (options === undefined) {
ret = {'handleClassName': defaultHandleClassName};
} else {
if (options['handleClassName'] === undefined) {
options['handleClassName'] = defaultHandleClassName;
}
ret = /** @type {miscSortableOptions} */ (options);
}
return ret;
}
}
};
}
|
javascript
|
function sortableComponent($timeout) {
return {
restrict: 'A',
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
*/
link: (scope, element, attrs) => {
const sortable = /** @type {Array} */
(scope.$eval(attrs['ngeoSortable'])) || [];
console.assert(Array.isArray(sortable));
scope.$watchCollection(() => sortable, () => {
sortable.length && $timeout(resetUpDragDrop, 0);
});
const optionsObject = scope.$eval(attrs['ngeoSortableOptions']);
const options = getOptions(optionsObject);
const callbackFn = scope.$eval(attrs['ngeoSortableCallback']);
const callbackCtx = scope.$eval(attrs['ngeoSortableCallbackCtx']);
/**
* This function resets drag&drop for the list. It is called each
* time the sortable array changes (see $watchCollection above).
*/
function resetUpDragDrop() {
// Add an index to the sortable to allow sorting of the
// underlying data.
const children = element.children();
for (let i = 0; i < children.length; ++i) {
angular.element(children[i]).data('idx', i);
}
const sortableElement = $(element);
// the element is already sortable; reset it.
if (sortableElement.data('ui-sortable')) {
sortableElement.off('sortupdate');
sortableElement.sortable('destroy');
}
const sortableOptions = {
'axis': 'y',
'classes': {
'ui-sortable-helper': options['draggerClassName']
}
};
// CSS class of the handle
if (options['handleClassName']) {
sortableOptions['handle'] = `.${options['handleClassName']}`;
}
// Placeholder for the item being dragged in the sortable list
if (options['placeholderClassName']) {
sortableOptions['placeholder'] = options['placeholderClassName'];
sortableOptions['forcePlaceholderSize'] = true;
}
sortableElement.sortable(sortableOptions);
// This event is triggered when the user stopped sorting and
// the DOM position (i.e. order in the sortable list) has changed.
sortableElement.on('sortupdate', (event, ui) => {
const oldIndex = $(ui.item[0]).data('idx');
const newIndex = ui.item.index();
// Update (data)-index on dom element to its new position
$(ui.item[0]).data('idx', newIndex);
// Move dragged item to new position
scope.$apply(() => {
sortable.splice(newIndex, 0, sortable.splice(oldIndex, 1)[0]);
});
// Call the callback function if it exists.
if (callbackFn instanceof Function) {
callbackFn.apply(callbackCtx, [element, sortable]);
}
});
}
/**
* @param {?} options Options after expression evaluation.
* @return {!miscSortableOptions} Options object.
* @private
*/
function getOptions(options) {
let ret;
const defaultHandleClassName = 'ngeo-sortable-handle';
if (options === undefined) {
ret = {'handleClassName': defaultHandleClassName};
} else {
if (options['handleClassName'] === undefined) {
options['handleClassName'] = defaultHandleClassName;
}
ret = /** @type {miscSortableOptions} */ (options);
}
return ret;
}
}
};
}
|
[
"function",
"sortableComponent",
"(",
"$timeout",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"/**\n * @param {angular.IScope} scope Scope.\n * @param {JQuery} element Element.\n * @param {angular.IAttributes} attrs Attributes.\n */",
"link",
":",
"(",
"scope",
",",
"element",
",",
"attrs",
")",
"=>",
"{",
"const",
"sortable",
"=",
"/** @type {Array} */",
"(",
"scope",
".",
"$eval",
"(",
"attrs",
"[",
"'ngeoSortable'",
"]",
")",
")",
"||",
"[",
"]",
";",
"console",
".",
"assert",
"(",
"Array",
".",
"isArray",
"(",
"sortable",
")",
")",
";",
"scope",
".",
"$watchCollection",
"(",
"(",
")",
"=>",
"sortable",
",",
"(",
")",
"=>",
"{",
"sortable",
".",
"length",
"&&",
"$timeout",
"(",
"resetUpDragDrop",
",",
"0",
")",
";",
"}",
")",
";",
"const",
"optionsObject",
"=",
"scope",
".",
"$eval",
"(",
"attrs",
"[",
"'ngeoSortableOptions'",
"]",
")",
";",
"const",
"options",
"=",
"getOptions",
"(",
"optionsObject",
")",
";",
"const",
"callbackFn",
"=",
"scope",
".",
"$eval",
"(",
"attrs",
"[",
"'ngeoSortableCallback'",
"]",
")",
";",
"const",
"callbackCtx",
"=",
"scope",
".",
"$eval",
"(",
"attrs",
"[",
"'ngeoSortableCallbackCtx'",
"]",
")",
";",
"/**\n * This function resets drag&drop for the list. It is called each\n * time the sortable array changes (see $watchCollection above).\n */",
"function",
"resetUpDragDrop",
"(",
")",
"{",
"// Add an index to the sortable to allow sorting of the",
"// underlying data.",
"const",
"children",
"=",
"element",
".",
"children",
"(",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"children",
".",
"length",
";",
"++",
"i",
")",
"{",
"angular",
".",
"element",
"(",
"children",
"[",
"i",
"]",
")",
".",
"data",
"(",
"'idx'",
",",
"i",
")",
";",
"}",
"const",
"sortableElement",
"=",
"$",
"(",
"element",
")",
";",
"// the element is already sortable; reset it.",
"if",
"(",
"sortableElement",
".",
"data",
"(",
"'ui-sortable'",
")",
")",
"{",
"sortableElement",
".",
"off",
"(",
"'sortupdate'",
")",
";",
"sortableElement",
".",
"sortable",
"(",
"'destroy'",
")",
";",
"}",
"const",
"sortableOptions",
"=",
"{",
"'axis'",
":",
"'y'",
",",
"'classes'",
":",
"{",
"'ui-sortable-helper'",
":",
"options",
"[",
"'draggerClassName'",
"]",
"}",
"}",
";",
"// CSS class of the handle",
"if",
"(",
"options",
"[",
"'handleClassName'",
"]",
")",
"{",
"sortableOptions",
"[",
"'handle'",
"]",
"=",
"`",
"${",
"options",
"[",
"'handleClassName'",
"]",
"}",
"`",
";",
"}",
"// Placeholder for the item being dragged in the sortable list",
"if",
"(",
"options",
"[",
"'placeholderClassName'",
"]",
")",
"{",
"sortableOptions",
"[",
"'placeholder'",
"]",
"=",
"options",
"[",
"'placeholderClassName'",
"]",
";",
"sortableOptions",
"[",
"'forcePlaceholderSize'",
"]",
"=",
"true",
";",
"}",
"sortableElement",
".",
"sortable",
"(",
"sortableOptions",
")",
";",
"// This event is triggered when the user stopped sorting and",
"// the DOM position (i.e. order in the sortable list) has changed.",
"sortableElement",
".",
"on",
"(",
"'sortupdate'",
",",
"(",
"event",
",",
"ui",
")",
"=>",
"{",
"const",
"oldIndex",
"=",
"$",
"(",
"ui",
".",
"item",
"[",
"0",
"]",
")",
".",
"data",
"(",
"'idx'",
")",
";",
"const",
"newIndex",
"=",
"ui",
".",
"item",
".",
"index",
"(",
")",
";",
"// Update (data)-index on dom element to its new position",
"$",
"(",
"ui",
".",
"item",
"[",
"0",
"]",
")",
".",
"data",
"(",
"'idx'",
",",
"newIndex",
")",
";",
"// Move dragged item to new position",
"scope",
".",
"$apply",
"(",
"(",
")",
"=>",
"{",
"sortable",
".",
"splice",
"(",
"newIndex",
",",
"0",
",",
"sortable",
".",
"splice",
"(",
"oldIndex",
",",
"1",
")",
"[",
"0",
"]",
")",
";",
"}",
")",
";",
"// Call the callback function if it exists.",
"if",
"(",
"callbackFn",
"instanceof",
"Function",
")",
"{",
"callbackFn",
".",
"apply",
"(",
"callbackCtx",
",",
"[",
"element",
",",
"sortable",
"]",
")",
";",
"}",
"}",
")",
";",
"}",
"/**\n * @param {?} options Options after expression evaluation.\n * @return {!miscSortableOptions} Options object.\n * @private\n */",
"function",
"getOptions",
"(",
"options",
")",
"{",
"let",
"ret",
";",
"const",
"defaultHandleClassName",
"=",
"'ngeo-sortable-handle'",
";",
"if",
"(",
"options",
"===",
"undefined",
")",
"{",
"ret",
"=",
"{",
"'handleClassName'",
":",
"defaultHandleClassName",
"}",
";",
"}",
"else",
"{",
"if",
"(",
"options",
"[",
"'handleClassName'",
"]",
"===",
"undefined",
")",
"{",
"options",
"[",
"'handleClassName'",
"]",
"=",
"defaultHandleClassName",
";",
"}",
"ret",
"=",
"/** @type {miscSortableOptions} */",
"(",
"options",
")",
";",
"}",
"return",
"ret",
";",
"}",
"}",
"}",
";",
"}"
] |
Provides a directive that allows drag-and-dropping DOM items between them.
It also changes the order of elements in the given array.
It is typically used together with `ng-repeat`, for example for re-ordering
layers in a map.
Example:
<ul ngeo-sortable="ctrl.layers"
ngeo-sortable-options="{handleClassName: 'ngeo-sortable-handle'}">
<li ng-repeat="layer in ctrl.layers">
<span class="ngeo-sortable-handle">handle</span>{{layer.get('name')}}
</li>
</ul>
The value of the "ngeo-sortable" attribute is an expression which evaluates
to an array (an array of layers in the above example). This is the array
that is re-ordered after a drag-and-drop.
The element with the class "ngeo-sortable-handle" is the "drag handle".
It is required.
This directives uses `$watchCollection` to watch the "sortable" array. So
if some outside code adds/removes elements to/from the "sortable" array,
the "ngeoSortable" directive will pick it up.
See our live example: [../examples/layerorder.html](../examples/layerorder.html)
@htmlAttribute {Array.<import("ol/layer/Base.js").default>} ngeo-sortable The layers to sort.
@htmlAttribute {!miscSortableOptions} ngeo-sortable-options The options.
@htmlAttribute {Function(JQuery, Array)?} ngeo-sortable-callback
Callback function called after the move end. The Function will be called
with the element and the sort array as arguments.
@htmlAttribute {Object?} ngeo-sortable-callback-ctx Context to apply at
the call of the callback function.
@param {angular.ITimeoutService} $timeout Angular timeout service.
@return {angular.IDirective} The directive specs.
@ngInject
@ngdoc directive
@ngname ngeoSortable
|
[
"Provides",
"a",
"directive",
"that",
"allows",
"drag",
"-",
"and",
"-",
"dropping",
"DOM",
"items",
"between",
"them",
".",
"It",
"also",
"changes",
"the",
"order",
"of",
"elements",
"in",
"the",
"given",
"array",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/misc/sortableComponent.js#L63-L169
|
16,622
|
camptocamp/ngeo
|
src/misc/filters.js
|
NumberFilter
|
function NumberFilter($locale) {
const formats = $locale.NUMBER_FORMATS;
/**
* @param {number} number The number to format.
* @param {number=} opt_precision The used precision, default is 3.
* @return {string} The formatted string.
*/
const result = function(number, opt_precision) {
const groupSep = formats.GROUP_SEP;
const decimalSep = formats.DECIMAL_SEP;
if (opt_precision === undefined) {
opt_precision = 3;
}
if (number === Infinity) {
return '\u221e';
} else if (number === -Infinity) {
return '-\u221e';
} else if (number === 0) {
// 0 will creates infinity values
return '0';
}
const sign = number < 0;
number = Math.abs(number);
const nb_decimal = opt_precision - Math.floor(Math.log(number) / Math.log(10)) - 1;
const factor = Math.pow(10, nb_decimal);
number = Math.round(number * factor);
let decimal = '';
const unit = Math.floor(number / factor);
if (nb_decimal > 0) {
let str_number = `${number}`;
// 0 padding
while (str_number.length < nb_decimal) {
str_number = `0${str_number}`;
}
decimal = str_number.substring(str_number.length - nb_decimal);
while (decimal[decimal.length - 1] === '0') {
decimal = decimal.substring(0, decimal.length - 1);
}
}
const groups = [];
let str_unit = `${unit}`;
while (str_unit.length > 3) {
const index = str_unit.length - 3;
groups.unshift(str_unit.substring(index));
str_unit = str_unit.substring(0, index);
}
groups.unshift(str_unit);
return (sign ? '-' : '') + groups.join(groupSep) + (
decimal.length === 0 ? '' : decimalSep + decimal
);
};
return result;
}
|
javascript
|
function NumberFilter($locale) {
const formats = $locale.NUMBER_FORMATS;
/**
* @param {number} number The number to format.
* @param {number=} opt_precision The used precision, default is 3.
* @return {string} The formatted string.
*/
const result = function(number, opt_precision) {
const groupSep = formats.GROUP_SEP;
const decimalSep = formats.DECIMAL_SEP;
if (opt_precision === undefined) {
opt_precision = 3;
}
if (number === Infinity) {
return '\u221e';
} else if (number === -Infinity) {
return '-\u221e';
} else if (number === 0) {
// 0 will creates infinity values
return '0';
}
const sign = number < 0;
number = Math.abs(number);
const nb_decimal = opt_precision - Math.floor(Math.log(number) / Math.log(10)) - 1;
const factor = Math.pow(10, nb_decimal);
number = Math.round(number * factor);
let decimal = '';
const unit = Math.floor(number / factor);
if (nb_decimal > 0) {
let str_number = `${number}`;
// 0 padding
while (str_number.length < nb_decimal) {
str_number = `0${str_number}`;
}
decimal = str_number.substring(str_number.length - nb_decimal);
while (decimal[decimal.length - 1] === '0') {
decimal = decimal.substring(0, decimal.length - 1);
}
}
const groups = [];
let str_unit = `${unit}`;
while (str_unit.length > 3) {
const index = str_unit.length - 3;
groups.unshift(str_unit.substring(index));
str_unit = str_unit.substring(0, index);
}
groups.unshift(str_unit);
return (sign ? '-' : '') + groups.join(groupSep) + (
decimal.length === 0 ? '' : decimalSep + decimal
);
};
return result;
}
|
[
"function",
"NumberFilter",
"(",
"$locale",
")",
"{",
"const",
"formats",
"=",
"$locale",
".",
"NUMBER_FORMATS",
";",
"/**\n * @param {number} number The number to format.\n * @param {number=} opt_precision The used precision, default is 3.\n * @return {string} The formatted string.\n */",
"const",
"result",
"=",
"function",
"(",
"number",
",",
"opt_precision",
")",
"{",
"const",
"groupSep",
"=",
"formats",
".",
"GROUP_SEP",
";",
"const",
"decimalSep",
"=",
"formats",
".",
"DECIMAL_SEP",
";",
"if",
"(",
"opt_precision",
"===",
"undefined",
")",
"{",
"opt_precision",
"=",
"3",
";",
"}",
"if",
"(",
"number",
"===",
"Infinity",
")",
"{",
"return",
"'\\u221e'",
";",
"}",
"else",
"if",
"(",
"number",
"===",
"-",
"Infinity",
")",
"{",
"return",
"'-\\u221e'",
";",
"}",
"else",
"if",
"(",
"number",
"===",
"0",
")",
"{",
"// 0 will creates infinity values",
"return",
"'0'",
";",
"}",
"const",
"sign",
"=",
"number",
"<",
"0",
";",
"number",
"=",
"Math",
".",
"abs",
"(",
"number",
")",
";",
"const",
"nb_decimal",
"=",
"opt_precision",
"-",
"Math",
".",
"floor",
"(",
"Math",
".",
"log",
"(",
"number",
")",
"/",
"Math",
".",
"log",
"(",
"10",
")",
")",
"-",
"1",
";",
"const",
"factor",
"=",
"Math",
".",
"pow",
"(",
"10",
",",
"nb_decimal",
")",
";",
"number",
"=",
"Math",
".",
"round",
"(",
"number",
"*",
"factor",
")",
";",
"let",
"decimal",
"=",
"''",
";",
"const",
"unit",
"=",
"Math",
".",
"floor",
"(",
"number",
"/",
"factor",
")",
";",
"if",
"(",
"nb_decimal",
">",
"0",
")",
"{",
"let",
"str_number",
"=",
"`",
"${",
"number",
"}",
"`",
";",
"// 0 padding",
"while",
"(",
"str_number",
".",
"length",
"<",
"nb_decimal",
")",
"{",
"str_number",
"=",
"`",
"${",
"str_number",
"}",
"`",
";",
"}",
"decimal",
"=",
"str_number",
".",
"substring",
"(",
"str_number",
".",
"length",
"-",
"nb_decimal",
")",
";",
"while",
"(",
"decimal",
"[",
"decimal",
".",
"length",
"-",
"1",
"]",
"===",
"'0'",
")",
"{",
"decimal",
"=",
"decimal",
".",
"substring",
"(",
"0",
",",
"decimal",
".",
"length",
"-",
"1",
")",
";",
"}",
"}",
"const",
"groups",
"=",
"[",
"]",
";",
"let",
"str_unit",
"=",
"`",
"${",
"unit",
"}",
"`",
";",
"while",
"(",
"str_unit",
".",
"length",
">",
"3",
")",
"{",
"const",
"index",
"=",
"str_unit",
".",
"length",
"-",
"3",
";",
"groups",
".",
"unshift",
"(",
"str_unit",
".",
"substring",
"(",
"index",
")",
")",
";",
"str_unit",
"=",
"str_unit",
".",
"substring",
"(",
"0",
",",
"index",
")",
";",
"}",
"groups",
".",
"unshift",
"(",
"str_unit",
")",
";",
"return",
"(",
"sign",
"?",
"'-'",
":",
"''",
")",
"+",
"groups",
".",
"join",
"(",
"groupSep",
")",
"+",
"(",
"decimal",
".",
"length",
"===",
"0",
"?",
"''",
":",
"decimalSep",
"+",
"decimal",
")",
";",
"}",
";",
"return",
"result",
";",
"}"
] |
A filter used to format a number with a precision, using the locale.
Arguments:
- opt_precision: The used precision, default is 3.
Examples:
{{0.1234 | ngeoNumber}} => 0.123
{{1.234 | ngeoNumber}} => 1.23
{{12.34 | ngeoNumber}} => 12.3
{{123.4 | ngeoNumber}} => 123
{{1234 | ngeoNumber}} => 1230
@param {angular.ILocaleService} $locale Angular locale
@return {formatNumber} Function used to format number into a string.
@ngInject
@ngdoc filter
@ngname ngeoNumber
|
[
"A",
"filter",
"used",
"to",
"format",
"a",
"number",
"with",
"a",
"precision",
"using",
"the",
"locale",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/misc/filters.js#L126-L184
|
16,623
|
camptocamp/ngeo
|
src/misc/filters.js
|
UnitPrefixFilter
|
function UnitPrefixFilter($filter) {
const numberFilter = $filter('ngeoNumber');
const standardPrefix = ['', 'k', 'M', 'G', 'T', 'P'];
const binaryPrefix = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi'];
/**
* @param {number} number The number to format.
* @param {string=} opt_unit The unit to used, default is ''.
* @param {string=} opt_type (unit|square|binary) the type of units, default is 'unit'.
* @param {number=} opt_precision The used precision, default is 3.
* @return {string} The formatted string.
*/
const result = function(number, opt_unit, opt_type, opt_precision) {
if (opt_unit === undefined) {
opt_unit = '';
}
let divisor = 1000;
let prefix = standardPrefix;
if (opt_type === 'square') {
divisor = 1000000;
} else if (opt_type === 'binary') {
divisor = 1024;
prefix = binaryPrefix;
}
let index = 0;
const index_max = prefix.length - 1;
while (number >= divisor && index < index_max) {
number = number / divisor;
index++;
}
const postfix = prefix[index] + opt_unit;
const space = postfix.length == 0 ? '' : '\u00a0';
return numberFilter(number, opt_precision) + space + postfix;
};
return result;
}
|
javascript
|
function UnitPrefixFilter($filter) {
const numberFilter = $filter('ngeoNumber');
const standardPrefix = ['', 'k', 'M', 'G', 'T', 'P'];
const binaryPrefix = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi'];
/**
* @param {number} number The number to format.
* @param {string=} opt_unit The unit to used, default is ''.
* @param {string=} opt_type (unit|square|binary) the type of units, default is 'unit'.
* @param {number=} opt_precision The used precision, default is 3.
* @return {string} The formatted string.
*/
const result = function(number, opt_unit, opt_type, opt_precision) {
if (opt_unit === undefined) {
opt_unit = '';
}
let divisor = 1000;
let prefix = standardPrefix;
if (opt_type === 'square') {
divisor = 1000000;
} else if (opt_type === 'binary') {
divisor = 1024;
prefix = binaryPrefix;
}
let index = 0;
const index_max = prefix.length - 1;
while (number >= divisor && index < index_max) {
number = number / divisor;
index++;
}
const postfix = prefix[index] + opt_unit;
const space = postfix.length == 0 ? '' : '\u00a0';
return numberFilter(number, opt_precision) + space + postfix;
};
return result;
}
|
[
"function",
"UnitPrefixFilter",
"(",
"$filter",
")",
"{",
"const",
"numberFilter",
"=",
"$filter",
"(",
"'ngeoNumber'",
")",
";",
"const",
"standardPrefix",
"=",
"[",
"''",
",",
"'k'",
",",
"'M'",
",",
"'G'",
",",
"'T'",
",",
"'P'",
"]",
";",
"const",
"binaryPrefix",
"=",
"[",
"''",
",",
"'Ki'",
",",
"'Mi'",
",",
"'Gi'",
",",
"'Ti'",
",",
"'Pi'",
"]",
";",
"/**\n * @param {number} number The number to format.\n * @param {string=} opt_unit The unit to used, default is ''.\n * @param {string=} opt_type (unit|square|binary) the type of units, default is 'unit'.\n * @param {number=} opt_precision The used precision, default is 3.\n * @return {string} The formatted string.\n */",
"const",
"result",
"=",
"function",
"(",
"number",
",",
"opt_unit",
",",
"opt_type",
",",
"opt_precision",
")",
"{",
"if",
"(",
"opt_unit",
"===",
"undefined",
")",
"{",
"opt_unit",
"=",
"''",
";",
"}",
"let",
"divisor",
"=",
"1000",
";",
"let",
"prefix",
"=",
"standardPrefix",
";",
"if",
"(",
"opt_type",
"===",
"'square'",
")",
"{",
"divisor",
"=",
"1000000",
";",
"}",
"else",
"if",
"(",
"opt_type",
"===",
"'binary'",
")",
"{",
"divisor",
"=",
"1024",
";",
"prefix",
"=",
"binaryPrefix",
";",
"}",
"let",
"index",
"=",
"0",
";",
"const",
"index_max",
"=",
"prefix",
".",
"length",
"-",
"1",
";",
"while",
"(",
"number",
">=",
"divisor",
"&&",
"index",
"<",
"index_max",
")",
"{",
"number",
"=",
"number",
"/",
"divisor",
";",
"index",
"++",
";",
"}",
"const",
"postfix",
"=",
"prefix",
"[",
"index",
"]",
"+",
"opt_unit",
";",
"const",
"space",
"=",
"postfix",
".",
"length",
"==",
"0",
"?",
"''",
":",
"'\\u00a0'",
";",
"return",
"numberFilter",
"(",
"number",
",",
"opt_precision",
")",
"+",
"space",
"+",
"postfix",
";",
"}",
";",
"return",
"result",
";",
"}"
] |
A filter used to format a number with the prefix and unit
Arguments:
- opt_unit: The unit to used, default is ''.
- opt_type: (unit|square|binary) the type of units, default is 'unit'.
- opt_precision: The used precision, default is 3.
Examples:
{{25000 | ngeoUnitPrefix}} => 25 k
{{25000 | ngeoUnitPrefix:'m'}} => 25 km
{{25000000 | ngeoUnitPrefix:'m²':'square'}} => 25 km²
{{2048 | ngeoUnitPrefix:'o':'binary'}} => 2 Kio
@param {angular.IFilterService} $filter Angular filter
@return {unitPrefix} Function used to format number into a string.
@ngInject
@ngdoc filter
@ngname ngeoUnitPrefix
|
[
"A",
"filter",
"used",
"to",
"format",
"a",
"number",
"with",
"the",
"prefix",
"and",
"unit"
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/misc/filters.js#L210-L246
|
16,624
|
camptocamp/ngeo
|
src/misc/filters.js
|
NumberCoordinatesFilter
|
function NumberCoordinatesFilter($filter) {
/**
* @param {import("ol/coordinate.js").Coordinate} coordinates Array of two numbers.
* @param {(number|string)=} opt_fractionDigits Optional number of digit.
* Default to 0.
* @param {string=} opt_template Optional template. Default to '{x} {y}'.
* Where "{x}" will be replaced by the easting coordinate and "{y}" by the
* northing one. Note: Use a html entity to use the semicolon symbol
* into a template.
* @return {string} Number formatted coordinates.
*/
const filterFn = function(coordinates, opt_fractionDigits, opt_template) {
const template = opt_template ? opt_template : '{x} {y}';
const x = coordinates[0];
const y = coordinates[1];
const fractionDigits = parseInt(/** @type {string} */(opt_fractionDigits), 10) | 0;
const x_str = $filter('number')(x, fractionDigits);
const y_str = $filter('number')(y, fractionDigits);
return template.replace('{x}', x_str).replace('{y}', y_str);
};
return filterFn;
}
|
javascript
|
function NumberCoordinatesFilter($filter) {
/**
* @param {import("ol/coordinate.js").Coordinate} coordinates Array of two numbers.
* @param {(number|string)=} opt_fractionDigits Optional number of digit.
* Default to 0.
* @param {string=} opt_template Optional template. Default to '{x} {y}'.
* Where "{x}" will be replaced by the easting coordinate and "{y}" by the
* northing one. Note: Use a html entity to use the semicolon symbol
* into a template.
* @return {string} Number formatted coordinates.
*/
const filterFn = function(coordinates, opt_fractionDigits, opt_template) {
const template = opt_template ? opt_template : '{x} {y}';
const x = coordinates[0];
const y = coordinates[1];
const fractionDigits = parseInt(/** @type {string} */(opt_fractionDigits), 10) | 0;
const x_str = $filter('number')(x, fractionDigits);
const y_str = $filter('number')(y, fractionDigits);
return template.replace('{x}', x_str).replace('{y}', y_str);
};
return filterFn;
}
|
[
"function",
"NumberCoordinatesFilter",
"(",
"$filter",
")",
"{",
"/**\n * @param {import(\"ol/coordinate.js\").Coordinate} coordinates Array of two numbers.\n * @param {(number|string)=} opt_fractionDigits Optional number of digit.\n * Default to 0.\n * @param {string=} opt_template Optional template. Default to '{x} {y}'.\n * Where \"{x}\" will be replaced by the easting coordinate and \"{y}\" by the\n * northing one. Note: Use a html entity to use the semicolon symbol\n * into a template.\n * @return {string} Number formatted coordinates.\n */",
"const",
"filterFn",
"=",
"function",
"(",
"coordinates",
",",
"opt_fractionDigits",
",",
"opt_template",
")",
"{",
"const",
"template",
"=",
"opt_template",
"?",
"opt_template",
":",
"'{x} {y}'",
";",
"const",
"x",
"=",
"coordinates",
"[",
"0",
"]",
";",
"const",
"y",
"=",
"coordinates",
"[",
"1",
"]",
";",
"const",
"fractionDigits",
"=",
"parseInt",
"(",
"/** @type {string} */",
"(",
"opt_fractionDigits",
")",
",",
"10",
")",
"|",
"0",
";",
"const",
"x_str",
"=",
"$filter",
"(",
"'number'",
")",
"(",
"x",
",",
"fractionDigits",
")",
";",
"const",
"y_str",
"=",
"$filter",
"(",
"'number'",
")",
"(",
"y",
",",
"fractionDigits",
")",
";",
"return",
"template",
".",
"replace",
"(",
"'{x}'",
",",
"x_str",
")",
".",
"replace",
"(",
"'{y}'",
",",
"y_str",
")",
";",
"}",
";",
"return",
"filterFn",
";",
"}"
] |
Format a couple of numbers as number coordinates.
Example without parameters:
<p>{{[7.1234, 46.9876] | ngeoNumberCoordinates}}</p>
<!-- will Become 7 47 -->
Example with defined fractionDigits and template (en-US localization):
<!-- With en-US localization -->
<p>{{[7.1234, 46.9876] | ngeoNumberCoordinates:2:'co {x} E; {y} N'}}</p>
<!-- will Become co 7.12 E; 46.99 N -->
<br/>
<!-- With en-US localization -->
<p>{{[2600000, 1600000] | ngeoNumberCoordinates:0:'{x}, {y}'}}</p>
<!-- will Become 2,600,000, 1,600,000 -->
<br/>
<!-- With fr-CH localization -->
<p>{{[2600000, 1600000] | ngeoNumberCoordinates:0:'{x}, {y}'}}</p>
<!-- will Become 2'600'000, 1'600'000 -->
@param {angular.IFilterService} $filter Angular filter
@return {numberCoordinates} A function to format numbers into coordinates string.
@ngInject
@ngdoc filter
@ngname ngeoNumberCoordinates
|
[
"Format",
"a",
"couple",
"of",
"numbers",
"as",
"number",
"coordinates",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/misc/filters.js#L278-L299
|
16,625
|
camptocamp/ngeo
|
src/misc/filters.js
|
DMSCoordinatesFilter
|
function DMSCoordinatesFilter() {
const degreesToStringHDMS = function(degrees, hemispheres, fractionDigits) {
const normalizedDegrees = modulo(degrees + 180, 360) - 180;
const dms = Math.abs(3600 * normalizedDegrees);
const d = Math.floor(dms / 3600);
const m = Math.floor((dms / 60) % 60);
const s = (dms % 60);
return `${d}\u00b0 ${
padNumber(m, 2)}\u2032 ${
padNumber(s, 2, fractionDigits)}\u2033 ${
hemispheres.charAt(normalizedDegrees < 0 ? 1 : 0)}`;
};
/**
* @param {import("ol/coordinate.js").Coordinate} coordinates Array of two numbers.
* @param {(number|string)=} opt_fractionDigits Optional number of digit.
* Default to 0.
* @param {string=} opt_template Optional template. Default to
* '{x} {y}'. Where "{x}" will be replaced by the easting
* coordinate, {y} by the northing one. Note: Use a html entity to use the
* semicolon symbol into a template.
* @return {string} DMS formatted coordinates.
*/
const filterFn = function(coordinates, opt_fractionDigits, opt_template) {
const fractionDigits = parseInt(/** @type {string} */(opt_fractionDigits), 10) | 0;
const template = opt_template ? opt_template : '{x} {y}';
const xdms = degreesToStringHDMS(coordinates[0], 'EW', fractionDigits);
const ydms = degreesToStringHDMS(coordinates[1], 'NS', fractionDigits);
return template.replace('{x}', xdms).replace('{y}', ydms);
};
return filterFn;
}
|
javascript
|
function DMSCoordinatesFilter() {
const degreesToStringHDMS = function(degrees, hemispheres, fractionDigits) {
const normalizedDegrees = modulo(degrees + 180, 360) - 180;
const dms = Math.abs(3600 * normalizedDegrees);
const d = Math.floor(dms / 3600);
const m = Math.floor((dms / 60) % 60);
const s = (dms % 60);
return `${d}\u00b0 ${
padNumber(m, 2)}\u2032 ${
padNumber(s, 2, fractionDigits)}\u2033 ${
hemispheres.charAt(normalizedDegrees < 0 ? 1 : 0)}`;
};
/**
* @param {import("ol/coordinate.js").Coordinate} coordinates Array of two numbers.
* @param {(number|string)=} opt_fractionDigits Optional number of digit.
* Default to 0.
* @param {string=} opt_template Optional template. Default to
* '{x} {y}'. Where "{x}" will be replaced by the easting
* coordinate, {y} by the northing one. Note: Use a html entity to use the
* semicolon symbol into a template.
* @return {string} DMS formatted coordinates.
*/
const filterFn = function(coordinates, opt_fractionDigits, opt_template) {
const fractionDigits = parseInt(/** @type {string} */(opt_fractionDigits), 10) | 0;
const template = opt_template ? opt_template : '{x} {y}';
const xdms = degreesToStringHDMS(coordinates[0], 'EW', fractionDigits);
const ydms = degreesToStringHDMS(coordinates[1], 'NS', fractionDigits);
return template.replace('{x}', xdms).replace('{y}', ydms);
};
return filterFn;
}
|
[
"function",
"DMSCoordinatesFilter",
"(",
")",
"{",
"const",
"degreesToStringHDMS",
"=",
"function",
"(",
"degrees",
",",
"hemispheres",
",",
"fractionDigits",
")",
"{",
"const",
"normalizedDegrees",
"=",
"modulo",
"(",
"degrees",
"+",
"180",
",",
"360",
")",
"-",
"180",
";",
"const",
"dms",
"=",
"Math",
".",
"abs",
"(",
"3600",
"*",
"normalizedDegrees",
")",
";",
"const",
"d",
"=",
"Math",
".",
"floor",
"(",
"dms",
"/",
"3600",
")",
";",
"const",
"m",
"=",
"Math",
".",
"floor",
"(",
"(",
"dms",
"/",
"60",
")",
"%",
"60",
")",
";",
"const",
"s",
"=",
"(",
"dms",
"%",
"60",
")",
";",
"return",
"`",
"${",
"d",
"}",
"\\u00b0",
"${",
"padNumber",
"(",
"m",
",",
"2",
")",
"}",
"\\u2032",
"${",
"padNumber",
"(",
"s",
",",
"2",
",",
"fractionDigits",
")",
"}",
"\\u2033",
"${",
"hemispheres",
".",
"charAt",
"(",
"normalizedDegrees",
"<",
"0",
"?",
"1",
":",
"0",
")",
"}",
"`",
";",
"}",
";",
"/**\n * @param {import(\"ol/coordinate.js\").Coordinate} coordinates Array of two numbers.\n * @param {(number|string)=} opt_fractionDigits Optional number of digit.\n * Default to 0.\n * @param {string=} opt_template Optional template. Default to\n * '{x} {y}'. Where \"{x}\" will be replaced by the easting\n * coordinate, {y} by the northing one. Note: Use a html entity to use the\n * semicolon symbol into a template.\n * @return {string} DMS formatted coordinates.\n */",
"const",
"filterFn",
"=",
"function",
"(",
"coordinates",
",",
"opt_fractionDigits",
",",
"opt_template",
")",
"{",
"const",
"fractionDigits",
"=",
"parseInt",
"(",
"/** @type {string} */",
"(",
"opt_fractionDigits",
")",
",",
"10",
")",
"|",
"0",
";",
"const",
"template",
"=",
"opt_template",
"?",
"opt_template",
":",
"'{x} {y}'",
";",
"const",
"xdms",
"=",
"degreesToStringHDMS",
"(",
"coordinates",
"[",
"0",
"]",
",",
"'EW'",
",",
"fractionDigits",
")",
";",
"const",
"ydms",
"=",
"degreesToStringHDMS",
"(",
"coordinates",
"[",
"1",
"]",
",",
"'NS'",
",",
"fractionDigits",
")",
";",
"return",
"template",
".",
"replace",
"(",
"'{x}'",
",",
"xdms",
")",
".",
"replace",
"(",
"'{y}'",
",",
"ydms",
")",
";",
"}",
";",
"return",
"filterFn",
";",
"}"
] |
Format coordinates as DMS coordinates.
Example without parameters:
<p>{{[7.1234, 46.9876] | ngeoDMSCoordinates}}</p>
<!-- will Become 7° 07' 24'' E 46° 59' 15'' N-->
Example with defined fractionDigits and a template.
<p>{{[7.1234, 46.9876] | ngeoDMSCoordinates:2:'[{y}; {x]'}}</p>
<!-- will Become [46° 59' 15.36'' N; 7° 07' 24.24'' E] -->
@return {dmsCoordinates} A function to format numbers into a DMS coordinates string.
@ngInject
@ngdoc filter
@ngname ngeoDMSCoordinates
|
[
"Format",
"coordinates",
"as",
"DMS",
"coordinates",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/misc/filters.js#L322-L357
|
16,626
|
camptocamp/ngeo
|
src/misc/filters.js
|
trustHtmlAutoFilter
|
function trustHtmlAutoFilter($sce, ngeoStringToHtmlReplacements) {
return function(input) {
if (input !== undefined && input !== null) {
if (typeof input === 'string') {
for (const replacement of ngeoStringToHtmlReplacements) {
if (input.match(replacement.expression)) {
input = replacement.template.replace(/\$1/g, input);
break;
}
}
return $sce.trustAsHtml(`${input}`);
} else {
return $sce.trustAsHtml(`${input}`);
}
} else {
return $sce.trustAsHtml(' ');
}
};
}
|
javascript
|
function trustHtmlAutoFilter($sce, ngeoStringToHtmlReplacements) {
return function(input) {
if (input !== undefined && input !== null) {
if (typeof input === 'string') {
for (const replacement of ngeoStringToHtmlReplacements) {
if (input.match(replacement.expression)) {
input = replacement.template.replace(/\$1/g, input);
break;
}
}
return $sce.trustAsHtml(`${input}`);
} else {
return $sce.trustAsHtml(`${input}`);
}
} else {
return $sce.trustAsHtml(' ');
}
};
}
|
[
"function",
"trustHtmlAutoFilter",
"(",
"$sce",
",",
"ngeoStringToHtmlReplacements",
")",
"{",
"return",
"function",
"(",
"input",
")",
"{",
"if",
"(",
"input",
"!==",
"undefined",
"&&",
"input",
"!==",
"null",
")",
"{",
"if",
"(",
"typeof",
"input",
"===",
"'string'",
")",
"{",
"for",
"(",
"const",
"replacement",
"of",
"ngeoStringToHtmlReplacements",
")",
"{",
"if",
"(",
"input",
".",
"match",
"(",
"replacement",
".",
"expression",
")",
")",
"{",
"input",
"=",
"replacement",
".",
"template",
".",
"replace",
"(",
"/",
"\\$1",
"/",
"g",
",",
"input",
")",
";",
"break",
";",
"}",
"}",
"return",
"$sce",
".",
"trustAsHtml",
"(",
"`",
"${",
"input",
"}",
"`",
")",
";",
"}",
"else",
"{",
"return",
"$sce",
".",
"trustAsHtml",
"(",
"`",
"${",
"input",
"}",
"`",
")",
";",
"}",
"}",
"else",
"{",
"return",
"$sce",
".",
"trustAsHtml",
"(",
"' '",
")",
";",
"}",
"}",
";",
"}"
] |
A filter to mark a value as trusted HTML, with the addition of
automatically converting any string that matches the
StringToHtmlReplacements list to HTML.
Usage:
<p ng-bind-html="ctrl.someValue | ngeoTrustHtmlAuto"></p>
If you use it, you don't require the "ngSanitize".
@return {function(?):string} The filter function.
@ngInject
@ngdoc filter
@param {angular.ISCEService} $sce Angular sce service.
@param {!Array.<!StringToHtmlReplacement>}
ngeoStringToHtmlReplacements List of replacements for string to html.
@ngname ngeoTrustHtmlAuto
|
[
"A",
"filter",
"to",
"mark",
"a",
"value",
"as",
"trusted",
"HTML",
"with",
"the",
"addition",
"of",
"automatically",
"converting",
"any",
"string",
"that",
"matches",
"the",
"StringToHtmlReplacements",
"list",
"to",
"HTML",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/misc/filters.js#L407-L425
|
16,627
|
camptocamp/ngeo
|
src/misc/filters.js
|
DurationFilter
|
function DurationFilter(gettextCatalog) {
// time unit enum
const TimeUnits = Object.freeze({
SECONDS: Symbol('seconds'),
MINUTES: Symbol('minutes'),
HOURS: Symbol('hours'),
DAYS: Symbol('days')
});
/**
* @param {number} amount Amount of time.
* @param {symbol} unit Unit of time.
* @return {string} formatted and translated string
*/
const pluralize = function(amount, unit) {
let formattedUnit = '';
switch (unit) {
case TimeUnits.SECONDS:
formattedUnit = gettextCatalog.getPlural(amount, 'second', 'seconds');
break;
case TimeUnits.MINUTES:
formattedUnit = gettextCatalog.getPlural(amount, 'minute', 'minutes');
break;
case TimeUnits.HOURS:
formattedUnit = gettextCatalog.getPlural(amount, 'hour', 'hours');
break;
case TimeUnits.DAYS:
formattedUnit = gettextCatalog.getPlural(amount, 'day', 'days');
break;
default:
break;
}
return `${amount} ${formattedUnit}`;
};
/**
* @param {number} duration The duration in seconds.
* @return {string} The formatted string.
*/
const result = function(duration) {
// round to next integer
duration = Math.round(duration);
// just seconds
let output;
if (duration < 60) {
return pluralize(duration, TimeUnits.SECONDS);
}
// minutes (+ seconds)
let remainder = duration % 60; // seconds
duration = Math.floor(duration / 60); // minutes
if (duration < 60) { // less than an hour
output = pluralize(duration, TimeUnits.MINUTES);
if (remainder > 0) {
output += ` ${pluralize(remainder, TimeUnits.SECONDS)}`;
}
return output;
}
// hours (+ minutes)
remainder = duration % 60; // minutes
duration = Math.floor(duration / 60); // hours
if (duration < 24) { // less than a day
output = pluralize(duration, TimeUnits.HOURS);
if (remainder > 0) {
output += ` ${pluralize(remainder, TimeUnits.MINUTES)}`;
}
return output;
}
// days (+ hours)
remainder = duration % 24; // hours
duration = Math.floor(duration / 24); // days
output = pluralize(duration, TimeUnits.DAYS);
if (remainder > 0) {
output += ` ${pluralize(remainder, TimeUnits.HOURS)}`;
}
return output;
};
return result;
}
|
javascript
|
function DurationFilter(gettextCatalog) {
// time unit enum
const TimeUnits = Object.freeze({
SECONDS: Symbol('seconds'),
MINUTES: Symbol('minutes'),
HOURS: Symbol('hours'),
DAYS: Symbol('days')
});
/**
* @param {number} amount Amount of time.
* @param {symbol} unit Unit of time.
* @return {string} formatted and translated string
*/
const pluralize = function(amount, unit) {
let formattedUnit = '';
switch (unit) {
case TimeUnits.SECONDS:
formattedUnit = gettextCatalog.getPlural(amount, 'second', 'seconds');
break;
case TimeUnits.MINUTES:
formattedUnit = gettextCatalog.getPlural(amount, 'minute', 'minutes');
break;
case TimeUnits.HOURS:
formattedUnit = gettextCatalog.getPlural(amount, 'hour', 'hours');
break;
case TimeUnits.DAYS:
formattedUnit = gettextCatalog.getPlural(amount, 'day', 'days');
break;
default:
break;
}
return `${amount} ${formattedUnit}`;
};
/**
* @param {number} duration The duration in seconds.
* @return {string} The formatted string.
*/
const result = function(duration) {
// round to next integer
duration = Math.round(duration);
// just seconds
let output;
if (duration < 60) {
return pluralize(duration, TimeUnits.SECONDS);
}
// minutes (+ seconds)
let remainder = duration % 60; // seconds
duration = Math.floor(duration / 60); // minutes
if (duration < 60) { // less than an hour
output = pluralize(duration, TimeUnits.MINUTES);
if (remainder > 0) {
output += ` ${pluralize(remainder, TimeUnits.SECONDS)}`;
}
return output;
}
// hours (+ minutes)
remainder = duration % 60; // minutes
duration = Math.floor(duration / 60); // hours
if (duration < 24) { // less than a day
output = pluralize(duration, TimeUnits.HOURS);
if (remainder > 0) {
output += ` ${pluralize(remainder, TimeUnits.MINUTES)}`;
}
return output;
}
// days (+ hours)
remainder = duration % 24; // hours
duration = Math.floor(duration / 24); // days
output = pluralize(duration, TimeUnits.DAYS);
if (remainder > 0) {
output += ` ${pluralize(remainder, TimeUnits.HOURS)}`;
}
return output;
};
return result;
}
|
[
"function",
"DurationFilter",
"(",
"gettextCatalog",
")",
"{",
"// time unit enum",
"const",
"TimeUnits",
"=",
"Object",
".",
"freeze",
"(",
"{",
"SECONDS",
":",
"Symbol",
"(",
"'seconds'",
")",
",",
"MINUTES",
":",
"Symbol",
"(",
"'minutes'",
")",
",",
"HOURS",
":",
"Symbol",
"(",
"'hours'",
")",
",",
"DAYS",
":",
"Symbol",
"(",
"'days'",
")",
"}",
")",
";",
"/**\n * @param {number} amount Amount of time.\n * @param {symbol} unit Unit of time.\n * @return {string} formatted and translated string\n */",
"const",
"pluralize",
"=",
"function",
"(",
"amount",
",",
"unit",
")",
"{",
"let",
"formattedUnit",
"=",
"''",
";",
"switch",
"(",
"unit",
")",
"{",
"case",
"TimeUnits",
".",
"SECONDS",
":",
"formattedUnit",
"=",
"gettextCatalog",
".",
"getPlural",
"(",
"amount",
",",
"'second'",
",",
"'seconds'",
")",
";",
"break",
";",
"case",
"TimeUnits",
".",
"MINUTES",
":",
"formattedUnit",
"=",
"gettextCatalog",
".",
"getPlural",
"(",
"amount",
",",
"'minute'",
",",
"'minutes'",
")",
";",
"break",
";",
"case",
"TimeUnits",
".",
"HOURS",
":",
"formattedUnit",
"=",
"gettextCatalog",
".",
"getPlural",
"(",
"amount",
",",
"'hour'",
",",
"'hours'",
")",
";",
"break",
";",
"case",
"TimeUnits",
".",
"DAYS",
":",
"formattedUnit",
"=",
"gettextCatalog",
".",
"getPlural",
"(",
"amount",
",",
"'day'",
",",
"'days'",
")",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"return",
"`",
"${",
"amount",
"}",
"${",
"formattedUnit",
"}",
"`",
";",
"}",
";",
"/**\n * @param {number} duration The duration in seconds.\n * @return {string} The formatted string.\n */",
"const",
"result",
"=",
"function",
"(",
"duration",
")",
"{",
"// round to next integer",
"duration",
"=",
"Math",
".",
"round",
"(",
"duration",
")",
";",
"// just seconds",
"let",
"output",
";",
"if",
"(",
"duration",
"<",
"60",
")",
"{",
"return",
"pluralize",
"(",
"duration",
",",
"TimeUnits",
".",
"SECONDS",
")",
";",
"}",
"// minutes (+ seconds)",
"let",
"remainder",
"=",
"duration",
"%",
"60",
";",
"// seconds",
"duration",
"=",
"Math",
".",
"floor",
"(",
"duration",
"/",
"60",
")",
";",
"// minutes",
"if",
"(",
"duration",
"<",
"60",
")",
"{",
"// less than an hour",
"output",
"=",
"pluralize",
"(",
"duration",
",",
"TimeUnits",
".",
"MINUTES",
")",
";",
"if",
"(",
"remainder",
">",
"0",
")",
"{",
"output",
"+=",
"`",
"${",
"pluralize",
"(",
"remainder",
",",
"TimeUnits",
".",
"SECONDS",
")",
"}",
"`",
";",
"}",
"return",
"output",
";",
"}",
"// hours (+ minutes)",
"remainder",
"=",
"duration",
"%",
"60",
";",
"// minutes",
"duration",
"=",
"Math",
".",
"floor",
"(",
"duration",
"/",
"60",
")",
";",
"// hours",
"if",
"(",
"duration",
"<",
"24",
")",
"{",
"// less than a day",
"output",
"=",
"pluralize",
"(",
"duration",
",",
"TimeUnits",
".",
"HOURS",
")",
";",
"if",
"(",
"remainder",
">",
"0",
")",
"{",
"output",
"+=",
"`",
"${",
"pluralize",
"(",
"remainder",
",",
"TimeUnits",
".",
"MINUTES",
")",
"}",
"`",
";",
"}",
"return",
"output",
";",
"}",
"// days (+ hours)",
"remainder",
"=",
"duration",
"%",
"24",
";",
"// hours",
"duration",
"=",
"Math",
".",
"floor",
"(",
"duration",
"/",
"24",
")",
";",
"// days",
"output",
"=",
"pluralize",
"(",
"duration",
",",
"TimeUnits",
".",
"DAYS",
")",
";",
"if",
"(",
"remainder",
">",
"0",
")",
"{",
"output",
"+=",
"`",
"${",
"pluralize",
"(",
"remainder",
",",
"TimeUnits",
".",
"HOURS",
")",
"}",
"`",
";",
"}",
"return",
"output",
";",
"}",
";",
"return",
"result",
";",
"}"
] |
A filter used to format a time duration in seconds into a more
readable form.
Only the two largest units will be shown.
Examples:
{{42 | ngeoDuration}} => 42 seconds
{{132 | ngeoDuration}} => 2 minutes 12 seconds
{{3910 | ngeoDuration}} => 1 hour 5 minutes
-> Note: the remaining 10 seconds will be dropped
@param {angular.gettext.gettextCatalog} gettextCatalog Gettext catalog.
@return {duration} Function used to format a time duration in seconds into a string.
@ngInject
@ngdoc filter
@ngname ngeoDuration
|
[
"A",
"filter",
"used",
"to",
"format",
"a",
"time",
"duration",
"in",
"seconds",
"into",
"a",
"more",
"readable",
"form",
".",
"Only",
"the",
"two",
"largest",
"units",
"will",
"be",
"shown",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/misc/filters.js#L447-L529
|
16,628
|
camptocamp/ngeo
|
contribs/gmf/src/profile/component.js
|
function(item) {
if ('values' in item && layerName in item.values && item.values[layerName]) {
return parseFloat(item.values[layerName]);
}
throw new Error('Unexpected');
}
|
javascript
|
function(item) {
if ('values' in item && layerName in item.values && item.values[layerName]) {
return parseFloat(item.values[layerName]);
}
throw new Error('Unexpected');
}
|
[
"function",
"(",
"item",
")",
"{",
"if",
"(",
"'values'",
"in",
"item",
"&&",
"layerName",
"in",
"item",
".",
"values",
"&&",
"item",
".",
"values",
"[",
"layerName",
"]",
")",
"{",
"return",
"parseFloat",
"(",
"item",
".",
"values",
"[",
"layerName",
"]",
")",
";",
"}",
"throw",
"new",
"Error",
"(",
"'Unexpected'",
")",
";",
"}"
] |
Generic GMF extractor for the 'given' value in 'values' in profileData.
@param {Object} item The item.
@return {number} The elevation.
@private
|
[
"Generic",
"GMF",
"extractor",
"for",
"the",
"given",
"value",
"in",
"values",
"in",
"profileData",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/contribs/gmf/src/profile/component.js#L636-L641
|
|
16,629
|
camptocamp/ngeo
|
contribs/gmf/src/raster/component.js
|
rasterComponent
|
function rasterComponent() {
return {
restrict: 'A',
controller: 'GmfElevationController as ctrl',
bindToController: true,
scope: {
'active': '<gmfElevationActive',
'elevation': '=gmfElevationElevation',
'layersconfig': '=gmfElevationLayersconfig',
'loading': '=?gmfElevationLoading',
'layer': '<gmfElevationLayer',
'map': '=gmfElevationMap'
},
link: (scope, element, attr) => {
const ctrl = scope['ctrl'];
// Watch active or not.
scope.$watch(() => ctrl.active, (active) => {
ctrl.toggleActive_(active);
});
// Watch current layer.
scope.$watch(() => ctrl.layer, (layer) => {
ctrl.layer = layer;
ctrl.elevation = null;
});
}
};
}
|
javascript
|
function rasterComponent() {
return {
restrict: 'A',
controller: 'GmfElevationController as ctrl',
bindToController: true,
scope: {
'active': '<gmfElevationActive',
'elevation': '=gmfElevationElevation',
'layersconfig': '=gmfElevationLayersconfig',
'loading': '=?gmfElevationLoading',
'layer': '<gmfElevationLayer',
'map': '=gmfElevationMap'
},
link: (scope, element, attr) => {
const ctrl = scope['ctrl'];
// Watch active or not.
scope.$watch(() => ctrl.active, (active) => {
ctrl.toggleActive_(active);
});
// Watch current layer.
scope.$watch(() => ctrl.layer, (layer) => {
ctrl.layer = layer;
ctrl.elevation = null;
});
}
};
}
|
[
"function",
"rasterComponent",
"(",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"controller",
":",
"'GmfElevationController as ctrl'",
",",
"bindToController",
":",
"true",
",",
"scope",
":",
"{",
"'active'",
":",
"'<gmfElevationActive'",
",",
"'elevation'",
":",
"'=gmfElevationElevation'",
",",
"'layersconfig'",
":",
"'=gmfElevationLayersconfig'",
",",
"'loading'",
":",
"'=?gmfElevationLoading'",
",",
"'layer'",
":",
"'<gmfElevationLayer'",
",",
"'map'",
":",
"'=gmfElevationMap'",
"}",
",",
"link",
":",
"(",
"scope",
",",
"element",
",",
"attr",
")",
"=>",
"{",
"const",
"ctrl",
"=",
"scope",
"[",
"'ctrl'",
"]",
";",
"// Watch active or not.",
"scope",
".",
"$watch",
"(",
"(",
")",
"=>",
"ctrl",
".",
"active",
",",
"(",
"active",
")",
"=>",
"{",
"ctrl",
".",
"toggleActive_",
"(",
"active",
")",
";",
"}",
")",
";",
"// Watch current layer.",
"scope",
".",
"$watch",
"(",
"(",
")",
"=>",
"ctrl",
".",
"layer",
",",
"(",
"layer",
")",
"=>",
"{",
"ctrl",
".",
"layer",
"=",
"layer",
";",
"ctrl",
".",
"elevation",
"=",
"null",
";",
"}",
")",
";",
"}",
"}",
";",
"}"
] |
Provide a directive that set a value each 500ms with the elevation under the
mouse cursor position on the map. The value must come from the elevation
service of a c2cgeoportal server. The server's URL must be defined as
config value of the application.
Example:
<span gmf-elevation
gmf-elevation-active="elevationActive"
gmf-elevation-elevation="elevationValue"
gmf-elevation-layer="mainCtrl.elevationLayer"
gmf-elevation-layersconfig="::mainCtrl.elevationLayersConfig"
gmf-elevation-map="::mainCtrl.map">
{{elevationValue}}
</span>
For value in meter `elevationLayersConfig` can be an empty object, complex example:
elevationLayersConfig = {
'<layer>': {
'filter': 'ngeoUnitPrefix',
'args': ['m²', 'square'],
'postfix': '<notice>',
'separator': ''
}
};
@htmlAttribute {boolean} gmf-elevation-active A boolean to set active or
deactivate the component.
@htmlAttribute {number} gmf-elevation-elevation The value to set with the
elevation value.
@htmlAttribute {string} gmf-elevation-layer Elevation layer to use.
@htmlAttribute {Object.<string, LayerConfig>} gmf-elevation-layersconfig Elevation layer configurations.
@htmlAttribute {import("ol/Map.js").default} gmf-elevation-map The map.
@return {angular.IDirective} Directive Definition Object.
@ngdoc directive
@ngname gmfElevation
|
[
"Provide",
"a",
"directive",
"that",
"set",
"a",
"value",
"each",
"500ms",
"with",
"the",
"elevation",
"under",
"the",
"mouse",
"cursor",
"position",
"on",
"the",
"map",
".",
"The",
"value",
"must",
"come",
"from",
"the",
"elevation",
"service",
"of",
"a",
"c2cgeoportal",
"server",
".",
"The",
"server",
"s",
"URL",
"must",
"be",
"defined",
"as",
"config",
"value",
"of",
"the",
"application",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/contribs/gmf/src/raster/component.js#L93-L121
|
16,630
|
camptocamp/ngeo
|
src/download/service.js
|
factory
|
function factory() {
/**
* @param {string} content The file content.
* @param {string} fileName The file name.
* @param {string=} opt_fileType The file type. If not given,
* `text/plain;charset=utf-8` is used.
*/
function download(content, fileName, opt_fileType) {
// Safari does not properly work with FileSaver. Using the the type 'text/plain'
// makes it a least possible to show the file content so that users can
// do a manual download with "Save as".
// See also: https://github.com/eligrey/FileSaver.js/issues/12
/** @type {string} */
const fileType = opt_fileType !== undefined && !isSafari() ?
opt_fileType : 'text/plain;charset=utf-8';
const blob = new Blob([content], {type: fileType});
saveAs(blob, fileName);
}
return download;
}
|
javascript
|
function factory() {
/**
* @param {string} content The file content.
* @param {string} fileName The file name.
* @param {string=} opt_fileType The file type. If not given,
* `text/plain;charset=utf-8` is used.
*/
function download(content, fileName, opt_fileType) {
// Safari does not properly work with FileSaver. Using the the type 'text/plain'
// makes it a least possible to show the file content so that users can
// do a manual download with "Save as".
// See also: https://github.com/eligrey/FileSaver.js/issues/12
/** @type {string} */
const fileType = opt_fileType !== undefined && !isSafari() ?
opt_fileType : 'text/plain;charset=utf-8';
const blob = new Blob([content], {type: fileType});
saveAs(blob, fileName);
}
return download;
}
|
[
"function",
"factory",
"(",
")",
"{",
"/**\n * @param {string} content The file content.\n * @param {string} fileName The file name.\n * @param {string=} opt_fileType The file type. If not given,\n * `text/plain;charset=utf-8` is used.\n */",
"function",
"download",
"(",
"content",
",",
"fileName",
",",
"opt_fileType",
")",
"{",
"// Safari does not properly work with FileSaver. Using the the type 'text/plain'",
"// makes it a least possible to show the file content so that users can",
"// do a manual download with \"Save as\".",
"// See also: https://github.com/eligrey/FileSaver.js/issues/12",
"/** @type {string} */",
"const",
"fileType",
"=",
"opt_fileType",
"!==",
"undefined",
"&&",
"!",
"isSafari",
"(",
")",
"?",
"opt_fileType",
":",
"'text/plain;charset=utf-8'",
";",
"const",
"blob",
"=",
"new",
"Blob",
"(",
"[",
"content",
"]",
",",
"{",
"type",
":",
"fileType",
"}",
")",
";",
"saveAs",
"(",
"blob",
",",
"fileName",
")",
";",
"}",
"return",
"download",
";",
"}"
] |
A service to start a download for a file.
@return {Download} The download function.
@ngdoc service
@ngname ngeoDownload
@private
@hidden
|
[
"A",
"service",
"to",
"start",
"a",
"download",
"for",
"a",
"file",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/download/service.js#L25-L46
|
16,631
|
camptocamp/ngeo
|
contribs/gmf/src/layertree/timeSliderComponent.js
|
Controller
|
function Controller(ngeoWMSTime) {
/**
* @type {import("ngeo/misc/WMSTime.js").WMSTime}
* @private
*/
this.ngeoWMSTime_ = ngeoWMSTime;
/**
* Function called after date(s) changed/selected
* @type {Function}
*/
this.onDateSelected = () => undefined;
/**
* A time object for directive initialization
* @type {?import('ngeo/datasource/OGC.js').TimeProperty}
*/
this.time = null;
/**
* If the component is used to select a date range
* @type {boolean}
*/
this.isModeRange = false;
/**
* Minimal value of the slider (time in ms)
* @type {number}
*/
this.minValue = -1;
/**
* Maximal value of the slider (time in ms)
* @type {number}
*/
this.maxValue = 999999;
/**
* Used when WMS time object has a property 'values' instead of an interval
* @type {?Array<number>}
*/
this.timeValueList = null;
/**
* Default Slider options (used by ui-slider directive)
* @type {?{
* range : boolean,
* min : number,
* max : number
* }}
*/
this.sliderOptions = null;
/**
* Model for the ui-slider directive (date in ms format)
* @type {Array<number>|number}
*/
this.dates = [];
}
|
javascript
|
function Controller(ngeoWMSTime) {
/**
* @type {import("ngeo/misc/WMSTime.js").WMSTime}
* @private
*/
this.ngeoWMSTime_ = ngeoWMSTime;
/**
* Function called after date(s) changed/selected
* @type {Function}
*/
this.onDateSelected = () => undefined;
/**
* A time object for directive initialization
* @type {?import('ngeo/datasource/OGC.js').TimeProperty}
*/
this.time = null;
/**
* If the component is used to select a date range
* @type {boolean}
*/
this.isModeRange = false;
/**
* Minimal value of the slider (time in ms)
* @type {number}
*/
this.minValue = -1;
/**
* Maximal value of the slider (time in ms)
* @type {number}
*/
this.maxValue = 999999;
/**
* Used when WMS time object has a property 'values' instead of an interval
* @type {?Array<number>}
*/
this.timeValueList = null;
/**
* Default Slider options (used by ui-slider directive)
* @type {?{
* range : boolean,
* min : number,
* max : number
* }}
*/
this.sliderOptions = null;
/**
* Model for the ui-slider directive (date in ms format)
* @type {Array<number>|number}
*/
this.dates = [];
}
|
[
"function",
"Controller",
"(",
"ngeoWMSTime",
")",
"{",
"/**\n * @type {import(\"ngeo/misc/WMSTime.js\").WMSTime}\n * @private\n */",
"this",
".",
"ngeoWMSTime_",
"=",
"ngeoWMSTime",
";",
"/**\n * Function called after date(s) changed/selected\n * @type {Function}\n */",
"this",
".",
"onDateSelected",
"=",
"(",
")",
"=>",
"undefined",
";",
"/**\n * A time object for directive initialization\n * @type {?import('ngeo/datasource/OGC.js').TimeProperty}\n */",
"this",
".",
"time",
"=",
"null",
";",
"/**\n * If the component is used to select a date range\n * @type {boolean}\n */",
"this",
".",
"isModeRange",
"=",
"false",
";",
"/**\n * Minimal value of the slider (time in ms)\n * @type {number}\n */",
"this",
".",
"minValue",
"=",
"-",
"1",
";",
"/**\n * Maximal value of the slider (time in ms)\n * @type {number}\n */",
"this",
".",
"maxValue",
"=",
"999999",
";",
"/**\n * Used when WMS time object has a property 'values' instead of an interval\n * @type {?Array<number>}\n */",
"this",
".",
"timeValueList",
"=",
"null",
";",
"/**\n * Default Slider options (used by ui-slider directive)\n * @type {?{\n * range : boolean,\n * min : number,\n * max : number\n * }}\n */",
"this",
".",
"sliderOptions",
"=",
"null",
";",
"/**\n * Model for the ui-slider directive (date in ms format)\n * @type {Array<number>|number}\n */",
"this",
".",
"dates",
"=",
"[",
"]",
";",
"}"
] |
TimeSliderController - directive controller
@param {import("ngeo/misc/WMSTime.js").WMSTime} ngeoWMSTime WMSTime service.
@constructor
@private
@hidden
@ngInject
@ngdoc controller
@ngname gmfTimeSliderController
|
[
"TimeSliderController",
"-",
"directive",
"controller"
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/contribs/gmf/src/layertree/timeSliderComponent.js#L118-L178
|
16,632
|
camptocamp/ngeo
|
src/misc/colorpickerComponent.js
|
colorPickerComponent
|
function colorPickerComponent(ngeoColorpickerTemplateUrl) {
return {
restrict: 'A',
scope: {
colors: '<?ngeoColorpicker',
color: '=?ngeoColorpickerColor'
},
controller: 'NgeoColorpickerController as ctrl',
bindToController: true,
templateUrl: ngeoColorpickerTemplateUrl
};
}
|
javascript
|
function colorPickerComponent(ngeoColorpickerTemplateUrl) {
return {
restrict: 'A',
scope: {
colors: '<?ngeoColorpicker',
color: '=?ngeoColorpickerColor'
},
controller: 'NgeoColorpickerController as ctrl',
bindToController: true,
templateUrl: ngeoColorpickerTemplateUrl
};
}
|
[
"function",
"colorPickerComponent",
"(",
"ngeoColorpickerTemplateUrl",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"scope",
":",
"{",
"colors",
":",
"'<?ngeoColorpicker'",
",",
"color",
":",
"'=?ngeoColorpickerColor'",
"}",
",",
"controller",
":",
"'NgeoColorpickerController as ctrl'",
",",
"bindToController",
":",
"true",
",",
"templateUrl",
":",
"ngeoColorpickerTemplateUrl",
"}",
";",
"}"
] |
Provides the "ngeoColorpicker" directive, a widget for
selecting a color among predefined ones.
Example:
<div ngeo-colorpicker="ctrl.colors">
</div>
@param {string|function(!JQuery=, !angular.IAttributes=): string}
ngeoColorpickerTemplateUrl Template URL for the directive.
@return {angular.IDirective} Directive Definition Object.
@ngInject
@ngdoc directive
@ngname ngeoColorpicker
|
[
"Provides",
"the",
"ngeoColorpicker",
"directive",
"a",
"widget",
"for",
"selecting",
"a",
"color",
"among",
"predefined",
"ones",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/misc/colorpickerComponent.js#L46-L57
|
16,633
|
camptocamp/ngeo
|
contribs/gmf/src/mobile/navigation/component.js
|
mobileNavigationComponent
|
function mobileNavigationComponent() {
return {
restrict: 'A',
controller: 'gmfMobileNavController as navCtrl',
bindToController: true,
scope: true,
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
* @param {angular.IController=} navCtrl Controller.
*/
link: (scope, element, attrs, navCtrl) => {
if (!navCtrl) {
throw new Error('Missing navCtrl');
}
navCtrl.init(element);
}
};
}
|
javascript
|
function mobileNavigationComponent() {
return {
restrict: 'A',
controller: 'gmfMobileNavController as navCtrl',
bindToController: true,
scope: true,
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
* @param {angular.IController=} navCtrl Controller.
*/
link: (scope, element, attrs, navCtrl) => {
if (!navCtrl) {
throw new Error('Missing navCtrl');
}
navCtrl.init(element);
}
};
}
|
[
"function",
"mobileNavigationComponent",
"(",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"controller",
":",
"'gmfMobileNavController as navCtrl'",
",",
"bindToController",
":",
"true",
",",
"scope",
":",
"true",
",",
"/**\n * @param {angular.IScope} scope Scope.\n * @param {JQuery} element Element.\n * @param {angular.IAttributes} attrs Attributes.\n * @param {angular.IController=} navCtrl Controller.\n */",
"link",
":",
"(",
"scope",
",",
"element",
",",
"attrs",
",",
"navCtrl",
")",
"=>",
"{",
"if",
"(",
"!",
"navCtrl",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing navCtrl'",
")",
";",
"}",
"navCtrl",
".",
"init",
"(",
"element",
")",
";",
"}",
"}",
";",
"}"
] |
An "gmf-mobile-nav" directive defining the behavior of a tree-structured menu.
The directive is to be placed on a `nav` element, with the following
structure:
<nav gmf-mobile-nav>
<header>
<a class="gmf-mobile-nav-go-back" href="#"></a>
</header>
<div class="gmf-mobile-nav-active gmf-mobile-nav-slide">
<ul>
<li>
<a href data-target="#devices">Devices</a>
</li>
<li>
<a href data-target="#vehicles">Vehicles</a>
</li>
</ul>
</div>
<div id="devices" class="gmf-mobile-nav-slide" data-header-title="Devices">
<ul>
<li>Mobile Phones</li>
<li>Televisions</li>
</ul>
</div>
<div id="vehicles" class="gmf-mobile-nav-slide" data-header-title="Vehicles">
<ul>
<li>Cars</li>
<li>Planes</li>
<li>Bicycles</li>
</ul>
</div>
</nav>
When an element slides in the directive changes the text in the header.
@return {angular.IDirective} The Directive Definition Object.
@ngInject
|
[
"An",
"gmf",
"-",
"mobile",
"-",
"nav",
"directive",
"defining",
"the",
"behavior",
"of",
"a",
"tree",
"-",
"structured",
"menu",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/contribs/gmf/src/mobile/navigation/component.js#L63-L82
|
16,634
|
camptocamp/ngeo
|
contribs/gmf/src/mobile/measure/areaComponent.js
|
mobileMeasureAreaComponent
|
function mobileMeasureAreaComponent(gmfMobileMeasureAreaTemplateUrl) {
return {
restrict: 'A',
scope: {
'active': '=gmfMobileMeasureareaActive',
'precision': '<?gmfMobileMeasureareaPrecision',
'map': '=gmfMobileMeasureareaMap',
'sketchStyle': '=?gmfMobileMeasureareaSketchstyle'
},
controller: 'GmfMobileMeasureAreaController as ctrl',
bindToController: true,
templateUrl: gmfMobileMeasureAreaTemplateUrl,
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
* @param {angular.IController=} controller Controller.
*/
link: (scope, element, attrs, controller) => {
if (!controller) {
throw new Error('Missing controller');
}
controller.init();
}
};
}
|
javascript
|
function mobileMeasureAreaComponent(gmfMobileMeasureAreaTemplateUrl) {
return {
restrict: 'A',
scope: {
'active': '=gmfMobileMeasureareaActive',
'precision': '<?gmfMobileMeasureareaPrecision',
'map': '=gmfMobileMeasureareaMap',
'sketchStyle': '=?gmfMobileMeasureareaSketchstyle'
},
controller: 'GmfMobileMeasureAreaController as ctrl',
bindToController: true,
templateUrl: gmfMobileMeasureAreaTemplateUrl,
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
* @param {angular.IController=} controller Controller.
*/
link: (scope, element, attrs, controller) => {
if (!controller) {
throw new Error('Missing controller');
}
controller.init();
}
};
}
|
[
"function",
"mobileMeasureAreaComponent",
"(",
"gmfMobileMeasureAreaTemplateUrl",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"scope",
":",
"{",
"'active'",
":",
"'=gmfMobileMeasureareaActive'",
",",
"'precision'",
":",
"'<?gmfMobileMeasureareaPrecision'",
",",
"'map'",
":",
"'=gmfMobileMeasureareaMap'",
",",
"'sketchStyle'",
":",
"'=?gmfMobileMeasureareaSketchstyle'",
"}",
",",
"controller",
":",
"'GmfMobileMeasureAreaController as ctrl'",
",",
"bindToController",
":",
"true",
",",
"templateUrl",
":",
"gmfMobileMeasureAreaTemplateUrl",
",",
"/**\n * @param {angular.IScope} scope Scope.\n * @param {JQuery} element Element.\n * @param {angular.IAttributes} attrs Attributes.\n * @param {angular.IController=} controller Controller.\n */",
"link",
":",
"(",
"scope",
",",
"element",
",",
"attrs",
",",
"controller",
")",
"=>",
"{",
"if",
"(",
"!",
"controller",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing controller'",
")",
";",
"}",
"controller",
".",
"init",
"(",
")",
";",
"}",
"}",
";",
"}"
] |
Provide a directive to do a area measure on the mobile devices.
Example:
<div gmf-mobile-measurearea
gmf-mobile-measurearea-active="ctrl.measureAreaActive"
gmf-mobile-measurearea-map="::ctrl.map">
</div>
@htmlAttribute {boolean} gmf-mobile-measurearea-active Used to active
or deactivate the component.
@htmlAttribute {number=} gmf-mobile-measurearea-precision the number of significant digits to display.
@htmlAttribute {import("ol/Map.js").default} gmf-mobile-measurearea-map The map.
@htmlAttribute {import("ol/style/Style.js").StyleLike=}
gmf-mobile-measurearea-sketchstyle A style for the measure area.
@param {string|function(!JQuery=, !angular.IAttributes=):string}
gmfMobileMeasureAreaTemplateUrl Template URL for the directive.
@return {angular.IDirective} The Directive Definition Object.
@ngInject
@ngdoc directive
@ngname gmfMobileMeasureArea
|
[
"Provide",
"a",
"directive",
"to",
"do",
"a",
"area",
"measure",
"on",
"the",
"mobile",
"devices",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/contribs/gmf/src/mobile/measure/areaComponent.js#L57-L82
|
16,635
|
camptocamp/ngeo
|
src/misc/debounce.js
|
debounce
|
function debounce(func, wait, invokeApply, $timeout) {
/**
* @type {?angular.IPromise}
*/
let timeout = null;
return /** @type {T} */(
/**
* @this {any} The context
*/
function(...args) {
const context = this;
const later = function() {
timeout = null;
func.apply(context, args);
};
if (timeout !== null) {
$timeout.cancel(timeout);
}
timeout = $timeout(later, wait, invokeApply);
}
);
}
|
javascript
|
function debounce(func, wait, invokeApply, $timeout) {
/**
* @type {?angular.IPromise}
*/
let timeout = null;
return /** @type {T} */(
/**
* @this {any} The context
*/
function(...args) {
const context = this;
const later = function() {
timeout = null;
func.apply(context, args);
};
if (timeout !== null) {
$timeout.cancel(timeout);
}
timeout = $timeout(later, wait, invokeApply);
}
);
}
|
[
"function",
"debounce",
"(",
"func",
",",
"wait",
",",
"invokeApply",
",",
"$timeout",
")",
"{",
"/**\n * @type {?angular.IPromise}\n */",
"let",
"timeout",
"=",
"null",
";",
"return",
"/** @type {T} */",
"(",
"/**\n * @this {any} The context\n */",
"function",
"(",
"...",
"args",
")",
"{",
"const",
"context",
"=",
"this",
";",
"const",
"later",
"=",
"function",
"(",
")",
"{",
"timeout",
"=",
"null",
";",
"func",
".",
"apply",
"(",
"context",
",",
"args",
")",
";",
"}",
";",
"if",
"(",
"timeout",
"!==",
"null",
")",
"{",
"$timeout",
".",
"cancel",
"(",
"timeout",
")",
";",
"}",
"timeout",
"=",
"$timeout",
"(",
"later",
",",
"wait",
",",
"invokeApply",
")",
";",
"}",
")",
";",
"}"
] |
Provides a debounce function used to debounce calls to a user-provided function.
@template {function(?): void} T args
@typedef {function(T, number, boolean): T} miscDebounce
@template {function(?): void} T args
@param {T} func The function to debounce.
@param {number} wait The wait time in ms.
@param {boolean} invokeApply Whether the call to `func` is wrapped into an `$apply` call.
@param {angular.ITimeoutService} $timeout Angular timeout service.
@return {T} The wrapper function.
@private
@hidden
|
[
"Provides",
"a",
"debounce",
"function",
"used",
"to",
"debounce",
"calls",
"to",
"a",
"user",
"-",
"provided",
"function",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/misc/debounce.js#L27-L48
|
16,636
|
camptocamp/ngeo
|
src/misc/debounce.js
|
factory
|
function factory($timeout) {
/** @type {function(T, number, boolean, angular.ITimeoutService): T} */
const deb = debounce;
return (func, wait, invokeApply) => {
return deb(func, wait, invokeApply, $timeout);
};
}
|
javascript
|
function factory($timeout) {
/** @type {function(T, number, boolean, angular.ITimeoutService): T} */
const deb = debounce;
return (func, wait, invokeApply) => {
return deb(func, wait, invokeApply, $timeout);
};
}
|
[
"function",
"factory",
"(",
"$timeout",
")",
"{",
"/** @type {function(T, number, boolean, angular.ITimeoutService): T} */",
"const",
"deb",
"=",
"debounce",
";",
"return",
"(",
"func",
",",
"wait",
",",
"invokeApply",
")",
"=>",
"{",
"return",
"deb",
"(",
"func",
",",
"wait",
",",
"invokeApply",
",",
"$timeout",
")",
";",
"}",
";",
"}"
] |
Provides a debounce service. That service is a function
used to debounce calls to a user-provided function.
@template {function(?): void} T args
@param {angular.ITimeoutService} $timeout Angular timeout service.
@return {import("ngeo/misc/debounce.js").miscDebounce<T>} The debounce function.
@ngdoc service
@ngname ngeoDebounce
@ngInject
@private
@hidden
|
[
"Provides",
"a",
"debounce",
"service",
".",
"That",
"service",
"is",
"a",
"function",
"used",
"to",
"debounce",
"calls",
"to",
"a",
"user",
"-",
"provided",
"function",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/misc/debounce.js#L65-L71
|
16,637
|
camptocamp/ngeo
|
src/map/resizemap.js
|
mapResizeComponent
|
function mapResizeComponent($window) {
const /** @type {number} */ duration = 1000;
return {
restrict: 'A',
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
*/
link: (scope, element, attrs) => {
const attr = 'ngeoResizemap';
const prop = attrs[attr];
const map = scope.$eval(prop);
console.assert(map instanceof olMap);
const stateExpr = attrs['ngeoResizemapState'];
console.assert(stateExpr !== undefined);
let start;
let animationDelayKey;
const animationDelay = () => {
map.updateSize();
map.renderSync();
if (Date.now() - start < duration) {
animationDelayKey = $window.requestAnimationFrame(animationDelay);
}
};
// Make sure the map is resized when the animation ends.
// It may help in case the animation didn't start correctly.
element.on('transitionend', () => {
map.updateSize();
map.renderSync();
});
scope.$watch(stateExpr, (newVal, oldVal) => {
if (newVal != oldVal) {
start = Date.now();
$window.cancelAnimationFrame(animationDelayKey);
animationDelayKey = $window.requestAnimationFrame(animationDelay);
}
});
}
};
}
|
javascript
|
function mapResizeComponent($window) {
const /** @type {number} */ duration = 1000;
return {
restrict: 'A',
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
*/
link: (scope, element, attrs) => {
const attr = 'ngeoResizemap';
const prop = attrs[attr];
const map = scope.$eval(prop);
console.assert(map instanceof olMap);
const stateExpr = attrs['ngeoResizemapState'];
console.assert(stateExpr !== undefined);
let start;
let animationDelayKey;
const animationDelay = () => {
map.updateSize();
map.renderSync();
if (Date.now() - start < duration) {
animationDelayKey = $window.requestAnimationFrame(animationDelay);
}
};
// Make sure the map is resized when the animation ends.
// It may help in case the animation didn't start correctly.
element.on('transitionend', () => {
map.updateSize();
map.renderSync();
});
scope.$watch(stateExpr, (newVal, oldVal) => {
if (newVal != oldVal) {
start = Date.now();
$window.cancelAnimationFrame(animationDelayKey);
animationDelayKey = $window.requestAnimationFrame(animationDelay);
}
});
}
};
}
|
[
"function",
"mapResizeComponent",
"(",
"$window",
")",
"{",
"const",
"/** @type {number} */",
"duration",
"=",
"1000",
";",
"return",
"{",
"restrict",
":",
"'A'",
",",
"/**\n * @param {angular.IScope} scope Scope.\n * @param {JQuery} element Element.\n * @param {angular.IAttributes} attrs Attributes.\n */",
"link",
":",
"(",
"scope",
",",
"element",
",",
"attrs",
")",
"=>",
"{",
"const",
"attr",
"=",
"'ngeoResizemap'",
";",
"const",
"prop",
"=",
"attrs",
"[",
"attr",
"]",
";",
"const",
"map",
"=",
"scope",
".",
"$eval",
"(",
"prop",
")",
";",
"console",
".",
"assert",
"(",
"map",
"instanceof",
"olMap",
")",
";",
"const",
"stateExpr",
"=",
"attrs",
"[",
"'ngeoResizemapState'",
"]",
";",
"console",
".",
"assert",
"(",
"stateExpr",
"!==",
"undefined",
")",
";",
"let",
"start",
";",
"let",
"animationDelayKey",
";",
"const",
"animationDelay",
"=",
"(",
")",
"=>",
"{",
"map",
".",
"updateSize",
"(",
")",
";",
"map",
".",
"renderSync",
"(",
")",
";",
"if",
"(",
"Date",
".",
"now",
"(",
")",
"-",
"start",
"<",
"duration",
")",
"{",
"animationDelayKey",
"=",
"$window",
".",
"requestAnimationFrame",
"(",
"animationDelay",
")",
";",
"}",
"}",
";",
"// Make sure the map is resized when the animation ends.",
"// It may help in case the animation didn't start correctly.",
"element",
".",
"on",
"(",
"'transitionend'",
",",
"(",
")",
"=>",
"{",
"map",
".",
"updateSize",
"(",
")",
";",
"map",
".",
"renderSync",
"(",
")",
";",
"}",
")",
";",
"scope",
".",
"$watch",
"(",
"stateExpr",
",",
"(",
"newVal",
",",
"oldVal",
")",
"=>",
"{",
"if",
"(",
"newVal",
"!=",
"oldVal",
")",
"{",
"start",
"=",
"Date",
".",
"now",
"(",
")",
";",
"$window",
".",
"cancelAnimationFrame",
"(",
"animationDelayKey",
")",
";",
"animationDelayKey",
"=",
"$window",
".",
"requestAnimationFrame",
"(",
"animationDelay",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
";",
"}"
] |
Provides a directive that resizes the map in an animation loop
during 1 second when the value of "state" changes. This is especially useful
when changing the size of other elements with a transition leads to a change
of the map size.
Example:
<div ng-class="ctrl.open ? 'open' : 'close' ngeo-resizemap="ctrl.map"
ngeo-resizemap-state="open">
<div>
<input type="checkbox" ng-model="ctrl.open" />
See our live example: [../examples/animation.html](../examples/animation.html)
@param {angular.IWindowService} $window Angular window service.
@return {angular.IDirective} The directive specs.
@ngInject
@ngdoc directive
@ngname ngeoResizemap
|
[
"Provides",
"a",
"directive",
"that",
"resizes",
"the",
"map",
"in",
"an",
"animation",
"loop",
"during",
"1",
"second",
"when",
"the",
"value",
"of",
"state",
"changes",
".",
"This",
"is",
"especially",
"useful",
"when",
"changing",
"the",
"size",
"of",
"other",
"elements",
"with",
"a",
"transition",
"leads",
"to",
"a",
"change",
"of",
"the",
"map",
"size",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/map/resizemap.js#L32-L79
|
16,638
|
camptocamp/ngeo
|
src/statemanager/Location.js
|
LocationFactory
|
function LocationFactory($rootScope, $window) {
const history = $window.history;
const service = new StatemanagerLocation($window.location, $window.history);
let lastUri = service.getUriString();
$rootScope.$watch(() => {
const newUri = service.getUriString();
if (lastUri !== newUri) {
$rootScope.$evalAsync(() => {
lastUri = newUri;
if (history !== undefined && history.replaceState !== undefined) {
replaceState(history, newUri);
}
$rootScope.$broadcast('ngeoLocationChange');
});
}
});
return service;
}
|
javascript
|
function LocationFactory($rootScope, $window) {
const history = $window.history;
const service = new StatemanagerLocation($window.location, $window.history);
let lastUri = service.getUriString();
$rootScope.$watch(() => {
const newUri = service.getUriString();
if (lastUri !== newUri) {
$rootScope.$evalAsync(() => {
lastUri = newUri;
if (history !== undefined && history.replaceState !== undefined) {
replaceState(history, newUri);
}
$rootScope.$broadcast('ngeoLocationChange');
});
}
});
return service;
}
|
[
"function",
"LocationFactory",
"(",
"$rootScope",
",",
"$window",
")",
"{",
"const",
"history",
"=",
"$window",
".",
"history",
";",
"const",
"service",
"=",
"new",
"StatemanagerLocation",
"(",
"$window",
".",
"location",
",",
"$window",
".",
"history",
")",
";",
"let",
"lastUri",
"=",
"service",
".",
"getUriString",
"(",
")",
";",
"$rootScope",
".",
"$watch",
"(",
"(",
")",
"=>",
"{",
"const",
"newUri",
"=",
"service",
".",
"getUriString",
"(",
")",
";",
"if",
"(",
"lastUri",
"!==",
"newUri",
")",
"{",
"$rootScope",
".",
"$evalAsync",
"(",
"(",
")",
"=>",
"{",
"lastUri",
"=",
"newUri",
";",
"if",
"(",
"history",
"!==",
"undefined",
"&&",
"history",
".",
"replaceState",
"!==",
"undefined",
")",
"{",
"replaceState",
"(",
"history",
",",
"newUri",
")",
";",
"}",
"$rootScope",
".",
"$broadcast",
"(",
"'ngeoLocationChange'",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"return",
"service",
";",
"}"
] |
The factory creating the ngeo Location service.
@param {angular.IScope} $rootScope The root scope.
@param {angular.IWindowService} $window Angular window service.
@return {StatemanagerLocation} The ngeo location service.
@ngInject
@private
@hidden
|
[
"The",
"factory",
"creating",
"the",
"ngeo",
"Location",
"service",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/statemanager/Location.js#L353-L372
|
16,639
|
camptocamp/ngeo
|
contribs/gmf/src/objectediting/coordinate.js
|
toXY
|
function toXY(coordinates, nesting) {
if (nesting === 0) {
return /** @type {Array<T>} */(coordinatesToXY0(/** @type {Coordinate} */(coordinates)));
} else {
for (let i = 0, ii = coordinates.length; i < ii; i++) {
// @ts-ignore: TypeScript is not able to do recurtion with deferent type in generic
coordinates[i] = toXY(coordinates[i], nesting - 1);
}
}
return coordinates;
}
|
javascript
|
function toXY(coordinates, nesting) {
if (nesting === 0) {
return /** @type {Array<T>} */(coordinatesToXY0(/** @type {Coordinate} */(coordinates)));
} else {
for (let i = 0, ii = coordinates.length; i < ii; i++) {
// @ts-ignore: TypeScript is not able to do recurtion with deferent type in generic
coordinates[i] = toXY(coordinates[i], nesting - 1);
}
}
return coordinates;
}
|
[
"function",
"toXY",
"(",
"coordinates",
",",
"nesting",
")",
"{",
"if",
"(",
"nesting",
"===",
"0",
")",
"{",
"return",
"/** @type {Array<T>} */",
"(",
"coordinatesToXY0",
"(",
"/** @type {Coordinate} */",
"(",
"coordinates",
")",
")",
")",
";",
"}",
"else",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"ii",
"=",
"coordinates",
".",
"length",
";",
"i",
"<",
"ii",
";",
"i",
"++",
")",
"{",
"// @ts-ignore: TypeScript is not able to do recurtion with deferent type in generic",
"coordinates",
"[",
"i",
"]",
"=",
"toXY",
"(",
"coordinates",
"[",
"i",
"]",
",",
"nesting",
"-",
"1",
")",
";",
"}",
"}",
"return",
"coordinates",
";",
"}"
] |
Convert a given coordinate or list of coordinates of any 'nesting' level
to XY, i.e. remove any extra dimensions to the coordinates and keep only 2.
@template {number|Coordinate|Array<Coordinate>|Array<Array<Coordinate>>} T
@param {Array<T>} coordinates Coordinates
@param {number} nesting Nesting level.
@return {Array<T>} Converted coordinates.
@private
@hidden
|
[
"Convert",
"a",
"given",
"coordinate",
"or",
"list",
"of",
"coordinates",
"of",
"any",
"nesting",
"level",
"to",
"XY",
"i",
".",
"e",
".",
"remove",
"any",
"extra",
"dimensions",
"to",
"the",
"coordinates",
"and",
"keep",
"only",
"2",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/contribs/gmf/src/objectediting/coordinate.js#L34-L44
|
16,640
|
camptocamp/ngeo
|
src/map/component.js
|
mapComponent
|
function mapComponent($window) {
return {
restrict: 'A',
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
*/
link: (scope, element, attrs) => {
// Get the 'ol.Map' object from attributes and manage it accordingly
const attr = 'ngeoMap';
const prop = attrs[attr];
const map = scope.$eval(prop);
console.assert(map instanceof olMap);
map.setTarget(element[0]);
// Get the 'window resize' attributes, which are optional. If defined,
// the browser window 'resize' event is listened to update the size of
// the map when fired. A transition option is also available to let any
// animation that may occur on the div of the map to smootly resize the
// map while in progress.
const manageResizeAttr = 'ngeoMapManageResize';
const manageResizeProp = attrs[manageResizeAttr];
const manageResize = scope.$eval(manageResizeProp);
if (manageResize) {
const resizeTransitionAttr = 'ngeoMapResizeTransition';
const resizeTransitionProp = attrs[resizeTransitionAttr];
const resizeTransition = /** @type {number|undefined} */ (
scope.$eval(resizeTransitionProp));
olEvents.listen(
$window,
'resize',
() => {
if (resizeTransition) {
// Resize with transition
const start = Date.now();
let loop = true;
const adjustSize = function() {
map.updateSize();
map.renderSync();
if (loop) {
$window.requestAnimationFrame(adjustSize);
}
if (Date.now() - start > resizeTransition) {
loop = false;
}
};
adjustSize();
} else {
// A single plain resize
map.updateSize();
}
}
);
}
}
};
}
|
javascript
|
function mapComponent($window) {
return {
restrict: 'A',
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
*/
link: (scope, element, attrs) => {
// Get the 'ol.Map' object from attributes and manage it accordingly
const attr = 'ngeoMap';
const prop = attrs[attr];
const map = scope.$eval(prop);
console.assert(map instanceof olMap);
map.setTarget(element[0]);
// Get the 'window resize' attributes, which are optional. If defined,
// the browser window 'resize' event is listened to update the size of
// the map when fired. A transition option is also available to let any
// animation that may occur on the div of the map to smootly resize the
// map while in progress.
const manageResizeAttr = 'ngeoMapManageResize';
const manageResizeProp = attrs[manageResizeAttr];
const manageResize = scope.$eval(manageResizeProp);
if (manageResize) {
const resizeTransitionAttr = 'ngeoMapResizeTransition';
const resizeTransitionProp = attrs[resizeTransitionAttr];
const resizeTransition = /** @type {number|undefined} */ (
scope.$eval(resizeTransitionProp));
olEvents.listen(
$window,
'resize',
() => {
if (resizeTransition) {
// Resize with transition
const start = Date.now();
let loop = true;
const adjustSize = function() {
map.updateSize();
map.renderSync();
if (loop) {
$window.requestAnimationFrame(adjustSize);
}
if (Date.now() - start > resizeTransition) {
loop = false;
}
};
adjustSize();
} else {
// A single plain resize
map.updateSize();
}
}
);
}
}
};
}
|
[
"function",
"mapComponent",
"(",
"$window",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"/**\n * @param {angular.IScope} scope Scope.\n * @param {JQuery} element Element.\n * @param {angular.IAttributes} attrs Attributes.\n */",
"link",
":",
"(",
"scope",
",",
"element",
",",
"attrs",
")",
"=>",
"{",
"// Get the 'ol.Map' object from attributes and manage it accordingly",
"const",
"attr",
"=",
"'ngeoMap'",
";",
"const",
"prop",
"=",
"attrs",
"[",
"attr",
"]",
";",
"const",
"map",
"=",
"scope",
".",
"$eval",
"(",
"prop",
")",
";",
"console",
".",
"assert",
"(",
"map",
"instanceof",
"olMap",
")",
";",
"map",
".",
"setTarget",
"(",
"element",
"[",
"0",
"]",
")",
";",
"// Get the 'window resize' attributes, which are optional. If defined,",
"// the browser window 'resize' event is listened to update the size of",
"// the map when fired. A transition option is also available to let any",
"// animation that may occur on the div of the map to smootly resize the",
"// map while in progress.",
"const",
"manageResizeAttr",
"=",
"'ngeoMapManageResize'",
";",
"const",
"manageResizeProp",
"=",
"attrs",
"[",
"manageResizeAttr",
"]",
";",
"const",
"manageResize",
"=",
"scope",
".",
"$eval",
"(",
"manageResizeProp",
")",
";",
"if",
"(",
"manageResize",
")",
"{",
"const",
"resizeTransitionAttr",
"=",
"'ngeoMapResizeTransition'",
";",
"const",
"resizeTransitionProp",
"=",
"attrs",
"[",
"resizeTransitionAttr",
"]",
";",
"const",
"resizeTransition",
"=",
"/** @type {number|undefined} */",
"(",
"scope",
".",
"$eval",
"(",
"resizeTransitionProp",
")",
")",
";",
"olEvents",
".",
"listen",
"(",
"$window",
",",
"'resize'",
",",
"(",
")",
"=>",
"{",
"if",
"(",
"resizeTransition",
")",
"{",
"// Resize with transition",
"const",
"start",
"=",
"Date",
".",
"now",
"(",
")",
";",
"let",
"loop",
"=",
"true",
";",
"const",
"adjustSize",
"=",
"function",
"(",
")",
"{",
"map",
".",
"updateSize",
"(",
")",
";",
"map",
".",
"renderSync",
"(",
")",
";",
"if",
"(",
"loop",
")",
"{",
"$window",
".",
"requestAnimationFrame",
"(",
"adjustSize",
")",
";",
"}",
"if",
"(",
"Date",
".",
"now",
"(",
")",
"-",
"start",
">",
"resizeTransition",
")",
"{",
"loop",
"=",
"false",
";",
"}",
"}",
";",
"adjustSize",
"(",
")",
";",
"}",
"else",
"{",
"// A single plain resize",
"map",
".",
"updateSize",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
"}",
";",
"}"
] |
Provides a directive used to insert a user-defined OpenLayers
map in the DOM. The directive does not create an isolate scope.
Examples:
Simple:
<div ngeo-map="ctrl.map"></div>
Manage window resizing:
<div
ngeo-map="ctrl.map"
ngeo-map-manage-resize="ctrl.manageResize"
ngeo-map-resize-transition="ctrl.resizeTransition">
</div>
See our live examples:
[../examples/permalink.html](../examples/permalink.html)
[../examples/simple.html](../examples/simple.html)
@htmlAttribute {import("ol/Map.js").default} ngeo-map The map.
@param {angular.IWindowService} $window The Angular $window service.
@return {angular.IDirective} Directive Definition Object.
@ngdoc directive
@ngname ngeoMap
@ngInject
|
[
"Provides",
"a",
"directive",
"used",
"to",
"insert",
"a",
"user",
"-",
"defined",
"OpenLayers",
"map",
"in",
"the",
"DOM",
".",
"The",
"directive",
"does",
"not",
"create",
"an",
"isolate",
"scope",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/map/component.js#L42-L104
|
16,641
|
camptocamp/ngeo
|
src/interaction/Measure.js
|
handleEvent_
|
function handleEvent_(evt) {
if (evt.type != 'pointermove' || evt.dragging) {
return true;
}
const helpMsg = this.sketchFeature === null ? this.startMsg : this.continueMsg;
if (!helpMsg) {
throw new Error('Missing helpMsg');
}
if (this.displayHelpTooltip_) {
if (!this.helpTooltipElement_) {
throw new Error('Missing helpTooltipElement');
}
if (!this.helpTooltipOverlay_) {
throw new Error('Missing helpTooltipOverlay');
}
olDom.removeChildren(this.helpTooltipElement_);
this.helpTooltipElement_.appendChild(helpMsg);
this.helpTooltipOverlay_.setPosition(evt.coordinate);
}
return true;
}
|
javascript
|
function handleEvent_(evt) {
if (evt.type != 'pointermove' || evt.dragging) {
return true;
}
const helpMsg = this.sketchFeature === null ? this.startMsg : this.continueMsg;
if (!helpMsg) {
throw new Error('Missing helpMsg');
}
if (this.displayHelpTooltip_) {
if (!this.helpTooltipElement_) {
throw new Error('Missing helpTooltipElement');
}
if (!this.helpTooltipOverlay_) {
throw new Error('Missing helpTooltipOverlay');
}
olDom.removeChildren(this.helpTooltipElement_);
this.helpTooltipElement_.appendChild(helpMsg);
this.helpTooltipOverlay_.setPosition(evt.coordinate);
}
return true;
}
|
[
"function",
"handleEvent_",
"(",
"evt",
")",
"{",
"if",
"(",
"evt",
".",
"type",
"!=",
"'pointermove'",
"||",
"evt",
".",
"dragging",
")",
"{",
"return",
"true",
";",
"}",
"const",
"helpMsg",
"=",
"this",
".",
"sketchFeature",
"===",
"null",
"?",
"this",
".",
"startMsg",
":",
"this",
".",
"continueMsg",
";",
"if",
"(",
"!",
"helpMsg",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing helpMsg'",
")",
";",
"}",
"if",
"(",
"this",
".",
"displayHelpTooltip_",
")",
"{",
"if",
"(",
"!",
"this",
".",
"helpTooltipElement_",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing helpTooltipElement'",
")",
";",
"}",
"if",
"(",
"!",
"this",
".",
"helpTooltipOverlay_",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing helpTooltipOverlay'",
")",
";",
"}",
"olDom",
".",
"removeChildren",
"(",
"this",
".",
"helpTooltipElement_",
")",
";",
"this",
".",
"helpTooltipElement_",
".",
"appendChild",
"(",
"helpMsg",
")",
";",
"this",
".",
"helpTooltipOverlay_",
".",
"setPosition",
"(",
"evt",
".",
"coordinate",
")",
";",
"}",
"return",
"true",
";",
"}"
] |
Handle map browser event.
@param {import("ol/MapBrowserEvent.js").default} evt Map browser event.
@return {boolean} `false` if event propagation should be stopped.
@private
@hidden
@this {Measure}
|
[
"Handle",
"map",
"browser",
"event",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/interaction/Measure.js#L576-L599
|
16,642
|
camptocamp/ngeo
|
src/misc/controlComponent.js
|
controlComponent
|
function controlComponent() {
return {
restrict: 'A',
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
*/
link: (scope, element, attrs) => {
const control = /** @type {import('ol/control/Control.js').default} */
(scope.$eval(attrs['ngeoControl']));
console.assert(control instanceof olControlControl);
const map = /** @type {import('ol/Map.js').default} */
(scope.$eval(attrs['ngeoControlMap']));
console.assert(map instanceof olMap);
control.setTarget(element[0]);
map.addControl(control);
}
};
}
|
javascript
|
function controlComponent() {
return {
restrict: 'A',
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
*/
link: (scope, element, attrs) => {
const control = /** @type {import('ol/control/Control.js').default} */
(scope.$eval(attrs['ngeoControl']));
console.assert(control instanceof olControlControl);
const map = /** @type {import('ol/Map.js').default} */
(scope.$eval(attrs['ngeoControlMap']));
console.assert(map instanceof olMap);
control.setTarget(element[0]);
map.addControl(control);
}
};
}
|
[
"function",
"controlComponent",
"(",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"/**\n * @param {angular.IScope} scope Scope.\n * @param {JQuery} element Element.\n * @param {angular.IAttributes} attrs Attributes.\n */",
"link",
":",
"(",
"scope",
",",
"element",
",",
"attrs",
")",
"=>",
"{",
"const",
"control",
"=",
"/** @type {import('ol/control/Control.js').default} */",
"(",
"scope",
".",
"$eval",
"(",
"attrs",
"[",
"'ngeoControl'",
"]",
")",
")",
";",
"console",
".",
"assert",
"(",
"control",
"instanceof",
"olControlControl",
")",
";",
"const",
"map",
"=",
"/** @type {import('ol/Map.js').default} */",
"(",
"scope",
".",
"$eval",
"(",
"attrs",
"[",
"'ngeoControlMap'",
"]",
")",
")",
";",
"console",
".",
"assert",
"(",
"map",
"instanceof",
"olMap",
")",
";",
"control",
".",
"setTarget",
"(",
"element",
"[",
"0",
"]",
")",
";",
"map",
".",
"addControl",
"(",
"control",
")",
";",
"}",
"}",
";",
"}"
] |
Provides a directive that can be used to add a control to the map
using a DOM element.
Example:
<div ngeo-control="ctrl.control" ngeo-control-map="ctrl.map"></div>
The expression passed to "ngeo-control" should evaluate to a control
instance, and the expression passed to "ngeo-control-map" should
evaluate to a map instance.
See our live example: [../examples/control.html](../examples/control.html)
@htmlAttribute {import("ol/Map.js").default} ngeo-control-map The map.
@return {angular.IDirective} The directive specs.
@ngInject
@ngdoc directive
@ngname ngeoControl
|
[
"Provides",
"a",
"directive",
"that",
"can",
"be",
"used",
"to",
"add",
"a",
"control",
"to",
"the",
"map",
"using",
"a",
"DOM",
"element",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/misc/controlComponent.js#L33-L55
|
16,643
|
camptocamp/ngeo
|
src/query/bboxQueryComponent.js
|
queryBboxComponent
|
function queryBboxComponent($rootScope, ngeoMapQuerent, ngeoQueryKeyboard) {
return {
restrict: 'A',
scope: false,
link: (scope, elem, attrs) => {
/**
* @type {import("ol/Map.js").default}
*/
const map = scope.$eval(attrs['ngeoBboxQueryMap']);
let active;
const interaction = new olInteractionDragBox({
condition: platformModifierKeyOnly,
onBoxEnd: VOID
});
/**
* Called when a bbox is drawn while this controller is active. Issue
* a request to the query service using the extent that was drawn.
* @param {!olInteractionDragBox} interaction Drag box interaction
*/
const handleBoxEnd = function(interaction) {
const action = ngeoQueryKeyboard.action;
const extent = interaction.getGeometry().getExtent();
const limit = scope.$eval(attrs['ngeoBboxQueryLimit']);
ngeoMapQuerent.issue({
action,
extent,
limit,
map
});
};
interaction.on('boxend', handleBoxEnd.bind(undefined, interaction));
// watch 'active' property -> activate/deactivate accordingly
scope.$watch(attrs['ngeoBboxQueryActive'],
(newVal, oldVal) => {
active = newVal;
if (newVal) {
// activate
map.addInteraction(interaction);
} else {
// deactivate
map.removeInteraction(interaction);
if (scope.$eval(attrs['ngeoBboxQueryAutoclear']) !== false) {
ngeoMapQuerent.clear();
}
}
}
);
// This second interaction is not given any condition and is
// automatically added to the map while the user presses the
// keys to either ADD or REMOVE
const interactionWithoutCondition = new olInteractionDragBox({
onBoxEnd: VOID
});
interactionWithoutCondition.on(
'boxend', handleBoxEnd.bind(undefined, interactionWithoutCondition));
let added = false;
$rootScope.$watch(
() => ngeoQueryKeyboard.action,
(newVal, oldVal) => {
// No need to do anything if directive is not active
if (!active) {
return;
}
if (newVal === ngeoQueryAction.REPLACE) {
if (added) {
map.removeInteraction(interactionWithoutCondition);
added = false;
}
} else {
if (!added) {
map.addInteraction(interactionWithoutCondition);
added = true;
}
}
}
);
}
};
}
|
javascript
|
function queryBboxComponent($rootScope, ngeoMapQuerent, ngeoQueryKeyboard) {
return {
restrict: 'A',
scope: false,
link: (scope, elem, attrs) => {
/**
* @type {import("ol/Map.js").default}
*/
const map = scope.$eval(attrs['ngeoBboxQueryMap']);
let active;
const interaction = new olInteractionDragBox({
condition: platformModifierKeyOnly,
onBoxEnd: VOID
});
/**
* Called when a bbox is drawn while this controller is active. Issue
* a request to the query service using the extent that was drawn.
* @param {!olInteractionDragBox} interaction Drag box interaction
*/
const handleBoxEnd = function(interaction) {
const action = ngeoQueryKeyboard.action;
const extent = interaction.getGeometry().getExtent();
const limit = scope.$eval(attrs['ngeoBboxQueryLimit']);
ngeoMapQuerent.issue({
action,
extent,
limit,
map
});
};
interaction.on('boxend', handleBoxEnd.bind(undefined, interaction));
// watch 'active' property -> activate/deactivate accordingly
scope.$watch(attrs['ngeoBboxQueryActive'],
(newVal, oldVal) => {
active = newVal;
if (newVal) {
// activate
map.addInteraction(interaction);
} else {
// deactivate
map.removeInteraction(interaction);
if (scope.$eval(attrs['ngeoBboxQueryAutoclear']) !== false) {
ngeoMapQuerent.clear();
}
}
}
);
// This second interaction is not given any condition and is
// automatically added to the map while the user presses the
// keys to either ADD or REMOVE
const interactionWithoutCondition = new olInteractionDragBox({
onBoxEnd: VOID
});
interactionWithoutCondition.on(
'boxend', handleBoxEnd.bind(undefined, interactionWithoutCondition));
let added = false;
$rootScope.$watch(
() => ngeoQueryKeyboard.action,
(newVal, oldVal) => {
// No need to do anything if directive is not active
if (!active) {
return;
}
if (newVal === ngeoQueryAction.REPLACE) {
if (added) {
map.removeInteraction(interactionWithoutCondition);
added = false;
}
} else {
if (!added) {
map.addInteraction(interactionWithoutCondition);
added = true;
}
}
}
);
}
};
}
|
[
"function",
"queryBboxComponent",
"(",
"$rootScope",
",",
"ngeoMapQuerent",
",",
"ngeoQueryKeyboard",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"scope",
":",
"false",
",",
"link",
":",
"(",
"scope",
",",
"elem",
",",
"attrs",
")",
"=>",
"{",
"/**\n * @type {import(\"ol/Map.js\").default}\n */",
"const",
"map",
"=",
"scope",
".",
"$eval",
"(",
"attrs",
"[",
"'ngeoBboxQueryMap'",
"]",
")",
";",
"let",
"active",
";",
"const",
"interaction",
"=",
"new",
"olInteractionDragBox",
"(",
"{",
"condition",
":",
"platformModifierKeyOnly",
",",
"onBoxEnd",
":",
"VOID",
"}",
")",
";",
"/**\n * Called when a bbox is drawn while this controller is active. Issue\n * a request to the query service using the extent that was drawn.\n * @param {!olInteractionDragBox} interaction Drag box interaction\n */",
"const",
"handleBoxEnd",
"=",
"function",
"(",
"interaction",
")",
"{",
"const",
"action",
"=",
"ngeoQueryKeyboard",
".",
"action",
";",
"const",
"extent",
"=",
"interaction",
".",
"getGeometry",
"(",
")",
".",
"getExtent",
"(",
")",
";",
"const",
"limit",
"=",
"scope",
".",
"$eval",
"(",
"attrs",
"[",
"'ngeoBboxQueryLimit'",
"]",
")",
";",
"ngeoMapQuerent",
".",
"issue",
"(",
"{",
"action",
",",
"extent",
",",
"limit",
",",
"map",
"}",
")",
";",
"}",
";",
"interaction",
".",
"on",
"(",
"'boxend'",
",",
"handleBoxEnd",
".",
"bind",
"(",
"undefined",
",",
"interaction",
")",
")",
";",
"// watch 'active' property -> activate/deactivate accordingly",
"scope",
".",
"$watch",
"(",
"attrs",
"[",
"'ngeoBboxQueryActive'",
"]",
",",
"(",
"newVal",
",",
"oldVal",
")",
"=>",
"{",
"active",
"=",
"newVal",
";",
"if",
"(",
"newVal",
")",
"{",
"// activate",
"map",
".",
"addInteraction",
"(",
"interaction",
")",
";",
"}",
"else",
"{",
"// deactivate",
"map",
".",
"removeInteraction",
"(",
"interaction",
")",
";",
"if",
"(",
"scope",
".",
"$eval",
"(",
"attrs",
"[",
"'ngeoBboxQueryAutoclear'",
"]",
")",
"!==",
"false",
")",
"{",
"ngeoMapQuerent",
".",
"clear",
"(",
")",
";",
"}",
"}",
"}",
")",
";",
"// This second interaction is not given any condition and is",
"// automatically added to the map while the user presses the",
"// keys to either ADD or REMOVE",
"const",
"interactionWithoutCondition",
"=",
"new",
"olInteractionDragBox",
"(",
"{",
"onBoxEnd",
":",
"VOID",
"}",
")",
";",
"interactionWithoutCondition",
".",
"on",
"(",
"'boxend'",
",",
"handleBoxEnd",
".",
"bind",
"(",
"undefined",
",",
"interactionWithoutCondition",
")",
")",
";",
"let",
"added",
"=",
"false",
";",
"$rootScope",
".",
"$watch",
"(",
"(",
")",
"=>",
"ngeoQueryKeyboard",
".",
"action",
",",
"(",
"newVal",
",",
"oldVal",
")",
"=>",
"{",
"// No need to do anything if directive is not active",
"if",
"(",
"!",
"active",
")",
"{",
"return",
";",
"}",
"if",
"(",
"newVal",
"===",
"ngeoQueryAction",
".",
"REPLACE",
")",
"{",
"if",
"(",
"added",
")",
"{",
"map",
".",
"removeInteraction",
"(",
"interactionWithoutCondition",
")",
";",
"added",
"=",
"false",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"!",
"added",
")",
"{",
"map",
".",
"addInteraction",
"(",
"interactionWithoutCondition",
")",
";",
"added",
"=",
"true",
";",
"}",
"}",
"}",
")",
";",
"}",
"}",
";",
"}"
] |
Provides a "bbox query" directive.
This directive is responsible of binding a map and the ngeo query service
together. While active, drawing a bbox while CTRL or the 'meta' key is pressed
issues a request to the query service.
This directive doesn't require to be rendered in a visible DOM element, but
it could be used with a ngeo-btn to manage the activation of the directive.
See below an example without any use of UI:
Example:
<span
ngeo-bbox-query=""
ngeo-bbox-query-map="::ctrl.map"
ngeo-bbox-query-limit="50"
ngeo-bbox-query-active="ctrl.queryActive">
ngeo-bbox-query-autoclear="ctrl.queryAutoClear">
</span>
See the live example: [../examples/bboxquery.html](../examples/bboxquery.html)
@param {angular.IScope} $rootScope The root scope.
@param {import("ngeo/query/MapQuerent.js").MapQuerent} ngeoMapQuerent The ngeo map querent service.
@param {import("ngeo/query/Keyboard.js").QueryKeyboard} ngeoQueryKeyboard The ngeo query keyboard service.
@return {angular.IDirective} The Directive Definition Object.
@ngInject
@ngdoc directive
@ngname ngeoBboxQuery
|
[
"Provides",
"a",
"bbox",
"query",
"directive",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/query/bboxQueryComponent.js#L52-L136
|
16,644
|
camptocamp/ngeo
|
src/query/bboxQueryComponent.js
|
function(interaction) {
const action = ngeoQueryKeyboard.action;
const extent = interaction.getGeometry().getExtent();
const limit = scope.$eval(attrs['ngeoBboxQueryLimit']);
ngeoMapQuerent.issue({
action,
extent,
limit,
map
});
}
|
javascript
|
function(interaction) {
const action = ngeoQueryKeyboard.action;
const extent = interaction.getGeometry().getExtent();
const limit = scope.$eval(attrs['ngeoBboxQueryLimit']);
ngeoMapQuerent.issue({
action,
extent,
limit,
map
});
}
|
[
"function",
"(",
"interaction",
")",
"{",
"const",
"action",
"=",
"ngeoQueryKeyboard",
".",
"action",
";",
"const",
"extent",
"=",
"interaction",
".",
"getGeometry",
"(",
")",
".",
"getExtent",
"(",
")",
";",
"const",
"limit",
"=",
"scope",
".",
"$eval",
"(",
"attrs",
"[",
"'ngeoBboxQueryLimit'",
"]",
")",
";",
"ngeoMapQuerent",
".",
"issue",
"(",
"{",
"action",
",",
"extent",
",",
"limit",
",",
"map",
"}",
")",
";",
"}"
] |
Called when a bbox is drawn while this controller is active. Issue
a request to the query service using the extent that was drawn.
@param {!olInteractionDragBox} interaction Drag box interaction
|
[
"Called",
"when",
"a",
"bbox",
"is",
"drawn",
"while",
"this",
"controller",
"is",
"active",
".",
"Issue",
"a",
"request",
"to",
"the",
"query",
"service",
"using",
"the",
"extent",
"that",
"was",
"drawn",
"."
] |
0d9d84b70199bc3de9cf367a0b406c7b488d2077
|
https://github.com/camptocamp/ngeo/blob/0d9d84b70199bc3de9cf367a0b406c7b488d2077/src/query/bboxQueryComponent.js#L74-L84
|
|
16,645
|
libp2p/js-libp2p-switch
|
src/transport.js
|
ourAddresses
|
function ourAddresses (peerInfo) {
const ourPeerId = peerInfo.id.toB58String()
return peerInfo.multiaddrs.toArray()
.reduce((ourAddrs, addr) => {
const peerId = addr.getPeerId()
addr = addr.toString()
const otherAddr = peerId
? addr.slice(0, addr.lastIndexOf(`/ipfs/${peerId}`))
: `${addr}/ipfs/${ourPeerId}`
return ourAddrs.concat([addr, otherAddr])
}, [])
.filter(a => Boolean(a))
.concat(`/ipfs/${ourPeerId}`)
}
|
javascript
|
function ourAddresses (peerInfo) {
const ourPeerId = peerInfo.id.toB58String()
return peerInfo.multiaddrs.toArray()
.reduce((ourAddrs, addr) => {
const peerId = addr.getPeerId()
addr = addr.toString()
const otherAddr = peerId
? addr.slice(0, addr.lastIndexOf(`/ipfs/${peerId}`))
: `${addr}/ipfs/${ourPeerId}`
return ourAddrs.concat([addr, otherAddr])
}, [])
.filter(a => Boolean(a))
.concat(`/ipfs/${ourPeerId}`)
}
|
[
"function",
"ourAddresses",
"(",
"peerInfo",
")",
"{",
"const",
"ourPeerId",
"=",
"peerInfo",
".",
"id",
".",
"toB58String",
"(",
")",
"return",
"peerInfo",
".",
"multiaddrs",
".",
"toArray",
"(",
")",
".",
"reduce",
"(",
"(",
"ourAddrs",
",",
"addr",
")",
"=>",
"{",
"const",
"peerId",
"=",
"addr",
".",
"getPeerId",
"(",
")",
"addr",
"=",
"addr",
".",
"toString",
"(",
")",
"const",
"otherAddr",
"=",
"peerId",
"?",
"addr",
".",
"slice",
"(",
"0",
",",
"addr",
".",
"lastIndexOf",
"(",
"`",
"${",
"peerId",
"}",
"`",
")",
")",
":",
"`",
"${",
"addr",
"}",
"${",
"ourPeerId",
"}",
"`",
"return",
"ourAddrs",
".",
"concat",
"(",
"[",
"addr",
",",
"otherAddr",
"]",
")",
"}",
",",
"[",
"]",
")",
".",
"filter",
"(",
"a",
"=>",
"Boolean",
"(",
"a",
")",
")",
".",
"concat",
"(",
"`",
"${",
"ourPeerId",
"}",
"`",
")",
"}"
] |
Expand addresses in peer info into array of addresses with and without peer
ID suffix.
@param {PeerInfo} peerInfo Our peer info object
@returns {String[]}
|
[
"Expand",
"addresses",
"in",
"peer",
"info",
"into",
"array",
"of",
"addresses",
"with",
"and",
"without",
"peer",
"ID",
"suffix",
"."
] |
f879cfc680521de81fef0bfc4a11e96623711712
|
https://github.com/libp2p/js-libp2p-switch/blob/f879cfc680521de81fef0bfc4a11e96623711712/src/transport.js#L236-L249
|
16,646
|
libp2p/js-libp2p-switch
|
src/get-peer-info.js
|
getPeerInfo
|
function getPeerInfo (peer, peerBook) {
let peerInfo
// Already a PeerInfo instance,
// add to the peer book and return the latest value
if (PeerInfo.isPeerInfo(peer)) {
return peerBook.put(peer)
}
// Attempt to convert from Multiaddr instance (not string)
if (multiaddr.isMultiaddr(peer)) {
const peerIdB58Str = peer.getPeerId()
try {
peerInfo = peerBook.get(peerIdB58Str)
} catch (err) {
peerInfo = new PeerInfo(PeerId.createFromB58String(peerIdB58Str))
}
peerInfo.multiaddrs.add(peer)
return peerInfo
}
// Attempt to convert from PeerId
if (PeerId.isPeerId(peer)) {
const peerIdB58Str = peer.toB58String()
try {
return peerBook.get(peerIdB58Str)
} catch (err) {
throw new Error(`Couldnt get PeerInfo for ${peerIdB58Str}`)
}
}
throw new Error('peer type not recognized')
}
|
javascript
|
function getPeerInfo (peer, peerBook) {
let peerInfo
// Already a PeerInfo instance,
// add to the peer book and return the latest value
if (PeerInfo.isPeerInfo(peer)) {
return peerBook.put(peer)
}
// Attempt to convert from Multiaddr instance (not string)
if (multiaddr.isMultiaddr(peer)) {
const peerIdB58Str = peer.getPeerId()
try {
peerInfo = peerBook.get(peerIdB58Str)
} catch (err) {
peerInfo = new PeerInfo(PeerId.createFromB58String(peerIdB58Str))
}
peerInfo.multiaddrs.add(peer)
return peerInfo
}
// Attempt to convert from PeerId
if (PeerId.isPeerId(peer)) {
const peerIdB58Str = peer.toB58String()
try {
return peerBook.get(peerIdB58Str)
} catch (err) {
throw new Error(`Couldnt get PeerInfo for ${peerIdB58Str}`)
}
}
throw new Error('peer type not recognized')
}
|
[
"function",
"getPeerInfo",
"(",
"peer",
",",
"peerBook",
")",
"{",
"let",
"peerInfo",
"// Already a PeerInfo instance,",
"// add to the peer book and return the latest value",
"if",
"(",
"PeerInfo",
".",
"isPeerInfo",
"(",
"peer",
")",
")",
"{",
"return",
"peerBook",
".",
"put",
"(",
"peer",
")",
"}",
"// Attempt to convert from Multiaddr instance (not string)",
"if",
"(",
"multiaddr",
".",
"isMultiaddr",
"(",
"peer",
")",
")",
"{",
"const",
"peerIdB58Str",
"=",
"peer",
".",
"getPeerId",
"(",
")",
"try",
"{",
"peerInfo",
"=",
"peerBook",
".",
"get",
"(",
"peerIdB58Str",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"peerInfo",
"=",
"new",
"PeerInfo",
"(",
"PeerId",
".",
"createFromB58String",
"(",
"peerIdB58Str",
")",
")",
"}",
"peerInfo",
".",
"multiaddrs",
".",
"add",
"(",
"peer",
")",
"return",
"peerInfo",
"}",
"// Attempt to convert from PeerId",
"if",
"(",
"PeerId",
".",
"isPeerId",
"(",
"peer",
")",
")",
"{",
"const",
"peerIdB58Str",
"=",
"peer",
".",
"toB58String",
"(",
")",
"try",
"{",
"return",
"peerBook",
".",
"get",
"(",
"peerIdB58Str",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"peerIdB58Str",
"}",
"`",
")",
"}",
"}",
"throw",
"new",
"Error",
"(",
"'peer type not recognized'",
")",
"}"
] |
Helper method to check the data type of peer and convert it to PeerInfo
@param {PeerInfo|Multiaddr|PeerId} peer
@param {PeerBook} peerBook
@throws {InvalidPeerType}
@returns {PeerInfo}
|
[
"Helper",
"method",
"to",
"check",
"the",
"data",
"type",
"of",
"peer",
"and",
"convert",
"it",
"to",
"PeerInfo"
] |
f879cfc680521de81fef0bfc4a11e96623711712
|
https://github.com/libp2p/js-libp2p-switch/blob/f879cfc680521de81fef0bfc4a11e96623711712/src/get-peer-info.js#L15-L47
|
16,647
|
libp2p/js-libp2p-switch
|
src/dialer/index.js
|
connect
|
function connect (peerInfo, options, callback) {
if (typeof options === 'function') {
callback = options
options = null
}
options = { useFSM: false, priority: PRIORITY_LOW, ...options }
_dial({ peerInfo, protocol: null, options, callback })
}
|
javascript
|
function connect (peerInfo, options, callback) {
if (typeof options === 'function') {
callback = options
options = null
}
options = { useFSM: false, priority: PRIORITY_LOW, ...options }
_dial({ peerInfo, protocol: null, options, callback })
}
|
[
"function",
"connect",
"(",
"peerInfo",
",",
"options",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"callback",
"=",
"options",
"options",
"=",
"null",
"}",
"options",
"=",
"{",
"useFSM",
":",
"false",
",",
"priority",
":",
"PRIORITY_LOW",
",",
"...",
"options",
"}",
"_dial",
"(",
"{",
"peerInfo",
",",
"protocol",
":",
"null",
",",
"options",
",",
"callback",
"}",
")",
"}"
] |
Attempts to establish a connection to the given `peerInfo` at
a lower priority than a standard dial.
@param {PeerInfo} peerInfo
@param {object} options
@param {boolean} options.useFSM Whether or not to return a `ConnectionFSM`. Defaults to false.
@param {number} options.priority Lowest priority goes first. Defaults to 20.
@param {function(Error, Connection)} callback
|
[
"Attempts",
"to",
"establish",
"a",
"connection",
"to",
"the",
"given",
"peerInfo",
"at",
"a",
"lower",
"priority",
"than",
"a",
"standard",
"dial",
"."
] |
f879cfc680521de81fef0bfc4a11e96623711712
|
https://github.com/libp2p/js-libp2p-switch/blob/f879cfc680521de81fef0bfc4a11e96623711712/src/dialer/index.js#L78-L85
|
16,648
|
libp2p/js-libp2p-switch
|
src/dialer/index.js
|
dialFSM
|
function dialFSM (peerInfo, protocol, callback) {
_dial({ peerInfo, protocol, options: { useFSM: true, priority: PRIORITY_HIGH }, callback })
}
|
javascript
|
function dialFSM (peerInfo, protocol, callback) {
_dial({ peerInfo, protocol, options: { useFSM: true, priority: PRIORITY_HIGH }, callback })
}
|
[
"function",
"dialFSM",
"(",
"peerInfo",
",",
"protocol",
",",
"callback",
")",
"{",
"_dial",
"(",
"{",
"peerInfo",
",",
"protocol",
",",
"options",
":",
"{",
"useFSM",
":",
"true",
",",
"priority",
":",
"PRIORITY_HIGH",
"}",
",",
"callback",
"}",
")",
"}"
] |
Behaves like dial, except it calls back with a ConnectionFSM
@param {PeerInfo} peerInfo
@param {string} protocol
@param {function(Error, ConnectionFSM)} callback
|
[
"Behaves",
"like",
"dial",
"except",
"it",
"calls",
"back",
"with",
"a",
"ConnectionFSM"
] |
f879cfc680521de81fef0bfc4a11e96623711712
|
https://github.com/libp2p/js-libp2p-switch/blob/f879cfc680521de81fef0bfc4a11e96623711712/src/dialer/index.js#L105-L107
|
16,649
|
stevebest/passport-vkontakte
|
lib/errors/vkontakteauthorizationerror.js
|
VkontakteAuthorizationError
|
function VkontakteAuthorizationError(message, type, code, status) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'VkontakteAuthorizationError';
this.message = message;
this.type = type;
this.code = code || 'server_error';
this.status = status || 500;
}
|
javascript
|
function VkontakteAuthorizationError(message, type, code, status) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'VkontakteAuthorizationError';
this.message = message;
this.type = type;
this.code = code || 'server_error';
this.status = status || 500;
}
|
[
"function",
"VkontakteAuthorizationError",
"(",
"message",
",",
"type",
",",
"code",
",",
"status",
")",
"{",
"Error",
".",
"call",
"(",
"this",
")",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"arguments",
".",
"callee",
")",
";",
"this",
".",
"name",
"=",
"'VkontakteAuthorizationError'",
";",
"this",
".",
"message",
"=",
"message",
";",
"this",
".",
"type",
"=",
"type",
";",
"this",
".",
"code",
"=",
"code",
"||",
"'server_error'",
";",
"this",
".",
"status",
"=",
"status",
"||",
"500",
";",
"}"
] |
`VkontakteAuthorizationError` error.
VkontakteAuthorizationError represents an error in response to an
authorization request on Vkontakte. Note that these responses don't conform
to the OAuth 2.0 specification.
@constructor
@param {String} [message]
@param {String} [type]
@param {String} [code]
@param {Number} [status]
@api public
|
[
"VkontakteAuthorizationError",
"error",
"."
] |
7a1fafc8d7fd337a96572c29c7a2a64d8dc2ddde
|
https://github.com/stevebest/passport-vkontakte/blob/7a1fafc8d7fd337a96572c29c7a2a64d8dc2ddde/lib/errors/vkontakteauthorizationerror.js#L15-L23
|
16,650
|
MacKentoch/easyFormGenerator
|
src/app/dragdropway/components/common/dragAndDropList/dragAndDropList.dndlist.directive.js
|
isMouseInFirstHalf
|
function isMouseInFirstHalf(event, targetNode, relativeToParent) {
var mousePointer = horizontal ? (event.offsetX || event.layerX)
: (event.offsetY || event.layerY);
var targetSize = horizontal ? targetNode.offsetWidth : targetNode.offsetHeight;
var targetPosition = horizontal ? targetNode.offsetLeft : targetNode.offsetTop;
targetPosition = relativeToParent ? targetPosition : 0;
return mousePointer < targetPosition + targetSize / 2;
}
|
javascript
|
function isMouseInFirstHalf(event, targetNode, relativeToParent) {
var mousePointer = horizontal ? (event.offsetX || event.layerX)
: (event.offsetY || event.layerY);
var targetSize = horizontal ? targetNode.offsetWidth : targetNode.offsetHeight;
var targetPosition = horizontal ? targetNode.offsetLeft : targetNode.offsetTop;
targetPosition = relativeToParent ? targetPosition : 0;
return mousePointer < targetPosition + targetSize / 2;
}
|
[
"function",
"isMouseInFirstHalf",
"(",
"event",
",",
"targetNode",
",",
"relativeToParent",
")",
"{",
"var",
"mousePointer",
"=",
"horizontal",
"?",
"(",
"event",
".",
"offsetX",
"||",
"event",
".",
"layerX",
")",
":",
"(",
"event",
".",
"offsetY",
"||",
"event",
".",
"layerY",
")",
";",
"var",
"targetSize",
"=",
"horizontal",
"?",
"targetNode",
".",
"offsetWidth",
":",
"targetNode",
".",
"offsetHeight",
";",
"var",
"targetPosition",
"=",
"horizontal",
"?",
"targetNode",
".",
"offsetLeft",
":",
"targetNode",
".",
"offsetTop",
";",
"targetPosition",
"=",
"relativeToParent",
"?",
"targetPosition",
":",
"0",
";",
"return",
"mousePointer",
"<",
"targetPosition",
"+",
"targetSize",
"/",
"2",
";",
"}"
] |
Checks whether the mouse pointer is in the first half of the given target element.
In Chrome we can just use offsetY, but in Firefox we have to use layerY, which only
works if the child element has position relative. In IE the events are only triggered
on the listNode instead of the listNodeItem, therefore the mouse positions are
relative to the parent element of targetNode.
|
[
"Checks",
"whether",
"the",
"mouse",
"pointer",
"is",
"in",
"the",
"first",
"half",
"of",
"the",
"given",
"target",
"element",
"."
] |
d146d9ac1aba87f8730001b61a737867a1a05695
|
https://github.com/MacKentoch/easyFormGenerator/blob/d146d9ac1aba87f8730001b61a737867a1a05695/src/app/dragdropway/components/common/dragAndDropList/dragAndDropList.dndlist.directive.js#L155-L162
|
16,651
|
MacKentoch/easyFormGenerator
|
src/app/dragdropway/components/common/dragAndDropList/dragAndDropList.dndlist.directive.js
|
isDropAllowed
|
function isDropAllowed(event) {
// Disallow drop from external source unless it's allowed explicitly.
if (!dndDragTypeWorkaround.isDragging && !externalSources) return false;
// Check mimetype. Usually we would use a custom drag type instead of Text, but IE doesn't
// support that.
if (!hasTextMimetype(event.dataTransfer.types)) return false;
// Now check the dnd-allowed-types against the type of the incoming element. For drops from
// external sources we don't know the type, so it will need to be checked via dnd-drop.
if (attr.dndAllowedTypes && dndDragTypeWorkaround.isDragging) {
var allowed = scope.$eval(attr.dndAllowedTypes);
if (angular.isArray(allowed) && allowed.indexOf(dndDragTypeWorkaround.dragType) === -1) {
return false;
}
}
// Check whether droping is disabled completely
if (attr.dndDisableIf && scope.$eval(attr.dndDisableIf)) return false;
return true;
}
|
javascript
|
function isDropAllowed(event) {
// Disallow drop from external source unless it's allowed explicitly.
if (!dndDragTypeWorkaround.isDragging && !externalSources) return false;
// Check mimetype. Usually we would use a custom drag type instead of Text, but IE doesn't
// support that.
if (!hasTextMimetype(event.dataTransfer.types)) return false;
// Now check the dnd-allowed-types against the type of the incoming element. For drops from
// external sources we don't know the type, so it will need to be checked via dnd-drop.
if (attr.dndAllowedTypes && dndDragTypeWorkaround.isDragging) {
var allowed = scope.$eval(attr.dndAllowedTypes);
if (angular.isArray(allowed) && allowed.indexOf(dndDragTypeWorkaround.dragType) === -1) {
return false;
}
}
// Check whether droping is disabled completely
if (attr.dndDisableIf && scope.$eval(attr.dndDisableIf)) return false;
return true;
}
|
[
"function",
"isDropAllowed",
"(",
"event",
")",
"{",
"// Disallow drop from external source unless it's allowed explicitly.",
"if",
"(",
"!",
"dndDragTypeWorkaround",
".",
"isDragging",
"&&",
"!",
"externalSources",
")",
"return",
"false",
";",
"// Check mimetype. Usually we would use a custom drag type instead of Text, but IE doesn't",
"// support that.",
"if",
"(",
"!",
"hasTextMimetype",
"(",
"event",
".",
"dataTransfer",
".",
"types",
")",
")",
"return",
"false",
";",
"// Now check the dnd-allowed-types against the type of the incoming element. For drops from",
"// external sources we don't know the type, so it will need to be checked via dnd-drop.",
"if",
"(",
"attr",
".",
"dndAllowedTypes",
"&&",
"dndDragTypeWorkaround",
".",
"isDragging",
")",
"{",
"var",
"allowed",
"=",
"scope",
".",
"$eval",
"(",
"attr",
".",
"dndAllowedTypes",
")",
";",
"if",
"(",
"angular",
".",
"isArray",
"(",
"allowed",
")",
"&&",
"allowed",
".",
"indexOf",
"(",
"dndDragTypeWorkaround",
".",
"dragType",
")",
"===",
"-",
"1",
")",
"{",
"return",
"false",
";",
"}",
"}",
"// Check whether droping is disabled completely",
"if",
"(",
"attr",
".",
"dndDisableIf",
"&&",
"scope",
".",
"$eval",
"(",
"attr",
".",
"dndDisableIf",
")",
")",
"return",
"false",
";",
"return",
"true",
";",
"}"
] |
Checks various conditions that must be fulfilled for a drop to be allowed
|
[
"Checks",
"various",
"conditions",
"that",
"must",
"be",
"fulfilled",
"for",
"a",
"drop",
"to",
"be",
"allowed"
] |
d146d9ac1aba87f8730001b61a737867a1a05695
|
https://github.com/MacKentoch/easyFormGenerator/blob/d146d9ac1aba87f8730001b61a737867a1a05695/src/app/dragdropway/components/common/dragAndDropList/dragAndDropList.dndlist.directive.js#L175-L192
|
16,652
|
MacKentoch/easyFormGenerator
|
src/app/dragdropway/components/common/dragAndDropList/dragAndDropList.dndlist.directive.js
|
hasTextMimetype
|
function hasTextMimetype(types) {
if (!types) return true;
for (var i = 0; i < types.length; i++) {
if (types[i] === 'Text' || types[i] === 'text/plain') return true;
}
return false;
}
|
javascript
|
function hasTextMimetype(types) {
if (!types) return true;
for (var i = 0; i < types.length; i++) {
if (types[i] === 'Text' || types[i] === 'text/plain') return true;
}
return false;
}
|
[
"function",
"hasTextMimetype",
"(",
"types",
")",
"{",
"if",
"(",
"!",
"types",
")",
"return",
"true",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"types",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"types",
"[",
"i",
"]",
"===",
"'Text'",
"||",
"types",
"[",
"i",
"]",
"===",
"'text/plain'",
")",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Check if the dataTransfer object contains a drag type that we can handle. In old versions
of IE the types collection will not even be there, so we just assume a drop is possible.
|
[
"Check",
"if",
"the",
"dataTransfer",
"object",
"contains",
"a",
"drag",
"type",
"that",
"we",
"can",
"handle",
".",
"In",
"old",
"versions",
"of",
"IE",
"the",
"types",
"collection",
"will",
"not",
"even",
"be",
"there",
"so",
"we",
"just",
"assume",
"a",
"drop",
"is",
"possible",
"."
] |
d146d9ac1aba87f8730001b61a737867a1a05695
|
https://github.com/MacKentoch/easyFormGenerator/blob/d146d9ac1aba87f8730001b61a737867a1a05695/src/app/dragdropway/components/common/dragAndDropList/dragAndDropList.dndlist.directive.js#L220-L226
|
16,653
|
tombatossals/angular-leaflet-directive
|
examples/js/controllers.js
|
getColor
|
function getColor(country) {
if (!country || !country["region-code"]) {
return "#FFF";
}
var colors = continentProperties[country["region-code"]].colors;
var index = country["alpha-3"].charCodeAt(0) % colors.length ;
return colors[index];
}
|
javascript
|
function getColor(country) {
if (!country || !country["region-code"]) {
return "#FFF";
}
var colors = continentProperties[country["region-code"]].colors;
var index = country["alpha-3"].charCodeAt(0) % colors.length ;
return colors[index];
}
|
[
"function",
"getColor",
"(",
"country",
")",
"{",
"if",
"(",
"!",
"country",
"||",
"!",
"country",
"[",
"\"region-code\"",
"]",
")",
"{",
"return",
"\"#FFF\"",
";",
"}",
"var",
"colors",
"=",
"continentProperties",
"[",
"country",
"[",
"\"region-code\"",
"]",
"]",
".",
"colors",
";",
"var",
"index",
"=",
"country",
"[",
"\"alpha-3\"",
"]",
".",
"charCodeAt",
"(",
"0",
")",
"%",
"colors",
".",
"length",
";",
"return",
"colors",
"[",
"index",
"]",
";",
"}"
] |
Get a country paint color from the continents array of colors
|
[
"Get",
"a",
"country",
"paint",
"color",
"from",
"the",
"continents",
"array",
"of",
"colors"
] |
1cfbdf4a7f68bfddddc7472b5799c7b950337b2a
|
https://github.com/tombatossals/angular-leaflet-directive/blob/1cfbdf4a7f68bfddddc7472b5799c7b950337b2a/examples/js/controllers.js#L3875-L3882
|
16,654
|
tombatossals/angular-leaflet-directive
|
src/services/leafletIterators.js
|
function(collection, cb, ignoreCollection, cbName) {
if (!ignoreCollection) {
if (!lHlp.isDefined(collection) || !lHlp.isDefined(cb)) {
return true;
}
}
if (!lHlp.isFunction(cb)) {
cbName = lHlp.defaultTo(cb, 'cb');
$log.error(errorHeader + cbName + ' is not a function');
return true;
}
return false;
}
|
javascript
|
function(collection, cb, ignoreCollection, cbName) {
if (!ignoreCollection) {
if (!lHlp.isDefined(collection) || !lHlp.isDefined(cb)) {
return true;
}
}
if (!lHlp.isFunction(cb)) {
cbName = lHlp.defaultTo(cb, 'cb');
$log.error(errorHeader + cbName + ' is not a function');
return true;
}
return false;
}
|
[
"function",
"(",
"collection",
",",
"cb",
",",
"ignoreCollection",
",",
"cbName",
")",
"{",
"if",
"(",
"!",
"ignoreCollection",
")",
"{",
"if",
"(",
"!",
"lHlp",
".",
"isDefined",
"(",
"collection",
")",
"||",
"!",
"lHlp",
".",
"isDefined",
"(",
"cb",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"if",
"(",
"!",
"lHlp",
".",
"isFunction",
"(",
"cb",
")",
")",
"{",
"cbName",
"=",
"lHlp",
".",
"defaultTo",
"(",
"cb",
",",
"'cb'",
")",
";",
"$log",
".",
"error",
"(",
"errorHeader",
"+",
"cbName",
"+",
"' is not a function'",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
END COPY fron underscore
|
[
"END",
"COPY",
"fron",
"underscore"
] |
1cfbdf4a7f68bfddddc7472b5799c7b950337b2a
|
https://github.com/tombatossals/angular-leaflet-directive/blob/1cfbdf4a7f68bfddddc7472b5799c7b950337b2a/src/services/leafletIterators.js#L136-L150
|
|
16,655
|
tombatossals/angular-leaflet-directive
|
src/directives/leaflet.js
|
updateWidth
|
function updateWidth() {
if (isNaN(attrs.width)) {
element.css('width', attrs.width);
} else {
element.css('width', attrs.width + 'px');
}
}
|
javascript
|
function updateWidth() {
if (isNaN(attrs.width)) {
element.css('width', attrs.width);
} else {
element.css('width', attrs.width + 'px');
}
}
|
[
"function",
"updateWidth",
"(",
")",
"{",
"if",
"(",
"isNaN",
"(",
"attrs",
".",
"width",
")",
")",
"{",
"element",
".",
"css",
"(",
"'width'",
",",
"attrs",
".",
"width",
")",
";",
"}",
"else",
"{",
"element",
".",
"css",
"(",
"'width'",
",",
"attrs",
".",
"width",
"+",
"'px'",
")",
";",
"}",
"}"
] |
Set width and height utility functions
|
[
"Set",
"width",
"and",
"height",
"utility",
"functions"
] |
1cfbdf4a7f68bfddddc7472b5799c7b950337b2a
|
https://github.com/tombatossals/angular-leaflet-directive/blob/1cfbdf4a7f68bfddddc7472b5799c7b950337b2a/src/directives/leaflet.js#L46-L52
|
16,656
|
marpple/partial.js
|
partial.js
|
_set
|
function _set(obj, key, vORf) {
obj && (obj[key] = _.is_fn(vORf) ? vORf(obj[key]) : vORf);
}
|
javascript
|
function _set(obj, key, vORf) {
obj && (obj[key] = _.is_fn(vORf) ? vORf(obj[key]) : vORf);
}
|
[
"function",
"_set",
"(",
"obj",
",",
"key",
",",
"vORf",
")",
"{",
"obj",
"&&",
"(",
"obj",
"[",
"key",
"]",
"=",
"_",
".",
"is_fn",
"(",
"vORf",
")",
"?",
"vORf",
"(",
"obj",
"[",
"key",
"]",
")",
":",
"vORf",
")",
";",
"}"
] |
template end mutable
|
[
"template",
"end",
"mutable"
] |
a331f891d2ba45a3a46311e5d4335474a17dae21
|
https://github.com/marpple/partial.js/blob/a331f891d2ba45a3a46311e5d4335474a17dae21/partial.js#L1408-L1410
|
16,657
|
wysiwygjs/wysiwyg.js
|
wysiwyg.js
|
function( popup, modify_a_href )
{
var textbox = document.createElement('input');
textbox.placeholder = 'www.example.com';
if( modify_a_href )
textbox.value = modify_a_href.href;
textbox.style.width = '20em';
textbox.style.maxWidth = parseInt(node_container.offsetWidth *2/3) + 'px';
textbox.autofocus = true;
if( modify_a_href )
addEvent( textbox, 'input', function( e )
{
var url = textbox.value.trim();
if( url )
modify_a_href.href = url;
});
addEvent( textbox, 'keypress', function( e )
{
var key = e.which || e.keyCode;
if( key != 13 )
return;
var url = textbox.value.trim();
if( modify_a_href )
;
else if( url )
{
var url_scheme = url;
if( ! /^[a-z0-9]+:\/\//.test(url) )
url_scheme = "http://" + url;
if( commands.getSelectedHTML() )
commands.insertLink( url_scheme );
else
{
// Encode html entities - http://stackoverflow.com/questions/5499078/fastest-method-to-escape-html-tags-as-html-entities
var htmlencode = function( text ) {
return text.replace(/[&<>"]/g, function(tag)
{
var charsToReplace = { '&':'&', '<':'<', '>':'>', '"':'"' };
return charsToReplace[tag] || tag;
});
}
commands.insertHTML( '<a href="' + htmlencode(url_scheme) + '">' + htmlencode(url) + '</a>' );
}
}
commands.closePopup().collapseSelection();
node_contenteditable.focus();
});
popup.appendChild( textbox );
// set focus
window.setTimeout( function()
{
textbox.focus();
add_class_focus();
}, 1 );
}
|
javascript
|
function( popup, modify_a_href )
{
var textbox = document.createElement('input');
textbox.placeholder = 'www.example.com';
if( modify_a_href )
textbox.value = modify_a_href.href;
textbox.style.width = '20em';
textbox.style.maxWidth = parseInt(node_container.offsetWidth *2/3) + 'px';
textbox.autofocus = true;
if( modify_a_href )
addEvent( textbox, 'input', function( e )
{
var url = textbox.value.trim();
if( url )
modify_a_href.href = url;
});
addEvent( textbox, 'keypress', function( e )
{
var key = e.which || e.keyCode;
if( key != 13 )
return;
var url = textbox.value.trim();
if( modify_a_href )
;
else if( url )
{
var url_scheme = url;
if( ! /^[a-z0-9]+:\/\//.test(url) )
url_scheme = "http://" + url;
if( commands.getSelectedHTML() )
commands.insertLink( url_scheme );
else
{
// Encode html entities - http://stackoverflow.com/questions/5499078/fastest-method-to-escape-html-tags-as-html-entities
var htmlencode = function( text ) {
return text.replace(/[&<>"]/g, function(tag)
{
var charsToReplace = { '&':'&', '<':'<', '>':'>', '"':'"' };
return charsToReplace[tag] || tag;
});
}
commands.insertHTML( '<a href="' + htmlencode(url_scheme) + '">' + htmlencode(url) + '</a>' );
}
}
commands.closePopup().collapseSelection();
node_contenteditable.focus();
});
popup.appendChild( textbox );
// set focus
window.setTimeout( function()
{
textbox.focus();
add_class_focus();
}, 1 );
}
|
[
"function",
"(",
"popup",
",",
"modify_a_href",
")",
"{",
"var",
"textbox",
"=",
"document",
".",
"createElement",
"(",
"'input'",
")",
";",
"textbox",
".",
"placeholder",
"=",
"'www.example.com'",
";",
"if",
"(",
"modify_a_href",
")",
"textbox",
".",
"value",
"=",
"modify_a_href",
".",
"href",
";",
"textbox",
".",
"style",
".",
"width",
"=",
"'20em'",
";",
"textbox",
".",
"style",
".",
"maxWidth",
"=",
"parseInt",
"(",
"node_container",
".",
"offsetWidth",
"*",
"2",
"/",
"3",
")",
"+",
"'px'",
";",
"textbox",
".",
"autofocus",
"=",
"true",
";",
"if",
"(",
"modify_a_href",
")",
"addEvent",
"(",
"textbox",
",",
"'input'",
",",
"function",
"(",
"e",
")",
"{",
"var",
"url",
"=",
"textbox",
".",
"value",
".",
"trim",
"(",
")",
";",
"if",
"(",
"url",
")",
"modify_a_href",
".",
"href",
"=",
"url",
";",
"}",
")",
";",
"addEvent",
"(",
"textbox",
",",
"'keypress'",
",",
"function",
"(",
"e",
")",
"{",
"var",
"key",
"=",
"e",
".",
"which",
"||",
"e",
".",
"keyCode",
";",
"if",
"(",
"key",
"!=",
"13",
")",
"return",
";",
"var",
"url",
"=",
"textbox",
".",
"value",
".",
"trim",
"(",
")",
";",
"if",
"(",
"modify_a_href",
")",
";",
"else",
"if",
"(",
"url",
")",
"{",
"var",
"url_scheme",
"=",
"url",
";",
"if",
"(",
"!",
"/",
"^[a-z0-9]+:\\/\\/",
"/",
".",
"test",
"(",
"url",
")",
")",
"url_scheme",
"=",
"\"http://\"",
"+",
"url",
";",
"if",
"(",
"commands",
".",
"getSelectedHTML",
"(",
")",
")",
"commands",
".",
"insertLink",
"(",
"url_scheme",
")",
";",
"else",
"{",
"// Encode html entities - http://stackoverflow.com/questions/5499078/fastest-method-to-escape-html-tags-as-html-entities",
"var",
"htmlencode",
"=",
"function",
"(",
"text",
")",
"{",
"return",
"text",
".",
"replace",
"(",
"/",
"[&<>\"]",
"/",
"g",
",",
"function",
"(",
"tag",
")",
"{",
"var",
"charsToReplace",
"=",
"{",
"'&'",
":",
"'&'",
",",
"'<'",
":",
"'<'",
",",
"'>'",
":",
"'>'",
",",
"'\"'",
":",
"'"'",
"}",
";",
"return",
"charsToReplace",
"[",
"tag",
"]",
"||",
"tag",
";",
"}",
")",
";",
"}",
"commands",
".",
"insertHTML",
"(",
"'<a href=\"'",
"+",
"htmlencode",
"(",
"url_scheme",
")",
"+",
"'\">'",
"+",
"htmlencode",
"(",
"url",
")",
"+",
"'</a>'",
")",
";",
"}",
"}",
"commands",
".",
"closePopup",
"(",
")",
".",
"collapseSelection",
"(",
")",
";",
"node_contenteditable",
".",
"focus",
"(",
")",
";",
"}",
")",
";",
"popup",
".",
"appendChild",
"(",
"textbox",
")",
";",
"// set focus",
"window",
".",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"textbox",
".",
"focus",
"(",
")",
";",
"add_class_focus",
"(",
")",
";",
"}",
",",
"1",
")",
";",
"}"
] |
Insert-link popup
|
[
"Insert",
"-",
"link",
"popup"
] |
1fccde7040e0d504cd0d9cb371c88d800c733de0
|
https://github.com/wysiwygjs/wysiwyg.js/blob/1fccde7040e0d504cd0d9cb371c88d800c733de0/wysiwyg.js#L363-L417
|
|
16,658
|
wysiwygjs/wysiwyg.js
|
wysiwyg.js
|
function( popup, left, top ) // left+top relative to container
{
// Test parents, el.getBoundingClientRect() does not work within 'position:fixed'
var node = node_container,
popup_parent = node.offsetParent;
while( node )
{
var node_style = getComputedStyle( node );
if( node_style['position'] != 'static' )
break;
left += node.offsetLeft;
top += node.offsetTop;
popup_parent = node;
node = node.offsetParent;
}
// Move popup as high as possible in the DOM tree
popup_parent.appendChild( popup );
// Trim to viewport
var rect = popup_parent.getBoundingClientRect();
var documentElement = document.documentElement;
var viewport_width = Math.min( window.innerWidth, Math.max(documentElement.offsetWidth, documentElement.scrollWidth) );
var viewport_height = window.innerHeight;
var popup_width = popup.offsetWidth; // accurate to integer
var popup_height = popup.offsetHeight;
if( rect.left + left < 1 )
left = 1 - rect.left;
else if( rect.left + left + popup_width > viewport_width - 1 )
left = Math.max( 1 - rect.left, viewport_width - 1 - rect.left - popup_width );
if( rect.top + top < 1 )
top = 1 - rect.top;
else if( rect.top + top + popup_height > viewport_height - 1 )
top = Math.max( 1 - rect.top, viewport_height - 1 - rect.top - popup_height );
// Set offset
popup.style.left = parseInt(left) + 'px';
popup.style.top = parseInt(top) + 'px';
}
|
javascript
|
function( popup, left, top ) // left+top relative to container
{
// Test parents, el.getBoundingClientRect() does not work within 'position:fixed'
var node = node_container,
popup_parent = node.offsetParent;
while( node )
{
var node_style = getComputedStyle( node );
if( node_style['position'] != 'static' )
break;
left += node.offsetLeft;
top += node.offsetTop;
popup_parent = node;
node = node.offsetParent;
}
// Move popup as high as possible in the DOM tree
popup_parent.appendChild( popup );
// Trim to viewport
var rect = popup_parent.getBoundingClientRect();
var documentElement = document.documentElement;
var viewport_width = Math.min( window.innerWidth, Math.max(documentElement.offsetWidth, documentElement.scrollWidth) );
var viewport_height = window.innerHeight;
var popup_width = popup.offsetWidth; // accurate to integer
var popup_height = popup.offsetHeight;
if( rect.left + left < 1 )
left = 1 - rect.left;
else if( rect.left + left + popup_width > viewport_width - 1 )
left = Math.max( 1 - rect.left, viewport_width - 1 - rect.left - popup_width );
if( rect.top + top < 1 )
top = 1 - rect.top;
else if( rect.top + top + popup_height > viewport_height - 1 )
top = Math.max( 1 - rect.top, viewport_height - 1 - rect.top - popup_height );
// Set offset
popup.style.left = parseInt(left) + 'px';
popup.style.top = parseInt(top) + 'px';
}
|
[
"function",
"(",
"popup",
",",
"left",
",",
"top",
")",
"// left+top relative to container",
"{",
"// Test parents, el.getBoundingClientRect() does not work within 'position:fixed'",
"var",
"node",
"=",
"node_container",
",",
"popup_parent",
"=",
"node",
".",
"offsetParent",
";",
"while",
"(",
"node",
")",
"{",
"var",
"node_style",
"=",
"getComputedStyle",
"(",
"node",
")",
";",
"if",
"(",
"node_style",
"[",
"'position'",
"]",
"!=",
"'static'",
")",
"break",
";",
"left",
"+=",
"node",
".",
"offsetLeft",
";",
"top",
"+=",
"node",
".",
"offsetTop",
";",
"popup_parent",
"=",
"node",
";",
"node",
"=",
"node",
".",
"offsetParent",
";",
"}",
"// Move popup as high as possible in the DOM tree",
"popup_parent",
".",
"appendChild",
"(",
"popup",
")",
";",
"// Trim to viewport",
"var",
"rect",
"=",
"popup_parent",
".",
"getBoundingClientRect",
"(",
")",
";",
"var",
"documentElement",
"=",
"document",
".",
"documentElement",
";",
"var",
"viewport_width",
"=",
"Math",
".",
"min",
"(",
"window",
".",
"innerWidth",
",",
"Math",
".",
"max",
"(",
"documentElement",
".",
"offsetWidth",
",",
"documentElement",
".",
"scrollWidth",
")",
")",
";",
"var",
"viewport_height",
"=",
"window",
".",
"innerHeight",
";",
"var",
"popup_width",
"=",
"popup",
".",
"offsetWidth",
";",
"// accurate to integer",
"var",
"popup_height",
"=",
"popup",
".",
"offsetHeight",
";",
"if",
"(",
"rect",
".",
"left",
"+",
"left",
"<",
"1",
")",
"left",
"=",
"1",
"-",
"rect",
".",
"left",
";",
"else",
"if",
"(",
"rect",
".",
"left",
"+",
"left",
"+",
"popup_width",
">",
"viewport_width",
"-",
"1",
")",
"left",
"=",
"Math",
".",
"max",
"(",
"1",
"-",
"rect",
".",
"left",
",",
"viewport_width",
"-",
"1",
"-",
"rect",
".",
"left",
"-",
"popup_width",
")",
";",
"if",
"(",
"rect",
".",
"top",
"+",
"top",
"<",
"1",
")",
"top",
"=",
"1",
"-",
"rect",
".",
"top",
";",
"else",
"if",
"(",
"rect",
".",
"top",
"+",
"top",
"+",
"popup_height",
">",
"viewport_height",
"-",
"1",
")",
"top",
"=",
"Math",
".",
"max",
"(",
"1",
"-",
"rect",
".",
"top",
",",
"viewport_height",
"-",
"1",
"-",
"rect",
".",
"top",
"-",
"popup_height",
")",
";",
"// Set offset",
"popup",
".",
"style",
".",
"left",
"=",
"parseInt",
"(",
"left",
")",
"+",
"'px'",
";",
"popup",
".",
"style",
".",
"top",
"=",
"parseInt",
"(",
"top",
")",
"+",
"'px'",
";",
"}"
] |
open popup and apply position
|
[
"open",
"popup",
"and",
"apply",
"position"
] |
1fccde7040e0d504cd0d9cb371c88d800c733de0
|
https://github.com/wysiwygjs/wysiwyg.js/blob/1fccde7040e0d504cd0d9cb371c88d800c733de0/wysiwyg.js#L492-L527
|
|
16,659
|
wysiwygjs/wysiwyg.js
|
legacy/src/wysiwyg-editor.js
|
function( url, filename )
{
var html = '<img id="wysiwyg-insert-image" src="" alt=""' + (filename ? ' title="'+html_encode(filename)+'"' : '') + '>';
wysiwygeditor.insertHTML( html ).closePopup().collapseSelection();
var $image = $('#wysiwyg-insert-image').removeAttr('id');
if( max_imagesize )
{
$image.css({maxWidth: max_imagesize[0]+'px',
maxHeight: max_imagesize[1]+'px'})
.load( function() {
$image.css({maxWidth: '',
maxHeight: ''});
// Resize $image to fit "clip-image"
var image_width = $image.width(),
image_height = $image.height();
if( image_width > max_imagesize[0] || image_height > max_imagesize[1] )
{
if( (image_width/image_height) > (max_imagesize[0]/max_imagesize[1]) )
{
image_height = parseInt(image_height / image_width * max_imagesize[0]);
image_width = max_imagesize[0];
}
else
{
image_width = parseInt(image_width / image_height * max_imagesize[1]);
image_height = max_imagesize[1];
}
$image.prop('width',image_width)
.prop('height',image_height);
}
});
}
$image.prop('src', url);
}
|
javascript
|
function( url, filename )
{
var html = '<img id="wysiwyg-insert-image" src="" alt=""' + (filename ? ' title="'+html_encode(filename)+'"' : '') + '>';
wysiwygeditor.insertHTML( html ).closePopup().collapseSelection();
var $image = $('#wysiwyg-insert-image').removeAttr('id');
if( max_imagesize )
{
$image.css({maxWidth: max_imagesize[0]+'px',
maxHeight: max_imagesize[1]+'px'})
.load( function() {
$image.css({maxWidth: '',
maxHeight: ''});
// Resize $image to fit "clip-image"
var image_width = $image.width(),
image_height = $image.height();
if( image_width > max_imagesize[0] || image_height > max_imagesize[1] )
{
if( (image_width/image_height) > (max_imagesize[0]/max_imagesize[1]) )
{
image_height = parseInt(image_height / image_width * max_imagesize[0]);
image_width = max_imagesize[0];
}
else
{
image_width = parseInt(image_width / image_height * max_imagesize[1]);
image_height = max_imagesize[1];
}
$image.prop('width',image_width)
.prop('height',image_height);
}
});
}
$image.prop('src', url);
}
|
[
"function",
"(",
"url",
",",
"filename",
")",
"{",
"var",
"html",
"=",
"'<img id=\"wysiwyg-insert-image\" src=\"\" alt=\"\"'",
"+",
"(",
"filename",
"?",
"' title=\"'",
"+",
"html_encode",
"(",
"filename",
")",
"+",
"'\"'",
":",
"''",
")",
"+",
"'>'",
";",
"wysiwygeditor",
".",
"insertHTML",
"(",
"html",
")",
".",
"closePopup",
"(",
")",
".",
"collapseSelection",
"(",
")",
";",
"var",
"$image",
"=",
"$",
"(",
"'#wysiwyg-insert-image'",
")",
".",
"removeAttr",
"(",
"'id'",
")",
";",
"if",
"(",
"max_imagesize",
")",
"{",
"$image",
".",
"css",
"(",
"{",
"maxWidth",
":",
"max_imagesize",
"[",
"0",
"]",
"+",
"'px'",
",",
"maxHeight",
":",
"max_imagesize",
"[",
"1",
"]",
"+",
"'px'",
"}",
")",
".",
"load",
"(",
"function",
"(",
")",
"{",
"$image",
".",
"css",
"(",
"{",
"maxWidth",
":",
"''",
",",
"maxHeight",
":",
"''",
"}",
")",
";",
"// Resize $image to fit \"clip-image\"",
"var",
"image_width",
"=",
"$image",
".",
"width",
"(",
")",
",",
"image_height",
"=",
"$image",
".",
"height",
"(",
")",
";",
"if",
"(",
"image_width",
">",
"max_imagesize",
"[",
"0",
"]",
"||",
"image_height",
">",
"max_imagesize",
"[",
"1",
"]",
")",
"{",
"if",
"(",
"(",
"image_width",
"/",
"image_height",
")",
">",
"(",
"max_imagesize",
"[",
"0",
"]",
"/",
"max_imagesize",
"[",
"1",
"]",
")",
")",
"{",
"image_height",
"=",
"parseInt",
"(",
"image_height",
"/",
"image_width",
"*",
"max_imagesize",
"[",
"0",
"]",
")",
";",
"image_width",
"=",
"max_imagesize",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"image_width",
"=",
"parseInt",
"(",
"image_width",
"/",
"image_height",
"*",
"max_imagesize",
"[",
"1",
"]",
")",
";",
"image_height",
"=",
"max_imagesize",
"[",
"1",
"]",
";",
"}",
"$image",
".",
"prop",
"(",
"'width'",
",",
"image_width",
")",
".",
"prop",
"(",
"'height'",
",",
"image_height",
")",
";",
"}",
"}",
")",
";",
"}",
"$image",
".",
"prop",
"(",
"'src'",
",",
"url",
")",
";",
"}"
] |
Add image to editor
|
[
"Add",
"image",
"to",
"editor"
] |
1fccde7040e0d504cd0d9cb371c88d800c733de0
|
https://github.com/wysiwygjs/wysiwyg.js/blob/1fccde7040e0d504cd0d9cb371c88d800c733de0/legacy/src/wysiwyg-editor.js#L113-L146
|
|
16,660
|
wysiwygjs/wysiwyg.js
|
legacy/src/wysiwyg-editor.js
|
function( file )
{
// Only process image files
if( typeof(filter_imageType) === 'function' && ! filter_imageType(file) )
return;
else if( ! file.type.match(filter_imageType) )
return;
var reader = new FileReader();
reader.onload = function(event) {
var dataurl = event.target.result;
insert_image_wysiwyg( dataurl, file.name );
};
// Read in the image file as a data URL
reader.readAsDataURL( file );
}
|
javascript
|
function( file )
{
// Only process image files
if( typeof(filter_imageType) === 'function' && ! filter_imageType(file) )
return;
else if( ! file.type.match(filter_imageType) )
return;
var reader = new FileReader();
reader.onload = function(event) {
var dataurl = event.target.result;
insert_image_wysiwyg( dataurl, file.name );
};
// Read in the image file as a data URL
reader.readAsDataURL( file );
}
|
[
"function",
"(",
"file",
")",
"{",
"// Only process image files",
"if",
"(",
"typeof",
"(",
"filter_imageType",
")",
"===",
"'function'",
"&&",
"!",
"filter_imageType",
"(",
"file",
")",
")",
"return",
";",
"else",
"if",
"(",
"!",
"file",
".",
"type",
".",
"match",
"(",
"filter_imageType",
")",
")",
"return",
";",
"var",
"reader",
"=",
"new",
"FileReader",
"(",
")",
";",
"reader",
".",
"onload",
"=",
"function",
"(",
"event",
")",
"{",
"var",
"dataurl",
"=",
"event",
".",
"target",
".",
"result",
";",
"insert_image_wysiwyg",
"(",
"dataurl",
",",
"file",
".",
"name",
")",
";",
"}",
";",
"// Read in the image file as a data URL",
"reader",
".",
"readAsDataURL",
"(",
"file",
")",
";",
"}"
] |
File-API
|
[
"File",
"-",
"API"
] |
1fccde7040e0d504cd0d9cb371c88d800c733de0
|
https://github.com/wysiwygjs/wysiwyg.js/blob/1fccde7040e0d504cd0d9cb371c88d800c733de0/legacy/src/wysiwyg-editor.js#L163-L177
|
|
16,661
|
wysiwygjs/wysiwyg.js
|
legacy/src/wysiwyg-editor.js
|
function( url, html )
{
url = $.trim(url||'');
html = $.trim(html||'');
var website_url = false;
if( url.length && ! html.length )
website_url = url;
else if( html.indexOf('<') == -1 && html.indexOf('>') == -1 &&
html.match(/^(?:https?:\/)?\/?(?:[^:\/\s]+)(?:(?:\/\w+)*\/)(?:[\w\-\.]+[^#?\s]+)(?:.*)?(?:#[\w\-]+)?$/) )
website_url = html;
if( website_url && video_from_url )
html = video_from_url( website_url ) || '';
if( ! html.length && website_url )
html = '<video src="' + html_encode(website_url) + '">';
wysiwygeditor.insertHTML( html ).closePopup().collapseSelection();
}
|
javascript
|
function( url, html )
{
url = $.trim(url||'');
html = $.trim(html||'');
var website_url = false;
if( url.length && ! html.length )
website_url = url;
else if( html.indexOf('<') == -1 && html.indexOf('>') == -1 &&
html.match(/^(?:https?:\/)?\/?(?:[^:\/\s]+)(?:(?:\/\w+)*\/)(?:[\w\-\.]+[^#?\s]+)(?:.*)?(?:#[\w\-]+)?$/) )
website_url = html;
if( website_url && video_from_url )
html = video_from_url( website_url ) || '';
if( ! html.length && website_url )
html = '<video src="' + html_encode(website_url) + '">';
wysiwygeditor.insertHTML( html ).closePopup().collapseSelection();
}
|
[
"function",
"(",
"url",
",",
"html",
")",
"{",
"url",
"=",
"$",
".",
"trim",
"(",
"url",
"||",
"''",
")",
";",
"html",
"=",
"$",
".",
"trim",
"(",
"html",
"||",
"''",
")",
";",
"var",
"website_url",
"=",
"false",
";",
"if",
"(",
"url",
".",
"length",
"&&",
"!",
"html",
".",
"length",
")",
"website_url",
"=",
"url",
";",
"else",
"if",
"(",
"html",
".",
"indexOf",
"(",
"'<'",
")",
"==",
"-",
"1",
"&&",
"html",
".",
"indexOf",
"(",
"'>'",
")",
"==",
"-",
"1",
"&&",
"html",
".",
"match",
"(",
"/",
"^(?:https?:\\/)?\\/?(?:[^:\\/\\s]+)(?:(?:\\/\\w+)*\\/)(?:[\\w\\-\\.]+[^#?\\s]+)(?:.*)?(?:#[\\w\\-]+)?$",
"/",
")",
")",
"website_url",
"=",
"html",
";",
"if",
"(",
"website_url",
"&&",
"video_from_url",
")",
"html",
"=",
"video_from_url",
"(",
"website_url",
")",
"||",
"''",
";",
"if",
"(",
"!",
"html",
".",
"length",
"&&",
"website_url",
")",
"html",
"=",
"'<video src=\"'",
"+",
"html_encode",
"(",
"website_url",
")",
"+",
"'\">'",
";",
"wysiwygeditor",
".",
"insertHTML",
"(",
"html",
")",
".",
"closePopup",
"(",
")",
".",
"collapseSelection",
"(",
")",
";",
"}"
] |
Add video to editor
|
[
"Add",
"video",
"to",
"editor"
] |
1fccde7040e0d504cd0d9cb371c88d800c733de0
|
https://github.com/wysiwygjs/wysiwyg.js/blob/1fccde7040e0d504cd0d9cb371c88d800c733de0/legacy/src/wysiwyg-editor.js#L238-L253
|
|
16,662
|
wysiwygjs/wysiwyg.js
|
legacy/src/wysiwyg-editor.js
|
function( button ) {
var $element = $('<a/>').addClass( 'wysiwyg-toolbar-icon' )
.prop('href','#')
.prop('unselectable','on')
.append(button.image);
// pass other properties as "prop()"
$.each( button, function( name, value )
{
switch( name )
{
// classes
case 'class':
$element.addClass( value );
break;
// special meaning
case 'image':
case 'html':
case 'popup':
case 'click':
case 'showstatic':
case 'showselection':
break;
default: // button.title, ...
$element.attr( name, value );
break;
}
});
return $element;
}
|
javascript
|
function( button ) {
var $element = $('<a/>').addClass( 'wysiwyg-toolbar-icon' )
.prop('href','#')
.prop('unselectable','on')
.append(button.image);
// pass other properties as "prop()"
$.each( button, function( name, value )
{
switch( name )
{
// classes
case 'class':
$element.addClass( value );
break;
// special meaning
case 'image':
case 'html':
case 'popup':
case 'click':
case 'showstatic':
case 'showselection':
break;
default: // button.title, ...
$element.attr( name, value );
break;
}
});
return $element;
}
|
[
"function",
"(",
"button",
")",
"{",
"var",
"$element",
"=",
"$",
"(",
"'<a/>'",
")",
".",
"addClass",
"(",
"'wysiwyg-toolbar-icon'",
")",
".",
"prop",
"(",
"'href'",
",",
"'#'",
")",
".",
"prop",
"(",
"'unselectable'",
",",
"'on'",
")",
".",
"append",
"(",
"button",
".",
"image",
")",
";",
"// pass other properties as \"prop()\"",
"$",
".",
"each",
"(",
"button",
",",
"function",
"(",
"name",
",",
"value",
")",
"{",
"switch",
"(",
"name",
")",
"{",
"// classes",
"case",
"'class'",
":",
"$element",
".",
"addClass",
"(",
"value",
")",
";",
"break",
";",
"// special meaning",
"case",
"'image'",
":",
"case",
"'html'",
":",
"case",
"'popup'",
":",
"case",
"'click'",
":",
"case",
"'showstatic'",
":",
"case",
"'showselection'",
":",
"break",
";",
"default",
":",
"// button.title, ...",
"$element",
".",
"attr",
"(",
"name",
",",
"value",
")",
";",
"break",
";",
"}",
"}",
")",
";",
"return",
"$element",
";",
"}"
] |
Create the toolbar
|
[
"Create",
"the",
"toolbar"
] |
1fccde7040e0d504cd0d9cb371c88d800c733de0
|
https://github.com/wysiwygjs/wysiwyg.js/blob/1fccde7040e0d504cd0d9cb371c88d800c733de0/legacy/src/wysiwyg-editor.js#L429-L457
|
|
16,663
|
wysiwygjs/wysiwyg.js
|
legacy/src/wysiwyg-editor.js
|
function()
{
var $toolbar = $('<div/>').addClass( 'wysiwyg-toolbar' ).addClass( toolbar_top ? 'wysiwyg-toolbar-top' : 'wysiwyg-toolbar-bottom' );
if( toolbar_focus )
$toolbar.hide().addClass( 'wysiwyg-toolbar-focus' );
// Add buttons to the toolbar
add_buttons_to_toolbar( $toolbar, false,
function() {
// Open a popup from the toolbar
var $popup = $(wysiwygeditor.openPopup());
// if wrong popup -> create a new one
if( $popup.hasClass('wysiwyg-popup') && $popup.hasClass('wysiwyg-popuphover') )
$popup = $(wysiwygeditor.closePopup().openPopup());
if( ! $popup.hasClass('wysiwyg-popup') )
// add classes + content
$popup.addClass( 'wysiwyg-popup' );
return $popup;
},
function( $popup, target, overwrite_offset ) {
// Popup position
var $button = $(target);
var popup_width = $popup.outerWidth();
// Point is the top/bottom-center of the button
var left = $button.offset().left - $container.offset().left + parseInt($button.width() / 2) - parseInt(popup_width / 2);
var top = $button.offset().top - $container.offset().top;
if( toolbar_top )
top += $button.outerHeight();
else
top -= $popup.outerHeight();
if( overwrite_offset )
{
left = overwrite_offset.left;
top = overwrite_offset.top;
}
popup_position( $popup, $container, left, top );
});
if( toolbar_top )
$container.prepend( $toolbar );
else
$container.append( $toolbar );
}
|
javascript
|
function()
{
var $toolbar = $('<div/>').addClass( 'wysiwyg-toolbar' ).addClass( toolbar_top ? 'wysiwyg-toolbar-top' : 'wysiwyg-toolbar-bottom' );
if( toolbar_focus )
$toolbar.hide().addClass( 'wysiwyg-toolbar-focus' );
// Add buttons to the toolbar
add_buttons_to_toolbar( $toolbar, false,
function() {
// Open a popup from the toolbar
var $popup = $(wysiwygeditor.openPopup());
// if wrong popup -> create a new one
if( $popup.hasClass('wysiwyg-popup') && $popup.hasClass('wysiwyg-popuphover') )
$popup = $(wysiwygeditor.closePopup().openPopup());
if( ! $popup.hasClass('wysiwyg-popup') )
// add classes + content
$popup.addClass( 'wysiwyg-popup' );
return $popup;
},
function( $popup, target, overwrite_offset ) {
// Popup position
var $button = $(target);
var popup_width = $popup.outerWidth();
// Point is the top/bottom-center of the button
var left = $button.offset().left - $container.offset().left + parseInt($button.width() / 2) - parseInt(popup_width / 2);
var top = $button.offset().top - $container.offset().top;
if( toolbar_top )
top += $button.outerHeight();
else
top -= $popup.outerHeight();
if( overwrite_offset )
{
left = overwrite_offset.left;
top = overwrite_offset.top;
}
popup_position( $popup, $container, left, top );
});
if( toolbar_top )
$container.prepend( $toolbar );
else
$container.append( $toolbar );
}
|
[
"function",
"(",
")",
"{",
"var",
"$toolbar",
"=",
"$",
"(",
"'<div/>'",
")",
".",
"addClass",
"(",
"'wysiwyg-toolbar'",
")",
".",
"addClass",
"(",
"toolbar_top",
"?",
"'wysiwyg-toolbar-top'",
":",
"'wysiwyg-toolbar-bottom'",
")",
";",
"if",
"(",
"toolbar_focus",
")",
"$toolbar",
".",
"hide",
"(",
")",
".",
"addClass",
"(",
"'wysiwyg-toolbar-focus'",
")",
";",
"// Add buttons to the toolbar",
"add_buttons_to_toolbar",
"(",
"$toolbar",
",",
"false",
",",
"function",
"(",
")",
"{",
"// Open a popup from the toolbar",
"var",
"$popup",
"=",
"$",
"(",
"wysiwygeditor",
".",
"openPopup",
"(",
")",
")",
";",
"// if wrong popup -> create a new one",
"if",
"(",
"$popup",
".",
"hasClass",
"(",
"'wysiwyg-popup'",
")",
"&&",
"$popup",
".",
"hasClass",
"(",
"'wysiwyg-popuphover'",
")",
")",
"$popup",
"=",
"$",
"(",
"wysiwygeditor",
".",
"closePopup",
"(",
")",
".",
"openPopup",
"(",
")",
")",
";",
"if",
"(",
"!",
"$popup",
".",
"hasClass",
"(",
"'wysiwyg-popup'",
")",
")",
"// add classes + content",
"$popup",
".",
"addClass",
"(",
"'wysiwyg-popup'",
")",
";",
"return",
"$popup",
";",
"}",
",",
"function",
"(",
"$popup",
",",
"target",
",",
"overwrite_offset",
")",
"{",
"// Popup position",
"var",
"$button",
"=",
"$",
"(",
"target",
")",
";",
"var",
"popup_width",
"=",
"$popup",
".",
"outerWidth",
"(",
")",
";",
"// Point is the top/bottom-center of the button",
"var",
"left",
"=",
"$button",
".",
"offset",
"(",
")",
".",
"left",
"-",
"$container",
".",
"offset",
"(",
")",
".",
"left",
"+",
"parseInt",
"(",
"$button",
".",
"width",
"(",
")",
"/",
"2",
")",
"-",
"parseInt",
"(",
"popup_width",
"/",
"2",
")",
";",
"var",
"top",
"=",
"$button",
".",
"offset",
"(",
")",
".",
"top",
"-",
"$container",
".",
"offset",
"(",
")",
".",
"top",
";",
"if",
"(",
"toolbar_top",
")",
"top",
"+=",
"$button",
".",
"outerHeight",
"(",
")",
";",
"else",
"top",
"-=",
"$popup",
".",
"outerHeight",
"(",
")",
";",
"if",
"(",
"overwrite_offset",
")",
"{",
"left",
"=",
"overwrite_offset",
".",
"left",
";",
"top",
"=",
"overwrite_offset",
".",
"top",
";",
"}",
"popup_position",
"(",
"$popup",
",",
"$container",
",",
"left",
",",
"top",
")",
";",
"}",
")",
";",
"if",
"(",
"toolbar_top",
")",
"$container",
".",
"prepend",
"(",
"$toolbar",
")",
";",
"else",
"$container",
".",
"append",
"(",
"$toolbar",
")",
";",
"}"
] |
Callback to create toolbar on demand
|
[
"Callback",
"to",
"create",
"toolbar",
"on",
"demand"
] |
1fccde7040e0d504cd0d9cb371c88d800c733de0
|
https://github.com/wysiwygjs/wysiwyg.js/blob/1fccde7040e0d504cd0d9cb371c88d800c733de0/legacy/src/wysiwyg-editor.js#L858-L898
|
|
16,664
|
a5hik/ng-sortable
|
source/sortable-item-handle.js
|
isParent
|
function isParent(possibleParent, elem) {
if(!elem || elem.nodeName === 'HTML') {
return false;
}
if(elem.parentNode === possibleParent) {
return true;
}
return isParent(possibleParent, elem.parentNode);
}
|
javascript
|
function isParent(possibleParent, elem) {
if(!elem || elem.nodeName === 'HTML') {
return false;
}
if(elem.parentNode === possibleParent) {
return true;
}
return isParent(possibleParent, elem.parentNode);
}
|
[
"function",
"isParent",
"(",
"possibleParent",
",",
"elem",
")",
"{",
"if",
"(",
"!",
"elem",
"||",
"elem",
".",
"nodeName",
"===",
"'HTML'",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"elem",
".",
"parentNode",
"===",
"possibleParent",
")",
"{",
"return",
"true",
";",
"}",
"return",
"isParent",
"(",
"possibleParent",
",",
"elem",
".",
"parentNode",
")",
";",
"}"
] |
Check if a node is parent to another node
|
[
"Check",
"if",
"a",
"node",
"is",
"parent",
"to",
"another",
"node"
] |
8b5fd8f90bf7b77069ffe91812e35dcbca367510
|
https://github.com/a5hik/ng-sortable/blob/8b5fd8f90bf7b77069ffe91812e35dcbca367510/source/sortable-item-handle.js#L23-L33
|
16,665
|
a5hik/ng-sortable
|
source/sortable-item-handle.js
|
insertBefore
|
function insertBefore(targetElement, targetScope) {
// Ensure the placeholder is visible in the target (unless it's a table row)
if (placeHolder.css('display') !== 'table-row') {
placeHolder.css('display', 'block');
}
if (!targetScope.sortableScope.options.clone) {
targetElement[0].parentNode.insertBefore(placeHolder[0], targetElement[0]);
dragItemInfo.moveTo(targetScope.sortableScope, targetScope.index());
}
}
|
javascript
|
function insertBefore(targetElement, targetScope) {
// Ensure the placeholder is visible in the target (unless it's a table row)
if (placeHolder.css('display') !== 'table-row') {
placeHolder.css('display', 'block');
}
if (!targetScope.sortableScope.options.clone) {
targetElement[0].parentNode.insertBefore(placeHolder[0], targetElement[0]);
dragItemInfo.moveTo(targetScope.sortableScope, targetScope.index());
}
}
|
[
"function",
"insertBefore",
"(",
"targetElement",
",",
"targetScope",
")",
"{",
"// Ensure the placeholder is visible in the target (unless it's a table row)",
"if",
"(",
"placeHolder",
".",
"css",
"(",
"'display'",
")",
"!==",
"'table-row'",
")",
"{",
"placeHolder",
".",
"css",
"(",
"'display'",
",",
"'block'",
")",
";",
"}",
"if",
"(",
"!",
"targetScope",
".",
"sortableScope",
".",
"options",
".",
"clone",
")",
"{",
"targetElement",
"[",
"0",
"]",
".",
"parentNode",
".",
"insertBefore",
"(",
"placeHolder",
"[",
"0",
"]",
",",
"targetElement",
"[",
"0",
"]",
")",
";",
"dragItemInfo",
".",
"moveTo",
"(",
"targetScope",
".",
"sortableScope",
",",
"targetScope",
".",
"index",
"(",
")",
")",
";",
"}",
"}"
] |
Inserts the placeHolder in to the targetScope.
@param targetElement the target element
@param targetScope the target scope
|
[
"Inserts",
"the",
"placeHolder",
"in",
"to",
"the",
"targetScope",
"."
] |
8b5fd8f90bf7b77069ffe91812e35dcbca367510
|
https://github.com/a5hik/ng-sortable/blob/8b5fd8f90bf7b77069ffe91812e35dcbca367510/source/sortable-item-handle.js#L285-L294
|
16,666
|
a5hik/ng-sortable
|
source/sortable-item-handle.js
|
insertAfter
|
function insertAfter(targetElement, targetScope) {
// Ensure the placeholder is visible in the target (unless it's a table row)
if (placeHolder.css('display') !== 'table-row') {
placeHolder.css('display', 'block');
}
if (!targetScope.sortableScope.options.clone) {
targetElement.after(placeHolder);
dragItemInfo.moveTo(targetScope.sortableScope, targetScope.index() + 1);
}
}
|
javascript
|
function insertAfter(targetElement, targetScope) {
// Ensure the placeholder is visible in the target (unless it's a table row)
if (placeHolder.css('display') !== 'table-row') {
placeHolder.css('display', 'block');
}
if (!targetScope.sortableScope.options.clone) {
targetElement.after(placeHolder);
dragItemInfo.moveTo(targetScope.sortableScope, targetScope.index() + 1);
}
}
|
[
"function",
"insertAfter",
"(",
"targetElement",
",",
"targetScope",
")",
"{",
"// Ensure the placeholder is visible in the target (unless it's a table row)",
"if",
"(",
"placeHolder",
".",
"css",
"(",
"'display'",
")",
"!==",
"'table-row'",
")",
"{",
"placeHolder",
".",
"css",
"(",
"'display'",
",",
"'block'",
")",
";",
"}",
"if",
"(",
"!",
"targetScope",
".",
"sortableScope",
".",
"options",
".",
"clone",
")",
"{",
"targetElement",
".",
"after",
"(",
"placeHolder",
")",
";",
"dragItemInfo",
".",
"moveTo",
"(",
"targetScope",
".",
"sortableScope",
",",
"targetScope",
".",
"index",
"(",
")",
"+",
"1",
")",
";",
"}",
"}"
] |
Inserts the placeHolder next to the targetScope.
@param targetElement the target element
@param targetScope the target scope
|
[
"Inserts",
"the",
"placeHolder",
"next",
"to",
"the",
"targetScope",
"."
] |
8b5fd8f90bf7b77069ffe91812e35dcbca367510
|
https://github.com/a5hik/ng-sortable/blob/8b5fd8f90bf7b77069ffe91812e35dcbca367510/source/sortable-item-handle.js#L302-L311
|
16,667
|
a5hik/ng-sortable
|
source/sortable-item-handle.js
|
fetchScope
|
function fetchScope(element) {
var scope;
while (!scope && element.length) {
scope = element.data('_scope');
if (!scope) {
element = element.parent();
}
}
return scope;
}
|
javascript
|
function fetchScope(element) {
var scope;
while (!scope && element.length) {
scope = element.data('_scope');
if (!scope) {
element = element.parent();
}
}
return scope;
}
|
[
"function",
"fetchScope",
"(",
"element",
")",
"{",
"var",
"scope",
";",
"while",
"(",
"!",
"scope",
"&&",
"element",
".",
"length",
")",
"{",
"scope",
"=",
"element",
".",
"data",
"(",
"'_scope'",
")",
";",
"if",
"(",
"!",
"scope",
")",
"{",
"element",
"=",
"element",
".",
"parent",
"(",
")",
";",
"}",
"}",
"return",
"scope",
";",
"}"
] |
Fetch scope from element or parents
@param {object} element Source element
@return {object} Scope, or null if not found
|
[
"Fetch",
"scope",
"from",
"element",
"or",
"parents"
] |
8b5fd8f90bf7b77069ffe91812e35dcbca367510
|
https://github.com/a5hik/ng-sortable/blob/8b5fd8f90bf7b77069ffe91812e35dcbca367510/source/sortable-item-handle.js#L409-L418
|
16,668
|
a5hik/ng-sortable
|
source/sortable-item-handle.js
|
rollbackDragChanges
|
function rollbackDragChanges() {
if (!scope.itemScope.sortableScope.cloning) {
placeElement.replaceWith(scope.itemScope.element);
}
placeHolder.remove();
dragElement.remove();
dragElement = null;
dragHandled = false;
containment.css('cursor', '');
containment.removeClass('as-sortable-un-selectable');
}
|
javascript
|
function rollbackDragChanges() {
if (!scope.itemScope.sortableScope.cloning) {
placeElement.replaceWith(scope.itemScope.element);
}
placeHolder.remove();
dragElement.remove();
dragElement = null;
dragHandled = false;
containment.css('cursor', '');
containment.removeClass('as-sortable-un-selectable');
}
|
[
"function",
"rollbackDragChanges",
"(",
")",
"{",
"if",
"(",
"!",
"scope",
".",
"itemScope",
".",
"sortableScope",
".",
"cloning",
")",
"{",
"placeElement",
".",
"replaceWith",
"(",
"scope",
".",
"itemScope",
".",
"element",
")",
";",
"}",
"placeHolder",
".",
"remove",
"(",
")",
";",
"dragElement",
".",
"remove",
"(",
")",
";",
"dragElement",
"=",
"null",
";",
"dragHandled",
"=",
"false",
";",
"containment",
".",
"css",
"(",
"'cursor'",
",",
"''",
")",
";",
"containment",
".",
"removeClass",
"(",
"'as-sortable-un-selectable'",
")",
";",
"}"
] |
Rollback the drag data changes.
|
[
"Rollback",
"the",
"drag",
"data",
"changes",
"."
] |
8b5fd8f90bf7b77069ffe91812e35dcbca367510
|
https://github.com/a5hik/ng-sortable/blob/8b5fd8f90bf7b77069ffe91812e35dcbca367510/source/sortable-item-handle.js#L458-L468
|
16,669
|
a5hik/ng-sortable
|
source/sortable-helper.js
|
function (event) {
var obj = event;
if (event.targetTouches !== undefined) {
obj = event.targetTouches.item(0);
} else if (event.originalEvent !== undefined && event.originalEvent.targetTouches !== undefined) {
obj = event.originalEvent.targetTouches.item(0);
}
return obj;
}
|
javascript
|
function (event) {
var obj = event;
if (event.targetTouches !== undefined) {
obj = event.targetTouches.item(0);
} else if (event.originalEvent !== undefined && event.originalEvent.targetTouches !== undefined) {
obj = event.originalEvent.targetTouches.item(0);
}
return obj;
}
|
[
"function",
"(",
"event",
")",
"{",
"var",
"obj",
"=",
"event",
";",
"if",
"(",
"event",
".",
"targetTouches",
"!==",
"undefined",
")",
"{",
"obj",
"=",
"event",
".",
"targetTouches",
".",
"item",
"(",
"0",
")",
";",
"}",
"else",
"if",
"(",
"event",
".",
"originalEvent",
"!==",
"undefined",
"&&",
"event",
".",
"originalEvent",
".",
"targetTouches",
"!==",
"undefined",
")",
"{",
"obj",
"=",
"event",
".",
"originalEvent",
".",
"targetTouches",
".",
"item",
"(",
"0",
")",
";",
"}",
"return",
"obj",
";",
"}"
] |
get the event object for touch.
@param {Object} event the touch event
@return {Object} the touch event object.
|
[
"get",
"the",
"event",
"object",
"for",
"touch",
"."
] |
8b5fd8f90bf7b77069ffe91812e35dcbca367510
|
https://github.com/a5hik/ng-sortable/blob/8b5fd8f90bf7b77069ffe91812e35dcbca367510/source/sortable-helper.js#L63-L71
|
|
16,670
|
a5hik/ng-sortable
|
source/sortable-helper.js
|
function (event) {
var touchInvalid = false;
if (event.touches !== undefined && event.touches.length > 1) {
touchInvalid = true;
} else if (event.originalEvent !== undefined &&
event.originalEvent.touches !== undefined && event.originalEvent.touches.length > 1) {
touchInvalid = true;
}
return touchInvalid;
}
|
javascript
|
function (event) {
var touchInvalid = false;
if (event.touches !== undefined && event.touches.length > 1) {
touchInvalid = true;
} else if (event.originalEvent !== undefined &&
event.originalEvent.touches !== undefined && event.originalEvent.touches.length > 1) {
touchInvalid = true;
}
return touchInvalid;
}
|
[
"function",
"(",
"event",
")",
"{",
"var",
"touchInvalid",
"=",
"false",
";",
"if",
"(",
"event",
".",
"touches",
"!==",
"undefined",
"&&",
"event",
".",
"touches",
".",
"length",
">",
"1",
")",
"{",
"touchInvalid",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"event",
".",
"originalEvent",
"!==",
"undefined",
"&&",
"event",
".",
"originalEvent",
".",
"touches",
"!==",
"undefined",
"&&",
"event",
".",
"originalEvent",
".",
"touches",
".",
"length",
">",
"1",
")",
"{",
"touchInvalid",
"=",
"true",
";",
"}",
"return",
"touchInvalid",
";",
"}"
] |
Checks whether the touch is valid and multiple.
@param event the event object.
@returns {boolean} true if touch is multiple.
|
[
"Checks",
"whether",
"the",
"touch",
"is",
"valid",
"and",
"multiple",
"."
] |
8b5fd8f90bf7b77069ffe91812e35dcbca367510
|
https://github.com/a5hik/ng-sortable/blob/8b5fd8f90bf7b77069ffe91812e35dcbca367510/source/sortable-helper.js#L79-L89
|
|
16,671
|
a5hik/ng-sortable
|
source/sortable-helper.js
|
function (event, target, scrollableContainer) {
var pos = {};
pos.offsetX = event.pageX - this.offset(target, scrollableContainer).left;
pos.offsetY = event.pageY - this.offset(target, scrollableContainer).top;
pos.startX = pos.lastX = event.pageX;
pos.startY = pos.lastY = event.pageY;
pos.nowX = pos.nowY = pos.distX = pos.distY = pos.dirAx = 0;
pos.dirX = pos.dirY = pos.lastDirX = pos.lastDirY = pos.distAxX = pos.distAxY = 0;
return pos;
}
|
javascript
|
function (event, target, scrollableContainer) {
var pos = {};
pos.offsetX = event.pageX - this.offset(target, scrollableContainer).left;
pos.offsetY = event.pageY - this.offset(target, scrollableContainer).top;
pos.startX = pos.lastX = event.pageX;
pos.startY = pos.lastY = event.pageY;
pos.nowX = pos.nowY = pos.distX = pos.distY = pos.dirAx = 0;
pos.dirX = pos.dirY = pos.lastDirX = pos.lastDirY = pos.distAxX = pos.distAxY = 0;
return pos;
}
|
[
"function",
"(",
"event",
",",
"target",
",",
"scrollableContainer",
")",
"{",
"var",
"pos",
"=",
"{",
"}",
";",
"pos",
".",
"offsetX",
"=",
"event",
".",
"pageX",
"-",
"this",
".",
"offset",
"(",
"target",
",",
"scrollableContainer",
")",
".",
"left",
";",
"pos",
".",
"offsetY",
"=",
"event",
".",
"pageY",
"-",
"this",
".",
"offset",
"(",
"target",
",",
"scrollableContainer",
")",
".",
"top",
";",
"pos",
".",
"startX",
"=",
"pos",
".",
"lastX",
"=",
"event",
".",
"pageX",
";",
"pos",
".",
"startY",
"=",
"pos",
".",
"lastY",
"=",
"event",
".",
"pageY",
";",
"pos",
".",
"nowX",
"=",
"pos",
".",
"nowY",
"=",
"pos",
".",
"distX",
"=",
"pos",
".",
"distY",
"=",
"pos",
".",
"dirAx",
"=",
"0",
";",
"pos",
".",
"dirX",
"=",
"pos",
".",
"dirY",
"=",
"pos",
".",
"lastDirX",
"=",
"pos",
".",
"lastDirY",
"=",
"pos",
".",
"distAxX",
"=",
"pos",
".",
"distAxY",
"=",
"0",
";",
"return",
"pos",
";",
"}"
] |
Get the start position of the target element according to the provided event properties.
@param {Object} event Event
@param {Object} target Target element
@param {Object} [scrollableContainer] (optional) Scrollable container object
@returns {Object} Object with properties offsetX, offsetY.
|
[
"Get",
"the",
"start",
"position",
"of",
"the",
"target",
"element",
"according",
"to",
"the",
"provided",
"event",
"properties",
"."
] |
8b5fd8f90bf7b77069ffe91812e35dcbca367510
|
https://github.com/a5hik/ng-sortable/blob/8b5fd8f90bf7b77069ffe91812e35dcbca367510/source/sortable-helper.js#L99-L108
|
|
16,672
|
a5hik/ng-sortable
|
source/sortable-helper.js
|
function (pos, event) {
// mouse position last events
pos.lastX = pos.nowX;
pos.lastY = pos.nowY;
// mouse position this events
pos.nowX = event.pageX;
pos.nowY = event.pageY;
// distance mouse moved between events
pos.distX = pos.nowX - pos.lastX;
pos.distY = pos.nowY - pos.lastY;
// direction mouse was moving
pos.lastDirX = pos.dirX;
pos.lastDirY = pos.dirY;
// direction mouse is now moving (on both axis)
pos.dirX = pos.distX === 0 ? 0 : pos.distX > 0 ? 1 : -1;
pos.dirY = pos.distY === 0 ? 0 : pos.distY > 0 ? 1 : -1;
// axis mouse is now moving on
var newAx = Math.abs(pos.distX) > Math.abs(pos.distY) ? 1 : 0;
// calc distance moved on this axis (and direction)
if (pos.dirAx !== newAx) {
pos.distAxX = 0;
pos.distAxY = 0;
} else {
pos.distAxX += Math.abs(pos.distX);
if (pos.dirX !== 0 && pos.dirX !== pos.lastDirX) {
pos.distAxX = 0;
}
pos.distAxY += Math.abs(pos.distY);
if (pos.dirY !== 0 && pos.dirY !== pos.lastDirY) {
pos.distAxY = 0;
}
}
pos.dirAx = newAx;
}
|
javascript
|
function (pos, event) {
// mouse position last events
pos.lastX = pos.nowX;
pos.lastY = pos.nowY;
// mouse position this events
pos.nowX = event.pageX;
pos.nowY = event.pageY;
// distance mouse moved between events
pos.distX = pos.nowX - pos.lastX;
pos.distY = pos.nowY - pos.lastY;
// direction mouse was moving
pos.lastDirX = pos.dirX;
pos.lastDirY = pos.dirY;
// direction mouse is now moving (on both axis)
pos.dirX = pos.distX === 0 ? 0 : pos.distX > 0 ? 1 : -1;
pos.dirY = pos.distY === 0 ? 0 : pos.distY > 0 ? 1 : -1;
// axis mouse is now moving on
var newAx = Math.abs(pos.distX) > Math.abs(pos.distY) ? 1 : 0;
// calc distance moved on this axis (and direction)
if (pos.dirAx !== newAx) {
pos.distAxX = 0;
pos.distAxY = 0;
} else {
pos.distAxX += Math.abs(pos.distX);
if (pos.dirX !== 0 && pos.dirX !== pos.lastDirX) {
pos.distAxX = 0;
}
pos.distAxY += Math.abs(pos.distY);
if (pos.dirY !== 0 && pos.dirY !== pos.lastDirY) {
pos.distAxY = 0;
}
}
pos.dirAx = newAx;
}
|
[
"function",
"(",
"pos",
",",
"event",
")",
"{",
"// mouse position last events",
"pos",
".",
"lastX",
"=",
"pos",
".",
"nowX",
";",
"pos",
".",
"lastY",
"=",
"pos",
".",
"nowY",
";",
"// mouse position this events",
"pos",
".",
"nowX",
"=",
"event",
".",
"pageX",
";",
"pos",
".",
"nowY",
"=",
"event",
".",
"pageY",
";",
"// distance mouse moved between events",
"pos",
".",
"distX",
"=",
"pos",
".",
"nowX",
"-",
"pos",
".",
"lastX",
";",
"pos",
".",
"distY",
"=",
"pos",
".",
"nowY",
"-",
"pos",
".",
"lastY",
";",
"// direction mouse was moving",
"pos",
".",
"lastDirX",
"=",
"pos",
".",
"dirX",
";",
"pos",
".",
"lastDirY",
"=",
"pos",
".",
"dirY",
";",
"// direction mouse is now moving (on both axis)",
"pos",
".",
"dirX",
"=",
"pos",
".",
"distX",
"===",
"0",
"?",
"0",
":",
"pos",
".",
"distX",
">",
"0",
"?",
"1",
":",
"-",
"1",
";",
"pos",
".",
"dirY",
"=",
"pos",
".",
"distY",
"===",
"0",
"?",
"0",
":",
"pos",
".",
"distY",
">",
"0",
"?",
"1",
":",
"-",
"1",
";",
"// axis mouse is now moving on",
"var",
"newAx",
"=",
"Math",
".",
"abs",
"(",
"pos",
".",
"distX",
")",
">",
"Math",
".",
"abs",
"(",
"pos",
".",
"distY",
")",
"?",
"1",
":",
"0",
";",
"// calc distance moved on this axis (and direction)",
"if",
"(",
"pos",
".",
"dirAx",
"!==",
"newAx",
")",
"{",
"pos",
".",
"distAxX",
"=",
"0",
";",
"pos",
".",
"distAxY",
"=",
"0",
";",
"}",
"else",
"{",
"pos",
".",
"distAxX",
"+=",
"Math",
".",
"abs",
"(",
"pos",
".",
"distX",
")",
";",
"if",
"(",
"pos",
".",
"dirX",
"!==",
"0",
"&&",
"pos",
".",
"dirX",
"!==",
"pos",
".",
"lastDirX",
")",
"{",
"pos",
".",
"distAxX",
"=",
"0",
";",
"}",
"pos",
".",
"distAxY",
"+=",
"Math",
".",
"abs",
"(",
"pos",
".",
"distY",
")",
";",
"if",
"(",
"pos",
".",
"dirY",
"!==",
"0",
"&&",
"pos",
".",
"dirY",
"!==",
"pos",
".",
"lastDirY",
")",
"{",
"pos",
".",
"distAxY",
"=",
"0",
";",
"}",
"}",
"pos",
".",
"dirAx",
"=",
"newAx",
";",
"}"
] |
Calculates the event position and sets the direction
properties.
@param pos the current position of the element.
@param event the move event.
|
[
"Calculates",
"the",
"event",
"position",
"and",
"sets",
"the",
"direction",
"properties",
"."
] |
8b5fd8f90bf7b77069ffe91812e35dcbca367510
|
https://github.com/a5hik/ng-sortable/blob/8b5fd8f90bf7b77069ffe91812e35dcbca367510/source/sortable-helper.js#L117-L157
|
|
16,673
|
a5hik/ng-sortable
|
source/sortable-helper.js
|
function (event, element, pos, container, containerPositioning, scrollableContainer) {
var bounds;
var useRelative = (containerPositioning === 'relative');
element.x = event.pageX - pos.offsetX;
element.y = event.pageY - pos.offsetY;
if (container) {
bounds = this.offset(container, scrollableContainer);
if (useRelative) {
// reduce positioning by bounds
element.x -= bounds.left;
element.y -= bounds.top;
// reset bounds
bounds.left = 0;
bounds.top = 0;
}
if (element.x < bounds.left) {
element.x = bounds.left;
} else if (element.x >= bounds.width + bounds.left - this.offset(element).width) {
element.x = bounds.width + bounds.left - this.offset(element).width;
}
if (element.y < bounds.top) {
element.y = bounds.top;
} else if (element.y >= bounds.height + bounds.top - this.offset(element).height) {
element.y = bounds.height + bounds.top - this.offset(element).height;
}
}
element.css({
'left': element.x + 'px',
'top': element.y + 'px'
});
this.calculatePosition(pos, event);
}
|
javascript
|
function (event, element, pos, container, containerPositioning, scrollableContainer) {
var bounds;
var useRelative = (containerPositioning === 'relative');
element.x = event.pageX - pos.offsetX;
element.y = event.pageY - pos.offsetY;
if (container) {
bounds = this.offset(container, scrollableContainer);
if (useRelative) {
// reduce positioning by bounds
element.x -= bounds.left;
element.y -= bounds.top;
// reset bounds
bounds.left = 0;
bounds.top = 0;
}
if (element.x < bounds.left) {
element.x = bounds.left;
} else if (element.x >= bounds.width + bounds.left - this.offset(element).width) {
element.x = bounds.width + bounds.left - this.offset(element).width;
}
if (element.y < bounds.top) {
element.y = bounds.top;
} else if (element.y >= bounds.height + bounds.top - this.offset(element).height) {
element.y = bounds.height + bounds.top - this.offset(element).height;
}
}
element.css({
'left': element.x + 'px',
'top': element.y + 'px'
});
this.calculatePosition(pos, event);
}
|
[
"function",
"(",
"event",
",",
"element",
",",
"pos",
",",
"container",
",",
"containerPositioning",
",",
"scrollableContainer",
")",
"{",
"var",
"bounds",
";",
"var",
"useRelative",
"=",
"(",
"containerPositioning",
"===",
"'relative'",
")",
";",
"element",
".",
"x",
"=",
"event",
".",
"pageX",
"-",
"pos",
".",
"offsetX",
";",
"element",
".",
"y",
"=",
"event",
".",
"pageY",
"-",
"pos",
".",
"offsetY",
";",
"if",
"(",
"container",
")",
"{",
"bounds",
"=",
"this",
".",
"offset",
"(",
"container",
",",
"scrollableContainer",
")",
";",
"if",
"(",
"useRelative",
")",
"{",
"// reduce positioning by bounds",
"element",
".",
"x",
"-=",
"bounds",
".",
"left",
";",
"element",
".",
"y",
"-=",
"bounds",
".",
"top",
";",
"// reset bounds",
"bounds",
".",
"left",
"=",
"0",
";",
"bounds",
".",
"top",
"=",
"0",
";",
"}",
"if",
"(",
"element",
".",
"x",
"<",
"bounds",
".",
"left",
")",
"{",
"element",
".",
"x",
"=",
"bounds",
".",
"left",
";",
"}",
"else",
"if",
"(",
"element",
".",
"x",
">=",
"bounds",
".",
"width",
"+",
"bounds",
".",
"left",
"-",
"this",
".",
"offset",
"(",
"element",
")",
".",
"width",
")",
"{",
"element",
".",
"x",
"=",
"bounds",
".",
"width",
"+",
"bounds",
".",
"left",
"-",
"this",
".",
"offset",
"(",
"element",
")",
".",
"width",
";",
"}",
"if",
"(",
"element",
".",
"y",
"<",
"bounds",
".",
"top",
")",
"{",
"element",
".",
"y",
"=",
"bounds",
".",
"top",
";",
"}",
"else",
"if",
"(",
"element",
".",
"y",
">=",
"bounds",
".",
"height",
"+",
"bounds",
".",
"top",
"-",
"this",
".",
"offset",
"(",
"element",
")",
".",
"height",
")",
"{",
"element",
".",
"y",
"=",
"bounds",
".",
"height",
"+",
"bounds",
".",
"top",
"-",
"this",
".",
"offset",
"(",
"element",
")",
".",
"height",
";",
"}",
"}",
"element",
".",
"css",
"(",
"{",
"'left'",
":",
"element",
".",
"x",
"+",
"'px'",
",",
"'top'",
":",
"element",
".",
"y",
"+",
"'px'",
"}",
")",
";",
"this",
".",
"calculatePosition",
"(",
"pos",
",",
"event",
")",
";",
"}"
] |
Move the position by applying style.
@param event the event object
@param element - the dom element
@param pos - current position
@param container - the bounding container.
@param containerPositioning - absolute or relative positioning.
@param {Object} [scrollableContainer] (optional) Scrollable container object
|
[
"Move",
"the",
"position",
"by",
"applying",
"style",
"."
] |
8b5fd8f90bf7b77069ffe91812e35dcbca367510
|
https://github.com/a5hik/ng-sortable/blob/8b5fd8f90bf7b77069ffe91812e35dcbca367510/source/sortable-helper.js#L169-L207
|
|
16,674
|
a5hik/ng-sortable
|
source/sortable-helper.js
|
function (item) {
return {
index: item.index(),
parent: item.sortableScope,
source: item,
targetElement: null,
targetElementOffset: null,
sourceInfo: {
index: item.index(),
itemScope: item.itemScope,
sortableScope: item.sortableScope
},
canMove: function(itemPosition, targetElement, targetElementOffset) {
// return true if targetElement has been changed since last call
if (this.targetElement !== targetElement) {
this.targetElement = targetElement;
this.targetElementOffset = targetElementOffset;
return true;
}
// return true if mouse is moving in the last moving direction of targetElement
if (itemPosition.dirX * (targetElementOffset.left - this.targetElementOffset.left) > 0 ||
itemPosition.dirY * (targetElementOffset.top - this.targetElementOffset.top) > 0) {
this.targetElementOffset = targetElementOffset;
return true;
}
// return false otherwise
return false;
},
moveTo: function (parent, index) {
// move the item to a new position
this.parent = parent;
// if the source item is in the same parent, the target index is after the source index and we're not cloning
if (this.isSameParent() && this.source.index() < index && !this.sourceInfo.sortableScope.cloning) {
index = index - 1;
}
this.index = index;
},
isSameParent: function () {
return this.parent.element === this.sourceInfo.sortableScope.element;
},
isOrderChanged: function () {
return this.index !== this.sourceInfo.index;
},
eventArgs: function () {
return {
source: this.sourceInfo,
dest: {
index: this.index,
sortableScope: this.parent
}
};
},
apply: function () {
if (!this.sourceInfo.sortableScope.cloning) {
// if not cloning, remove the item from the source model.
this.sourceInfo.sortableScope.removeItem(this.sourceInfo.index);
// if the dragged item is not already there, insert the item. This avoids ng-repeat dupes error
if (this.parent.options.allowDuplicates || this.parent.modelValue.indexOf(this.source.modelValue) < 0) {
this.parent.insertItem(this.index, this.source.modelValue);
}
} else if (!this.parent.options.clone) { // prevent drop inside sortables that specify options.clone = true
// clone the model value as well
this.parent.insertItem(this.index, angular.copy(this.source.modelValue));
}
}
};
}
|
javascript
|
function (item) {
return {
index: item.index(),
parent: item.sortableScope,
source: item,
targetElement: null,
targetElementOffset: null,
sourceInfo: {
index: item.index(),
itemScope: item.itemScope,
sortableScope: item.sortableScope
},
canMove: function(itemPosition, targetElement, targetElementOffset) {
// return true if targetElement has been changed since last call
if (this.targetElement !== targetElement) {
this.targetElement = targetElement;
this.targetElementOffset = targetElementOffset;
return true;
}
// return true if mouse is moving in the last moving direction of targetElement
if (itemPosition.dirX * (targetElementOffset.left - this.targetElementOffset.left) > 0 ||
itemPosition.dirY * (targetElementOffset.top - this.targetElementOffset.top) > 0) {
this.targetElementOffset = targetElementOffset;
return true;
}
// return false otherwise
return false;
},
moveTo: function (parent, index) {
// move the item to a new position
this.parent = parent;
// if the source item is in the same parent, the target index is after the source index and we're not cloning
if (this.isSameParent() && this.source.index() < index && !this.sourceInfo.sortableScope.cloning) {
index = index - 1;
}
this.index = index;
},
isSameParent: function () {
return this.parent.element === this.sourceInfo.sortableScope.element;
},
isOrderChanged: function () {
return this.index !== this.sourceInfo.index;
},
eventArgs: function () {
return {
source: this.sourceInfo,
dest: {
index: this.index,
sortableScope: this.parent
}
};
},
apply: function () {
if (!this.sourceInfo.sortableScope.cloning) {
// if not cloning, remove the item from the source model.
this.sourceInfo.sortableScope.removeItem(this.sourceInfo.index);
// if the dragged item is not already there, insert the item. This avoids ng-repeat dupes error
if (this.parent.options.allowDuplicates || this.parent.modelValue.indexOf(this.source.modelValue) < 0) {
this.parent.insertItem(this.index, this.source.modelValue);
}
} else if (!this.parent.options.clone) { // prevent drop inside sortables that specify options.clone = true
// clone the model value as well
this.parent.insertItem(this.index, angular.copy(this.source.modelValue));
}
}
};
}
|
[
"function",
"(",
"item",
")",
"{",
"return",
"{",
"index",
":",
"item",
".",
"index",
"(",
")",
",",
"parent",
":",
"item",
".",
"sortableScope",
",",
"source",
":",
"item",
",",
"targetElement",
":",
"null",
",",
"targetElementOffset",
":",
"null",
",",
"sourceInfo",
":",
"{",
"index",
":",
"item",
".",
"index",
"(",
")",
",",
"itemScope",
":",
"item",
".",
"itemScope",
",",
"sortableScope",
":",
"item",
".",
"sortableScope",
"}",
",",
"canMove",
":",
"function",
"(",
"itemPosition",
",",
"targetElement",
",",
"targetElementOffset",
")",
"{",
"// return true if targetElement has been changed since last call",
"if",
"(",
"this",
".",
"targetElement",
"!==",
"targetElement",
")",
"{",
"this",
".",
"targetElement",
"=",
"targetElement",
";",
"this",
".",
"targetElementOffset",
"=",
"targetElementOffset",
";",
"return",
"true",
";",
"}",
"// return true if mouse is moving in the last moving direction of targetElement",
"if",
"(",
"itemPosition",
".",
"dirX",
"*",
"(",
"targetElementOffset",
".",
"left",
"-",
"this",
".",
"targetElementOffset",
".",
"left",
")",
">",
"0",
"||",
"itemPosition",
".",
"dirY",
"*",
"(",
"targetElementOffset",
".",
"top",
"-",
"this",
".",
"targetElementOffset",
".",
"top",
")",
">",
"0",
")",
"{",
"this",
".",
"targetElementOffset",
"=",
"targetElementOffset",
";",
"return",
"true",
";",
"}",
"// return false otherwise",
"return",
"false",
";",
"}",
",",
"moveTo",
":",
"function",
"(",
"parent",
",",
"index",
")",
"{",
"// move the item to a new position",
"this",
".",
"parent",
"=",
"parent",
";",
"// if the source item is in the same parent, the target index is after the source index and we're not cloning",
"if",
"(",
"this",
".",
"isSameParent",
"(",
")",
"&&",
"this",
".",
"source",
".",
"index",
"(",
")",
"<",
"index",
"&&",
"!",
"this",
".",
"sourceInfo",
".",
"sortableScope",
".",
"cloning",
")",
"{",
"index",
"=",
"index",
"-",
"1",
";",
"}",
"this",
".",
"index",
"=",
"index",
";",
"}",
",",
"isSameParent",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"parent",
".",
"element",
"===",
"this",
".",
"sourceInfo",
".",
"sortableScope",
".",
"element",
";",
"}",
",",
"isOrderChanged",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"index",
"!==",
"this",
".",
"sourceInfo",
".",
"index",
";",
"}",
",",
"eventArgs",
":",
"function",
"(",
")",
"{",
"return",
"{",
"source",
":",
"this",
".",
"sourceInfo",
",",
"dest",
":",
"{",
"index",
":",
"this",
".",
"index",
",",
"sortableScope",
":",
"this",
".",
"parent",
"}",
"}",
";",
"}",
",",
"apply",
":",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"sourceInfo",
".",
"sortableScope",
".",
"cloning",
")",
"{",
"// if not cloning, remove the item from the source model.",
"this",
".",
"sourceInfo",
".",
"sortableScope",
".",
"removeItem",
"(",
"this",
".",
"sourceInfo",
".",
"index",
")",
";",
"// if the dragged item is not already there, insert the item. This avoids ng-repeat dupes error",
"if",
"(",
"this",
".",
"parent",
".",
"options",
".",
"allowDuplicates",
"||",
"this",
".",
"parent",
".",
"modelValue",
".",
"indexOf",
"(",
"this",
".",
"source",
".",
"modelValue",
")",
"<",
"0",
")",
"{",
"this",
".",
"parent",
".",
"insertItem",
"(",
"this",
".",
"index",
",",
"this",
".",
"source",
".",
"modelValue",
")",
";",
"}",
"}",
"else",
"if",
"(",
"!",
"this",
".",
"parent",
".",
"options",
".",
"clone",
")",
"{",
"// prevent drop inside sortables that specify options.clone = true",
"// clone the model value as well",
"this",
".",
"parent",
".",
"insertItem",
"(",
"this",
".",
"index",
",",
"angular",
".",
"copy",
"(",
"this",
".",
"source",
".",
"modelValue",
")",
")",
";",
"}",
"}",
"}",
";",
"}"
] |
The drag item info and functions.
retains the item info before and after move.
holds source item and target scope.
@param item - the drag item
@returns {{index: *, parent: *, source: *,
sourceInfo: {index: *, itemScope: (*|.dragItem.sourceInfo.itemScope|$scope.itemScope|itemScope), sortableScope: *},
moveTo: moveTo, isSameParent: isSameParent, isOrderChanged: isOrderChanged, eventArgs: eventArgs, apply: apply}}
|
[
"The",
"drag",
"item",
"info",
"and",
"functions",
".",
"retains",
"the",
"item",
"info",
"before",
"and",
"after",
"move",
".",
"holds",
"source",
"item",
"and",
"target",
"scope",
"."
] |
8b5fd8f90bf7b77069ffe91812e35dcbca367510
|
https://github.com/a5hik/ng-sortable/blob/8b5fd8f90bf7b77069ffe91812e35dcbca367510/source/sortable-helper.js#L219-L287
|
|
16,675
|
a5hik/ng-sortable
|
source/sortable-helper.js
|
function (el, selector) {
el = el[0];
var matches = Element.matches || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector;
while ((el = el.parentElement) && !matches.call(el, selector)) {
}
return el ? angular.element(el) : angular.element(document.body);
}
|
javascript
|
function (el, selector) {
el = el[0];
var matches = Element.matches || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector;
while ((el = el.parentElement) && !matches.call(el, selector)) {
}
return el ? angular.element(el) : angular.element(document.body);
}
|
[
"function",
"(",
"el",
",",
"selector",
")",
"{",
"el",
"=",
"el",
"[",
"0",
"]",
";",
"var",
"matches",
"=",
"Element",
".",
"matches",
"||",
"Element",
".",
"prototype",
".",
"mozMatchesSelector",
"||",
"Element",
".",
"prototype",
".",
"msMatchesSelector",
"||",
"Element",
".",
"prototype",
".",
"oMatchesSelector",
"||",
"Element",
".",
"prototype",
".",
"webkitMatchesSelector",
";",
"while",
"(",
"(",
"el",
"=",
"el",
".",
"parentElement",
")",
"&&",
"!",
"matches",
".",
"call",
"(",
"el",
",",
"selector",
")",
")",
"{",
"}",
"return",
"el",
"?",
"angular",
".",
"element",
"(",
"el",
")",
":",
"angular",
".",
"element",
"(",
"document",
".",
"body",
")",
";",
"}"
] |
Helper function to find the first ancestor with a given selector
@param el - angular element to start looking at
@param selector - selector to find the parent
@returns {Object} - Angular element of the ancestor or body if not found
@private
|
[
"Helper",
"function",
"to",
"find",
"the",
"first",
"ancestor",
"with",
"a",
"given",
"selector"
] |
8b5fd8f90bf7b77069ffe91812e35dcbca367510
|
https://github.com/a5hik/ng-sortable/blob/8b5fd8f90bf7b77069ffe91812e35dcbca367510/source/sortable-helper.js#L306-L312
|
|
16,676
|
Azure/node-red-contrib-azure
|
event-hub/azureeventhub2.js
|
printResultFor
|
function printResultFor(node, op) {
return function printResult(err, res) {
if (err) node.error(op + ' error: ' + err.toString());
if (res) node.log(op + ' status: ' + res.constructor.name);
};
}
|
javascript
|
function printResultFor(node, op) {
return function printResult(err, res) {
if (err) node.error(op + ' error: ' + err.toString());
if (res) node.log(op + ' status: ' + res.constructor.name);
};
}
|
[
"function",
"printResultFor",
"(",
"node",
",",
"op",
")",
"{",
"return",
"function",
"printResult",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"node",
".",
"error",
"(",
"op",
"+",
"' error: '",
"+",
"err",
".",
"toString",
"(",
")",
")",
";",
"if",
"(",
"res",
")",
"node",
".",
"log",
"(",
"op",
"+",
"' status: '",
"+",
"res",
".",
"constructor",
".",
"name",
")",
";",
"}",
";",
"}"
] |
Helper function to print results in the console
|
[
"Helper",
"function",
"to",
"print",
"results",
"in",
"the",
"console"
] |
12b117c67385b019b1dd92ff689974674c1a4e87
|
https://github.com/Azure/node-red-contrib-azure/blob/12b117c67385b019b1dd92ff689974674c1a4e87/event-hub/azureeventhub2.js#L132-L137
|
16,677
|
wdfe/wdui
|
src/utils/Scroller.js
|
function(factor, animate, originLeft, originTop, callback) {
let self = this
self.zoomTo(self.__zoomLevel * factor, animate, originLeft, originTop, callback)
}
|
javascript
|
function(factor, animate, originLeft, originTop, callback) {
let self = this
self.zoomTo(self.__zoomLevel * factor, animate, originLeft, originTop, callback)
}
|
[
"function",
"(",
"factor",
",",
"animate",
",",
"originLeft",
",",
"originTop",
",",
"callback",
")",
"{",
"let",
"self",
"=",
"this",
"self",
".",
"zoomTo",
"(",
"self",
".",
"__zoomLevel",
"*",
"factor",
",",
"animate",
",",
"originLeft",
",",
"originTop",
",",
"callback",
")",
"}"
] |
Zooms the content by the given factor.
@param factor {Number} Zoom by given factor
@param animate {Boolean ? false} Whether to use animation
@param originLeft {Number ? 0} Zoom in at given left coordinate
@param originTop {Number ? 0} Zoom in at given top coordinate
@param callback {Function ? null} A callback that gets fired when the zoom is complete.
|
[
"Zooms",
"the",
"content",
"by",
"the",
"given",
"factor",
"."
] |
796ae53886d0db9f5acf26d5ca049eb3274002df
|
https://github.com/wdfe/wdui/blob/796ae53886d0db9f5acf26d5ca049eb3274002df/src/utils/Scroller.js#L728-L734
|
|
16,678
|
box/t3js
|
examples/todo/js/modules/header.js
|
function(event, element, elementType) {
// code to be run when a click occurs
if (elementType === 'new-todo-input') {
if (event.keyCode === ENTER_KEY) {
var todoTitle = (element.value).trim();
if (todoTitle.length) {
var newTodoId = todosDB.add(todoTitle);
context.broadcast('todoadded', {
id: newTodoId
});
// Clear input afterwards
element.value = '';
}
event.preventDefault();
event.stopPropagation();
}
}
}
|
javascript
|
function(event, element, elementType) {
// code to be run when a click occurs
if (elementType === 'new-todo-input') {
if (event.keyCode === ENTER_KEY) {
var todoTitle = (element.value).trim();
if (todoTitle.length) {
var newTodoId = todosDB.add(todoTitle);
context.broadcast('todoadded', {
id: newTodoId
});
// Clear input afterwards
element.value = '';
}
event.preventDefault();
event.stopPropagation();
}
}
}
|
[
"function",
"(",
"event",
",",
"element",
",",
"elementType",
")",
"{",
"// code to be run when a click occurs",
"if",
"(",
"elementType",
"===",
"'new-todo-input'",
")",
"{",
"if",
"(",
"event",
".",
"keyCode",
"===",
"ENTER_KEY",
")",
"{",
"var",
"todoTitle",
"=",
"(",
"element",
".",
"value",
")",
".",
"trim",
"(",
")",
";",
"if",
"(",
"todoTitle",
".",
"length",
")",
"{",
"var",
"newTodoId",
"=",
"todosDB",
".",
"add",
"(",
"todoTitle",
")",
";",
"context",
".",
"broadcast",
"(",
"'todoadded'",
",",
"{",
"id",
":",
"newTodoId",
"}",
")",
";",
"// Clear input afterwards",
"element",
".",
"value",
"=",
"''",
";",
"}",
"event",
".",
"preventDefault",
"(",
")",
";",
"event",
".",
"stopPropagation",
"(",
")",
";",
"}",
"}",
"}"
] |
Handles the keydown event for the module.
@param {Event} event A DOM-normalized event object.
@param {HTMLElement} element The nearest HTML element with a data-type
attribute specified or null if there is none.
@param {string} elementType The value of data-type for the nearest
element with that attribute specified or null if there is none.
@returns {void}
|
[
"Handles",
"the",
"keydown",
"event",
"for",
"the",
"module",
"."
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/examples/todo/js/modules/header.js#L52-L78
|
|
16,679
|
box/t3js
|
Makefile.js
|
nodeExec
|
function nodeExec(args) {
args = arguments; // make linting happy
var code = nodeCLI.exec.apply(nodeCLI, args).code;
if (code !== 0) {
exit(code);
}
}
|
javascript
|
function nodeExec(args) {
args = arguments; // make linting happy
var code = nodeCLI.exec.apply(nodeCLI, args).code;
if (code !== 0) {
exit(code);
}
}
|
[
"function",
"nodeExec",
"(",
"args",
")",
"{",
"args",
"=",
"arguments",
";",
"// make linting happy",
"var",
"code",
"=",
"nodeCLI",
".",
"exec",
".",
"apply",
"(",
"nodeCLI",
",",
"args",
")",
".",
"code",
";",
"if",
"(",
"code",
"!==",
"0",
")",
"{",
"exit",
"(",
"code",
")",
";",
"}",
"}"
] |
Executes a Node CLI and exits with a non-zero exit code if the
CLI execution returns a non-zero exit code. Otherwise, it does
not exit.
@param {...string} [args] Arguments to pass to the Node CLI utility.
@returns {void}
@private
|
[
"Executes",
"a",
"Node",
"CLI",
"and",
"exits",
"with",
"a",
"non",
"-",
"zero",
"exit",
"code",
"if",
"the",
"CLI",
"execution",
"returns",
"a",
"non",
"-",
"zero",
"exit",
"code",
".",
"Otherwise",
"it",
"does",
"not",
"exit",
"."
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/Makefile.js#L75-L81
|
16,680
|
box/t3js
|
Makefile.js
|
getSourceDirectories
|
function getSourceDirectories() {
var dirs = [ 'lib', 'src', 'app' ],
result = [];
dirs.forEach(function(dir) {
if (test('-d', dir)) {
result.push(dir);
}
});
return result;
}
|
javascript
|
function getSourceDirectories() {
var dirs = [ 'lib', 'src', 'app' ],
result = [];
dirs.forEach(function(dir) {
if (test('-d', dir)) {
result.push(dir);
}
});
return result;
}
|
[
"function",
"getSourceDirectories",
"(",
")",
"{",
"var",
"dirs",
"=",
"[",
"'lib'",
",",
"'src'",
",",
"'app'",
"]",
",",
"result",
"=",
"[",
"]",
";",
"dirs",
".",
"forEach",
"(",
"function",
"(",
"dir",
")",
"{",
"if",
"(",
"test",
"(",
"'-d'",
",",
"dir",
")",
")",
"{",
"result",
".",
"push",
"(",
"dir",
")",
";",
"}",
"}",
")",
";",
"return",
"result",
";",
"}"
] |
Determines which directories are present that might have JavaScript files.
@returns {string[]} An array of directories that exist.
@private
|
[
"Determines",
"which",
"directories",
"are",
"present",
"that",
"might",
"have",
"JavaScript",
"files",
"."
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/Makefile.js#L113-L124
|
16,681
|
box/t3js
|
Makefile.js
|
getVersionTags
|
function getVersionTags() {
var tags = exec('git tag', { silent: true }).output.trim().split(/\n/g);
return tags.reduce(function(list, tag) {
if (semver.valid(tag)) {
list.push(tag);
}
return list;
}, []).sort(semver.compare);
}
|
javascript
|
function getVersionTags() {
var tags = exec('git tag', { silent: true }).output.trim().split(/\n/g);
return tags.reduce(function(list, tag) {
if (semver.valid(tag)) {
list.push(tag);
}
return list;
}, []).sort(semver.compare);
}
|
[
"function",
"getVersionTags",
"(",
")",
"{",
"var",
"tags",
"=",
"exec",
"(",
"'git tag'",
",",
"{",
"silent",
":",
"true",
"}",
")",
".",
"output",
".",
"trim",
"(",
")",
".",
"split",
"(",
"/",
"\\n",
"/",
"g",
")",
";",
"return",
"tags",
".",
"reduce",
"(",
"function",
"(",
"list",
",",
"tag",
")",
"{",
"if",
"(",
"semver",
".",
"valid",
"(",
"tag",
")",
")",
"{",
"list",
".",
"push",
"(",
"tag",
")",
";",
"}",
"return",
"list",
";",
"}",
",",
"[",
"]",
")",
".",
"sort",
"(",
"semver",
".",
"compare",
")",
";",
"}"
] |
Gets the git tags that represent versions.
@returns {string[]} An array of tags in the git repo.
@private
|
[
"Gets",
"the",
"git",
"tags",
"that",
"represent",
"versions",
"."
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/Makefile.js#L131-L140
|
16,682
|
box/t3js
|
Makefile.js
|
generateDistFiles
|
function generateDistFiles(config) {
// Delete package.json from the cache since it can get updated by npm version
delete require.cache[require.resolve('./package.json')];
var pkg = require('./package.json'),
distFilename = DIST_DIR + config.name + '.js',
minDistFilename = distFilename.replace(/\.js$/, '.min.js'),
minDistSourcemapFilename = minDistFilename + '.map',
distTestingFilename = DIST_DIR + config.name + '-testing' + '.js';
// Add copyrights and version info
var versionComment = '/*! ' + config.name + ' v' + pkg.version + ' */\n',
testingVersionComment = '/*! ' + config.name + '-testing v' + pkg.version + ' */\n',
copyrightComment = cat('./config/copyright.txt');
// concatenate files together and add version/copyright notices
(versionComment + copyrightComment + cat(config.files)).to(distFilename);
(testingVersionComment + copyrightComment + cat(config.testingFiles)).to(distTestingFilename);
// create minified version with source maps
var result = uglifyjs.minify(distFilename, {
output: {
comments: /^!/
},
outSourceMap: path.basename(minDistSourcemapFilename)
});
result.code.to(minDistFilename);
result.map.to(minDistSourcemapFilename);
// create filenames with version in them
cp(distFilename, distFilename.replace('.js', '-' + pkg.version + '.js'));
cp(minDistFilename, minDistFilename.replace('.min.js', '-' + pkg.version + '.min.js'));
cp(distTestingFilename, distTestingFilename.replace('.js', '-' + pkg.version + '.js'));
}
|
javascript
|
function generateDistFiles(config) {
// Delete package.json from the cache since it can get updated by npm version
delete require.cache[require.resolve('./package.json')];
var pkg = require('./package.json'),
distFilename = DIST_DIR + config.name + '.js',
minDistFilename = distFilename.replace(/\.js$/, '.min.js'),
minDistSourcemapFilename = minDistFilename + '.map',
distTestingFilename = DIST_DIR + config.name + '-testing' + '.js';
// Add copyrights and version info
var versionComment = '/*! ' + config.name + ' v' + pkg.version + ' */\n',
testingVersionComment = '/*! ' + config.name + '-testing v' + pkg.version + ' */\n',
copyrightComment = cat('./config/copyright.txt');
// concatenate files together and add version/copyright notices
(versionComment + copyrightComment + cat(config.files)).to(distFilename);
(testingVersionComment + copyrightComment + cat(config.testingFiles)).to(distTestingFilename);
// create minified version with source maps
var result = uglifyjs.minify(distFilename, {
output: {
comments: /^!/
},
outSourceMap: path.basename(minDistSourcemapFilename)
});
result.code.to(minDistFilename);
result.map.to(minDistSourcemapFilename);
// create filenames with version in them
cp(distFilename, distFilename.replace('.js', '-' + pkg.version + '.js'));
cp(minDistFilename, minDistFilename.replace('.min.js', '-' + pkg.version + '.min.js'));
cp(distTestingFilename, distTestingFilename.replace('.js', '-' + pkg.version + '.js'));
}
|
[
"function",
"generateDistFiles",
"(",
"config",
")",
"{",
"// Delete package.json from the cache since it can get updated by npm version",
"delete",
"require",
".",
"cache",
"[",
"require",
".",
"resolve",
"(",
"'./package.json'",
")",
"]",
";",
"var",
"pkg",
"=",
"require",
"(",
"'./package.json'",
")",
",",
"distFilename",
"=",
"DIST_DIR",
"+",
"config",
".",
"name",
"+",
"'.js'",
",",
"minDistFilename",
"=",
"distFilename",
".",
"replace",
"(",
"/",
"\\.js$",
"/",
",",
"'.min.js'",
")",
",",
"minDistSourcemapFilename",
"=",
"minDistFilename",
"+",
"'.map'",
",",
"distTestingFilename",
"=",
"DIST_DIR",
"+",
"config",
".",
"name",
"+",
"'-testing'",
"+",
"'.js'",
";",
"// Add copyrights and version info",
"var",
"versionComment",
"=",
"'/*! '",
"+",
"config",
".",
"name",
"+",
"' v'",
"+",
"pkg",
".",
"version",
"+",
"' */\\n'",
",",
"testingVersionComment",
"=",
"'/*! '",
"+",
"config",
".",
"name",
"+",
"'-testing v'",
"+",
"pkg",
".",
"version",
"+",
"' */\\n'",
",",
"copyrightComment",
"=",
"cat",
"(",
"'./config/copyright.txt'",
")",
";",
"// concatenate files together and add version/copyright notices",
"(",
"versionComment",
"+",
"copyrightComment",
"+",
"cat",
"(",
"config",
".",
"files",
")",
")",
".",
"to",
"(",
"distFilename",
")",
";",
"(",
"testingVersionComment",
"+",
"copyrightComment",
"+",
"cat",
"(",
"config",
".",
"testingFiles",
")",
")",
".",
"to",
"(",
"distTestingFilename",
")",
";",
"// create minified version with source maps",
"var",
"result",
"=",
"uglifyjs",
".",
"minify",
"(",
"distFilename",
",",
"{",
"output",
":",
"{",
"comments",
":",
"/",
"^!",
"/",
"}",
",",
"outSourceMap",
":",
"path",
".",
"basename",
"(",
"minDistSourcemapFilename",
")",
"}",
")",
";",
"result",
".",
"code",
".",
"to",
"(",
"minDistFilename",
")",
";",
"result",
".",
"map",
".",
"to",
"(",
"minDistSourcemapFilename",
")",
";",
"// create filenames with version in them",
"cp",
"(",
"distFilename",
",",
"distFilename",
".",
"replace",
"(",
"'.js'",
",",
"'-'",
"+",
"pkg",
".",
"version",
"+",
"'.js'",
")",
")",
";",
"cp",
"(",
"minDistFilename",
",",
"minDistFilename",
".",
"replace",
"(",
"'.min.js'",
",",
"'-'",
"+",
"pkg",
".",
"version",
"+",
"'.min.js'",
")",
")",
";",
"cp",
"(",
"distTestingFilename",
",",
"distTestingFilename",
".",
"replace",
"(",
"'.js'",
",",
"'-'",
"+",
"pkg",
".",
"version",
"+",
"'.js'",
")",
")",
";",
"}"
] |
Generate distribution files for a single package
@param Object config The distribution configuration
@returns {void}
@private
|
[
"Generate",
"distribution",
"files",
"for",
"a",
"single",
"package"
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/Makefile.js#L181-L214
|
16,683
|
box/t3js
|
Makefile.js
|
dist
|
function dist() {
if (test('-d', DIST_DIR)) {
rm('-r', DIST_DIR + '*');
} else {
mkdir(DIST_DIR);
}
[{
name: DIST_NATIVE_NAME,
files: SRC_NATIVE_FILES,
testingFiles: TESTING_NATIVE_FILES
}, {
name: DIST_JQUERY_NAME,
files: SRC_JQUERY_FILES,
testingFiles: TESTING_JQUERY_FILES
}, {
name: DIST_NAME,
files: SRC_NATIVE_FILES,
testingFiles: TESTING_NATIVE_FILES
}].forEach(function(config){
generateDistFiles(config);
});
}
|
javascript
|
function dist() {
if (test('-d', DIST_DIR)) {
rm('-r', DIST_DIR + '*');
} else {
mkdir(DIST_DIR);
}
[{
name: DIST_NATIVE_NAME,
files: SRC_NATIVE_FILES,
testingFiles: TESTING_NATIVE_FILES
}, {
name: DIST_JQUERY_NAME,
files: SRC_JQUERY_FILES,
testingFiles: TESTING_JQUERY_FILES
}, {
name: DIST_NAME,
files: SRC_NATIVE_FILES,
testingFiles: TESTING_NATIVE_FILES
}].forEach(function(config){
generateDistFiles(config);
});
}
|
[
"function",
"dist",
"(",
")",
"{",
"if",
"(",
"test",
"(",
"'-d'",
",",
"DIST_DIR",
")",
")",
"{",
"rm",
"(",
"'-r'",
",",
"DIST_DIR",
"+",
"'*'",
")",
";",
"}",
"else",
"{",
"mkdir",
"(",
"DIST_DIR",
")",
";",
"}",
"[",
"{",
"name",
":",
"DIST_NATIVE_NAME",
",",
"files",
":",
"SRC_NATIVE_FILES",
",",
"testingFiles",
":",
"TESTING_NATIVE_FILES",
"}",
",",
"{",
"name",
":",
"DIST_JQUERY_NAME",
",",
"files",
":",
"SRC_JQUERY_FILES",
",",
"testingFiles",
":",
"TESTING_JQUERY_FILES",
"}",
",",
"{",
"name",
":",
"DIST_NAME",
",",
"files",
":",
"SRC_NATIVE_FILES",
",",
"testingFiles",
":",
"TESTING_NATIVE_FILES",
"}",
"]",
".",
"forEach",
"(",
"function",
"(",
"config",
")",
"{",
"generateDistFiles",
"(",
"config",
")",
";",
"}",
")",
";",
"}"
] |
Generate all distribution files
@private
|
[
"Generate",
"all",
"distribution",
"files"
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/Makefile.js#L220-L242
|
16,684
|
box/t3js
|
examples/todo/js/t3-dev-build.js
|
reset
|
function reset() {
globalConfig = {};
modules = {};
services = {};
behaviors = {};
instances = {};
initialized = false;
for (var i = 0; i < exports.length; i++) {
delete application[exports[i]];
delete Box.Context.prototype[exports[i]];
}
exports = [];
}
|
javascript
|
function reset() {
globalConfig = {};
modules = {};
services = {};
behaviors = {};
instances = {};
initialized = false;
for (var i = 0; i < exports.length; i++) {
delete application[exports[i]];
delete Box.Context.prototype[exports[i]];
}
exports = [];
}
|
[
"function",
"reset",
"(",
")",
"{",
"globalConfig",
"=",
"{",
"}",
";",
"modules",
"=",
"{",
"}",
";",
"services",
"=",
"{",
"}",
";",
"behaviors",
"=",
"{",
"}",
";",
"instances",
"=",
"{",
"}",
";",
"initialized",
"=",
"false",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"exports",
".",
"length",
";",
"i",
"++",
")",
"{",
"delete",
"application",
"[",
"exports",
"[",
"i",
"]",
"]",
";",
"delete",
"Box",
".",
"Context",
".",
"prototype",
"[",
"exports",
"[",
"i",
"]",
"]",
";",
"}",
"exports",
"=",
"[",
"]",
";",
"}"
] |
Reset all state to its default values
@returns {void}
@private
|
[
"Reset",
"all",
"state",
"to",
"its",
"default",
"values"
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/examples/todo/js/t3-dev-build.js#L265-L278
|
16,685
|
box/t3js
|
examples/todo/js/t3-dev-build.js
|
callModuleMethod
|
function callModuleMethod(instance, method) {
if (typeof instance[method] === 'function') {
// Getting the rest of the parameters (the ones other than instance and method)
instance[method].apply(instance, Array.prototype.slice.call(arguments, 2));
}
}
|
javascript
|
function callModuleMethod(instance, method) {
if (typeof instance[method] === 'function') {
// Getting the rest of the parameters (the ones other than instance and method)
instance[method].apply(instance, Array.prototype.slice.call(arguments, 2));
}
}
|
[
"function",
"callModuleMethod",
"(",
"instance",
",",
"method",
")",
"{",
"if",
"(",
"typeof",
"instance",
"[",
"method",
"]",
"===",
"'function'",
")",
"{",
"// Getting the rest of the parameters (the ones other than instance and method)",
"instance",
"[",
"method",
"]",
".",
"apply",
"(",
"instance",
",",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"2",
")",
")",
";",
"}",
"}"
] |
Calls a method on an object if it exists
@param {Box.Application~ModuleInstance} instance Module object to call the method on.
@param {string} method Name of method
@param {...*} [args] Any additional arguments are passed as function parameters (Optional)
@returns {void}
@private
|
[
"Calls",
"a",
"method",
"on",
"an",
"object",
"if",
"it",
"exists"
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/examples/todo/js/t3-dev-build.js#L366-L371
|
16,686
|
box/t3js
|
examples/todo/js/t3-dev-build.js
|
bindEventType
|
function bindEventType(element, type, handlers) {
function eventHandler(event) {
var targetElement = getNearestTypeElement(event.target),
elementType = targetElement ? targetElement.getAttribute('data-type') : '';
for (var i = 0; i < handlers.length; i++) {
handlers[i](event, targetElement, elementType);
}
return true;
}
$(element).on(type, eventHandler);
return eventHandler;
}
|
javascript
|
function bindEventType(element, type, handlers) {
function eventHandler(event) {
var targetElement = getNearestTypeElement(event.target),
elementType = targetElement ? targetElement.getAttribute('data-type') : '';
for (var i = 0; i < handlers.length; i++) {
handlers[i](event, targetElement, elementType);
}
return true;
}
$(element).on(type, eventHandler);
return eventHandler;
}
|
[
"function",
"bindEventType",
"(",
"element",
",",
"type",
",",
"handlers",
")",
"{",
"function",
"eventHandler",
"(",
"event",
")",
"{",
"var",
"targetElement",
"=",
"getNearestTypeElement",
"(",
"event",
".",
"target",
")",
",",
"elementType",
"=",
"targetElement",
"?",
"targetElement",
".",
"getAttribute",
"(",
"'data-type'",
")",
":",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"handlers",
".",
"length",
";",
"i",
"++",
")",
"{",
"handlers",
"[",
"i",
"]",
"(",
"event",
",",
"targetElement",
",",
"elementType",
")",
";",
"}",
"return",
"true",
";",
"}",
"$",
"(",
"element",
")",
".",
"on",
"(",
"type",
",",
"eventHandler",
")",
";",
"return",
"eventHandler",
";",
"}"
] |
Binds a user event to a DOM element with the given handler
@param {HTMLElement} element DOM element to bind the event to
@param {string} type Event type (click, mouseover, ...)
@param {Function[]} handlers Array of event callbacks to be called in that order
@returns {Function} The event handler
@private
|
[
"Binds",
"a",
"user",
"event",
"to",
"a",
"DOM",
"element",
"with",
"the",
"given",
"handler"
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/examples/todo/js/t3-dev-build.js#L453-L470
|
16,687
|
box/t3js
|
examples/todo/js/t3-dev-build.js
|
function(root) {
var me = this,
$root = $(root);
$root.find(MODULE_SELECTOR).each(function(idx, element) {
me.start(element);
});
}
|
javascript
|
function(root) {
var me = this,
$root = $(root);
$root.find(MODULE_SELECTOR).each(function(idx, element) {
me.start(element);
});
}
|
[
"function",
"(",
"root",
")",
"{",
"var",
"me",
"=",
"this",
",",
"$root",
"=",
"$",
"(",
"root",
")",
";",
"$root",
".",
"find",
"(",
"MODULE_SELECTOR",
")",
".",
"each",
"(",
"function",
"(",
"idx",
",",
"element",
")",
"{",
"me",
".",
"start",
"(",
"element",
")",
";",
"}",
")",
";",
"}"
] |
Starts all modules contained within an element
@param {HTMLElement} root DOM element which contains modules
@returns {void}
|
[
"Starts",
"all",
"modules",
"contained",
"within",
"an",
"element"
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/examples/todo/js/t3-dev-build.js#L684-L691
|
|
16,688
|
box/t3js
|
examples/todo/js/t3-dev-build.js
|
function(config) {
if (initialized) {
error(new Error('Cannot set global configuration after application initialization'));
return;
}
for (var prop in config) {
if (config.hasOwnProperty(prop)) {
globalConfig[prop] = config[prop];
}
}
}
|
javascript
|
function(config) {
if (initialized) {
error(new Error('Cannot set global configuration after application initialization'));
return;
}
for (var prop in config) {
if (config.hasOwnProperty(prop)) {
globalConfig[prop] = config[prop];
}
}
}
|
[
"function",
"(",
"config",
")",
"{",
"if",
"(",
"initialized",
")",
"{",
"error",
"(",
"new",
"Error",
"(",
"'Cannot set global configuration after application initialization'",
")",
")",
";",
"return",
";",
"}",
"for",
"(",
"var",
"prop",
"in",
"config",
")",
"{",
"if",
"(",
"config",
".",
"hasOwnProperty",
"(",
"prop",
")",
")",
"{",
"globalConfig",
"[",
"prop",
"]",
"=",
"config",
"[",
"prop",
"]",
";",
"}",
"}",
"}"
] |
Sets the global configuration data
@param {Object} config Global configuration object
@returns {void}
|
[
"Sets",
"the",
"global",
"configuration",
"data"
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/examples/todo/js/t3-dev-build.js#L945-L956
|
|
16,689
|
box/t3js
|
examples/todo/js/modules/page.js
|
function() {
var baseUrl = context.getGlobal('location').pathname;
routerService = context.getService('router');
routerService.init([
baseUrl,
baseUrl + 'active',
baseUrl + 'completed'
]);
}
|
javascript
|
function() {
var baseUrl = context.getGlobal('location').pathname;
routerService = context.getService('router');
routerService.init([
baseUrl,
baseUrl + 'active',
baseUrl + 'completed'
]);
}
|
[
"function",
"(",
")",
"{",
"var",
"baseUrl",
"=",
"context",
".",
"getGlobal",
"(",
"'location'",
")",
".",
"pathname",
";",
"routerService",
"=",
"context",
".",
"getService",
"(",
"'router'",
")",
";",
"routerService",
".",
"init",
"(",
"[",
"baseUrl",
",",
"baseUrl",
"+",
"'active'",
",",
"baseUrl",
"+",
"'completed'",
"]",
")",
";",
"}"
] |
Initializes the module. Caches a data store object to todos
@returns {void}
|
[
"Initializes",
"the",
"module",
".",
"Caches",
"a",
"data",
"store",
"object",
"to",
"todos"
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/examples/todo/js/modules/page.js#L29-L38
|
|
16,690
|
box/t3js
|
lib/application-stub.js
|
function(serviceName, application) {
var serviceData = services[serviceName];
if (serviceData) {
return services[serviceName].creator(application);
}
return null;
}
|
javascript
|
function(serviceName, application) {
var serviceData = services[serviceName];
if (serviceData) {
return services[serviceName].creator(application);
}
return null;
}
|
[
"function",
"(",
"serviceName",
",",
"application",
")",
"{",
"var",
"serviceData",
"=",
"services",
"[",
"serviceName",
"]",
";",
"if",
"(",
"serviceData",
")",
"{",
"return",
"services",
"[",
"serviceName",
"]",
".",
"creator",
"(",
"application",
")",
";",
"}",
"return",
"null",
";",
"}"
] |
Will create a new instance of a service with the given application context
@param {string} serviceName The name of the service being created
@param {Object} application The application context object (usually a TestServiceProvider)
@returns {?Object} The service object
|
[
"Will",
"create",
"a",
"new",
"instance",
"of",
"a",
"service",
"with",
"the",
"given",
"application",
"context"
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/lib/application-stub.js#L86-L92
|
|
16,691
|
box/t3js
|
lib/application-stub.js
|
function(moduleName, context) {
var module = modules[moduleName].creator(context);
if (!context.getElement) {
// Add in a default getElement function that matches the first module element
// Developer should stub this out if there are more than one instance of this module
context.getElement = function() {
return document.querySelector('[data-module="' + moduleName + '"]');
};
}
return module;
}
|
javascript
|
function(moduleName, context) {
var module = modules[moduleName].creator(context);
if (!context.getElement) {
// Add in a default getElement function that matches the first module element
// Developer should stub this out if there are more than one instance of this module
context.getElement = function() {
return document.querySelector('[data-module="' + moduleName + '"]');
};
}
return module;
}
|
[
"function",
"(",
"moduleName",
",",
"context",
")",
"{",
"var",
"module",
"=",
"modules",
"[",
"moduleName",
"]",
".",
"creator",
"(",
"context",
")",
";",
"if",
"(",
"!",
"context",
".",
"getElement",
")",
"{",
"// Add in a default getElement function that matches the first module element",
"// Developer should stub this out if there are more than one instance of this module",
"context",
".",
"getElement",
"=",
"function",
"(",
")",
"{",
"return",
"document",
".",
"querySelector",
"(",
"'[data-module=\"'",
"+",
"moduleName",
"+",
"'\"]'",
")",
";",
"}",
";",
"}",
"return",
"module",
";",
"}"
] |
Will create a new instance of a module with a given context
@param {string} moduleName The name of the module being created
@param {Object} context The context object (usually a TestServiceProvider)
@returns {?Object} The module object
|
[
"Will",
"create",
"a",
"new",
"instance",
"of",
"a",
"module",
"with",
"a",
"given",
"context"
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/lib/application-stub.js#L100-L111
|
|
16,692
|
box/t3js
|
lib/application-stub.js
|
function(behaviorName, context) {
var behaviorData = behaviors[behaviorName];
if (behaviorData) {
// getElement on behaviors must be stubbed
if (!context.getElement) {
context.getElement = function() {
throw new Error('You must stub `getElement` for behaviors.');
};
}
return behaviors[behaviorName].creator(context);
}
return null;
}
|
javascript
|
function(behaviorName, context) {
var behaviorData = behaviors[behaviorName];
if (behaviorData) {
// getElement on behaviors must be stubbed
if (!context.getElement) {
context.getElement = function() {
throw new Error('You must stub `getElement` for behaviors.');
};
}
return behaviors[behaviorName].creator(context);
}
return null;
}
|
[
"function",
"(",
"behaviorName",
",",
"context",
")",
"{",
"var",
"behaviorData",
"=",
"behaviors",
"[",
"behaviorName",
"]",
";",
"if",
"(",
"behaviorData",
")",
"{",
"// getElement on behaviors must be stubbed",
"if",
"(",
"!",
"context",
".",
"getElement",
")",
"{",
"context",
".",
"getElement",
"=",
"function",
"(",
")",
"{",
"throw",
"new",
"Error",
"(",
"'You must stub `getElement` for behaviors.'",
")",
";",
"}",
";",
"}",
"return",
"behaviors",
"[",
"behaviorName",
"]",
".",
"creator",
"(",
"context",
")",
";",
"}",
"return",
"null",
";",
"}"
] |
Will create a new instance of a behavior with a given context
@param {string} behaviorName The name of the behavior being created
@param {Object} context The context object (usually a TestServiceProvider)
@returns {?Object} The behavior object
|
[
"Will",
"create",
"a",
"new",
"instance",
"of",
"a",
"behavior",
"with",
"a",
"given",
"context"
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/lib/application-stub.js#L119-L131
|
|
16,693
|
box/t3js
|
examples/todo/js/services/todos-db.js
|
function() {
var todoList = [];
Object.keys(todos).forEach(function(id) {
todoList.push(todos[id]);
});
return todoList;
}
|
javascript
|
function() {
var todoList = [];
Object.keys(todos).forEach(function(id) {
todoList.push(todos[id]);
});
return todoList;
}
|
[
"function",
"(",
")",
"{",
"var",
"todoList",
"=",
"[",
"]",
";",
"Object",
".",
"keys",
"(",
"todos",
")",
".",
"forEach",
"(",
"function",
"(",
"id",
")",
"{",
"todoList",
".",
"push",
"(",
"todos",
"[",
"id",
"]",
")",
";",
"}",
")",
";",
"return",
"todoList",
";",
"}"
] |
Returns list of all todos
@returns {Todo[]} List of todos
|
[
"Returns",
"list",
"of",
"all",
"todos"
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/examples/todo/js/services/todos-db.js#L48-L56
|
|
16,694
|
box/t3js
|
examples/todo/js/services/todos-db.js
|
function() {
var me = this;
Object.keys(todos).forEach(function(id) {
if (todos[id].completed) {
me.remove(id);
}
});
}
|
javascript
|
function() {
var me = this;
Object.keys(todos).forEach(function(id) {
if (todos[id].completed) {
me.remove(id);
}
});
}
|
[
"function",
"(",
")",
"{",
"var",
"me",
"=",
"this",
";",
"Object",
".",
"keys",
"(",
"todos",
")",
".",
"forEach",
"(",
"function",
"(",
"id",
")",
"{",
"if",
"(",
"todos",
"[",
"id",
"]",
".",
"completed",
")",
"{",
"me",
".",
"remove",
"(",
"id",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Removes all completed tasks
@returns {void}
|
[
"Removes",
"all",
"completed",
"tasks"
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/examples/todo/js/services/todos-db.js#L106-L113
|
|
16,695
|
box/t3js
|
examples/todo/js/services/todos-db.js
|
function(title) {
var todoId = counter++;
todos[todoId] = {
id: todoId,
title: title,
completed: false
};
return todoId;
}
|
javascript
|
function(title) {
var todoId = counter++;
todos[todoId] = {
id: todoId,
title: title,
completed: false
};
return todoId;
}
|
[
"function",
"(",
"title",
")",
"{",
"var",
"todoId",
"=",
"counter",
"++",
";",
"todos",
"[",
"todoId",
"]",
"=",
"{",
"id",
":",
"todoId",
",",
"title",
":",
"title",
",",
"completed",
":",
"false",
"}",
";",
"return",
"todoId",
";",
"}"
] |
Adds a todo
@param {string} title The label of the todo
@returns {number} The id of the new todo
|
[
"Adds",
"a",
"todo"
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/examples/todo/js/services/todos-db.js#L120-L128
|
|
16,696
|
box/t3js
|
lib/application.js
|
isServiceBeingInstantiated
|
function isServiceBeingInstantiated(serviceName) {
for (var i = 0, len = serviceStack.length; i < len; i++) {
if (serviceStack[i] === serviceName) {
return true;
}
}
return false;
}
|
javascript
|
function isServiceBeingInstantiated(serviceName) {
for (var i = 0, len = serviceStack.length; i < len; i++) {
if (serviceStack[i] === serviceName) {
return true;
}
}
return false;
}
|
[
"function",
"isServiceBeingInstantiated",
"(",
"serviceName",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"serviceStack",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"serviceStack",
"[",
"i",
"]",
"===",
"serviceName",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Indicates if a given service is being instantiated. This is used to check
for circular dependencies in service instantiation. If two services
reference each other, it causes a stack overflow and is really hard to
track down, so we provide an extra check to make finding this issue
easier.
@param {string} serviceName The name of the service to check.
@returns {boolean} True if the service is already being instantiated,
false if not.
@private
|
[
"Indicates",
"if",
"a",
"given",
"service",
"is",
"being",
"instantiated",
".",
"This",
"is",
"used",
"to",
"check",
"for",
"circular",
"dependencies",
"in",
"service",
"instantiation",
".",
"If",
"two",
"services",
"reference",
"each",
"other",
"it",
"causes",
"a",
"stack",
"overflow",
"and",
"is",
"really",
"hard",
"to",
"track",
"down",
"so",
"we",
"provide",
"an",
"extra",
"check",
"to",
"make",
"finding",
"this",
"issue",
"easier",
"."
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/lib/application.js#L121-L129
|
16,697
|
box/t3js
|
lib/application.js
|
error
|
function error(exception) {
if (typeof customErrorHandler === 'function') {
customErrorHandler(exception);
return;
}
if (globalConfig.debug) {
throw exception;
} else {
application.fire('error', {
exception: exception
});
}
}
|
javascript
|
function error(exception) {
if (typeof customErrorHandler === 'function') {
customErrorHandler(exception);
return;
}
if (globalConfig.debug) {
throw exception;
} else {
application.fire('error', {
exception: exception
});
}
}
|
[
"function",
"error",
"(",
"exception",
")",
"{",
"if",
"(",
"typeof",
"customErrorHandler",
"===",
"'function'",
")",
"{",
"customErrorHandler",
"(",
"exception",
")",
";",
"return",
";",
"}",
"if",
"(",
"globalConfig",
".",
"debug",
")",
"{",
"throw",
"exception",
";",
"}",
"else",
"{",
"application",
".",
"fire",
"(",
"'error'",
",",
"{",
"exception",
":",
"exception",
"}",
")",
";",
"}",
"}"
] |
Signals that an error has occurred. If in development mode, an error
is thrown. If in production mode, an event is fired.
@param {Error} [exception] The exception object to use.
@returns {void}
@private
|
[
"Signals",
"that",
"an",
"error",
"has",
"occurred",
".",
"If",
"in",
"development",
"mode",
"an",
"error",
"is",
"thrown",
".",
"If",
"in",
"production",
"mode",
"an",
"event",
"is",
"fired",
"."
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/lib/application.js#L138-L150
|
16,698
|
box/t3js
|
lib/application.js
|
createAndBindEventDelegate
|
function createAndBindEventDelegate(eventDelegates, element, handler) {
var delegate = new Box.DOMEventDelegate(element, handler, globalConfig.eventTypes);
eventDelegates.push(delegate);
delegate.attachEvents();
}
|
javascript
|
function createAndBindEventDelegate(eventDelegates, element, handler) {
var delegate = new Box.DOMEventDelegate(element, handler, globalConfig.eventTypes);
eventDelegates.push(delegate);
delegate.attachEvents();
}
|
[
"function",
"createAndBindEventDelegate",
"(",
"eventDelegates",
",",
"element",
",",
"handler",
")",
"{",
"var",
"delegate",
"=",
"new",
"Box",
".",
"DOMEventDelegate",
"(",
"element",
",",
"handler",
",",
"globalConfig",
".",
"eventTypes",
")",
";",
"eventDelegates",
".",
"push",
"(",
"delegate",
")",
";",
"delegate",
".",
"attachEvents",
"(",
")",
";",
"}"
] |
Creates a new event delegate and sets up its event handlers.
@param {Array} eventDelegates The array of event delegates to add to.
@param {HTMLElement} element The HTML element to bind to.
@param {Object} handler The handler object for the delegate (either the
module instance or behavior instance).
@returns {void}
@private
|
[
"Creates",
"a",
"new",
"event",
"delegate",
"and",
"sets",
"up",
"its",
"event",
"handlers",
"."
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/lib/application.js#L326-L330
|
16,699
|
box/t3js
|
lib/application.js
|
callMessageHandler
|
function callMessageHandler(instance, name, data) {
// If onmessage is an object call message handler with the matching key (if any)
if (instance.onmessage !== null && typeof instance.onmessage === 'object' && instance.onmessage.hasOwnProperty(name)) {
instance.onmessage[name].call(instance, data);
// Otherwise if message name exists in messages call onmessage with name, data
} else if (indexOf(instance.messages || [], name) !== -1) {
instance.onmessage.call(instance, name, data);
}
}
|
javascript
|
function callMessageHandler(instance, name, data) {
// If onmessage is an object call message handler with the matching key (if any)
if (instance.onmessage !== null && typeof instance.onmessage === 'object' && instance.onmessage.hasOwnProperty(name)) {
instance.onmessage[name].call(instance, data);
// Otherwise if message name exists in messages call onmessage with name, data
} else if (indexOf(instance.messages || [], name) !== -1) {
instance.onmessage.call(instance, name, data);
}
}
|
[
"function",
"callMessageHandler",
"(",
"instance",
",",
"name",
",",
"data",
")",
"{",
"// If onmessage is an object call message handler with the matching key (if any)",
"if",
"(",
"instance",
".",
"onmessage",
"!==",
"null",
"&&",
"typeof",
"instance",
".",
"onmessage",
"===",
"'object'",
"&&",
"instance",
".",
"onmessage",
".",
"hasOwnProperty",
"(",
"name",
")",
")",
"{",
"instance",
".",
"onmessage",
"[",
"name",
"]",
".",
"call",
"(",
"instance",
",",
"data",
")",
";",
"// Otherwise if message name exists in messages call onmessage with name, data",
"}",
"else",
"if",
"(",
"indexOf",
"(",
"instance",
".",
"messages",
"||",
"[",
"]",
",",
"name",
")",
"!==",
"-",
"1",
")",
"{",
"instance",
".",
"onmessage",
".",
"call",
"(",
"instance",
",",
"name",
",",
"data",
")",
";",
"}",
"}"
] |
Gets message handlers from the provided module instance
@param {Box.Application~ModuleInstance|Box.Application~BehaviorInstance} instance Messages handlers will be retrieved from the Instance object
@param {String} name The name of the message to be handled
@param {Any} data A playload to be passed to the message handler
@returns {void}
@private
|
[
"Gets",
"message",
"handlers",
"from",
"the",
"provided",
"module",
"instance"
] |
1cc1751650e339bd5243a0f20cc76543c834ac09
|
https://github.com/box/t3js/blob/1cc1751650e339bd5243a0f20cc76543c834ac09/lib/application.js#L386-L396
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.