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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
6,900
|
pissang/claygl
|
dist/claygl.es.js
|
function () {
if (this.image.px) {
return isPowerOfTwo$1(this.image.px.width)
&& isPowerOfTwo$1(this.image.px.height);
}
else {
return isPowerOfTwo$1(this.width)
&& isPowerOfTwo$1(this.height);
}
}
|
javascript
|
function () {
if (this.image.px) {
return isPowerOfTwo$1(this.image.px.width)
&& isPowerOfTwo$1(this.image.px.height);
}
else {
return isPowerOfTwo$1(this.width)
&& isPowerOfTwo$1(this.height);
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"image",
".",
"px",
")",
"{",
"return",
"isPowerOfTwo$1",
"(",
"this",
".",
"image",
".",
"px",
".",
"width",
")",
"&&",
"isPowerOfTwo$1",
"(",
"this",
".",
"image",
".",
"px",
".",
"height",
")",
";",
"}",
"else",
"{",
"return",
"isPowerOfTwo$1",
"(",
"this",
".",
"width",
")",
"&&",
"isPowerOfTwo$1",
"(",
"this",
".",
"height",
")",
";",
"}",
"}"
] |
Overwrite the isPowerOfTwo method
|
[
"Overwrite",
"the",
"isPowerOfTwo",
"method"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L19498-L19507
|
|
6,901
|
pissang/claygl
|
dist/claygl.es.js
|
function (clip, mapRule) {
// Clip have been exists in
for (var i = 0; i < this._clips.length; i++) {
if (this._clips[i].clip === clip) {
return;
}
}
// Map the joint index in skeleton to joint pose index in clip
var maps = [];
for (var i = 0; i < this.joints.length; i++) {
maps[i] = -1;
}
// Create avatar
for (var i = 0; i < clip.tracks.length; i++) {
for (var j = 0; j < this.joints.length; j++) {
var joint = this.joints[j];
var track = clip.tracks[i];
var jointName = joint.name;
if (mapRule) {
jointName = mapRule[jointName];
}
if (track.name === jointName) {
maps[j] = i;
break;
}
}
}
this._clips.push({
maps: maps,
clip: clip
});
return this._clips.length - 1;
}
|
javascript
|
function (clip, mapRule) {
// Clip have been exists in
for (var i = 0; i < this._clips.length; i++) {
if (this._clips[i].clip === clip) {
return;
}
}
// Map the joint index in skeleton to joint pose index in clip
var maps = [];
for (var i = 0; i < this.joints.length; i++) {
maps[i] = -1;
}
// Create avatar
for (var i = 0; i < clip.tracks.length; i++) {
for (var j = 0; j < this.joints.length; j++) {
var joint = this.joints[j];
var track = clip.tracks[i];
var jointName = joint.name;
if (mapRule) {
jointName = mapRule[jointName];
}
if (track.name === jointName) {
maps[j] = i;
break;
}
}
}
this._clips.push({
maps: maps,
clip: clip
});
return this._clips.length - 1;
}
|
[
"function",
"(",
"clip",
",",
"mapRule",
")",
"{",
"// Clip have been exists in",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"_clips",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"this",
".",
"_clips",
"[",
"i",
"]",
".",
"clip",
"===",
"clip",
")",
"{",
"return",
";",
"}",
"}",
"// Map the joint index in skeleton to joint pose index in clip",
"var",
"maps",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"joints",
".",
"length",
";",
"i",
"++",
")",
"{",
"maps",
"[",
"i",
"]",
"=",
"-",
"1",
";",
"}",
"// Create avatar",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"clip",
".",
"tracks",
".",
"length",
";",
"i",
"++",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"this",
".",
"joints",
".",
"length",
";",
"j",
"++",
")",
"{",
"var",
"joint",
"=",
"this",
".",
"joints",
"[",
"j",
"]",
";",
"var",
"track",
"=",
"clip",
".",
"tracks",
"[",
"i",
"]",
";",
"var",
"jointName",
"=",
"joint",
".",
"name",
";",
"if",
"(",
"mapRule",
")",
"{",
"jointName",
"=",
"mapRule",
"[",
"jointName",
"]",
";",
"}",
"if",
"(",
"track",
".",
"name",
"===",
"jointName",
")",
"{",
"maps",
"[",
"j",
"]",
"=",
"i",
";",
"break",
";",
"}",
"}",
"}",
"this",
".",
"_clips",
".",
"push",
"(",
"{",
"maps",
":",
"maps",
",",
"clip",
":",
"clip",
"}",
")",
";",
"return",
"this",
".",
"_clips",
".",
"length",
"-",
"1",
";",
"}"
] |
Add a skinning clip and create a map between clip and skeleton
@param {clay.animation.SkinningClip} clip
@param {Object} [mapRule] Map between joint name in skeleton and joint name in clip
|
[
"Add",
"a",
"skinning",
"clip",
"and",
"create",
"a",
"map",
"between",
"clip",
"and",
"skeleton"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L20438-L20472
|
|
6,902
|
pissang/claygl
|
dist/claygl.es.js
|
function (geometry) {
var attributes = geometry.attributes;
var positionAttr = attributes.position;
var jointAttr = attributes.joint;
var weightAttr = attributes.weight;
var jointsBoundingBoxes = [];
for (var i = 0; i < this.joints.length; i++) {
jointsBoundingBoxes[i] = new BoundingBox();
jointsBoundingBoxes[i].__updated = false;
}
var vtxJoint = [];
var vtxPos = [];
var vtxWeight = [];
var maxJointIdx = 0;
for (var i = 0; i < geometry.vertexCount; i++) {
jointAttr.get(i, vtxJoint);
positionAttr.get(i, vtxPos);
weightAttr.get(i, vtxWeight);
for (var k = 0; k < 4; k++) {
if (vtxWeight[k] > 0.01) {
var jointIdx = vtxJoint[k];
maxJointIdx = Math.max(maxJointIdx, jointIdx);
var min = jointsBoundingBoxes[jointIdx].min.array;
var max = jointsBoundingBoxes[jointIdx].max.array;
jointsBoundingBoxes[jointIdx].__updated = true;
min = vec3.min(min, min, vtxPos);
max = vec3.max(max, max, vtxPos);
}
}
}
this._jointsBoundingBoxes = jointsBoundingBoxes;
this.boundingBox = new BoundingBox();
if (maxJointIdx < this.joints.length - 1) {
console.warn('Geometry joints and skeleton joints don\'t match');
}
}
|
javascript
|
function (geometry) {
var attributes = geometry.attributes;
var positionAttr = attributes.position;
var jointAttr = attributes.joint;
var weightAttr = attributes.weight;
var jointsBoundingBoxes = [];
for (var i = 0; i < this.joints.length; i++) {
jointsBoundingBoxes[i] = new BoundingBox();
jointsBoundingBoxes[i].__updated = false;
}
var vtxJoint = [];
var vtxPos = [];
var vtxWeight = [];
var maxJointIdx = 0;
for (var i = 0; i < geometry.vertexCount; i++) {
jointAttr.get(i, vtxJoint);
positionAttr.get(i, vtxPos);
weightAttr.get(i, vtxWeight);
for (var k = 0; k < 4; k++) {
if (vtxWeight[k] > 0.01) {
var jointIdx = vtxJoint[k];
maxJointIdx = Math.max(maxJointIdx, jointIdx);
var min = jointsBoundingBoxes[jointIdx].min.array;
var max = jointsBoundingBoxes[jointIdx].max.array;
jointsBoundingBoxes[jointIdx].__updated = true;
min = vec3.min(min, min, vtxPos);
max = vec3.max(max, max, vtxPos);
}
}
}
this._jointsBoundingBoxes = jointsBoundingBoxes;
this.boundingBox = new BoundingBox();
if (maxJointIdx < this.joints.length - 1) {
console.warn('Geometry joints and skeleton joints don\'t match');
}
}
|
[
"function",
"(",
"geometry",
")",
"{",
"var",
"attributes",
"=",
"geometry",
".",
"attributes",
";",
"var",
"positionAttr",
"=",
"attributes",
".",
"position",
";",
"var",
"jointAttr",
"=",
"attributes",
".",
"joint",
";",
"var",
"weightAttr",
"=",
"attributes",
".",
"weight",
";",
"var",
"jointsBoundingBoxes",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"joints",
".",
"length",
";",
"i",
"++",
")",
"{",
"jointsBoundingBoxes",
"[",
"i",
"]",
"=",
"new",
"BoundingBox",
"(",
")",
";",
"jointsBoundingBoxes",
"[",
"i",
"]",
".",
"__updated",
"=",
"false",
";",
"}",
"var",
"vtxJoint",
"=",
"[",
"]",
";",
"var",
"vtxPos",
"=",
"[",
"]",
";",
"var",
"vtxWeight",
"=",
"[",
"]",
";",
"var",
"maxJointIdx",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"geometry",
".",
"vertexCount",
";",
"i",
"++",
")",
"{",
"jointAttr",
".",
"get",
"(",
"i",
",",
"vtxJoint",
")",
";",
"positionAttr",
".",
"get",
"(",
"i",
",",
"vtxPos",
")",
";",
"weightAttr",
".",
"get",
"(",
"i",
",",
"vtxWeight",
")",
";",
"for",
"(",
"var",
"k",
"=",
"0",
";",
"k",
"<",
"4",
";",
"k",
"++",
")",
"{",
"if",
"(",
"vtxWeight",
"[",
"k",
"]",
">",
"0.01",
")",
"{",
"var",
"jointIdx",
"=",
"vtxJoint",
"[",
"k",
"]",
";",
"maxJointIdx",
"=",
"Math",
".",
"max",
"(",
"maxJointIdx",
",",
"jointIdx",
")",
";",
"var",
"min",
"=",
"jointsBoundingBoxes",
"[",
"jointIdx",
"]",
".",
"min",
".",
"array",
";",
"var",
"max",
"=",
"jointsBoundingBoxes",
"[",
"jointIdx",
"]",
".",
"max",
".",
"array",
";",
"jointsBoundingBoxes",
"[",
"jointIdx",
"]",
".",
"__updated",
"=",
"true",
";",
"min",
"=",
"vec3",
".",
"min",
"(",
"min",
",",
"min",
",",
"vtxPos",
")",
";",
"max",
"=",
"vec3",
".",
"max",
"(",
"max",
",",
"max",
",",
"vtxPos",
")",
";",
"}",
"}",
"}",
"this",
".",
"_jointsBoundingBoxes",
"=",
"jointsBoundingBoxes",
";",
"this",
".",
"boundingBox",
"=",
"new",
"BoundingBox",
"(",
")",
";",
"if",
"(",
"maxJointIdx",
"<",
"this",
".",
"joints",
".",
"length",
"-",
"1",
")",
"{",
"console",
".",
"warn",
"(",
"'Geometry joints and skeleton joints don\\'t match'",
")",
";",
"}",
"}"
] |
Update boundingBox of each joint bound to geometry.
ASSUME skeleton and geometry joints are matched.
@param {clay.Geometry} geometry
|
[
"Update",
"boundingBox",
"of",
"each",
"joint",
"bound",
"to",
"geometry",
".",
"ASSUME",
"skeleton",
"and",
"geometry",
"joints",
"are",
"matched",
"."
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L20545-L20589
|
|
6,903
|
pissang/claygl
|
dist/claygl.es.js
|
function () {
this._setPose();
var jointsBoundingBoxes = this._jointsBoundingBoxes;
for (var i = 0; i < this.joints.length; i++) {
var joint = this.joints[i];
mat4.multiply(
this._skinMatricesSubArrays[i],
joint.node.worldTransform.array,
this._jointMatricesSubArrays[i]
);
}
if (this.boundingBox) {
this.boundingBox.min.set(Infinity, Infinity, Infinity);
this.boundingBox.max.set(-Infinity, -Infinity, -Infinity);
for (var i = 0; i < this.joints.length; i++) {
var joint = this.joints[i];
var bbox = jointsBoundingBoxes[i];
if (bbox.__updated) {
tmpBoundingBox.copy(bbox);
tmpMat4.array = this._skinMatricesSubArrays[i];
tmpBoundingBox.applyTransform(tmpMat4);
this.boundingBox.union(tmpBoundingBox);
}
}
}
}
|
javascript
|
function () {
this._setPose();
var jointsBoundingBoxes = this._jointsBoundingBoxes;
for (var i = 0; i < this.joints.length; i++) {
var joint = this.joints[i];
mat4.multiply(
this._skinMatricesSubArrays[i],
joint.node.worldTransform.array,
this._jointMatricesSubArrays[i]
);
}
if (this.boundingBox) {
this.boundingBox.min.set(Infinity, Infinity, Infinity);
this.boundingBox.max.set(-Infinity, -Infinity, -Infinity);
for (var i = 0; i < this.joints.length; i++) {
var joint = this.joints[i];
var bbox = jointsBoundingBoxes[i];
if (bbox.__updated) {
tmpBoundingBox.copy(bbox);
tmpMat4.array = this._skinMatricesSubArrays[i];
tmpBoundingBox.applyTransform(tmpMat4);
this.boundingBox.union(tmpBoundingBox);
}
}
}
}
|
[
"function",
"(",
")",
"{",
"this",
".",
"_setPose",
"(",
")",
";",
"var",
"jointsBoundingBoxes",
"=",
"this",
".",
"_jointsBoundingBoxes",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"joints",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"joint",
"=",
"this",
".",
"joints",
"[",
"i",
"]",
";",
"mat4",
".",
"multiply",
"(",
"this",
".",
"_skinMatricesSubArrays",
"[",
"i",
"]",
",",
"joint",
".",
"node",
".",
"worldTransform",
".",
"array",
",",
"this",
".",
"_jointMatricesSubArrays",
"[",
"i",
"]",
")",
";",
"}",
"if",
"(",
"this",
".",
"boundingBox",
")",
"{",
"this",
".",
"boundingBox",
".",
"min",
".",
"set",
"(",
"Infinity",
",",
"Infinity",
",",
"Infinity",
")",
";",
"this",
".",
"boundingBox",
".",
"max",
".",
"set",
"(",
"-",
"Infinity",
",",
"-",
"Infinity",
",",
"-",
"Infinity",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"joints",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"joint",
"=",
"this",
".",
"joints",
"[",
"i",
"]",
";",
"var",
"bbox",
"=",
"jointsBoundingBoxes",
"[",
"i",
"]",
";",
"if",
"(",
"bbox",
".",
"__updated",
")",
"{",
"tmpBoundingBox",
".",
"copy",
"(",
"bbox",
")",
";",
"tmpMat4",
".",
"array",
"=",
"this",
".",
"_skinMatricesSubArrays",
"[",
"i",
"]",
";",
"tmpBoundingBox",
".",
"applyTransform",
"(",
"tmpMat4",
")",
";",
"this",
".",
"boundingBox",
".",
"union",
"(",
"tmpBoundingBox",
")",
";",
"}",
"}",
"}",
"}"
] |
Update skinning matrices
|
[
"Update",
"skinning",
"matrices"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L20607-L20636
|
|
6,904
|
pissang/claygl
|
dist/claygl.es.js
|
function (buffer) {
var header = new Uint32Array(buffer, 0, 4);
if (header[0] !== 0x46546C67) {
this.trigger('error', 'Invalid glTF binary format: Invalid header');
return;
}
if (header[0] < 2) {
this.trigger('error', 'Only glTF2.0 is supported.');
return;
}
var dataView = new DataView(buffer, 12);
var json;
var buffers = [];
// Read chunks
for (var i = 0; i < dataView.byteLength;) {
var chunkLength = dataView.getUint32(i, true);
i += 4;
var chunkType = dataView.getUint32(i, true);
i += 4;
// json
if (chunkType === 0x4E4F534A) {
var arr = new Uint8Array(buffer, i + 12, chunkLength);
// TODO, for the browser not support TextDecoder.
var decoder = new TextDecoder();
var str = decoder.decode(arr);
try {
json = JSON.parse(str);
}
catch (e) {
this.trigger('error', 'JSON Parse error:' + e.toString());
return;
}
}
else if (chunkType === 0x004E4942) {
buffers.push(buffer.slice(i + 12, i + 12 + chunkLength));
}
i += chunkLength;
}
if (!json) {
this.trigger('error', 'Invalid glTF binary format: Can\'t find JSON.');
return;
}
return this.parse(json, buffers);
}
|
javascript
|
function (buffer) {
var header = new Uint32Array(buffer, 0, 4);
if (header[0] !== 0x46546C67) {
this.trigger('error', 'Invalid glTF binary format: Invalid header');
return;
}
if (header[0] < 2) {
this.trigger('error', 'Only glTF2.0 is supported.');
return;
}
var dataView = new DataView(buffer, 12);
var json;
var buffers = [];
// Read chunks
for (var i = 0; i < dataView.byteLength;) {
var chunkLength = dataView.getUint32(i, true);
i += 4;
var chunkType = dataView.getUint32(i, true);
i += 4;
// json
if (chunkType === 0x4E4F534A) {
var arr = new Uint8Array(buffer, i + 12, chunkLength);
// TODO, for the browser not support TextDecoder.
var decoder = new TextDecoder();
var str = decoder.decode(arr);
try {
json = JSON.parse(str);
}
catch (e) {
this.trigger('error', 'JSON Parse error:' + e.toString());
return;
}
}
else if (chunkType === 0x004E4942) {
buffers.push(buffer.slice(i + 12, i + 12 + chunkLength));
}
i += chunkLength;
}
if (!json) {
this.trigger('error', 'Invalid glTF binary format: Can\'t find JSON.');
return;
}
return this.parse(json, buffers);
}
|
[
"function",
"(",
"buffer",
")",
"{",
"var",
"header",
"=",
"new",
"Uint32Array",
"(",
"buffer",
",",
"0",
",",
"4",
")",
";",
"if",
"(",
"header",
"[",
"0",
"]",
"!==",
"0x46546C67",
")",
"{",
"this",
".",
"trigger",
"(",
"'error'",
",",
"'Invalid glTF binary format: Invalid header'",
")",
";",
"return",
";",
"}",
"if",
"(",
"header",
"[",
"0",
"]",
"<",
"2",
")",
"{",
"this",
".",
"trigger",
"(",
"'error'",
",",
"'Only glTF2.0 is supported.'",
")",
";",
"return",
";",
"}",
"var",
"dataView",
"=",
"new",
"DataView",
"(",
"buffer",
",",
"12",
")",
";",
"var",
"json",
";",
"var",
"buffers",
"=",
"[",
"]",
";",
"// Read chunks",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"dataView",
".",
"byteLength",
";",
")",
"{",
"var",
"chunkLength",
"=",
"dataView",
".",
"getUint32",
"(",
"i",
",",
"true",
")",
";",
"i",
"+=",
"4",
";",
"var",
"chunkType",
"=",
"dataView",
".",
"getUint32",
"(",
"i",
",",
"true",
")",
";",
"i",
"+=",
"4",
";",
"// json",
"if",
"(",
"chunkType",
"===",
"0x4E4F534A",
")",
"{",
"var",
"arr",
"=",
"new",
"Uint8Array",
"(",
"buffer",
",",
"i",
"+",
"12",
",",
"chunkLength",
")",
";",
"// TODO, for the browser not support TextDecoder.",
"var",
"decoder",
"=",
"new",
"TextDecoder",
"(",
")",
";",
"var",
"str",
"=",
"decoder",
".",
"decode",
"(",
"arr",
")",
";",
"try",
"{",
"json",
"=",
"JSON",
".",
"parse",
"(",
"str",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"this",
".",
"trigger",
"(",
"'error'",
",",
"'JSON Parse error:'",
"+",
"e",
".",
"toString",
"(",
")",
")",
";",
"return",
";",
"}",
"}",
"else",
"if",
"(",
"chunkType",
"===",
"0x004E4942",
")",
"{",
"buffers",
".",
"push",
"(",
"buffer",
".",
"slice",
"(",
"i",
"+",
"12",
",",
"i",
"+",
"12",
"+",
"chunkLength",
")",
")",
";",
"}",
"i",
"+=",
"chunkLength",
";",
"}",
"if",
"(",
"!",
"json",
")",
"{",
"this",
".",
"trigger",
"(",
"'error'",
",",
"'Invalid glTF binary format: Can\\'t find JSON.'",
")",
";",
"return",
";",
"}",
"return",
"this",
".",
"parse",
"(",
"json",
",",
"buffers",
")",
";",
"}"
] |
Parse glTF binary
@param {ArrayBuffer} buffer
@return {clay.loader.GLTF.Result}
|
[
"Parse",
"glTF",
"binary"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L21046-L21094
|
|
6,905
|
pissang/claygl
|
dist/claygl.es.js
|
function (path) {
if (path && path.match(/^data:(.*?)base64,/)) {
return path;
}
var rootPath = this.bufferRootPath;
if (rootPath == null) {
rootPath = this.rootPath;
}
return util$1.relative2absolute(path, rootPath);
}
|
javascript
|
function (path) {
if (path && path.match(/^data:(.*?)base64,/)) {
return path;
}
var rootPath = this.bufferRootPath;
if (rootPath == null) {
rootPath = this.rootPath;
}
return util$1.relative2absolute(path, rootPath);
}
|
[
"function",
"(",
"path",
")",
"{",
"if",
"(",
"path",
"&&",
"path",
".",
"match",
"(",
"/",
"^data:(.*?)base64,",
"/",
")",
")",
"{",
"return",
"path",
";",
"}",
"var",
"rootPath",
"=",
"this",
".",
"bufferRootPath",
";",
"if",
"(",
"rootPath",
"==",
"null",
")",
"{",
"rootPath",
"=",
"this",
".",
"rootPath",
";",
"}",
"return",
"util$1",
".",
"relative2absolute",
"(",
"path",
",",
"rootPath",
")",
";",
"}"
] |
Binary file path resolver. User can override it
@param {string} path
|
[
"Binary",
"file",
"path",
"resolver",
".",
"User",
"can",
"override",
"it"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L21220-L21230
|
|
6,906
|
pissang/claygl
|
dist/claygl.es.js
|
function (path) {
if (path && path.match(/^data:(.*?)base64,/)) {
return path;
}
var rootPath = this.textureRootPath;
if (rootPath == null) {
rootPath = this.rootPath;
}
return util$1.relative2absolute(path, rootPath);
}
|
javascript
|
function (path) {
if (path && path.match(/^data:(.*?)base64,/)) {
return path;
}
var rootPath = this.textureRootPath;
if (rootPath == null) {
rootPath = this.rootPath;
}
return util$1.relative2absolute(path, rootPath);
}
|
[
"function",
"(",
"path",
")",
"{",
"if",
"(",
"path",
"&&",
"path",
".",
"match",
"(",
"/",
"^data:(.*?)base64,",
"/",
")",
")",
"{",
"return",
"path",
";",
"}",
"var",
"rootPath",
"=",
"this",
".",
"textureRootPath",
";",
"if",
"(",
"rootPath",
"==",
"null",
")",
"{",
"rootPath",
"=",
"this",
".",
"rootPath",
";",
"}",
"return",
"util$1",
".",
"relative2absolute",
"(",
"path",
",",
"rootPath",
")",
";",
"}"
] |
Texture file path resolver. User can override it
@param {string} path
|
[
"Texture",
"file",
"path",
"resolver",
".",
"User",
"can",
"override",
"it"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L21236-L21246
|
|
6,907
|
pissang/claygl
|
dist/claygl.es.js
|
function (renderer) {
if (renderer.__currentFrameBuffer) {
// Already bound
if (renderer.__currentFrameBuffer === this) {
return;
}
console.warn('Renderer already bound with another framebuffer. Unbind it first');
}
renderer.__currentFrameBuffer = this;
var _gl = renderer.gl;
_gl.bindFramebuffer(GL_FRAMEBUFFER, this._getFrameBufferGL(renderer));
this._boundRenderer = renderer;
var cache = this._cache;
cache.put('viewport', renderer.viewport);
var hasTextureAttached = false;
var width;
var height;
for (var attachment in this._textures) {
hasTextureAttached = true;
var obj = this._textures[attachment];
if (obj) {
// TODO Do width, height checking, make sure size are same
width = obj.texture.width;
height = obj.texture.height;
// Attach textures
this._doAttach(renderer, obj.texture, attachment, obj.target);
}
}
this._width = width;
this._height = height;
if (!hasTextureAttached && this.depthBuffer) {
console.error('Must attach texture before bind, or renderbuffer may have incorrect width and height.');
}
if (this.viewport) {
renderer.setViewport(this.viewport);
}
else {
renderer.setViewport(0, 0, width, height, 1);
}
var attachedTextures = cache.get('attached_textures');
if (attachedTextures) {
for (var attachment in attachedTextures) {
if (!this._textures[attachment]) {
var target = attachedTextures[attachment];
this._doDetach(_gl, attachment, target);
}
}
}
if (!cache.get(KEY_DEPTHTEXTURE_ATTACHED) && this.depthBuffer) {
// Create a new render buffer
if (cache.miss(KEY_RENDERBUFFER)) {
cache.put(KEY_RENDERBUFFER, _gl.createRenderbuffer());
}
var renderbuffer = cache.get(KEY_RENDERBUFFER);
if (width !== cache.get(KEY_RENDERBUFFER_WIDTH)
|| height !== cache.get(KEY_RENDERBUFFER_HEIGHT)) {
_gl.bindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
_gl.renderbufferStorage(GL_RENDERBUFFER, _gl.DEPTH_COMPONENT16, width, height);
cache.put(KEY_RENDERBUFFER_WIDTH, width);
cache.put(KEY_RENDERBUFFER_HEIGHT, height);
_gl.bindRenderbuffer(GL_RENDERBUFFER, null);
}
if (!cache.get(KEY_RENDERBUFFER_ATTACHED)) {
_gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, renderbuffer);
cache.put(KEY_RENDERBUFFER_ATTACHED, true);
}
}
}
|
javascript
|
function (renderer) {
if (renderer.__currentFrameBuffer) {
// Already bound
if (renderer.__currentFrameBuffer === this) {
return;
}
console.warn('Renderer already bound with another framebuffer. Unbind it first');
}
renderer.__currentFrameBuffer = this;
var _gl = renderer.gl;
_gl.bindFramebuffer(GL_FRAMEBUFFER, this._getFrameBufferGL(renderer));
this._boundRenderer = renderer;
var cache = this._cache;
cache.put('viewport', renderer.viewport);
var hasTextureAttached = false;
var width;
var height;
for (var attachment in this._textures) {
hasTextureAttached = true;
var obj = this._textures[attachment];
if (obj) {
// TODO Do width, height checking, make sure size are same
width = obj.texture.width;
height = obj.texture.height;
// Attach textures
this._doAttach(renderer, obj.texture, attachment, obj.target);
}
}
this._width = width;
this._height = height;
if (!hasTextureAttached && this.depthBuffer) {
console.error('Must attach texture before bind, or renderbuffer may have incorrect width and height.');
}
if (this.viewport) {
renderer.setViewport(this.viewport);
}
else {
renderer.setViewport(0, 0, width, height, 1);
}
var attachedTextures = cache.get('attached_textures');
if (attachedTextures) {
for (var attachment in attachedTextures) {
if (!this._textures[attachment]) {
var target = attachedTextures[attachment];
this._doDetach(_gl, attachment, target);
}
}
}
if (!cache.get(KEY_DEPTHTEXTURE_ATTACHED) && this.depthBuffer) {
// Create a new render buffer
if (cache.miss(KEY_RENDERBUFFER)) {
cache.put(KEY_RENDERBUFFER, _gl.createRenderbuffer());
}
var renderbuffer = cache.get(KEY_RENDERBUFFER);
if (width !== cache.get(KEY_RENDERBUFFER_WIDTH)
|| height !== cache.get(KEY_RENDERBUFFER_HEIGHT)) {
_gl.bindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
_gl.renderbufferStorage(GL_RENDERBUFFER, _gl.DEPTH_COMPONENT16, width, height);
cache.put(KEY_RENDERBUFFER_WIDTH, width);
cache.put(KEY_RENDERBUFFER_HEIGHT, height);
_gl.bindRenderbuffer(GL_RENDERBUFFER, null);
}
if (!cache.get(KEY_RENDERBUFFER_ATTACHED)) {
_gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, renderbuffer);
cache.put(KEY_RENDERBUFFER_ATTACHED, true);
}
}
}
|
[
"function",
"(",
"renderer",
")",
"{",
"if",
"(",
"renderer",
".",
"__currentFrameBuffer",
")",
"{",
"// Already bound",
"if",
"(",
"renderer",
".",
"__currentFrameBuffer",
"===",
"this",
")",
"{",
"return",
";",
"}",
"console",
".",
"warn",
"(",
"'Renderer already bound with another framebuffer. Unbind it first'",
")",
";",
"}",
"renderer",
".",
"__currentFrameBuffer",
"=",
"this",
";",
"var",
"_gl",
"=",
"renderer",
".",
"gl",
";",
"_gl",
".",
"bindFramebuffer",
"(",
"GL_FRAMEBUFFER",
",",
"this",
".",
"_getFrameBufferGL",
"(",
"renderer",
")",
")",
";",
"this",
".",
"_boundRenderer",
"=",
"renderer",
";",
"var",
"cache",
"=",
"this",
".",
"_cache",
";",
"cache",
".",
"put",
"(",
"'viewport'",
",",
"renderer",
".",
"viewport",
")",
";",
"var",
"hasTextureAttached",
"=",
"false",
";",
"var",
"width",
";",
"var",
"height",
";",
"for",
"(",
"var",
"attachment",
"in",
"this",
".",
"_textures",
")",
"{",
"hasTextureAttached",
"=",
"true",
";",
"var",
"obj",
"=",
"this",
".",
"_textures",
"[",
"attachment",
"]",
";",
"if",
"(",
"obj",
")",
"{",
"// TODO Do width, height checking, make sure size are same",
"width",
"=",
"obj",
".",
"texture",
".",
"width",
";",
"height",
"=",
"obj",
".",
"texture",
".",
"height",
";",
"// Attach textures",
"this",
".",
"_doAttach",
"(",
"renderer",
",",
"obj",
".",
"texture",
",",
"attachment",
",",
"obj",
".",
"target",
")",
";",
"}",
"}",
"this",
".",
"_width",
"=",
"width",
";",
"this",
".",
"_height",
"=",
"height",
";",
"if",
"(",
"!",
"hasTextureAttached",
"&&",
"this",
".",
"depthBuffer",
")",
"{",
"console",
".",
"error",
"(",
"'Must attach texture before bind, or renderbuffer may have incorrect width and height.'",
")",
";",
"}",
"if",
"(",
"this",
".",
"viewport",
")",
"{",
"renderer",
".",
"setViewport",
"(",
"this",
".",
"viewport",
")",
";",
"}",
"else",
"{",
"renderer",
".",
"setViewport",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
",",
"1",
")",
";",
"}",
"var",
"attachedTextures",
"=",
"cache",
".",
"get",
"(",
"'attached_textures'",
")",
";",
"if",
"(",
"attachedTextures",
")",
"{",
"for",
"(",
"var",
"attachment",
"in",
"attachedTextures",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_textures",
"[",
"attachment",
"]",
")",
"{",
"var",
"target",
"=",
"attachedTextures",
"[",
"attachment",
"]",
";",
"this",
".",
"_doDetach",
"(",
"_gl",
",",
"attachment",
",",
"target",
")",
";",
"}",
"}",
"}",
"if",
"(",
"!",
"cache",
".",
"get",
"(",
"KEY_DEPTHTEXTURE_ATTACHED",
")",
"&&",
"this",
".",
"depthBuffer",
")",
"{",
"// Create a new render buffer",
"if",
"(",
"cache",
".",
"miss",
"(",
"KEY_RENDERBUFFER",
")",
")",
"{",
"cache",
".",
"put",
"(",
"KEY_RENDERBUFFER",
",",
"_gl",
".",
"createRenderbuffer",
"(",
")",
")",
";",
"}",
"var",
"renderbuffer",
"=",
"cache",
".",
"get",
"(",
"KEY_RENDERBUFFER",
")",
";",
"if",
"(",
"width",
"!==",
"cache",
".",
"get",
"(",
"KEY_RENDERBUFFER_WIDTH",
")",
"||",
"height",
"!==",
"cache",
".",
"get",
"(",
"KEY_RENDERBUFFER_HEIGHT",
")",
")",
"{",
"_gl",
".",
"bindRenderbuffer",
"(",
"GL_RENDERBUFFER",
",",
"renderbuffer",
")",
";",
"_gl",
".",
"renderbufferStorage",
"(",
"GL_RENDERBUFFER",
",",
"_gl",
".",
"DEPTH_COMPONENT16",
",",
"width",
",",
"height",
")",
";",
"cache",
".",
"put",
"(",
"KEY_RENDERBUFFER_WIDTH",
",",
"width",
")",
";",
"cache",
".",
"put",
"(",
"KEY_RENDERBUFFER_HEIGHT",
",",
"height",
")",
";",
"_gl",
".",
"bindRenderbuffer",
"(",
"GL_RENDERBUFFER",
",",
"null",
")",
";",
"}",
"if",
"(",
"!",
"cache",
".",
"get",
"(",
"KEY_RENDERBUFFER_ATTACHED",
")",
")",
"{",
"_gl",
".",
"framebufferRenderbuffer",
"(",
"GL_FRAMEBUFFER",
",",
"GL_DEPTH_ATTACHMENT",
",",
"GL_RENDERBUFFER",
",",
"renderbuffer",
")",
";",
"cache",
".",
"put",
"(",
"KEY_RENDERBUFFER_ATTACHED",
",",
"true",
")",
";",
"}",
"}",
"}"
] |
Bind the framebuffer to given renderer before rendering
@param {clay.Renderer} renderer
|
[
"Bind",
"the",
"framebuffer",
"to",
"given",
"renderer",
"before",
"rendering"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L22362-L22440
|
|
6,908
|
pissang/claygl
|
dist/claygl.es.js
|
function (renderer) {
// Remove status record on renderer
renderer.__currentFrameBuffer = null;
var _gl = renderer.gl;
_gl.bindFramebuffer(GL_FRAMEBUFFER, null);
this._boundRenderer = null;
this._cache.use(renderer.__uid__);
var viewport = this._cache.get('viewport');
// Reset viewport;
if (viewport) {
renderer.setViewport(viewport);
}
this.updateMipmap(renderer);
}
|
javascript
|
function (renderer) {
// Remove status record on renderer
renderer.__currentFrameBuffer = null;
var _gl = renderer.gl;
_gl.bindFramebuffer(GL_FRAMEBUFFER, null);
this._boundRenderer = null;
this._cache.use(renderer.__uid__);
var viewport = this._cache.get('viewport');
// Reset viewport;
if (viewport) {
renderer.setViewport(viewport);
}
this.updateMipmap(renderer);
}
|
[
"function",
"(",
"renderer",
")",
"{",
"// Remove status record on renderer",
"renderer",
".",
"__currentFrameBuffer",
"=",
"null",
";",
"var",
"_gl",
"=",
"renderer",
".",
"gl",
";",
"_gl",
".",
"bindFramebuffer",
"(",
"GL_FRAMEBUFFER",
",",
"null",
")",
";",
"this",
".",
"_boundRenderer",
"=",
"null",
";",
"this",
".",
"_cache",
".",
"use",
"(",
"renderer",
".",
"__uid__",
")",
";",
"var",
"viewport",
"=",
"this",
".",
"_cache",
".",
"get",
"(",
"'viewport'",
")",
";",
"// Reset viewport;",
"if",
"(",
"viewport",
")",
"{",
"renderer",
".",
"setViewport",
"(",
"viewport",
")",
";",
"}",
"this",
".",
"updateMipmap",
"(",
"renderer",
")",
";",
"}"
] |
Unbind the frame buffer after rendering
@param {clay.Renderer} renderer
|
[
"Unbind",
"the",
"frame",
"buffer",
"after",
"rendering"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L22446-L22463
|
|
6,909
|
pissang/claygl
|
dist/claygl.es.js
|
function (renderer) {
var _gl = renderer.gl;
for (var attachment in this._textures) {
var obj = this._textures[attachment];
if (obj) {
var texture = obj.texture;
// FIXME some texture format can't generate mipmap
if (!texture.NPOT && texture.useMipmap
&& texture.minFilter === Texture.LINEAR_MIPMAP_LINEAR) {
var target = texture.textureType === 'textureCube' ? glenum.TEXTURE_CUBE_MAP : glenum.TEXTURE_2D;
_gl.bindTexture(target, texture.getWebGLTexture(renderer));
_gl.generateMipmap(target);
_gl.bindTexture(target, null);
}
}
}
}
|
javascript
|
function (renderer) {
var _gl = renderer.gl;
for (var attachment in this._textures) {
var obj = this._textures[attachment];
if (obj) {
var texture = obj.texture;
// FIXME some texture format can't generate mipmap
if (!texture.NPOT && texture.useMipmap
&& texture.minFilter === Texture.LINEAR_MIPMAP_LINEAR) {
var target = texture.textureType === 'textureCube' ? glenum.TEXTURE_CUBE_MAP : glenum.TEXTURE_2D;
_gl.bindTexture(target, texture.getWebGLTexture(renderer));
_gl.generateMipmap(target);
_gl.bindTexture(target, null);
}
}
}
}
|
[
"function",
"(",
"renderer",
")",
"{",
"var",
"_gl",
"=",
"renderer",
".",
"gl",
";",
"for",
"(",
"var",
"attachment",
"in",
"this",
".",
"_textures",
")",
"{",
"var",
"obj",
"=",
"this",
".",
"_textures",
"[",
"attachment",
"]",
";",
"if",
"(",
"obj",
")",
"{",
"var",
"texture",
"=",
"obj",
".",
"texture",
";",
"// FIXME some texture format can't generate mipmap",
"if",
"(",
"!",
"texture",
".",
"NPOT",
"&&",
"texture",
".",
"useMipmap",
"&&",
"texture",
".",
"minFilter",
"===",
"Texture",
".",
"LINEAR_MIPMAP_LINEAR",
")",
"{",
"var",
"target",
"=",
"texture",
".",
"textureType",
"===",
"'textureCube'",
"?",
"glenum",
".",
"TEXTURE_CUBE_MAP",
":",
"glenum",
".",
"TEXTURE_2D",
";",
"_gl",
".",
"bindTexture",
"(",
"target",
",",
"texture",
".",
"getWebGLTexture",
"(",
"renderer",
")",
")",
";",
"_gl",
".",
"generateMipmap",
"(",
"target",
")",
";",
"_gl",
".",
"bindTexture",
"(",
"target",
",",
"null",
")",
";",
"}",
"}",
"}",
"}"
] |
Because the data of texture is changed over time, Here update the mipmaps of texture each time after rendered;
|
[
"Because",
"the",
"data",
"of",
"texture",
"is",
"changed",
"over",
"time",
"Here",
"update",
"the",
"mipmaps",
"of",
"texture",
"each",
"time",
"after",
"rendered",
";"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L22467-L22483
|
|
6,910
|
pissang/claygl
|
dist/claygl.es.js
|
function (attachment, target) {
// TODO depth extension check ?
this._textures[attachment] = null;
if (this._boundRenderer) {
var cache = this._cache;
cache.use(this._boundRenderer.__uid__);
this._doDetach(this._boundRenderer.gl, attachment, target);
}
}
|
javascript
|
function (attachment, target) {
// TODO depth extension check ?
this._textures[attachment] = null;
if (this._boundRenderer) {
var cache = this._cache;
cache.use(this._boundRenderer.__uid__);
this._doDetach(this._boundRenderer.gl, attachment, target);
}
}
|
[
"function",
"(",
"attachment",
",",
"target",
")",
"{",
"// TODO depth extension check ?",
"this",
".",
"_textures",
"[",
"attachment",
"]",
"=",
"null",
";",
"if",
"(",
"this",
".",
"_boundRenderer",
")",
"{",
"var",
"cache",
"=",
"this",
".",
"_cache",
";",
"cache",
".",
"use",
"(",
"this",
".",
"_boundRenderer",
".",
"__uid__",
")",
";",
"this",
".",
"_doDetach",
"(",
"this",
".",
"_boundRenderer",
".",
"gl",
",",
"attachment",
",",
"target",
")",
";",
"}",
"}"
] |
Detach a texture
@param {number} [attachment=gl.COLOR_ATTACHMENT0]
@param {number} [target=gl.TEXTURE_2D]
|
[
"Detach",
"a",
"texture"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L22641-L22649
|
|
6,911
|
pissang/claygl
|
dist/claygl.es.js
|
function (scene) {
if (this.scene) {
this.detachScene();
}
scene.skybox = this;
this.scene = scene;
scene.on('beforerender', this._beforeRenderScene, this);
}
|
javascript
|
function (scene) {
if (this.scene) {
this.detachScene();
}
scene.skybox = this;
this.scene = scene;
scene.on('beforerender', this._beforeRenderScene, this);
}
|
[
"function",
"(",
"scene",
")",
"{",
"if",
"(",
"this",
".",
"scene",
")",
"{",
"this",
".",
"detachScene",
"(",
")",
";",
"}",
"scene",
".",
"skybox",
"=",
"this",
";",
"this",
".",
"scene",
"=",
"scene",
";",
"scene",
".",
"on",
"(",
"'beforerender'",
",",
"this",
".",
"_beforeRenderScene",
",",
"this",
")",
";",
"}"
] |
Attach the skybox to the scene
@param {clay.Scene} scene
|
[
"Attach",
"the",
"skybox",
"to",
"the",
"scene"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L22939-L22947
|
|
6,912
|
pissang/claygl
|
dist/claygl.es.js
|
function (envMap) {
if (envMap.textureType === 'texture2D') {
this.material.define('EQUIRECTANGULAR');
// LINEAR filter can remove the artifacts in pole
envMap.minFilter = Texture.LINEAR;
}
else {
this.material.undefine('EQUIRECTANGULAR');
}
this.material.set('environmentMap', envMap);
}
|
javascript
|
function (envMap) {
if (envMap.textureType === 'texture2D') {
this.material.define('EQUIRECTANGULAR');
// LINEAR filter can remove the artifacts in pole
envMap.minFilter = Texture.LINEAR;
}
else {
this.material.undefine('EQUIRECTANGULAR');
}
this.material.set('environmentMap', envMap);
}
|
[
"function",
"(",
"envMap",
")",
"{",
"if",
"(",
"envMap",
".",
"textureType",
"===",
"'texture2D'",
")",
"{",
"this",
".",
"material",
".",
"define",
"(",
"'EQUIRECTANGULAR'",
")",
";",
"// LINEAR filter can remove the artifacts in pole",
"envMap",
".",
"minFilter",
"=",
"Texture",
".",
"LINEAR",
";",
"}",
"else",
"{",
"this",
".",
"material",
".",
"undefine",
"(",
"'EQUIRECTANGULAR'",
")",
";",
"}",
"this",
".",
"material",
".",
"set",
"(",
"'environmentMap'",
",",
"envMap",
")",
";",
"}"
] |
Set environment map
@param {clay.TextureCube} envMap
|
[
"Set",
"environment",
"map"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L22971-L22981
|
|
6,913
|
pissang/claygl
|
dist/claygl.es.js
|
function (renderer, path, cubeMap, option, onsuccess, onerror) {
var self = this;
if (typeof(option) === 'function') {
onsuccess = option;
onerror = onsuccess;
option = {};
}
else {
option = option || {};
}
textureUtil.loadTexture(path, option, function (texture) {
// PENDING
texture.flipY = option.flipY || false;
self.panoramaToCubeMap(renderer, texture, cubeMap, option);
texture.dispose(renderer);
onsuccess && onsuccess(cubeMap);
}, onerror);
}
|
javascript
|
function (renderer, path, cubeMap, option, onsuccess, onerror) {
var self = this;
if (typeof(option) === 'function') {
onsuccess = option;
onerror = onsuccess;
option = {};
}
else {
option = option || {};
}
textureUtil.loadTexture(path, option, function (texture) {
// PENDING
texture.flipY = option.flipY || false;
self.panoramaToCubeMap(renderer, texture, cubeMap, option);
texture.dispose(renderer);
onsuccess && onsuccess(cubeMap);
}, onerror);
}
|
[
"function",
"(",
"renderer",
",",
"path",
",",
"cubeMap",
",",
"option",
",",
"onsuccess",
",",
"onerror",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"typeof",
"(",
"option",
")",
"===",
"'function'",
")",
"{",
"onsuccess",
"=",
"option",
";",
"onerror",
"=",
"onsuccess",
";",
"option",
"=",
"{",
"}",
";",
"}",
"else",
"{",
"option",
"=",
"option",
"||",
"{",
"}",
";",
"}",
"textureUtil",
".",
"loadTexture",
"(",
"path",
",",
"option",
",",
"function",
"(",
"texture",
")",
"{",
"// PENDING",
"texture",
".",
"flipY",
"=",
"option",
".",
"flipY",
"||",
"false",
";",
"self",
".",
"panoramaToCubeMap",
"(",
"renderer",
",",
"texture",
",",
"cubeMap",
",",
"option",
")",
";",
"texture",
".",
"dispose",
"(",
"renderer",
")",
";",
"onsuccess",
"&&",
"onsuccess",
"(",
"cubeMap",
")",
";",
"}",
",",
"onerror",
")",
";",
"}"
] |
Load a panorama texture and render it to a cube map
@param {clay.Renderer} renderer
@param {string} path
@param {clay.TextureCube} cubeMap
@param {object} [option]
@param {boolean} [option.encodeRGBM]
@param {number} [option.exposure]
@param {Function} [onsuccess]
@param {Function} [onerror]
|
[
"Load",
"a",
"panorama",
"texture",
"and",
"render",
"it",
"to",
"a",
"cube",
"map"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L23522-L23541
|
|
6,914
|
pissang/claygl
|
dist/claygl.es.js
|
function (renderer, panoramaMap, cubeMap, option) {
var environmentMapPass = new EnvironmentMapPass();
var skydome = new Skybox$1({
scene: new Scene()
});
skydome.setEnvironmentMap(panoramaMap);
option = option || {};
if (option.encodeRGBM) {
skydome.material.define('fragment', 'RGBM_ENCODE');
}
// Share sRGB
cubeMap.sRGB = panoramaMap.sRGB;
environmentMapPass.texture = cubeMap;
environmentMapPass.render(renderer, skydome.scene);
environmentMapPass.texture = null;
environmentMapPass.dispose(renderer);
return cubeMap;
}
|
javascript
|
function (renderer, panoramaMap, cubeMap, option) {
var environmentMapPass = new EnvironmentMapPass();
var skydome = new Skybox$1({
scene: new Scene()
});
skydome.setEnvironmentMap(panoramaMap);
option = option || {};
if (option.encodeRGBM) {
skydome.material.define('fragment', 'RGBM_ENCODE');
}
// Share sRGB
cubeMap.sRGB = panoramaMap.sRGB;
environmentMapPass.texture = cubeMap;
environmentMapPass.render(renderer, skydome.scene);
environmentMapPass.texture = null;
environmentMapPass.dispose(renderer);
return cubeMap;
}
|
[
"function",
"(",
"renderer",
",",
"panoramaMap",
",",
"cubeMap",
",",
"option",
")",
"{",
"var",
"environmentMapPass",
"=",
"new",
"EnvironmentMapPass",
"(",
")",
";",
"var",
"skydome",
"=",
"new",
"Skybox$1",
"(",
"{",
"scene",
":",
"new",
"Scene",
"(",
")",
"}",
")",
";",
"skydome",
".",
"setEnvironmentMap",
"(",
"panoramaMap",
")",
";",
"option",
"=",
"option",
"||",
"{",
"}",
";",
"if",
"(",
"option",
".",
"encodeRGBM",
")",
"{",
"skydome",
".",
"material",
".",
"define",
"(",
"'fragment'",
",",
"'RGBM_ENCODE'",
")",
";",
"}",
"// Share sRGB",
"cubeMap",
".",
"sRGB",
"=",
"panoramaMap",
".",
"sRGB",
";",
"environmentMapPass",
".",
"texture",
"=",
"cubeMap",
";",
"environmentMapPass",
".",
"render",
"(",
"renderer",
",",
"skydome",
".",
"scene",
")",
";",
"environmentMapPass",
".",
"texture",
"=",
"null",
";",
"environmentMapPass",
".",
"dispose",
"(",
"renderer",
")",
";",
"return",
"cubeMap",
";",
"}"
] |
Render a panorama texture to a cube map
@param {clay.Renderer} renderer
@param {clay.Texture2D} panoramaMap
@param {clay.TextureCube} cubeMap
@param {Object} option
@param {boolean} [option.encodeRGBM]
|
[
"Render",
"a",
"panorama",
"texture",
"to",
"a",
"cube",
"map"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L23551-L23571
|
|
6,915
|
pissang/claygl
|
dist/claygl.es.js
|
function (size, unitSize, color1, color2) {
size = size || 512;
unitSize = unitSize || 64;
color1 = color1 || 'black';
color2 = color2 || 'white';
var repeat = Math.ceil(size / unitSize);
var canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
var ctx = canvas.getContext('2d');
ctx.fillStyle = color2;
ctx.fillRect(0, 0, size, size);
ctx.fillStyle = color1;
for (var i = 0; i < repeat; i++) {
for (var j = 0; j < repeat; j++) {
var isFill = j % 2 ? (i % 2) : (i % 2 - 1);
if (isFill) {
ctx.fillRect(i * unitSize, j * unitSize, unitSize, unitSize);
}
}
}
var texture = new Texture2D({
image: canvas,
anisotropic: 8
});
return texture;
}
|
javascript
|
function (size, unitSize, color1, color2) {
size = size || 512;
unitSize = unitSize || 64;
color1 = color1 || 'black';
color2 = color2 || 'white';
var repeat = Math.ceil(size / unitSize);
var canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
var ctx = canvas.getContext('2d');
ctx.fillStyle = color2;
ctx.fillRect(0, 0, size, size);
ctx.fillStyle = color1;
for (var i = 0; i < repeat; i++) {
for (var j = 0; j < repeat; j++) {
var isFill = j % 2 ? (i % 2) : (i % 2 - 1);
if (isFill) {
ctx.fillRect(i * unitSize, j * unitSize, unitSize, unitSize);
}
}
}
var texture = new Texture2D({
image: canvas,
anisotropic: 8
});
return texture;
}
|
[
"function",
"(",
"size",
",",
"unitSize",
",",
"color1",
",",
"color2",
")",
"{",
"size",
"=",
"size",
"||",
"512",
";",
"unitSize",
"=",
"unitSize",
"||",
"64",
";",
"color1",
"=",
"color1",
"||",
"'black'",
";",
"color2",
"=",
"color2",
"||",
"'white'",
";",
"var",
"repeat",
"=",
"Math",
".",
"ceil",
"(",
"size",
"/",
"unitSize",
")",
";",
"var",
"canvas",
"=",
"document",
".",
"createElement",
"(",
"'canvas'",
")",
";",
"canvas",
".",
"width",
"=",
"size",
";",
"canvas",
".",
"height",
"=",
"size",
";",
"var",
"ctx",
"=",
"canvas",
".",
"getContext",
"(",
"'2d'",
")",
";",
"ctx",
".",
"fillStyle",
"=",
"color2",
";",
"ctx",
".",
"fillRect",
"(",
"0",
",",
"0",
",",
"size",
",",
"size",
")",
";",
"ctx",
".",
"fillStyle",
"=",
"color1",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"repeat",
";",
"i",
"++",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"repeat",
";",
"j",
"++",
")",
"{",
"var",
"isFill",
"=",
"j",
"%",
"2",
"?",
"(",
"i",
"%",
"2",
")",
":",
"(",
"i",
"%",
"2",
"-",
"1",
")",
";",
"if",
"(",
"isFill",
")",
"{",
"ctx",
".",
"fillRect",
"(",
"i",
"*",
"unitSize",
",",
"j",
"*",
"unitSize",
",",
"unitSize",
",",
"unitSize",
")",
";",
"}",
"}",
"}",
"var",
"texture",
"=",
"new",
"Texture2D",
"(",
"{",
"image",
":",
"canvas",
",",
"anisotropic",
":",
"8",
"}",
")",
";",
"return",
"texture",
";",
"}"
] |
Create a chessboard texture
@param {number} [size]
@param {number} [unitSize]
@param {string} [color1]
@param {string} [color2]
@return {clay.Texture2D}
|
[
"Create",
"a",
"chessboard",
"texture"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L23688-L23719
|
|
6,916
|
pissang/claygl
|
dist/claygl.es.js
|
function (color) {
var canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 1;
var ctx = canvas.getContext('2d');
ctx.fillStyle = color;
ctx.fillRect(0, 0, 1, 1);
var texture = new Texture2D({
image: canvas
});
return texture;
}
|
javascript
|
function (color) {
var canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 1;
var ctx = canvas.getContext('2d');
ctx.fillStyle = color;
ctx.fillRect(0, 0, 1, 1);
var texture = new Texture2D({
image: canvas
});
return texture;
}
|
[
"function",
"(",
"color",
")",
"{",
"var",
"canvas",
"=",
"document",
".",
"createElement",
"(",
"'canvas'",
")",
";",
"canvas",
".",
"width",
"=",
"1",
";",
"canvas",
".",
"height",
"=",
"1",
";",
"var",
"ctx",
"=",
"canvas",
".",
"getContext",
"(",
"'2d'",
")",
";",
"ctx",
".",
"fillStyle",
"=",
"color",
";",
"ctx",
".",
"fillRect",
"(",
"0",
",",
"0",
",",
"1",
",",
"1",
")",
";",
"var",
"texture",
"=",
"new",
"Texture2D",
"(",
"{",
"image",
":",
"canvas",
"}",
")",
";",
"return",
"texture",
";",
"}"
] |
Create a blank pure color 1x1 texture
@param {string} color
@return {clay.Texture2D}
|
[
"Create",
"a",
"blank",
"pure",
"color",
"1x1",
"texture"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L23726-L23739
|
|
6,917
|
pissang/claygl
|
dist/claygl.es.js
|
function (renderer, size) {
if (!renderer.getGLExtension('EXT_shader_texture_lod')) {
console.warn('Device not support textureCubeLodEXT');
return;
}
if (!this._brdfLookup) {
this._normalDistribution = cubemapUtil.generateNormalDistribution();
this._brdfLookup = cubemapUtil.integrateBRDF(renderer, this._normalDistribution);
}
var cubemap = this.cubemap;
if (cubemap.__prefiltered) {
return;
}
var result = cubemapUtil.prefilterEnvironmentMap(
renderer, cubemap, {
encodeRGBM: true,
width: size,
height: size
}, this._normalDistribution, this._brdfLookup
);
this.cubemap = result.environmentMap;
this.cubemap.__prefiltered = true;
cubemap.dispose(renderer);
}
|
javascript
|
function (renderer, size) {
if (!renderer.getGLExtension('EXT_shader_texture_lod')) {
console.warn('Device not support textureCubeLodEXT');
return;
}
if (!this._brdfLookup) {
this._normalDistribution = cubemapUtil.generateNormalDistribution();
this._brdfLookup = cubemapUtil.integrateBRDF(renderer, this._normalDistribution);
}
var cubemap = this.cubemap;
if (cubemap.__prefiltered) {
return;
}
var result = cubemapUtil.prefilterEnvironmentMap(
renderer, cubemap, {
encodeRGBM: true,
width: size,
height: size
}, this._normalDistribution, this._brdfLookup
);
this.cubemap = result.environmentMap;
this.cubemap.__prefiltered = true;
cubemap.dispose(renderer);
}
|
[
"function",
"(",
"renderer",
",",
"size",
")",
"{",
"if",
"(",
"!",
"renderer",
".",
"getGLExtension",
"(",
"'EXT_shader_texture_lod'",
")",
")",
"{",
"console",
".",
"warn",
"(",
"'Device not support textureCubeLodEXT'",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"this",
".",
"_brdfLookup",
")",
"{",
"this",
".",
"_normalDistribution",
"=",
"cubemapUtil",
".",
"generateNormalDistribution",
"(",
")",
";",
"this",
".",
"_brdfLookup",
"=",
"cubemapUtil",
".",
"integrateBRDF",
"(",
"renderer",
",",
"this",
".",
"_normalDistribution",
")",
";",
"}",
"var",
"cubemap",
"=",
"this",
".",
"cubemap",
";",
"if",
"(",
"cubemap",
".",
"__prefiltered",
")",
"{",
"return",
";",
"}",
"var",
"result",
"=",
"cubemapUtil",
".",
"prefilterEnvironmentMap",
"(",
"renderer",
",",
"cubemap",
",",
"{",
"encodeRGBM",
":",
"true",
",",
"width",
":",
"size",
",",
"height",
":",
"size",
"}",
",",
"this",
".",
"_normalDistribution",
",",
"this",
".",
"_brdfLookup",
")",
";",
"this",
".",
"cubemap",
"=",
"result",
".",
"environmentMap",
";",
"this",
".",
"cubemap",
".",
"__prefiltered",
"=",
"true",
";",
"cubemap",
".",
"dispose",
"(",
"renderer",
")",
";",
"}"
] |
Do prefitering the cubemap
@param {clay.Renderer} renderer
@param {number} [size=32]
|
[
"Do",
"prefitering",
"the",
"cubemap"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L24048-L24073
|
|
6,918
|
pissang/claygl
|
dist/claygl.es.js
|
function (renderer, scene, sceneCamera, notUpdateScene) {
if (!sceneCamera) {
sceneCamera = scene.getMainCamera();
}
this.trigger('beforerender', this, renderer, scene, sceneCamera);
this._renderShadowPass(renderer, scene, sceneCamera, notUpdateScene);
this.trigger('afterrender', this, renderer, scene, sceneCamera);
}
|
javascript
|
function (renderer, scene, sceneCamera, notUpdateScene) {
if (!sceneCamera) {
sceneCamera = scene.getMainCamera();
}
this.trigger('beforerender', this, renderer, scene, sceneCamera);
this._renderShadowPass(renderer, scene, sceneCamera, notUpdateScene);
this.trigger('afterrender', this, renderer, scene, sceneCamera);
}
|
[
"function",
"(",
"renderer",
",",
"scene",
",",
"sceneCamera",
",",
"notUpdateScene",
")",
"{",
"if",
"(",
"!",
"sceneCamera",
")",
"{",
"sceneCamera",
"=",
"scene",
".",
"getMainCamera",
"(",
")",
";",
"}",
"this",
".",
"trigger",
"(",
"'beforerender'",
",",
"this",
",",
"renderer",
",",
"scene",
",",
"sceneCamera",
")",
";",
"this",
".",
"_renderShadowPass",
"(",
"renderer",
",",
"scene",
",",
"sceneCamera",
",",
"notUpdateScene",
")",
";",
"this",
".",
"trigger",
"(",
"'afterrender'",
",",
"this",
",",
"renderer",
",",
"scene",
",",
"sceneCamera",
")",
";",
"}"
] |
Render scene to shadow textures
@param {clay.Renderer} renderer
@param {clay.Scene} scene
@param {clay.Camera} sceneCamera
@param {boolean} [notUpdateScene=false]
@memberOf clay.prePass.ShadowMap.prototype
|
[
"Render",
"scene",
"to",
"shadow",
"textures"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L24395-L24402
|
|
6,919
|
pissang/claygl
|
dist/claygl.es.js
|
function (renderer, size) {
renderer.saveClear();
var viewport = renderer.viewport;
var x = 0, y = 0;
var width = size || viewport.width / 4;
var height = width;
if (this.softShadow === ShadowMapPass.VSM) {
this._outputDepthPass.material.define('fragment', 'USE_VSM');
}
else {
this._outputDepthPass.material.undefine('fragment', 'USE_VSM');
}
for (var name in this._textures) {
var texture = this._textures[name];
renderer.setViewport(x, y, width * texture.width / texture.height, height);
this._outputDepthPass.setUniform('depthMap', texture);
this._outputDepthPass.render(renderer);
x += width * texture.width / texture.height;
}
renderer.setViewport(viewport);
renderer.restoreClear();
}
|
javascript
|
function (renderer, size) {
renderer.saveClear();
var viewport = renderer.viewport;
var x = 0, y = 0;
var width = size || viewport.width / 4;
var height = width;
if (this.softShadow === ShadowMapPass.VSM) {
this._outputDepthPass.material.define('fragment', 'USE_VSM');
}
else {
this._outputDepthPass.material.undefine('fragment', 'USE_VSM');
}
for (var name in this._textures) {
var texture = this._textures[name];
renderer.setViewport(x, y, width * texture.width / texture.height, height);
this._outputDepthPass.setUniform('depthMap', texture);
this._outputDepthPass.render(renderer);
x += width * texture.width / texture.height;
}
renderer.setViewport(viewport);
renderer.restoreClear();
}
|
[
"function",
"(",
"renderer",
",",
"size",
")",
"{",
"renderer",
".",
"saveClear",
"(",
")",
";",
"var",
"viewport",
"=",
"renderer",
".",
"viewport",
";",
"var",
"x",
"=",
"0",
",",
"y",
"=",
"0",
";",
"var",
"width",
"=",
"size",
"||",
"viewport",
".",
"width",
"/",
"4",
";",
"var",
"height",
"=",
"width",
";",
"if",
"(",
"this",
".",
"softShadow",
"===",
"ShadowMapPass",
".",
"VSM",
")",
"{",
"this",
".",
"_outputDepthPass",
".",
"material",
".",
"define",
"(",
"'fragment'",
",",
"'USE_VSM'",
")",
";",
"}",
"else",
"{",
"this",
".",
"_outputDepthPass",
".",
"material",
".",
"undefine",
"(",
"'fragment'",
",",
"'USE_VSM'",
")",
";",
"}",
"for",
"(",
"var",
"name",
"in",
"this",
".",
"_textures",
")",
"{",
"var",
"texture",
"=",
"this",
".",
"_textures",
"[",
"name",
"]",
";",
"renderer",
".",
"setViewport",
"(",
"x",
",",
"y",
",",
"width",
"*",
"texture",
".",
"width",
"/",
"texture",
".",
"height",
",",
"height",
")",
";",
"this",
".",
"_outputDepthPass",
".",
"setUniform",
"(",
"'depthMap'",
",",
"texture",
")",
";",
"this",
".",
"_outputDepthPass",
".",
"render",
"(",
"renderer",
")",
";",
"x",
"+=",
"width",
"*",
"texture",
".",
"width",
"/",
"texture",
".",
"height",
";",
"}",
"renderer",
".",
"setViewport",
"(",
"viewport",
")",
";",
"renderer",
".",
"restoreClear",
"(",
")",
";",
"}"
] |
Debug rendering of shadow textures
@param {clay.Renderer} renderer
@param {number} size
@memberOf clay.prePass.ShadowMap.prototype
|
[
"Debug",
"rendering",
"of",
"shadow",
"textures"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L24410-L24431
|
|
6,920
|
pissang/claygl
|
dist/claygl.es.js
|
function (x, y, forcePickAll) {
var out = this.pickAll(x, y, [], forcePickAll);
return out[0] || null;
}
|
javascript
|
function (x, y, forcePickAll) {
var out = this.pickAll(x, y, [], forcePickAll);
return out[0] || null;
}
|
[
"function",
"(",
"x",
",",
"y",
",",
"forcePickAll",
")",
"{",
"var",
"out",
"=",
"this",
".",
"pickAll",
"(",
"x",
",",
"y",
",",
"[",
"]",
",",
"forcePickAll",
")",
";",
"return",
"out",
"[",
"0",
"]",
"||",
"null",
";",
"}"
] |
Pick the nearest intersection object in the scene
@param {number} x Mouse position x
@param {number} y Mouse position y
@param {boolean} [forcePickAll=false] ignore ignorePicking
@return {clay.picking.RayPicking~Intersection}
|
[
"Pick",
"the",
"nearest",
"intersection",
"object",
"in",
"the",
"scene"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L25182-L25185
|
|
6,921
|
pissang/claygl
|
dist/claygl.es.js
|
function (x, y, output, forcePickAll) {
this.renderer.screenToNDC(x, y, this._ndc);
this.camera.castRay(this._ndc, this._ray);
output = output || [];
this._intersectNode(this.scene, output, forcePickAll || false);
output.sort(this._intersectionCompareFunc);
return output;
}
|
javascript
|
function (x, y, output, forcePickAll) {
this.renderer.screenToNDC(x, y, this._ndc);
this.camera.castRay(this._ndc, this._ray);
output = output || [];
this._intersectNode(this.scene, output, forcePickAll || false);
output.sort(this._intersectionCompareFunc);
return output;
}
|
[
"function",
"(",
"x",
",",
"y",
",",
"output",
",",
"forcePickAll",
")",
"{",
"this",
".",
"renderer",
".",
"screenToNDC",
"(",
"x",
",",
"y",
",",
"this",
".",
"_ndc",
")",
";",
"this",
".",
"camera",
".",
"castRay",
"(",
"this",
".",
"_ndc",
",",
"this",
".",
"_ray",
")",
";",
"output",
"=",
"output",
"||",
"[",
"]",
";",
"this",
".",
"_intersectNode",
"(",
"this",
".",
"scene",
",",
"output",
",",
"forcePickAll",
"||",
"false",
")",
";",
"output",
".",
"sort",
"(",
"this",
".",
"_intersectionCompareFunc",
")",
";",
"return",
"output",
";",
"}"
] |
Pick all intersection objects, wich will be sorted from near to far
@param {number} x Mouse position x
@param {number} y Mouse position y
@param {Array} [output]
@param {boolean} [forcePickAll=false] ignore ignorePicking
@return {Array.<clay.picking.RayPicking~Intersection>}
|
[
"Pick",
"all",
"intersection",
"objects",
"wich",
"will",
"be",
"sorted",
"from",
"near",
"to",
"far"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L25195-L25206
|
|
6,922
|
pissang/claygl
|
dist/claygl.es.js
|
function () {
for (var i = 0; i < this.nodes.length; i++) {
this.nodes[i].clear();
}
// Traverse all the nodes and build the graph
for (var i = 0; i < this.nodes.length; i++) {
var node = this.nodes[i];
if (!node.inputs) {
continue;
}
for (var inputName in node.inputs) {
if (!node.inputs[inputName]) {
continue;
}
if (node.pass && !node.pass.material.isUniformEnabled(inputName)) {
console.warn('Pin ' + node.name + '.' + inputName + ' not used.');
continue;
}
var fromPinInfo = node.inputs[inputName];
var fromPin = this.findPin(fromPinInfo);
if (fromPin) {
node.link(inputName, fromPin.node, fromPin.pin);
}
else {
if (typeof fromPinInfo === 'string') {
console.warn('Node ' + fromPinInfo + ' not exist');
}
else {
console.warn('Pin of ' + fromPinInfo.node + '.' + fromPinInfo.pin + ' not exist');
}
}
}
}
}
|
javascript
|
function () {
for (var i = 0; i < this.nodes.length; i++) {
this.nodes[i].clear();
}
// Traverse all the nodes and build the graph
for (var i = 0; i < this.nodes.length; i++) {
var node = this.nodes[i];
if (!node.inputs) {
continue;
}
for (var inputName in node.inputs) {
if (!node.inputs[inputName]) {
continue;
}
if (node.pass && !node.pass.material.isUniformEnabled(inputName)) {
console.warn('Pin ' + node.name + '.' + inputName + ' not used.');
continue;
}
var fromPinInfo = node.inputs[inputName];
var fromPin = this.findPin(fromPinInfo);
if (fromPin) {
node.link(inputName, fromPin.node, fromPin.pin);
}
else {
if (typeof fromPinInfo === 'string') {
console.warn('Node ' + fromPinInfo + ' not exist');
}
else {
console.warn('Pin of ' + fromPinInfo.node + '.' + fromPinInfo.pin + ' not exist');
}
}
}
}
}
|
[
"function",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"nodes",
".",
"length",
";",
"i",
"++",
")",
"{",
"this",
".",
"nodes",
"[",
"i",
"]",
".",
"clear",
"(",
")",
";",
"}",
"// Traverse all the nodes and build the graph",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"nodes",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"node",
"=",
"this",
".",
"nodes",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"node",
".",
"inputs",
")",
"{",
"continue",
";",
"}",
"for",
"(",
"var",
"inputName",
"in",
"node",
".",
"inputs",
")",
"{",
"if",
"(",
"!",
"node",
".",
"inputs",
"[",
"inputName",
"]",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"node",
".",
"pass",
"&&",
"!",
"node",
".",
"pass",
".",
"material",
".",
"isUniformEnabled",
"(",
"inputName",
")",
")",
"{",
"console",
".",
"warn",
"(",
"'Pin '",
"+",
"node",
".",
"name",
"+",
"'.'",
"+",
"inputName",
"+",
"' not used.'",
")",
";",
"continue",
";",
"}",
"var",
"fromPinInfo",
"=",
"node",
".",
"inputs",
"[",
"inputName",
"]",
";",
"var",
"fromPin",
"=",
"this",
".",
"findPin",
"(",
"fromPinInfo",
")",
";",
"if",
"(",
"fromPin",
")",
"{",
"node",
".",
"link",
"(",
"inputName",
",",
"fromPin",
".",
"node",
",",
"fromPin",
".",
"pin",
")",
";",
"}",
"else",
"{",
"if",
"(",
"typeof",
"fromPinInfo",
"===",
"'string'",
")",
"{",
"console",
".",
"warn",
"(",
"'Node '",
"+",
"fromPinInfo",
"+",
"' not exist'",
")",
";",
"}",
"else",
"{",
"console",
".",
"warn",
"(",
"'Pin of '",
"+",
"fromPinInfo",
".",
"node",
"+",
"'.'",
"+",
"fromPinInfo",
".",
"pin",
"+",
"' not exist'",
")",
";",
"}",
"}",
"}",
"}",
"}"
] |
Update links of graph
|
[
"Update",
"links",
"of",
"graph"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L27548-L27583
|
|
6,923
|
pissang/claygl
|
dist/claygl.es.js
|
function (width, height) {
if (this._gBufferTex1.width === width
&& this._gBufferTex1.height === height
) {
return;
}
this._gBufferTex1.width = width;
this._gBufferTex1.height = height;
this._gBufferTex2.width = width;
this._gBufferTex2.height = height;
this._gBufferTex3.width = width;
this._gBufferTex3.height = height;
this._gBufferTex4.width = width;
this._gBufferTex4.height = height;
}
|
javascript
|
function (width, height) {
if (this._gBufferTex1.width === width
&& this._gBufferTex1.height === height
) {
return;
}
this._gBufferTex1.width = width;
this._gBufferTex1.height = height;
this._gBufferTex2.width = width;
this._gBufferTex2.height = height;
this._gBufferTex3.width = width;
this._gBufferTex3.height = height;
this._gBufferTex4.width = width;
this._gBufferTex4.height = height;
}
|
[
"function",
"(",
"width",
",",
"height",
")",
"{",
"if",
"(",
"this",
".",
"_gBufferTex1",
".",
"width",
"===",
"width",
"&&",
"this",
".",
"_gBufferTex1",
".",
"height",
"===",
"height",
")",
"{",
"return",
";",
"}",
"this",
".",
"_gBufferTex1",
".",
"width",
"=",
"width",
";",
"this",
".",
"_gBufferTex1",
".",
"height",
"=",
"height",
";",
"this",
".",
"_gBufferTex2",
".",
"width",
"=",
"width",
";",
"this",
".",
"_gBufferTex2",
".",
"height",
"=",
"height",
";",
"this",
".",
"_gBufferTex3",
".",
"width",
"=",
"width",
";",
"this",
".",
"_gBufferTex3",
".",
"height",
"=",
"height",
";",
"this",
".",
"_gBufferTex4",
".",
"width",
"=",
"width",
";",
"this",
".",
"_gBufferTex4",
".",
"height",
"=",
"height",
";",
"}"
] |
Set G Buffer size.
@param {number} width
@param {number} height
|
[
"Set",
"G",
"Buffer",
"size",
"."
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L28704-L28721
|
|
6,924
|
pissang/claygl
|
dist/claygl.es.js
|
function() {
var cone = new Cone$1({
topRadius: this.radius,
bottomRadius: this.radius,
capSegments: this.capSegments,
heightSegments: this.heightSegments,
height: this.height
});
this.attributes.position.value = cone.attributes.position.value;
this.attributes.normal.value = cone.attributes.normal.value;
this.attributes.texcoord0.value = cone.attributes.texcoord0.value;
this.indices = cone.indices;
this.boundingBox = cone.boundingBox;
}
|
javascript
|
function() {
var cone = new Cone$1({
topRadius: this.radius,
bottomRadius: this.radius,
capSegments: this.capSegments,
heightSegments: this.heightSegments,
height: this.height
});
this.attributes.position.value = cone.attributes.position.value;
this.attributes.normal.value = cone.attributes.normal.value;
this.attributes.texcoord0.value = cone.attributes.texcoord0.value;
this.indices = cone.indices;
this.boundingBox = cone.boundingBox;
}
|
[
"function",
"(",
")",
"{",
"var",
"cone",
"=",
"new",
"Cone$1",
"(",
"{",
"topRadius",
":",
"this",
".",
"radius",
",",
"bottomRadius",
":",
"this",
".",
"radius",
",",
"capSegments",
":",
"this",
".",
"capSegments",
",",
"heightSegments",
":",
"this",
".",
"heightSegments",
",",
"height",
":",
"this",
".",
"height",
"}",
")",
";",
"this",
".",
"attributes",
".",
"position",
".",
"value",
"=",
"cone",
".",
"attributes",
".",
"position",
".",
"value",
";",
"this",
".",
"attributes",
".",
"normal",
".",
"value",
"=",
"cone",
".",
"attributes",
".",
"normal",
".",
"value",
";",
"this",
".",
"attributes",
".",
"texcoord0",
".",
"value",
"=",
"cone",
".",
"attributes",
".",
"texcoord0",
".",
"value",
";",
"this",
".",
"indices",
"=",
"cone",
".",
"indices",
";",
"this",
".",
"boundingBox",
"=",
"cone",
".",
"boundingBox",
";",
"}"
] |
Build cylinder geometry
|
[
"Build",
"cylinder",
"geometry"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L29252-L29267
|
|
6,925
|
pissang/claygl
|
dist/claygl.es.js
|
function (light) {
var volumeMesh;
if (light.volumeMesh) {
volumeMesh = light.volumeMesh;
}
else {
switch (light.type) {
// Only local light (point and spot) needs volume mesh.
// Directional and ambient light renders in full quad
case 'POINT_LIGHT':
case 'SPHERE_LIGHT':
var shader = light.type === 'SPHERE_LIGHT'
? this._sphereLightShader : this._pointLightShader;
// Volume mesh created automatically
if (!light.__volumeMesh) {
light.__volumeMesh = new Mesh({
material: this._createLightPassMat(shader),
geometry: this._lightSphereGeo,
// Disable culling
// if light volume mesh intersect camera near plane
// We need mesh inside can still be rendered
culling: false
});
}
volumeMesh = light.__volumeMesh;
var r = light.range + (light.radius || 0);
volumeMesh.scale.set(r, r, r);
break;
case 'SPOT_LIGHT':
light.__volumeMesh = light.__volumeMesh || new Mesh({
material: this._createLightPassMat(this._spotLightShader),
geometry: this._lightConeGeo,
culling: false
});
volumeMesh = light.__volumeMesh;
var aspect = Math.tan(light.penumbraAngle * Math.PI / 180);
var range = light.range;
volumeMesh.scale.set(aspect * range, aspect * range, range / 2);
break;
case 'TUBE_LIGHT':
light.__volumeMesh = light.__volumeMesh || new Mesh({
material: this._createLightPassMat(this._tubeLightShader),
geometry: this._lightCylinderGeo,
culling: false
});
volumeMesh = light.__volumeMesh;
var range = light.range;
volumeMesh.scale.set(light.length / 2 + range, range, range);
break;
}
}
if (volumeMesh) {
volumeMesh.update();
// Apply light transform
Matrix4.multiply(volumeMesh.worldTransform, light.worldTransform, volumeMesh.worldTransform);
var hasShadow = this.shadowMapPass && light.castShadow;
volumeMesh.material[hasShadow ? 'define' : 'undefine']('fragment', 'SHADOWMAP_ENABLED');
}
}
|
javascript
|
function (light) {
var volumeMesh;
if (light.volumeMesh) {
volumeMesh = light.volumeMesh;
}
else {
switch (light.type) {
// Only local light (point and spot) needs volume mesh.
// Directional and ambient light renders in full quad
case 'POINT_LIGHT':
case 'SPHERE_LIGHT':
var shader = light.type === 'SPHERE_LIGHT'
? this._sphereLightShader : this._pointLightShader;
// Volume mesh created automatically
if (!light.__volumeMesh) {
light.__volumeMesh = new Mesh({
material: this._createLightPassMat(shader),
geometry: this._lightSphereGeo,
// Disable culling
// if light volume mesh intersect camera near plane
// We need mesh inside can still be rendered
culling: false
});
}
volumeMesh = light.__volumeMesh;
var r = light.range + (light.radius || 0);
volumeMesh.scale.set(r, r, r);
break;
case 'SPOT_LIGHT':
light.__volumeMesh = light.__volumeMesh || new Mesh({
material: this._createLightPassMat(this._spotLightShader),
geometry: this._lightConeGeo,
culling: false
});
volumeMesh = light.__volumeMesh;
var aspect = Math.tan(light.penumbraAngle * Math.PI / 180);
var range = light.range;
volumeMesh.scale.set(aspect * range, aspect * range, range / 2);
break;
case 'TUBE_LIGHT':
light.__volumeMesh = light.__volumeMesh || new Mesh({
material: this._createLightPassMat(this._tubeLightShader),
geometry: this._lightCylinderGeo,
culling: false
});
volumeMesh = light.__volumeMesh;
var range = light.range;
volumeMesh.scale.set(light.length / 2 + range, range, range);
break;
}
}
if (volumeMesh) {
volumeMesh.update();
// Apply light transform
Matrix4.multiply(volumeMesh.worldTransform, light.worldTransform, volumeMesh.worldTransform);
var hasShadow = this.shadowMapPass && light.castShadow;
volumeMesh.material[hasShadow ? 'define' : 'undefine']('fragment', 'SHADOWMAP_ENABLED');
}
}
|
[
"function",
"(",
"light",
")",
"{",
"var",
"volumeMesh",
";",
"if",
"(",
"light",
".",
"volumeMesh",
")",
"{",
"volumeMesh",
"=",
"light",
".",
"volumeMesh",
";",
"}",
"else",
"{",
"switch",
"(",
"light",
".",
"type",
")",
"{",
"// Only local light (point and spot) needs volume mesh.",
"// Directional and ambient light renders in full quad",
"case",
"'POINT_LIGHT'",
":",
"case",
"'SPHERE_LIGHT'",
":",
"var",
"shader",
"=",
"light",
".",
"type",
"===",
"'SPHERE_LIGHT'",
"?",
"this",
".",
"_sphereLightShader",
":",
"this",
".",
"_pointLightShader",
";",
"// Volume mesh created automatically",
"if",
"(",
"!",
"light",
".",
"__volumeMesh",
")",
"{",
"light",
".",
"__volumeMesh",
"=",
"new",
"Mesh",
"(",
"{",
"material",
":",
"this",
".",
"_createLightPassMat",
"(",
"shader",
")",
",",
"geometry",
":",
"this",
".",
"_lightSphereGeo",
",",
"// Disable culling",
"// if light volume mesh intersect camera near plane",
"// We need mesh inside can still be rendered",
"culling",
":",
"false",
"}",
")",
";",
"}",
"volumeMesh",
"=",
"light",
".",
"__volumeMesh",
";",
"var",
"r",
"=",
"light",
".",
"range",
"+",
"(",
"light",
".",
"radius",
"||",
"0",
")",
";",
"volumeMesh",
".",
"scale",
".",
"set",
"(",
"r",
",",
"r",
",",
"r",
")",
";",
"break",
";",
"case",
"'SPOT_LIGHT'",
":",
"light",
".",
"__volumeMesh",
"=",
"light",
".",
"__volumeMesh",
"||",
"new",
"Mesh",
"(",
"{",
"material",
":",
"this",
".",
"_createLightPassMat",
"(",
"this",
".",
"_spotLightShader",
")",
",",
"geometry",
":",
"this",
".",
"_lightConeGeo",
",",
"culling",
":",
"false",
"}",
")",
";",
"volumeMesh",
"=",
"light",
".",
"__volumeMesh",
";",
"var",
"aspect",
"=",
"Math",
".",
"tan",
"(",
"light",
".",
"penumbraAngle",
"*",
"Math",
".",
"PI",
"/",
"180",
")",
";",
"var",
"range",
"=",
"light",
".",
"range",
";",
"volumeMesh",
".",
"scale",
".",
"set",
"(",
"aspect",
"*",
"range",
",",
"aspect",
"*",
"range",
",",
"range",
"/",
"2",
")",
";",
"break",
";",
"case",
"'TUBE_LIGHT'",
":",
"light",
".",
"__volumeMesh",
"=",
"light",
".",
"__volumeMesh",
"||",
"new",
"Mesh",
"(",
"{",
"material",
":",
"this",
".",
"_createLightPassMat",
"(",
"this",
".",
"_tubeLightShader",
")",
",",
"geometry",
":",
"this",
".",
"_lightCylinderGeo",
",",
"culling",
":",
"false",
"}",
")",
";",
"volumeMesh",
"=",
"light",
".",
"__volumeMesh",
";",
"var",
"range",
"=",
"light",
".",
"range",
";",
"volumeMesh",
".",
"scale",
".",
"set",
"(",
"light",
".",
"length",
"/",
"2",
"+",
"range",
",",
"range",
",",
"range",
")",
";",
"break",
";",
"}",
"}",
"if",
"(",
"volumeMesh",
")",
"{",
"volumeMesh",
".",
"update",
"(",
")",
";",
"// Apply light transform",
"Matrix4",
".",
"multiply",
"(",
"volumeMesh",
".",
"worldTransform",
",",
"light",
".",
"worldTransform",
",",
"volumeMesh",
".",
"worldTransform",
")",
";",
"var",
"hasShadow",
"=",
"this",
".",
"shadowMapPass",
"&&",
"light",
".",
"castShadow",
";",
"volumeMesh",
".",
"material",
"[",
"hasShadow",
"?",
"'define'",
":",
"'undefine'",
"]",
"(",
"'fragment'",
",",
"'SHADOWMAP_ENABLED'",
")",
";",
"}",
"}"
] |
Update light volume mesh Light volume mesh is rendered in light accumulate pass instead of full quad. It will reduce pixels significantly when local light is relatively small. And we can use custom volume mesh to shape the light. See "Deferred Shading Optimizations" in GDC2011
|
[
"Update",
"light",
"volume",
"mesh",
"Light",
"volume",
"mesh",
"is",
"rendered",
"in",
"light",
"accumulate",
"pass",
"instead",
"of",
"full",
"quad",
".",
"It",
"will",
"reduce",
"pixels",
"significantly",
"when",
"local",
"light",
"is",
"relatively",
"small",
".",
"And",
"we",
"can",
"use",
"custom",
"volume",
"mesh",
"to",
"shape",
"the",
"light",
".",
"See",
"Deferred",
"Shading",
"Optimizations",
"in",
"GDC2011"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L29771-L29829
|
|
6,926
|
pissang/claygl
|
dist/claygl.es.js
|
function(out) {
var amount = Math.min(this._particlePool.length, this.amount);
var particle;
for (var i = 0; i < amount; i++) {
particle = this._particlePool.pop();
// Initialize particle status
if (this.position) {
this.position.get(particle.position);
}
if (this.rotation) {
this.rotation.get(particle.rotation);
}
if (this.velocity) {
this.velocity.get(particle.velocity);
}
if (this.angularVelocity) {
this.angularVelocity.get(particle.angularVelocity);
}
if (this.life) {
particle.life = this.life.get();
}
if (this.spriteSize) {
particle.spriteSize = this.spriteSize.get();
}
if (this.weight) {
particle.weight = this.weight.get();
}
particle.age = 0;
out.push(particle);
}
}
|
javascript
|
function(out) {
var amount = Math.min(this._particlePool.length, this.amount);
var particle;
for (var i = 0; i < amount; i++) {
particle = this._particlePool.pop();
// Initialize particle status
if (this.position) {
this.position.get(particle.position);
}
if (this.rotation) {
this.rotation.get(particle.rotation);
}
if (this.velocity) {
this.velocity.get(particle.velocity);
}
if (this.angularVelocity) {
this.angularVelocity.get(particle.angularVelocity);
}
if (this.life) {
particle.life = this.life.get();
}
if (this.spriteSize) {
particle.spriteSize = this.spriteSize.get();
}
if (this.weight) {
particle.weight = this.weight.get();
}
particle.age = 0;
out.push(particle);
}
}
|
[
"function",
"(",
"out",
")",
"{",
"var",
"amount",
"=",
"Math",
".",
"min",
"(",
"this",
".",
"_particlePool",
".",
"length",
",",
"this",
".",
"amount",
")",
";",
"var",
"particle",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"amount",
";",
"i",
"++",
")",
"{",
"particle",
"=",
"this",
".",
"_particlePool",
".",
"pop",
"(",
")",
";",
"// Initialize particle status",
"if",
"(",
"this",
".",
"position",
")",
"{",
"this",
".",
"position",
".",
"get",
"(",
"particle",
".",
"position",
")",
";",
"}",
"if",
"(",
"this",
".",
"rotation",
")",
"{",
"this",
".",
"rotation",
".",
"get",
"(",
"particle",
".",
"rotation",
")",
";",
"}",
"if",
"(",
"this",
".",
"velocity",
")",
"{",
"this",
".",
"velocity",
".",
"get",
"(",
"particle",
".",
"velocity",
")",
";",
"}",
"if",
"(",
"this",
".",
"angularVelocity",
")",
"{",
"this",
".",
"angularVelocity",
".",
"get",
"(",
"particle",
".",
"angularVelocity",
")",
";",
"}",
"if",
"(",
"this",
".",
"life",
")",
"{",
"particle",
".",
"life",
"=",
"this",
".",
"life",
".",
"get",
"(",
")",
";",
"}",
"if",
"(",
"this",
".",
"spriteSize",
")",
"{",
"particle",
".",
"spriteSize",
"=",
"this",
".",
"spriteSize",
".",
"get",
"(",
")",
";",
"}",
"if",
"(",
"this",
".",
"weight",
")",
"{",
"particle",
".",
"weight",
"=",
"this",
".",
"weight",
".",
"get",
"(",
")",
";",
"}",
"particle",
".",
"age",
"=",
"0",
";",
"out",
".",
"push",
"(",
"particle",
")",
";",
"}",
"}"
] |
Emitter number of particles and push them to a given particle list. Emmit number is defined by amount property
@param {Array.<clay.particle.Particle>} out
|
[
"Emitter",
"number",
"of",
"particles",
"and",
"push",
"them",
"to",
"a",
"given",
"particle",
"list",
".",
"Emmit",
"number",
"is",
"defined",
"by",
"amount",
"property"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L32704-L32736
|
|
6,927
|
pissang/claygl
|
dist/claygl.es.js
|
function() {
// Put all the particles back
for (var i = 0; i < this._particles.length; i++) {
var p = this._particles[i];
p.emitter.kill(p);
}
this._particles.length = 0;
this._elapsedTime = 0;
this._emitting = true;
}
|
javascript
|
function() {
// Put all the particles back
for (var i = 0; i < this._particles.length; i++) {
var p = this._particles[i];
p.emitter.kill(p);
}
this._particles.length = 0;
this._elapsedTime = 0;
this._emitting = true;
}
|
[
"function",
"(",
")",
"{",
"// Put all the particles back",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"_particles",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"p",
"=",
"this",
".",
"_particles",
"[",
"i",
"]",
";",
"p",
".",
"emitter",
".",
"kill",
"(",
"p",
")",
";",
"}",
"this",
".",
"_particles",
".",
"length",
"=",
"0",
";",
"this",
".",
"_elapsedTime",
"=",
"0",
";",
"this",
".",
"_emitting",
"=",
"true",
";",
"}"
] |
Reset the particle system.
|
[
"Reset",
"the",
"particle",
"system",
"."
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L32948-L32957
|
|
6,928
|
pissang/claygl
|
dist/claygl.es.js
|
function(ratio) {
this._texture.width = this.width * ratio;
this._texture.height = this.height * ratio;
this.downSampleRatio = ratio;
}
|
javascript
|
function(ratio) {
this._texture.width = this.width * ratio;
this._texture.height = this.height * ratio;
this.downSampleRatio = ratio;
}
|
[
"function",
"(",
"ratio",
")",
"{",
"this",
".",
"_texture",
".",
"width",
"=",
"this",
".",
"width",
"*",
"ratio",
";",
"this",
".",
"_texture",
".",
"height",
"=",
"this",
".",
"height",
"*",
"ratio",
";",
"this",
".",
"downSampleRatio",
"=",
"ratio",
";",
"}"
] |
Set picking presision
@param {number} ratio
|
[
"Set",
"picking",
"presision"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L33165-L33169
|
|
6,929
|
pissang/claygl
|
dist/claygl.es.js
|
function(scene, camera) {
var renderer = this.renderer;
if (renderer.getWidth() !== this.width || renderer.getHeight() !== this.height) {
this.resize(renderer.width, renderer.height);
}
this._frameBuffer.attach(this._texture);
this._frameBuffer.bind(renderer);
this._idOffset = this.lookupOffset;
this._setMaterial(scene);
renderer.render(scene, camera);
this._restoreMaterial();
this._frameBuffer.unbind(renderer);
}
|
javascript
|
function(scene, camera) {
var renderer = this.renderer;
if (renderer.getWidth() !== this.width || renderer.getHeight() !== this.height) {
this.resize(renderer.width, renderer.height);
}
this._frameBuffer.attach(this._texture);
this._frameBuffer.bind(renderer);
this._idOffset = this.lookupOffset;
this._setMaterial(scene);
renderer.render(scene, camera);
this._restoreMaterial();
this._frameBuffer.unbind(renderer);
}
|
[
"function",
"(",
"scene",
",",
"camera",
")",
"{",
"var",
"renderer",
"=",
"this",
".",
"renderer",
";",
"if",
"(",
"renderer",
".",
"getWidth",
"(",
")",
"!==",
"this",
".",
"width",
"||",
"renderer",
".",
"getHeight",
"(",
")",
"!==",
"this",
".",
"height",
")",
"{",
"this",
".",
"resize",
"(",
"renderer",
".",
"width",
",",
"renderer",
".",
"height",
")",
";",
"}",
"this",
".",
"_frameBuffer",
".",
"attach",
"(",
"this",
".",
"_texture",
")",
";",
"this",
".",
"_frameBuffer",
".",
"bind",
"(",
"renderer",
")",
";",
"this",
".",
"_idOffset",
"=",
"this",
".",
"lookupOffset",
";",
"this",
".",
"_setMaterial",
"(",
"scene",
")",
";",
"renderer",
".",
"render",
"(",
"scene",
",",
"camera",
")",
";",
"this",
".",
"_restoreMaterial",
"(",
")",
";",
"this",
".",
"_frameBuffer",
".",
"unbind",
"(",
"renderer",
")",
";",
"}"
] |
Update the picking framebuffer
@param {number} ratio
|
[
"Update",
"the",
"picking",
"framebuffer"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L33181-L33194
|
|
6,930
|
pissang/claygl
|
dist/claygl.es.js
|
function(x, y) {
var renderer = this.renderer;
var ratio = this.downSampleRatio;
x = Math.ceil(ratio * x);
y = Math.ceil(ratio * (this.height - y));
this._frameBuffer.bind(renderer);
var pixel = new Uint8Array(4);
var _gl = renderer.gl;
// TODO out of bounds ?
// preserveDrawingBuffer ?
_gl.readPixels(x, y, 1, 1, _gl.RGBA, _gl.UNSIGNED_BYTE, pixel);
this._frameBuffer.unbind(renderer);
// Skip interpolated pixel because of anti alias
if (pixel[3] === 255) {
var id = unpackID(pixel[0], pixel[1], pixel[2]);
if (id) {
var el = this._lookupTable[id - this.lookupOffset];
return el;
}
}
}
|
javascript
|
function(x, y) {
var renderer = this.renderer;
var ratio = this.downSampleRatio;
x = Math.ceil(ratio * x);
y = Math.ceil(ratio * (this.height - y));
this._frameBuffer.bind(renderer);
var pixel = new Uint8Array(4);
var _gl = renderer.gl;
// TODO out of bounds ?
// preserveDrawingBuffer ?
_gl.readPixels(x, y, 1, 1, _gl.RGBA, _gl.UNSIGNED_BYTE, pixel);
this._frameBuffer.unbind(renderer);
// Skip interpolated pixel because of anti alias
if (pixel[3] === 255) {
var id = unpackID(pixel[0], pixel[1], pixel[2]);
if (id) {
var el = this._lookupTable[id - this.lookupOffset];
return el;
}
}
}
|
[
"function",
"(",
"x",
",",
"y",
")",
"{",
"var",
"renderer",
"=",
"this",
".",
"renderer",
";",
"var",
"ratio",
"=",
"this",
".",
"downSampleRatio",
";",
"x",
"=",
"Math",
".",
"ceil",
"(",
"ratio",
"*",
"x",
")",
";",
"y",
"=",
"Math",
".",
"ceil",
"(",
"ratio",
"*",
"(",
"this",
".",
"height",
"-",
"y",
")",
")",
";",
"this",
".",
"_frameBuffer",
".",
"bind",
"(",
"renderer",
")",
";",
"var",
"pixel",
"=",
"new",
"Uint8Array",
"(",
"4",
")",
";",
"var",
"_gl",
"=",
"renderer",
".",
"gl",
";",
"// TODO out of bounds ?",
"// preserveDrawingBuffer ?",
"_gl",
".",
"readPixels",
"(",
"x",
",",
"y",
",",
"1",
",",
"1",
",",
"_gl",
".",
"RGBA",
",",
"_gl",
".",
"UNSIGNED_BYTE",
",",
"pixel",
")",
";",
"this",
".",
"_frameBuffer",
".",
"unbind",
"(",
"renderer",
")",
";",
"// Skip interpolated pixel because of anti alias",
"if",
"(",
"pixel",
"[",
"3",
"]",
"===",
"255",
")",
"{",
"var",
"id",
"=",
"unpackID",
"(",
"pixel",
"[",
"0",
"]",
",",
"pixel",
"[",
"1",
"]",
",",
"pixel",
"[",
"2",
"]",
")",
";",
"if",
"(",
"id",
")",
"{",
"var",
"el",
"=",
"this",
".",
"_lookupTable",
"[",
"id",
"-",
"this",
".",
"lookupOffset",
"]",
";",
"return",
"el",
";",
"}",
"}",
"}"
] |
Pick the object
@param {number} x Mouse position x
@param {number} y Mouse position y
@return {clay.Node}
|
[
"Pick",
"the",
"object"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L33231-L33253
|
|
6,931
|
pissang/claygl
|
dist/claygl.es.js
|
function (frameTime) {
var target = this.target;
var position = this.target.position;
var xAxis = target.localTransform.x.normalize();
var zAxis = target.localTransform.z.normalize();
if (this.verticalMoveLock) {
zAxis.y = 0;
zAxis.normalize();
}
var speed = this.speed * frameTime / 20;
if (this._moveForward) {
// Opposite direction of z
position.scaleAndAdd(zAxis, -speed);
}
if (this._moveBackward) {
position.scaleAndAdd(zAxis, speed);
}
if (this._moveLeft) {
position.scaleAndAdd(xAxis, -speed / 2);
}
if (this._moveRight) {
position.scaleAndAdd(xAxis, speed / 2);
}
target.rotateAround(target.position, this.up, -this._offsetPitch * frameTime * Math.PI / 360);
var xAxis = target.localTransform.x;
target.rotateAround(target.position, xAxis, -this._offsetRoll * frameTime * Math.PI / 360);
this._offsetRoll = this._offsetPitch = 0;
}
|
javascript
|
function (frameTime) {
var target = this.target;
var position = this.target.position;
var xAxis = target.localTransform.x.normalize();
var zAxis = target.localTransform.z.normalize();
if (this.verticalMoveLock) {
zAxis.y = 0;
zAxis.normalize();
}
var speed = this.speed * frameTime / 20;
if (this._moveForward) {
// Opposite direction of z
position.scaleAndAdd(zAxis, -speed);
}
if (this._moveBackward) {
position.scaleAndAdd(zAxis, speed);
}
if (this._moveLeft) {
position.scaleAndAdd(xAxis, -speed / 2);
}
if (this._moveRight) {
position.scaleAndAdd(xAxis, speed / 2);
}
target.rotateAround(target.position, this.up, -this._offsetPitch * frameTime * Math.PI / 360);
var xAxis = target.localTransform.x;
target.rotateAround(target.position, xAxis, -this._offsetRoll * frameTime * Math.PI / 360);
this._offsetRoll = this._offsetPitch = 0;
}
|
[
"function",
"(",
"frameTime",
")",
"{",
"var",
"target",
"=",
"this",
".",
"target",
";",
"var",
"position",
"=",
"this",
".",
"target",
".",
"position",
";",
"var",
"xAxis",
"=",
"target",
".",
"localTransform",
".",
"x",
".",
"normalize",
"(",
")",
";",
"var",
"zAxis",
"=",
"target",
".",
"localTransform",
".",
"z",
".",
"normalize",
"(",
")",
";",
"if",
"(",
"this",
".",
"verticalMoveLock",
")",
"{",
"zAxis",
".",
"y",
"=",
"0",
";",
"zAxis",
".",
"normalize",
"(",
")",
";",
"}",
"var",
"speed",
"=",
"this",
".",
"speed",
"*",
"frameTime",
"/",
"20",
";",
"if",
"(",
"this",
".",
"_moveForward",
")",
"{",
"// Opposite direction of z",
"position",
".",
"scaleAndAdd",
"(",
"zAxis",
",",
"-",
"speed",
")",
";",
"}",
"if",
"(",
"this",
".",
"_moveBackward",
")",
"{",
"position",
".",
"scaleAndAdd",
"(",
"zAxis",
",",
"speed",
")",
";",
"}",
"if",
"(",
"this",
".",
"_moveLeft",
")",
"{",
"position",
".",
"scaleAndAdd",
"(",
"xAxis",
",",
"-",
"speed",
"/",
"2",
")",
";",
"}",
"if",
"(",
"this",
".",
"_moveRight",
")",
"{",
"position",
".",
"scaleAndAdd",
"(",
"xAxis",
",",
"speed",
"/",
"2",
")",
";",
"}",
"target",
".",
"rotateAround",
"(",
"target",
".",
"position",
",",
"this",
".",
"up",
",",
"-",
"this",
".",
"_offsetPitch",
"*",
"frameTime",
"*",
"Math",
".",
"PI",
"/",
"360",
")",
";",
"var",
"xAxis",
"=",
"target",
".",
"localTransform",
".",
"x",
";",
"target",
".",
"rotateAround",
"(",
"target",
".",
"position",
",",
"xAxis",
",",
"-",
"this",
".",
"_offsetRoll",
"*",
"frameTime",
"*",
"Math",
".",
"PI",
"/",
"360",
")",
";",
"this",
".",
"_offsetRoll",
"=",
"this",
".",
"_offsetPitch",
"=",
"0",
";",
"}"
] |
Control update. Should be invoked every frame
@param {number} frameTime Frame time
|
[
"Control",
"update",
".",
"Should",
"be",
"invoked",
"every",
"frame"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L33421-L33454
|
|
6,932
|
pissang/claygl
|
dist/claygl.es.js
|
function() {
/**
* When user begins to interact with connected gamepad:
*
* @see https://w3c.github.io/gamepad/#dom-gamepadevent
*/
vendor.addEventListener(window, 'gamepadconnected', this._checkGamepadCompatibility);
if (this.timeline) {
this.timeline.on('frame', this.update);
}
vendor.addEventListener(window, 'gamepaddisconnected', this._disconnectGamepad);
}
|
javascript
|
function() {
/**
* When user begins to interact with connected gamepad:
*
* @see https://w3c.github.io/gamepad/#dom-gamepadevent
*/
vendor.addEventListener(window, 'gamepadconnected', this._checkGamepadCompatibility);
if (this.timeline) {
this.timeline.on('frame', this.update);
}
vendor.addEventListener(window, 'gamepaddisconnected', this._disconnectGamepad);
}
|
[
"function",
"(",
")",
"{",
"/**\n * When user begins to interact with connected gamepad:\n *\n * @see https://w3c.github.io/gamepad/#dom-gamepadevent\n */",
"vendor",
".",
"addEventListener",
"(",
"window",
",",
"'gamepadconnected'",
",",
"this",
".",
"_checkGamepadCompatibility",
")",
";",
"if",
"(",
"this",
".",
"timeline",
")",
"{",
"this",
".",
"timeline",
".",
"on",
"(",
"'frame'",
",",
"this",
".",
"update",
")",
";",
"}",
"vendor",
".",
"addEventListener",
"(",
"window",
",",
"'gamepaddisconnected'",
",",
"this",
".",
"_disconnectGamepad",
")",
";",
"}"
] |
Init. control.
|
[
"Init",
".",
"control",
"."
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L33639-L33654
|
|
6,933
|
pissang/claygl
|
dist/claygl.es.js
|
function() {
vendor.removeEventListener(window, 'gamepadconnected', this._checkGamepadCompatibility);
if (this.timeline) {
this.timeline.off('frame', this.update);
}
vendor.removeEventListener(window, 'gamepaddisconnected', this._disconnectGamepad);
}
|
javascript
|
function() {
vendor.removeEventListener(window, 'gamepadconnected', this._checkGamepadCompatibility);
if (this.timeline) {
this.timeline.off('frame', this.update);
}
vendor.removeEventListener(window, 'gamepaddisconnected', this._disconnectGamepad);
}
|
[
"function",
"(",
")",
"{",
"vendor",
".",
"removeEventListener",
"(",
"window",
",",
"'gamepadconnected'",
",",
"this",
".",
"_checkGamepadCompatibility",
")",
";",
"if",
"(",
"this",
".",
"timeline",
")",
"{",
"this",
".",
"timeline",
".",
"off",
"(",
"'frame'",
",",
"this",
".",
"update",
")",
";",
"}",
"vendor",
".",
"removeEventListener",
"(",
"window",
",",
"'gamepaddisconnected'",
",",
"this",
".",
"_disconnectGamepad",
")",
";",
"}"
] |
Dispose control.
|
[
"Dispose",
"control",
"."
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L33659-L33669
|
|
6,934
|
pissang/claygl
|
dist/claygl.es.js
|
function (frameTime) {
if (!this._standardGamepadAvailable) {
return;
}
this._scanPressedGamepadButtons();
this._scanInclinedGamepadAxes();
// Update target depending on user input.
var target = this.target;
var position = this.target.position;
var xAxis = target.localTransform.x.normalize();
var zAxis = target.localTransform.z.normalize();
var moveSpeed = this.moveSpeed * frameTime / 20;
if (this._moveForward) {
// Opposite direction of z.
position.scaleAndAdd(zAxis, -moveSpeed);
}
if (this._moveBackward) {
position.scaleAndAdd(zAxis, moveSpeed);
}
if (this._moveLeft) {
position.scaleAndAdd(xAxis, -moveSpeed);
}
if (this._moveRight) {
position.scaleAndAdd(xAxis, moveSpeed);
}
target.rotateAround(target.position, this.up, -this._offsetPitch * frameTime * Math.PI / 360);
var xAxis = target.localTransform.x;
target.rotateAround(target.position, xAxis, -this._offsetRoll * frameTime * Math.PI / 360);
/*
* If necessary: trigger `update` event.
* XXX This can economize rendering OPs.
*/
if (this._moveForward === true || this._moveBackward === true || this._moveLeft === true
|| this._moveRight === true || this._offsetPitch !== 0 || this._offsetRoll !== 0)
{
this.trigger('update');
}
// Reset values to avoid lost of control.
this._moveForward = this._moveBackward = this._moveLeft = this._moveRight = false;
this._offsetPitch = this._offsetRoll = 0;
}
|
javascript
|
function (frameTime) {
if (!this._standardGamepadAvailable) {
return;
}
this._scanPressedGamepadButtons();
this._scanInclinedGamepadAxes();
// Update target depending on user input.
var target = this.target;
var position = this.target.position;
var xAxis = target.localTransform.x.normalize();
var zAxis = target.localTransform.z.normalize();
var moveSpeed = this.moveSpeed * frameTime / 20;
if (this._moveForward) {
// Opposite direction of z.
position.scaleAndAdd(zAxis, -moveSpeed);
}
if (this._moveBackward) {
position.scaleAndAdd(zAxis, moveSpeed);
}
if (this._moveLeft) {
position.scaleAndAdd(xAxis, -moveSpeed);
}
if (this._moveRight) {
position.scaleAndAdd(xAxis, moveSpeed);
}
target.rotateAround(target.position, this.up, -this._offsetPitch * frameTime * Math.PI / 360);
var xAxis = target.localTransform.x;
target.rotateAround(target.position, xAxis, -this._offsetRoll * frameTime * Math.PI / 360);
/*
* If necessary: trigger `update` event.
* XXX This can economize rendering OPs.
*/
if (this._moveForward === true || this._moveBackward === true || this._moveLeft === true
|| this._moveRight === true || this._offsetPitch !== 0 || this._offsetRoll !== 0)
{
this.trigger('update');
}
// Reset values to avoid lost of control.
this._moveForward = this._moveBackward = this._moveLeft = this._moveRight = false;
this._offsetPitch = this._offsetRoll = 0;
}
|
[
"function",
"(",
"frameTime",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_standardGamepadAvailable",
")",
"{",
"return",
";",
"}",
"this",
".",
"_scanPressedGamepadButtons",
"(",
")",
";",
"this",
".",
"_scanInclinedGamepadAxes",
"(",
")",
";",
"// Update target depending on user input.",
"var",
"target",
"=",
"this",
".",
"target",
";",
"var",
"position",
"=",
"this",
".",
"target",
".",
"position",
";",
"var",
"xAxis",
"=",
"target",
".",
"localTransform",
".",
"x",
".",
"normalize",
"(",
")",
";",
"var",
"zAxis",
"=",
"target",
".",
"localTransform",
".",
"z",
".",
"normalize",
"(",
")",
";",
"var",
"moveSpeed",
"=",
"this",
".",
"moveSpeed",
"*",
"frameTime",
"/",
"20",
";",
"if",
"(",
"this",
".",
"_moveForward",
")",
"{",
"// Opposite direction of z.",
"position",
".",
"scaleAndAdd",
"(",
"zAxis",
",",
"-",
"moveSpeed",
")",
";",
"}",
"if",
"(",
"this",
".",
"_moveBackward",
")",
"{",
"position",
".",
"scaleAndAdd",
"(",
"zAxis",
",",
"moveSpeed",
")",
";",
"}",
"if",
"(",
"this",
".",
"_moveLeft",
")",
"{",
"position",
".",
"scaleAndAdd",
"(",
"xAxis",
",",
"-",
"moveSpeed",
")",
";",
"}",
"if",
"(",
"this",
".",
"_moveRight",
")",
"{",
"position",
".",
"scaleAndAdd",
"(",
"xAxis",
",",
"moveSpeed",
")",
";",
"}",
"target",
".",
"rotateAround",
"(",
"target",
".",
"position",
",",
"this",
".",
"up",
",",
"-",
"this",
".",
"_offsetPitch",
"*",
"frameTime",
"*",
"Math",
".",
"PI",
"/",
"360",
")",
";",
"var",
"xAxis",
"=",
"target",
".",
"localTransform",
".",
"x",
";",
"target",
".",
"rotateAround",
"(",
"target",
".",
"position",
",",
"xAxis",
",",
"-",
"this",
".",
"_offsetRoll",
"*",
"frameTime",
"*",
"Math",
".",
"PI",
"/",
"360",
")",
";",
"/*\n * If necessary: trigger `update` event.\n * XXX This can economize rendering OPs.\n */",
"if",
"(",
"this",
".",
"_moveForward",
"===",
"true",
"||",
"this",
".",
"_moveBackward",
"===",
"true",
"||",
"this",
".",
"_moveLeft",
"===",
"true",
"||",
"this",
".",
"_moveRight",
"===",
"true",
"||",
"this",
".",
"_offsetPitch",
"!==",
"0",
"||",
"this",
".",
"_offsetRoll",
"!==",
"0",
")",
"{",
"this",
".",
"trigger",
"(",
"'update'",
")",
";",
"}",
"// Reset values to avoid lost of control.",
"this",
".",
"_moveForward",
"=",
"this",
".",
"_moveBackward",
"=",
"this",
".",
"_moveLeft",
"=",
"this",
".",
"_moveRight",
"=",
"false",
";",
"this",
".",
"_offsetPitch",
"=",
"this",
".",
"_offsetRoll",
"=",
"0",
";",
"}"
] |
Control's update. Should be invoked every frame.
@param {number} frameTime Frame time.
|
[
"Control",
"s",
"update",
".",
"Should",
"be",
"invoked",
"every",
"frame",
"."
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L33676-L33728
|
|
6,935
|
pissang/claygl
|
dist/claygl.es.js
|
function () {
var dom = this.domElement;
vendor.addEventListener(dom, 'touchstart', this._mouseDownHandler);
vendor.addEventListener(dom, 'mousedown', this._mouseDownHandler);
vendor.addEventListener(dom, 'wheel', this._mouseWheelHandler);
if (this.timeline) {
this.timeline.on('frame', this.update, this);
}
if (this.target) {
this.decomposeTransform();
}
}
|
javascript
|
function () {
var dom = this.domElement;
vendor.addEventListener(dom, 'touchstart', this._mouseDownHandler);
vendor.addEventListener(dom, 'mousedown', this._mouseDownHandler);
vendor.addEventListener(dom, 'wheel', this._mouseWheelHandler);
if (this.timeline) {
this.timeline.on('frame', this.update, this);
}
if (this.target) {
this.decomposeTransform();
}
}
|
[
"function",
"(",
")",
"{",
"var",
"dom",
"=",
"this",
".",
"domElement",
";",
"vendor",
".",
"addEventListener",
"(",
"dom",
",",
"'touchstart'",
",",
"this",
".",
"_mouseDownHandler",
")",
";",
"vendor",
".",
"addEventListener",
"(",
"dom",
",",
"'mousedown'",
",",
"this",
".",
"_mouseDownHandler",
")",
";",
"vendor",
".",
"addEventListener",
"(",
"dom",
",",
"'wheel'",
",",
"this",
".",
"_mouseWheelHandler",
")",
";",
"if",
"(",
"this",
".",
"timeline",
")",
"{",
"this",
".",
"timeline",
".",
"on",
"(",
"'frame'",
",",
"this",
".",
"update",
",",
"this",
")",
";",
"}",
"if",
"(",
"this",
".",
"target",
")",
"{",
"this",
".",
"decomposeTransform",
"(",
")",
";",
"}",
"}"
] |
Initialize.
Mouse event binding
|
[
"Initialize",
".",
"Mouse",
"event",
"binding"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L34260-L34274
|
|
6,936
|
pissang/claygl
|
dist/claygl.es.js
|
function () {
var dom = this.domElement;
vendor.removeEventListener(dom, 'touchstart', this._mouseDownHandler);
vendor.removeEventListener(dom, 'touchmove', this._mouseMoveHandler);
vendor.removeEventListener(dom, 'touchend', this._mouseUpHandler);
vendor.removeEventListener(dom, 'mousedown', this._mouseDownHandler);
vendor.removeEventListener(dom, 'mousemove', this._mouseMoveHandler);
vendor.removeEventListener(dom, 'mouseup', this._mouseUpHandler);
vendor.removeEventListener(dom, 'wheel', this._mouseWheelHandler);
vendor.removeEventListener(dom, 'mouseout', this._mouseUpHandler);
if (this.timeline) {
this.timeline.off('frame', this.update);
}
this.stopAllAnimation();
}
|
javascript
|
function () {
var dom = this.domElement;
vendor.removeEventListener(dom, 'touchstart', this._mouseDownHandler);
vendor.removeEventListener(dom, 'touchmove', this._mouseMoveHandler);
vendor.removeEventListener(dom, 'touchend', this._mouseUpHandler);
vendor.removeEventListener(dom, 'mousedown', this._mouseDownHandler);
vendor.removeEventListener(dom, 'mousemove', this._mouseMoveHandler);
vendor.removeEventListener(dom, 'mouseup', this._mouseUpHandler);
vendor.removeEventListener(dom, 'wheel', this._mouseWheelHandler);
vendor.removeEventListener(dom, 'mouseout', this._mouseUpHandler);
if (this.timeline) {
this.timeline.off('frame', this.update);
}
this.stopAllAnimation();
}
|
[
"function",
"(",
")",
"{",
"var",
"dom",
"=",
"this",
".",
"domElement",
";",
"vendor",
".",
"removeEventListener",
"(",
"dom",
",",
"'touchstart'",
",",
"this",
".",
"_mouseDownHandler",
")",
";",
"vendor",
".",
"removeEventListener",
"(",
"dom",
",",
"'touchmove'",
",",
"this",
".",
"_mouseMoveHandler",
")",
";",
"vendor",
".",
"removeEventListener",
"(",
"dom",
",",
"'touchend'",
",",
"this",
".",
"_mouseUpHandler",
")",
";",
"vendor",
".",
"removeEventListener",
"(",
"dom",
",",
"'mousedown'",
",",
"this",
".",
"_mouseDownHandler",
")",
";",
"vendor",
".",
"removeEventListener",
"(",
"dom",
",",
"'mousemove'",
",",
"this",
".",
"_mouseMoveHandler",
")",
";",
"vendor",
".",
"removeEventListener",
"(",
"dom",
",",
"'mouseup'",
",",
"this",
".",
"_mouseUpHandler",
")",
";",
"vendor",
".",
"removeEventListener",
"(",
"dom",
",",
"'wheel'",
",",
"this",
".",
"_mouseWheelHandler",
")",
";",
"vendor",
".",
"removeEventListener",
"(",
"dom",
",",
"'mouseout'",
",",
"this",
".",
"_mouseUpHandler",
")",
";",
"if",
"(",
"this",
".",
"timeline",
")",
"{",
"this",
".",
"timeline",
".",
"off",
"(",
"'frame'",
",",
"this",
".",
"update",
")",
";",
"}",
"this",
".",
"stopAllAnimation",
"(",
")",
";",
"}"
] |
Dispose.
Mouse event unbinding
|
[
"Dispose",
".",
"Mouse",
"event",
"unbinding"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L34280-L34297
|
|
6,937
|
pissang/claygl
|
dist/claygl.es.js
|
function (alpha) {
alpha = Math.max(Math.min(this.maxAlpha, alpha), this.minAlpha);
this._theta = alpha / 180 * Math.PI;
this._needsUpdate = true;
}
|
javascript
|
function (alpha) {
alpha = Math.max(Math.min(this.maxAlpha, alpha), this.minAlpha);
this._theta = alpha / 180 * Math.PI;
this._needsUpdate = true;
}
|
[
"function",
"(",
"alpha",
")",
"{",
"alpha",
"=",
"Math",
".",
"max",
"(",
"Math",
".",
"min",
"(",
"this",
".",
"maxAlpha",
",",
"alpha",
")",
",",
"this",
".",
"minAlpha",
")",
";",
"this",
".",
"_theta",
"=",
"alpha",
"/",
"180",
"*",
"Math",
".",
"PI",
";",
"this",
".",
"_needsUpdate",
"=",
"true",
";",
"}"
] |
Set alpha rotation angle
@param {number} alpha
|
[
"Set",
"alpha",
"rotation",
"angle"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L34365-L34370
|
|
6,938
|
pissang/claygl
|
dist/claygl.es.js
|
function (beta) {
beta = Math.max(Math.min(this.maxBeta, beta), this.minBeta);
this._phi = -beta / 180 * Math.PI;
this._needsUpdate = true;
}
|
javascript
|
function (beta) {
beta = Math.max(Math.min(this.maxBeta, beta), this.minBeta);
this._phi = -beta / 180 * Math.PI;
this._needsUpdate = true;
}
|
[
"function",
"(",
"beta",
")",
"{",
"beta",
"=",
"Math",
".",
"max",
"(",
"Math",
".",
"min",
"(",
"this",
".",
"maxBeta",
",",
"beta",
")",
",",
"this",
".",
"minBeta",
")",
";",
"this",
".",
"_phi",
"=",
"-",
"beta",
"/",
"180",
"*",
"Math",
".",
"PI",
";",
"this",
".",
"_needsUpdate",
"=",
"true",
";",
"}"
] |
Set beta rotation angle
@param {number} beta
|
[
"Set",
"beta",
"rotation",
"angle"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L34376-L34381
|
|
6,939
|
pissang/claygl
|
dist/claygl.es.js
|
function () {
for (var i = 0; i < this._animators.length; i++) {
this._animators[i].stop();
}
this._animators.length = 0;
}
|
javascript
|
function () {
for (var i = 0; i < this._animators.length; i++) {
this._animators[i].stop();
}
this._animators.length = 0;
}
|
[
"function",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"_animators",
".",
"length",
";",
"i",
"++",
")",
"{",
"this",
".",
"_animators",
"[",
"i",
"]",
".",
"stop",
"(",
")",
";",
"}",
"this",
".",
"_animators",
".",
"length",
"=",
"0",
";",
"}"
] |
Stop all animations
|
[
"Stop",
"all",
"animations"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L34500-L34505
|
|
6,940
|
pissang/claygl
|
dist/claygl.es.js
|
function (deltaTime) {
deltaTime = deltaTime || 16;
if (this._rotating) {
var radian = (this.autoRotateDirection === 'cw' ? 1 : -1)
* this.autoRotateSpeed / 180 * Math.PI;
this._phi -= radian * deltaTime / 1000;
this._needsUpdate = true;
}
else if (this._rotateVelocity.len() > 0) {
this._needsUpdate = true;
}
if (Math.abs(this._zoomSpeed) > 0.01 || this._panVelocity.len() > 0) {
this._needsUpdate = true;
}
if (!this._needsUpdate) {
return;
}
// Fixed deltaTime
this._updateDistanceOrSize(Math.min(deltaTime, 50));
this._updatePan(Math.min(deltaTime, 50));
this._updateRotate(Math.min(deltaTime, 50));
this._updateTransform();
this.target.update();
this.trigger('update');
this._needsUpdate = false;
}
|
javascript
|
function (deltaTime) {
deltaTime = deltaTime || 16;
if (this._rotating) {
var radian = (this.autoRotateDirection === 'cw' ? 1 : -1)
* this.autoRotateSpeed / 180 * Math.PI;
this._phi -= radian * deltaTime / 1000;
this._needsUpdate = true;
}
else if (this._rotateVelocity.len() > 0) {
this._needsUpdate = true;
}
if (Math.abs(this._zoomSpeed) > 0.01 || this._panVelocity.len() > 0) {
this._needsUpdate = true;
}
if (!this._needsUpdate) {
return;
}
// Fixed deltaTime
this._updateDistanceOrSize(Math.min(deltaTime, 50));
this._updatePan(Math.min(deltaTime, 50));
this._updateRotate(Math.min(deltaTime, 50));
this._updateTransform();
this.target.update();
this.trigger('update');
this._needsUpdate = false;
}
|
[
"function",
"(",
"deltaTime",
")",
"{",
"deltaTime",
"=",
"deltaTime",
"||",
"16",
";",
"if",
"(",
"this",
".",
"_rotating",
")",
"{",
"var",
"radian",
"=",
"(",
"this",
".",
"autoRotateDirection",
"===",
"'cw'",
"?",
"1",
":",
"-",
"1",
")",
"*",
"this",
".",
"autoRotateSpeed",
"/",
"180",
"*",
"Math",
".",
"PI",
";",
"this",
".",
"_phi",
"-=",
"radian",
"*",
"deltaTime",
"/",
"1000",
";",
"this",
".",
"_needsUpdate",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"this",
".",
"_rotateVelocity",
".",
"len",
"(",
")",
">",
"0",
")",
"{",
"this",
".",
"_needsUpdate",
"=",
"true",
";",
"}",
"if",
"(",
"Math",
".",
"abs",
"(",
"this",
".",
"_zoomSpeed",
")",
">",
"0.01",
"||",
"this",
".",
"_panVelocity",
".",
"len",
"(",
")",
">",
"0",
")",
"{",
"this",
".",
"_needsUpdate",
"=",
"true",
";",
"}",
"if",
"(",
"!",
"this",
".",
"_needsUpdate",
")",
"{",
"return",
";",
"}",
"// Fixed deltaTime",
"this",
".",
"_updateDistanceOrSize",
"(",
"Math",
".",
"min",
"(",
"deltaTime",
",",
"50",
")",
")",
";",
"this",
".",
"_updatePan",
"(",
"Math",
".",
"min",
"(",
"deltaTime",
",",
"50",
")",
")",
";",
"this",
".",
"_updateRotate",
"(",
"Math",
".",
"min",
"(",
"deltaTime",
",",
"50",
")",
")",
";",
"this",
".",
"_updateTransform",
"(",
")",
";",
"this",
".",
"target",
".",
"update",
"(",
")",
";",
"this",
".",
"trigger",
"(",
"'update'",
")",
";",
"this",
".",
"_needsUpdate",
"=",
"false",
";",
"}"
] |
Call update each frame
@param {number} deltaTime Frame time
|
[
"Call",
"update",
"each",
"frame"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L34514-L34549
|
|
6,941
|
pissang/claygl
|
dist/claygl.es.js
|
function (geometry, shallow) {
if (!geometry) {
return null;
}
var data = {
metadata : util$1.extend({}, META)
};
//transferable buffers
var buffers = [];
//dynamic
data.dynamic = geometry.dynamic;
//bounding box
if (geometry.boundingBox) {
data.boundingBox = {
min : geometry.boundingBox.min.toArray(),
max : geometry.boundingBox.max.toArray()
};
}
//indices
if (geometry.indices && geometry.indices.length > 0) {
data.indices = copyIfNecessary(geometry.indices, shallow);
buffers.push(data.indices.buffer);
}
//attributes
data.attributes = {};
for (var p in geometry.attributes) {
if (geometry.attributes.hasOwnProperty(p)) {
var attr = geometry.attributes[p];
//ignore empty attributes
if (attr && attr.value && attr.value.length > 0) {
attr = data.attributes[p] = copyAttribute(attr, shallow);
buffers.push(attr.value.buffer);
}
}
}
return {
data : data,
buffers : buffers
};
}
|
javascript
|
function (geometry, shallow) {
if (!geometry) {
return null;
}
var data = {
metadata : util$1.extend({}, META)
};
//transferable buffers
var buffers = [];
//dynamic
data.dynamic = geometry.dynamic;
//bounding box
if (geometry.boundingBox) {
data.boundingBox = {
min : geometry.boundingBox.min.toArray(),
max : geometry.boundingBox.max.toArray()
};
}
//indices
if (geometry.indices && geometry.indices.length > 0) {
data.indices = copyIfNecessary(geometry.indices, shallow);
buffers.push(data.indices.buffer);
}
//attributes
data.attributes = {};
for (var p in geometry.attributes) {
if (geometry.attributes.hasOwnProperty(p)) {
var attr = geometry.attributes[p];
//ignore empty attributes
if (attr && attr.value && attr.value.length > 0) {
attr = data.attributes[p] = copyAttribute(attr, shallow);
buffers.push(attr.value.buffer);
}
}
}
return {
data : data,
buffers : buffers
};
}
|
[
"function",
"(",
"geometry",
",",
"shallow",
")",
"{",
"if",
"(",
"!",
"geometry",
")",
"{",
"return",
"null",
";",
"}",
"var",
"data",
"=",
"{",
"metadata",
":",
"util$1",
".",
"extend",
"(",
"{",
"}",
",",
"META",
")",
"}",
";",
"//transferable buffers",
"var",
"buffers",
"=",
"[",
"]",
";",
"//dynamic",
"data",
".",
"dynamic",
"=",
"geometry",
".",
"dynamic",
";",
"//bounding box",
"if",
"(",
"geometry",
".",
"boundingBox",
")",
"{",
"data",
".",
"boundingBox",
"=",
"{",
"min",
":",
"geometry",
".",
"boundingBox",
".",
"min",
".",
"toArray",
"(",
")",
",",
"max",
":",
"geometry",
".",
"boundingBox",
".",
"max",
".",
"toArray",
"(",
")",
"}",
";",
"}",
"//indices",
"if",
"(",
"geometry",
".",
"indices",
"&&",
"geometry",
".",
"indices",
".",
"length",
">",
"0",
")",
"{",
"data",
".",
"indices",
"=",
"copyIfNecessary",
"(",
"geometry",
".",
"indices",
",",
"shallow",
")",
";",
"buffers",
".",
"push",
"(",
"data",
".",
"indices",
".",
"buffer",
")",
";",
"}",
"//attributes",
"data",
".",
"attributes",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"p",
"in",
"geometry",
".",
"attributes",
")",
"{",
"if",
"(",
"geometry",
".",
"attributes",
".",
"hasOwnProperty",
"(",
"p",
")",
")",
"{",
"var",
"attr",
"=",
"geometry",
".",
"attributes",
"[",
"p",
"]",
";",
"//ignore empty attributes",
"if",
"(",
"attr",
"&&",
"attr",
".",
"value",
"&&",
"attr",
".",
"value",
".",
"length",
">",
"0",
")",
"{",
"attr",
"=",
"data",
".",
"attributes",
"[",
"p",
"]",
"=",
"copyAttribute",
"(",
"attr",
",",
"shallow",
")",
";",
"buffers",
".",
"push",
"(",
"attr",
".",
"value",
".",
"buffer",
")",
";",
"}",
"}",
"}",
"return",
"{",
"data",
":",
"data",
",",
"buffers",
":",
"buffers",
"}",
";",
"}"
] |
Convert geometry to a object containing transferable data
@param {Geometry} geometry geometry
@param {Boolean} shallow whether shallow copy
@returns {Object} { data : data, buffers : buffers }, buffers is the transferable list
|
[
"Convert",
"geometry",
"to",
"a",
"object",
"containing",
"transferable",
"data"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L35242-L35286
|
|
6,942
|
pissang/claygl
|
dist/claygl.es.js
|
function (object) {
if (!object) {
return null;
}
if (object.data && object.buffers) {
return transferableUtil.toGeometry(object.data);
}
if (!object.metadata || object.metadata.generator !== META.generator) {
throw new Error('[util.transferable.toGeometry] the object is not generated by util.transferable.');
}
//basic options
var options = {
dynamic : object.dynamic,
indices : object.indices
};
if (object.boundingBox) {
var min = new Vector3().setArray(object.boundingBox.min);
var max = new Vector3().setArray(object.boundingBox.max);
options.boundingBox = new BoundingBox(min, max);
}
var geometry = new Geometry(options);
//attributes
for (var p in object.attributes) {
if (object.attributes.hasOwnProperty(p)) {
var attr = object.attributes[p];
geometry.attributes[p] = new Geometry.Attribute(attr.name, attr.type, attr.size, attr.semantic);
geometry.attributes[p].value = attr.value;
}
}
return geometry;
}
|
javascript
|
function (object) {
if (!object) {
return null;
}
if (object.data && object.buffers) {
return transferableUtil.toGeometry(object.data);
}
if (!object.metadata || object.metadata.generator !== META.generator) {
throw new Error('[util.transferable.toGeometry] the object is not generated by util.transferable.');
}
//basic options
var options = {
dynamic : object.dynamic,
indices : object.indices
};
if (object.boundingBox) {
var min = new Vector3().setArray(object.boundingBox.min);
var max = new Vector3().setArray(object.boundingBox.max);
options.boundingBox = new BoundingBox(min, max);
}
var geometry = new Geometry(options);
//attributes
for (var p in object.attributes) {
if (object.attributes.hasOwnProperty(p)) {
var attr = object.attributes[p];
geometry.attributes[p] = new Geometry.Attribute(attr.name, attr.type, attr.size, attr.semantic);
geometry.attributes[p].value = attr.value;
}
}
return geometry;
}
|
[
"function",
"(",
"object",
")",
"{",
"if",
"(",
"!",
"object",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"object",
".",
"data",
"&&",
"object",
".",
"buffers",
")",
"{",
"return",
"transferableUtil",
".",
"toGeometry",
"(",
"object",
".",
"data",
")",
";",
"}",
"if",
"(",
"!",
"object",
".",
"metadata",
"||",
"object",
".",
"metadata",
".",
"generator",
"!==",
"META",
".",
"generator",
")",
"{",
"throw",
"new",
"Error",
"(",
"'[util.transferable.toGeometry] the object is not generated by util.transferable.'",
")",
";",
"}",
"//basic options",
"var",
"options",
"=",
"{",
"dynamic",
":",
"object",
".",
"dynamic",
",",
"indices",
":",
"object",
".",
"indices",
"}",
";",
"if",
"(",
"object",
".",
"boundingBox",
")",
"{",
"var",
"min",
"=",
"new",
"Vector3",
"(",
")",
".",
"setArray",
"(",
"object",
".",
"boundingBox",
".",
"min",
")",
";",
"var",
"max",
"=",
"new",
"Vector3",
"(",
")",
".",
"setArray",
"(",
"object",
".",
"boundingBox",
".",
"max",
")",
";",
"options",
".",
"boundingBox",
"=",
"new",
"BoundingBox",
"(",
"min",
",",
"max",
")",
";",
"}",
"var",
"geometry",
"=",
"new",
"Geometry",
"(",
"options",
")",
";",
"//attributes",
"for",
"(",
"var",
"p",
"in",
"object",
".",
"attributes",
")",
"{",
"if",
"(",
"object",
".",
"attributes",
".",
"hasOwnProperty",
"(",
"p",
")",
")",
"{",
"var",
"attr",
"=",
"object",
".",
"attributes",
"[",
"p",
"]",
";",
"geometry",
".",
"attributes",
"[",
"p",
"]",
"=",
"new",
"Geometry",
".",
"Attribute",
"(",
"attr",
".",
"name",
",",
"attr",
".",
"type",
",",
"attr",
".",
"size",
",",
"attr",
".",
"semantic",
")",
";",
"geometry",
".",
"attributes",
"[",
"p",
"]",
".",
"value",
"=",
"attr",
".",
"value",
";",
"}",
"}",
"return",
"geometry",
";",
"}"
] |
Reproduce a geometry from object generated by toObject
@param {Object} object object generated by toObject
@returns {Geometry} geometry
|
[
"Reproduce",
"a",
"geometry",
"from",
"object",
"generated",
"by",
"toObject"
] |
b157bb50cf8c725fa20f90ebb55481352777f0a7
|
https://github.com/pissang/claygl/blob/b157bb50cf8c725fa20f90ebb55481352777f0a7/dist/claygl.es.js#L35293-L35328
|
|
6,943
|
webslides/WebSlides
|
src/js/utils/custom-event.js
|
canIuseNativeCustom
|
function canIuseNativeCustom() {
try {
const p = new NativeCustomEvent('t', {
detail: {
a: 'b'
}
});
return 't' === p.type && 'b' === p.detail.a;
} catch (e) { }
/* istanbul ignore next: hard to reproduce on test environment */
return false;
}
|
javascript
|
function canIuseNativeCustom() {
try {
const p = new NativeCustomEvent('t', {
detail: {
a: 'b'
}
});
return 't' === p.type && 'b' === p.detail.a;
} catch (e) { }
/* istanbul ignore next: hard to reproduce on test environment */
return false;
}
|
[
"function",
"canIuseNativeCustom",
"(",
")",
"{",
"try",
"{",
"const",
"p",
"=",
"new",
"NativeCustomEvent",
"(",
"'t'",
",",
"{",
"detail",
":",
"{",
"a",
":",
"'b'",
"}",
"}",
")",
";",
"return",
"'t'",
"===",
"p",
".",
"type",
"&&",
"'b'",
"===",
"p",
".",
"detail",
".",
"a",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"/* istanbul ignore next: hard to reproduce on test environment */",
"return",
"false",
";",
"}"
] |
Check for the usage of native support for CustomEvents which is lacking
completely on IE.
@return {boolean} Whether it can be used or not.
|
[
"Check",
"for",
"the",
"usage",
"of",
"native",
"support",
"for",
"CustomEvents",
"which",
"is",
"lacking",
"completely",
"on",
"IE",
"."
] |
fb5208218f15eb341d0aab64d86ba67a221aced3
|
https://github.com/webslides/WebSlides/blob/fb5208218f15eb341d0aab64d86ba67a221aced3/src/js/utils/custom-event.js#L8-L20
|
6,944
|
webslides/WebSlides
|
src/js/utils/custom-event.js
|
CustomEvent
|
function CustomEvent(type, params) {
const e = document.createEvent('CustomEvent');
if (params) {
e.initCustomEvent(type, params.bubbles, params.cancelable, params.detail);
} else {
e.initCustomEvent(type, false, false, undefined);
}
return e;
}
|
javascript
|
function CustomEvent(type, params) {
const e = document.createEvent('CustomEvent');
if (params) {
e.initCustomEvent(type, params.bubbles, params.cancelable, params.detail);
} else {
e.initCustomEvent(type, false, false, undefined);
}
return e;
}
|
[
"function",
"CustomEvent",
"(",
"type",
",",
"params",
")",
"{",
"const",
"e",
"=",
"document",
".",
"createEvent",
"(",
"'CustomEvent'",
")",
";",
"if",
"(",
"params",
")",
"{",
"e",
".",
"initCustomEvent",
"(",
"type",
",",
"params",
".",
"bubbles",
",",
"params",
".",
"cancelable",
",",
"params",
".",
"detail",
")",
";",
"}",
"else",
"{",
"e",
".",
"initCustomEvent",
"(",
"type",
",",
"false",
",",
"false",
",",
"undefined",
")",
";",
"}",
"return",
"e",
";",
"}"
] |
Lousy polyfill for the Custom Event constructor for IE.
@param {!string} type The type of the event.
@param {?Object} params Additional information for the event.
@return {Event}
@constructor
/* istanbul ignore next: hard to reproduce on test environment
|
[
"Lousy",
"polyfill",
"for",
"the",
"Custom",
"Event",
"constructor",
"for",
"IE",
"."
] |
fb5208218f15eb341d0aab64d86ba67a221aced3
|
https://github.com/webslides/WebSlides/blob/fb5208218f15eb341d0aab64d86ba67a221aced3/src/js/utils/custom-event.js#L30-L40
|
6,945
|
libp2p/js-libp2p
|
src/util/index.js
|
emitFirst
|
function emitFirst (emitter, events, handler) {
handler = once(handler)
events.forEach((e) => {
emitter.once(e, (...args) => {
events.forEach((ev) => {
emitter.removeListener(ev, handler)
})
handler.apply(emitter, args)
})
})
}
|
javascript
|
function emitFirst (emitter, events, handler) {
handler = once(handler)
events.forEach((e) => {
emitter.once(e, (...args) => {
events.forEach((ev) => {
emitter.removeListener(ev, handler)
})
handler.apply(emitter, args)
})
})
}
|
[
"function",
"emitFirst",
"(",
"emitter",
",",
"events",
",",
"handler",
")",
"{",
"handler",
"=",
"once",
"(",
"handler",
")",
"events",
".",
"forEach",
"(",
"(",
"e",
")",
"=>",
"{",
"emitter",
".",
"once",
"(",
"e",
",",
"(",
"...",
"args",
")",
"=>",
"{",
"events",
".",
"forEach",
"(",
"(",
"ev",
")",
"=>",
"{",
"emitter",
".",
"removeListener",
"(",
"ev",
",",
"handler",
")",
"}",
")",
"handler",
".",
"apply",
"(",
"emitter",
",",
"args",
")",
"}",
")",
"}",
")",
"}"
] |
Registers `handler` to each event in `events`. The `handler`
will only be called for the first event fired, at which point
the `handler` will be removed as a listener.
Ensures `handler` is only called once.
@example
// will call `callback` when `start` or `error` is emitted by `this`
emitFirst(this, ['error', 'start'], callback)
@private
@param {EventEmitter} emitter The emitter to listen on
@param {Array<string>} events The events to listen for
@param {function(*)} handler The handler to call when an event is triggered
@returns {void}
|
[
"Registers",
"handler",
"to",
"each",
"event",
"in",
"events",
".",
"The",
"handler",
"will",
"only",
"be",
"called",
"for",
"the",
"first",
"event",
"fired",
"at",
"which",
"point",
"the",
"handler",
"will",
"be",
"removed",
"as",
"a",
"listener",
"."
] |
28c054c21e7ba2796450d2ab2a0bef6542ec3583
|
https://github.com/libp2p/js-libp2p/blob/28c054c21e7ba2796450d2ab2a0bef6542ec3583/src/util/index.js#L21-L31
|
6,946
|
vue-styleguidist/vue-styleguidist
|
packages/vue-styleguidist/loaders/utils/getSections.js
|
getSections
|
function getSections(sections, config, parentDepth) {
return sections.map(section => processSection(section, config, parentDepth))
}
|
javascript
|
function getSections(sections, config, parentDepth) {
return sections.map(section => processSection(section, config, parentDepth))
}
|
[
"function",
"getSections",
"(",
"sections",
",",
"config",
",",
"parentDepth",
")",
"{",
"return",
"sections",
".",
"map",
"(",
"section",
"=>",
"processSection",
"(",
"section",
",",
"config",
",",
"parentDepth",
")",
")",
"}"
] |
Return object for one level of sections.
@param {Array} sections
@param {object} config
@param {number} parentDepth
@returns {Array}
|
[
"Return",
"object",
"for",
"one",
"level",
"of",
"sections",
"."
] |
a039dc0e112a1d59122d84f5a7ce6b328a63c61b
|
https://github.com/vue-styleguidist/vue-styleguidist/blob/a039dc0e112a1d59122d84f5a7ce6b328a63c61b/packages/vue-styleguidist/loaders/utils/getSections.js#L21-L23
|
6,947
|
vue-styleguidist/vue-styleguidist
|
packages/vue-styleguidist/loaders/utils/getSections.js
|
processSection
|
function processSection(section, config, parentDepth) {
const contentRelativePath = section.content
// Try to load section content file
let content
if (contentRelativePath) {
const contentAbsolutePath = path.resolve(config.configDir, contentRelativePath)
if (!fs.existsSync(contentAbsolutePath)) {
throw new Error(`Styleguidist: Section content file not found: ${contentAbsolutePath}`)
}
content = requireIt(`!!${examplesLoader}?customLangs=vue|js|jsx!${contentAbsolutePath}`)
}
let sectionDepth
if (parentDepth === undefined) {
sectionDepth = section.sectionDepth !== undefined ? section.sectionDepth : 0
} else {
sectionDepth = parentDepth === 0 ? 0 : parentDepth - 1
}
return {
name: section.name,
exampleMode: section.exampleMode || config.exampleMode,
usageMode: section.usageMode || config.usageMode,
sectionDepth,
description: section.description,
slug: slugger.slug(section.name),
sections: getSections(section.sections || [], config, sectionDepth),
filepath: contentRelativePath,
href: section.href,
components: getSectionComponents(section, config),
content,
external: section.external
}
}
|
javascript
|
function processSection(section, config, parentDepth) {
const contentRelativePath = section.content
// Try to load section content file
let content
if (contentRelativePath) {
const contentAbsolutePath = path.resolve(config.configDir, contentRelativePath)
if (!fs.existsSync(contentAbsolutePath)) {
throw new Error(`Styleguidist: Section content file not found: ${contentAbsolutePath}`)
}
content = requireIt(`!!${examplesLoader}?customLangs=vue|js|jsx!${contentAbsolutePath}`)
}
let sectionDepth
if (parentDepth === undefined) {
sectionDepth = section.sectionDepth !== undefined ? section.sectionDepth : 0
} else {
sectionDepth = parentDepth === 0 ? 0 : parentDepth - 1
}
return {
name: section.name,
exampleMode: section.exampleMode || config.exampleMode,
usageMode: section.usageMode || config.usageMode,
sectionDepth,
description: section.description,
slug: slugger.slug(section.name),
sections: getSections(section.sections || [], config, sectionDepth),
filepath: contentRelativePath,
href: section.href,
components: getSectionComponents(section, config),
content,
external: section.external
}
}
|
[
"function",
"processSection",
"(",
"section",
",",
"config",
",",
"parentDepth",
")",
"{",
"const",
"contentRelativePath",
"=",
"section",
".",
"content",
"// Try to load section content file",
"let",
"content",
"if",
"(",
"contentRelativePath",
")",
"{",
"const",
"contentAbsolutePath",
"=",
"path",
".",
"resolve",
"(",
"config",
".",
"configDir",
",",
"contentRelativePath",
")",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"contentAbsolutePath",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"contentAbsolutePath",
"}",
"`",
")",
"}",
"content",
"=",
"requireIt",
"(",
"`",
"${",
"examplesLoader",
"}",
"${",
"contentAbsolutePath",
"}",
"`",
")",
"}",
"let",
"sectionDepth",
"if",
"(",
"parentDepth",
"===",
"undefined",
")",
"{",
"sectionDepth",
"=",
"section",
".",
"sectionDepth",
"!==",
"undefined",
"?",
"section",
".",
"sectionDepth",
":",
"0",
"}",
"else",
"{",
"sectionDepth",
"=",
"parentDepth",
"===",
"0",
"?",
"0",
":",
"parentDepth",
"-",
"1",
"}",
"return",
"{",
"name",
":",
"section",
".",
"name",
",",
"exampleMode",
":",
"section",
".",
"exampleMode",
"||",
"config",
".",
"exampleMode",
",",
"usageMode",
":",
"section",
".",
"usageMode",
"||",
"config",
".",
"usageMode",
",",
"sectionDepth",
",",
"description",
":",
"section",
".",
"description",
",",
"slug",
":",
"slugger",
".",
"slug",
"(",
"section",
".",
"name",
")",
",",
"sections",
":",
"getSections",
"(",
"section",
".",
"sections",
"||",
"[",
"]",
",",
"config",
",",
"sectionDepth",
")",
",",
"filepath",
":",
"contentRelativePath",
",",
"href",
":",
"section",
".",
"href",
",",
"components",
":",
"getSectionComponents",
"(",
"section",
",",
"config",
")",
",",
"content",
",",
"external",
":",
"section",
".",
"external",
"}",
"}"
] |
Return an object for a given section with all components and subsections.
@param {object} section
@param {object} config
@param {number} parentDepth
@returns {object}
|
[
"Return",
"an",
"object",
"for",
"a",
"given",
"section",
"with",
"all",
"components",
"and",
"subsections",
"."
] |
a039dc0e112a1d59122d84f5a7ce6b328a63c61b
|
https://github.com/vue-styleguidist/vue-styleguidist/blob/a039dc0e112a1d59122d84f5a7ce6b328a63c61b/packages/vue-styleguidist/loaders/utils/getSections.js#L41-L76
|
6,948
|
vue-styleguidist/vue-styleguidist
|
packages/vue-styleguidist/loaders/utils/processComponent.js
|
getComponentMetadataPath
|
function getComponentMetadataPath(filepath) {
const extname = path.extname(filepath)
return filepath.substring(0, filepath.length - extname.length) + '.json'
}
|
javascript
|
function getComponentMetadataPath(filepath) {
const extname = path.extname(filepath)
return filepath.substring(0, filepath.length - extname.length) + '.json'
}
|
[
"function",
"getComponentMetadataPath",
"(",
"filepath",
")",
"{",
"const",
"extname",
"=",
"path",
".",
"extname",
"(",
"filepath",
")",
"return",
"filepath",
".",
"substring",
"(",
"0",
",",
"filepath",
".",
"length",
"-",
"extname",
".",
"length",
")",
"+",
"'.json'",
"}"
] |
References the filepath of the metadata file.
@param {string} filepath
@returns {object}
|
[
"References",
"the",
"filepath",
"of",
"the",
"metadata",
"file",
"."
] |
a039dc0e112a1d59122d84f5a7ce6b328a63c61b
|
https://github.com/vue-styleguidist/vue-styleguidist/blob/a039dc0e112a1d59122d84f5a7ce6b328a63c61b/packages/vue-styleguidist/loaders/utils/processComponent.js#L15-L18
|
6,949
|
vue-styleguidist/vue-styleguidist
|
packages/vue-styleguidist/scripts/config.js
|
findConfigFile
|
function findConfigFile() {
let configDir
try {
configDir = findup.sync(process.cwd(), CONFIG_FILENAME)
} catch (exception) {
return false
}
return path.join(configDir, CONFIG_FILENAME)
}
|
javascript
|
function findConfigFile() {
let configDir
try {
configDir = findup.sync(process.cwd(), CONFIG_FILENAME)
} catch (exception) {
return false
}
return path.join(configDir, CONFIG_FILENAME)
}
|
[
"function",
"findConfigFile",
"(",
")",
"{",
"let",
"configDir",
"try",
"{",
"configDir",
"=",
"findup",
".",
"sync",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"CONFIG_FILENAME",
")",
"}",
"catch",
"(",
"exception",
")",
"{",
"return",
"false",
"}",
"return",
"path",
".",
"join",
"(",
"configDir",
",",
"CONFIG_FILENAME",
")",
"}"
] |
Try to find config file up the file tree.
@return {string|boolean} Config absolute file path.
|
[
"Try",
"to",
"find",
"config",
"file",
"up",
"the",
"file",
"tree",
"."
] |
a039dc0e112a1d59122d84f5a7ce6b328a63c61b
|
https://github.com/vue-styleguidist/vue-styleguidist/blob/a039dc0e112a1d59122d84f5a7ce6b328a63c61b/packages/vue-styleguidist/scripts/config.js#L62-L71
|
6,950
|
Microsoft/Recognizers-Text
|
JavaScript/samples/simple-console/index.js
|
runRecognition
|
function runRecognition() {
var stdin = process.openStdin();
// Read the text to recognize
write('Enter the text to recognize: ');
stdin.addListener('data', function (e) {
var input = e.toString().trim();
if (input) {
// Exit
if (input.toLowerCase() === 'exit') {
return process.exit();
} else {
// Retrieve all the ModelResult recognized from the user input
var results = parseAll(input, defaultCulture);
results = [].concat.apply([], results);
// Write results on console
write();
write(results.length > 0 ? "I found the following entities (" + results.length + "):" : "I found no entities.");
write();
results.forEach(function (result) {
write(JSON.stringify(result, null, "\t"));
write();
});
}
}
// Read the text to recognize
write('\nEnter the text to recognize: ');
});
}
|
javascript
|
function runRecognition() {
var stdin = process.openStdin();
// Read the text to recognize
write('Enter the text to recognize: ');
stdin.addListener('data', function (e) {
var input = e.toString().trim();
if (input) {
// Exit
if (input.toLowerCase() === 'exit') {
return process.exit();
} else {
// Retrieve all the ModelResult recognized from the user input
var results = parseAll(input, defaultCulture);
results = [].concat.apply([], results);
// Write results on console
write();
write(results.length > 0 ? "I found the following entities (" + results.length + "):" : "I found no entities.");
write();
results.forEach(function (result) {
write(JSON.stringify(result, null, "\t"));
write();
});
}
}
// Read the text to recognize
write('\nEnter the text to recognize: ');
});
}
|
[
"function",
"runRecognition",
"(",
")",
"{",
"var",
"stdin",
"=",
"process",
".",
"openStdin",
"(",
")",
";",
"// Read the text to recognize",
"write",
"(",
"'Enter the text to recognize: '",
")",
";",
"stdin",
".",
"addListener",
"(",
"'data'",
",",
"function",
"(",
"e",
")",
"{",
"var",
"input",
"=",
"e",
".",
"toString",
"(",
")",
".",
"trim",
"(",
")",
";",
"if",
"(",
"input",
")",
"{",
"// Exit",
"if",
"(",
"input",
".",
"toLowerCase",
"(",
")",
"===",
"'exit'",
")",
"{",
"return",
"process",
".",
"exit",
"(",
")",
";",
"}",
"else",
"{",
"// Retrieve all the ModelResult recognized from the user input",
"var",
"results",
"=",
"parseAll",
"(",
"input",
",",
"defaultCulture",
")",
";",
"results",
"=",
"[",
"]",
".",
"concat",
".",
"apply",
"(",
"[",
"]",
",",
"results",
")",
";",
"// Write results on console",
"write",
"(",
")",
";",
"write",
"(",
"results",
".",
"length",
">",
"0",
"?",
"\"I found the following entities (\"",
"+",
"results",
".",
"length",
"+",
"\"):\"",
":",
"\"I found no entities.\"",
")",
";",
"write",
"(",
")",
";",
"results",
".",
"forEach",
"(",
"function",
"(",
"result",
")",
"{",
"write",
"(",
"JSON",
".",
"stringify",
"(",
"result",
",",
"null",
",",
"\"\\t\"",
")",
")",
";",
"write",
"(",
")",
";",
"}",
")",
";",
"}",
"}",
"// Read the text to recognize",
"write",
"(",
"'\\nEnter the text to recognize: '",
")",
";",
"}",
")",
";",
"}"
] |
Read from Console and recognize
|
[
"Read",
"from",
"Console",
"and",
"recognize"
] |
08414d1585eaa29a61455aaea95bf29a8d629b23
|
https://github.com/Microsoft/Recognizers-Text/blob/08414d1585eaa29a61455aaea95bf29a8d629b23/JavaScript/samples/simple-console/index.js#L11-L44
|
6,951
|
jfhbrook/node-ecstatic
|
lib/ecstatic.js
|
shouldCompressGzip
|
function shouldCompressGzip(req) {
const headers = req.headers;
return headers && headers['accept-encoding'] &&
headers['accept-encoding']
.split(',')
.some(el => ['*', 'compress', 'gzip', 'deflate'].indexOf(el.trim()) !== -1)
;
}
|
javascript
|
function shouldCompressGzip(req) {
const headers = req.headers;
return headers && headers['accept-encoding'] &&
headers['accept-encoding']
.split(',')
.some(el => ['*', 'compress', 'gzip', 'deflate'].indexOf(el.trim()) !== -1)
;
}
|
[
"function",
"shouldCompressGzip",
"(",
"req",
")",
"{",
"const",
"headers",
"=",
"req",
".",
"headers",
";",
"return",
"headers",
"&&",
"headers",
"[",
"'accept-encoding'",
"]",
"&&",
"headers",
"[",
"'accept-encoding'",
"]",
".",
"split",
"(",
"','",
")",
".",
"some",
"(",
"el",
"=>",
"[",
"'*'",
",",
"'compress'",
",",
"'gzip'",
",",
"'deflate'",
"]",
".",
"indexOf",
"(",
"el",
".",
"trim",
"(",
")",
")",
"!==",
"-",
"1",
")",
";",
"}"
] |
Check to see if we should try to compress a file with gzip.
|
[
"Check",
"to",
"see",
"if",
"we",
"should",
"try",
"to",
"compress",
"a",
"file",
"with",
"gzip",
"."
] |
ae7a39b1ecdbe3aa8c0162ab2c3f7365bf9a6d75
|
https://github.com/jfhbrook/node-ecstatic/blob/ae7a39b1ecdbe3aa8c0162ab2c3f7365bf9a6d75/lib/ecstatic.js#L36-L44
|
6,952
|
jfhbrook/node-ecstatic
|
lib/ecstatic.js
|
tryServeWithGzip
|
function tryServeWithGzip() {
fs.stat(gzippedFile, (err, stat) => {
if (!err && stat.isFile()) {
hasGzipId12(gzippedFile, (gzipErr, isGzip) => {
if (!gzipErr && isGzip) {
file = gzippedFile;
serve(stat);
} else {
statFile();
}
});
} else {
statFile();
}
});
}
|
javascript
|
function tryServeWithGzip() {
fs.stat(gzippedFile, (err, stat) => {
if (!err && stat.isFile()) {
hasGzipId12(gzippedFile, (gzipErr, isGzip) => {
if (!gzipErr && isGzip) {
file = gzippedFile;
serve(stat);
} else {
statFile();
}
});
} else {
statFile();
}
});
}
|
[
"function",
"tryServeWithGzip",
"(",
")",
"{",
"fs",
".",
"stat",
"(",
"gzippedFile",
",",
"(",
"err",
",",
"stat",
")",
"=>",
"{",
"if",
"(",
"!",
"err",
"&&",
"stat",
".",
"isFile",
"(",
")",
")",
"{",
"hasGzipId12",
"(",
"gzippedFile",
",",
"(",
"gzipErr",
",",
"isGzip",
")",
"=>",
"{",
"if",
"(",
"!",
"gzipErr",
"&&",
"isGzip",
")",
"{",
"file",
"=",
"gzippedFile",
";",
"serve",
"(",
"stat",
")",
";",
"}",
"else",
"{",
"statFile",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"statFile",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
serve gzip file if exists and is valid
|
[
"serve",
"gzip",
"file",
"if",
"exists",
"and",
"is",
"valid"
] |
ae7a39b1ecdbe3aa8c0162ab2c3f7365bf9a6d75
|
https://github.com/jfhbrook/node-ecstatic/blob/ae7a39b1ecdbe3aa8c0162ab2c3f7365bf9a6d75/lib/ecstatic.js#L433-L448
|
6,953
|
jfhbrook/node-ecstatic
|
lib/ecstatic.js
|
tryServeWithBrotli
|
function tryServeWithBrotli(shouldTryGzip) {
fs.stat(brotliFile, (err, stat) => {
if (!err && stat.isFile()) {
file = brotliFile;
serve(stat);
} else if (shouldTryGzip) {
tryServeWithGzip();
} else {
statFile();
}
});
}
|
javascript
|
function tryServeWithBrotli(shouldTryGzip) {
fs.stat(brotliFile, (err, stat) => {
if (!err && stat.isFile()) {
file = brotliFile;
serve(stat);
} else if (shouldTryGzip) {
tryServeWithGzip();
} else {
statFile();
}
});
}
|
[
"function",
"tryServeWithBrotli",
"(",
"shouldTryGzip",
")",
"{",
"fs",
".",
"stat",
"(",
"brotliFile",
",",
"(",
"err",
",",
"stat",
")",
"=>",
"{",
"if",
"(",
"!",
"err",
"&&",
"stat",
".",
"isFile",
"(",
")",
")",
"{",
"file",
"=",
"brotliFile",
";",
"serve",
"(",
"stat",
")",
";",
"}",
"else",
"if",
"(",
"shouldTryGzip",
")",
"{",
"tryServeWithGzip",
"(",
")",
";",
"}",
"else",
"{",
"statFile",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
serve brotli file if exists, otherwise try gzip
|
[
"serve",
"brotli",
"file",
"if",
"exists",
"otherwise",
"try",
"gzip"
] |
ae7a39b1ecdbe3aa8c0162ab2c3f7365bf9a6d75
|
https://github.com/jfhbrook/node-ecstatic/blob/ae7a39b1ecdbe3aa8c0162ab2c3f7365bf9a6d75/lib/ecstatic.js#L451-L462
|
6,954
|
rauchg/slackin
|
lib/assets/superagent.js
|
getXHR
|
function getXHR () {
if (root.XMLHttpRequest
&& ('file:' != root.location.protocol || !root.ActiveXObject)) {
return new XMLHttpRequest
} else {
try { return new ActiveXObject('Microsoft.XMLHTTP') } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0') } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0') } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP') } catch(e) {}
}
return false
}
|
javascript
|
function getXHR () {
if (root.XMLHttpRequest
&& ('file:' != root.location.protocol || !root.ActiveXObject)) {
return new XMLHttpRequest
} else {
try { return new ActiveXObject('Microsoft.XMLHTTP') } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0') } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0') } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP') } catch(e) {}
}
return false
}
|
[
"function",
"getXHR",
"(",
")",
"{",
"if",
"(",
"root",
".",
"XMLHttpRequest",
"&&",
"(",
"'file:'",
"!=",
"root",
".",
"location",
".",
"protocol",
"||",
"!",
"root",
".",
"ActiveXObject",
")",
")",
"{",
"return",
"new",
"XMLHttpRequest",
"}",
"else",
"{",
"try",
"{",
"return",
"new",
"ActiveXObject",
"(",
"'Microsoft.XMLHTTP'",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"try",
"{",
"return",
"new",
"ActiveXObject",
"(",
"'Msxml2.XMLHTTP.6.0'",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"try",
"{",
"return",
"new",
"ActiveXObject",
"(",
"'Msxml2.XMLHTTP.3.0'",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"try",
"{",
"return",
"new",
"ActiveXObject",
"(",
"'Msxml2.XMLHTTP'",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"}",
"return",
"false",
"}"
] |
Determine XHR.
|
[
"Determine",
"XHR",
"."
] |
fa88a860a87cf38d9a1c4007207e6efae4288242
|
https://github.com/rauchg/slackin/blob/fa88a860a87cf38d9a1c4007207e6efae4288242/lib/assets/superagent.js#L446-L457
|
6,955
|
rauchg/slackin
|
lib/assets/superagent.js
|
params
|
function params (str){
return reduce(str.split(/ *; */), function (obj, str){
var parts = str.split(/ *= */),
key = parts.shift(),
val = parts.shift()
if (key && val) obj[key] = val
return obj
}, {})
}
|
javascript
|
function params (str){
return reduce(str.split(/ *; */), function (obj, str){
var parts = str.split(/ *= */),
key = parts.shift(),
val = parts.shift()
if (key && val) obj[key] = val
return obj
}, {})
}
|
[
"function",
"params",
"(",
"str",
")",
"{",
"return",
"reduce",
"(",
"str",
".",
"split",
"(",
"/",
" *; *",
"/",
")",
",",
"function",
"(",
"obj",
",",
"str",
")",
"{",
"var",
"parts",
"=",
"str",
".",
"split",
"(",
"/",
" *= *",
"/",
")",
",",
"key",
"=",
"parts",
".",
"shift",
"(",
")",
",",
"val",
"=",
"parts",
".",
"shift",
"(",
")",
"if",
"(",
"key",
"&&",
"val",
")",
"obj",
"[",
"key",
"]",
"=",
"val",
"return",
"obj",
"}",
",",
"{",
"}",
")",
"}"
] |
Return header field parameters.
@param {String} str
@return {Object}
@api private
|
[
"Return",
"header",
"field",
"parameters",
"."
] |
fa88a860a87cf38d9a1c4007207e6efae4288242
|
https://github.com/rauchg/slackin/blob/fa88a860a87cf38d9a1c4007207e6efae4288242/lib/assets/superagent.js#L632-L641
|
6,956
|
rauchg/slackin
|
lib/assets/badge.js
|
search
|
function search (){
var replaced = 0
var scripts = document.querySelectorAll('script')
var script
for (var i = 0; i < scripts.length; i++) {
script = scripts[i]
if (!script.src) continue
if (/\/slackin\.js(\?.*)?$/.test(script.src)) {
// replace script with iframe
replace(script)
// we abort the search for subsequent
// slackin.js executions to exhaust
// the queue
return true
}
}
}
|
javascript
|
function search (){
var replaced = 0
var scripts = document.querySelectorAll('script')
var script
for (var i = 0; i < scripts.length; i++) {
script = scripts[i]
if (!script.src) continue
if (/\/slackin\.js(\?.*)?$/.test(script.src)) {
// replace script with iframe
replace(script)
// we abort the search for subsequent
// slackin.js executions to exhaust
// the queue
return true
}
}
}
|
[
"function",
"search",
"(",
")",
"{",
"var",
"replaced",
"=",
"0",
"var",
"scripts",
"=",
"document",
".",
"querySelectorAll",
"(",
"'script'",
")",
"var",
"script",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"scripts",
".",
"length",
";",
"i",
"++",
")",
"{",
"script",
"=",
"scripts",
"[",
"i",
"]",
"if",
"(",
"!",
"script",
".",
"src",
")",
"continue",
"if",
"(",
"/",
"\\/slackin\\.js(\\?.*)?$",
"/",
".",
"test",
"(",
"script",
".",
"src",
")",
")",
"{",
"// replace script with iframe",
"replace",
"(",
"script",
")",
"// we abort the search for subsequent",
"// slackin.js executions to exhaust",
"// the queue",
"return",
"true",
"}",
"}",
"}"
] |
search for a script tag pointing to slackin.js
|
[
"search",
"for",
"a",
"script",
"tag",
"pointing",
"to",
"slackin",
".",
"js"
] |
fa88a860a87cf38d9a1c4007207e6efae4288242
|
https://github.com/rauchg/slackin/blob/fa88a860a87cf38d9a1c4007207e6efae4288242/lib/assets/badge.js#L12-L29
|
6,957
|
rauchg/slackin
|
lib/assets/badge.js
|
replace
|
function replace (script){
var parent = script.parentNode
if (!parent) return
LARGE = /\?large/.test(script.src)
var iframe = document.createElement('iframe')
var iframePath = '/iframe' + (LARGE ? '?large' : '')
iframe.src = script.src.replace(/\/slackin\.js.*/, iframePath)
iframe.style.borderWidth = 0
iframe.className = '__slackin'
// a decent aproximation that we adjust later
// once we have the knowledge of the actual
// numbers of users, based on a user count
// of 3 digits by 3 digits
iframe.style.width = (LARGE ? 190 : 140) + 'px'
// height depends on target size
iframe.style.height = (LARGE ? 30 : 20) + 'px'
// hidden by default to avoid flicker
iframe.style.visibility = 'hidden'
parent.insertBefore(iframe, script)
parent.removeChild(script)
// setup iframe RPC
iframe.onload = function (){
setup(iframe)
}
}
|
javascript
|
function replace (script){
var parent = script.parentNode
if (!parent) return
LARGE = /\?large/.test(script.src)
var iframe = document.createElement('iframe')
var iframePath = '/iframe' + (LARGE ? '?large' : '')
iframe.src = script.src.replace(/\/slackin\.js.*/, iframePath)
iframe.style.borderWidth = 0
iframe.className = '__slackin'
// a decent aproximation that we adjust later
// once we have the knowledge of the actual
// numbers of users, based on a user count
// of 3 digits by 3 digits
iframe.style.width = (LARGE ? 190 : 140) + 'px'
// height depends on target size
iframe.style.height = (LARGE ? 30 : 20) + 'px'
// hidden by default to avoid flicker
iframe.style.visibility = 'hidden'
parent.insertBefore(iframe, script)
parent.removeChild(script)
// setup iframe RPC
iframe.onload = function (){
setup(iframe)
}
}
|
[
"function",
"replace",
"(",
"script",
")",
"{",
"var",
"parent",
"=",
"script",
".",
"parentNode",
"if",
"(",
"!",
"parent",
")",
"return",
"LARGE",
"=",
"/",
"\\?large",
"/",
".",
"test",
"(",
"script",
".",
"src",
")",
"var",
"iframe",
"=",
"document",
".",
"createElement",
"(",
"'iframe'",
")",
"var",
"iframePath",
"=",
"'/iframe'",
"+",
"(",
"LARGE",
"?",
"'?large'",
":",
"''",
")",
"iframe",
".",
"src",
"=",
"script",
".",
"src",
".",
"replace",
"(",
"/",
"\\/slackin\\.js.*",
"/",
",",
"iframePath",
")",
"iframe",
".",
"style",
".",
"borderWidth",
"=",
"0",
"iframe",
".",
"className",
"=",
"'__slackin'",
"// a decent aproximation that we adjust later",
"// once we have the knowledge of the actual",
"// numbers of users, based on a user count",
"// of 3 digits by 3 digits",
"iframe",
".",
"style",
".",
"width",
"=",
"(",
"LARGE",
"?",
"190",
":",
"140",
")",
"+",
"'px'",
"// height depends on target size",
"iframe",
".",
"style",
".",
"height",
"=",
"(",
"LARGE",
"?",
"30",
":",
"20",
")",
"+",
"'px'",
"// hidden by default to avoid flicker",
"iframe",
".",
"style",
".",
"visibility",
"=",
"'hidden'",
"parent",
".",
"insertBefore",
"(",
"iframe",
",",
"script",
")",
"parent",
".",
"removeChild",
"(",
"script",
")",
"// setup iframe RPC",
"iframe",
".",
"onload",
"=",
"function",
"(",
")",
"{",
"setup",
"(",
"iframe",
")",
"}",
"}"
] |
replace the script tag with an iframe
|
[
"replace",
"the",
"script",
"tag",
"with",
"an",
"iframe"
] |
fa88a860a87cf38d9a1c4007207e6efae4288242
|
https://github.com/rauchg/slackin/blob/fa88a860a87cf38d9a1c4007207e6efae4288242/lib/assets/badge.js#L34-L64
|
6,958
|
rauchg/slackin
|
lib/assets/badge.js
|
setup
|
function setup (iframe){
var id = Math.random() * (1 << 24) | 0
iframe.contentWindow.postMessage('slackin:' + id, '*')
window.addEventListener('message', function (e){
if (typeof e.data !== 'string') return
// show dialog upon click
if ('slackin-click:' + id === e.data) {
showDialog(iframe)
}
// update width
var wp = 'slackin-width:' + id + ':'
if (wp === e.data.substr(0, wp.length)) {
var width = e.data.substr(wp.length)
iframe.style.width = width + 'px'
// ensure it's shown (since first time hidden)
iframe.style.visibility = 'visible'
}
// redirect to URL
var redir = 'slackin-redirect:' + id + ':'
if (redir === e.data.substr(0, redir.length)) {
location.href = e.data.substr(redir.length)
}
})
}
|
javascript
|
function setup (iframe){
var id = Math.random() * (1 << 24) | 0
iframe.contentWindow.postMessage('slackin:' + id, '*')
window.addEventListener('message', function (e){
if (typeof e.data !== 'string') return
// show dialog upon click
if ('slackin-click:' + id === e.data) {
showDialog(iframe)
}
// update width
var wp = 'slackin-width:' + id + ':'
if (wp === e.data.substr(0, wp.length)) {
var width = e.data.substr(wp.length)
iframe.style.width = width + 'px'
// ensure it's shown (since first time hidden)
iframe.style.visibility = 'visible'
}
// redirect to URL
var redir = 'slackin-redirect:' + id + ':'
if (redir === e.data.substr(0, redir.length)) {
location.href = e.data.substr(redir.length)
}
})
}
|
[
"function",
"setup",
"(",
"iframe",
")",
"{",
"var",
"id",
"=",
"Math",
".",
"random",
"(",
")",
"*",
"(",
"1",
"<<",
"24",
")",
"|",
"0",
"iframe",
".",
"contentWindow",
".",
"postMessage",
"(",
"'slackin:'",
"+",
"id",
",",
"'*'",
")",
"window",
".",
"addEventListener",
"(",
"'message'",
",",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"typeof",
"e",
".",
"data",
"!==",
"'string'",
")",
"return",
"// show dialog upon click",
"if",
"(",
"'slackin-click:'",
"+",
"id",
"===",
"e",
".",
"data",
")",
"{",
"showDialog",
"(",
"iframe",
")",
"}",
"// update width",
"var",
"wp",
"=",
"'slackin-width:'",
"+",
"id",
"+",
"':'",
"if",
"(",
"wp",
"===",
"e",
".",
"data",
".",
"substr",
"(",
"0",
",",
"wp",
".",
"length",
")",
")",
"{",
"var",
"width",
"=",
"e",
".",
"data",
".",
"substr",
"(",
"wp",
".",
"length",
")",
"iframe",
".",
"style",
".",
"width",
"=",
"width",
"+",
"'px'",
"// ensure it's shown (since first time hidden)",
"iframe",
".",
"style",
".",
"visibility",
"=",
"'visible'",
"}",
"// redirect to URL",
"var",
"redir",
"=",
"'slackin-redirect:'",
"+",
"id",
"+",
"':'",
"if",
"(",
"redir",
"===",
"e",
".",
"data",
".",
"substr",
"(",
"0",
",",
"redir",
".",
"length",
")",
")",
"{",
"location",
".",
"href",
"=",
"e",
".",
"data",
".",
"substr",
"(",
"redir",
".",
"length",
")",
"}",
"}",
")",
"}"
] |
setup an "RPC" channel between iframe and us
|
[
"setup",
"an",
"RPC",
"channel",
"between",
"iframe",
"and",
"us"
] |
fa88a860a87cf38d9a1c4007207e6efae4288242
|
https://github.com/rauchg/slackin/blob/fa88a860a87cf38d9a1c4007207e6efae4288242/lib/assets/badge.js#L67-L94
|
6,959
|
rauchg/slackin
|
lib/badge.js
|
text
|
function text ({str, x, y}){
return [
svg(`text fill=#010101 fill-opacity=.3 x=${x} y=${y + 1}`, str),
svg(`text fill=#fff x=${x} y=${y}`, str)
]
}
|
javascript
|
function text ({str, x, y}){
return [
svg(`text fill=#010101 fill-opacity=.3 x=${x} y=${y + 1}`, str),
svg(`text fill=#fff x=${x} y=${y}`, str)
]
}
|
[
"function",
"text",
"(",
"{",
"str",
",",
"x",
",",
"y",
"}",
")",
"{",
"return",
"[",
"svg",
"(",
"`",
"${",
"x",
"}",
"${",
"y",
"+",
"1",
"}",
"`",
",",
"str",
")",
",",
"svg",
"(",
"`",
"${",
"x",
"}",
"${",
"y",
"}",
"`",
",",
"str",
")",
"]",
"}"
] |
generate text with 1px shadow
|
[
"generate",
"text",
"with",
"1px",
"shadow"
] |
fa88a860a87cf38d9a1c4007207e6efae4288242
|
https://github.com/rauchg/slackin/blob/fa88a860a87cf38d9a1c4007207e6efae4288242/lib/badge.js#L26-L31
|
6,960
|
rauchg/slackin
|
lib/assets/client.js
|
topLevelRedirect
|
function topLevelRedirect (url) {
if (window === top) location.href = url
else parent.postMessage('slackin-redirect:' + id + ':' + url, '*')
// Q: Why can't we just `top.location.href = url;`?
// A:
// [sandboxing]: http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/
// [CSP]: http://www.html5rocks.com/en/tutorials/security/content-security-policy/
// [nope]: http://output.jsbin.com/popawuk/16
}
|
javascript
|
function topLevelRedirect (url) {
if (window === top) location.href = url
else parent.postMessage('slackin-redirect:' + id + ':' + url, '*')
// Q: Why can't we just `top.location.href = url;`?
// A:
// [sandboxing]: http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/
// [CSP]: http://www.html5rocks.com/en/tutorials/security/content-security-policy/
// [nope]: http://output.jsbin.com/popawuk/16
}
|
[
"function",
"topLevelRedirect",
"(",
"url",
")",
"{",
"if",
"(",
"window",
"===",
"top",
")",
"location",
".",
"href",
"=",
"url",
"else",
"parent",
".",
"postMessage",
"(",
"'slackin-redirect:'",
"+",
"id",
"+",
"':'",
"+",
"url",
",",
"'*'",
")",
"// Q: Why can't we just `top.location.href = url;`?",
"// A:",
"// [sandboxing]: http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/",
"// [CSP]: http://www.html5rocks.com/en/tutorials/security/content-security-policy/",
"// [nope]: http://output.jsbin.com/popawuk/16",
"}"
] |
redirect, using "RPC" to parent if necessary
|
[
"redirect",
"using",
"RPC",
"to",
"parent",
"if",
"necessary"
] |
fa88a860a87cf38d9a1c4007207e6efae4288242
|
https://github.com/rauchg/slackin/blob/fa88a860a87cf38d9a1c4007207e6efae4288242/lib/assets/client.js#L89-L97
|
6,961
|
facebook/prop-types
|
factoryWithTypeCheckers.js
|
getClassName
|
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
|
javascript
|
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
|
[
"function",
"getClassName",
"(",
"propValue",
")",
"{",
"if",
"(",
"!",
"propValue",
".",
"constructor",
"||",
"!",
"propValue",
".",
"constructor",
".",
"name",
")",
"{",
"return",
"ANONYMOUS",
";",
"}",
"return",
"propValue",
".",
"constructor",
".",
"name",
";",
"}"
] |
Returns class name of the object, if any.
|
[
"Returns",
"class",
"name",
"of",
"the",
"object",
"if",
"any",
"."
] |
e32c4900f5ab5fd3acea93e9d2f0d09e4a2f2ceb
|
https://github.com/facebook/prop-types/blob/e32c4900f5ab5fd3acea93e9d2f0d09e4a2f2ceb/factoryWithTypeCheckers.js#L598-L603
|
6,962
|
EddyVerbruggen/nativescript-plugin-firebase
|
publish/scripts/installer.js
|
writeBuildscriptHookForCrashlytics
|
function writeBuildscriptHookForCrashlytics(enable) {
var scriptPath = path.join(appRoot, "hooks", "after-prepare", "firebase-crashlytics-buildscript.js");
if (!enable) {
if (fs.existsSync(scriptPath)) {
fs.unlinkSync(scriptPath);
}
return
}
console.log("Install Crashlytics buildscript hook.");
try {
var scriptContent =
`const fs = require('fs-extra');
const path = require('path');
const xcode = require('xcode');
const pattern1 = /\\n\\s*\\/\\/Crashlytics 1 BEGIN[\\s\\S]*\\/\\/Crashlytics 1 END.*\\n/m;
const pattern2 = /\\n\\s*\\/\\/Crashlytics 2 BEGIN[\\s\\S]*\\/\\/Crashlytics 2 END.*\\n/m;
const pattern3 = /\\n\\s*\\/\\/Crashlytics 3 BEGIN[\\s\\S]*\\/\\/Crashlytics 3 END.*\\n/m;
const string1 = \`
//Crashlytics 1 BEGIN
#else
#import <Crashlytics/CLSLogging.h>
#endif
//Crashlytics 1 END
\`;
const string2 = \`
//Crashlytics 2 BEGIN
#if DEBUG
#else
static int redirect_cls(const char *prefix, const char *buffer, int size) {
CLSLog(@"%s: %.*s", prefix, size, buffer);
return size;
}
static int stderr_redirect(void *inFD, const char *buffer, int size) {
return redirect_cls("stderr", buffer, size);
}
static int stdout_redirect(void *inFD, const char *buffer, int size) {
return redirect_cls("stdout", buffer, size);
}
#endif
//Crashlytics 2 END
\`;
const string3 = \`
//Crashlytics 3 BEGIN
#if DEBUG
#else
// Per https://docs.fabric.io/apple/crashlytics/enhanced-reports.html#custom-logs :
// Crashlytics ensures that all log entries are recorded, even if the very next line of code crashes.
// This means that logging must incur some IO. Be careful when logging in performance-critical areas.
// As per the note above, enabling this can affect performance if too much logging is present.
// stdout->_write = stdout_redirect;
// stderr usually only occurs during critical failures;
// so it is usually essential to identifying crashes, especially in JS
stderr->_write = stderr_redirect;
#endif
//Crashlytics 3 END
\`;
module.exports = function($logger, $projectData, hookArgs) {
const platform = hookArgs.platform.toLowerCase();
return new Promise(function(resolve, reject) {
const isNativeProjectPrepared = !hookArgs.nativePrepare || !hookArgs.nativePrepare.skipNativePrepare;
if (isNativeProjectPrepared) {
try {
if (platform === 'ios') {
const sanitizedAppName = path.basename($projectData.projectDir).split('').filter((c) => /[a-zA-Z0-9]/.test(c)).join('');
// write buildscript for dSYM upload
const xcodeProjectPath = path.join($projectData.platformsDir, 'ios', sanitizedAppName + '.xcodeproj', 'project.pbxproj');
$logger.trace('Using Xcode project', xcodeProjectPath);
if (fs.existsSync(xcodeProjectPath)) {
var xcodeProject = xcode.project(xcodeProjectPath);
xcodeProject.parseSync();
var options = { shellPath: '/bin/sh', shellScript: '\"\${PODS_ROOT}/Fabric/run\"' };
xcodeProject.addBuildPhase(
[], 'PBXShellScriptBuildPhase', 'Configure Crashlytics', undefined, options
).buildPhase;
fs.writeFileSync(xcodeProjectPath, xcodeProject.writeSync());
$logger.trace('Xcode project written');
} else {
$logger.error(xcodeProjectPath + ' is missing.');
reject();
return;
}
// Logging from stdout/stderr
$logger.out('Add iOS crash logging');
const mainmPath = path.join($projectData.platformsDir, 'ios', 'internal', 'main.m');
if (fs.existsSync(mainmPath)) {
let mainmContent = fs.readFileSync(mainmPath).toString();
// string1
mainmContent = pattern1.test(mainmContent)
? mainmContent.replace(pattern1, string1)
: mainmContent.replace(/(\\n#endif\\n)/, string1);
// string2
mainmContent = pattern2.test(mainmContent)
? mainmContent.replace(pattern2, string2)
: mainmContent.replace(/(\\nint main.*)/, string2 + '$1');
// string3
mainmContent = pattern3.test(mainmContent)
? mainmContent.replace(pattern3, string3)
: mainmContent.replace(/(int main.*\\n)/, '$1' + string3 + '\\n');
fs.writeFileSync(mainmPath, mainmContent);
} else {
$logger.error(mainmPath + ' is missing.');
reject();
return;
}
resolve();
} else {
resolve();
}
} catch (e) {
$logger.error('Unknown error during prepare Crashlytics', e);
reject();
}
} else {
$logger.trace("Native project not prepared.");
resolve();
}
});
};
`;
var afterPrepareDirPath = path.dirname(scriptPath);
var hooksDirPath = path.dirname(afterPrepareDirPath);
if (!fs.existsSync(afterPrepareDirPath)) {
if (!fs.existsSync(hooksDirPath)) {
fs.mkdirSync(hooksDirPath);
}
fs.mkdirSync(afterPrepareDirPath);
}
fs.writeFileSync(scriptPath, scriptContent);
} catch (e) {
console.log("Failed to install Crashlytics buildscript hook.");
console.log(e);
}
}
|
javascript
|
function writeBuildscriptHookForCrashlytics(enable) {
var scriptPath = path.join(appRoot, "hooks", "after-prepare", "firebase-crashlytics-buildscript.js");
if (!enable) {
if (fs.existsSync(scriptPath)) {
fs.unlinkSync(scriptPath);
}
return
}
console.log("Install Crashlytics buildscript hook.");
try {
var scriptContent =
`const fs = require('fs-extra');
const path = require('path');
const xcode = require('xcode');
const pattern1 = /\\n\\s*\\/\\/Crashlytics 1 BEGIN[\\s\\S]*\\/\\/Crashlytics 1 END.*\\n/m;
const pattern2 = /\\n\\s*\\/\\/Crashlytics 2 BEGIN[\\s\\S]*\\/\\/Crashlytics 2 END.*\\n/m;
const pattern3 = /\\n\\s*\\/\\/Crashlytics 3 BEGIN[\\s\\S]*\\/\\/Crashlytics 3 END.*\\n/m;
const string1 = \`
//Crashlytics 1 BEGIN
#else
#import <Crashlytics/CLSLogging.h>
#endif
//Crashlytics 1 END
\`;
const string2 = \`
//Crashlytics 2 BEGIN
#if DEBUG
#else
static int redirect_cls(const char *prefix, const char *buffer, int size) {
CLSLog(@"%s: %.*s", prefix, size, buffer);
return size;
}
static int stderr_redirect(void *inFD, const char *buffer, int size) {
return redirect_cls("stderr", buffer, size);
}
static int stdout_redirect(void *inFD, const char *buffer, int size) {
return redirect_cls("stdout", buffer, size);
}
#endif
//Crashlytics 2 END
\`;
const string3 = \`
//Crashlytics 3 BEGIN
#if DEBUG
#else
// Per https://docs.fabric.io/apple/crashlytics/enhanced-reports.html#custom-logs :
// Crashlytics ensures that all log entries are recorded, even if the very next line of code crashes.
// This means that logging must incur some IO. Be careful when logging in performance-critical areas.
// As per the note above, enabling this can affect performance if too much logging is present.
// stdout->_write = stdout_redirect;
// stderr usually only occurs during critical failures;
// so it is usually essential to identifying crashes, especially in JS
stderr->_write = stderr_redirect;
#endif
//Crashlytics 3 END
\`;
module.exports = function($logger, $projectData, hookArgs) {
const platform = hookArgs.platform.toLowerCase();
return new Promise(function(resolve, reject) {
const isNativeProjectPrepared = !hookArgs.nativePrepare || !hookArgs.nativePrepare.skipNativePrepare;
if (isNativeProjectPrepared) {
try {
if (platform === 'ios') {
const sanitizedAppName = path.basename($projectData.projectDir).split('').filter((c) => /[a-zA-Z0-9]/.test(c)).join('');
// write buildscript for dSYM upload
const xcodeProjectPath = path.join($projectData.platformsDir, 'ios', sanitizedAppName + '.xcodeproj', 'project.pbxproj');
$logger.trace('Using Xcode project', xcodeProjectPath);
if (fs.existsSync(xcodeProjectPath)) {
var xcodeProject = xcode.project(xcodeProjectPath);
xcodeProject.parseSync();
var options = { shellPath: '/bin/sh', shellScript: '\"\${PODS_ROOT}/Fabric/run\"' };
xcodeProject.addBuildPhase(
[], 'PBXShellScriptBuildPhase', 'Configure Crashlytics', undefined, options
).buildPhase;
fs.writeFileSync(xcodeProjectPath, xcodeProject.writeSync());
$logger.trace('Xcode project written');
} else {
$logger.error(xcodeProjectPath + ' is missing.');
reject();
return;
}
// Logging from stdout/stderr
$logger.out('Add iOS crash logging');
const mainmPath = path.join($projectData.platformsDir, 'ios', 'internal', 'main.m');
if (fs.existsSync(mainmPath)) {
let mainmContent = fs.readFileSync(mainmPath).toString();
// string1
mainmContent = pattern1.test(mainmContent)
? mainmContent.replace(pattern1, string1)
: mainmContent.replace(/(\\n#endif\\n)/, string1);
// string2
mainmContent = pattern2.test(mainmContent)
? mainmContent.replace(pattern2, string2)
: mainmContent.replace(/(\\nint main.*)/, string2 + '$1');
// string3
mainmContent = pattern3.test(mainmContent)
? mainmContent.replace(pattern3, string3)
: mainmContent.replace(/(int main.*\\n)/, '$1' + string3 + '\\n');
fs.writeFileSync(mainmPath, mainmContent);
} else {
$logger.error(mainmPath + ' is missing.');
reject();
return;
}
resolve();
} else {
resolve();
}
} catch (e) {
$logger.error('Unknown error during prepare Crashlytics', e);
reject();
}
} else {
$logger.trace("Native project not prepared.");
resolve();
}
});
};
`;
var afterPrepareDirPath = path.dirname(scriptPath);
var hooksDirPath = path.dirname(afterPrepareDirPath);
if (!fs.existsSync(afterPrepareDirPath)) {
if (!fs.existsSync(hooksDirPath)) {
fs.mkdirSync(hooksDirPath);
}
fs.mkdirSync(afterPrepareDirPath);
}
fs.writeFileSync(scriptPath, scriptContent);
} catch (e) {
console.log("Failed to install Crashlytics buildscript hook.");
console.log(e);
}
}
|
[
"function",
"writeBuildscriptHookForCrashlytics",
"(",
"enable",
")",
"{",
"var",
"scriptPath",
"=",
"path",
".",
"join",
"(",
"appRoot",
",",
"\"hooks\"",
",",
"\"after-prepare\"",
",",
"\"firebase-crashlytics-buildscript.js\"",
")",
";",
"if",
"(",
"!",
"enable",
")",
"{",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"scriptPath",
")",
")",
"{",
"fs",
".",
"unlinkSync",
"(",
"scriptPath",
")",
";",
"}",
"return",
"}",
"console",
".",
"log",
"(",
"\"Install Crashlytics buildscript hook.\"",
")",
";",
"try",
"{",
"var",
"scriptContent",
"=",
"`",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\`",
"\\`",
"\\`",
"\\`",
"\\`",
"\\`",
"\\\"",
"\\$",
"\\\"",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"`",
";",
"var",
"afterPrepareDirPath",
"=",
"path",
".",
"dirname",
"(",
"scriptPath",
")",
";",
"var",
"hooksDirPath",
"=",
"path",
".",
"dirname",
"(",
"afterPrepareDirPath",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"afterPrepareDirPath",
")",
")",
"{",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"hooksDirPath",
")",
")",
"{",
"fs",
".",
"mkdirSync",
"(",
"hooksDirPath",
")",
";",
"}",
"fs",
".",
"mkdirSync",
"(",
"afterPrepareDirPath",
")",
";",
"}",
"fs",
".",
"writeFileSync",
"(",
"scriptPath",
",",
"scriptContent",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"log",
"(",
"\"Failed to install Crashlytics buildscript hook.\"",
")",
";",
"console",
".",
"log",
"(",
"e",
")",
";",
"}",
"}"
] |
Create the iOS build script for uploading dSYM files to Crashlytics
@param {any} enable Is Crashlytics enabled
|
[
"Create",
"the",
"iOS",
"build",
"script",
"for",
"uploading",
"dSYM",
"files",
"to",
"Crashlytics"
] |
e83ac1c4b6e18eb525ab6fb7ca6802f9cd3940ea
|
https://github.com/EddyVerbruggen/nativescript-plugin-firebase/blob/e83ac1c4b6e18eb525ab6fb7ca6802f9cd3940ea/publish/scripts/installer.js#L462-L608
|
6,963
|
ethantw/Han
|
src/js/locale/h-ruby.js
|
renderSimpleRuby
|
function renderSimpleRuby( $ruby ) {
var frag = $.create( '!' )
var clazz = $ruby.classList
var $rb, $ru
frag.appendChild( $.clone( $ruby ))
$
.tag( 'rt', frag.firstChild )
.forEach(function( $rt ) {
var $rb = $.create( '!' )
var airb = []
var irb
// Consider the previous nodes the implied
// ruby base
do {
irb = ( irb || $rt ).previousSibling
if ( !irb || irb.nodeName.match( /((?:h\-)?r[ubt])/i )) break
$rb.insertBefore( $.clone( irb ), $rb.firstChild )
airb.push( irb )
} while ( !irb.nodeName.match( /((?:h\-)?r[ubt])/i ))
// Create a real `<h-ru>` to append.
$ru = clazz.contains( 'zhuyin' ) ? createZhuyinRu( $rb, $rt ) : createNormalRu( $rb, $rt )
// Replace the ruby text with the new `<h-ru>`,
// and remove the original implied ruby base(s)
try {
$rt.parentNode.replaceChild( $ru, $rt )
airb.map( $.remove )
} catch ( e ) {}
})
return createCustomRuby( frag )
}
|
javascript
|
function renderSimpleRuby( $ruby ) {
var frag = $.create( '!' )
var clazz = $ruby.classList
var $rb, $ru
frag.appendChild( $.clone( $ruby ))
$
.tag( 'rt', frag.firstChild )
.forEach(function( $rt ) {
var $rb = $.create( '!' )
var airb = []
var irb
// Consider the previous nodes the implied
// ruby base
do {
irb = ( irb || $rt ).previousSibling
if ( !irb || irb.nodeName.match( /((?:h\-)?r[ubt])/i )) break
$rb.insertBefore( $.clone( irb ), $rb.firstChild )
airb.push( irb )
} while ( !irb.nodeName.match( /((?:h\-)?r[ubt])/i ))
// Create a real `<h-ru>` to append.
$ru = clazz.contains( 'zhuyin' ) ? createZhuyinRu( $rb, $rt ) : createNormalRu( $rb, $rt )
// Replace the ruby text with the new `<h-ru>`,
// and remove the original implied ruby base(s)
try {
$rt.parentNode.replaceChild( $ru, $rt )
airb.map( $.remove )
} catch ( e ) {}
})
return createCustomRuby( frag )
}
|
[
"function",
"renderSimpleRuby",
"(",
"$ruby",
")",
"{",
"var",
"frag",
"=",
"$",
".",
"create",
"(",
"'!'",
")",
"var",
"clazz",
"=",
"$ruby",
".",
"classList",
"var",
"$rb",
",",
"$ru",
"frag",
".",
"appendChild",
"(",
"$",
".",
"clone",
"(",
"$ruby",
")",
")",
"$",
".",
"tag",
"(",
"'rt'",
",",
"frag",
".",
"firstChild",
")",
".",
"forEach",
"(",
"function",
"(",
"$rt",
")",
"{",
"var",
"$rb",
"=",
"$",
".",
"create",
"(",
"'!'",
")",
"var",
"airb",
"=",
"[",
"]",
"var",
"irb",
"// Consider the previous nodes the implied",
"// ruby base",
"do",
"{",
"irb",
"=",
"(",
"irb",
"||",
"$rt",
")",
".",
"previousSibling",
"if",
"(",
"!",
"irb",
"||",
"irb",
".",
"nodeName",
".",
"match",
"(",
"/",
"((?:h\\-)?r[ubt])",
"/",
"i",
")",
")",
"break",
"$rb",
".",
"insertBefore",
"(",
"$",
".",
"clone",
"(",
"irb",
")",
",",
"$rb",
".",
"firstChild",
")",
"airb",
".",
"push",
"(",
"irb",
")",
"}",
"while",
"(",
"!",
"irb",
".",
"nodeName",
".",
"match",
"(",
"/",
"((?:h\\-)?r[ubt])",
"/",
"i",
")",
")",
"// Create a real `<h-ru>` to append.",
"$ru",
"=",
"clazz",
".",
"contains",
"(",
"'zhuyin'",
")",
"?",
"createZhuyinRu",
"(",
"$rb",
",",
"$rt",
")",
":",
"createNormalRu",
"(",
"$rb",
",",
"$rt",
")",
"// Replace the ruby text with the new `<h-ru>`,",
"// and remove the original implied ruby base(s)",
"try",
"{",
"$rt",
".",
"parentNode",
".",
"replaceChild",
"(",
"$ru",
",",
"$rt",
")",
"airb",
".",
"map",
"(",
"$",
".",
"remove",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"}",
")",
"return",
"createCustomRuby",
"(",
"frag",
")",
"}"
] |
1. Simple ruby polyfill; 2. Inter-character polyfill for Zhuyin
|
[
"1",
".",
"Simple",
"ruby",
"polyfill",
";",
"2",
".",
"Inter",
"-",
"character",
"polyfill",
"for",
"Zhuyin"
] |
940014b48dded1eaa7fa92fa5a09d9cfc96429a9
|
https://github.com/ethantw/Han/blob/940014b48dded1eaa7fa92fa5a09d9cfc96429a9/src/js/locale/h-ruby.js#L11-L46
|
6,964
|
ethantw/Han
|
src/js/locale/h-ruby.js
|
renderComplexRuby
|
function renderComplexRuby( $ruby ) {
var frag = $.create( '!' )
var clazz = $ruby.classList
var $cloned, $rb, $ru, maxspan
frag.appendChild( $.clone( $ruby ))
$cloned = frag.firstChild
$rb = $ru = $.tag( 'rb', $cloned )
maxspan = $rb.length
// First of all, deal with Zhuyin containers
// individually
//
// Note that we only support one single Zhuyin
// container in each complex ruby
void function( $rtc ) {
if ( !$rtc ) return
$ru = $
.tag( 'rt', $rtc )
.map(function( $rt, i ) {
if ( !$rb[ i ] ) return
var ret = createZhuyinRu( $rb[ i ], $rt )
try {
$rb[ i ].parentNode.replaceChild( ret, $rb[ i ] )
} catch ( e ) {}
return ret
})
// Remove the container once it's useless
$.remove( $rtc )
$cloned.setAttribute( 'rightangle', 'true' )
}( $cloned.querySelector( 'rtc.zhuyin' ))
// Then, normal annotations other than Zhuyin
$
.qsa( 'rtc:not(.zhuyin)', $cloned )
.forEach(function( $rtc, order ) {
var ret
ret = $
.tag( 'rt', $rtc )
.map(function( $rt, i ) {
var rbspan = Number( $rt.getAttribute( 'rbspan' ) || 1 )
var span = 0
var aRb = []
var $rb, ret
if ( rbspan > maxspan ) rbspan = maxspan
do {
try {
$rb = $ru.shift()
aRb.push( $rb )
} catch (e) {}
if ( typeof $rb === 'undefined' ) break
span += Number( $rb.getAttribute( 'span' ) || 1 )
} while ( rbspan > span )
if ( rbspan < span ) {
if ( aRb.length > 1 ) {
console.error( 'An impossible `rbspan` value detected.', ruby )
return
}
aRb = $.tag( 'rb', aRb[0] )
$ru = aRb.slice( rbspan ).concat( $ru )
aRb = aRb.slice( 0, rbspan )
span = rbspan
}
ret = createNormalRu( aRb, $rt, {
'class': clazz,
span: span,
order: order
})
try {
aRb[0].parentNode.replaceChild( ret, aRb.shift() )
aRb.map( $.remove )
} catch (e) {}
return ret
})
$ru = ret
if ( order === 1 ) $cloned.setAttribute( 'doubleline', 'true' )
// Remove the container once it's useless
$.remove( $rtc )
})
return createCustomRuby( frag )
}
|
javascript
|
function renderComplexRuby( $ruby ) {
var frag = $.create( '!' )
var clazz = $ruby.classList
var $cloned, $rb, $ru, maxspan
frag.appendChild( $.clone( $ruby ))
$cloned = frag.firstChild
$rb = $ru = $.tag( 'rb', $cloned )
maxspan = $rb.length
// First of all, deal with Zhuyin containers
// individually
//
// Note that we only support one single Zhuyin
// container in each complex ruby
void function( $rtc ) {
if ( !$rtc ) return
$ru = $
.tag( 'rt', $rtc )
.map(function( $rt, i ) {
if ( !$rb[ i ] ) return
var ret = createZhuyinRu( $rb[ i ], $rt )
try {
$rb[ i ].parentNode.replaceChild( ret, $rb[ i ] )
} catch ( e ) {}
return ret
})
// Remove the container once it's useless
$.remove( $rtc )
$cloned.setAttribute( 'rightangle', 'true' )
}( $cloned.querySelector( 'rtc.zhuyin' ))
// Then, normal annotations other than Zhuyin
$
.qsa( 'rtc:not(.zhuyin)', $cloned )
.forEach(function( $rtc, order ) {
var ret
ret = $
.tag( 'rt', $rtc )
.map(function( $rt, i ) {
var rbspan = Number( $rt.getAttribute( 'rbspan' ) || 1 )
var span = 0
var aRb = []
var $rb, ret
if ( rbspan > maxspan ) rbspan = maxspan
do {
try {
$rb = $ru.shift()
aRb.push( $rb )
} catch (e) {}
if ( typeof $rb === 'undefined' ) break
span += Number( $rb.getAttribute( 'span' ) || 1 )
} while ( rbspan > span )
if ( rbspan < span ) {
if ( aRb.length > 1 ) {
console.error( 'An impossible `rbspan` value detected.', ruby )
return
}
aRb = $.tag( 'rb', aRb[0] )
$ru = aRb.slice( rbspan ).concat( $ru )
aRb = aRb.slice( 0, rbspan )
span = rbspan
}
ret = createNormalRu( aRb, $rt, {
'class': clazz,
span: span,
order: order
})
try {
aRb[0].parentNode.replaceChild( ret, aRb.shift() )
aRb.map( $.remove )
} catch (e) {}
return ret
})
$ru = ret
if ( order === 1 ) $cloned.setAttribute( 'doubleline', 'true' )
// Remove the container once it's useless
$.remove( $rtc )
})
return createCustomRuby( frag )
}
|
[
"function",
"renderComplexRuby",
"(",
"$ruby",
")",
"{",
"var",
"frag",
"=",
"$",
".",
"create",
"(",
"'!'",
")",
"var",
"clazz",
"=",
"$ruby",
".",
"classList",
"var",
"$cloned",
",",
"$rb",
",",
"$ru",
",",
"maxspan",
"frag",
".",
"appendChild",
"(",
"$",
".",
"clone",
"(",
"$ruby",
")",
")",
"$cloned",
"=",
"frag",
".",
"firstChild",
"$rb",
"=",
"$ru",
"=",
"$",
".",
"tag",
"(",
"'rb'",
",",
"$cloned",
")",
"maxspan",
"=",
"$rb",
".",
"length",
"// First of all, deal with Zhuyin containers",
"// individually",
"//",
"// Note that we only support one single Zhuyin",
"// container in each complex ruby",
"void",
"function",
"(",
"$rtc",
")",
"{",
"if",
"(",
"!",
"$rtc",
")",
"return",
"$ru",
"=",
"$",
".",
"tag",
"(",
"'rt'",
",",
"$rtc",
")",
".",
"map",
"(",
"function",
"(",
"$rt",
",",
"i",
")",
"{",
"if",
"(",
"!",
"$rb",
"[",
"i",
"]",
")",
"return",
"var",
"ret",
"=",
"createZhuyinRu",
"(",
"$rb",
"[",
"i",
"]",
",",
"$rt",
")",
"try",
"{",
"$rb",
"[",
"i",
"]",
".",
"parentNode",
".",
"replaceChild",
"(",
"ret",
",",
"$rb",
"[",
"i",
"]",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"return",
"ret",
"}",
")",
"// Remove the container once it's useless",
"$",
".",
"remove",
"(",
"$rtc",
")",
"$cloned",
".",
"setAttribute",
"(",
"'rightangle'",
",",
"'true'",
")",
"}",
"(",
"$cloned",
".",
"querySelector",
"(",
"'rtc.zhuyin'",
")",
")",
"// Then, normal annotations other than Zhuyin",
"$",
".",
"qsa",
"(",
"'rtc:not(.zhuyin)'",
",",
"$cloned",
")",
".",
"forEach",
"(",
"function",
"(",
"$rtc",
",",
"order",
")",
"{",
"var",
"ret",
"ret",
"=",
"$",
".",
"tag",
"(",
"'rt'",
",",
"$rtc",
")",
".",
"map",
"(",
"function",
"(",
"$rt",
",",
"i",
")",
"{",
"var",
"rbspan",
"=",
"Number",
"(",
"$rt",
".",
"getAttribute",
"(",
"'rbspan'",
")",
"||",
"1",
")",
"var",
"span",
"=",
"0",
"var",
"aRb",
"=",
"[",
"]",
"var",
"$rb",
",",
"ret",
"if",
"(",
"rbspan",
">",
"maxspan",
")",
"rbspan",
"=",
"maxspan",
"do",
"{",
"try",
"{",
"$rb",
"=",
"$ru",
".",
"shift",
"(",
")",
"aRb",
".",
"push",
"(",
"$rb",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"if",
"(",
"typeof",
"$rb",
"===",
"'undefined'",
")",
"break",
"span",
"+=",
"Number",
"(",
"$rb",
".",
"getAttribute",
"(",
"'span'",
")",
"||",
"1",
")",
"}",
"while",
"(",
"rbspan",
">",
"span",
")",
"if",
"(",
"rbspan",
"<",
"span",
")",
"{",
"if",
"(",
"aRb",
".",
"length",
">",
"1",
")",
"{",
"console",
".",
"error",
"(",
"'An impossible `rbspan` value detected.'",
",",
"ruby",
")",
"return",
"}",
"aRb",
"=",
"$",
".",
"tag",
"(",
"'rb'",
",",
"aRb",
"[",
"0",
"]",
")",
"$ru",
"=",
"aRb",
".",
"slice",
"(",
"rbspan",
")",
".",
"concat",
"(",
"$ru",
")",
"aRb",
"=",
"aRb",
".",
"slice",
"(",
"0",
",",
"rbspan",
")",
"span",
"=",
"rbspan",
"}",
"ret",
"=",
"createNormalRu",
"(",
"aRb",
",",
"$rt",
",",
"{",
"'class'",
":",
"clazz",
",",
"span",
":",
"span",
",",
"order",
":",
"order",
"}",
")",
"try",
"{",
"aRb",
"[",
"0",
"]",
".",
"parentNode",
".",
"replaceChild",
"(",
"ret",
",",
"aRb",
".",
"shift",
"(",
")",
")",
"aRb",
".",
"map",
"(",
"$",
".",
"remove",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"return",
"ret",
"}",
")",
"$ru",
"=",
"ret",
"if",
"(",
"order",
"===",
"1",
")",
"$cloned",
".",
"setAttribute",
"(",
"'doubleline'",
",",
"'true'",
")",
"// Remove the container once it's useless",
"$",
".",
"remove",
"(",
"$rtc",
")",
"}",
")",
"return",
"createCustomRuby",
"(",
"frag",
")",
"}"
] |
3. Complex ruby polyfill - Double-lined annotation; - Right-angled annotation.
|
[
"3",
".",
"Complex",
"ruby",
"polyfill",
"-",
"Double",
"-",
"lined",
"annotation",
";",
"-",
"Right",
"-",
"angled",
"annotation",
"."
] |
940014b48dded1eaa7fa92fa5a09d9cfc96429a9
|
https://github.com/ethantw/Han/blob/940014b48dded1eaa7fa92fa5a09d9cfc96429a9/src/js/locale/h-ruby.js#L79-L170
|
6,965
|
ethantw/Han
|
src/js/locale/h-ruby.js
|
getZhuyinHTML
|
function getZhuyinHTML( rt ) {
// #### Explanation ####
// * `zhuyin`: the entire phonetic annotation
// * `yin`: the plain pronunciation (w/out tone)
// * `diao`: the tone
// * `len`: the length of the plain pronunciation (`yin`)
var zhuyin = typeof rt === 'string' ? rt : rt.textContent
var yin, diao, len
yin = zhuyin.replace( TYPESET.zhuyin.diao, '' )
len = yin ? yin.length : 0
diao = zhuyin
.replace( yin, '' )
.replace( /[\u02C5]/g, '\u02C7' )
.replace( /[\u030D\u0358]/g, '\u0307' )
return len === 0 ? '' : '<h-zhuyin length="' + len + '" diao="' + diao + '"><h-yin>' + yin + '</h-yin><h-diao>' + diao + '</h-diao></h-zhuyin>'
}
|
javascript
|
function getZhuyinHTML( rt ) {
// #### Explanation ####
// * `zhuyin`: the entire phonetic annotation
// * `yin`: the plain pronunciation (w/out tone)
// * `diao`: the tone
// * `len`: the length of the plain pronunciation (`yin`)
var zhuyin = typeof rt === 'string' ? rt : rt.textContent
var yin, diao, len
yin = zhuyin.replace( TYPESET.zhuyin.diao, '' )
len = yin ? yin.length : 0
diao = zhuyin
.replace( yin, '' )
.replace( /[\u02C5]/g, '\u02C7' )
.replace( /[\u030D\u0358]/g, '\u0307' )
return len === 0 ? '' : '<h-zhuyin length="' + len + '" diao="' + diao + '"><h-yin>' + yin + '</h-yin><h-diao>' + diao + '</h-diao></h-zhuyin>'
}
|
[
"function",
"getZhuyinHTML",
"(",
"rt",
")",
"{",
"// #### Explanation ####",
"// * `zhuyin`: the entire phonetic annotation",
"// * `yin`: the plain pronunciation (w/out tone)",
"// * `diao`: the tone",
"// * `len`: the length of the plain pronunciation (`yin`)",
"var",
"zhuyin",
"=",
"typeof",
"rt",
"===",
"'string'",
"?",
"rt",
":",
"rt",
".",
"textContent",
"var",
"yin",
",",
"diao",
",",
"len",
"yin",
"=",
"zhuyin",
".",
"replace",
"(",
"TYPESET",
".",
"zhuyin",
".",
"diao",
",",
"''",
")",
"len",
"=",
"yin",
"?",
"yin",
".",
"length",
":",
"0",
"diao",
"=",
"zhuyin",
".",
"replace",
"(",
"yin",
",",
"''",
")",
".",
"replace",
"(",
"/",
"[\\u02C5]",
"/",
"g",
",",
"'\\u02C7'",
")",
".",
"replace",
"(",
"/",
"[\\u030D\\u0358]",
"/",
"g",
",",
"'\\u0307'",
")",
"return",
"len",
"===",
"0",
"?",
"''",
":",
"'<h-zhuyin length=\"'",
"+",
"len",
"+",
"'\" diao=\"'",
"+",
"diao",
"+",
"'\"><h-yin>'",
"+",
"yin",
"+",
"'</h-yin><h-diao>'",
"+",
"diao",
"+",
"'</h-diao></h-zhuyin>'",
"}"
] |
Create a Zhuyin-form HTML string
|
[
"Create",
"a",
"Zhuyin",
"-",
"form",
"HTML",
"string"
] |
940014b48dded1eaa7fa92fa5a09d9cfc96429a9
|
https://github.com/ethantw/Han/blob/940014b48dded1eaa7fa92fa5a09d9cfc96429a9/src/js/locale/h-ruby.js#L246-L262
|
6,966
|
ethantw/Han
|
src/js/method.js
|
function( target, attr ) {
if ( typeof attr !== 'object' ) return
var len = attr.length
// Native `NamedNodeMap``:
if (
typeof attr[0] === 'object' &&
'name' in attr[0]
) {
for ( var i = 0; i < len; i++ ) {
if ( attr[ i ].value !== undefined ) {
target.setAttribute( attr[ i ].name, attr[ i ].value )
}
}
// Plain object:
} else {
for ( var name in attr ) {
if (
attr.hasOwnProperty( name ) &&
attr[ name ] !== undefined
) {
target.setAttribute( name, attr[ name ] )
}
}
}
return target
}
|
javascript
|
function( target, attr ) {
if ( typeof attr !== 'object' ) return
var len = attr.length
// Native `NamedNodeMap``:
if (
typeof attr[0] === 'object' &&
'name' in attr[0]
) {
for ( var i = 0; i < len; i++ ) {
if ( attr[ i ].value !== undefined ) {
target.setAttribute( attr[ i ].name, attr[ i ].value )
}
}
// Plain object:
} else {
for ( var name in attr ) {
if (
attr.hasOwnProperty( name ) &&
attr[ name ] !== undefined
) {
target.setAttribute( name, attr[ name ] )
}
}
}
return target
}
|
[
"function",
"(",
"target",
",",
"attr",
")",
"{",
"if",
"(",
"typeof",
"attr",
"!==",
"'object'",
")",
"return",
"var",
"len",
"=",
"attr",
".",
"length",
"// Native `NamedNodeMap``:",
"if",
"(",
"typeof",
"attr",
"[",
"0",
"]",
"===",
"'object'",
"&&",
"'name'",
"in",
"attr",
"[",
"0",
"]",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"attr",
"[",
"i",
"]",
".",
"value",
"!==",
"undefined",
")",
"{",
"target",
".",
"setAttribute",
"(",
"attr",
"[",
"i",
"]",
".",
"name",
",",
"attr",
"[",
"i",
"]",
".",
"value",
")",
"}",
"}",
"// Plain object:",
"}",
"else",
"{",
"for",
"(",
"var",
"name",
"in",
"attr",
")",
"{",
"if",
"(",
"attr",
".",
"hasOwnProperty",
"(",
"name",
")",
"&&",
"attr",
"[",
"name",
"]",
"!==",
"undefined",
")",
"{",
"target",
".",
"setAttribute",
"(",
"name",
",",
"attr",
"[",
"name",
"]",
")",
"}",
"}",
"}",
"return",
"target",
"}"
] |
Set attributes all in once with an object.
|
[
"Set",
"attributes",
"all",
"in",
"once",
"with",
"an",
"object",
"."
] |
940014b48dded1eaa7fa92fa5a09d9cfc96429a9
|
https://github.com/ethantw/Han/blob/940014b48dded1eaa7fa92fa5a09d9cfc96429a9/src/js/method.js#L91-L118
|
|
6,967
|
ethantw/Han
|
src/js/method.js
|
function( target, object ) {
if ((
typeof target === 'object' ||
typeof target === 'function' ) &&
typeof object === 'object'
) {
for ( var name in object ) {
if (object.hasOwnProperty( name )) {
target[ name ] = object[ name ]
}
}
}
return target
}
|
javascript
|
function( target, object ) {
if ((
typeof target === 'object' ||
typeof target === 'function' ) &&
typeof object === 'object'
) {
for ( var name in object ) {
if (object.hasOwnProperty( name )) {
target[ name ] = object[ name ]
}
}
}
return target
}
|
[
"function",
"(",
"target",
",",
"object",
")",
"{",
"if",
"(",
"(",
"typeof",
"target",
"===",
"'object'",
"||",
"typeof",
"target",
"===",
"'function'",
")",
"&&",
"typeof",
"object",
"===",
"'object'",
")",
"{",
"for",
"(",
"var",
"name",
"in",
"object",
")",
"{",
"if",
"(",
"object",
".",
"hasOwnProperty",
"(",
"name",
")",
")",
"{",
"target",
"[",
"name",
"]",
"=",
"object",
"[",
"name",
"]",
"}",
"}",
"}",
"return",
"target",
"}"
] |
Extend target with an object.
|
[
"Extend",
"target",
"with",
"an",
"object",
"."
] |
940014b48dded1eaa7fa92fa5a09d9cfc96429a9
|
https://github.com/ethantw/Han/blob/940014b48dded1eaa7fa92fa5a09d9cfc96429a9/src/js/method.js#L151-L164
|
|
6,968
|
ethantw/Han
|
src/lib/fibre.js/index.js
|
function() {
var match
var matchIndex = 0
var offset = 0
var regex = this.options.find
var textAggregation = this.getAggregateText()
var matches = []
var self = this
regex = typeof regex === 'string' ? RegExp(escapeRegExp(regex), 'g') : regex
matchAggregation(textAggregation)
function matchAggregation(textAggregation) {
for (var i = 0, l = textAggregation.length; i < l; ++i) {
var text = textAggregation[i]
if (typeof text !== 'string') {
// Deal with nested contexts: (recursive)
matchAggregation(text)
continue
}
if (regex.global) {
while (match = regex.exec(text)) {
matches.push(self.prepMatch(match, matchIndex++, offset))
}
} else {
if (match = text.match(regex)) {
matches.push(self.prepMatch(match, 0, offset))
}
}
offset += text.length
}
}
return matches
}
|
javascript
|
function() {
var match
var matchIndex = 0
var offset = 0
var regex = this.options.find
var textAggregation = this.getAggregateText()
var matches = []
var self = this
regex = typeof regex === 'string' ? RegExp(escapeRegExp(regex), 'g') : regex
matchAggregation(textAggregation)
function matchAggregation(textAggregation) {
for (var i = 0, l = textAggregation.length; i < l; ++i) {
var text = textAggregation[i]
if (typeof text !== 'string') {
// Deal with nested contexts: (recursive)
matchAggregation(text)
continue
}
if (regex.global) {
while (match = regex.exec(text)) {
matches.push(self.prepMatch(match, matchIndex++, offset))
}
} else {
if (match = text.match(regex)) {
matches.push(self.prepMatch(match, 0, offset))
}
}
offset += text.length
}
}
return matches
}
|
[
"function",
"(",
")",
"{",
"var",
"match",
"var",
"matchIndex",
"=",
"0",
"var",
"offset",
"=",
"0",
"var",
"regex",
"=",
"this",
".",
"options",
".",
"find",
"var",
"textAggregation",
"=",
"this",
".",
"getAggregateText",
"(",
")",
"var",
"matches",
"=",
"[",
"]",
"var",
"self",
"=",
"this",
"regex",
"=",
"typeof",
"regex",
"===",
"'string'",
"?",
"RegExp",
"(",
"escapeRegExp",
"(",
"regex",
")",
",",
"'g'",
")",
":",
"regex",
"matchAggregation",
"(",
"textAggregation",
")",
"function",
"matchAggregation",
"(",
"textAggregation",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"textAggregation",
".",
"length",
";",
"i",
"<",
"l",
";",
"++",
"i",
")",
"{",
"var",
"text",
"=",
"textAggregation",
"[",
"i",
"]",
"if",
"(",
"typeof",
"text",
"!==",
"'string'",
")",
"{",
"// Deal with nested contexts: (recursive)",
"matchAggregation",
"(",
"text",
")",
"continue",
"}",
"if",
"(",
"regex",
".",
"global",
")",
"{",
"while",
"(",
"match",
"=",
"regex",
".",
"exec",
"(",
"text",
")",
")",
"{",
"matches",
".",
"push",
"(",
"self",
".",
"prepMatch",
"(",
"match",
",",
"matchIndex",
"++",
",",
"offset",
")",
")",
"}",
"}",
"else",
"{",
"if",
"(",
"match",
"=",
"text",
".",
"match",
"(",
"regex",
")",
")",
"{",
"matches",
".",
"push",
"(",
"self",
".",
"prepMatch",
"(",
"match",
",",
"0",
",",
"offset",
")",
")",
"}",
"}",
"offset",
"+=",
"text",
".",
"length",
"}",
"}",
"return",
"matches",
"}"
] |
Searches for all matches that comply with the instance's 'match' option
|
[
"Searches",
"for",
"all",
"matches",
"that",
"comply",
"with",
"the",
"instance",
"s",
"match",
"option"
] |
940014b48dded1eaa7fa92fa5a09d9cfc96429a9
|
https://github.com/ethantw/Han/blob/940014b48dded1eaa7fa92fa5a09d9cfc96429a9/src/lib/fibre.js/index.js#L368-L404
|
|
6,969
|
ethantw/Han
|
src/lib/fibre.js/index.js
|
function() {
var elementFilter = this.options.filterElements
var forceContext = this.options.forceContext
return getText(this.node)
/**
* Gets aggregate text of a node without resorting
* to broken innerText/textContent
*/
function getText(node, txt) {
if (node.nodeType === 3) {
return [node.data]
}
if (elementFilter && !elementFilter(node)) {
return []
}
var txt = ['']
var i = 0
if (node = node.firstChild) do {
if (node.nodeType === 3) {
txt[i] += node.data
continue
}
var innerText = getText(node)
if (
forceContext &&
node.nodeType === 1 &&
(forceContext === true || forceContext(node))
) {
txt[++i] = innerText
txt[++i] = ''
} else {
if (typeof innerText[0] === 'string') {
// Bridge nested text-node data so that they're
// not considered their own contexts:
// I.e. ['some', ['thing']] -> ['something']
txt[i] += innerText.shift()
}
if (innerText.length) {
txt[++i] = innerText
txt[++i] = ''
}
}
} while (node = node.nextSibling)
return txt
}
}
|
javascript
|
function() {
var elementFilter = this.options.filterElements
var forceContext = this.options.forceContext
return getText(this.node)
/**
* Gets aggregate text of a node without resorting
* to broken innerText/textContent
*/
function getText(node, txt) {
if (node.nodeType === 3) {
return [node.data]
}
if (elementFilter && !elementFilter(node)) {
return []
}
var txt = ['']
var i = 0
if (node = node.firstChild) do {
if (node.nodeType === 3) {
txt[i] += node.data
continue
}
var innerText = getText(node)
if (
forceContext &&
node.nodeType === 1 &&
(forceContext === true || forceContext(node))
) {
txt[++i] = innerText
txt[++i] = ''
} else {
if (typeof innerText[0] === 'string') {
// Bridge nested text-node data so that they're
// not considered their own contexts:
// I.e. ['some', ['thing']] -> ['something']
txt[i] += innerText.shift()
}
if (innerText.length) {
txt[++i] = innerText
txt[++i] = ''
}
}
} while (node = node.nextSibling)
return txt
}
}
|
[
"function",
"(",
")",
"{",
"var",
"elementFilter",
"=",
"this",
".",
"options",
".",
"filterElements",
"var",
"forceContext",
"=",
"this",
".",
"options",
".",
"forceContext",
"return",
"getText",
"(",
"this",
".",
"node",
")",
"/**\n * Gets aggregate text of a node without resorting\n * to broken innerText/textContent\n */",
"function",
"getText",
"(",
"node",
",",
"txt",
")",
"{",
"if",
"(",
"node",
".",
"nodeType",
"===",
"3",
")",
"{",
"return",
"[",
"node",
".",
"data",
"]",
"}",
"if",
"(",
"elementFilter",
"&&",
"!",
"elementFilter",
"(",
"node",
")",
")",
"{",
"return",
"[",
"]",
"}",
"var",
"txt",
"=",
"[",
"''",
"]",
"var",
"i",
"=",
"0",
"if",
"(",
"node",
"=",
"node",
".",
"firstChild",
")",
"do",
"{",
"if",
"(",
"node",
".",
"nodeType",
"===",
"3",
")",
"{",
"txt",
"[",
"i",
"]",
"+=",
"node",
".",
"data",
"continue",
"}",
"var",
"innerText",
"=",
"getText",
"(",
"node",
")",
"if",
"(",
"forceContext",
"&&",
"node",
".",
"nodeType",
"===",
"1",
"&&",
"(",
"forceContext",
"===",
"true",
"||",
"forceContext",
"(",
"node",
")",
")",
")",
"{",
"txt",
"[",
"++",
"i",
"]",
"=",
"innerText",
"txt",
"[",
"++",
"i",
"]",
"=",
"''",
"}",
"else",
"{",
"if",
"(",
"typeof",
"innerText",
"[",
"0",
"]",
"===",
"'string'",
")",
"{",
"// Bridge nested text-node data so that they're",
"// not considered their own contexts:",
"// I.e. ['some', ['thing']] -> ['something']",
"txt",
"[",
"i",
"]",
"+=",
"innerText",
".",
"shift",
"(",
")",
"}",
"if",
"(",
"innerText",
".",
"length",
")",
"{",
"txt",
"[",
"++",
"i",
"]",
"=",
"innerText",
"txt",
"[",
"++",
"i",
"]",
"=",
"''",
"}",
"}",
"}",
"while",
"(",
"node",
"=",
"node",
".",
"nextSibling",
")",
"return",
"txt",
"}",
"}"
] |
Gets aggregate text within subject node
|
[
"Gets",
"aggregate",
"text",
"within",
"subject",
"node"
] |
940014b48dded1eaa7fa92fa5a09d9cfc96429a9
|
https://github.com/ethantw/Han/blob/940014b48dded1eaa7fa92fa5a09d9cfc96429a9/src/lib/fibre.js/index.js#L424-L476
|
|
6,970
|
ethantw/Han
|
src/lib/fibre.js/index.js
|
function() {
var matches = this.matches
var node = this.node
var elementFilter = this.options.filterElements
var startPortion,
endPortion,
innerPortions = [],
curNode = node,
match = matches.shift(),
atIndex = 0, // i.e. nodeAtIndex
matchIndex = 0,
portionIndex = 0,
doAvoidNode,
nodeStack = [node]
out: while (true) {
if (curNode.nodeType === 3) {
if (!endPortion && curNode.length + atIndex >= match.endIndex) {
// We've found the ending
endPortion = {
node: curNode,
index: portionIndex++,
text: curNode.data.substring(match.startIndex - atIndex, match.endIndex - atIndex),
indexInMatch: atIndex - match.startIndex,
indexInNode: match.startIndex - atIndex, // always zero for end-portions
endIndexInNode: match.endIndex - atIndex,
isEnd: true
}
} else if (startPortion) {
// Intersecting node
innerPortions.push({
node: curNode,
index: portionIndex++,
text: curNode.data,
indexInMatch: atIndex - match.startIndex,
indexInNode: 0 // always zero for inner-portions
})
}
if (!startPortion && curNode.length + atIndex > match.startIndex) {
// We've found the match start
startPortion = {
node: curNode,
index: portionIndex++,
indexInMatch: 0,
indexInNode: match.startIndex - atIndex,
endIndexInNode: match.endIndex - atIndex,
text: curNode.data.substring(match.startIndex - atIndex, match.endIndex - atIndex)
}
}
atIndex += curNode.data.length
}
doAvoidNode = curNode.nodeType === 1 && elementFilter && !elementFilter(curNode)
if (startPortion && endPortion) {
curNode = this.replaceMatch(match, startPortion, innerPortions, endPortion)
// processMatches has to return the node that replaced the endNode
// and then we step back so we can continue from the end of the
// match:
atIndex -= (endPortion.node.data.length - endPortion.endIndexInNode)
startPortion = null
endPortion = null
innerPortions = []
match = matches.shift()
portionIndex = 0
matchIndex++
if (!match) {
break; // no more matches
}
} else if (
!doAvoidNode &&
(curNode.firstChild || curNode.nextSibling)
) {
// Move down or forward:
if (curNode.firstChild) {
nodeStack.push(curNode)
curNode = curNode.firstChild
} else {
curNode = curNode.nextSibling
}
continue
}
// Move forward or up:
while (true) {
if (curNode.nextSibling) {
curNode = curNode.nextSibling
break
}
curNode = nodeStack.pop()
if (curNode === node) {
break out
}
}
}
}
|
javascript
|
function() {
var matches = this.matches
var node = this.node
var elementFilter = this.options.filterElements
var startPortion,
endPortion,
innerPortions = [],
curNode = node,
match = matches.shift(),
atIndex = 0, // i.e. nodeAtIndex
matchIndex = 0,
portionIndex = 0,
doAvoidNode,
nodeStack = [node]
out: while (true) {
if (curNode.nodeType === 3) {
if (!endPortion && curNode.length + atIndex >= match.endIndex) {
// We've found the ending
endPortion = {
node: curNode,
index: portionIndex++,
text: curNode.data.substring(match.startIndex - atIndex, match.endIndex - atIndex),
indexInMatch: atIndex - match.startIndex,
indexInNode: match.startIndex - atIndex, // always zero for end-portions
endIndexInNode: match.endIndex - atIndex,
isEnd: true
}
} else if (startPortion) {
// Intersecting node
innerPortions.push({
node: curNode,
index: portionIndex++,
text: curNode.data,
indexInMatch: atIndex - match.startIndex,
indexInNode: 0 // always zero for inner-portions
})
}
if (!startPortion && curNode.length + atIndex > match.startIndex) {
// We've found the match start
startPortion = {
node: curNode,
index: portionIndex++,
indexInMatch: 0,
indexInNode: match.startIndex - atIndex,
endIndexInNode: match.endIndex - atIndex,
text: curNode.data.substring(match.startIndex - atIndex, match.endIndex - atIndex)
}
}
atIndex += curNode.data.length
}
doAvoidNode = curNode.nodeType === 1 && elementFilter && !elementFilter(curNode)
if (startPortion && endPortion) {
curNode = this.replaceMatch(match, startPortion, innerPortions, endPortion)
// processMatches has to return the node that replaced the endNode
// and then we step back so we can continue from the end of the
// match:
atIndex -= (endPortion.node.data.length - endPortion.endIndexInNode)
startPortion = null
endPortion = null
innerPortions = []
match = matches.shift()
portionIndex = 0
matchIndex++
if (!match) {
break; // no more matches
}
} else if (
!doAvoidNode &&
(curNode.firstChild || curNode.nextSibling)
) {
// Move down or forward:
if (curNode.firstChild) {
nodeStack.push(curNode)
curNode = curNode.firstChild
} else {
curNode = curNode.nextSibling
}
continue
}
// Move forward or up:
while (true) {
if (curNode.nextSibling) {
curNode = curNode.nextSibling
break
}
curNode = nodeStack.pop()
if (curNode === node) {
break out
}
}
}
}
|
[
"function",
"(",
")",
"{",
"var",
"matches",
"=",
"this",
".",
"matches",
"var",
"node",
"=",
"this",
".",
"node",
"var",
"elementFilter",
"=",
"this",
".",
"options",
".",
"filterElements",
"var",
"startPortion",
",",
"endPortion",
",",
"innerPortions",
"=",
"[",
"]",
",",
"curNode",
"=",
"node",
",",
"match",
"=",
"matches",
".",
"shift",
"(",
")",
",",
"atIndex",
"=",
"0",
",",
"// i.e. nodeAtIndex",
"matchIndex",
"=",
"0",
",",
"portionIndex",
"=",
"0",
",",
"doAvoidNode",
",",
"nodeStack",
"=",
"[",
"node",
"]",
"out",
":",
"while",
"(",
"true",
")",
"{",
"if",
"(",
"curNode",
".",
"nodeType",
"===",
"3",
")",
"{",
"if",
"(",
"!",
"endPortion",
"&&",
"curNode",
".",
"length",
"+",
"atIndex",
">=",
"match",
".",
"endIndex",
")",
"{",
"// We've found the ending",
"endPortion",
"=",
"{",
"node",
":",
"curNode",
",",
"index",
":",
"portionIndex",
"++",
",",
"text",
":",
"curNode",
".",
"data",
".",
"substring",
"(",
"match",
".",
"startIndex",
"-",
"atIndex",
",",
"match",
".",
"endIndex",
"-",
"atIndex",
")",
",",
"indexInMatch",
":",
"atIndex",
"-",
"match",
".",
"startIndex",
",",
"indexInNode",
":",
"match",
".",
"startIndex",
"-",
"atIndex",
",",
"// always zero for end-portions",
"endIndexInNode",
":",
"match",
".",
"endIndex",
"-",
"atIndex",
",",
"isEnd",
":",
"true",
"}",
"}",
"else",
"if",
"(",
"startPortion",
")",
"{",
"// Intersecting node",
"innerPortions",
".",
"push",
"(",
"{",
"node",
":",
"curNode",
",",
"index",
":",
"portionIndex",
"++",
",",
"text",
":",
"curNode",
".",
"data",
",",
"indexInMatch",
":",
"atIndex",
"-",
"match",
".",
"startIndex",
",",
"indexInNode",
":",
"0",
"// always zero for inner-portions",
"}",
")",
"}",
"if",
"(",
"!",
"startPortion",
"&&",
"curNode",
".",
"length",
"+",
"atIndex",
">",
"match",
".",
"startIndex",
")",
"{",
"// We've found the match start",
"startPortion",
"=",
"{",
"node",
":",
"curNode",
",",
"index",
":",
"portionIndex",
"++",
",",
"indexInMatch",
":",
"0",
",",
"indexInNode",
":",
"match",
".",
"startIndex",
"-",
"atIndex",
",",
"endIndexInNode",
":",
"match",
".",
"endIndex",
"-",
"atIndex",
",",
"text",
":",
"curNode",
".",
"data",
".",
"substring",
"(",
"match",
".",
"startIndex",
"-",
"atIndex",
",",
"match",
".",
"endIndex",
"-",
"atIndex",
")",
"}",
"}",
"atIndex",
"+=",
"curNode",
".",
"data",
".",
"length",
"}",
"doAvoidNode",
"=",
"curNode",
".",
"nodeType",
"===",
"1",
"&&",
"elementFilter",
"&&",
"!",
"elementFilter",
"(",
"curNode",
")",
"if",
"(",
"startPortion",
"&&",
"endPortion",
")",
"{",
"curNode",
"=",
"this",
".",
"replaceMatch",
"(",
"match",
",",
"startPortion",
",",
"innerPortions",
",",
"endPortion",
")",
"// processMatches has to return the node that replaced the endNode",
"// and then we step back so we can continue from the end of the ",
"// match:",
"atIndex",
"-=",
"(",
"endPortion",
".",
"node",
".",
"data",
".",
"length",
"-",
"endPortion",
".",
"endIndexInNode",
")",
"startPortion",
"=",
"null",
"endPortion",
"=",
"null",
"innerPortions",
"=",
"[",
"]",
"match",
"=",
"matches",
".",
"shift",
"(",
")",
"portionIndex",
"=",
"0",
"matchIndex",
"++",
"if",
"(",
"!",
"match",
")",
"{",
"break",
";",
"// no more matches",
"}",
"}",
"else",
"if",
"(",
"!",
"doAvoidNode",
"&&",
"(",
"curNode",
".",
"firstChild",
"||",
"curNode",
".",
"nextSibling",
")",
")",
"{",
"// Move down or forward:",
"if",
"(",
"curNode",
".",
"firstChild",
")",
"{",
"nodeStack",
".",
"push",
"(",
"curNode",
")",
"curNode",
"=",
"curNode",
".",
"firstChild",
"}",
"else",
"{",
"curNode",
"=",
"curNode",
".",
"nextSibling",
"}",
"continue",
"}",
"// Move forward or up:",
"while",
"(",
"true",
")",
"{",
"if",
"(",
"curNode",
".",
"nextSibling",
")",
"{",
"curNode",
"=",
"curNode",
".",
"nextSibling",
"break",
"}",
"curNode",
"=",
"nodeStack",
".",
"pop",
"(",
")",
"if",
"(",
"curNode",
"===",
"node",
")",
"{",
"break",
"out",
"}",
"}",
"}",
"}"
] |
Steps through the target node, looking for matches, and
calling replaceFn when a match is found.
|
[
"Steps",
"through",
"the",
"target",
"node",
"looking",
"for",
"matches",
"and",
"calling",
"replaceFn",
"when",
"a",
"match",
"is",
"found",
"."
] |
940014b48dded1eaa7fa92fa5a09d9cfc96429a9
|
https://github.com/ethantw/Han/blob/940014b48dded1eaa7fa92fa5a09d9cfc96429a9/src/lib/fibre.js/index.js#L482-L586
|
|
6,971
|
ethantw/Han
|
src/js/core.js
|
function( routine ) {
var it = this
var routine = Array.isArray( routine )
? routine
: this.routine
routine
.forEach(function( method ) {
if (
typeof method === 'string' &&
typeof it[ method ] === 'function'
) {
it[ method ]()
} else if (
Array.isArray( method ) &&
typeof it[ method[0] ] === 'function'
) {
it[ method.shift() ].apply( it, method )
}
})
return this
}
|
javascript
|
function( routine ) {
var it = this
var routine = Array.isArray( routine )
? routine
: this.routine
routine
.forEach(function( method ) {
if (
typeof method === 'string' &&
typeof it[ method ] === 'function'
) {
it[ method ]()
} else if (
Array.isArray( method ) &&
typeof it[ method[0] ] === 'function'
) {
it[ method.shift() ].apply( it, method )
}
})
return this
}
|
[
"function",
"(",
"routine",
")",
"{",
"var",
"it",
"=",
"this",
"var",
"routine",
"=",
"Array",
".",
"isArray",
"(",
"routine",
")",
"?",
"routine",
":",
"this",
".",
"routine",
"routine",
".",
"forEach",
"(",
"function",
"(",
"method",
")",
"{",
"if",
"(",
"typeof",
"method",
"===",
"'string'",
"&&",
"typeof",
"it",
"[",
"method",
"]",
"===",
"'function'",
")",
"{",
"it",
"[",
"method",
"]",
"(",
")",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"method",
")",
"&&",
"typeof",
"it",
"[",
"method",
"[",
"0",
"]",
"]",
"===",
"'function'",
")",
"{",
"it",
"[",
"method",
".",
"shift",
"(",
")",
"]",
".",
"apply",
"(",
"it",
",",
"method",
")",
"}",
"}",
")",
"return",
"this",
"}"
] |
Note that the routine set up here will execute only once. The method won't alter the routine in the instance or in the prototype chain.
|
[
"Note",
"that",
"the",
"routine",
"set",
"up",
"here",
"will",
"execute",
"only",
"once",
".",
"The",
"method",
"won",
"t",
"alter",
"the",
"routine",
"in",
"the",
"instance",
"or",
"in",
"the",
"prototype",
"chain",
"."
] |
940014b48dded1eaa7fa92fa5a09d9cfc96429a9
|
https://github.com/ethantw/Han/blob/940014b48dded1eaa7fa92fa5a09d9cfc96429a9/src/js/core.js#L80-L101
|
|
6,972
|
ethantw/Han
|
src/js/find.js
|
function( selector ) {
return (
this
.filter( selector || null )
.avoid( 'h-jinze' )
.replace(
TYPESET.jinze.touwei,
function( portion, match ) {
var elem = $.create( 'h-jinze', 'touwei' )
elem.innerHTML = match[0]
return (( portion.index === 0 && portion.isEnd ) || portion.index === 1 ) ? elem : ''
}
)
.replace(
TYPESET.jinze.wei,
function( portion, match ) {
var elem = $.create( 'h-jinze', 'wei' )
elem.innerHTML = match[0]
return portion.index === 0 ? elem : ''
}
)
.replace(
TYPESET.jinze.tou,
function( portion, match ) {
var elem = $.create( 'h-jinze', 'tou' )
elem.innerHTML = match[0]
return (( portion.index === 0 && portion.isEnd ) || portion.index === 1 )
? elem : ''
}
)
.replace(
TYPESET.jinze.middle,
function( portion, match ) {
var elem = $.create( 'h-jinze', 'middle' )
elem.innerHTML = match[0]
return (( portion.index === 0 && portion.isEnd ) || portion.index === 1 )
? elem : ''
}
)
.endAvoid()
.endFilter()
)
}
|
javascript
|
function( selector ) {
return (
this
.filter( selector || null )
.avoid( 'h-jinze' )
.replace(
TYPESET.jinze.touwei,
function( portion, match ) {
var elem = $.create( 'h-jinze', 'touwei' )
elem.innerHTML = match[0]
return (( portion.index === 0 && portion.isEnd ) || portion.index === 1 ) ? elem : ''
}
)
.replace(
TYPESET.jinze.wei,
function( portion, match ) {
var elem = $.create( 'h-jinze', 'wei' )
elem.innerHTML = match[0]
return portion.index === 0 ? elem : ''
}
)
.replace(
TYPESET.jinze.tou,
function( portion, match ) {
var elem = $.create( 'h-jinze', 'tou' )
elem.innerHTML = match[0]
return (( portion.index === 0 && portion.isEnd ) || portion.index === 1 )
? elem : ''
}
)
.replace(
TYPESET.jinze.middle,
function( portion, match ) {
var elem = $.create( 'h-jinze', 'middle' )
elem.innerHTML = match[0]
return (( portion.index === 0 && portion.isEnd ) || portion.index === 1 )
? elem : ''
}
)
.endAvoid()
.endFilter()
)
}
|
[
"function",
"(",
"selector",
")",
"{",
"return",
"(",
"this",
".",
"filter",
"(",
"selector",
"||",
"null",
")",
".",
"avoid",
"(",
"'h-jinze'",
")",
".",
"replace",
"(",
"TYPESET",
".",
"jinze",
".",
"touwei",
",",
"function",
"(",
"portion",
",",
"match",
")",
"{",
"var",
"elem",
"=",
"$",
".",
"create",
"(",
"'h-jinze'",
",",
"'touwei'",
")",
"elem",
".",
"innerHTML",
"=",
"match",
"[",
"0",
"]",
"return",
"(",
"(",
"portion",
".",
"index",
"===",
"0",
"&&",
"portion",
".",
"isEnd",
")",
"||",
"portion",
".",
"index",
"===",
"1",
")",
"?",
"elem",
":",
"''",
"}",
")",
".",
"replace",
"(",
"TYPESET",
".",
"jinze",
".",
"wei",
",",
"function",
"(",
"portion",
",",
"match",
")",
"{",
"var",
"elem",
"=",
"$",
".",
"create",
"(",
"'h-jinze'",
",",
"'wei'",
")",
"elem",
".",
"innerHTML",
"=",
"match",
"[",
"0",
"]",
"return",
"portion",
".",
"index",
"===",
"0",
"?",
"elem",
":",
"''",
"}",
")",
".",
"replace",
"(",
"TYPESET",
".",
"jinze",
".",
"tou",
",",
"function",
"(",
"portion",
",",
"match",
")",
"{",
"var",
"elem",
"=",
"$",
".",
"create",
"(",
"'h-jinze'",
",",
"'tou'",
")",
"elem",
".",
"innerHTML",
"=",
"match",
"[",
"0",
"]",
"return",
"(",
"(",
"portion",
".",
"index",
"===",
"0",
"&&",
"portion",
".",
"isEnd",
")",
"||",
"portion",
".",
"index",
"===",
"1",
")",
"?",
"elem",
":",
"''",
"}",
")",
".",
"replace",
"(",
"TYPESET",
".",
"jinze",
".",
"middle",
",",
"function",
"(",
"portion",
",",
"match",
")",
"{",
"var",
"elem",
"=",
"$",
".",
"create",
"(",
"'h-jinze'",
",",
"'middle'",
")",
"elem",
".",
"innerHTML",
"=",
"match",
"[",
"0",
"]",
"return",
"(",
"(",
"portion",
".",
"index",
"===",
"0",
"&&",
"portion",
".",
"isEnd",
")",
"||",
"portion",
".",
"index",
"===",
"1",
")",
"?",
"elem",
":",
"''",
"}",
")",
".",
"endAvoid",
"(",
")",
".",
"endFilter",
"(",
")",
")",
"}"
] |
Force punctuation & biaodian typesetting rules to be applied.
|
[
"Force",
"punctuation",
"&",
"biaodian",
"typesetting",
"rules",
"to",
"be",
"applied",
"."
] |
940014b48dded1eaa7fa92fa5a09d9cfc96429a9
|
https://github.com/ethantw/Han/blob/940014b48dded1eaa7fa92fa5a09d9cfc96429a9/src/js/find.js#L86-L128
|
|
6,973
|
ethantw/Han
|
src/js/locale/normalize.js
|
function( context, target ) {
var $$target = $.qsa( target || 'u, ins', context )
var i = $$target.length
traverse: while ( i-- ) {
var $this = $$target[ i ]
var $prev = null
// Ignore all `<wbr>` and comments in between,
// and add class `.adjacent` once two targets
// are next to each other.
ignore: do {
$prev = ( $prev || $this ).previousSibling
if ( !$prev ) {
continue traverse
} else if ( $$target[ i-1 ] === $prev ) {
$this.classList.add( 'adjacent' )
}
} while ( $.isIgnorable( $prev ))
}
}
|
javascript
|
function( context, target ) {
var $$target = $.qsa( target || 'u, ins', context )
var i = $$target.length
traverse: while ( i-- ) {
var $this = $$target[ i ]
var $prev = null
// Ignore all `<wbr>` and comments in between,
// and add class `.adjacent` once two targets
// are next to each other.
ignore: do {
$prev = ( $prev || $this ).previousSibling
if ( !$prev ) {
continue traverse
} else if ( $$target[ i-1 ] === $prev ) {
$this.classList.add( 'adjacent' )
}
} while ( $.isIgnorable( $prev ))
}
}
|
[
"function",
"(",
"context",
",",
"target",
")",
"{",
"var",
"$$target",
"=",
"$",
".",
"qsa",
"(",
"target",
"||",
"'u, ins'",
",",
"context",
")",
"var",
"i",
"=",
"$$target",
".",
"length",
"traverse",
":",
"while",
"(",
"i",
"--",
")",
"{",
"var",
"$this",
"=",
"$$target",
"[",
"i",
"]",
"var",
"$prev",
"=",
"null",
"// Ignore all `<wbr>` and comments in between,",
"// and add class `.adjacent` once two targets",
"// are next to each other.",
"ignore",
":",
"do",
"{",
"$prev",
"=",
"(",
"$prev",
"||",
"$this",
")",
".",
"previousSibling",
"if",
"(",
"!",
"$prev",
")",
"{",
"continue",
"traverse",
"}",
"else",
"if",
"(",
"$$target",
"[",
"i",
"-",
"1",
"]",
"===",
"$prev",
")",
"{",
"$this",
".",
"classList",
".",
"add",
"(",
"'adjacent'",
")",
"}",
"}",
"while",
"(",
"$",
".",
"isIgnorable",
"(",
"$prev",
")",
")",
"}",
"}"
] |
Traverse all target elements and address presentational corrections if any two of them are adjacent to each other.
|
[
"Traverse",
"all",
"target",
"elements",
"and",
"address",
"presentational",
"corrections",
"if",
"any",
"two",
"of",
"them",
"are",
"adjacent",
"to",
"each",
"other",
"."
] |
940014b48dded1eaa7fa92fa5a09d9cfc96429a9
|
https://github.com/ethantw/Han/blob/940014b48dded1eaa7fa92fa5a09d9cfc96429a9/src/js/locale/normalize.js#L27-L48
|
|
6,974
|
ethantw/Han
|
src/js/locale/normalize.js
|
function( context, target ) {
var method = target ? 'qsa' : 'tag'
var target = target || 'em'
var $target = $[ method ]( target, context )
$target
.forEach(function( elem ) {
var $elem = Han( elem )
if ( Locale.support.textemphasis ) {
$elem
.avoid( 'rt, h-char' )
.charify({ biaodian: true, punct: true })
} else {
$elem
.avoid( 'rt, h-char, h-char-group' )
.jinzify()
.groupify({ western: true })
.charify({
hanzi: true,
biaodian: true,
punct: true,
latin: true,
ellinika: true,
kirillica: true
})
}
})
}
|
javascript
|
function( context, target ) {
var method = target ? 'qsa' : 'tag'
var target = target || 'em'
var $target = $[ method ]( target, context )
$target
.forEach(function( elem ) {
var $elem = Han( elem )
if ( Locale.support.textemphasis ) {
$elem
.avoid( 'rt, h-char' )
.charify({ biaodian: true, punct: true })
} else {
$elem
.avoid( 'rt, h-char, h-char-group' )
.jinzify()
.groupify({ western: true })
.charify({
hanzi: true,
biaodian: true,
punct: true,
latin: true,
ellinika: true,
kirillica: true
})
}
})
}
|
[
"function",
"(",
"context",
",",
"target",
")",
"{",
"var",
"method",
"=",
"target",
"?",
"'qsa'",
":",
"'tag'",
"var",
"target",
"=",
"target",
"||",
"'em'",
"var",
"$target",
"=",
"$",
"[",
"method",
"]",
"(",
"target",
",",
"context",
")",
"$target",
".",
"forEach",
"(",
"function",
"(",
"elem",
")",
"{",
"var",
"$elem",
"=",
"Han",
"(",
"elem",
")",
"if",
"(",
"Locale",
".",
"support",
".",
"textemphasis",
")",
"{",
"$elem",
".",
"avoid",
"(",
"'rt, h-char'",
")",
".",
"charify",
"(",
"{",
"biaodian",
":",
"true",
",",
"punct",
":",
"true",
"}",
")",
"}",
"else",
"{",
"$elem",
".",
"avoid",
"(",
"'rt, h-char, h-char-group'",
")",
".",
"jinzify",
"(",
")",
".",
"groupify",
"(",
"{",
"western",
":",
"true",
"}",
")",
".",
"charify",
"(",
"{",
"hanzi",
":",
"true",
",",
"biaodian",
":",
"true",
",",
"punct",
":",
"true",
",",
"latin",
":",
"true",
",",
"ellinika",
":",
"true",
",",
"kirillica",
":",
"true",
"}",
")",
"}",
"}",
")",
"}"
] |
Traverse all target elements to render emphasis marks.
|
[
"Traverse",
"all",
"target",
"elements",
"to",
"render",
"emphasis",
"marks",
"."
] |
940014b48dded1eaa7fa92fa5a09d9cfc96429a9
|
https://github.com/ethantw/Han/blob/940014b48dded1eaa7fa92fa5a09d9cfc96429a9/src/js/locale/normalize.js#L52-L80
|
|
6,975
|
fable-compiler/Fable
|
src/fable-library/Types.js
|
inherits
|
function inherits(subClass, superClass) {
// if (typeof superClass !== "function" && superClass !== null) {
// throw new TypeError(
// "Super expression must either be null or a function, not " +
// typeof superClass
// );
// }
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true,
},
});
// if (superClass)
// Object.setPrototypeOf
// ? Object.setPrototypeOf(subClass, superClass)
// : (subClass.__proto__ = superClass);
}
|
javascript
|
function inherits(subClass, superClass) {
// if (typeof superClass !== "function" && superClass !== null) {
// throw new TypeError(
// "Super expression must either be null or a function, not " +
// typeof superClass
// );
// }
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true,
},
});
// if (superClass)
// Object.setPrototypeOf
// ? Object.setPrototypeOf(subClass, superClass)
// : (subClass.__proto__ = superClass);
}
|
[
"function",
"inherits",
"(",
"subClass",
",",
"superClass",
")",
"{",
"// if (typeof superClass !== \"function\" && superClass !== null) {",
"// throw new TypeError(",
"// \"Super expression must either be null or a function, not \" +",
"// typeof superClass",
"// );",
"// }",
"subClass",
".",
"prototype",
"=",
"Object",
".",
"create",
"(",
"superClass",
"&&",
"superClass",
".",
"prototype",
",",
"{",
"constructor",
":",
"{",
"value",
":",
"subClass",
",",
"enumerable",
":",
"false",
",",
"writable",
":",
"true",
",",
"configurable",
":",
"true",
",",
"}",
",",
"}",
")",
";",
"// if (superClass)",
"// Object.setPrototypeOf",
"// ? Object.setPrototypeOf(subClass, superClass)",
"// : (subClass.__proto__ = superClass);",
"}"
] |
Taken from Babel helpers
|
[
"Taken",
"from",
"Babel",
"helpers"
] |
de59950a5c1ee3f8294bc67b1aeb3961538b464a
|
https://github.com/fable-compiler/Fable/blob/de59950a5c1ee3f8294bc67b1aeb3961538b464a/src/fable-library/Types.js#L8-L27
|
6,976
|
developit/preact-router
|
src/index.js
|
canRoute
|
function canRoute(url) {
for (let i=ROUTERS.length; i--; ) {
if (ROUTERS[i].canRoute(url)) return true;
}
return false;
}
|
javascript
|
function canRoute(url) {
for (let i=ROUTERS.length; i--; ) {
if (ROUTERS[i].canRoute(url)) return true;
}
return false;
}
|
[
"function",
"canRoute",
"(",
"url",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"ROUTERS",
".",
"length",
";",
"i",
"--",
";",
")",
"{",
"if",
"(",
"ROUTERS",
"[",
"i",
"]",
".",
"canRoute",
"(",
"url",
")",
")",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Check if the given URL can be handled by any router instances.
|
[
"Check",
"if",
"the",
"given",
"URL",
"can",
"be",
"handled",
"by",
"any",
"router",
"instances",
"."
] |
ef8983acdd87b55792e20cdc56401dda0ed80e3f
|
https://github.com/developit/preact-router/blob/ef8983acdd87b55792e20cdc56401dda0ed80e3f/src/index.js#L54-L59
|
6,977
|
developit/preact-router
|
src/index.js
|
routeTo
|
function routeTo(url) {
let didRoute = false;
for (let i=0; i<ROUTERS.length; i++) {
if (ROUTERS[i].routeTo(url)===true) {
didRoute = true;
}
}
for (let i=subscribers.length; i--; ) {
subscribers[i](url);
}
return didRoute;
}
|
javascript
|
function routeTo(url) {
let didRoute = false;
for (let i=0; i<ROUTERS.length; i++) {
if (ROUTERS[i].routeTo(url)===true) {
didRoute = true;
}
}
for (let i=subscribers.length; i--; ) {
subscribers[i](url);
}
return didRoute;
}
|
[
"function",
"routeTo",
"(",
"url",
")",
"{",
"let",
"didRoute",
"=",
"false",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"ROUTERS",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"ROUTERS",
"[",
"i",
"]",
".",
"routeTo",
"(",
"url",
")",
"===",
"true",
")",
"{",
"didRoute",
"=",
"true",
";",
"}",
"}",
"for",
"(",
"let",
"i",
"=",
"subscribers",
".",
"length",
";",
"i",
"--",
";",
")",
"{",
"subscribers",
"[",
"i",
"]",
"(",
"url",
")",
";",
"}",
"return",
"didRoute",
";",
"}"
] |
Tell all router instances to handle the given URL.
|
[
"Tell",
"all",
"router",
"instances",
"to",
"handle",
"the",
"given",
"URL",
"."
] |
ef8983acdd87b55792e20cdc56401dda0ed80e3f
|
https://github.com/developit/preact-router/blob/ef8983acdd87b55792e20cdc56401dda0ed80e3f/src/index.js#L63-L74
|
6,978
|
patrick-steele-idem/morphdom
|
dist/morphdom-esm.js
|
compareNodeNames
|
function compareNodeNames(fromEl, toEl) {
var fromNodeName = fromEl.nodeName;
var toNodeName = toEl.nodeName;
if (fromNodeName === toNodeName) {
return true;
}
if (toEl.actualize &&
fromNodeName.charCodeAt(0) < 91 && /* from tag name is upper case */
toNodeName.charCodeAt(0) > 90 /* target tag name is lower case */) {
// If the target element is a virtual DOM node then we may need to normalize the tag name
// before comparing. Normal HTML elements that are in the "http://www.w3.org/1999/xhtml"
// are converted to upper case
return fromNodeName === toNodeName.toUpperCase();
} else {
return false;
}
}
|
javascript
|
function compareNodeNames(fromEl, toEl) {
var fromNodeName = fromEl.nodeName;
var toNodeName = toEl.nodeName;
if (fromNodeName === toNodeName) {
return true;
}
if (toEl.actualize &&
fromNodeName.charCodeAt(0) < 91 && /* from tag name is upper case */
toNodeName.charCodeAt(0) > 90 /* target tag name is lower case */) {
// If the target element is a virtual DOM node then we may need to normalize the tag name
// before comparing. Normal HTML elements that are in the "http://www.w3.org/1999/xhtml"
// are converted to upper case
return fromNodeName === toNodeName.toUpperCase();
} else {
return false;
}
}
|
[
"function",
"compareNodeNames",
"(",
"fromEl",
",",
"toEl",
")",
"{",
"var",
"fromNodeName",
"=",
"fromEl",
".",
"nodeName",
";",
"var",
"toNodeName",
"=",
"toEl",
".",
"nodeName",
";",
"if",
"(",
"fromNodeName",
"===",
"toNodeName",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"toEl",
".",
"actualize",
"&&",
"fromNodeName",
".",
"charCodeAt",
"(",
"0",
")",
"<",
"91",
"&&",
"/* from tag name is upper case */",
"toNodeName",
".",
"charCodeAt",
"(",
"0",
")",
">",
"90",
"/* target tag name is lower case */",
")",
"{",
"// If the target element is a virtual DOM node then we may need to normalize the tag name",
"// before comparing. Normal HTML elements that are in the \"http://www.w3.org/1999/xhtml\"",
"// are converted to upper case",
"return",
"fromNodeName",
"===",
"toNodeName",
".",
"toUpperCase",
"(",
")",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] |
Returns true if two node's names are the same.
NOTE: We don't bother checking `namespaceURI` because you will never find two HTML elements with the same
nodeName and different namespace URIs.
@param {Element} a
@param {Element} b The target element
@return {boolean}
|
[
"Returns",
"true",
"if",
"two",
"node",
"s",
"names",
"are",
"the",
"same",
"."
] |
da08ab419ae21d305bc5cfb38f2f3d6c2152d1c7
|
https://github.com/patrick-steele-idem/morphdom/blob/da08ab419ae21d305bc5cfb38f2f3d6c2152d1c7/dist/morphdom-esm.js#L97-L115
|
6,979
|
patrick-steele-idem/morphdom
|
dist/morphdom-esm.js
|
createElementNS
|
function createElementNS(name, namespaceURI) {
return !namespaceURI || namespaceURI === NS_XHTML ?
doc.createElement(name) :
doc.createElementNS(namespaceURI, name);
}
|
javascript
|
function createElementNS(name, namespaceURI) {
return !namespaceURI || namespaceURI === NS_XHTML ?
doc.createElement(name) :
doc.createElementNS(namespaceURI, name);
}
|
[
"function",
"createElementNS",
"(",
"name",
",",
"namespaceURI",
")",
"{",
"return",
"!",
"namespaceURI",
"||",
"namespaceURI",
"===",
"NS_XHTML",
"?",
"doc",
".",
"createElement",
"(",
"name",
")",
":",
"doc",
".",
"createElementNS",
"(",
"namespaceURI",
",",
"name",
")",
";",
"}"
] |
Create an element, optionally with a known namespace URI.
@param {string} name the element name, e.g. 'div' or 'svg'
@param {string} [namespaceURI] the element's namespace URI, i.e. the value of
its `xmlns` attribute or its inferred namespace.
@return {Element}
|
[
"Create",
"an",
"element",
"optionally",
"with",
"a",
"known",
"namespace",
"URI",
"."
] |
da08ab419ae21d305bc5cfb38f2f3d6c2152d1c7
|
https://github.com/patrick-steele-idem/morphdom/blob/da08ab419ae21d305bc5cfb38f2f3d6c2152d1c7/dist/morphdom-esm.js#L126-L130
|
6,980
|
patrick-steele-idem/morphdom
|
dist/morphdom-esm.js
|
moveChildren
|
function moveChildren(fromEl, toEl) {
var curChild = fromEl.firstChild;
while (curChild) {
var nextChild = curChild.nextSibling;
toEl.appendChild(curChild);
curChild = nextChild;
}
return toEl;
}
|
javascript
|
function moveChildren(fromEl, toEl) {
var curChild = fromEl.firstChild;
while (curChild) {
var nextChild = curChild.nextSibling;
toEl.appendChild(curChild);
curChild = nextChild;
}
return toEl;
}
|
[
"function",
"moveChildren",
"(",
"fromEl",
",",
"toEl",
")",
"{",
"var",
"curChild",
"=",
"fromEl",
".",
"firstChild",
";",
"while",
"(",
"curChild",
")",
"{",
"var",
"nextChild",
"=",
"curChild",
".",
"nextSibling",
";",
"toEl",
".",
"appendChild",
"(",
"curChild",
")",
";",
"curChild",
"=",
"nextChild",
";",
"}",
"return",
"toEl",
";",
"}"
] |
Copies the children of one DOM element to another DOM element
|
[
"Copies",
"the",
"children",
"of",
"one",
"DOM",
"element",
"to",
"another",
"DOM",
"element"
] |
da08ab419ae21d305bc5cfb38f2f3d6c2152d1c7
|
https://github.com/patrick-steele-idem/morphdom/blob/da08ab419ae21d305bc5cfb38f2f3d6c2152d1c7/dist/morphdom-esm.js#L135-L143
|
6,981
|
patrick-steele-idem/morphdom
|
dist/morphdom-esm.js
|
removeNode
|
function removeNode(node, parentNode, skipKeyedNodes) {
if (onBeforeNodeDiscarded(node) === false) {
return;
}
if (parentNode) {
parentNode.removeChild(node);
}
onNodeDiscarded(node);
walkDiscardedChildNodes(node, skipKeyedNodes);
}
|
javascript
|
function removeNode(node, parentNode, skipKeyedNodes) {
if (onBeforeNodeDiscarded(node) === false) {
return;
}
if (parentNode) {
parentNode.removeChild(node);
}
onNodeDiscarded(node);
walkDiscardedChildNodes(node, skipKeyedNodes);
}
|
[
"function",
"removeNode",
"(",
"node",
",",
"parentNode",
",",
"skipKeyedNodes",
")",
"{",
"if",
"(",
"onBeforeNodeDiscarded",
"(",
"node",
")",
"===",
"false",
")",
"{",
"return",
";",
"}",
"if",
"(",
"parentNode",
")",
"{",
"parentNode",
".",
"removeChild",
"(",
"node",
")",
";",
"}",
"onNodeDiscarded",
"(",
"node",
")",
";",
"walkDiscardedChildNodes",
"(",
"node",
",",
"skipKeyedNodes",
")",
";",
"}"
] |
Removes a DOM node out of the original DOM
@param {Node} node The node to remove
@param {Node} parentNode The nodes parent
@param {Boolean} skipKeyedNodes If true then elements with keys will be skipped and not discarded.
@return {undefined}
|
[
"Removes",
"a",
"DOM",
"node",
"out",
"of",
"the",
"original",
"DOM"
] |
da08ab419ae21d305bc5cfb38f2f3d6c2152d1c7
|
https://github.com/patrick-steele-idem/morphdom/blob/da08ab419ae21d305bc5cfb38f2f3d6c2152d1c7/dist/morphdom-esm.js#L340-L351
|
6,982
|
23/resumable.js
|
resumable.js
|
processCallbacks
|
function processCallbacks(items, cb){
if(!items || items.length === 0){
// empty or no list, invoke callback
return cb();
}
// invoke current function, pass the next part as continuation
items[0](function(){
processCallbacks(items.slice(1), cb);
});
}
|
javascript
|
function processCallbacks(items, cb){
if(!items || items.length === 0){
// empty or no list, invoke callback
return cb();
}
// invoke current function, pass the next part as continuation
items[0](function(){
processCallbacks(items.slice(1), cb);
});
}
|
[
"function",
"processCallbacks",
"(",
"items",
",",
"cb",
")",
"{",
"if",
"(",
"!",
"items",
"||",
"items",
".",
"length",
"===",
"0",
")",
"{",
"// empty or no list, invoke callback",
"return",
"cb",
"(",
")",
";",
"}",
"// invoke current function, pass the next part as continuation",
"items",
"[",
"0",
"]",
"(",
"function",
"(",
")",
"{",
"processCallbacks",
"(",
"items",
".",
"slice",
"(",
"1",
")",
",",
"cb",
")",
";",
"}",
")",
";",
"}"
] |
cps-style list iteration.
invokes all functions in list and waits for their callback to be
triggered.
@param {Function[]} items list of functions expecting callback parameter
@param {Function} cb callback to trigger after the last callback has been invoked
|
[
"cps",
"-",
"style",
"list",
"iteration",
".",
"invokes",
"all",
"functions",
"in",
"list",
"and",
"waits",
"for",
"their",
"callback",
"to",
"be",
"triggered",
"."
] |
247f339c4a30e10f559a2770a5a0030de0be9363
|
https://github.com/23/resumable.js/blob/247f339c4a30e10f559a2770a5a0030de0be9363/resumable.js#L300-L309
|
6,983
|
23/resumable.js
|
resumable.js
|
processDirectory
|
function processDirectory (directory, path, items, cb) {
var dirReader = directory.createReader();
var allEntries = [];
function readEntries () {
dirReader.readEntries(function(entries){
if (entries.length) {
allEntries = allEntries.concat(entries);
return readEntries();
}
// process all conversion callbacks, finally invoke own one
processCallbacks(
allEntries.map(function(entry){
// bind all properties except for callback
return processItem.bind(null, entry, path, items);
}),
cb
);
});
}
readEntries();
}
|
javascript
|
function processDirectory (directory, path, items, cb) {
var dirReader = directory.createReader();
var allEntries = [];
function readEntries () {
dirReader.readEntries(function(entries){
if (entries.length) {
allEntries = allEntries.concat(entries);
return readEntries();
}
// process all conversion callbacks, finally invoke own one
processCallbacks(
allEntries.map(function(entry){
// bind all properties except for callback
return processItem.bind(null, entry, path, items);
}),
cb
);
});
}
readEntries();
}
|
[
"function",
"processDirectory",
"(",
"directory",
",",
"path",
",",
"items",
",",
"cb",
")",
"{",
"var",
"dirReader",
"=",
"directory",
".",
"createReader",
"(",
")",
";",
"var",
"allEntries",
"=",
"[",
"]",
";",
"function",
"readEntries",
"(",
")",
"{",
"dirReader",
".",
"readEntries",
"(",
"function",
"(",
"entries",
")",
"{",
"if",
"(",
"entries",
".",
"length",
")",
"{",
"allEntries",
"=",
"allEntries",
".",
"concat",
"(",
"entries",
")",
";",
"return",
"readEntries",
"(",
")",
";",
"}",
"// process all conversion callbacks, finally invoke own one",
"processCallbacks",
"(",
"allEntries",
".",
"map",
"(",
"function",
"(",
"entry",
")",
"{",
"// bind all properties except for callback",
"return",
"processItem",
".",
"bind",
"(",
"null",
",",
"entry",
",",
"path",
",",
"items",
")",
";",
"}",
")",
",",
"cb",
")",
";",
"}",
")",
";",
"}",
"readEntries",
"(",
")",
";",
"}"
] |
recursively traverse directory and collect files to upload
@param {Object} directory directory to process
@param {string} path current path
@param {File[]} items target list of items
@param {Function} cb callback invoked after traversing directory
|
[
"recursively",
"traverse",
"directory",
"and",
"collect",
"files",
"to",
"upload"
] |
247f339c4a30e10f559a2770a5a0030de0be9363
|
https://github.com/23/resumable.js/blob/247f339c4a30e10f559a2770a5a0030de0be9363/resumable.js#L318-L341
|
6,984
|
23/resumable.js
|
resumable.js
|
loadFiles
|
function loadFiles(items, event) {
if(!items.length){
return; // nothing to do
}
$.fire('beforeAdd');
var files = [];
processCallbacks(
Array.prototype.map.call(items, function(item){
// bind all properties except for callback
var entry = item;
if('function' === typeof item.webkitGetAsEntry){
entry = item.webkitGetAsEntry();
}
return processItem.bind(null, entry, "", files);
}),
function(){
if(files.length){
// at least one file found
appendFilesFromFileList(files, event);
}
}
);
}
|
javascript
|
function loadFiles(items, event) {
if(!items.length){
return; // nothing to do
}
$.fire('beforeAdd');
var files = [];
processCallbacks(
Array.prototype.map.call(items, function(item){
// bind all properties except for callback
var entry = item;
if('function' === typeof item.webkitGetAsEntry){
entry = item.webkitGetAsEntry();
}
return processItem.bind(null, entry, "", files);
}),
function(){
if(files.length){
// at least one file found
appendFilesFromFileList(files, event);
}
}
);
}
|
[
"function",
"loadFiles",
"(",
"items",
",",
"event",
")",
"{",
"if",
"(",
"!",
"items",
".",
"length",
")",
"{",
"return",
";",
"// nothing to do",
"}",
"$",
".",
"fire",
"(",
"'beforeAdd'",
")",
";",
"var",
"files",
"=",
"[",
"]",
";",
"processCallbacks",
"(",
"Array",
".",
"prototype",
".",
"map",
".",
"call",
"(",
"items",
",",
"function",
"(",
"item",
")",
"{",
"// bind all properties except for callback",
"var",
"entry",
"=",
"item",
";",
"if",
"(",
"'function'",
"===",
"typeof",
"item",
".",
"webkitGetAsEntry",
")",
"{",
"entry",
"=",
"item",
".",
"webkitGetAsEntry",
"(",
")",
";",
"}",
"return",
"processItem",
".",
"bind",
"(",
"null",
",",
"entry",
",",
"\"\"",
",",
"files",
")",
";",
"}",
")",
",",
"function",
"(",
")",
"{",
"if",
"(",
"files",
".",
"length",
")",
"{",
"// at least one file found",
"appendFilesFromFileList",
"(",
"files",
",",
"event",
")",
";",
"}",
"}",
")",
";",
"}"
] |
process items to extract files to be uploaded
@param {File[]} items items to process
@param {Event} event event that led to upload
|
[
"process",
"items",
"to",
"extract",
"files",
"to",
"be",
"uploaded"
] |
247f339c4a30e10f559a2770a5a0030de0be9363
|
https://github.com/23/resumable.js/blob/247f339c4a30e10f559a2770a5a0030de0be9363/resumable.js#L348-L370
|
6,985
|
TerriaJS/terriajs
|
lib/Map/SummaryConcept.js
|
function(name, options) {
name = defaultValue(name, "Conditions");
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
DisplayVariablesConcept.call(this, name, options);
}
|
javascript
|
function(name, options) {
name = defaultValue(name, "Conditions");
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
DisplayVariablesConcept.call(this, name, options);
}
|
[
"function",
"(",
"name",
",",
"options",
")",
"{",
"name",
"=",
"defaultValue",
"(",
"name",
",",
"\"Conditions\"",
")",
";",
"options",
"=",
"defaultValue",
"(",
"options",
",",
"defaultValue",
".",
"EMPTY_OBJECT",
")",
";",
"DisplayVariablesConcept",
".",
"call",
"(",
"this",
",",
"name",
",",
"options",
")",
";",
"}"
] |
Represents the top-level node of a tree which should be displayed using
a different UX to the more usual DisplayVariablesConcept.
Intended for use when the tree is huge, and would take up too much space in the UI.
Contains an items array of Concepts.
@alias SummaryConcept
@constructor
@extends DisplayVariablesConcept
@param {String} [name='Conditions'] Display name of this concept.
@param {Object} [options] Options, as per DisplayVariablesConcept.
|
[
"Represents",
"the",
"top",
"-",
"level",
"node",
"of",
"a",
"tree",
"which",
"should",
"be",
"displayed",
"using",
"a",
"different",
"UX",
"to",
"the",
"more",
"usual",
"DisplayVariablesConcept",
".",
"Intended",
"for",
"use",
"when",
"the",
"tree",
"is",
"huge",
"and",
"would",
"take",
"up",
"too",
"much",
"space",
"in",
"the",
"UI",
".",
"Contains",
"an",
"items",
"array",
"of",
"Concepts",
"."
] |
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
|
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Map/SummaryConcept.js#L22-L27
|
|
6,986
|
TerriaJS/terriajs
|
lib/Map/SummaryConcept.js
|
closeDescendants
|
function closeDescendants(concept) {
concept.isOpen = false;
concept.items.forEach(child => {
if (child.items) {
closeDescendants(child);
}
});
}
|
javascript
|
function closeDescendants(concept) {
concept.isOpen = false;
concept.items.forEach(child => {
if (child.items) {
closeDescendants(child);
}
});
}
|
[
"function",
"closeDescendants",
"(",
"concept",
")",
"{",
"concept",
".",
"isOpen",
"=",
"false",
";",
"concept",
".",
"items",
".",
"forEach",
"(",
"child",
"=>",
"{",
"if",
"(",
"child",
".",
"items",
")",
"{",
"closeDescendants",
"(",
"child",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Traverses the concepts' descendants, setting isOpen = false as it goes.
|
[
"Traverses",
"the",
"concepts",
"descendants",
"setting",
"isOpen",
"=",
"false",
"as",
"it",
"goes",
"."
] |
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
|
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Map/SummaryConcept.js#L39-L46
|
6,987
|
TerriaJS/terriajs
|
lib/Models/CatalogFunction.js
|
function(terria) {
CatalogMember.call(this, terria);
this._loadingPromise = undefined;
this._lastLoadInfluencingValues = undefined;
this._parameters = [];
/**
* Gets or sets a value indicating whether the group is currently loading. This property
* is observable.
* @type {Boolean}
*/
this.isLoading = false;
/**
* A catalog item that will be enabled while preparing to invoke this catalog function, in order to
* provide context for the function.
* @type {CatalogItem}
*/
this.contextItem = undefined;
knockout.track(this, ["isLoading"]);
}
|
javascript
|
function(terria) {
CatalogMember.call(this, terria);
this._loadingPromise = undefined;
this._lastLoadInfluencingValues = undefined;
this._parameters = [];
/**
* Gets or sets a value indicating whether the group is currently loading. This property
* is observable.
* @type {Boolean}
*/
this.isLoading = false;
/**
* A catalog item that will be enabled while preparing to invoke this catalog function, in order to
* provide context for the function.
* @type {CatalogItem}
*/
this.contextItem = undefined;
knockout.track(this, ["isLoading"]);
}
|
[
"function",
"(",
"terria",
")",
"{",
"CatalogMember",
".",
"call",
"(",
"this",
",",
"terria",
")",
";",
"this",
".",
"_loadingPromise",
"=",
"undefined",
";",
"this",
".",
"_lastLoadInfluencingValues",
"=",
"undefined",
";",
"this",
".",
"_parameters",
"=",
"[",
"]",
";",
"/**\n * Gets or sets a value indicating whether the group is currently loading. This property\n * is observable.\n * @type {Boolean}\n */",
"this",
".",
"isLoading",
"=",
"false",
";",
"/**\n * A catalog item that will be enabled while preparing to invoke this catalog function, in order to\n * provide context for the function.\n * @type {CatalogItem}\n */",
"this",
".",
"contextItem",
"=",
"undefined",
";",
"knockout",
".",
"track",
"(",
"this",
",",
"[",
"\"isLoading\"",
"]",
")",
";",
"}"
] |
A member of a catalog that does some kind of parameterized processing or analysis.
@alias CatalogFunction
@constructor
@extends CatalogMember
@abstract
@param {Terria} terria The Terria instance.
|
[
"A",
"member",
"of",
"a",
"catalog",
"that",
"does",
"some",
"kind",
"of",
"parameterized",
"processing",
"or",
"analysis",
"."
] |
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
|
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/CatalogFunction.js#L28-L50
|
|
6,988
|
TerriaJS/terriajs
|
lib/Core/replaceUnderscores.js
|
replaceUnderscores
|
function replaceUnderscores(string) {
if (typeof string === "string" || string instanceof String) {
return string.replace(/_/g, " ");
}
return string;
}
|
javascript
|
function replaceUnderscores(string) {
if (typeof string === "string" || string instanceof String) {
return string.replace(/_/g, " ");
}
return string;
}
|
[
"function",
"replaceUnderscores",
"(",
"string",
")",
"{",
"if",
"(",
"typeof",
"string",
"===",
"\"string\"",
"||",
"string",
"instanceof",
"String",
")",
"{",
"return",
"string",
".",
"replace",
"(",
"/",
"_",
"/",
"g",
",",
"\" \"",
")",
";",
"}",
"return",
"string",
";",
"}"
] |
Replace all underscores in the string with spaces. If the argument is not a string, return it unchanged.
@param {} string The string to replace. If the argument is not a string, does nothing.
@return {} The argument with all underscores replaced with spaces. If the argument is not a string, returns the argument unchanged.
|
[
"Replace",
"all",
"underscores",
"in",
"the",
"string",
"with",
"spaces",
".",
"If",
"the",
"argument",
"is",
"not",
"a",
"string",
"return",
"it",
"unchanged",
"."
] |
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
|
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Core/replaceUnderscores.js#L8-L13
|
6,989
|
TerriaJS/terriajs
|
lib/Models/SensorObservationServiceCatalogItem.js
|
extractValues
|
function extractValues(response) {
var observationData =
response.GetObservationResponse &&
response.GetObservationResponse.observationData;
if (defined(observationData)) {
if (!Array.isArray(observationData)) {
observationData = [observationData];
}
var observations = observationData.map(o => o.OM_Observation);
observations.forEach(observation => {
if (!defined(observation)) {
return;
}
var points = observation.result.MeasurementTimeseries.point;
if (!defined(points)) {
return;
}
if (!Array.isArray(points)) {
points = [points];
}
var measurements = points.map(point => point.MeasurementTVP); // TVP = Time value pairs, I think.
// var procedureTitle = defined(observation.procedure) ? observation.procedure['xlink:title'] : 'value';
// var featureName = observation.featureOfInterest['xlink:title'];
var featureIdentifier = observation.featureOfInterest["xlink:href"];
dateValues.push(
...measurements.map(measurement =>
typeof measurement.time === "object" ? null : measurement.time
)
);
valueValues.push(
...measurements.map(measurement =>
typeof measurement.value === "object"
? null
: parseFloat(measurement.value)
)
);
// These 5 arrays constitute columns in the table, some of which (like this one) have the same
// value in each row.
featureValues.push(...measurements.map(_ => featureIdentifier));
procedureValues.push(...measurements.map(_ => procedure.identifier));
observedPropertyValues.push(
...measurements.map(_ => observableProperty.identifier)
);
});
}
}
|
javascript
|
function extractValues(response) {
var observationData =
response.GetObservationResponse &&
response.GetObservationResponse.observationData;
if (defined(observationData)) {
if (!Array.isArray(observationData)) {
observationData = [observationData];
}
var observations = observationData.map(o => o.OM_Observation);
observations.forEach(observation => {
if (!defined(observation)) {
return;
}
var points = observation.result.MeasurementTimeseries.point;
if (!defined(points)) {
return;
}
if (!Array.isArray(points)) {
points = [points];
}
var measurements = points.map(point => point.MeasurementTVP); // TVP = Time value pairs, I think.
// var procedureTitle = defined(observation.procedure) ? observation.procedure['xlink:title'] : 'value';
// var featureName = observation.featureOfInterest['xlink:title'];
var featureIdentifier = observation.featureOfInterest["xlink:href"];
dateValues.push(
...measurements.map(measurement =>
typeof measurement.time === "object" ? null : measurement.time
)
);
valueValues.push(
...measurements.map(measurement =>
typeof measurement.value === "object"
? null
: parseFloat(measurement.value)
)
);
// These 5 arrays constitute columns in the table, some of which (like this one) have the same
// value in each row.
featureValues.push(...measurements.map(_ => featureIdentifier));
procedureValues.push(...measurements.map(_ => procedure.identifier));
observedPropertyValues.push(
...measurements.map(_ => observableProperty.identifier)
);
});
}
}
|
[
"function",
"extractValues",
"(",
"response",
")",
"{",
"var",
"observationData",
"=",
"response",
".",
"GetObservationResponse",
"&&",
"response",
".",
"GetObservationResponse",
".",
"observationData",
";",
"if",
"(",
"defined",
"(",
"observationData",
")",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"observationData",
")",
")",
"{",
"observationData",
"=",
"[",
"observationData",
"]",
";",
"}",
"var",
"observations",
"=",
"observationData",
".",
"map",
"(",
"o",
"=>",
"o",
".",
"OM_Observation",
")",
";",
"observations",
".",
"forEach",
"(",
"observation",
"=>",
"{",
"if",
"(",
"!",
"defined",
"(",
"observation",
")",
")",
"{",
"return",
";",
"}",
"var",
"points",
"=",
"observation",
".",
"result",
".",
"MeasurementTimeseries",
".",
"point",
";",
"if",
"(",
"!",
"defined",
"(",
"points",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"points",
")",
")",
"{",
"points",
"=",
"[",
"points",
"]",
";",
"}",
"var",
"measurements",
"=",
"points",
".",
"map",
"(",
"point",
"=>",
"point",
".",
"MeasurementTVP",
")",
";",
"// TVP = Time value pairs, I think.",
"// var procedureTitle = defined(observation.procedure) ? observation.procedure['xlink:title'] : 'value';",
"// var featureName = observation.featureOfInterest['xlink:title'];",
"var",
"featureIdentifier",
"=",
"observation",
".",
"featureOfInterest",
"[",
"\"xlink:href\"",
"]",
";",
"dateValues",
".",
"push",
"(",
"...",
"measurements",
".",
"map",
"(",
"measurement",
"=>",
"typeof",
"measurement",
".",
"time",
"===",
"\"object\"",
"?",
"null",
":",
"measurement",
".",
"time",
")",
")",
";",
"valueValues",
".",
"push",
"(",
"...",
"measurements",
".",
"map",
"(",
"measurement",
"=>",
"typeof",
"measurement",
".",
"value",
"===",
"\"object\"",
"?",
"null",
":",
"parseFloat",
"(",
"measurement",
".",
"value",
")",
")",
")",
";",
"// These 5 arrays constitute columns in the table, some of which (like this one) have the same",
"// value in each row.",
"featureValues",
".",
"push",
"(",
"...",
"measurements",
".",
"map",
"(",
"_",
"=>",
"featureIdentifier",
")",
")",
";",
"procedureValues",
".",
"push",
"(",
"...",
"measurements",
".",
"map",
"(",
"_",
"=>",
"procedure",
".",
"identifier",
")",
")",
";",
"observedPropertyValues",
".",
"push",
"(",
"...",
"measurements",
".",
"map",
"(",
"_",
"=>",
"observableProperty",
".",
"identifier",
")",
")",
";",
"}",
")",
";",
"}",
"}"
] |
Iterate over all the points in all the time series in all the observations in all the bodies to get individual result rows.
|
[
"Iterate",
"over",
"all",
"the",
"points",
"in",
"all",
"the",
"time",
"series",
"in",
"all",
"the",
"observations",
"in",
"all",
"the",
"bodies",
"to",
"get",
"individual",
"result",
"rows",
"."
] |
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
|
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/SensorObservationServiceCatalogItem.js#L527-L572
|
6,990
|
TerriaJS/terriajs
|
lib/Models/SensorObservationServiceCatalogItem.js
|
loadObservationData
|
function loadObservationData(item) {
if (!item._featureMapping) {
return;
}
var featuresOfInterest = Object.keys(item._featureMapping);
// Are there too many features to load observations (or we've been asked not to try)?
if (
!item.tryToLoadObservationData ||
featuresOfInterest.length > item.requestSizeLimit * item.requestNumberLimit
) {
// MODE 1. Do not load observation data for the features.
// Just show where the features are, and when the feature info panel is opened, then load the feature's observation data
// (via the 'chart' column in _tableStructure, which generates a call to item.loadIntoTableStructure).
var tableStructure = item._tableStructure;
if (!defined(tableStructure)) {
tableStructure = new TableStructure(item.name);
}
var columns = createColumnsFromMapping(item, tableStructure);
tableStructure.columns = columns;
if (!defined(item._tableStructure)) {
item._tableStyle.dataVariable = null; // Turn off the legend and give all the points a single colour.
item.initializeFromTableStructure(tableStructure);
} else {
item._tableStructure.columns = tableStructure.columns;
}
return when();
}
// MODE 2. Create a big time-varying tableStructure with all the observations for all the features.
// In this mode, the feature info panel shows a chart through as a standard time-series, like it would for any time-varying csv.
return item
.loadIntoTableStructure(featuresOfInterest)
.then(function(observationTableStructure) {
if (
!defined(observationTableStructure) ||
observationTableStructure.columns[0].values.length === 0
) {
throw new TerriaError({
sender: item,
title: item.name,
message:
"The Sensor Observation Service did not return any features matching your query."
});
}
// Add the extra columns from the mapping into the table.
var identifiers = observationTableStructure.getColumnWithName(
"identifier"
).values;
var newColumns = createColumnsFromMapping(
item,
observationTableStructure,
identifiers
);
observationTableStructure.activeTimeColumnNameIdOrIndex = undefined;
observationTableStructure.columns = observationTableStructure.columns.concat(
newColumns
);
observationTableStructure.idColumnNames = item._idColumnNames;
if (item.showFeaturesAtAllTimes) {
// Set finalEndJulianDate so that adding new null-valued feature rows doesn't mess with the final date calculations.
// To do this, we need to set the active time column, so that finishJulianDates is calculated.
observationTableStructure.setActiveTimeColumn(
item.tableStyle.timeColumn
);
var finishDates = observationTableStructure.finishJulianDates.map(d =>
Number(JulianDate.toDate(d))
);
// I thought we'd need to unset the time column, because we're about to change the columns again, and there can be interactions
// - but it works without unsetting it.
// observationTableStructure.setActiveTimeColumn(undefined);
observationTableStructure.finalEndJulianDate = JulianDate.fromDate(
new Date(Math.max.apply(null, finishDates))
);
observationTableStructure.columns = observationTableStructure.getColumnsWithFeatureRowsAtStartAndEndDates(
"date",
"value"
);
}
if (!defined(item._tableStructure)) {
observationTableStructure.name = item.name;
item.initializeFromTableStructure(observationTableStructure);
} else {
observationTableStructure.setActiveTimeColumn(
item.tableStyle.timeColumn
);
// Moving this isActive statement earlier stops all points appearing on the map/globe.
observationTableStructure.columns.filter(
column => column.id === "value"
)[0].isActive = true;
item._tableStructure.columns = observationTableStructure.columns; // TODO: doesn't do anything.
// Force the timeline (terria.clock) to update by toggling "isShown" (see CatalogItem's isShownChanged).
if (item.isShown) {
item.isShown = false;
item.isShown = true;
}
// Changing the columns triggers a knockout change of the TableDataSource that uses this table.
}
});
}
|
javascript
|
function loadObservationData(item) {
if (!item._featureMapping) {
return;
}
var featuresOfInterest = Object.keys(item._featureMapping);
// Are there too many features to load observations (or we've been asked not to try)?
if (
!item.tryToLoadObservationData ||
featuresOfInterest.length > item.requestSizeLimit * item.requestNumberLimit
) {
// MODE 1. Do not load observation data for the features.
// Just show where the features are, and when the feature info panel is opened, then load the feature's observation data
// (via the 'chart' column in _tableStructure, which generates a call to item.loadIntoTableStructure).
var tableStructure = item._tableStructure;
if (!defined(tableStructure)) {
tableStructure = new TableStructure(item.name);
}
var columns = createColumnsFromMapping(item, tableStructure);
tableStructure.columns = columns;
if (!defined(item._tableStructure)) {
item._tableStyle.dataVariable = null; // Turn off the legend and give all the points a single colour.
item.initializeFromTableStructure(tableStructure);
} else {
item._tableStructure.columns = tableStructure.columns;
}
return when();
}
// MODE 2. Create a big time-varying tableStructure with all the observations for all the features.
// In this mode, the feature info panel shows a chart through as a standard time-series, like it would for any time-varying csv.
return item
.loadIntoTableStructure(featuresOfInterest)
.then(function(observationTableStructure) {
if (
!defined(observationTableStructure) ||
observationTableStructure.columns[0].values.length === 0
) {
throw new TerriaError({
sender: item,
title: item.name,
message:
"The Sensor Observation Service did not return any features matching your query."
});
}
// Add the extra columns from the mapping into the table.
var identifiers = observationTableStructure.getColumnWithName(
"identifier"
).values;
var newColumns = createColumnsFromMapping(
item,
observationTableStructure,
identifiers
);
observationTableStructure.activeTimeColumnNameIdOrIndex = undefined;
observationTableStructure.columns = observationTableStructure.columns.concat(
newColumns
);
observationTableStructure.idColumnNames = item._idColumnNames;
if (item.showFeaturesAtAllTimes) {
// Set finalEndJulianDate so that adding new null-valued feature rows doesn't mess with the final date calculations.
// To do this, we need to set the active time column, so that finishJulianDates is calculated.
observationTableStructure.setActiveTimeColumn(
item.tableStyle.timeColumn
);
var finishDates = observationTableStructure.finishJulianDates.map(d =>
Number(JulianDate.toDate(d))
);
// I thought we'd need to unset the time column, because we're about to change the columns again, and there can be interactions
// - but it works without unsetting it.
// observationTableStructure.setActiveTimeColumn(undefined);
observationTableStructure.finalEndJulianDate = JulianDate.fromDate(
new Date(Math.max.apply(null, finishDates))
);
observationTableStructure.columns = observationTableStructure.getColumnsWithFeatureRowsAtStartAndEndDates(
"date",
"value"
);
}
if (!defined(item._tableStructure)) {
observationTableStructure.name = item.name;
item.initializeFromTableStructure(observationTableStructure);
} else {
observationTableStructure.setActiveTimeColumn(
item.tableStyle.timeColumn
);
// Moving this isActive statement earlier stops all points appearing on the map/globe.
observationTableStructure.columns.filter(
column => column.id === "value"
)[0].isActive = true;
item._tableStructure.columns = observationTableStructure.columns; // TODO: doesn't do anything.
// Force the timeline (terria.clock) to update by toggling "isShown" (see CatalogItem's isShownChanged).
if (item.isShown) {
item.isShown = false;
item.isShown = true;
}
// Changing the columns triggers a knockout change of the TableDataSource that uses this table.
}
});
}
|
[
"function",
"loadObservationData",
"(",
"item",
")",
"{",
"if",
"(",
"!",
"item",
".",
"_featureMapping",
")",
"{",
"return",
";",
"}",
"var",
"featuresOfInterest",
"=",
"Object",
".",
"keys",
"(",
"item",
".",
"_featureMapping",
")",
";",
"// Are there too many features to load observations (or we've been asked not to try)?",
"if",
"(",
"!",
"item",
".",
"tryToLoadObservationData",
"||",
"featuresOfInterest",
".",
"length",
">",
"item",
".",
"requestSizeLimit",
"*",
"item",
".",
"requestNumberLimit",
")",
"{",
"// MODE 1. Do not load observation data for the features.",
"// Just show where the features are, and when the feature info panel is opened, then load the feature's observation data",
"// (via the 'chart' column in _tableStructure, which generates a call to item.loadIntoTableStructure).",
"var",
"tableStructure",
"=",
"item",
".",
"_tableStructure",
";",
"if",
"(",
"!",
"defined",
"(",
"tableStructure",
")",
")",
"{",
"tableStructure",
"=",
"new",
"TableStructure",
"(",
"item",
".",
"name",
")",
";",
"}",
"var",
"columns",
"=",
"createColumnsFromMapping",
"(",
"item",
",",
"tableStructure",
")",
";",
"tableStructure",
".",
"columns",
"=",
"columns",
";",
"if",
"(",
"!",
"defined",
"(",
"item",
".",
"_tableStructure",
")",
")",
"{",
"item",
".",
"_tableStyle",
".",
"dataVariable",
"=",
"null",
";",
"// Turn off the legend and give all the points a single colour.",
"item",
".",
"initializeFromTableStructure",
"(",
"tableStructure",
")",
";",
"}",
"else",
"{",
"item",
".",
"_tableStructure",
".",
"columns",
"=",
"tableStructure",
".",
"columns",
";",
"}",
"return",
"when",
"(",
")",
";",
"}",
"// MODE 2. Create a big time-varying tableStructure with all the observations for all the features.",
"// In this mode, the feature info panel shows a chart through as a standard time-series, like it would for any time-varying csv.",
"return",
"item",
".",
"loadIntoTableStructure",
"(",
"featuresOfInterest",
")",
".",
"then",
"(",
"function",
"(",
"observationTableStructure",
")",
"{",
"if",
"(",
"!",
"defined",
"(",
"observationTableStructure",
")",
"||",
"observationTableStructure",
".",
"columns",
"[",
"0",
"]",
".",
"values",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"TerriaError",
"(",
"{",
"sender",
":",
"item",
",",
"title",
":",
"item",
".",
"name",
",",
"message",
":",
"\"The Sensor Observation Service did not return any features matching your query.\"",
"}",
")",
";",
"}",
"// Add the extra columns from the mapping into the table.",
"var",
"identifiers",
"=",
"observationTableStructure",
".",
"getColumnWithName",
"(",
"\"identifier\"",
")",
".",
"values",
";",
"var",
"newColumns",
"=",
"createColumnsFromMapping",
"(",
"item",
",",
"observationTableStructure",
",",
"identifiers",
")",
";",
"observationTableStructure",
".",
"activeTimeColumnNameIdOrIndex",
"=",
"undefined",
";",
"observationTableStructure",
".",
"columns",
"=",
"observationTableStructure",
".",
"columns",
".",
"concat",
"(",
"newColumns",
")",
";",
"observationTableStructure",
".",
"idColumnNames",
"=",
"item",
".",
"_idColumnNames",
";",
"if",
"(",
"item",
".",
"showFeaturesAtAllTimes",
")",
"{",
"// Set finalEndJulianDate so that adding new null-valued feature rows doesn't mess with the final date calculations.",
"// To do this, we need to set the active time column, so that finishJulianDates is calculated.",
"observationTableStructure",
".",
"setActiveTimeColumn",
"(",
"item",
".",
"tableStyle",
".",
"timeColumn",
")",
";",
"var",
"finishDates",
"=",
"observationTableStructure",
".",
"finishJulianDates",
".",
"map",
"(",
"d",
"=>",
"Number",
"(",
"JulianDate",
".",
"toDate",
"(",
"d",
")",
")",
")",
";",
"// I thought we'd need to unset the time column, because we're about to change the columns again, and there can be interactions",
"// - but it works without unsetting it.",
"// observationTableStructure.setActiveTimeColumn(undefined);",
"observationTableStructure",
".",
"finalEndJulianDate",
"=",
"JulianDate",
".",
"fromDate",
"(",
"new",
"Date",
"(",
"Math",
".",
"max",
".",
"apply",
"(",
"null",
",",
"finishDates",
")",
")",
")",
";",
"observationTableStructure",
".",
"columns",
"=",
"observationTableStructure",
".",
"getColumnsWithFeatureRowsAtStartAndEndDates",
"(",
"\"date\"",
",",
"\"value\"",
")",
";",
"}",
"if",
"(",
"!",
"defined",
"(",
"item",
".",
"_tableStructure",
")",
")",
"{",
"observationTableStructure",
".",
"name",
"=",
"item",
".",
"name",
";",
"item",
".",
"initializeFromTableStructure",
"(",
"observationTableStructure",
")",
";",
"}",
"else",
"{",
"observationTableStructure",
".",
"setActiveTimeColumn",
"(",
"item",
".",
"tableStyle",
".",
"timeColumn",
")",
";",
"// Moving this isActive statement earlier stops all points appearing on the map/globe.",
"observationTableStructure",
".",
"columns",
".",
"filter",
"(",
"column",
"=>",
"column",
".",
"id",
"===",
"\"value\"",
")",
"[",
"0",
"]",
".",
"isActive",
"=",
"true",
";",
"item",
".",
"_tableStructure",
".",
"columns",
"=",
"observationTableStructure",
".",
"columns",
";",
"// TODO: doesn't do anything.",
"// Force the timeline (terria.clock) to update by toggling \"isShown\" (see CatalogItem's isShownChanged).",
"if",
"(",
"item",
".",
"isShown",
")",
"{",
"item",
".",
"isShown",
"=",
"false",
";",
"item",
".",
"isShown",
"=",
"true",
";",
"}",
"// Changing the columns triggers a knockout change of the TableDataSource that uses this table.",
"}",
"}",
")",
";",
"}"
] |
Given the features already loaded into item._featureMap, this loads the observations according to the user-selected concepts,
and puts them into item._tableStructure.
If there are too many features, fall back to a tableStructure without the observation data.
@param {SensorObservationServiceCatalogItem} item This catalog item.
@return {Promise} A promise which, when it resolves, sets item._tableStructure.
@private
|
[
"Given",
"the",
"features",
"already",
"loaded",
"into",
"item",
".",
"_featureMap",
"this",
"loads",
"the",
"observations",
"according",
"to",
"the",
"user",
"-",
"selected",
"concepts",
"and",
"puts",
"them",
"into",
"item",
".",
"_tableStructure",
".",
"If",
"there",
"are",
"too",
"many",
"features",
"fall",
"back",
"to",
"a",
"tableStructure",
"without",
"the",
"observation",
"data",
"."
] |
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
|
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/SensorObservationServiceCatalogItem.js#L851-L948
|
6,991
|
TerriaJS/terriajs
|
lib/Models/SensorObservationServiceCatalogItem.js
|
createColumnsFromMapping
|
function createColumnsFromMapping(item, tableStructure, identifiers) {
var featureMapping = item._featureMapping;
var addChartColumn = !defined(identifiers);
if (!defined(identifiers)) {
identifiers = Object.keys(featureMapping);
}
var rows = identifiers.map(identifier => featureMapping[identifier]);
var columnOptions = { tableStructure: tableStructure };
var chartColumnOptions = { tableStructure: tableStructure, id: "chart" }; // So the chart column can be referred to in the FeatureInfoTemplate as 'chart'.
var result = [
new TableColumn("type", rows.map(row => row.type), columnOptions),
new TableColumn("name", rows.map(row => row.name), columnOptions),
new TableColumn("id", rows.map(row => row.id), columnOptions),
new TableColumn("lat", rows.map(row => row.lat), columnOptions),
new TableColumn("lon", rows.map(row => row.lon), columnOptions)
];
if (addChartColumn) {
var procedure = getObjectCorrespondingToSelectedConcept(item, "procedures");
var observableProperty = getObjectCorrespondingToSelectedConcept(
item,
"observableProperties"
);
var chartName = procedure.title || observableProperty.title || "chart";
var chartId = procedure.title + "_" + observableProperty.title;
var charts = rows.map(row =>
getChartTagFromFeatureIdentifier(row.identifier, chartId)
);
result.push(
new TableColumn(
"identifier",
rows.map(row => row.identifier),
columnOptions
),
new TableColumn(chartName, charts, chartColumnOptions)
);
}
return result;
}
|
javascript
|
function createColumnsFromMapping(item, tableStructure, identifiers) {
var featureMapping = item._featureMapping;
var addChartColumn = !defined(identifiers);
if (!defined(identifiers)) {
identifiers = Object.keys(featureMapping);
}
var rows = identifiers.map(identifier => featureMapping[identifier]);
var columnOptions = { tableStructure: tableStructure };
var chartColumnOptions = { tableStructure: tableStructure, id: "chart" }; // So the chart column can be referred to in the FeatureInfoTemplate as 'chart'.
var result = [
new TableColumn("type", rows.map(row => row.type), columnOptions),
new TableColumn("name", rows.map(row => row.name), columnOptions),
new TableColumn("id", rows.map(row => row.id), columnOptions),
new TableColumn("lat", rows.map(row => row.lat), columnOptions),
new TableColumn("lon", rows.map(row => row.lon), columnOptions)
];
if (addChartColumn) {
var procedure = getObjectCorrespondingToSelectedConcept(item, "procedures");
var observableProperty = getObjectCorrespondingToSelectedConcept(
item,
"observableProperties"
);
var chartName = procedure.title || observableProperty.title || "chart";
var chartId = procedure.title + "_" + observableProperty.title;
var charts = rows.map(row =>
getChartTagFromFeatureIdentifier(row.identifier, chartId)
);
result.push(
new TableColumn(
"identifier",
rows.map(row => row.identifier),
columnOptions
),
new TableColumn(chartName, charts, chartColumnOptions)
);
}
return result;
}
|
[
"function",
"createColumnsFromMapping",
"(",
"item",
",",
"tableStructure",
",",
"identifiers",
")",
"{",
"var",
"featureMapping",
"=",
"item",
".",
"_featureMapping",
";",
"var",
"addChartColumn",
"=",
"!",
"defined",
"(",
"identifiers",
")",
";",
"if",
"(",
"!",
"defined",
"(",
"identifiers",
")",
")",
"{",
"identifiers",
"=",
"Object",
".",
"keys",
"(",
"featureMapping",
")",
";",
"}",
"var",
"rows",
"=",
"identifiers",
".",
"map",
"(",
"identifier",
"=>",
"featureMapping",
"[",
"identifier",
"]",
")",
";",
"var",
"columnOptions",
"=",
"{",
"tableStructure",
":",
"tableStructure",
"}",
";",
"var",
"chartColumnOptions",
"=",
"{",
"tableStructure",
":",
"tableStructure",
",",
"id",
":",
"\"chart\"",
"}",
";",
"// So the chart column can be referred to in the FeatureInfoTemplate as 'chart'.",
"var",
"result",
"=",
"[",
"new",
"TableColumn",
"(",
"\"type\"",
",",
"rows",
".",
"map",
"(",
"row",
"=>",
"row",
".",
"type",
")",
",",
"columnOptions",
")",
",",
"new",
"TableColumn",
"(",
"\"name\"",
",",
"rows",
".",
"map",
"(",
"row",
"=>",
"row",
".",
"name",
")",
",",
"columnOptions",
")",
",",
"new",
"TableColumn",
"(",
"\"id\"",
",",
"rows",
".",
"map",
"(",
"row",
"=>",
"row",
".",
"id",
")",
",",
"columnOptions",
")",
",",
"new",
"TableColumn",
"(",
"\"lat\"",
",",
"rows",
".",
"map",
"(",
"row",
"=>",
"row",
".",
"lat",
")",
",",
"columnOptions",
")",
",",
"new",
"TableColumn",
"(",
"\"lon\"",
",",
"rows",
".",
"map",
"(",
"row",
"=>",
"row",
".",
"lon",
")",
",",
"columnOptions",
")",
"]",
";",
"if",
"(",
"addChartColumn",
")",
"{",
"var",
"procedure",
"=",
"getObjectCorrespondingToSelectedConcept",
"(",
"item",
",",
"\"procedures\"",
")",
";",
"var",
"observableProperty",
"=",
"getObjectCorrespondingToSelectedConcept",
"(",
"item",
",",
"\"observableProperties\"",
")",
";",
"var",
"chartName",
"=",
"procedure",
".",
"title",
"||",
"observableProperty",
".",
"title",
"||",
"\"chart\"",
";",
"var",
"chartId",
"=",
"procedure",
".",
"title",
"+",
"\"_\"",
"+",
"observableProperty",
".",
"title",
";",
"var",
"charts",
"=",
"rows",
".",
"map",
"(",
"row",
"=>",
"getChartTagFromFeatureIdentifier",
"(",
"row",
".",
"identifier",
",",
"chartId",
")",
")",
";",
"result",
".",
"push",
"(",
"new",
"TableColumn",
"(",
"\"identifier\"",
",",
"rows",
".",
"map",
"(",
"row",
"=>",
"row",
".",
"identifier",
")",
",",
"columnOptions",
")",
",",
"new",
"TableColumn",
"(",
"chartName",
",",
"charts",
",",
"chartColumnOptions",
")",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Converts the featureMapping output by createMappingFromFeatureMembers into columns for a TableStructure.
@param {SensorObservationServiceCatalogItem} item This catalog item.
@param {TableStructure} [tableStructure] Used to set the columns' tableStructure (parent). If identifiers given, output columns line up with them.
@param {String[]} identifiers An array of identifier values from tableStructure. Defaults to all available identifiers.
@return {TableColumn[]} An array of columns to add to observationTableStructure. Only include 'identifier' and 'chart' columns if no identifiers provided.
@private
|
[
"Converts",
"the",
"featureMapping",
"output",
"by",
"createMappingFromFeatureMembers",
"into",
"columns",
"for",
"a",
"TableStructure",
"."
] |
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
|
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/SensorObservationServiceCatalogItem.js#L1066-L1103
|
6,992
|
TerriaJS/terriajs
|
lib/Models/AugmentedVirtuality.js
|
function(terria) {
const that = this;
this._terria = terria;
// Note: We create a persistant object and define a transient property, since knockout needs a persistant variable
// to track, but for state we want a 'maybe' intervalId.
this._eventLoopState = {};
this._manualAlignment = false;
this._maximumUpdatesPerSecond =
AugmentedVirtuality.DEFAULT_MAXIMUM_UPDATES_PER_SECOND;
this._orientationUpdated = false;
this._alpha = 0;
this._beta = 0;
this._gamma = 0;
this._realignAlpha = 0;
this._realignHeading = 0;
// Set the default height to be the last height so that when we first toggle (and increment) we cycle and go to the first height.
this._hoverLevel = AugmentedVirtuality.PRESET_HEIGHTS.length - 1;
// Always run the device orientation event, this way as soon as we enable we know where we are and set the
// orientation rather then having to wait for the next update.
// The following is disabled because chrome does not currently support deviceorientationabsolute correctly:
// if ('ondeviceorientationabsolute' in window)
// {
// window.addEventListener('deviceorientationabsolute', function(event) {that._orientationUpdate(event);} );
// }
// else
if ("ondeviceorientation" in window) {
window.addEventListener("deviceorientation", function(event) {
that._storeOrientation(event);
});
}
// Make the variables used by the object properties knockout observable so that changes in the state notify the UI
// and cause a UI update. Note: These are all of the variables used just by the getters (not the setters), since
// these unqiquely define what the current state is and are the only things that can effect/cause the state to change
// (note: _eventLoopState is hidden behind ._eventLoopRunning() ).
knockout.track(this, [
"_eventLoopState",
"_manualAlignment",
"_maximumUpdatesPerSecond",
"_realignAlpha",
"_realignHeading",
"_hoverLevel"
]);
// Note: The following properties are defined as knockout properties so that they can be used to trigger updates on the UI.
/**
* Gets or sets whether Augmented Virtuality mode is currently enabled (true) or not (false).
*
* Note: If {@link AugmentedVirtuality#manualAlignment} is enabled and the state is changed it will be disabled.
*
* @memberOf AugmentedVirtuality.prototype
* @member {Boolean} enabled
*/
knockout.defineProperty(this, "enabled", {
get: function() {
return this._eventLoopRunning() || this._manualAlignment;
},
set: function(enable) {
if (enable !== true) {
enable = false;
this.resetAlignment();
}
if (enable !== this.enabled) {
// If we are changing the enabled state then disable manual alignment.
// We only do this if we are changing the enabled state so that the client can repeatedly call the
// setting without having any effect if they aren't changing the enabled state, but so that every time
// that the state is changed that the manual alignment is turned back off initally.
this._manualAlignment = false;
this._startEventLoop(enable);
}
}
});
/**
* Gets or sets whether manual realignment mode is currently enabled (true) or not (false).
*
* @memberOf AugmentedVirtuality.prototype
* @member {Boolean} manualAlignment
*/
knockout.defineProperty(this, "manualAlignment", {
get: function() {
return this._getManualAlignment();
},
set: function(startEnd) {
this._setManualAlignment(startEnd);
}
});
/**
* Gets whether a manual realignment has been specified (true) or not (false).
*
* @memberOf AugmentedVirtuality.prototype
* @member {Boolean} manualAlignmentSet
*/
knockout.defineProperty(this, "manualAlignmentSet", {
get: function() {
return this._realignAlpha !== 0.0 || this._realignHeading !== 0.0;
}
});
/**
* Gets the index of the current hover level.
*
* Use <code>AugmentedVirtuality.PRESET_HEIGHTS.length</code> to find the total avaliable levels.
*
* @memberOf AugmentedVirtuality.prototype
* @member {int} hoverLevel
*/
knockout.defineProperty(this, "hoverLevel", {
get: function() {
return this._hoverLevel;
}
});
/**
* Gets or sets the the maximum number of times that the camera orientation will be updated per second. This is
* the number of camera orientation updates per seconds is capped to (explicitly the number of times the
* orientation is updated per second might be less but it won't be more then this number). We want the number of
* times that the orientation is updated capped so that we don't consume to much battery life updating to
* frequently, but responsiveness is still acceptable.
*
* @memberOf AugmentedVirtuality.prototype
* @member {Float} maximumUpdatesPerSecond
*/
knockout.defineProperty(this, "maximumUpdatesPerSecond", {
get: function() {
return this._maximumUpdatesPerSecond;
},
set: function(maximumUpdatesPerSecond) {
this._maximumUpdatesPerSecond = maximumUpdatesPerSecond;
// If we are currently enabled reset to update the timing interval used.
if (this._eventLoopRunning()) {
this._startEventLoop(false);
this._startEventLoop(true);
}
}
});
this.enabled = false;
}
|
javascript
|
function(terria) {
const that = this;
this._terria = terria;
// Note: We create a persistant object and define a transient property, since knockout needs a persistant variable
// to track, but for state we want a 'maybe' intervalId.
this._eventLoopState = {};
this._manualAlignment = false;
this._maximumUpdatesPerSecond =
AugmentedVirtuality.DEFAULT_MAXIMUM_UPDATES_PER_SECOND;
this._orientationUpdated = false;
this._alpha = 0;
this._beta = 0;
this._gamma = 0;
this._realignAlpha = 0;
this._realignHeading = 0;
// Set the default height to be the last height so that when we first toggle (and increment) we cycle and go to the first height.
this._hoverLevel = AugmentedVirtuality.PRESET_HEIGHTS.length - 1;
// Always run the device orientation event, this way as soon as we enable we know where we are and set the
// orientation rather then having to wait for the next update.
// The following is disabled because chrome does not currently support deviceorientationabsolute correctly:
// if ('ondeviceorientationabsolute' in window)
// {
// window.addEventListener('deviceorientationabsolute', function(event) {that._orientationUpdate(event);} );
// }
// else
if ("ondeviceorientation" in window) {
window.addEventListener("deviceorientation", function(event) {
that._storeOrientation(event);
});
}
// Make the variables used by the object properties knockout observable so that changes in the state notify the UI
// and cause a UI update. Note: These are all of the variables used just by the getters (not the setters), since
// these unqiquely define what the current state is and are the only things that can effect/cause the state to change
// (note: _eventLoopState is hidden behind ._eventLoopRunning() ).
knockout.track(this, [
"_eventLoopState",
"_manualAlignment",
"_maximumUpdatesPerSecond",
"_realignAlpha",
"_realignHeading",
"_hoverLevel"
]);
// Note: The following properties are defined as knockout properties so that they can be used to trigger updates on the UI.
/**
* Gets or sets whether Augmented Virtuality mode is currently enabled (true) or not (false).
*
* Note: If {@link AugmentedVirtuality#manualAlignment} is enabled and the state is changed it will be disabled.
*
* @memberOf AugmentedVirtuality.prototype
* @member {Boolean} enabled
*/
knockout.defineProperty(this, "enabled", {
get: function() {
return this._eventLoopRunning() || this._manualAlignment;
},
set: function(enable) {
if (enable !== true) {
enable = false;
this.resetAlignment();
}
if (enable !== this.enabled) {
// If we are changing the enabled state then disable manual alignment.
// We only do this if we are changing the enabled state so that the client can repeatedly call the
// setting without having any effect if they aren't changing the enabled state, but so that every time
// that the state is changed that the manual alignment is turned back off initally.
this._manualAlignment = false;
this._startEventLoop(enable);
}
}
});
/**
* Gets or sets whether manual realignment mode is currently enabled (true) or not (false).
*
* @memberOf AugmentedVirtuality.prototype
* @member {Boolean} manualAlignment
*/
knockout.defineProperty(this, "manualAlignment", {
get: function() {
return this._getManualAlignment();
},
set: function(startEnd) {
this._setManualAlignment(startEnd);
}
});
/**
* Gets whether a manual realignment has been specified (true) or not (false).
*
* @memberOf AugmentedVirtuality.prototype
* @member {Boolean} manualAlignmentSet
*/
knockout.defineProperty(this, "manualAlignmentSet", {
get: function() {
return this._realignAlpha !== 0.0 || this._realignHeading !== 0.0;
}
});
/**
* Gets the index of the current hover level.
*
* Use <code>AugmentedVirtuality.PRESET_HEIGHTS.length</code> to find the total avaliable levels.
*
* @memberOf AugmentedVirtuality.prototype
* @member {int} hoverLevel
*/
knockout.defineProperty(this, "hoverLevel", {
get: function() {
return this._hoverLevel;
}
});
/**
* Gets or sets the the maximum number of times that the camera orientation will be updated per second. This is
* the number of camera orientation updates per seconds is capped to (explicitly the number of times the
* orientation is updated per second might be less but it won't be more then this number). We want the number of
* times that the orientation is updated capped so that we don't consume to much battery life updating to
* frequently, but responsiveness is still acceptable.
*
* @memberOf AugmentedVirtuality.prototype
* @member {Float} maximumUpdatesPerSecond
*/
knockout.defineProperty(this, "maximumUpdatesPerSecond", {
get: function() {
return this._maximumUpdatesPerSecond;
},
set: function(maximumUpdatesPerSecond) {
this._maximumUpdatesPerSecond = maximumUpdatesPerSecond;
// If we are currently enabled reset to update the timing interval used.
if (this._eventLoopRunning()) {
this._startEventLoop(false);
this._startEventLoop(true);
}
}
});
this.enabled = false;
}
|
[
"function",
"(",
"terria",
")",
"{",
"const",
"that",
"=",
"this",
";",
"this",
".",
"_terria",
"=",
"terria",
";",
"// Note: We create a persistant object and define a transient property, since knockout needs a persistant variable",
"// to track, but for state we want a 'maybe' intervalId.",
"this",
".",
"_eventLoopState",
"=",
"{",
"}",
";",
"this",
".",
"_manualAlignment",
"=",
"false",
";",
"this",
".",
"_maximumUpdatesPerSecond",
"=",
"AugmentedVirtuality",
".",
"DEFAULT_MAXIMUM_UPDATES_PER_SECOND",
";",
"this",
".",
"_orientationUpdated",
"=",
"false",
";",
"this",
".",
"_alpha",
"=",
"0",
";",
"this",
".",
"_beta",
"=",
"0",
";",
"this",
".",
"_gamma",
"=",
"0",
";",
"this",
".",
"_realignAlpha",
"=",
"0",
";",
"this",
".",
"_realignHeading",
"=",
"0",
";",
"// Set the default height to be the last height so that when we first toggle (and increment) we cycle and go to the first height.",
"this",
".",
"_hoverLevel",
"=",
"AugmentedVirtuality",
".",
"PRESET_HEIGHTS",
".",
"length",
"-",
"1",
";",
"// Always run the device orientation event, this way as soon as we enable we know where we are and set the",
"// orientation rather then having to wait for the next update.",
"// The following is disabled because chrome does not currently support deviceorientationabsolute correctly:",
"// if ('ondeviceorientationabsolute' in window)",
"// {",
"// window.addEventListener('deviceorientationabsolute', function(event) {that._orientationUpdate(event);} );",
"// }",
"// else",
"if",
"(",
"\"ondeviceorientation\"",
"in",
"window",
")",
"{",
"window",
".",
"addEventListener",
"(",
"\"deviceorientation\"",
",",
"function",
"(",
"event",
")",
"{",
"that",
".",
"_storeOrientation",
"(",
"event",
")",
";",
"}",
")",
";",
"}",
"// Make the variables used by the object properties knockout observable so that changes in the state notify the UI",
"// and cause a UI update. Note: These are all of the variables used just by the getters (not the setters), since",
"// these unqiquely define what the current state is and are the only things that can effect/cause the state to change",
"// (note: _eventLoopState is hidden behind ._eventLoopRunning() ).",
"knockout",
".",
"track",
"(",
"this",
",",
"[",
"\"_eventLoopState\"",
",",
"\"_manualAlignment\"",
",",
"\"_maximumUpdatesPerSecond\"",
",",
"\"_realignAlpha\"",
",",
"\"_realignHeading\"",
",",
"\"_hoverLevel\"",
"]",
")",
";",
"// Note: The following properties are defined as knockout properties so that they can be used to trigger updates on the UI.",
"/**\n * Gets or sets whether Augmented Virtuality mode is currently enabled (true) or not (false).\n *\n * Note: If {@link AugmentedVirtuality#manualAlignment} is enabled and the state is changed it will be disabled.\n *\n * @memberOf AugmentedVirtuality.prototype\n * @member {Boolean} enabled\n */",
"knockout",
".",
"defineProperty",
"(",
"this",
",",
"\"enabled\"",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"_eventLoopRunning",
"(",
")",
"||",
"this",
".",
"_manualAlignment",
";",
"}",
",",
"set",
":",
"function",
"(",
"enable",
")",
"{",
"if",
"(",
"enable",
"!==",
"true",
")",
"{",
"enable",
"=",
"false",
";",
"this",
".",
"resetAlignment",
"(",
")",
";",
"}",
"if",
"(",
"enable",
"!==",
"this",
".",
"enabled",
")",
"{",
"// If we are changing the enabled state then disable manual alignment.",
"// We only do this if we are changing the enabled state so that the client can repeatedly call the",
"// setting without having any effect if they aren't changing the enabled state, but so that every time",
"// that the state is changed that the manual alignment is turned back off initally.",
"this",
".",
"_manualAlignment",
"=",
"false",
";",
"this",
".",
"_startEventLoop",
"(",
"enable",
")",
";",
"}",
"}",
"}",
")",
";",
"/**\n * Gets or sets whether manual realignment mode is currently enabled (true) or not (false).\n *\n * @memberOf AugmentedVirtuality.prototype\n * @member {Boolean} manualAlignment\n */",
"knockout",
".",
"defineProperty",
"(",
"this",
",",
"\"manualAlignment\"",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"_getManualAlignment",
"(",
")",
";",
"}",
",",
"set",
":",
"function",
"(",
"startEnd",
")",
"{",
"this",
".",
"_setManualAlignment",
"(",
"startEnd",
")",
";",
"}",
"}",
")",
";",
"/**\n * Gets whether a manual realignment has been specified (true) or not (false).\n *\n * @memberOf AugmentedVirtuality.prototype\n * @member {Boolean} manualAlignmentSet\n */",
"knockout",
".",
"defineProperty",
"(",
"this",
",",
"\"manualAlignmentSet\"",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"_realignAlpha",
"!==",
"0.0",
"||",
"this",
".",
"_realignHeading",
"!==",
"0.0",
";",
"}",
"}",
")",
";",
"/**\n * Gets the index of the current hover level.\n *\n * Use <code>AugmentedVirtuality.PRESET_HEIGHTS.length</code> to find the total avaliable levels.\n *\n * @memberOf AugmentedVirtuality.prototype\n * @member {int} hoverLevel\n */",
"knockout",
".",
"defineProperty",
"(",
"this",
",",
"\"hoverLevel\"",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"_hoverLevel",
";",
"}",
"}",
")",
";",
"/**\n * Gets or sets the the maximum number of times that the camera orientation will be updated per second. This is\n * the number of camera orientation updates per seconds is capped to (explicitly the number of times the\n * orientation is updated per second might be less but it won't be more then this number). We want the number of\n * times that the orientation is updated capped so that we don't consume to much battery life updating to\n * frequently, but responsiveness is still acceptable.\n *\n * @memberOf AugmentedVirtuality.prototype\n * @member {Float} maximumUpdatesPerSecond\n */",
"knockout",
".",
"defineProperty",
"(",
"this",
",",
"\"maximumUpdatesPerSecond\"",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"_maximumUpdatesPerSecond",
";",
"}",
",",
"set",
":",
"function",
"(",
"maximumUpdatesPerSecond",
")",
"{",
"this",
".",
"_maximumUpdatesPerSecond",
"=",
"maximumUpdatesPerSecond",
";",
"// If we are currently enabled reset to update the timing interval used.",
"if",
"(",
"this",
".",
"_eventLoopRunning",
"(",
")",
")",
"{",
"this",
".",
"_startEventLoop",
"(",
"false",
")",
";",
"this",
".",
"_startEventLoop",
"(",
"true",
")",
";",
"}",
"}",
"}",
")",
";",
"this",
".",
"enabled",
"=",
"false",
";",
"}"
] |
Manages state for Augmented Virtuality mode.
This mode uses the devices orientation sensors to change the viewers viewport to match the change in orientation.
Term Augmented Virtuality:
"The use of real-world sensor information (e.g., gyroscopes) to control a virtual environment is an additional form
of augmented virtuality, in which external inputs provide context for the virtual view."
{@link https://en.wikipedia.org/wiki/Mixed_reality}
@alias AugmentedVirtuality
@constructor
|
[
"Manages",
"state",
"for",
"Augmented",
"Virtuality",
"mode",
"."
] |
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
|
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/AugmentedVirtuality.js#L25-L175
|
|
6,993
|
TerriaJS/terriajs
|
lib/Models/MapInteractionMode.js
|
MapInteractionMode
|
function MapInteractionMode(options) {
/**
* Gets or sets a callback that is invoked when the user cancels the interaction mode. If this property is undefined,
* the interaction mode cannot be canceled.
* @type {Function}
*/
this.onCancel = options.onCancel;
/**
* Gets or sets the details of a custom user interface for this map interaction mode. This property is not used by
* the `MapInteractionMode` itself, so it can be anything that is suitable for the user interface. In the standard
* React-based user interface included with TerriaJS, this property is a function that is called with no parameters
* and is expected to return a React component.
* @type {Any}
*/
this.customUi = defaultValue(options.customUi, undefined);
/**
* Gets or sets the html formatted message displayed on the map when in this mode.
* @type {Function}
*/
this.message = function() {
return options.message;
};
/**
* Set the text of the button for the dialog the message is displayed on.
* @type {String}
*/
this.buttonText = defaultValue(options.buttonText, "Cancel");
/**
* Gets or sets the features that are currently picked.
* @type {PickedFeatures}
*/
this.pickedFeatures = undefined;
/**
* Determines whether a rectangle will be requested from the user rather than a set of pickedFeatures.
* @type {Boolean}
*/
this.drawRectangle = defaultValue(options.drawRectangle, false);
knockout.track(this, ["message", "pickedFeatures", "customUi"]);
}
|
javascript
|
function MapInteractionMode(options) {
/**
* Gets or sets a callback that is invoked when the user cancels the interaction mode. If this property is undefined,
* the interaction mode cannot be canceled.
* @type {Function}
*/
this.onCancel = options.onCancel;
/**
* Gets or sets the details of a custom user interface for this map interaction mode. This property is not used by
* the `MapInteractionMode` itself, so it can be anything that is suitable for the user interface. In the standard
* React-based user interface included with TerriaJS, this property is a function that is called with no parameters
* and is expected to return a React component.
* @type {Any}
*/
this.customUi = defaultValue(options.customUi, undefined);
/**
* Gets or sets the html formatted message displayed on the map when in this mode.
* @type {Function}
*/
this.message = function() {
return options.message;
};
/**
* Set the text of the button for the dialog the message is displayed on.
* @type {String}
*/
this.buttonText = defaultValue(options.buttonText, "Cancel");
/**
* Gets or sets the features that are currently picked.
* @type {PickedFeatures}
*/
this.pickedFeatures = undefined;
/**
* Determines whether a rectangle will be requested from the user rather than a set of pickedFeatures.
* @type {Boolean}
*/
this.drawRectangle = defaultValue(options.drawRectangle, false);
knockout.track(this, ["message", "pickedFeatures", "customUi"]);
}
|
[
"function",
"MapInteractionMode",
"(",
"options",
")",
"{",
"/**\n * Gets or sets a callback that is invoked when the user cancels the interaction mode. If this property is undefined,\n * the interaction mode cannot be canceled.\n * @type {Function}\n */",
"this",
".",
"onCancel",
"=",
"options",
".",
"onCancel",
";",
"/**\n * Gets or sets the details of a custom user interface for this map interaction mode. This property is not used by\n * the `MapInteractionMode` itself, so it can be anything that is suitable for the user interface. In the standard\n * React-based user interface included with TerriaJS, this property is a function that is called with no parameters\n * and is expected to return a React component.\n * @type {Any}\n */",
"this",
".",
"customUi",
"=",
"defaultValue",
"(",
"options",
".",
"customUi",
",",
"undefined",
")",
";",
"/**\n * Gets or sets the html formatted message displayed on the map when in this mode.\n * @type {Function}\n */",
"this",
".",
"message",
"=",
"function",
"(",
")",
"{",
"return",
"options",
".",
"message",
";",
"}",
";",
"/**\n * Set the text of the button for the dialog the message is displayed on.\n * @type {String}\n */",
"this",
".",
"buttonText",
"=",
"defaultValue",
"(",
"options",
".",
"buttonText",
",",
"\"Cancel\"",
")",
";",
"/**\n * Gets or sets the features that are currently picked.\n * @type {PickedFeatures}\n */",
"this",
".",
"pickedFeatures",
"=",
"undefined",
";",
"/**\n * Determines whether a rectangle will be requested from the user rather than a set of pickedFeatures.\n * @type {Boolean}\n */",
"this",
".",
"drawRectangle",
"=",
"defaultValue",
"(",
"options",
".",
"drawRectangle",
",",
"false",
")",
";",
"knockout",
".",
"track",
"(",
"this",
",",
"[",
"\"message\"",
",",
"\"pickedFeatures\"",
",",
"\"customUi\"",
"]",
")",
";",
"}"
] |
A mode for interacting with the map.
@alias MapInteractionMode
@constructor
@param {Object} [options] Object with the following properties:
@param {Function} [options.onCancel] The function to invoke if the user cancels the interaction mode. The cancel button will
only appear if this property is specified.
@param {String} [options.message] The message to display over the map while the interaction mode is active.
|
[
"A",
"mode",
"for",
"interacting",
"with",
"the",
"map",
"."
] |
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
|
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/MapInteractionMode.js#L18-L62
|
6,994
|
TerriaJS/terriajs
|
lib/Map/MapboxVectorTileImageryProvider.js
|
function(options) {
this._uriTemplate = new URITemplate(options.url);
if (typeof options.layerName !== "string") {
throw new DeveloperError(
"MapboxVectorTileImageryProvider requires a layer name passed as options.layerName"
);
}
this._layerName = options.layerName;
this._subdomains = defaultValue(options.subdomains, []);
if (!(options.styleFunc instanceof Function)) {
throw new DeveloperError(
"MapboxVectorTileImageryProvider requires a styling function passed as options.styleFunc"
);
}
this._styleFunc = options.styleFunc;
this._tilingScheme = new WebMercatorTilingScheme();
this._tileWidth = 256;
this._tileHeight = 256;
this._minimumLevel = defaultValue(options.minimumZoom, 0);
this._maximumLevel = defaultValue(options.maximumZoom, Infinity);
this._maximumNativeLevel = defaultValue(
options.maximumNativeZoom,
this._maximumLevel
);
this._rectangle = defined(options.rectangle)
? Rectangle.intersection(options.rectangle, this._tilingScheme.rectangle)
: this._tilingScheme.rectangle;
this._uniqueIdProp = options.uniqueIdProp;
this._featureInfoFunc = options.featureInfoFunc;
//this._featurePicking = options.featurePicking;
// Check the number of tiles at the minimum level. If it's more than four,
// throw an exception, because starting at the higher minimum
// level will cause too many tiles to be downloaded and rendered.
var swTile = this._tilingScheme.positionToTileXY(
Rectangle.southwest(this._rectangle),
this._minimumLevel
);
var neTile = this._tilingScheme.positionToTileXY(
Rectangle.northeast(this._rectangle),
this._minimumLevel
);
var tileCount =
(Math.abs(neTile.x - swTile.x) + 1) * (Math.abs(neTile.y - swTile.y) + 1);
if (tileCount > 4) {
throw new DeveloperError(
"The imagery provider's rectangle and minimumLevel indicate that there are " +
tileCount +
" tiles at the minimum level. Imagery providers with more than four tiles at the minimum level are not supported."
);
}
this._errorEvent = new CesiumEvent();
this._ready = true;
}
|
javascript
|
function(options) {
this._uriTemplate = new URITemplate(options.url);
if (typeof options.layerName !== "string") {
throw new DeveloperError(
"MapboxVectorTileImageryProvider requires a layer name passed as options.layerName"
);
}
this._layerName = options.layerName;
this._subdomains = defaultValue(options.subdomains, []);
if (!(options.styleFunc instanceof Function)) {
throw new DeveloperError(
"MapboxVectorTileImageryProvider requires a styling function passed as options.styleFunc"
);
}
this._styleFunc = options.styleFunc;
this._tilingScheme = new WebMercatorTilingScheme();
this._tileWidth = 256;
this._tileHeight = 256;
this._minimumLevel = defaultValue(options.minimumZoom, 0);
this._maximumLevel = defaultValue(options.maximumZoom, Infinity);
this._maximumNativeLevel = defaultValue(
options.maximumNativeZoom,
this._maximumLevel
);
this._rectangle = defined(options.rectangle)
? Rectangle.intersection(options.rectangle, this._tilingScheme.rectangle)
: this._tilingScheme.rectangle;
this._uniqueIdProp = options.uniqueIdProp;
this._featureInfoFunc = options.featureInfoFunc;
//this._featurePicking = options.featurePicking;
// Check the number of tiles at the minimum level. If it's more than four,
// throw an exception, because starting at the higher minimum
// level will cause too many tiles to be downloaded and rendered.
var swTile = this._tilingScheme.positionToTileXY(
Rectangle.southwest(this._rectangle),
this._minimumLevel
);
var neTile = this._tilingScheme.positionToTileXY(
Rectangle.northeast(this._rectangle),
this._minimumLevel
);
var tileCount =
(Math.abs(neTile.x - swTile.x) + 1) * (Math.abs(neTile.y - swTile.y) + 1);
if (tileCount > 4) {
throw new DeveloperError(
"The imagery provider's rectangle and minimumLevel indicate that there are " +
tileCount +
" tiles at the minimum level. Imagery providers with more than four tiles at the minimum level are not supported."
);
}
this._errorEvent = new CesiumEvent();
this._ready = true;
}
|
[
"function",
"(",
"options",
")",
"{",
"this",
".",
"_uriTemplate",
"=",
"new",
"URITemplate",
"(",
"options",
".",
"url",
")",
";",
"if",
"(",
"typeof",
"options",
".",
"layerName",
"!==",
"\"string\"",
")",
"{",
"throw",
"new",
"DeveloperError",
"(",
"\"MapboxVectorTileImageryProvider requires a layer name passed as options.layerName\"",
")",
";",
"}",
"this",
".",
"_layerName",
"=",
"options",
".",
"layerName",
";",
"this",
".",
"_subdomains",
"=",
"defaultValue",
"(",
"options",
".",
"subdomains",
",",
"[",
"]",
")",
";",
"if",
"(",
"!",
"(",
"options",
".",
"styleFunc",
"instanceof",
"Function",
")",
")",
"{",
"throw",
"new",
"DeveloperError",
"(",
"\"MapboxVectorTileImageryProvider requires a styling function passed as options.styleFunc\"",
")",
";",
"}",
"this",
".",
"_styleFunc",
"=",
"options",
".",
"styleFunc",
";",
"this",
".",
"_tilingScheme",
"=",
"new",
"WebMercatorTilingScheme",
"(",
")",
";",
"this",
".",
"_tileWidth",
"=",
"256",
";",
"this",
".",
"_tileHeight",
"=",
"256",
";",
"this",
".",
"_minimumLevel",
"=",
"defaultValue",
"(",
"options",
".",
"minimumZoom",
",",
"0",
")",
";",
"this",
".",
"_maximumLevel",
"=",
"defaultValue",
"(",
"options",
".",
"maximumZoom",
",",
"Infinity",
")",
";",
"this",
".",
"_maximumNativeLevel",
"=",
"defaultValue",
"(",
"options",
".",
"maximumNativeZoom",
",",
"this",
".",
"_maximumLevel",
")",
";",
"this",
".",
"_rectangle",
"=",
"defined",
"(",
"options",
".",
"rectangle",
")",
"?",
"Rectangle",
".",
"intersection",
"(",
"options",
".",
"rectangle",
",",
"this",
".",
"_tilingScheme",
".",
"rectangle",
")",
":",
"this",
".",
"_tilingScheme",
".",
"rectangle",
";",
"this",
".",
"_uniqueIdProp",
"=",
"options",
".",
"uniqueIdProp",
";",
"this",
".",
"_featureInfoFunc",
"=",
"options",
".",
"featureInfoFunc",
";",
"//this._featurePicking = options.featurePicking;",
"// Check the number of tiles at the minimum level. If it's more than four,",
"// throw an exception, because starting at the higher minimum",
"// level will cause too many tiles to be downloaded and rendered.",
"var",
"swTile",
"=",
"this",
".",
"_tilingScheme",
".",
"positionToTileXY",
"(",
"Rectangle",
".",
"southwest",
"(",
"this",
".",
"_rectangle",
")",
",",
"this",
".",
"_minimumLevel",
")",
";",
"var",
"neTile",
"=",
"this",
".",
"_tilingScheme",
".",
"positionToTileXY",
"(",
"Rectangle",
".",
"northeast",
"(",
"this",
".",
"_rectangle",
")",
",",
"this",
".",
"_minimumLevel",
")",
";",
"var",
"tileCount",
"=",
"(",
"Math",
".",
"abs",
"(",
"neTile",
".",
"x",
"-",
"swTile",
".",
"x",
")",
"+",
"1",
")",
"*",
"(",
"Math",
".",
"abs",
"(",
"neTile",
".",
"y",
"-",
"swTile",
".",
"y",
")",
"+",
"1",
")",
";",
"if",
"(",
"tileCount",
">",
"4",
")",
"{",
"throw",
"new",
"DeveloperError",
"(",
"\"The imagery provider's rectangle and minimumLevel indicate that there are \"",
"+",
"tileCount",
"+",
"\" tiles at the minimum level. Imagery providers with more than four tiles at the minimum level are not supported.\"",
")",
";",
"}",
"this",
".",
"_errorEvent",
"=",
"new",
"CesiumEvent",
"(",
")",
";",
"this",
".",
"_ready",
"=",
"true",
";",
"}"
] |
feature.type == 3 for polygon features
|
[
"feature",
".",
"type",
"==",
"3",
"for",
"polygon",
"features"
] |
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
|
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Map/MapboxVectorTileImageryProvider.js#L25-L87
|
|
6,995
|
TerriaJS/terriajs
|
lib/Map/MapboxVectorTileImageryProvider.js
|
overzoomGeometry
|
function overzoomGeometry(rings, nativeTile, newExtent, newTile) {
var diffZ = newTile.level - nativeTile.level;
if (diffZ === 0) {
return rings;
} else {
var newRings = [];
// (offsetX, offsetY) is the (0,0) of the new tile
var offsetX = newExtent * (newTile.x - (nativeTile.x << diffZ));
var offsetY = newExtent * (newTile.y - (nativeTile.y << diffZ));
for (var i = 0; i < rings.length; i++) {
var ring = [];
for (var i2 = 0; i2 < rings[i].length; i2++) {
ring.push(rings[i][i2].sub(new Point(offsetX, offsetY)));
}
newRings.push(ring);
}
return newRings;
}
}
|
javascript
|
function overzoomGeometry(rings, nativeTile, newExtent, newTile) {
var diffZ = newTile.level - nativeTile.level;
if (diffZ === 0) {
return rings;
} else {
var newRings = [];
// (offsetX, offsetY) is the (0,0) of the new tile
var offsetX = newExtent * (newTile.x - (nativeTile.x << diffZ));
var offsetY = newExtent * (newTile.y - (nativeTile.y << diffZ));
for (var i = 0; i < rings.length; i++) {
var ring = [];
for (var i2 = 0; i2 < rings[i].length; i2++) {
ring.push(rings[i][i2].sub(new Point(offsetX, offsetY)));
}
newRings.push(ring);
}
return newRings;
}
}
|
[
"function",
"overzoomGeometry",
"(",
"rings",
",",
"nativeTile",
",",
"newExtent",
",",
"newTile",
")",
"{",
"var",
"diffZ",
"=",
"newTile",
".",
"level",
"-",
"nativeTile",
".",
"level",
";",
"if",
"(",
"diffZ",
"===",
"0",
")",
"{",
"return",
"rings",
";",
"}",
"else",
"{",
"var",
"newRings",
"=",
"[",
"]",
";",
"// (offsetX, offsetY) is the (0,0) of the new tile",
"var",
"offsetX",
"=",
"newExtent",
"*",
"(",
"newTile",
".",
"x",
"-",
"(",
"nativeTile",
".",
"x",
"<<",
"diffZ",
")",
")",
";",
"var",
"offsetY",
"=",
"newExtent",
"*",
"(",
"newTile",
".",
"y",
"-",
"(",
"nativeTile",
".",
"y",
"<<",
"diffZ",
")",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"rings",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"ring",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i2",
"=",
"0",
";",
"i2",
"<",
"rings",
"[",
"i",
"]",
".",
"length",
";",
"i2",
"++",
")",
"{",
"ring",
".",
"push",
"(",
"rings",
"[",
"i",
"]",
"[",
"i2",
"]",
".",
"sub",
"(",
"new",
"Point",
"(",
"offsetX",
",",
"offsetY",
")",
")",
")",
";",
"}",
"newRings",
".",
"push",
"(",
"ring",
")",
";",
"}",
"return",
"newRings",
";",
"}",
"}"
] |
Use x,y,level vector tile to produce imagery for newX,newY,newLevel
|
[
"Use",
"x",
"y",
"level",
"vector",
"tile",
"to",
"produce",
"imagery",
"for",
"newX",
"newY",
"newLevel"
] |
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
|
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Map/MapboxVectorTileImageryProvider.js#L223-L241
|
6,996
|
TerriaJS/terriajs
|
lib/Map/MapboxVectorTileImageryProvider.js
|
inside
|
function inside(point, vs) {
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
var x = point.x,
y = point.y;
var inside = false;
for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
var xi = vs[i].x,
yi = vs[i].y;
var xj = vs[j].x,
yj = vs[j].y;
var intersect =
yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi;
if (intersect) inside = !inside;
}
return inside;
}
|
javascript
|
function inside(point, vs) {
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
var x = point.x,
y = point.y;
var inside = false;
for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
var xi = vs[i].x,
yi = vs[i].y;
var xj = vs[j].x,
yj = vs[j].y;
var intersect =
yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi;
if (intersect) inside = !inside;
}
return inside;
}
|
[
"function",
"inside",
"(",
"point",
",",
"vs",
")",
"{",
"// ray-casting algorithm based on",
"// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html",
"var",
"x",
"=",
"point",
".",
"x",
",",
"y",
"=",
"point",
".",
"y",
";",
"var",
"inside",
"=",
"false",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"j",
"=",
"vs",
".",
"length",
"-",
"1",
";",
"i",
"<",
"vs",
".",
"length",
";",
"j",
"=",
"i",
"++",
")",
"{",
"var",
"xi",
"=",
"vs",
"[",
"i",
"]",
".",
"x",
",",
"yi",
"=",
"vs",
"[",
"i",
"]",
".",
"y",
";",
"var",
"xj",
"=",
"vs",
"[",
"j",
"]",
".",
"x",
",",
"yj",
"=",
"vs",
"[",
"j",
"]",
".",
"y",
";",
"var",
"intersect",
"=",
"yi",
">",
"y",
"!==",
"yj",
">",
"y",
"&&",
"x",
"<",
"(",
"(",
"xj",
"-",
"xi",
")",
"*",
"(",
"y",
"-",
"yi",
")",
")",
"/",
"(",
"yj",
"-",
"yi",
")",
"+",
"xi",
";",
"if",
"(",
"intersect",
")",
"inside",
"=",
"!",
"inside",
";",
"}",
"return",
"inside",
";",
"}"
] |
Adapted from npm package "point-in-polygon" by James Halliday Licence included in LICENSE.md
|
[
"Adapted",
"from",
"npm",
"package",
"point",
"-",
"in",
"-",
"polygon",
"by",
"James",
"Halliday",
"Licence",
"included",
"in",
"LICENSE",
".",
"md"
] |
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
|
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Map/MapboxVectorTileImageryProvider.js#L343-L363
|
6,997
|
TerriaJS/terriajs
|
lib/Models/SdmxJsonCatalogItem.js
|
updateColumns
|
function updateColumns(item, newColumns) {
item._tableStructure.columns = newColumns;
if (item._tableStructure.columns.length === 0) {
// Nothing to show, so the attempt to redraw will fail; need to explicitly hide the existing regions.
item._regionMapping.hideImageryLayer();
item.terria.currentViewer.notifyRepaintRequired();
}
// Close any picked features, as the description of any associated with this catalog item may change.
item.terria.pickedFeatures = undefined;
}
|
javascript
|
function updateColumns(item, newColumns) {
item._tableStructure.columns = newColumns;
if (item._tableStructure.columns.length === 0) {
// Nothing to show, so the attempt to redraw will fail; need to explicitly hide the existing regions.
item._regionMapping.hideImageryLayer();
item.terria.currentViewer.notifyRepaintRequired();
}
// Close any picked features, as the description of any associated with this catalog item may change.
item.terria.pickedFeatures = undefined;
}
|
[
"function",
"updateColumns",
"(",
"item",
",",
"newColumns",
")",
"{",
"item",
".",
"_tableStructure",
".",
"columns",
"=",
"newColumns",
";",
"if",
"(",
"item",
".",
"_tableStructure",
".",
"columns",
".",
"length",
"===",
"0",
")",
"{",
"// Nothing to show, so the attempt to redraw will fail; need to explicitly hide the existing regions.",
"item",
".",
"_regionMapping",
".",
"hideImageryLayer",
"(",
")",
";",
"item",
".",
"terria",
".",
"currentViewer",
".",
"notifyRepaintRequired",
"(",
")",
";",
"}",
"// Close any picked features, as the description of any associated with this catalog item may change.",
"item",
".",
"terria",
".",
"pickedFeatures",
"=",
"undefined",
";",
"}"
] |
Sets the tableStructure's columns to the new columns, redraws the map, and closes the feature info panel.
|
[
"Sets",
"the",
"tableStructure",
"s",
"columns",
"to",
"the",
"new",
"columns",
"redraws",
"the",
"map",
"and",
"closes",
"the",
"feature",
"info",
"panel",
"."
] |
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
|
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/SdmxJsonCatalogItem.js#L627-L636
|
6,998
|
TerriaJS/terriajs
|
lib/Models/SdmxJsonCatalogItem.js
|
fixSelectedInitially
|
function fixSelectedInitially(item, conceptDimensions) {
conceptDimensions.forEach(dimension => {
if (defined(item.selectedInitially)) {
var thisSelectedInitially = item.selectedInitially[dimension.id];
if (thisSelectedInitially) {
var valueIds = dimension.values.map(value => value.id);
if (
!thisSelectedInitially.some(
initialValue => valueIds.indexOf(initialValue) >= 0
)
) {
console.warn(
"Ignoring invalid initial selection " +
thisSelectedInitially +
" on " +
dimension.name
);
item.selectedInitially[dimension.id] = undefined;
}
}
}
});
}
|
javascript
|
function fixSelectedInitially(item, conceptDimensions) {
conceptDimensions.forEach(dimension => {
if (defined(item.selectedInitially)) {
var thisSelectedInitially = item.selectedInitially[dimension.id];
if (thisSelectedInitially) {
var valueIds = dimension.values.map(value => value.id);
if (
!thisSelectedInitially.some(
initialValue => valueIds.indexOf(initialValue) >= 0
)
) {
console.warn(
"Ignoring invalid initial selection " +
thisSelectedInitially +
" on " +
dimension.name
);
item.selectedInitially[dimension.id] = undefined;
}
}
}
});
}
|
[
"function",
"fixSelectedInitially",
"(",
"item",
",",
"conceptDimensions",
")",
"{",
"conceptDimensions",
".",
"forEach",
"(",
"dimension",
"=>",
"{",
"if",
"(",
"defined",
"(",
"item",
".",
"selectedInitially",
")",
")",
"{",
"var",
"thisSelectedInitially",
"=",
"item",
".",
"selectedInitially",
"[",
"dimension",
".",
"id",
"]",
";",
"if",
"(",
"thisSelectedInitially",
")",
"{",
"var",
"valueIds",
"=",
"dimension",
".",
"values",
".",
"map",
"(",
"value",
"=>",
"value",
".",
"id",
")",
";",
"if",
"(",
"!",
"thisSelectedInitially",
".",
"some",
"(",
"initialValue",
"=>",
"valueIds",
".",
"indexOf",
"(",
"initialValue",
")",
">=",
"0",
")",
")",
"{",
"console",
".",
"warn",
"(",
"\"Ignoring invalid initial selection \"",
"+",
"thisSelectedInitially",
"+",
"\" on \"",
"+",
"dimension",
".",
"name",
")",
";",
"item",
".",
"selectedInitially",
"[",
"dimension",
".",
"id",
"]",
"=",
"undefined",
";",
"}",
"}",
"}",
"}",
")",
";",
"}"
] |
Check if item.selectedInitially has at least one value that exists in dimension.values, and if it doesn't, reset item.selectedInitially.
|
[
"Check",
"if",
"item",
".",
"selectedInitially",
"has",
"at",
"least",
"one",
"value",
"that",
"exists",
"in",
"dimension",
".",
"values",
"and",
"if",
"it",
"doesn",
"t",
"reset",
"item",
".",
"selectedInitially",
"."
] |
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
|
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/SdmxJsonCatalogItem.js#L1164-L1186
|
6,999
|
TerriaJS/terriajs
|
lib/Models/SdmxJsonCatalogItem.js
|
buildConcepts
|
function buildConcepts(item, fullDimensions) {
function isInitiallyActive(dimensionId, value, index) {
if (!defined(item.selectedInitially)) {
return index === 0;
}
var dimensionSelectedInitially = item.selectedInitially[dimensionId];
if (!defined(dimensionSelectedInitially)) {
return index === 0;
}
return dimensionSelectedInitially.indexOf(value.id) >= 0;
}
var conceptDimensions = getShownDimensions(
item,
fullDimensions,
fullDimensions
);
fixSelectedInitially(item, conceptDimensions); // Note side-effect.
var concepts = conceptDimensions.map(function(dimension, i) {
var allowMultiple =
item.allSingleValuedDimensionIds.indexOf(dimension.id) === -1;
var concept = new DisplayVariablesConcept(dimension.name, {
isOpen: false,
allowMultiple: allowMultiple,
requireSomeActive: true,
exclusiveChildIds: getTotalValueIdsForDimensionId(item, dimension.id)
});
concept.id = dimension.id;
concept.items = dimension.values.map(function(value, index) {
return new VariableConcept(renameValue(item, value.name), {
parent: concept,
id: value.id,
active: isInitiallyActive(concept.id, value, index)
});
});
return concept;
});
if (concepts.length > 0) {
return [new SummaryConcept(undefined, { items: concepts, isOpen: false })];
}
return [];
}
|
javascript
|
function buildConcepts(item, fullDimensions) {
function isInitiallyActive(dimensionId, value, index) {
if (!defined(item.selectedInitially)) {
return index === 0;
}
var dimensionSelectedInitially = item.selectedInitially[dimensionId];
if (!defined(dimensionSelectedInitially)) {
return index === 0;
}
return dimensionSelectedInitially.indexOf(value.id) >= 0;
}
var conceptDimensions = getShownDimensions(
item,
fullDimensions,
fullDimensions
);
fixSelectedInitially(item, conceptDimensions); // Note side-effect.
var concepts = conceptDimensions.map(function(dimension, i) {
var allowMultiple =
item.allSingleValuedDimensionIds.indexOf(dimension.id) === -1;
var concept = new DisplayVariablesConcept(dimension.name, {
isOpen: false,
allowMultiple: allowMultiple,
requireSomeActive: true,
exclusiveChildIds: getTotalValueIdsForDimensionId(item, dimension.id)
});
concept.id = dimension.id;
concept.items = dimension.values.map(function(value, index) {
return new VariableConcept(renameValue(item, value.name), {
parent: concept,
id: value.id,
active: isInitiallyActive(concept.id, value, index)
});
});
return concept;
});
if (concepts.length > 0) {
return [new SummaryConcept(undefined, { items: concepts, isOpen: false })];
}
return [];
}
|
[
"function",
"buildConcepts",
"(",
"item",
",",
"fullDimensions",
")",
"{",
"function",
"isInitiallyActive",
"(",
"dimensionId",
",",
"value",
",",
"index",
")",
"{",
"if",
"(",
"!",
"defined",
"(",
"item",
".",
"selectedInitially",
")",
")",
"{",
"return",
"index",
"===",
"0",
";",
"}",
"var",
"dimensionSelectedInitially",
"=",
"item",
".",
"selectedInitially",
"[",
"dimensionId",
"]",
";",
"if",
"(",
"!",
"defined",
"(",
"dimensionSelectedInitially",
")",
")",
"{",
"return",
"index",
"===",
"0",
";",
"}",
"return",
"dimensionSelectedInitially",
".",
"indexOf",
"(",
"value",
".",
"id",
")",
">=",
"0",
";",
"}",
"var",
"conceptDimensions",
"=",
"getShownDimensions",
"(",
"item",
",",
"fullDimensions",
",",
"fullDimensions",
")",
";",
"fixSelectedInitially",
"(",
"item",
",",
"conceptDimensions",
")",
";",
"// Note side-effect.",
"var",
"concepts",
"=",
"conceptDimensions",
".",
"map",
"(",
"function",
"(",
"dimension",
",",
"i",
")",
"{",
"var",
"allowMultiple",
"=",
"item",
".",
"allSingleValuedDimensionIds",
".",
"indexOf",
"(",
"dimension",
".",
"id",
")",
"===",
"-",
"1",
";",
"var",
"concept",
"=",
"new",
"DisplayVariablesConcept",
"(",
"dimension",
".",
"name",
",",
"{",
"isOpen",
":",
"false",
",",
"allowMultiple",
":",
"allowMultiple",
",",
"requireSomeActive",
":",
"true",
",",
"exclusiveChildIds",
":",
"getTotalValueIdsForDimensionId",
"(",
"item",
",",
"dimension",
".",
"id",
")",
"}",
")",
";",
"concept",
".",
"id",
"=",
"dimension",
".",
"id",
";",
"concept",
".",
"items",
"=",
"dimension",
".",
"values",
".",
"map",
"(",
"function",
"(",
"value",
",",
"index",
")",
"{",
"return",
"new",
"VariableConcept",
"(",
"renameValue",
"(",
"item",
",",
"value",
".",
"name",
")",
",",
"{",
"parent",
":",
"concept",
",",
"id",
":",
"value",
".",
"id",
",",
"active",
":",
"isInitiallyActive",
"(",
"concept",
".",
"id",
",",
"value",
",",
"index",
")",
"}",
")",
";",
"}",
")",
";",
"return",
"concept",
";",
"}",
")",
";",
"if",
"(",
"concepts",
".",
"length",
">",
"0",
")",
"{",
"return",
"[",
"new",
"SummaryConcept",
"(",
"undefined",
",",
"{",
"items",
":",
"concepts",
",",
"isOpen",
":",
"false",
"}",
")",
"]",
";",
"}",
"return",
"[",
"]",
";",
"}"
] |
Build out the concepts displayed in the NowViewing panel. Also fixes selectedInitially, if broken.
|
[
"Build",
"out",
"the",
"concepts",
"displayed",
"in",
"the",
"NowViewing",
"panel",
".",
"Also",
"fixes",
"selectedInitially",
"if",
"broken",
"."
] |
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
|
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/SdmxJsonCatalogItem.js#L1189-L1230
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.