id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
|---|---|---|---|---|---|---|---|---|---|---|---|
16,300
|
graphology/graphology
|
src/iteration/edges.js
|
createIteratorForKey
|
function createIteratorForKey(object, k) {
const v = object[k];
if (v instanceof Set) {
const iterator = v.values();
return new Iterator(function() {
const step = iterator.next();
if (step.done)
return step;
const edgeData = step.value;
return {
done: false,
value: [
edgeData.key,
edgeData.attributes,
edgeData.source.key,
edgeData.target.key,
edgeData.source.attributes,
edgeData.target.attributes
]
};
});
}
return Iterator.of([
v.key,
v.attributes,
v.source.key,
v.target.key,
v.source.attributes,
v.target.attributes
]);
}
|
javascript
|
function createIteratorForKey(object, k) {
const v = object[k];
if (v instanceof Set) {
const iterator = v.values();
return new Iterator(function() {
const step = iterator.next();
if (step.done)
return step;
const edgeData = step.value;
return {
done: false,
value: [
edgeData.key,
edgeData.attributes,
edgeData.source.key,
edgeData.target.key,
edgeData.source.attributes,
edgeData.target.attributes
]
};
});
}
return Iterator.of([
v.key,
v.attributes,
v.source.key,
v.target.key,
v.source.attributes,
v.target.attributes
]);
}
|
[
"function",
"createIteratorForKey",
"(",
"object",
",",
"k",
")",
"{",
"const",
"v",
"=",
"object",
"[",
"k",
"]",
";",
"if",
"(",
"v",
"instanceof",
"Set",
")",
"{",
"const",
"iterator",
"=",
"v",
".",
"values",
"(",
")",
";",
"return",
"new",
"Iterator",
"(",
"function",
"(",
")",
"{",
"const",
"step",
"=",
"iterator",
".",
"next",
"(",
")",
";",
"if",
"(",
"step",
".",
"done",
")",
"return",
"step",
";",
"const",
"edgeData",
"=",
"step",
".",
"value",
";",
"return",
"{",
"done",
":",
"false",
",",
"value",
":",
"[",
"edgeData",
".",
"key",
",",
"edgeData",
".",
"attributes",
",",
"edgeData",
".",
"source",
".",
"key",
",",
"edgeData",
".",
"target",
".",
"key",
",",
"edgeData",
".",
"source",
".",
"attributes",
",",
"edgeData",
".",
"target",
".",
"attributes",
"]",
"}",
";",
"}",
")",
";",
"}",
"return",
"Iterator",
".",
"of",
"(",
"[",
"v",
".",
"key",
",",
"v",
".",
"attributes",
",",
"v",
".",
"source",
".",
"key",
",",
"v",
".",
"target",
".",
"key",
",",
"v",
".",
"source",
".",
"attributes",
",",
"v",
".",
"target",
".",
"attributes",
"]",
")",
";",
"}"
] |
Function returning an iterator over the egdes from the object at given key.
@param {object} object - Target object.
@param {mixed} k - Neighbor key.
@return {Iterator}
|
[
"Function",
"returning",
"an",
"iterator",
"over",
"the",
"egdes",
"from",
"the",
"object",
"at",
"given",
"key",
"."
] |
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
|
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/iteration/edges.js#L228-L264
|
16,301
|
graphology/graphology
|
src/iteration/edges.js
|
createEdgeArray
|
function createEdgeArray(graph, type) {
if (graph.size === 0)
return [];
if (type === 'mixed' || type === graph.type)
return take(graph._edges.keys(), graph._edges.size);
const size = type === 'undirected' ?
graph.undirectedSize :
graph.directedSize;
const list = new Array(size),
mask = type === 'undirected';
let i = 0;
graph._edges.forEach((data, edge) => {
if ((data instanceof UndirectedEdgeData) === mask)
list[i++] = edge;
});
return list;
}
|
javascript
|
function createEdgeArray(graph, type) {
if (graph.size === 0)
return [];
if (type === 'mixed' || type === graph.type)
return take(graph._edges.keys(), graph._edges.size);
const size = type === 'undirected' ?
graph.undirectedSize :
graph.directedSize;
const list = new Array(size),
mask = type === 'undirected';
let i = 0;
graph._edges.forEach((data, edge) => {
if ((data instanceof UndirectedEdgeData) === mask)
list[i++] = edge;
});
return list;
}
|
[
"function",
"createEdgeArray",
"(",
"graph",
",",
"type",
")",
"{",
"if",
"(",
"graph",
".",
"size",
"===",
"0",
")",
"return",
"[",
"]",
";",
"if",
"(",
"type",
"===",
"'mixed'",
"||",
"type",
"===",
"graph",
".",
"type",
")",
"return",
"take",
"(",
"graph",
".",
"_edges",
".",
"keys",
"(",
")",
",",
"graph",
".",
"_edges",
".",
"size",
")",
";",
"const",
"size",
"=",
"type",
"===",
"'undirected'",
"?",
"graph",
".",
"undirectedSize",
":",
"graph",
".",
"directedSize",
";",
"const",
"list",
"=",
"new",
"Array",
"(",
"size",
")",
",",
"mask",
"=",
"type",
"===",
"'undirected'",
";",
"let",
"i",
"=",
"0",
";",
"graph",
".",
"_edges",
".",
"forEach",
"(",
"(",
"data",
",",
"edge",
")",
"=>",
"{",
"if",
"(",
"(",
"data",
"instanceof",
"UndirectedEdgeData",
")",
"===",
"mask",
")",
"list",
"[",
"i",
"++",
"]",
"=",
"edge",
";",
"}",
")",
";",
"return",
"list",
";",
"}"
] |
Function creating an array of edges for the given type.
@param {Graph} graph - Target Graph instance.
@param {string} type - Type of edges to retrieve.
@return {array} - Array of edges.
|
[
"Function",
"creating",
"an",
"array",
"of",
"edges",
"for",
"the",
"given",
"type",
"."
] |
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
|
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/iteration/edges.js#L273-L296
|
16,302
|
graphology/graphology
|
src/iteration/edges.js
|
forEachEdge
|
function forEachEdge(graph, type, callback) {
if (graph.size === 0)
return;
if (type === 'mixed' || type === graph.type) {
graph._edges.forEach((data, key) => {
const {attributes, source, target} = data;
callback(
key,
attributes,
source.key,
target.key,
source.attributes,
target.attributes
);
});
}
else {
const mask = type === 'undirected';
graph._edges.forEach((data, key) => {
if ((data instanceof UndirectedEdgeData) === mask) {
const {attributes, source, target} = data;
callback(
key,
attributes,
source.key,
target.key,
source.attributes,
target.attributes
);
}
});
}
}
|
javascript
|
function forEachEdge(graph, type, callback) {
if (graph.size === 0)
return;
if (type === 'mixed' || type === graph.type) {
graph._edges.forEach((data, key) => {
const {attributes, source, target} = data;
callback(
key,
attributes,
source.key,
target.key,
source.attributes,
target.attributes
);
});
}
else {
const mask = type === 'undirected';
graph._edges.forEach((data, key) => {
if ((data instanceof UndirectedEdgeData) === mask) {
const {attributes, source, target} = data;
callback(
key,
attributes,
source.key,
target.key,
source.attributes,
target.attributes
);
}
});
}
}
|
[
"function",
"forEachEdge",
"(",
"graph",
",",
"type",
",",
"callback",
")",
"{",
"if",
"(",
"graph",
".",
"size",
"===",
"0",
")",
"return",
";",
"if",
"(",
"type",
"===",
"'mixed'",
"||",
"type",
"===",
"graph",
".",
"type",
")",
"{",
"graph",
".",
"_edges",
".",
"forEach",
"(",
"(",
"data",
",",
"key",
")",
"=>",
"{",
"const",
"{",
"attributes",
",",
"source",
",",
"target",
"}",
"=",
"data",
";",
"callback",
"(",
"key",
",",
"attributes",
",",
"source",
".",
"key",
",",
"target",
".",
"key",
",",
"source",
".",
"attributes",
",",
"target",
".",
"attributes",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"const",
"mask",
"=",
"type",
"===",
"'undirected'",
";",
"graph",
".",
"_edges",
".",
"forEach",
"(",
"(",
"data",
",",
"key",
")",
"=>",
"{",
"if",
"(",
"(",
"data",
"instanceof",
"UndirectedEdgeData",
")",
"===",
"mask",
")",
"{",
"const",
"{",
"attributes",
",",
"source",
",",
"target",
"}",
"=",
"data",
";",
"callback",
"(",
"key",
",",
"attributes",
",",
"source",
".",
"key",
",",
"target",
".",
"key",
",",
"source",
".",
"attributes",
",",
"target",
".",
"attributes",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] |
Function iterating over a graph's edges using a callback.
@param {Graph} graph - Target Graph instance.
@param {string} type - Type of edges to retrieve.
@param {function} callback - Function to call.
|
[
"Function",
"iterating",
"over",
"a",
"graph",
"s",
"edges",
"using",
"a",
"callback",
"."
] |
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
|
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/iteration/edges.js#L305-L343
|
16,303
|
graphology/graphology
|
src/iteration/edges.js
|
createEdgeIterator
|
function createEdgeIterator(graph, type) {
if (graph.size === 0)
return Iterator.empty();
let iterator;
if (type === 'mixed') {
iterator = graph._edges.values();
return new Iterator(function next() {
const step = iterator.next();
if (step.done)
return step;
const data = step.value;
const value = [
data.key,
data.attributes,
data.source.key,
data.target.key,
data.source.attributes,
data.target.attributes
];
return {value, done: false};
});
}
iterator = graph._edges.values();
return new Iterator(function next() {
const step = iterator.next();
if (step.done)
return step;
const data = step.value;
if ((data instanceof UndirectedEdgeData) === (type === 'undirected')) {
const value = [
data.key,
data.attributes,
data.source.key,
data.target.key,
data.source.attributes,
data.target.attributes
];
return {value, done: false};
}
return next();
});
}
|
javascript
|
function createEdgeIterator(graph, type) {
if (graph.size === 0)
return Iterator.empty();
let iterator;
if (type === 'mixed') {
iterator = graph._edges.values();
return new Iterator(function next() {
const step = iterator.next();
if (step.done)
return step;
const data = step.value;
const value = [
data.key,
data.attributes,
data.source.key,
data.target.key,
data.source.attributes,
data.target.attributes
];
return {value, done: false};
});
}
iterator = graph._edges.values();
return new Iterator(function next() {
const step = iterator.next();
if (step.done)
return step;
const data = step.value;
if ((data instanceof UndirectedEdgeData) === (type === 'undirected')) {
const value = [
data.key,
data.attributes,
data.source.key,
data.target.key,
data.source.attributes,
data.target.attributes
];
return {value, done: false};
}
return next();
});
}
|
[
"function",
"createEdgeIterator",
"(",
"graph",
",",
"type",
")",
"{",
"if",
"(",
"graph",
".",
"size",
"===",
"0",
")",
"return",
"Iterator",
".",
"empty",
"(",
")",
";",
"let",
"iterator",
";",
"if",
"(",
"type",
"===",
"'mixed'",
")",
"{",
"iterator",
"=",
"graph",
".",
"_edges",
".",
"values",
"(",
")",
";",
"return",
"new",
"Iterator",
"(",
"function",
"next",
"(",
")",
"{",
"const",
"step",
"=",
"iterator",
".",
"next",
"(",
")",
";",
"if",
"(",
"step",
".",
"done",
")",
"return",
"step",
";",
"const",
"data",
"=",
"step",
".",
"value",
";",
"const",
"value",
"=",
"[",
"data",
".",
"key",
",",
"data",
".",
"attributes",
",",
"data",
".",
"source",
".",
"key",
",",
"data",
".",
"target",
".",
"key",
",",
"data",
".",
"source",
".",
"attributes",
",",
"data",
".",
"target",
".",
"attributes",
"]",
";",
"return",
"{",
"value",
",",
"done",
":",
"false",
"}",
";",
"}",
")",
";",
"}",
"iterator",
"=",
"graph",
".",
"_edges",
".",
"values",
"(",
")",
";",
"return",
"new",
"Iterator",
"(",
"function",
"next",
"(",
")",
"{",
"const",
"step",
"=",
"iterator",
".",
"next",
"(",
")",
";",
"if",
"(",
"step",
".",
"done",
")",
"return",
"step",
";",
"const",
"data",
"=",
"step",
".",
"value",
";",
"if",
"(",
"(",
"data",
"instanceof",
"UndirectedEdgeData",
")",
"===",
"(",
"type",
"===",
"'undirected'",
")",
")",
"{",
"const",
"value",
"=",
"[",
"data",
".",
"key",
",",
"data",
".",
"attributes",
",",
"data",
".",
"source",
".",
"key",
",",
"data",
".",
"target",
".",
"key",
",",
"data",
".",
"source",
".",
"attributes",
",",
"data",
".",
"target",
".",
"attributes",
"]",
";",
"return",
"{",
"value",
",",
"done",
":",
"false",
"}",
";",
"}",
"return",
"next",
"(",
")",
";",
"}",
")",
";",
"}"
] |
Function creating an iterator of edges for the given type.
@param {Graph} graph - Target Graph instance.
@param {string} type - Type of edges to retrieve.
@return {Iterator}
|
[
"Function",
"creating",
"an",
"iterator",
"of",
"edges",
"for",
"the",
"given",
"type",
"."
] |
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
|
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/iteration/edges.js#L352-L407
|
16,304
|
graphology/graphology
|
src/iteration/edges.js
|
createEdgeArrayForNode
|
function createEdgeArrayForNode(type, direction, nodeData) {
const edges = [];
if (type !== 'undirected') {
if (direction !== 'out')
collect(edges, nodeData.in);
if (direction !== 'in')
collect(edges, nodeData.out);
}
if (type !== 'directed') {
collect(edges, nodeData.undirected);
}
return edges;
}
|
javascript
|
function createEdgeArrayForNode(type, direction, nodeData) {
const edges = [];
if (type !== 'undirected') {
if (direction !== 'out')
collect(edges, nodeData.in);
if (direction !== 'in')
collect(edges, nodeData.out);
}
if (type !== 'directed') {
collect(edges, nodeData.undirected);
}
return edges;
}
|
[
"function",
"createEdgeArrayForNode",
"(",
"type",
",",
"direction",
",",
"nodeData",
")",
"{",
"const",
"edges",
"=",
"[",
"]",
";",
"if",
"(",
"type",
"!==",
"'undirected'",
")",
"{",
"if",
"(",
"direction",
"!==",
"'out'",
")",
"collect",
"(",
"edges",
",",
"nodeData",
".",
"in",
")",
";",
"if",
"(",
"direction",
"!==",
"'in'",
")",
"collect",
"(",
"edges",
",",
"nodeData",
".",
"out",
")",
";",
"}",
"if",
"(",
"type",
"!==",
"'directed'",
")",
"{",
"collect",
"(",
"edges",
",",
"nodeData",
".",
"undirected",
")",
";",
"}",
"return",
"edges",
";",
"}"
] |
Function creating an array of edges for the given type & the given node.
@param {string} type - Type of edges to retrieve.
@param {string} direction - In or out?
@param {any} nodeData - Target node's data.
@return {array} - Array of edges.
|
[
"Function",
"creating",
"an",
"array",
"of",
"edges",
"for",
"the",
"given",
"type",
"&",
"the",
"given",
"node",
"."
] |
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
|
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/iteration/edges.js#L417-L432
|
16,305
|
graphology/graphology
|
src/iteration/edges.js
|
createEdgeArrayForPath
|
function createEdgeArrayForPath(type, direction, sourceData, target) {
const edges = [];
if (type !== 'undirected') {
if (typeof sourceData.in !== 'undefined' && direction !== 'out')
collectForKey(edges, sourceData.in, target);
if (typeof sourceData.out !== 'undefined' && direction !== 'in')
collectForKey(edges, sourceData.out, target);
}
if (type !== 'directed') {
if (typeof sourceData.undirected !== 'undefined')
collectForKey(edges, sourceData.undirected, target);
}
return edges;
}
|
javascript
|
function createEdgeArrayForPath(type, direction, sourceData, target) {
const edges = [];
if (type !== 'undirected') {
if (typeof sourceData.in !== 'undefined' && direction !== 'out')
collectForKey(edges, sourceData.in, target);
if (typeof sourceData.out !== 'undefined' && direction !== 'in')
collectForKey(edges, sourceData.out, target);
}
if (type !== 'directed') {
if (typeof sourceData.undirected !== 'undefined')
collectForKey(edges, sourceData.undirected, target);
}
return edges;
}
|
[
"function",
"createEdgeArrayForPath",
"(",
"type",
",",
"direction",
",",
"sourceData",
",",
"target",
")",
"{",
"const",
"edges",
"=",
"[",
"]",
";",
"if",
"(",
"type",
"!==",
"'undirected'",
")",
"{",
"if",
"(",
"typeof",
"sourceData",
".",
"in",
"!==",
"'undefined'",
"&&",
"direction",
"!==",
"'out'",
")",
"collectForKey",
"(",
"edges",
",",
"sourceData",
".",
"in",
",",
"target",
")",
";",
"if",
"(",
"typeof",
"sourceData",
".",
"out",
"!==",
"'undefined'",
"&&",
"direction",
"!==",
"'in'",
")",
"collectForKey",
"(",
"edges",
",",
"sourceData",
".",
"out",
",",
"target",
")",
";",
"}",
"if",
"(",
"type",
"!==",
"'directed'",
")",
"{",
"if",
"(",
"typeof",
"sourceData",
".",
"undirected",
"!==",
"'undefined'",
")",
"collectForKey",
"(",
"edges",
",",
"sourceData",
".",
"undirected",
",",
"target",
")",
";",
"}",
"return",
"edges",
";",
"}"
] |
Function creating an array of edges for the given path.
@param {string} type - Type of edges to retrieve.
@param {string} direction - In or out?
@param {NodeData} sourceData - Source node's data.
@param {any} target - Target node.
@return {array} - Array of edges.
|
[
"Function",
"creating",
"an",
"array",
"of",
"edges",
"for",
"the",
"given",
"path",
"."
] |
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
|
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/iteration/edges.js#L490-L508
|
16,306
|
graphology/graphology
|
src/iteration/edges.js
|
forEachEdgeForPath
|
function forEachEdgeForPath(type, direction, sourceData, target, callback) {
if (type !== 'undirected') {
if (typeof sourceData.in !== 'undefined' && direction !== 'out')
forEachForKey(sourceData.in, target, callback);
if (typeof sourceData.out !== 'undefined' && direction !== 'in')
forEachForKey(sourceData.out, target, callback);
}
if (type !== 'directed') {
if (typeof sourceData.undirected !== 'undefined')
forEachForKey(sourceData.undirected, target, callback);
}
}
|
javascript
|
function forEachEdgeForPath(type, direction, sourceData, target, callback) {
if (type !== 'undirected') {
if (typeof sourceData.in !== 'undefined' && direction !== 'out')
forEachForKey(sourceData.in, target, callback);
if (typeof sourceData.out !== 'undefined' && direction !== 'in')
forEachForKey(sourceData.out, target, callback);
}
if (type !== 'directed') {
if (typeof sourceData.undirected !== 'undefined')
forEachForKey(sourceData.undirected, target, callback);
}
}
|
[
"function",
"forEachEdgeForPath",
"(",
"type",
",",
"direction",
",",
"sourceData",
",",
"target",
",",
"callback",
")",
"{",
"if",
"(",
"type",
"!==",
"'undirected'",
")",
"{",
"if",
"(",
"typeof",
"sourceData",
".",
"in",
"!==",
"'undefined'",
"&&",
"direction",
"!==",
"'out'",
")",
"forEachForKey",
"(",
"sourceData",
".",
"in",
",",
"target",
",",
"callback",
")",
";",
"if",
"(",
"typeof",
"sourceData",
".",
"out",
"!==",
"'undefined'",
"&&",
"direction",
"!==",
"'in'",
")",
"forEachForKey",
"(",
"sourceData",
".",
"out",
",",
"target",
",",
"callback",
")",
";",
"}",
"if",
"(",
"type",
"!==",
"'directed'",
")",
"{",
"if",
"(",
"typeof",
"sourceData",
".",
"undirected",
"!==",
"'undefined'",
")",
"forEachForKey",
"(",
"sourceData",
".",
"undirected",
",",
"target",
",",
"callback",
")",
";",
"}",
"}"
] |
Function iterating over edges for the given path using a callback.
@param {string} type - Type of edges to retrieve.
@param {string} direction - In or out?
@param {NodeData} sourceData - Source node's data.
@param {string} target - Target node.
@param {function} callback - Function to call.
|
[
"Function",
"iterating",
"over",
"edges",
"for",
"the",
"given",
"path",
"using",
"a",
"callback",
"."
] |
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
|
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/iteration/edges.js#L519-L533
|
16,307
|
graphology/graphology
|
src/iteration/edges.js
|
createEdgeIteratorForPath
|
function createEdgeIteratorForPath(type, direction, sourceData, target) {
let iterator = Iterator.empty();
if (type !== 'undirected') {
if (
typeof sourceData.in !== 'undefined' &&
direction !== 'out' &&
target in sourceData.in
)
iterator = chain(iterator, createIteratorForKey(sourceData.in, target));
if (
typeof sourceData.out !== 'undefined' &&
direction !== 'in' &&
target in sourceData.out
)
iterator = chain(iterator, createIteratorForKey(sourceData.out, target));
}
if (type !== 'directed') {
if (
typeof sourceData.undirected !== 'undefined' &&
target in sourceData.undirected
)
iterator = chain(iterator, createIteratorForKey(sourceData.undirected, target));
}
return iterator;
}
|
javascript
|
function createEdgeIteratorForPath(type, direction, sourceData, target) {
let iterator = Iterator.empty();
if (type !== 'undirected') {
if (
typeof sourceData.in !== 'undefined' &&
direction !== 'out' &&
target in sourceData.in
)
iterator = chain(iterator, createIteratorForKey(sourceData.in, target));
if (
typeof sourceData.out !== 'undefined' &&
direction !== 'in' &&
target in sourceData.out
)
iterator = chain(iterator, createIteratorForKey(sourceData.out, target));
}
if (type !== 'directed') {
if (
typeof sourceData.undirected !== 'undefined' &&
target in sourceData.undirected
)
iterator = chain(iterator, createIteratorForKey(sourceData.undirected, target));
}
return iterator;
}
|
[
"function",
"createEdgeIteratorForPath",
"(",
"type",
",",
"direction",
",",
"sourceData",
",",
"target",
")",
"{",
"let",
"iterator",
"=",
"Iterator",
".",
"empty",
"(",
")",
";",
"if",
"(",
"type",
"!==",
"'undirected'",
")",
"{",
"if",
"(",
"typeof",
"sourceData",
".",
"in",
"!==",
"'undefined'",
"&&",
"direction",
"!==",
"'out'",
"&&",
"target",
"in",
"sourceData",
".",
"in",
")",
"iterator",
"=",
"chain",
"(",
"iterator",
",",
"createIteratorForKey",
"(",
"sourceData",
".",
"in",
",",
"target",
")",
")",
";",
"if",
"(",
"typeof",
"sourceData",
".",
"out",
"!==",
"'undefined'",
"&&",
"direction",
"!==",
"'in'",
"&&",
"target",
"in",
"sourceData",
".",
"out",
")",
"iterator",
"=",
"chain",
"(",
"iterator",
",",
"createIteratorForKey",
"(",
"sourceData",
".",
"out",
",",
"target",
")",
")",
";",
"}",
"if",
"(",
"type",
"!==",
"'directed'",
")",
"{",
"if",
"(",
"typeof",
"sourceData",
".",
"undirected",
"!==",
"'undefined'",
"&&",
"target",
"in",
"sourceData",
".",
"undirected",
")",
"iterator",
"=",
"chain",
"(",
"iterator",
",",
"createIteratorForKey",
"(",
"sourceData",
".",
"undirected",
",",
"target",
")",
")",
";",
"}",
"return",
"iterator",
";",
"}"
] |
Function returning an iterator over edges for the given path.
@param {string} type - Type of edges to retrieve.
@param {string} direction - In or out?
@param {NodeData} sourceData - Source node's data.
@param {string} target - Target node.
@param {function} callback - Function to call.
|
[
"Function",
"returning",
"an",
"iterator",
"over",
"edges",
"for",
"the",
"given",
"path",
"."
] |
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
|
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/iteration/edges.js#L544-L573
|
16,308
|
graphology/graphology
|
src/iteration/edges.js
|
attachEdgeArrayCreator
|
function attachEdgeArrayCreator(Class, description) {
const {
name,
type,
direction
} = description;
/**
* Function returning an array of certain edges.
*
* Arity 0: Return all the relevant edges.
*
* Arity 1: Return all of a node's relevant edges.
* @param {any} node - Target node.
*
* Arity 2: Return the relevant edges across the given path.
* @param {any} source - Source node.
* @param {any} target - Target node.
*
* @return {array|number} - The edges or the number of edges.
*
* @throws {Error} - Will throw if there are too many arguments.
*/
Class.prototype[name] = function(source, target) {
// Early termination
if (type !== 'mixed' && this.type !== 'mixed' && type !== this.type)
return [];
if (!arguments.length)
return createEdgeArray(this, type);
if (arguments.length === 1) {
source = '' + source;
const nodeData = this._nodes.get(source);
if (typeof nodeData === 'undefined')
throw new NotFoundGraphError(`Graph.${name}: could not find the "${source}" node in the graph.`);
// Iterating over a node's edges
return createEdgeArrayForNode(
type === 'mixed' ? this.type : type,
direction,
nodeData
);
}
if (arguments.length === 2) {
source = '' + source;
target = '' + target;
const sourceData = this._nodes.get(source);
if (!sourceData)
throw new NotFoundGraphError(`Graph.${name}: could not find the "${source}" source node in the graph.`);
if (!this._nodes.has(target))
throw new NotFoundGraphError(`Graph.${name}: could not find the "${target}" target node in the graph.`);
// Iterating over the edges between source & target
return createEdgeArrayForPath(type, direction, sourceData, target);
}
throw new InvalidArgumentsGraphError(`Graph.${name}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`);
};
}
|
javascript
|
function attachEdgeArrayCreator(Class, description) {
const {
name,
type,
direction
} = description;
/**
* Function returning an array of certain edges.
*
* Arity 0: Return all the relevant edges.
*
* Arity 1: Return all of a node's relevant edges.
* @param {any} node - Target node.
*
* Arity 2: Return the relevant edges across the given path.
* @param {any} source - Source node.
* @param {any} target - Target node.
*
* @return {array|number} - The edges or the number of edges.
*
* @throws {Error} - Will throw if there are too many arguments.
*/
Class.prototype[name] = function(source, target) {
// Early termination
if (type !== 'mixed' && this.type !== 'mixed' && type !== this.type)
return [];
if (!arguments.length)
return createEdgeArray(this, type);
if (arguments.length === 1) {
source = '' + source;
const nodeData = this._nodes.get(source);
if (typeof nodeData === 'undefined')
throw new NotFoundGraphError(`Graph.${name}: could not find the "${source}" node in the graph.`);
// Iterating over a node's edges
return createEdgeArrayForNode(
type === 'mixed' ? this.type : type,
direction,
nodeData
);
}
if (arguments.length === 2) {
source = '' + source;
target = '' + target;
const sourceData = this._nodes.get(source);
if (!sourceData)
throw new NotFoundGraphError(`Graph.${name}: could not find the "${source}" source node in the graph.`);
if (!this._nodes.has(target))
throw new NotFoundGraphError(`Graph.${name}: could not find the "${target}" target node in the graph.`);
// Iterating over the edges between source & target
return createEdgeArrayForPath(type, direction, sourceData, target);
}
throw new InvalidArgumentsGraphError(`Graph.${name}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`);
};
}
|
[
"function",
"attachEdgeArrayCreator",
"(",
"Class",
",",
"description",
")",
"{",
"const",
"{",
"name",
",",
"type",
",",
"direction",
"}",
"=",
"description",
";",
"/**\n * Function returning an array of certain edges.\n *\n * Arity 0: Return all the relevant edges.\n *\n * Arity 1: Return all of a node's relevant edges.\n * @param {any} node - Target node.\n *\n * Arity 2: Return the relevant edges across the given path.\n * @param {any} source - Source node.\n * @param {any} target - Target node.\n *\n * @return {array|number} - The edges or the number of edges.\n *\n * @throws {Error} - Will throw if there are too many arguments.\n */",
"Class",
".",
"prototype",
"[",
"name",
"]",
"=",
"function",
"(",
"source",
",",
"target",
")",
"{",
"// Early termination",
"if",
"(",
"type",
"!==",
"'mixed'",
"&&",
"this",
".",
"type",
"!==",
"'mixed'",
"&&",
"type",
"!==",
"this",
".",
"type",
")",
"return",
"[",
"]",
";",
"if",
"(",
"!",
"arguments",
".",
"length",
")",
"return",
"createEdgeArray",
"(",
"this",
",",
"type",
")",
";",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
")",
"{",
"source",
"=",
"''",
"+",
"source",
";",
"const",
"nodeData",
"=",
"this",
".",
"_nodes",
".",
"get",
"(",
"source",
")",
";",
"if",
"(",
"typeof",
"nodeData",
"===",
"'undefined'",
")",
"throw",
"new",
"NotFoundGraphError",
"(",
"`",
"${",
"name",
"}",
"${",
"source",
"}",
"`",
")",
";",
"// Iterating over a node's edges",
"return",
"createEdgeArrayForNode",
"(",
"type",
"===",
"'mixed'",
"?",
"this",
".",
"type",
":",
"type",
",",
"direction",
",",
"nodeData",
")",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
"===",
"2",
")",
"{",
"source",
"=",
"''",
"+",
"source",
";",
"target",
"=",
"''",
"+",
"target",
";",
"const",
"sourceData",
"=",
"this",
".",
"_nodes",
".",
"get",
"(",
"source",
")",
";",
"if",
"(",
"!",
"sourceData",
")",
"throw",
"new",
"NotFoundGraphError",
"(",
"`",
"${",
"name",
"}",
"${",
"source",
"}",
"`",
")",
";",
"if",
"(",
"!",
"this",
".",
"_nodes",
".",
"has",
"(",
"target",
")",
")",
"throw",
"new",
"NotFoundGraphError",
"(",
"`",
"${",
"name",
"}",
"${",
"target",
"}",
"`",
")",
";",
"// Iterating over the edges between source & target",
"return",
"createEdgeArrayForPath",
"(",
"type",
",",
"direction",
",",
"sourceData",
",",
"target",
")",
";",
"}",
"throw",
"new",
"InvalidArgumentsGraphError",
"(",
"`",
"${",
"name",
"}",
"${",
"arguments",
".",
"length",
"}",
"`",
")",
";",
"}",
";",
"}"
] |
Function attaching an edge array creator method to the Graph prototype.
@param {function} Class - Target class.
@param {object} description - Method description.
|
[
"Function",
"attaching",
"an",
"edge",
"array",
"creator",
"method",
"to",
"the",
"Graph",
"prototype",
"."
] |
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
|
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/iteration/edges.js#L581-L647
|
16,309
|
graphology/graphology
|
src/iteration/edges.js
|
attachForEachEdge
|
function attachForEachEdge(Class, description) {
const {
name,
type,
direction
} = description;
const forEachName = 'forEach' + name[0].toUpperCase() + name.slice(1, -1);
/**
* Function iterating over the graph's relevant edges by applying the given
* callback.
*
* Arity 1: Iterate over all the relevant edges.
* @param {function} callback - Callback to use.
*
* Arity 2: Iterate over all of a node's relevant edges.
* @param {any} node - Target node.
* @param {function} callback - Callback to use.
*
* Arity 3: Iterate over the relevant edges across the given path.
* @param {any} source - Source node.
* @param {any} target - Target node.
* @param {function} callback - Callback to use.
*
* @return {undefined}
*
* @throws {Error} - Will throw if there are too many arguments.
*/
Class.prototype[forEachName] = function(source, target, callback) {
// Early termination
if (type !== 'mixed' && this.type !== 'mixed' && type !== this.type)
return;
if (arguments.length === 1) {
callback = source;
return forEachEdge(this, type, callback);
}
if (arguments.length === 2) {
source = '' + source;
callback = target;
const nodeData = this._nodes.get(source);
if (typeof nodeData === 'undefined')
throw new NotFoundGraphError(`Graph.${forEachName}: could not find the "${source}" node in the graph.`);
// Iterating over a node's edges
return forEachEdgeForNode(
type === 'mixed' ? this.type : type,
direction,
nodeData,
callback
);
}
if (arguments.length === 3) {
source = '' + source;
target = '' + target;
const sourceData = this._nodes.get(source);
if (!sourceData)
throw new NotFoundGraphError(`Graph.${forEachName}: could not find the "${source}" source node in the graph.`);
if (!this._nodes.has(target))
throw new NotFoundGraphError(`Graph.${forEachName}: could not find the "${target}" target node in the graph.`);
// Iterating over the edges between source & target
return forEachEdgeForPath(type, direction, sourceData, target, callback);
}
throw new InvalidArgumentsGraphError(`Graph.${forEachName}: too many arguments (expecting 1, 2 or 3 and got ${arguments.length}).`);
};
}
|
javascript
|
function attachForEachEdge(Class, description) {
const {
name,
type,
direction
} = description;
const forEachName = 'forEach' + name[0].toUpperCase() + name.slice(1, -1);
/**
* Function iterating over the graph's relevant edges by applying the given
* callback.
*
* Arity 1: Iterate over all the relevant edges.
* @param {function} callback - Callback to use.
*
* Arity 2: Iterate over all of a node's relevant edges.
* @param {any} node - Target node.
* @param {function} callback - Callback to use.
*
* Arity 3: Iterate over the relevant edges across the given path.
* @param {any} source - Source node.
* @param {any} target - Target node.
* @param {function} callback - Callback to use.
*
* @return {undefined}
*
* @throws {Error} - Will throw if there are too many arguments.
*/
Class.prototype[forEachName] = function(source, target, callback) {
// Early termination
if (type !== 'mixed' && this.type !== 'mixed' && type !== this.type)
return;
if (arguments.length === 1) {
callback = source;
return forEachEdge(this, type, callback);
}
if (arguments.length === 2) {
source = '' + source;
callback = target;
const nodeData = this._nodes.get(source);
if (typeof nodeData === 'undefined')
throw new NotFoundGraphError(`Graph.${forEachName}: could not find the "${source}" node in the graph.`);
// Iterating over a node's edges
return forEachEdgeForNode(
type === 'mixed' ? this.type : type,
direction,
nodeData,
callback
);
}
if (arguments.length === 3) {
source = '' + source;
target = '' + target;
const sourceData = this._nodes.get(source);
if (!sourceData)
throw new NotFoundGraphError(`Graph.${forEachName}: could not find the "${source}" source node in the graph.`);
if (!this._nodes.has(target))
throw new NotFoundGraphError(`Graph.${forEachName}: could not find the "${target}" target node in the graph.`);
// Iterating over the edges between source & target
return forEachEdgeForPath(type, direction, sourceData, target, callback);
}
throw new InvalidArgumentsGraphError(`Graph.${forEachName}: too many arguments (expecting 1, 2 or 3 and got ${arguments.length}).`);
};
}
|
[
"function",
"attachForEachEdge",
"(",
"Class",
",",
"description",
")",
"{",
"const",
"{",
"name",
",",
"type",
",",
"direction",
"}",
"=",
"description",
";",
"const",
"forEachName",
"=",
"'forEach'",
"+",
"name",
"[",
"0",
"]",
".",
"toUpperCase",
"(",
")",
"+",
"name",
".",
"slice",
"(",
"1",
",",
"-",
"1",
")",
";",
"/**\n * Function iterating over the graph's relevant edges by applying the given\n * callback.\n *\n * Arity 1: Iterate over all the relevant edges.\n * @param {function} callback - Callback to use.\n *\n * Arity 2: Iterate over all of a node's relevant edges.\n * @param {any} node - Target node.\n * @param {function} callback - Callback to use.\n *\n * Arity 3: Iterate over the relevant edges across the given path.\n * @param {any} source - Source node.\n * @param {any} target - Target node.\n * @param {function} callback - Callback to use.\n *\n * @return {undefined}\n *\n * @throws {Error} - Will throw if there are too many arguments.\n */",
"Class",
".",
"prototype",
"[",
"forEachName",
"]",
"=",
"function",
"(",
"source",
",",
"target",
",",
"callback",
")",
"{",
"// Early termination",
"if",
"(",
"type",
"!==",
"'mixed'",
"&&",
"this",
".",
"type",
"!==",
"'mixed'",
"&&",
"type",
"!==",
"this",
".",
"type",
")",
"return",
";",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
")",
"{",
"callback",
"=",
"source",
";",
"return",
"forEachEdge",
"(",
"this",
",",
"type",
",",
"callback",
")",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
"===",
"2",
")",
"{",
"source",
"=",
"''",
"+",
"source",
";",
"callback",
"=",
"target",
";",
"const",
"nodeData",
"=",
"this",
".",
"_nodes",
".",
"get",
"(",
"source",
")",
";",
"if",
"(",
"typeof",
"nodeData",
"===",
"'undefined'",
")",
"throw",
"new",
"NotFoundGraphError",
"(",
"`",
"${",
"forEachName",
"}",
"${",
"source",
"}",
"`",
")",
";",
"// Iterating over a node's edges",
"return",
"forEachEdgeForNode",
"(",
"type",
"===",
"'mixed'",
"?",
"this",
".",
"type",
":",
"type",
",",
"direction",
",",
"nodeData",
",",
"callback",
")",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
"===",
"3",
")",
"{",
"source",
"=",
"''",
"+",
"source",
";",
"target",
"=",
"''",
"+",
"target",
";",
"const",
"sourceData",
"=",
"this",
".",
"_nodes",
".",
"get",
"(",
"source",
")",
";",
"if",
"(",
"!",
"sourceData",
")",
"throw",
"new",
"NotFoundGraphError",
"(",
"`",
"${",
"forEachName",
"}",
"${",
"source",
"}",
"`",
")",
";",
"if",
"(",
"!",
"this",
".",
"_nodes",
".",
"has",
"(",
"target",
")",
")",
"throw",
"new",
"NotFoundGraphError",
"(",
"`",
"${",
"forEachName",
"}",
"${",
"target",
"}",
"`",
")",
";",
"// Iterating over the edges between source & target",
"return",
"forEachEdgeForPath",
"(",
"type",
",",
"direction",
",",
"sourceData",
",",
"target",
",",
"callback",
")",
";",
"}",
"throw",
"new",
"InvalidArgumentsGraphError",
"(",
"`",
"${",
"forEachName",
"}",
"${",
"arguments",
".",
"length",
"}",
"`",
")",
";",
"}",
";",
"}"
] |
Function attaching a edge callback iterator method to the Graph prototype.
@param {function} Class - Target class.
@param {object} description - Method description.
|
[
"Function",
"attaching",
"a",
"edge",
"callback",
"iterator",
"method",
"to",
"the",
"Graph",
"prototype",
"."
] |
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
|
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/iteration/edges.js#L655-L731
|
16,310
|
graphology/graphology
|
src/graph.js
|
addEdge
|
function addEdge(
graph,
name,
mustGenerateKey,
undirected,
edge,
source,
target,
attributes
) {
// Checking validity of operation
if (!undirected && graph.type === 'undirected')
throw new UsageGraphError(`Graph.${name}: you cannot add a directed edge to an undirected graph. Use the #.addEdge or #.addUndirectedEdge instead.`);
if (undirected && graph.type === 'directed')
throw new UsageGraphError(`Graph.${name}: you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead.`);
if (attributes && !isPlainObject(attributes))
throw new InvalidArgumentsGraphError(`Graph.${name}: invalid attributes. Expecting an object but got "${attributes}"`);
// Coercion of source & target:
source = '' + source;
target = '' + target;
attributes = attributes || {};
if (!graph.allowSelfLoops && source === target)
throw new UsageGraphError(`Graph.${name}: source & target are the same ("${source}"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.`);
const sourceData = graph._nodes.get(source),
targetData = graph._nodes.get(target);
if (!sourceData)
throw new NotFoundGraphError(`Graph.${name}: source node "${source}" not found.`);
if (!targetData)
throw new NotFoundGraphError(`Graph.${name}: target node "${target}" not found.`);
// Must the graph generate an id for this edge?
const eventData = {
key: null,
undirected,
source,
target,
attributes
};
if (mustGenerateKey)
edge = graph._edgeKeyGenerator(eventData);
// Coercion of edge key
edge = '' + edge;
// Here, we have a key collision
if (graph._edges.has(edge))
throw new UsageGraphError(`Graph.${name}: the "${edge}" edge already exists in the graph.`);
// Here, we might have a source / target collision
if (
!graph.multi &&
(
undirected ?
typeof sourceData.undirected[target] !== 'undefined' :
typeof sourceData.out[target] !== 'undefined'
)
) {
throw new UsageGraphError(`Graph.${name}: an edge linking "${source}" to "${target}" already exists. If you really want to add multiple edges linking those nodes, you should create a multi graph by using the 'multi' option.`);
}
// Storing some data
const DataClass = undirected ? UndirectedEdgeData : DirectedEdgeData;
const edgeData = new DataClass(
edge,
mustGenerateKey,
sourceData,
targetData,
attributes
);
// Adding the edge to the internal register
graph._edges.set(edge, edgeData);
// Incrementing node degree counters
if (source === target) {
if (undirected)
sourceData.undirectedSelfLoops++;
else
sourceData.directedSelfLoops++;
}
else {
if (undirected) {
sourceData.undirectedDegree++;
targetData.undirectedDegree++;
}
else {
sourceData.outDegree++;
targetData.inDegree++;
}
}
// Updating relevant index
updateStructureIndex(
graph,
undirected,
edgeData,
source,
target,
sourceData,
targetData
);
if (undirected)
graph._undirectedSize++;
else
graph._directedSize++;
// Emitting
eventData.key = edge;
graph.emit('edgeAdded', eventData);
return edge;
}
|
javascript
|
function addEdge(
graph,
name,
mustGenerateKey,
undirected,
edge,
source,
target,
attributes
) {
// Checking validity of operation
if (!undirected && graph.type === 'undirected')
throw new UsageGraphError(`Graph.${name}: you cannot add a directed edge to an undirected graph. Use the #.addEdge or #.addUndirectedEdge instead.`);
if (undirected && graph.type === 'directed')
throw new UsageGraphError(`Graph.${name}: you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead.`);
if (attributes && !isPlainObject(attributes))
throw new InvalidArgumentsGraphError(`Graph.${name}: invalid attributes. Expecting an object but got "${attributes}"`);
// Coercion of source & target:
source = '' + source;
target = '' + target;
attributes = attributes || {};
if (!graph.allowSelfLoops && source === target)
throw new UsageGraphError(`Graph.${name}: source & target are the same ("${source}"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.`);
const sourceData = graph._nodes.get(source),
targetData = graph._nodes.get(target);
if (!sourceData)
throw new NotFoundGraphError(`Graph.${name}: source node "${source}" not found.`);
if (!targetData)
throw new NotFoundGraphError(`Graph.${name}: target node "${target}" not found.`);
// Must the graph generate an id for this edge?
const eventData = {
key: null,
undirected,
source,
target,
attributes
};
if (mustGenerateKey)
edge = graph._edgeKeyGenerator(eventData);
// Coercion of edge key
edge = '' + edge;
// Here, we have a key collision
if (graph._edges.has(edge))
throw new UsageGraphError(`Graph.${name}: the "${edge}" edge already exists in the graph.`);
// Here, we might have a source / target collision
if (
!graph.multi &&
(
undirected ?
typeof sourceData.undirected[target] !== 'undefined' :
typeof sourceData.out[target] !== 'undefined'
)
) {
throw new UsageGraphError(`Graph.${name}: an edge linking "${source}" to "${target}" already exists. If you really want to add multiple edges linking those nodes, you should create a multi graph by using the 'multi' option.`);
}
// Storing some data
const DataClass = undirected ? UndirectedEdgeData : DirectedEdgeData;
const edgeData = new DataClass(
edge,
mustGenerateKey,
sourceData,
targetData,
attributes
);
// Adding the edge to the internal register
graph._edges.set(edge, edgeData);
// Incrementing node degree counters
if (source === target) {
if (undirected)
sourceData.undirectedSelfLoops++;
else
sourceData.directedSelfLoops++;
}
else {
if (undirected) {
sourceData.undirectedDegree++;
targetData.undirectedDegree++;
}
else {
sourceData.outDegree++;
targetData.inDegree++;
}
}
// Updating relevant index
updateStructureIndex(
graph,
undirected,
edgeData,
source,
target,
sourceData,
targetData
);
if (undirected)
graph._undirectedSize++;
else
graph._directedSize++;
// Emitting
eventData.key = edge;
graph.emit('edgeAdded', eventData);
return edge;
}
|
[
"function",
"addEdge",
"(",
"graph",
",",
"name",
",",
"mustGenerateKey",
",",
"undirected",
",",
"edge",
",",
"source",
",",
"target",
",",
"attributes",
")",
"{",
"// Checking validity of operation",
"if",
"(",
"!",
"undirected",
"&&",
"graph",
".",
"type",
"===",
"'undirected'",
")",
"throw",
"new",
"UsageGraphError",
"(",
"`",
"${",
"name",
"}",
"`",
")",
";",
"if",
"(",
"undirected",
"&&",
"graph",
".",
"type",
"===",
"'directed'",
")",
"throw",
"new",
"UsageGraphError",
"(",
"`",
"${",
"name",
"}",
"`",
")",
";",
"if",
"(",
"attributes",
"&&",
"!",
"isPlainObject",
"(",
"attributes",
")",
")",
"throw",
"new",
"InvalidArgumentsGraphError",
"(",
"`",
"${",
"name",
"}",
"${",
"attributes",
"}",
"`",
")",
";",
"// Coercion of source & target:",
"source",
"=",
"''",
"+",
"source",
";",
"target",
"=",
"''",
"+",
"target",
";",
"attributes",
"=",
"attributes",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"graph",
".",
"allowSelfLoops",
"&&",
"source",
"===",
"target",
")",
"throw",
"new",
"UsageGraphError",
"(",
"`",
"${",
"name",
"}",
"${",
"source",
"}",
"`",
")",
";",
"const",
"sourceData",
"=",
"graph",
".",
"_nodes",
".",
"get",
"(",
"source",
")",
",",
"targetData",
"=",
"graph",
".",
"_nodes",
".",
"get",
"(",
"target",
")",
";",
"if",
"(",
"!",
"sourceData",
")",
"throw",
"new",
"NotFoundGraphError",
"(",
"`",
"${",
"name",
"}",
"${",
"source",
"}",
"`",
")",
";",
"if",
"(",
"!",
"targetData",
")",
"throw",
"new",
"NotFoundGraphError",
"(",
"`",
"${",
"name",
"}",
"${",
"target",
"}",
"`",
")",
";",
"// Must the graph generate an id for this edge?",
"const",
"eventData",
"=",
"{",
"key",
":",
"null",
",",
"undirected",
",",
"source",
",",
"target",
",",
"attributes",
"}",
";",
"if",
"(",
"mustGenerateKey",
")",
"edge",
"=",
"graph",
".",
"_edgeKeyGenerator",
"(",
"eventData",
")",
";",
"// Coercion of edge key",
"edge",
"=",
"''",
"+",
"edge",
";",
"// Here, we have a key collision",
"if",
"(",
"graph",
".",
"_edges",
".",
"has",
"(",
"edge",
")",
")",
"throw",
"new",
"UsageGraphError",
"(",
"`",
"${",
"name",
"}",
"${",
"edge",
"}",
"`",
")",
";",
"// Here, we might have a source / target collision",
"if",
"(",
"!",
"graph",
".",
"multi",
"&&",
"(",
"undirected",
"?",
"typeof",
"sourceData",
".",
"undirected",
"[",
"target",
"]",
"!==",
"'undefined'",
":",
"typeof",
"sourceData",
".",
"out",
"[",
"target",
"]",
"!==",
"'undefined'",
")",
")",
"{",
"throw",
"new",
"UsageGraphError",
"(",
"`",
"${",
"name",
"}",
"${",
"source",
"}",
"${",
"target",
"}",
"`",
")",
";",
"}",
"// Storing some data",
"const",
"DataClass",
"=",
"undirected",
"?",
"UndirectedEdgeData",
":",
"DirectedEdgeData",
";",
"const",
"edgeData",
"=",
"new",
"DataClass",
"(",
"edge",
",",
"mustGenerateKey",
",",
"sourceData",
",",
"targetData",
",",
"attributes",
")",
";",
"// Adding the edge to the internal register",
"graph",
".",
"_edges",
".",
"set",
"(",
"edge",
",",
"edgeData",
")",
";",
"// Incrementing node degree counters",
"if",
"(",
"source",
"===",
"target",
")",
"{",
"if",
"(",
"undirected",
")",
"sourceData",
".",
"undirectedSelfLoops",
"++",
";",
"else",
"sourceData",
".",
"directedSelfLoops",
"++",
";",
"}",
"else",
"{",
"if",
"(",
"undirected",
")",
"{",
"sourceData",
".",
"undirectedDegree",
"++",
";",
"targetData",
".",
"undirectedDegree",
"++",
";",
"}",
"else",
"{",
"sourceData",
".",
"outDegree",
"++",
";",
"targetData",
".",
"inDegree",
"++",
";",
"}",
"}",
"// Updating relevant index",
"updateStructureIndex",
"(",
"graph",
",",
"undirected",
",",
"edgeData",
",",
"source",
",",
"target",
",",
"sourceData",
",",
"targetData",
")",
";",
"if",
"(",
"undirected",
")",
"graph",
".",
"_undirectedSize",
"++",
";",
"else",
"graph",
".",
"_directedSize",
"++",
";",
"// Emitting",
"eventData",
".",
"key",
"=",
"edge",
";",
"graph",
".",
"emit",
"(",
"'edgeAdded'",
",",
"eventData",
")",
";",
"return",
"edge",
";",
"}"
] |
Abstract functions used by the Graph class for various methods.
Internal method used to add an arbitrary edge to the given graph.
@param {Graph} graph - Target graph.
@param {string} name - Name of the child method for errors.
@param {boolean} mustGenerateKey - Should the graph generate an id?
@param {boolean} undirected - Whether the edge is undirected.
@param {any} edge - The edge's key.
@param {any} source - The source node.
@param {any} target - The target node.
@param {object} [attributes] - Optional attributes.
@return {any} - The edge.
@throws {Error} - Will throw if the graph is of the wrong type.
@throws {Error} - Will throw if the given attributes are not an object.
@throws {Error} - Will throw if source or target doesn't exist.
@throws {Error} - Will throw if the edge already exist.
|
[
"Abstract",
"functions",
"used",
"by",
"the",
"Graph",
"class",
"for",
"various",
"methods",
".",
"Internal",
"method",
"used",
"to",
"add",
"an",
"arbitrary",
"edge",
"to",
"the",
"given",
"graph",
"."
] |
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
|
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/graph.js#L131-L254
|
16,311
|
graphology/graphology
|
src/attributes.js
|
attachAttributeGetter
|
function attachAttributeGetter(Class, method, type, EdgeDataClass) {
/**
* Get the desired attribute for the given element (node or edge).
*
* Arity 2:
* @param {any} element - Target element.
* @param {string} name - Attribute's name.
*
* Arity 3 (only for edges):
* @param {any} source - Source element.
* @param {any} target - Target element.
* @param {string} name - Attribute's name.
*
* @return {mixed} - The attribute's value.
*
* @throws {Error} - Will throw if too many arguments are provided.
* @throws {Error} - Will throw if any of the elements is not found.
*/
Class.prototype[method] = function(element, name) {
let data;
if (this.type !== 'mixed' && type !== 'mixed' && type !== this.type)
throw new UsageGraphError(`Graph.${method}: cannot find this type of edges in your ${this.type} graph.`);
if (arguments.length > 2) {
if (this.multi)
throw new UsageGraphError(`Graph.${method}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);
const source = '' + element,
target = '' + name;
name = arguments[2];
data = getMatchingEdge(this, source, target, type);
if (!data)
throw new NotFoundGraphError(`Graph.${method}: could not find an edge for the given path ("${source}" - "${target}").`);
}
else {
element = '' + element;
data = this._edges.get(element);
if (!data)
throw new NotFoundGraphError(`Graph.${method}: could not find the "${element}" edge in the graph.`);
}
if (type !== 'mixed' && !(data instanceof EdgeDataClass))
throw new NotFoundGraphError(`Graph.${method}: could not find the "${element}" ${type} edge in the graph.`);
return data.attributes[name];
};
}
|
javascript
|
function attachAttributeGetter(Class, method, type, EdgeDataClass) {
/**
* Get the desired attribute for the given element (node or edge).
*
* Arity 2:
* @param {any} element - Target element.
* @param {string} name - Attribute's name.
*
* Arity 3 (only for edges):
* @param {any} source - Source element.
* @param {any} target - Target element.
* @param {string} name - Attribute's name.
*
* @return {mixed} - The attribute's value.
*
* @throws {Error} - Will throw if too many arguments are provided.
* @throws {Error} - Will throw if any of the elements is not found.
*/
Class.prototype[method] = function(element, name) {
let data;
if (this.type !== 'mixed' && type !== 'mixed' && type !== this.type)
throw new UsageGraphError(`Graph.${method}: cannot find this type of edges in your ${this.type} graph.`);
if (arguments.length > 2) {
if (this.multi)
throw new UsageGraphError(`Graph.${method}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);
const source = '' + element,
target = '' + name;
name = arguments[2];
data = getMatchingEdge(this, source, target, type);
if (!data)
throw new NotFoundGraphError(`Graph.${method}: could not find an edge for the given path ("${source}" - "${target}").`);
}
else {
element = '' + element;
data = this._edges.get(element);
if (!data)
throw new NotFoundGraphError(`Graph.${method}: could not find the "${element}" edge in the graph.`);
}
if (type !== 'mixed' && !(data instanceof EdgeDataClass))
throw new NotFoundGraphError(`Graph.${method}: could not find the "${element}" ${type} edge in the graph.`);
return data.attributes[name];
};
}
|
[
"function",
"attachAttributeGetter",
"(",
"Class",
",",
"method",
",",
"type",
",",
"EdgeDataClass",
")",
"{",
"/**\n * Get the desired attribute for the given element (node or edge).\n *\n * Arity 2:\n * @param {any} element - Target element.\n * @param {string} name - Attribute's name.\n *\n * Arity 3 (only for edges):\n * @param {any} source - Source element.\n * @param {any} target - Target element.\n * @param {string} name - Attribute's name.\n *\n * @return {mixed} - The attribute's value.\n *\n * @throws {Error} - Will throw if too many arguments are provided.\n * @throws {Error} - Will throw if any of the elements is not found.\n */",
"Class",
".",
"prototype",
"[",
"method",
"]",
"=",
"function",
"(",
"element",
",",
"name",
")",
"{",
"let",
"data",
";",
"if",
"(",
"this",
".",
"type",
"!==",
"'mixed'",
"&&",
"type",
"!==",
"'mixed'",
"&&",
"type",
"!==",
"this",
".",
"type",
")",
"throw",
"new",
"UsageGraphError",
"(",
"`",
"${",
"method",
"}",
"${",
"this",
".",
"type",
"}",
"`",
")",
";",
"if",
"(",
"arguments",
".",
"length",
">",
"2",
")",
"{",
"if",
"(",
"this",
".",
"multi",
")",
"throw",
"new",
"UsageGraphError",
"(",
"`",
"${",
"method",
"}",
"`",
")",
";",
"const",
"source",
"=",
"''",
"+",
"element",
",",
"target",
"=",
"''",
"+",
"name",
";",
"name",
"=",
"arguments",
"[",
"2",
"]",
";",
"data",
"=",
"getMatchingEdge",
"(",
"this",
",",
"source",
",",
"target",
",",
"type",
")",
";",
"if",
"(",
"!",
"data",
")",
"throw",
"new",
"NotFoundGraphError",
"(",
"`",
"${",
"method",
"}",
"${",
"source",
"}",
"${",
"target",
"}",
"`",
")",
";",
"}",
"else",
"{",
"element",
"=",
"''",
"+",
"element",
";",
"data",
"=",
"this",
".",
"_edges",
".",
"get",
"(",
"element",
")",
";",
"if",
"(",
"!",
"data",
")",
"throw",
"new",
"NotFoundGraphError",
"(",
"`",
"${",
"method",
"}",
"${",
"element",
"}",
"`",
")",
";",
"}",
"if",
"(",
"type",
"!==",
"'mixed'",
"&&",
"!",
"(",
"data",
"instanceof",
"EdgeDataClass",
")",
")",
"throw",
"new",
"NotFoundGraphError",
"(",
"`",
"${",
"method",
"}",
"${",
"element",
"}",
"${",
"type",
"}",
"`",
")",
";",
"return",
"data",
".",
"attributes",
"[",
"name",
"]",
";",
"}",
";",
"}"
] |
Attach an attribute getter method onto the provided class.
@param {function} Class - Target class.
@param {string} method - Method name.
@param {string} type - Type of the edge to find.
@param {Class} EdgeDataClass - Class of the edges to filter.
|
[
"Attach",
"an",
"attribute",
"getter",
"method",
"onto",
"the",
"provided",
"class",
"."
] |
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
|
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/attributes.js#L33-L86
|
16,312
|
emadalam/atvjs
|
src/navigation.js
|
getLoaderDoc
|
function getLoaderDoc(message) {
let tpl = defaults.templates.loader;
let str = (tpl && tpl({message: message})) || '<document></document>';
return Parser.dom(str);
}
|
javascript
|
function getLoaderDoc(message) {
let tpl = defaults.templates.loader;
let str = (tpl && tpl({message: message})) || '<document></document>';
return Parser.dom(str);
}
|
[
"function",
"getLoaderDoc",
"(",
"message",
")",
"{",
"let",
"tpl",
"=",
"defaults",
".",
"templates",
".",
"loader",
";",
"let",
"str",
"=",
"(",
"tpl",
"&&",
"tpl",
"(",
"{",
"message",
":",
"message",
"}",
")",
")",
"||",
"'<document></document>'",
";",
"return",
"Parser",
".",
"dom",
"(",
"str",
")",
";",
"}"
] |
Get a loader document.
@inner
@alias module:navigation.getLoaderDoc
@param {String} message Loading message
@return {Document} A newly created loader document
|
[
"Get",
"a",
"loader",
"document",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/navigation.js#L41-L46
|
16,313
|
emadalam/atvjs
|
src/navigation.js
|
getErrorDoc
|
function getErrorDoc(message) {
let cfg = {};
if (_.isPlainObject(message)) {
cfg = message;
if (cfg.status && !cfg.template && defaults.templates.status[cfg.status]) {
cfg.template = defaults.templates.status[cfg.status];
}
} else {
cfg.template = defaults.templates.error || (() => '<document></document>');
cfg.data = {message: message};
}
return Page.makeDom(cfg);
}
|
javascript
|
function getErrorDoc(message) {
let cfg = {};
if (_.isPlainObject(message)) {
cfg = message;
if (cfg.status && !cfg.template && defaults.templates.status[cfg.status]) {
cfg.template = defaults.templates.status[cfg.status];
}
} else {
cfg.template = defaults.templates.error || (() => '<document></document>');
cfg.data = {message: message};
}
return Page.makeDom(cfg);
}
|
[
"function",
"getErrorDoc",
"(",
"message",
")",
"{",
"let",
"cfg",
"=",
"{",
"}",
";",
"if",
"(",
"_",
".",
"isPlainObject",
"(",
"message",
")",
")",
"{",
"cfg",
"=",
"message",
";",
"if",
"(",
"cfg",
".",
"status",
"&&",
"!",
"cfg",
".",
"template",
"&&",
"defaults",
".",
"templates",
".",
"status",
"[",
"cfg",
".",
"status",
"]",
")",
"{",
"cfg",
".",
"template",
"=",
"defaults",
".",
"templates",
".",
"status",
"[",
"cfg",
".",
"status",
"]",
";",
"}",
"}",
"else",
"{",
"cfg",
".",
"template",
"=",
"defaults",
".",
"templates",
".",
"error",
"||",
"(",
"(",
")",
"=>",
"'<document></document>'",
")",
";",
"cfg",
".",
"data",
"=",
"{",
"message",
":",
"message",
"}",
";",
"}",
"return",
"Page",
".",
"makeDom",
"(",
"cfg",
")",
";",
"}"
] |
Get an error document.
@inner
@alias module:navigation.getErrorDoc
@param {Object|String} message Error page configuration or error message
@return {Document} A newly created error document
|
[
"Get",
"an",
"error",
"document",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/navigation.js#L57-L70
|
16,314
|
emadalam/atvjs
|
src/navigation.js
|
initMenu
|
function initMenu() {
let menuCfg = defaults.menu;
// no configuration given and neither the menu created earlier
// no need to proceed
if (!menuCfg && !Menu.created) {
return;
}
// set options to create menu
if (menuCfg) {
Menu.setOptions(menuCfg);
}
menuDoc = Menu.get();
Page.prepareDom(menuDoc);
}
|
javascript
|
function initMenu() {
let menuCfg = defaults.menu;
// no configuration given and neither the menu created earlier
// no need to proceed
if (!menuCfg && !Menu.created) {
return;
}
// set options to create menu
if (menuCfg) {
Menu.setOptions(menuCfg);
}
menuDoc = Menu.get();
Page.prepareDom(menuDoc);
}
|
[
"function",
"initMenu",
"(",
")",
"{",
"let",
"menuCfg",
"=",
"defaults",
".",
"menu",
";",
"// no configuration given and neither the menu created earlier",
"// no need to proceed",
"if",
"(",
"!",
"menuCfg",
"&&",
"!",
"Menu",
".",
"created",
")",
"{",
"return",
";",
"}",
"// set options to create menu",
"if",
"(",
"menuCfg",
")",
"{",
"Menu",
".",
"setOptions",
"(",
"menuCfg",
")",
";",
"}",
"menuDoc",
"=",
"Menu",
".",
"get",
"(",
")",
";",
"Page",
".",
"prepareDom",
"(",
"menuDoc",
")",
";",
"}"
] |
Initializes the menu document if present
@private
|
[
"Initializes",
"the",
"menu",
"document",
"if",
"present"
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/navigation.js#L89-L105
|
16,315
|
emadalam/atvjs
|
src/navigation.js
|
show
|
function show(cfg = {}) {
if (_.isFunction(cfg)) {
cfg = {
template: cfg
};
}
// no template exists, cannot proceed
if (!cfg.template) {
console.warn('No template found!')
return;
}
let doc = null;
if (getLastDocumentFromStack() && cfg.type === 'modal') { // show as a modal if there is something on the navigation stack
doc = presentModal(cfg);
} else { // no document on the navigation stack, show as a document
doc = Page.makeDom(cfg);
cleanNavigate(doc);
}
return doc;
}
|
javascript
|
function show(cfg = {}) {
if (_.isFunction(cfg)) {
cfg = {
template: cfg
};
}
// no template exists, cannot proceed
if (!cfg.template) {
console.warn('No template found!')
return;
}
let doc = null;
if (getLastDocumentFromStack() && cfg.type === 'modal') { // show as a modal if there is something on the navigation stack
doc = presentModal(cfg);
} else { // no document on the navigation stack, show as a document
doc = Page.makeDom(cfg);
cleanNavigate(doc);
}
return doc;
}
|
[
"function",
"show",
"(",
"cfg",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"_",
".",
"isFunction",
"(",
"cfg",
")",
")",
"{",
"cfg",
"=",
"{",
"template",
":",
"cfg",
"}",
";",
"}",
"// no template exists, cannot proceed",
"if",
"(",
"!",
"cfg",
".",
"template",
")",
"{",
"console",
".",
"warn",
"(",
"'No template found!'",
")",
"return",
";",
"}",
"let",
"doc",
"=",
"null",
";",
"if",
"(",
"getLastDocumentFromStack",
"(",
")",
"&&",
"cfg",
".",
"type",
"===",
"'modal'",
")",
"{",
"// show as a modal if there is something on the navigation stack",
"doc",
"=",
"presentModal",
"(",
"cfg",
")",
";",
"}",
"else",
"{",
"// no document on the navigation stack, show as a document",
"doc",
"=",
"Page",
".",
"makeDom",
"(",
"cfg",
")",
";",
"cleanNavigate",
"(",
"doc",
")",
";",
"}",
"return",
"doc",
";",
"}"
] |
Helper function to perform navigation after applying the page level default handlers
@private
@param {Object} cfg The configurations
@return {Document} The created document
|
[
"Helper",
"function",
"to",
"perform",
"navigation",
"after",
"applying",
"the",
"page",
"level",
"default",
"handlers"
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/navigation.js#L115-L135
|
16,316
|
emadalam/atvjs
|
src/navigation.js
|
showLoading
|
function showLoading(cfg = {}) {
if (_.isString(cfg)) {
cfg = {
data: {
message: cfg
}
};
}
// use default loading template if not passed as a configuration
_.defaultsDeep(cfg, {
template: defaults.templates.loader,
type: 'modal'
});
console.log('showing loader... options:', cfg);
// cache the doc for later use
loaderDoc = show(cfg);
return loaderDoc;
}
|
javascript
|
function showLoading(cfg = {}) {
if (_.isString(cfg)) {
cfg = {
data: {
message: cfg
}
};
}
// use default loading template if not passed as a configuration
_.defaultsDeep(cfg, {
template: defaults.templates.loader,
type: 'modal'
});
console.log('showing loader... options:', cfg);
// cache the doc for later use
loaderDoc = show(cfg);
return loaderDoc;
}
|
[
"function",
"showLoading",
"(",
"cfg",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"_",
".",
"isString",
"(",
"cfg",
")",
")",
"{",
"cfg",
"=",
"{",
"data",
":",
"{",
"message",
":",
"cfg",
"}",
"}",
";",
"}",
"// use default loading template if not passed as a configuration",
"_",
".",
"defaultsDeep",
"(",
"cfg",
",",
"{",
"template",
":",
"defaults",
".",
"templates",
".",
"loader",
",",
"type",
":",
"'modal'",
"}",
")",
";",
"console",
".",
"log",
"(",
"'showing loader... options:'",
",",
"cfg",
")",
";",
"// cache the doc for later use",
"loaderDoc",
"=",
"show",
"(",
"cfg",
")",
";",
"return",
"loaderDoc",
";",
"}"
] |
Shows a loading page if a loader template exists.
Also applies any default handlers and caches the document for later use.
@inner
@alias module:navigation.showLoading
@param {Object|Function} cfg The configuration options or the template function
@return {Document} The created loader document.
|
[
"Shows",
"a",
"loading",
"page",
"if",
"a",
"loader",
"template",
"exists",
".",
"Also",
"applies",
"any",
"default",
"handlers",
"and",
"caches",
"the",
"document",
"for",
"later",
"use",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/navigation.js#L147-L167
|
16,317
|
emadalam/atvjs
|
src/navigation.js
|
showError
|
function showError(cfg = {}) {
if (_.isBoolean(cfg) && !cfg && errorDoc) { // hide error
navigationDocument.removeDocument(errorDoc);
return;
}
if (_.isString(cfg)) {
cfg = {
data: {
message: cfg
}
};
}
// use default error template if not passed as a configuration
_.defaultsDeep(cfg, {
template: defaults.templates.error
});
console.log('showing error... options:', cfg);
// cache the doc for later use
errorDoc = show(cfg);
return errorDoc;
}
|
javascript
|
function showError(cfg = {}) {
if (_.isBoolean(cfg) && !cfg && errorDoc) { // hide error
navigationDocument.removeDocument(errorDoc);
return;
}
if (_.isString(cfg)) {
cfg = {
data: {
message: cfg
}
};
}
// use default error template if not passed as a configuration
_.defaultsDeep(cfg, {
template: defaults.templates.error
});
console.log('showing error... options:', cfg);
// cache the doc for later use
errorDoc = show(cfg);
return errorDoc;
}
|
[
"function",
"showError",
"(",
"cfg",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"_",
".",
"isBoolean",
"(",
"cfg",
")",
"&&",
"!",
"cfg",
"&&",
"errorDoc",
")",
"{",
"// hide error",
"navigationDocument",
".",
"removeDocument",
"(",
"errorDoc",
")",
";",
"return",
";",
"}",
"if",
"(",
"_",
".",
"isString",
"(",
"cfg",
")",
")",
"{",
"cfg",
"=",
"{",
"data",
":",
"{",
"message",
":",
"cfg",
"}",
"}",
";",
"}",
"// use default error template if not passed as a configuration",
"_",
".",
"defaultsDeep",
"(",
"cfg",
",",
"{",
"template",
":",
"defaults",
".",
"templates",
".",
"error",
"}",
")",
";",
"console",
".",
"log",
"(",
"'showing error... options:'",
",",
"cfg",
")",
";",
"// cache the doc for later use",
"errorDoc",
"=",
"show",
"(",
"cfg",
")",
";",
"return",
"errorDoc",
";",
"}"
] |
Shows the error page using the existing error template.
Also applies any default handlers and caches the document for later use.
@inner
@alias module:navigation.showError
@param {Object|Function|Boolean} cfg The configuration options or the template function or boolean to hide the error
@return {Document} The created error document.
|
[
"Shows",
"the",
"error",
"page",
"using",
"the",
"existing",
"error",
"template",
".",
"Also",
"applies",
"any",
"default",
"handlers",
"and",
"caches",
"the",
"document",
"for",
"later",
"use",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/navigation.js#L179-L202
|
16,318
|
emadalam/atvjs
|
src/navigation.js
|
pushDocument
|
function pushDocument(doc) {
if (!(doc instanceof Document)) {
console.warn('Cannot navigate to the document.', doc);
return;
}
navigationDocument.pushDocument(doc);
}
|
javascript
|
function pushDocument(doc) {
if (!(doc instanceof Document)) {
console.warn('Cannot navigate to the document.', doc);
return;
}
navigationDocument.pushDocument(doc);
}
|
[
"function",
"pushDocument",
"(",
"doc",
")",
"{",
"if",
"(",
"!",
"(",
"doc",
"instanceof",
"Document",
")",
")",
"{",
"console",
".",
"warn",
"(",
"'Cannot navigate to the document.'",
",",
"doc",
")",
";",
"return",
";",
"}",
"navigationDocument",
".",
"pushDocument",
"(",
"doc",
")",
";",
"}"
] |
Pushes a given document to the navigation stack after applying all the default page level handlers.
@private
@param {Document} doc The document to push to the navigation stack
|
[
"Pushes",
"a",
"given",
"document",
"to",
"the",
"navigation",
"stack",
"after",
"applying",
"all",
"the",
"default",
"page",
"level",
"handlers",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/navigation.js#L211-L217
|
16,319
|
emadalam/atvjs
|
src/navigation.js
|
replaceDocument
|
function replaceDocument(doc, docToReplace) {
if (!(doc instanceof Document) || !(docToReplace instanceof Document)) {
console.warn('Cannot replace document.');
return;
}
navigationDocument.replaceDocument(doc, docToReplace);
}
|
javascript
|
function replaceDocument(doc, docToReplace) {
if (!(doc instanceof Document) || !(docToReplace instanceof Document)) {
console.warn('Cannot replace document.');
return;
}
navigationDocument.replaceDocument(doc, docToReplace);
}
|
[
"function",
"replaceDocument",
"(",
"doc",
",",
"docToReplace",
")",
"{",
"if",
"(",
"!",
"(",
"doc",
"instanceof",
"Document",
")",
"||",
"!",
"(",
"docToReplace",
"instanceof",
"Document",
")",
")",
"{",
"console",
".",
"warn",
"(",
"'Cannot replace document.'",
")",
";",
"return",
";",
"}",
"navigationDocument",
".",
"replaceDocument",
"(",
"doc",
",",
"docToReplace",
")",
";",
"}"
] |
Replaces a document on the navigation stack with the provided new document.
Also adds the page level default handlers to the new document and removes the existing handlers from the document that is to be replaced.
@inner
@alias module:navigation.replaceDocument
@param {Document} doc The document to push
@param {Document} docToReplace The document to replace
|
[
"Replaces",
"a",
"document",
"on",
"the",
"navigation",
"stack",
"with",
"the",
"provided",
"new",
"document",
".",
"Also",
"adds",
"the",
"page",
"level",
"default",
"handlers",
"to",
"the",
"new",
"document",
"and",
"removes",
"the",
"existing",
"handlers",
"from",
"the",
"document",
"that",
"is",
"to",
"be",
"replaced",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/navigation.js#L229-L235
|
16,320
|
emadalam/atvjs
|
src/navigation.js
|
cleanNavigate
|
function cleanNavigate(doc, replace = false) {
let navigated = false;
let docs = navigationDocument.documents;
let last = getLastDocumentFromStack();
if (!replace && (!last || last !== loaderDoc && last !== errorDoc)) {
pushDocument(doc);
} else if (last && last === loaderDoc || last === errorDoc) { // replaces any error or loader document from the current document stack
console.log('replacing current error/loader...');
replaceDocument(doc, last);
loaderDoc = null;
errorDoc = null;
}
// determine the current document on the navigation stack
last = replace && getLastDocumentFromStack();
// if replace is passed as a param and there is some document on the top of stack
if (last) {
console.log('replacing current document...');
replaceDocument(doc, last);
}
// dismisses any modal open modal
_.delay(dismissModal, 2000);
return docs[docs.length - 1];
}
|
javascript
|
function cleanNavigate(doc, replace = false) {
let navigated = false;
let docs = navigationDocument.documents;
let last = getLastDocumentFromStack();
if (!replace && (!last || last !== loaderDoc && last !== errorDoc)) {
pushDocument(doc);
} else if (last && last === loaderDoc || last === errorDoc) { // replaces any error or loader document from the current document stack
console.log('replacing current error/loader...');
replaceDocument(doc, last);
loaderDoc = null;
errorDoc = null;
}
// determine the current document on the navigation stack
last = replace && getLastDocumentFromStack();
// if replace is passed as a param and there is some document on the top of stack
if (last) {
console.log('replacing current document...');
replaceDocument(doc, last);
}
// dismisses any modal open modal
_.delay(dismissModal, 2000);
return docs[docs.length - 1];
}
|
[
"function",
"cleanNavigate",
"(",
"doc",
",",
"replace",
"=",
"false",
")",
"{",
"let",
"navigated",
"=",
"false",
";",
"let",
"docs",
"=",
"navigationDocument",
".",
"documents",
";",
"let",
"last",
"=",
"getLastDocumentFromStack",
"(",
")",
";",
"if",
"(",
"!",
"replace",
"&&",
"(",
"!",
"last",
"||",
"last",
"!==",
"loaderDoc",
"&&",
"last",
"!==",
"errorDoc",
")",
")",
"{",
"pushDocument",
"(",
"doc",
")",
";",
"}",
"else",
"if",
"(",
"last",
"&&",
"last",
"===",
"loaderDoc",
"||",
"last",
"===",
"errorDoc",
")",
"{",
"// replaces any error or loader document from the current document stack",
"console",
".",
"log",
"(",
"'replacing current error/loader...'",
")",
";",
"replaceDocument",
"(",
"doc",
",",
"last",
")",
";",
"loaderDoc",
"=",
"null",
";",
"errorDoc",
"=",
"null",
";",
"}",
"// determine the current document on the navigation stack",
"last",
"=",
"replace",
"&&",
"getLastDocumentFromStack",
"(",
")",
";",
"// if replace is passed as a param and there is some document on the top of stack",
"if",
"(",
"last",
")",
"{",
"console",
".",
"log",
"(",
"'replacing current document...'",
")",
";",
"replaceDocument",
"(",
"doc",
",",
"last",
")",
";",
"}",
"// dismisses any modal open modal",
"_",
".",
"delay",
"(",
"dismissModal",
",",
"2000",
")",
";",
"return",
"docs",
"[",
"docs",
".",
"length",
"-",
"1",
"]",
";",
"}"
] |
Performs a navigation by checking the existing document stack to see if any error or loader page needs to be replaced from the current stack
@private
@param {Document} doc The document that needs to be pushed on to the navigation stack
@param {Boolean} [replace=false] Whether to replace the last document from the navigation stack
@return {Document} The current document on the stack
|
[
"Performs",
"a",
"navigation",
"by",
"checking",
"the",
"existing",
"document",
"stack",
"to",
"see",
"if",
"any",
"error",
"or",
"loader",
"page",
"needs",
"to",
"be",
"replaced",
"from",
"the",
"current",
"stack"
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/navigation.js#L246-L271
|
16,321
|
emadalam/atvjs
|
src/navigation.js
|
navigateToMenuPage
|
function navigateToMenuPage() {
console.log('navigating to menu...');
return new Promise((resolve, reject) => {
if (!menuDoc) {
initMenu();
}
if (!menuDoc) {
console.warn('No menu configuration exists, cannot navigate to the menu page.');
reject();
} else {
cleanNavigate(menuDoc);
resolve(menuDoc);
}
});
}
|
javascript
|
function navigateToMenuPage() {
console.log('navigating to menu...');
return new Promise((resolve, reject) => {
if (!menuDoc) {
initMenu();
}
if (!menuDoc) {
console.warn('No menu configuration exists, cannot navigate to the menu page.');
reject();
} else {
cleanNavigate(menuDoc);
resolve(menuDoc);
}
});
}
|
[
"function",
"navigateToMenuPage",
"(",
")",
"{",
"console",
".",
"log",
"(",
"'navigating to menu...'",
")",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"if",
"(",
"!",
"menuDoc",
")",
"{",
"initMenu",
"(",
")",
";",
"}",
"if",
"(",
"!",
"menuDoc",
")",
"{",
"console",
".",
"warn",
"(",
"'No menu configuration exists, cannot navigate to the menu page.'",
")",
";",
"reject",
"(",
")",
";",
"}",
"else",
"{",
"cleanNavigate",
"(",
"menuDoc",
")",
";",
"resolve",
"(",
"menuDoc",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Navigates to the menu page if it exists
@inner
@alias module:navigation.navigateToMenuPage
@return {Promise} Returns a Promise that resolves upon successful navigation.
|
[
"Navigates",
"to",
"the",
"menu",
"page",
"if",
"it",
"exists"
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/navigation.js#L281-L297
|
16,322
|
emadalam/atvjs
|
src/navigation.js
|
navigate
|
function navigate(page, options, replace) {
let p = Page.get(page);
if (_.isBoolean(options)) {
replace = options;
} else {
options = options || {};
}
if (_.isBoolean(options.replace)) {
replace = options.replace;
}
console.log('navigating... page:', page, ':: options:', options);
// return a promise that resolves if there was a navigation that was performed
return new Promise((resolve, reject) => {
if (!p) {
console.error(page, 'page does not exist!');
let tpl = defaults.templates.status['404'];
if (tpl) {
let doc = showError({
template: tpl,
title: '404',
message: 'The requested page cannot be found!'
});
resolve(doc);
} else {
reject();
}
return;
}
p(options).then((doc) => {
// support suppressing of navigation since there is no dom available (page resolved with empty document)
if (doc) {
// if page is a modal, show as modal window
if (p.type === 'modal') {
// defer to avoid clashes with any ongoing process (tvmlkit weird behavior -_-)
_.defer(presentModal, doc);
} else { // navigate
// defer to avoid clashes with any ongoing process (tvmlkit weird behavior -_-)
_.defer(cleanNavigate, doc, replace);
}
}
// resolve promise
resolve(doc);
}, (error) => {
// something went wrong during the page execution
// warn and set the status to 500
if (error instanceof Error) {
console.error(`There was an error in the page code. ${error}`);
error.status = '500';
}
// try showing a status level error page if it exists
let statusLevelErrorTpls = defaults.templates.status;
let tpl = statusLevelErrorTpls[error.status];
if (tpl) {
showError(_.defaults({
template: tpl
}, error.response));
resolve(error);
} else {
console.warn('No error handler present in the page or navigation default configurations.', error);
reject(error);
}
});
});
}
|
javascript
|
function navigate(page, options, replace) {
let p = Page.get(page);
if (_.isBoolean(options)) {
replace = options;
} else {
options = options || {};
}
if (_.isBoolean(options.replace)) {
replace = options.replace;
}
console.log('navigating... page:', page, ':: options:', options);
// return a promise that resolves if there was a navigation that was performed
return new Promise((resolve, reject) => {
if (!p) {
console.error(page, 'page does not exist!');
let tpl = defaults.templates.status['404'];
if (tpl) {
let doc = showError({
template: tpl,
title: '404',
message: 'The requested page cannot be found!'
});
resolve(doc);
} else {
reject();
}
return;
}
p(options).then((doc) => {
// support suppressing of navigation since there is no dom available (page resolved with empty document)
if (doc) {
// if page is a modal, show as modal window
if (p.type === 'modal') {
// defer to avoid clashes with any ongoing process (tvmlkit weird behavior -_-)
_.defer(presentModal, doc);
} else { // navigate
// defer to avoid clashes with any ongoing process (tvmlkit weird behavior -_-)
_.defer(cleanNavigate, doc, replace);
}
}
// resolve promise
resolve(doc);
}, (error) => {
// something went wrong during the page execution
// warn and set the status to 500
if (error instanceof Error) {
console.error(`There was an error in the page code. ${error}`);
error.status = '500';
}
// try showing a status level error page if it exists
let statusLevelErrorTpls = defaults.templates.status;
let tpl = statusLevelErrorTpls[error.status];
if (tpl) {
showError(_.defaults({
template: tpl
}, error.response));
resolve(error);
} else {
console.warn('No error handler present in the page or navigation default configurations.', error);
reject(error);
}
});
});
}
|
[
"function",
"navigate",
"(",
"page",
",",
"options",
",",
"replace",
")",
"{",
"let",
"p",
"=",
"Page",
".",
"get",
"(",
"page",
")",
";",
"if",
"(",
"_",
".",
"isBoolean",
"(",
"options",
")",
")",
"{",
"replace",
"=",
"options",
";",
"}",
"else",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"}",
"if",
"(",
"_",
".",
"isBoolean",
"(",
"options",
".",
"replace",
")",
")",
"{",
"replace",
"=",
"options",
".",
"replace",
";",
"}",
"console",
".",
"log",
"(",
"'navigating... page:'",
",",
"page",
",",
"':: options:'",
",",
"options",
")",
";",
"// return a promise that resolves if there was a navigation that was performed",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"if",
"(",
"!",
"p",
")",
"{",
"console",
".",
"error",
"(",
"page",
",",
"'page does not exist!'",
")",
";",
"let",
"tpl",
"=",
"defaults",
".",
"templates",
".",
"status",
"[",
"'404'",
"]",
";",
"if",
"(",
"tpl",
")",
"{",
"let",
"doc",
"=",
"showError",
"(",
"{",
"template",
":",
"tpl",
",",
"title",
":",
"'404'",
",",
"message",
":",
"'The requested page cannot be found!'",
"}",
")",
";",
"resolve",
"(",
"doc",
")",
";",
"}",
"else",
"{",
"reject",
"(",
")",
";",
"}",
"return",
";",
"}",
"p",
"(",
"options",
")",
".",
"then",
"(",
"(",
"doc",
")",
"=>",
"{",
"// support suppressing of navigation since there is no dom available (page resolved with empty document)",
"if",
"(",
"doc",
")",
"{",
"// if page is a modal, show as modal window",
"if",
"(",
"p",
".",
"type",
"===",
"'modal'",
")",
"{",
"// defer to avoid clashes with any ongoing process (tvmlkit weird behavior -_-)",
"_",
".",
"defer",
"(",
"presentModal",
",",
"doc",
")",
";",
"}",
"else",
"{",
"// navigate",
"// defer to avoid clashes with any ongoing process (tvmlkit weird behavior -_-)",
"_",
".",
"defer",
"(",
"cleanNavigate",
",",
"doc",
",",
"replace",
")",
";",
"}",
"}",
"// resolve promise",
"resolve",
"(",
"doc",
")",
";",
"}",
",",
"(",
"error",
")",
"=>",
"{",
"// something went wrong during the page execution",
"// warn and set the status to 500",
"if",
"(",
"error",
"instanceof",
"Error",
")",
"{",
"console",
".",
"error",
"(",
"`",
"${",
"error",
"}",
"`",
")",
";",
"error",
".",
"status",
"=",
"'500'",
";",
"}",
"// try showing a status level error page if it exists",
"let",
"statusLevelErrorTpls",
"=",
"defaults",
".",
"templates",
".",
"status",
";",
"let",
"tpl",
"=",
"statusLevelErrorTpls",
"[",
"error",
".",
"status",
"]",
";",
"if",
"(",
"tpl",
")",
"{",
"showError",
"(",
"_",
".",
"defaults",
"(",
"{",
"template",
":",
"tpl",
"}",
",",
"error",
".",
"response",
")",
")",
";",
"resolve",
"(",
"error",
")",
";",
"}",
"else",
"{",
"console",
".",
"warn",
"(",
"'No error handler present in the page or navigation default configurations.'",
",",
"error",
")",
";",
"reject",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Navigates to the provided page if it exists in the list of available pages.
@inner
@alias module:navigation.navigate
@param {String} page Name of the previously created page.
@param {Object} options The options that will be passed on to the page during runtime.
@param {Boolean} replace Replace the previous page.
@return {Promise} Returns a Promise that resolves upon successful navigation.
|
[
"Navigates",
"to",
"the",
"provided",
"page",
"if",
"it",
"exists",
"in",
"the",
"list",
"of",
"available",
"pages",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/navigation.js#L310-L378
|
16,323
|
emadalam/atvjs
|
src/navigation.js
|
presentModal
|
function presentModal(modal) {
let doc = modal; // assume a document object is passed
if (_.isString(modal)) { // if a modal document string is passed
doc = Parser.dom(modal);
} else if (_.isPlainObject(modal)) { // if a modal page configuration is passed
doc = Page.makeDom(modal);
}
navigationDocument.presentModal(doc);
modalDoc = doc;
return doc;
}
|
javascript
|
function presentModal(modal) {
let doc = modal; // assume a document object is passed
if (_.isString(modal)) { // if a modal document string is passed
doc = Parser.dom(modal);
} else if (_.isPlainObject(modal)) { // if a modal page configuration is passed
doc = Page.makeDom(modal);
}
navigationDocument.presentModal(doc);
modalDoc = doc;
return doc;
}
|
[
"function",
"presentModal",
"(",
"modal",
")",
"{",
"let",
"doc",
"=",
"modal",
";",
"// assume a document object is passed",
"if",
"(",
"_",
".",
"isString",
"(",
"modal",
")",
")",
"{",
"// if a modal document string is passed",
"doc",
"=",
"Parser",
".",
"dom",
"(",
"modal",
")",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isPlainObject",
"(",
"modal",
")",
")",
"{",
"// if a modal page configuration is passed",
"doc",
"=",
"Page",
".",
"makeDom",
"(",
"modal",
")",
";",
"}",
"navigationDocument",
".",
"presentModal",
"(",
"doc",
")",
";",
"modalDoc",
"=",
"doc",
";",
"return",
"doc",
";",
"}"
] |
Shows a modal. Closes the previous modal before showing a new modal.
@inner
@alias module:navigation.presentModal
@param {Document|String|Object} modal The TVML string/document representation of the modal window or a configuration object to create modal from
@return {Document} The created modal document
|
[
"Shows",
"a",
"modal",
".",
"Closes",
"the",
"previous",
"modal",
"before",
"showing",
"a",
"new",
"modal",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/navigation.js#L389-L399
|
16,324
|
emadalam/atvjs
|
src/navigation.js
|
pop
|
function pop(doc) {
if (doc instanceof Document) {
_.defer(() => navigationDocument.popToDocument(doc));
} else {
_.defer(() => navigationDocument.popDocument());
}
}
|
javascript
|
function pop(doc) {
if (doc instanceof Document) {
_.defer(() => navigationDocument.popToDocument(doc));
} else {
_.defer(() => navigationDocument.popDocument());
}
}
|
[
"function",
"pop",
"(",
"doc",
")",
"{",
"if",
"(",
"doc",
"instanceof",
"Document",
")",
"{",
"_",
".",
"defer",
"(",
"(",
")",
"=>",
"navigationDocument",
".",
"popToDocument",
"(",
"doc",
")",
")",
";",
"}",
"else",
"{",
"_",
".",
"defer",
"(",
"(",
")",
"=>",
"navigationDocument",
".",
"popDocument",
"(",
")",
")",
";",
"}",
"}"
] |
Pops the recent document or pops all document before the provided document.
@inner
@alias module:navigation.pop
@param {Document} [doc] The document until which we need to pop.
|
[
"Pops",
"the",
"recent",
"document",
"or",
"pops",
"all",
"document",
"before",
"the",
"provided",
"document",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/navigation.js#L432-L438
|
16,325
|
emadalam/atvjs
|
src/page.js
|
appendStyle
|
function appendStyle(style, doc) {
if (!_.isString(style) || !doc) {
console.log('invalid document or style string...', style, doc);
return;
}
let docEl = (doc.getElementsByTagName('document')).item(0);
let styleString = ['<style>', style, '</style>'].join('');
let headTag = doc.getElementsByTagName('head');
headTag = headTag && headTag.item(0);
if (!headTag) {
headTag = doc.createElement('head');
docEl.insertBefore(headTag, docEl.firstChild);
}
headTag.innerHTML = styleString;
}
|
javascript
|
function appendStyle(style, doc) {
if (!_.isString(style) || !doc) {
console.log('invalid document or style string...', style, doc);
return;
}
let docEl = (doc.getElementsByTagName('document')).item(0);
let styleString = ['<style>', style, '</style>'].join('');
let headTag = doc.getElementsByTagName('head');
headTag = headTag && headTag.item(0);
if (!headTag) {
headTag = doc.createElement('head');
docEl.insertBefore(headTag, docEl.firstChild);
}
headTag.innerHTML = styleString;
}
|
[
"function",
"appendStyle",
"(",
"style",
",",
"doc",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isString",
"(",
"style",
")",
"||",
"!",
"doc",
")",
"{",
"console",
".",
"log",
"(",
"'invalid document or style string...'",
",",
"style",
",",
"doc",
")",
";",
"return",
";",
"}",
"let",
"docEl",
"=",
"(",
"doc",
".",
"getElementsByTagName",
"(",
"'document'",
")",
")",
".",
"item",
"(",
"0",
")",
";",
"let",
"styleString",
"=",
"[",
"'<style>'",
",",
"style",
",",
"'</style>'",
"]",
".",
"join",
"(",
"''",
")",
";",
"let",
"headTag",
"=",
"doc",
".",
"getElementsByTagName",
"(",
"'head'",
")",
";",
"headTag",
"=",
"headTag",
"&&",
"headTag",
".",
"item",
"(",
"0",
")",
";",
"if",
"(",
"!",
"headTag",
")",
"{",
"headTag",
"=",
"doc",
".",
"createElement",
"(",
"'head'",
")",
";",
"docEl",
".",
"insertBefore",
"(",
"headTag",
",",
"docEl",
".",
"firstChild",
")",
";",
"}",
"headTag",
".",
"innerHTML",
"=",
"styleString",
";",
"}"
] |
Adds style to a document.
@todo Check for existing style tag within the head of the provided document and append if exists
@private
@param {String} style Style string
@param {Document} doc The document to add styles on
|
[
"Adds",
"style",
"to",
"a",
"document",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/page.js#L79-L94
|
16,326
|
emadalam/atvjs
|
src/page.js
|
prepareDom
|
function prepareDom(doc, cfg = {}) {
if (!(doc instanceof Document)) {
console.warn('Cannnot prepare, the provided element is not a document.');
return;
}
// apply defaults
_.defaults(cfg, defaults);
// append any default styles
appendStyle(cfg.style, doc);
// attach event handlers
Handler.addAll(doc, cfg);
return doc;
}
|
javascript
|
function prepareDom(doc, cfg = {}) {
if (!(doc instanceof Document)) {
console.warn('Cannnot prepare, the provided element is not a document.');
return;
}
// apply defaults
_.defaults(cfg, defaults);
// append any default styles
appendStyle(cfg.style, doc);
// attach event handlers
Handler.addAll(doc, cfg);
return doc;
}
|
[
"function",
"prepareDom",
"(",
"doc",
",",
"cfg",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"!",
"(",
"doc",
"instanceof",
"Document",
")",
")",
"{",
"console",
".",
"warn",
"(",
"'Cannnot prepare, the provided element is not a document.'",
")",
";",
"return",
";",
"}",
"// apply defaults",
"_",
".",
"defaults",
"(",
"cfg",
",",
"defaults",
")",
";",
"// append any default styles",
"appendStyle",
"(",
"cfg",
".",
"style",
",",
"doc",
")",
";",
"// attach event handlers",
"Handler",
".",
"addAll",
"(",
"doc",
",",
"cfg",
")",
";",
"return",
"doc",
";",
"}"
] |
Prepares a document by adding styles and event handlers.
@inner
@alias module:page.prepareDom
@param {Document} doc The document to prepare
@return {Document} The document passed
|
[
"Prepares",
"a",
"document",
"by",
"adding",
"styles",
"and",
"event",
"handlers",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/page.js#L105-L118
|
16,327
|
emadalam/atvjs
|
src/page.js
|
makeDom
|
function makeDom(cfg, response) {
// apply defaults
_.defaults(cfg, defaults);
// create Document
let doc = Parser.dom(cfg.template, (_.isPlainObject(cfg.data) ? cfg.data: cfg.data(response)));
// prepare the Document
prepareDom(doc, cfg);
// call the after ready method if defined in the configuration
if (_.isFunction(cfg.afterReady)) {
console.log('calling afterReady method...');
cfg.afterReady(doc);
}
// cache cfg at the document level
doc.page = cfg;
return doc;
}
|
javascript
|
function makeDom(cfg, response) {
// apply defaults
_.defaults(cfg, defaults);
// create Document
let doc = Parser.dom(cfg.template, (_.isPlainObject(cfg.data) ? cfg.data: cfg.data(response)));
// prepare the Document
prepareDom(doc, cfg);
// call the after ready method if defined in the configuration
if (_.isFunction(cfg.afterReady)) {
console.log('calling afterReady method...');
cfg.afterReady(doc);
}
// cache cfg at the document level
doc.page = cfg;
return doc;
}
|
[
"function",
"makeDom",
"(",
"cfg",
",",
"response",
")",
"{",
"// apply defaults",
"_",
".",
"defaults",
"(",
"cfg",
",",
"defaults",
")",
";",
"// create Document",
"let",
"doc",
"=",
"Parser",
".",
"dom",
"(",
"cfg",
".",
"template",
",",
"(",
"_",
".",
"isPlainObject",
"(",
"cfg",
".",
"data",
")",
"?",
"cfg",
".",
"data",
":",
"cfg",
".",
"data",
"(",
"response",
")",
")",
")",
";",
"// prepare the Document",
"prepareDom",
"(",
"doc",
",",
"cfg",
")",
";",
"// call the after ready method if defined in the configuration",
"if",
"(",
"_",
".",
"isFunction",
"(",
"cfg",
".",
"afterReady",
")",
")",
"{",
"console",
".",
"log",
"(",
"'calling afterReady method...'",
")",
";",
"cfg",
".",
"afterReady",
"(",
"doc",
")",
";",
"}",
"// cache cfg at the document level",
"doc",
".",
"page",
"=",
"cfg",
";",
"return",
"doc",
";",
"}"
] |
A helper method that calls the data method to transform the data.
It then creates a dom from the provided template and the final data.
@inner
@alias module:page.makeDom
@param {Object} cfg Page configuration options
@param {Object} response The data object
@return {Document} The newly created document
|
[
"A",
"helper",
"method",
"that",
"calls",
"the",
"data",
"method",
"to",
"transform",
"the",
"data",
".",
"It",
"then",
"creates",
"a",
"dom",
"from",
"the",
"provided",
"template",
"and",
"the",
"final",
"data",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/page.js#L131-L147
|
16,328
|
emadalam/atvjs
|
src/page.js
|
makePage
|
function makePage(cfg) {
return (options) => {
_.defaultsDeep(cfg, defaults);
console.log('making page... options:', cfg);
// return a promise that resolves after completion of the ajax request
// if no ready method or url configuration exist, the promise is resolved immediately and the resultant dom is returned
return new Promise((resolve, reject) => {
if (_.isFunction(cfg.ready)) { // if present, call the ready function
console.log('calling page ready... options:', options);
// resolves promise with a doc if there is a response param passed
// if the response param is null/falsy value, resolve with null (usefull for catching and supressing any navigation later)
cfg.ready(options, (response) => resolve((response || _.isUndefined(response)) ? makeDom(cfg, response) : null), reject);
} else if (cfg.url) { // make ajax request if a url is provided
Ajax
.get(cfg.url, cfg.options)
.then((xhr) => {
resolve(makeDom(cfg, xhr.response));
}, (xhr) => {
// if present, call the error handler
if (_.isFunction(cfg.onError)) {
cfg.onError(xhr.response, xhr);
} else {
reject(xhr);
}
});
} else { // no url/ready method provided, resolve the promise immediately
resolve(makeDom(cfg));
}
});
}
}
|
javascript
|
function makePage(cfg) {
return (options) => {
_.defaultsDeep(cfg, defaults);
console.log('making page... options:', cfg);
// return a promise that resolves after completion of the ajax request
// if no ready method or url configuration exist, the promise is resolved immediately and the resultant dom is returned
return new Promise((resolve, reject) => {
if (_.isFunction(cfg.ready)) { // if present, call the ready function
console.log('calling page ready... options:', options);
// resolves promise with a doc if there is a response param passed
// if the response param is null/falsy value, resolve with null (usefull for catching and supressing any navigation later)
cfg.ready(options, (response) => resolve((response || _.isUndefined(response)) ? makeDom(cfg, response) : null), reject);
} else if (cfg.url) { // make ajax request if a url is provided
Ajax
.get(cfg.url, cfg.options)
.then((xhr) => {
resolve(makeDom(cfg, xhr.response));
}, (xhr) => {
// if present, call the error handler
if (_.isFunction(cfg.onError)) {
cfg.onError(xhr.response, xhr);
} else {
reject(xhr);
}
});
} else { // no url/ready method provided, resolve the promise immediately
resolve(makeDom(cfg));
}
});
}
}
|
[
"function",
"makePage",
"(",
"cfg",
")",
"{",
"return",
"(",
"options",
")",
"=>",
"{",
"_",
".",
"defaultsDeep",
"(",
"cfg",
",",
"defaults",
")",
";",
"console",
".",
"log",
"(",
"'making page... options:'",
",",
"cfg",
")",
";",
"// return a promise that resolves after completion of the ajax request",
"// if no ready method or url configuration exist, the promise is resolved immediately and the resultant dom is returned",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"if",
"(",
"_",
".",
"isFunction",
"(",
"cfg",
".",
"ready",
")",
")",
"{",
"// if present, call the ready function",
"console",
".",
"log",
"(",
"'calling page ready... options:'",
",",
"options",
")",
";",
"// resolves promise with a doc if there is a response param passed",
"// if the response param is null/falsy value, resolve with null (usefull for catching and supressing any navigation later)",
"cfg",
".",
"ready",
"(",
"options",
",",
"(",
"response",
")",
"=>",
"resolve",
"(",
"(",
"response",
"||",
"_",
".",
"isUndefined",
"(",
"response",
")",
")",
"?",
"makeDom",
"(",
"cfg",
",",
"response",
")",
":",
"null",
")",
",",
"reject",
")",
";",
"}",
"else",
"if",
"(",
"cfg",
".",
"url",
")",
"{",
"// make ajax request if a url is provided",
"Ajax",
".",
"get",
"(",
"cfg",
".",
"url",
",",
"cfg",
".",
"options",
")",
".",
"then",
"(",
"(",
"xhr",
")",
"=>",
"{",
"resolve",
"(",
"makeDom",
"(",
"cfg",
",",
"xhr",
".",
"response",
")",
")",
";",
"}",
",",
"(",
"xhr",
")",
"=>",
"{",
"// if present, call the error handler",
"if",
"(",
"_",
".",
"isFunction",
"(",
"cfg",
".",
"onError",
")",
")",
"{",
"cfg",
".",
"onError",
"(",
"xhr",
".",
"response",
",",
"xhr",
")",
";",
"}",
"else",
"{",
"reject",
"(",
"xhr",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"// no url/ready method provided, resolve the promise immediately",
"resolve",
"(",
"makeDom",
"(",
"cfg",
")",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] |
Generated a page function which returns a promise after invocation.
@private
@param {Object} cfg The page configuration object
@return {Function} A function that returns promise upon execution
|
[
"Generated",
"a",
"page",
"function",
"which",
"returns",
"a",
"promise",
"after",
"invocation",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/page.js#L157-L189
|
16,329
|
emadalam/atvjs
|
src/parser.js
|
parse
|
function parse(s, data) {
// if a template function is provided, call the function with data
s = _.isFunction(s) ? s(data) : s;
console.log('parsing string...');
console.log(s);
// prepend the xml string if not already present
if (!_.startsWith(s, '<?xml')) {
s = xmlPrefix + s;
}
return parser.parseFromString(s, 'application/xml');
}
|
javascript
|
function parse(s, data) {
// if a template function is provided, call the function with data
s = _.isFunction(s) ? s(data) : s;
console.log('parsing string...');
console.log(s);
// prepend the xml string if not already present
if (!_.startsWith(s, '<?xml')) {
s = xmlPrefix + s;
}
return parser.parseFromString(s, 'application/xml');
}
|
[
"function",
"parse",
"(",
"s",
",",
"data",
")",
"{",
"// if a template function is provided, call the function with data",
"s",
"=",
"_",
".",
"isFunction",
"(",
"s",
")",
"?",
"s",
"(",
"data",
")",
":",
"s",
";",
"console",
".",
"log",
"(",
"'parsing string...'",
")",
";",
"console",
".",
"log",
"(",
"s",
")",
";",
"// prepend the xml string if not already present",
"if",
"(",
"!",
"_",
".",
"startsWith",
"(",
"s",
",",
"'<?xml'",
")",
")",
"{",
"s",
"=",
"xmlPrefix",
"+",
"s",
";",
"}",
"return",
"parser",
".",
"parseFromString",
"(",
"s",
",",
"'application/xml'",
")",
";",
"}"
] |
xml prefix
Parses the given XML string or a function and returns a DOM
@private
@param {String|Function} s The template function or the string
@param {Object} [data] The data that will be applied to the function
@return {Document} A new Document
|
[
"xml",
"prefix",
"Parses",
"the",
"given",
"XML",
"string",
"or",
"a",
"function",
"and",
"returns",
"a",
"DOM"
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/parser.js#L14-L27
|
16,330
|
emadalam/atvjs
|
src/menu.js
|
setAttributes
|
function setAttributes(el, attributes) {
console.log('setting attributes on element...', el, attributes);
_.each(attributes, (value, name) => el.setAttribute(name, value));
}
|
javascript
|
function setAttributes(el, attributes) {
console.log('setting attributes on element...', el, attributes);
_.each(attributes, (value, name) => el.setAttribute(name, value));
}
|
[
"function",
"setAttributes",
"(",
"el",
",",
"attributes",
")",
"{",
"console",
".",
"log",
"(",
"'setting attributes on element...'",
",",
"el",
",",
"attributes",
")",
";",
"_",
".",
"each",
"(",
"attributes",
",",
"(",
"value",
",",
"name",
")",
"=>",
"el",
".",
"setAttribute",
"(",
"name",
",",
"value",
")",
")",
";",
"}"
] |
Iterates and sets attributes to an element.
@private
@param {Element} el The element to set attributes on
@param {Object} attributes Attributes key value pairs.
|
[
"Iterates",
"and",
"sets",
"attributes",
"to",
"an",
"element",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/menu.js#L46-L49
|
16,331
|
emadalam/atvjs
|
src/menu.js
|
addItem
|
function addItem(item = {}) {
if (!item.id) {
console.warn('Cannot add menuitem. A unique identifier is required for the menuitem to work correctly.');
return;
}
let el = doc.createElement('menuItem');
// assign unique id
item.attributes = _.assign({}, item.attributes, {
id: item.id
});
// add all attributes
setAttributes(el, item.attributes);
// add title
el.innerHTML = `<title>${(_.isFunction(item.name) ? item.name() : item.name)}</title>`;
// add page reference
el.page = item.page;
// appends to the menu
menuBarEl.insertBefore(el, null);
// cache for later use
itemsCache[item.id] = el;
return el;
}
|
javascript
|
function addItem(item = {}) {
if (!item.id) {
console.warn('Cannot add menuitem. A unique identifier is required for the menuitem to work correctly.');
return;
}
let el = doc.createElement('menuItem');
// assign unique id
item.attributes = _.assign({}, item.attributes, {
id: item.id
});
// add all attributes
setAttributes(el, item.attributes);
// add title
el.innerHTML = `<title>${(_.isFunction(item.name) ? item.name() : item.name)}</title>`;
// add page reference
el.page = item.page;
// appends to the menu
menuBarEl.insertBefore(el, null);
// cache for later use
itemsCache[item.id] = el;
return el;
}
|
[
"function",
"addItem",
"(",
"item",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"!",
"item",
".",
"id",
")",
"{",
"console",
".",
"warn",
"(",
"'Cannot add menuitem. A unique identifier is required for the menuitem to work correctly.'",
")",
";",
"return",
";",
"}",
"let",
"el",
"=",
"doc",
".",
"createElement",
"(",
"'menuItem'",
")",
";",
"// assign unique id",
"item",
".",
"attributes",
"=",
"_",
".",
"assign",
"(",
"{",
"}",
",",
"item",
".",
"attributes",
",",
"{",
"id",
":",
"item",
".",
"id",
"}",
")",
";",
"// add all attributes",
"setAttributes",
"(",
"el",
",",
"item",
".",
"attributes",
")",
";",
"// add title",
"el",
".",
"innerHTML",
"=",
"`",
"${",
"(",
"_",
".",
"isFunction",
"(",
"item",
".",
"name",
")",
"?",
"item",
".",
"name",
"(",
")",
":",
"item",
".",
"name",
")",
"}",
"`",
";",
"// add page reference",
"el",
".",
"page",
"=",
"item",
".",
"page",
";",
"// appends to the menu",
"menuBarEl",
".",
"insertBefore",
"(",
"el",
",",
"null",
")",
";",
"// cache for later use",
"itemsCache",
"[",
"item",
".",
"id",
"]",
"=",
"el",
";",
"return",
"el",
";",
"}"
] |
Adds menu item to the menu document.
@private
@param {Object} item The configuration realted to the menu item.
|
[
"Adds",
"menu",
"item",
"to",
"the",
"menu",
"document",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/menu.js#L73-L95
|
16,332
|
emadalam/atvjs
|
src/menu.js
|
create
|
function create(cfg = {}) {
if (created) {
console.warn('An instance of menu already exists, skipping creation...');
return;
}
// defaults
_.assign(defaults, cfg);
console.log('creating menu...', defaults);
// set attributes to the menubar element
setAttributes(menuBarEl, defaults.attributes);
// set attributes to the menubarTemplate element
setAttributes(menuBarTpl, defaults.rootTemplateAttributes);
// add all items to the menubar
_.each(defaults.items, (item) => addItem(item));
// indicate done
created = true;
return doc;
}
|
javascript
|
function create(cfg = {}) {
if (created) {
console.warn('An instance of menu already exists, skipping creation...');
return;
}
// defaults
_.assign(defaults, cfg);
console.log('creating menu...', defaults);
// set attributes to the menubar element
setAttributes(menuBarEl, defaults.attributes);
// set attributes to the menubarTemplate element
setAttributes(menuBarTpl, defaults.rootTemplateAttributes);
// add all items to the menubar
_.each(defaults.items, (item) => addItem(item));
// indicate done
created = true;
return doc;
}
|
[
"function",
"create",
"(",
"cfg",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"created",
")",
"{",
"console",
".",
"warn",
"(",
"'An instance of menu already exists, skipping creation...'",
")",
";",
"return",
";",
"}",
"// defaults",
"_",
".",
"assign",
"(",
"defaults",
",",
"cfg",
")",
";",
"console",
".",
"log",
"(",
"'creating menu...'",
",",
"defaults",
")",
";",
"// set attributes to the menubar element",
"setAttributes",
"(",
"menuBarEl",
",",
"defaults",
".",
"attributes",
")",
";",
"// set attributes to the menubarTemplate element",
"setAttributes",
"(",
"menuBarTpl",
",",
"defaults",
".",
"rootTemplateAttributes",
")",
";",
"// add all items to the menubar",
"_",
".",
"each",
"(",
"defaults",
".",
"items",
",",
"(",
"item",
")",
"=>",
"addItem",
"(",
"item",
")",
")",
";",
"// indicate done",
"created",
"=",
"true",
";",
"return",
"doc",
";",
"}"
] |
Generates a menu from the configuration object.
@example
ATV.Menu.create({
attributes: {}, // menuBar attributes
rootTemplateAttributes: {}, // menuBarTemplate attributes
items: [{
id: 'search',
name: 'Search',
page: SearchPage
}, {
id: 'homepage',
name: 'Home',
page: HomePage,
attributes: {
autoHighlight: true // auto highlight on navigate
}
}, {
id: 'movies',
name: 'Movies',
page: MoviesPage
}, {
id: 'tvshows',
name: 'TV Shows',
page: TVShowsPage
}]
});
@inner
@alias module:menu.create
@param {Object} cfg Menu related configurations
@return {Document} The created menu document
|
[
"Generates",
"a",
"menu",
"from",
"the",
"configuration",
"object",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/menu.js#L132-L152
|
16,333
|
emadalam/atvjs
|
src/ajax.js
|
ajax
|
function ajax(url, options, method = 'GET') {
if (typeof url == 'undefined') {
console.error('No url specified for the ajax.');
throw new TypeError('A URL is required for making the ajax request.');
}
if (typeof options === 'undefined' && typeof url === 'object' && url.url) {
options = url;
url = options.url;
} else if (typeof url !== 'string') {
console.error('No url/options specified for the ajax.');
throw new TypeError('Options must be an object for making the ajax request.');
}
// default options
options = Object.assign({}, defaults, options, {method: method});
console.log(`initiating ajax request... url: ${url}`, ' :: options:', options);
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
// set response type
if (options.responseType) {
xhr.responseType = options.responseType;
}
// open connection
xhr.open(
options.method,
url,
typeof options.async === 'undefined' ? true : options.async,
options.user,
options.password
);
// set headers
Object.keys(options.headers || {}).forEach(function(name) {
xhr.setRequestHeader(name, options.headers[name]);
});
// listen to the state change
xhr.onreadystatechange = () => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status <= 300) {
resolve(xhr);
} else {
reject(xhr);
}
};
// error handling
xhr.addEventListener('error', () => reject(xhr));
xhr.addEventListener('abort', () => reject(xhr));
// send request
xhr.send(options.data);
});
}
|
javascript
|
function ajax(url, options, method = 'GET') {
if (typeof url == 'undefined') {
console.error('No url specified for the ajax.');
throw new TypeError('A URL is required for making the ajax request.');
}
if (typeof options === 'undefined' && typeof url === 'object' && url.url) {
options = url;
url = options.url;
} else if (typeof url !== 'string') {
console.error('No url/options specified for the ajax.');
throw new TypeError('Options must be an object for making the ajax request.');
}
// default options
options = Object.assign({}, defaults, options, {method: method});
console.log(`initiating ajax request... url: ${url}`, ' :: options:', options);
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
// set response type
if (options.responseType) {
xhr.responseType = options.responseType;
}
// open connection
xhr.open(
options.method,
url,
typeof options.async === 'undefined' ? true : options.async,
options.user,
options.password
);
// set headers
Object.keys(options.headers || {}).forEach(function(name) {
xhr.setRequestHeader(name, options.headers[name]);
});
// listen to the state change
xhr.onreadystatechange = () => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status <= 300) {
resolve(xhr);
} else {
reject(xhr);
}
};
// error handling
xhr.addEventListener('error', () => reject(xhr));
xhr.addEventListener('abort', () => reject(xhr));
// send request
xhr.send(options.data);
});
}
|
[
"function",
"ajax",
"(",
"url",
",",
"options",
",",
"method",
"=",
"'GET'",
")",
"{",
"if",
"(",
"typeof",
"url",
"==",
"'undefined'",
")",
"{",
"console",
".",
"error",
"(",
"'No url specified for the ajax.'",
")",
";",
"throw",
"new",
"TypeError",
"(",
"'A URL is required for making the ajax request.'",
")",
";",
"}",
"if",
"(",
"typeof",
"options",
"===",
"'undefined'",
"&&",
"typeof",
"url",
"===",
"'object'",
"&&",
"url",
".",
"url",
")",
"{",
"options",
"=",
"url",
";",
"url",
"=",
"options",
".",
"url",
";",
"}",
"else",
"if",
"(",
"typeof",
"url",
"!==",
"'string'",
")",
"{",
"console",
".",
"error",
"(",
"'No url/options specified for the ajax.'",
")",
";",
"throw",
"new",
"TypeError",
"(",
"'Options must be an object for making the ajax request.'",
")",
";",
"}",
"// default options",
"options",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"defaults",
",",
"options",
",",
"{",
"method",
":",
"method",
"}",
")",
";",
"console",
".",
"log",
"(",
"`",
"${",
"url",
"}",
"`",
",",
"' :: options:'",
",",
"options",
")",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"let",
"xhr",
"=",
"new",
"XMLHttpRequest",
"(",
")",
";",
"// set response type",
"if",
"(",
"options",
".",
"responseType",
")",
"{",
"xhr",
".",
"responseType",
"=",
"options",
".",
"responseType",
";",
"}",
"// open connection",
"xhr",
".",
"open",
"(",
"options",
".",
"method",
",",
"url",
",",
"typeof",
"options",
".",
"async",
"===",
"'undefined'",
"?",
"true",
":",
"options",
".",
"async",
",",
"options",
".",
"user",
",",
"options",
".",
"password",
")",
";",
"// set headers",
"Object",
".",
"keys",
"(",
"options",
".",
"headers",
"||",
"{",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"xhr",
".",
"setRequestHeader",
"(",
"name",
",",
"options",
".",
"headers",
"[",
"name",
"]",
")",
";",
"}",
")",
";",
"// listen to the state change",
"xhr",
".",
"onreadystatechange",
"=",
"(",
")",
"=>",
"{",
"if",
"(",
"xhr",
".",
"readyState",
"!==",
"4",
")",
"{",
"return",
";",
"}",
"if",
"(",
"xhr",
".",
"status",
">=",
"200",
"&&",
"xhr",
".",
"status",
"<=",
"300",
")",
"{",
"resolve",
"(",
"xhr",
")",
";",
"}",
"else",
"{",
"reject",
"(",
"xhr",
")",
";",
"}",
"}",
";",
"// error handling",
"xhr",
".",
"addEventListener",
"(",
"'error'",
",",
"(",
")",
"=>",
"reject",
"(",
"xhr",
")",
")",
";",
"xhr",
".",
"addEventListener",
"(",
"'abort'",
",",
"(",
")",
"=>",
"reject",
"(",
"xhr",
")",
")",
";",
"// send request",
"xhr",
".",
"send",
"(",
"options",
".",
"data",
")",
";",
"}",
")",
";",
"}"
] |
A function to perform ajax requests. It returns promise instead of relying on callbacks.
@example
ATV.Ajax('http://api.mymovieapp.com/movies')
.then((response) => // do something with the response)
.catch((error) => // catch errors )
@memberof module:ajax
@param {String} url Resource url
@param {Object} [options={responseType: 'json'}] Options to apply for the ajax request
@param {String} [method='GET'] Type of HTTP request (defaults to GET)
@return {Promise} The Promise that resolves on ajax success
|
[
"A",
"function",
"to",
"perform",
"ajax",
"requests",
".",
"It",
"returns",
"promise",
"instead",
"of",
"relying",
"on",
"callbacks",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/ajax.js#L26-L82
|
16,334
|
emadalam/atvjs
|
src/index.js
|
initLibraries
|
function initLibraries(cfg = {}) {
_.each(configMap, (keys, libName) => {
let lib = libs[libName];
let options = {};
_.each(keys, (key) => options[key] = cfg[key]);
lib.setOptions && lib.setOptions(options);
});
}
|
javascript
|
function initLibraries(cfg = {}) {
_.each(configMap, (keys, libName) => {
let lib = libs[libName];
let options = {};
_.each(keys, (key) => options[key] = cfg[key]);
lib.setOptions && lib.setOptions(options);
});
}
|
[
"function",
"initLibraries",
"(",
"cfg",
"=",
"{",
"}",
")",
"{",
"_",
".",
"each",
"(",
"configMap",
",",
"(",
"keys",
",",
"libName",
")",
"=>",
"{",
"let",
"lib",
"=",
"libs",
"[",
"libName",
"]",
";",
"let",
"options",
"=",
"{",
"}",
";",
"_",
".",
"each",
"(",
"keys",
",",
"(",
"key",
")",
"=>",
"options",
"[",
"key",
"]",
"=",
"cfg",
"[",
"key",
"]",
")",
";",
"lib",
".",
"setOptions",
"&&",
"lib",
".",
"setOptions",
"(",
"options",
")",
";",
"}",
")",
";",
"}"
] |
Iterates over each libraries and call setOptions with the relevant options.
@private
@param {Object} cfg All configuration options relevant to the libraries
|
[
"Iterates",
"over",
"each",
"libraries",
"and",
"call",
"setOptions",
"with",
"the",
"relevant",
"options",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/index.js#L133-L140
|
16,335
|
emadalam/atvjs
|
src/index.js
|
initAppHandlers
|
function initAppHandlers (cfg = {}) {
_.each(handlers, (handler, name) => App[name] = _.partial(handler, _, (_.isFunction(cfg[name])) ? cfg[name] : _.noop));
}
|
javascript
|
function initAppHandlers (cfg = {}) {
_.each(handlers, (handler, name) => App[name] = _.partial(handler, _, (_.isFunction(cfg[name])) ? cfg[name] : _.noop));
}
|
[
"function",
"initAppHandlers",
"(",
"cfg",
"=",
"{",
"}",
")",
"{",
"_",
".",
"each",
"(",
"handlers",
",",
"(",
"handler",
",",
"name",
")",
"=>",
"App",
"[",
"name",
"]",
"=",
"_",
".",
"partial",
"(",
"handler",
",",
"_",
",",
"(",
"_",
".",
"isFunction",
"(",
"cfg",
"[",
"name",
"]",
")",
")",
"?",
"cfg",
"[",
"name",
"]",
":",
"_",
".",
"noop",
")",
")",
";",
"}"
] |
Iterates over each supported handler types and attach it on the Apple TV App object.
@private
@param {Object} cfg All configuration options relevant to the App.
|
[
"Iterates",
"over",
"each",
"supported",
"handler",
"types",
"and",
"attach",
"it",
"on",
"the",
"Apple",
"TV",
"App",
"object",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/index.js#L214-L216
|
16,336
|
emadalam/atvjs
|
src/index.js
|
start
|
function start(cfg = {}) {
if (started) {
console.warn('Application already started, cannot call start again.');
return;
}
initLibraries(cfg);
initAppHandlers(cfg);
// if already bootloaded somewhere
// immediately call the onLaunch method
if (cfg.bootloaded) {
App.onLaunch(App.launchOptions);
}
started = true;
}
|
javascript
|
function start(cfg = {}) {
if (started) {
console.warn('Application already started, cannot call start again.');
return;
}
initLibraries(cfg);
initAppHandlers(cfg);
// if already bootloaded somewhere
// immediately call the onLaunch method
if (cfg.bootloaded) {
App.onLaunch(App.launchOptions);
}
started = true;
}
|
[
"function",
"start",
"(",
"cfg",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"started",
")",
"{",
"console",
".",
"warn",
"(",
"'Application already started, cannot call start again.'",
")",
";",
"return",
";",
"}",
"initLibraries",
"(",
"cfg",
")",
";",
"initAppHandlers",
"(",
"cfg",
")",
";",
"// if already bootloaded somewhere",
"// immediately call the onLaunch method",
"if",
"(",
"cfg",
".",
"bootloaded",
")",
"{",
"App",
".",
"onLaunch",
"(",
"App",
".",
"launchOptions",
")",
";",
"}",
"started",
"=",
"true",
";",
"}"
] |
Starts the Apple TV application after applying the relevant configuration options
@example
// create your pages
let SearchPage = ATV.Page.create({ page configurations });
let HomePage = ATV.Page.create({ page configurations });
let MoviesPage = ATV.Page.create({ page configurations });
let TVShowsPage = ATV.Page.create({ page configurations });
let LoginPage = ATV.Page.create({ page configurations });
// template functions
const loaderTpl = (data) => `<document>
<loadingTemplate>
<activityIndicator>
<title>${data.message}</title>
</activityIndicator>
</loadingTemplate>
</document>`;
const errorTpl = (data) => `<document>
<descriptiveAlertTemplate>
<title>${data.title}</title>
<description>${data.message}</description>
</descriptiveAlertTemplate>
</document>`;
// Global TVML styles
let globalStyles = `
.text-bold {
font-weight: bold;
}
.text-white {
color: rgb(255, 255, 255);
}
.dark-background-color {
background-color: #091a2a;
}
.button {
background-color: rgba(0, 0, 0, 0.1);
tv-tint-color: rgba(0, 0, 0, 0.1);
}
`;
// start your application by passing configurations
ATV.start({
style: globalStyles,
menu: {
attributes: {},
items: [{
id: 'search',
name: 'Search',
page: SearchPage
}, {
id: 'homepage',
name: 'Home',
page: HomePage,
attributes: {
autoHighlight: true // auto highlight on navigate
}
}, {
id: 'movies',
name: 'Movies',
page: MoviesPage
}, {
id: 'tvshows',
name: 'TV Shows',
page: TVShowsPage
}]
},
templates: {
// loader template
loader: loaderTpl,
// global error template
error: errorTpl,
// xhr status based error messages
status: {
'404': () => errorTpl({
title: '404',
message: 'The given page was not found'
}),
'500': () => errorTpl({
title: '500',
message: 'An unknown error occurred, please try again later!'
})
}
},
// global event handlers that will be called for each of the pages
handlers: {
select: {
globalSelecthandler(e) {
let element = e.target;
let someElementTypeCheck = element.getAttribute('data-my-attribute');
if (elementTypeCheck) {
// perform action
}
}
}
},
onLaunch(options) {
// navigate to menu page
ATV.Navigation.navigateToMenuPage();
// or you can navigate to previously created page
// ATV.Navigation.navigate('login');
}
});
@inner
@alias module:ATV.start
@fires onLaunch
@param {Object} cfg Configuration options
|
[
"Starts",
"the",
"Apple",
"TV",
"application",
"after",
"applying",
"the",
"relevant",
"configuration",
"options"
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/index.js#L332-L346
|
16,337
|
emadalam/atvjs
|
src/index.js
|
reload
|
function reload(options, reloadData) {
App.onReload(options);
App.reload(options, reloadData);
}
|
javascript
|
function reload(options, reloadData) {
App.onReload(options);
App.reload(options, reloadData);
}
|
[
"function",
"reload",
"(",
"options",
",",
"reloadData",
")",
"{",
"App",
".",
"onReload",
"(",
"options",
")",
";",
"App",
".",
"reload",
"(",
"options",
",",
"reloadData",
")",
";",
"}"
] |
Reloads the application with the provided options and data.
@example
ATV.reload({when: 'now'}, {customData});
@inner
@alias module:ATV.reload
@fires onReload
@param {Object} [options] Options value. {when: 'now'} // or 'onResume'
@param {Object} [reloadData] Custom data that needs to be passed while reloading the app
|
[
"Reloads",
"the",
"application",
"with",
"the",
"provided",
"options",
"and",
"data",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/index.js#L361-L364
|
16,338
|
emadalam/atvjs
|
src/handler.js
|
setOptions
|
function setOptions(cfg = {}) {
console.log('setting handler options...', cfg);
// override the default options
_.defaultsDeep(handlers, cfg.handlers);
}
|
javascript
|
function setOptions(cfg = {}) {
console.log('setting handler options...', cfg);
// override the default options
_.defaultsDeep(handlers, cfg.handlers);
}
|
[
"function",
"setOptions",
"(",
"cfg",
"=",
"{",
"}",
")",
"{",
"console",
".",
"log",
"(",
"'setting handler options...'",
",",
"cfg",
")",
";",
"// override the default options",
"_",
".",
"defaultsDeep",
"(",
"handlers",
",",
"cfg",
".",
"handlers",
")",
";",
"}"
] |
Sets the default handlers options
@inner
@alias module:handler.setOptions
@param {Object} cfg The configuration object {defaults}
|
[
"Sets",
"the",
"default",
"handlers",
"options"
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/handler.js#L137-L141
|
16,339
|
emadalam/atvjs
|
src/handler.js
|
setListeners
|
function setListeners(doc, cfg = {}, add = true) {
if (!doc || !(doc instanceof Document)) {
return;
}
let listenerFn = doc.addEventListener;
if (!add) {
listenerFn = doc.removeEventListener;
}
if (_.isObject(cfg.events)) {
let events = cfg.events;
_.each(events, (fns, e) => {
let [ev, selector] = e.split(' ');
let elements = null;
if (!_.isArray(fns)) { // support list of event handlers
fns = [fns];
}
if (selector) {
selector = e.substring(e.indexOf(' ') + 1); // everything after space
elements = _.attempt(() => doc.querySelectorAll(selector)); // catch any errors while document selection
} else {
elements = [doc];
}
elements = _.isError(elements) ? [] : elements;
_.each(fns, (fn) => {
fn = _.isString(fn) ? cfg[fn] : fn; // assume the function to be present on the page configuration obeject
if (_.isFunction(fn)) {
console.log((add ? 'adding' : 'removing') + ' event on documents...', ev, elements);
_.each(elements, (el) => listenerFn.call(el, ev, (e) => fn.call(cfg, e))); // bind to the original configuration object
}
});
})
}
}
|
javascript
|
function setListeners(doc, cfg = {}, add = true) {
if (!doc || !(doc instanceof Document)) {
return;
}
let listenerFn = doc.addEventListener;
if (!add) {
listenerFn = doc.removeEventListener;
}
if (_.isObject(cfg.events)) {
let events = cfg.events;
_.each(events, (fns, e) => {
let [ev, selector] = e.split(' ');
let elements = null;
if (!_.isArray(fns)) { // support list of event handlers
fns = [fns];
}
if (selector) {
selector = e.substring(e.indexOf(' ') + 1); // everything after space
elements = _.attempt(() => doc.querySelectorAll(selector)); // catch any errors while document selection
} else {
elements = [doc];
}
elements = _.isError(elements) ? [] : elements;
_.each(fns, (fn) => {
fn = _.isString(fn) ? cfg[fn] : fn; // assume the function to be present on the page configuration obeject
if (_.isFunction(fn)) {
console.log((add ? 'adding' : 'removing') + ' event on documents...', ev, elements);
_.each(elements, (el) => listenerFn.call(el, ev, (e) => fn.call(cfg, e))); // bind to the original configuration object
}
});
})
}
}
|
[
"function",
"setListeners",
"(",
"doc",
",",
"cfg",
"=",
"{",
"}",
",",
"add",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"doc",
"||",
"!",
"(",
"doc",
"instanceof",
"Document",
")",
")",
"{",
"return",
";",
"}",
"let",
"listenerFn",
"=",
"doc",
".",
"addEventListener",
";",
"if",
"(",
"!",
"add",
")",
"{",
"listenerFn",
"=",
"doc",
".",
"removeEventListener",
";",
"}",
"if",
"(",
"_",
".",
"isObject",
"(",
"cfg",
".",
"events",
")",
")",
"{",
"let",
"events",
"=",
"cfg",
".",
"events",
";",
"_",
".",
"each",
"(",
"events",
",",
"(",
"fns",
",",
"e",
")",
"=>",
"{",
"let",
"[",
"ev",
",",
"selector",
"]",
"=",
"e",
".",
"split",
"(",
"' '",
")",
";",
"let",
"elements",
"=",
"null",
";",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"fns",
")",
")",
"{",
"// support list of event handlers",
"fns",
"=",
"[",
"fns",
"]",
";",
"}",
"if",
"(",
"selector",
")",
"{",
"selector",
"=",
"e",
".",
"substring",
"(",
"e",
".",
"indexOf",
"(",
"' '",
")",
"+",
"1",
")",
";",
"// everything after space",
"elements",
"=",
"_",
".",
"attempt",
"(",
"(",
")",
"=>",
"doc",
".",
"querySelectorAll",
"(",
"selector",
")",
")",
";",
"// catch any errors while document selection",
"}",
"else",
"{",
"elements",
"=",
"[",
"doc",
"]",
";",
"}",
"elements",
"=",
"_",
".",
"isError",
"(",
"elements",
")",
"?",
"[",
"]",
":",
"elements",
";",
"_",
".",
"each",
"(",
"fns",
",",
"(",
"fn",
")",
"=>",
"{",
"fn",
"=",
"_",
".",
"isString",
"(",
"fn",
")",
"?",
"cfg",
"[",
"fn",
"]",
":",
"fn",
";",
"// assume the function to be present on the page configuration obeject",
"if",
"(",
"_",
".",
"isFunction",
"(",
"fn",
")",
")",
"{",
"console",
".",
"log",
"(",
"(",
"add",
"?",
"'adding'",
":",
"'removing'",
")",
"+",
"' event on documents...'",
",",
"ev",
",",
"elements",
")",
";",
"_",
".",
"each",
"(",
"elements",
",",
"(",
"el",
")",
"=>",
"listenerFn",
".",
"call",
"(",
"el",
",",
"ev",
",",
"(",
"e",
")",
"=>",
"fn",
".",
"call",
"(",
"cfg",
",",
"e",
")",
")",
")",
";",
"// bind to the original configuration object",
"}",
"}",
")",
";",
"}",
")",
"}",
"}"
] |
Iterates over the events configuration and add event listeners to the document.
@example
{
events: {
'scroll': function(e) { // do the magic here },
'select listItemLockup title': 'onTitleSelect',
'someOtherEvent': ['onTitleSelect', function(e) { // some other magic }, ...]
},
onTitleSelect: function(e) {
// do the magic here
}
}
@todo Implement querySelectorAll polyfill (it doesn't seem to exist on the xml document)
@private
@param {Document} doc The document to add the listeners on.
@param {Object} cfg The page object configuration.
@param {Boolean} [add=true] Whether to add or remove listeners. Defaults to true (add)
|
[
"Iterates",
"over",
"the",
"events",
"configuration",
"and",
"add",
"event",
"listeners",
"to",
"the",
"document",
"."
] |
e42a538805e610fce99b48d32f4e5b81f09ae4c4
|
https://github.com/emadalam/atvjs/blob/e42a538805e610fce99b48d32f4e5b81f09ae4c4/src/handler.js#L166-L200
|
16,340
|
archfirst/joinjs
|
src/index.js
|
map
|
function map(resultSet, maps, mapId, columnPrefix) {
let mappedCollection = [];
resultSet.forEach(result => {
injectResultInCollection(result, mappedCollection, maps, mapId, columnPrefix);
});
return mappedCollection;
}
|
javascript
|
function map(resultSet, maps, mapId, columnPrefix) {
let mappedCollection = [];
resultSet.forEach(result => {
injectResultInCollection(result, mappedCollection, maps, mapId, columnPrefix);
});
return mappedCollection;
}
|
[
"function",
"map",
"(",
"resultSet",
",",
"maps",
",",
"mapId",
",",
"columnPrefix",
")",
"{",
"let",
"mappedCollection",
"=",
"[",
"]",
";",
"resultSet",
".",
"forEach",
"(",
"result",
"=>",
"{",
"injectResultInCollection",
"(",
"result",
",",
"mappedCollection",
",",
"maps",
",",
"mapId",
",",
"columnPrefix",
")",
";",
"}",
")",
";",
"return",
"mappedCollection",
";",
"}"
] |
Maps a resultSet to an array of objects.
@param {Array} resultSet - an array of database results
@param {Array} maps - an array of result maps
@param {String} mapId - mapId of the top-level objects in the resultSet
@param {String} [columnPrefix] - prefix that should be applied to the column names of the top-level objects
@returns {Array} array of mapped objects
|
[
"Maps",
"a",
"resultSet",
"to",
"an",
"array",
"of",
"objects",
"."
] |
3f55faa1178121436c8a51889b291cfef604a87f
|
https://github.com/archfirst/joinjs/blob/3f55faa1178121436c8a51889b291cfef604a87f/src/index.js#L20-L29
|
16,341
|
archfirst/joinjs
|
src/index.js
|
mapOne
|
function mapOne(resultSet, maps, mapId, columnPrefix, isRequired = true) {
var mappedCollection = map(resultSet, maps, mapId, columnPrefix);
if (mappedCollection.length > 0) {
return mappedCollection[0];
}
else if (isRequired) {
throw new NotFoundError('EmptyResponse');
}
else {
return null;
}
}
|
javascript
|
function mapOne(resultSet, maps, mapId, columnPrefix, isRequired = true) {
var mappedCollection = map(resultSet, maps, mapId, columnPrefix);
if (mappedCollection.length > 0) {
return mappedCollection[0];
}
else if (isRequired) {
throw new NotFoundError('EmptyResponse');
}
else {
return null;
}
}
|
[
"function",
"mapOne",
"(",
"resultSet",
",",
"maps",
",",
"mapId",
",",
"columnPrefix",
",",
"isRequired",
"=",
"true",
")",
"{",
"var",
"mappedCollection",
"=",
"map",
"(",
"resultSet",
",",
"maps",
",",
"mapId",
",",
"columnPrefix",
")",
";",
"if",
"(",
"mappedCollection",
".",
"length",
">",
"0",
")",
"{",
"return",
"mappedCollection",
"[",
"0",
"]",
";",
"}",
"else",
"if",
"(",
"isRequired",
")",
"{",
"throw",
"new",
"NotFoundError",
"(",
"'EmptyResponse'",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] |
Maps a resultSet to a single object.
Although the result is a single object, resultSet may have multiple results (e.g. when the
top-level object has many children in a one-to-many relationship). So mapOne() must still
call map(), only difference is that it will return only the first result.
@param {Array} resultSet - an array of database results
@param {Array} maps - an array of result maps
@param {String} mapId - mapId of the top-level object in the resultSet
@param {String} [columnPrefix] - prefix that should be applied to the column names of the top-level object
@param {boolean} [isRequired] - is it required to have a mapped object as a return value? Default is true.
@returns {Object} one mapped object or null
@throws {NotFoundError} if object is not found and isRequired is true
|
[
"Maps",
"a",
"resultSet",
"to",
"a",
"single",
"object",
"."
] |
3f55faa1178121436c8a51889b291cfef604a87f
|
https://github.com/archfirst/joinjs/blob/3f55faa1178121436c8a51889b291cfef604a87f/src/index.js#L46-L59
|
16,342
|
archfirst/joinjs
|
src/index.js
|
injectResultInCollection
|
function injectResultInCollection(result, mappedCollection, maps, mapId, columnPrefix = '') {
// Check if the object is already in mappedCollection
let resultMap = maps.find(map => map.mapId === mapId);
let idProperty = getIdProperty(resultMap);
let predicate = idProperty.reduce((accumulator, field) => {
accumulator[field.name] = result[columnPrefix + field.column];
return accumulator;
}, {});
let mappedObject = mappedCollection.find(item => {
for (let k in predicate) {
if (item[k] !== predicate[k]) {
return false;
}
}
return true;
});
// Inject only if the value of idProperty is not null (ignore joins to null records)
let isIdPropertyNotNull = idProperty.every(field => result[columnPrefix + field.column] !== null);
if (isIdPropertyNotNull) {
// Create mappedObject if it does not exist in mappedCollection
if (!mappedObject) {
mappedObject = createMappedObject(resultMap);
mappedCollection.push(mappedObject);
}
// Inject result in object
injectResultInObject(result, mappedObject, maps, mapId, columnPrefix);
}
}
|
javascript
|
function injectResultInCollection(result, mappedCollection, maps, mapId, columnPrefix = '') {
// Check if the object is already in mappedCollection
let resultMap = maps.find(map => map.mapId === mapId);
let idProperty = getIdProperty(resultMap);
let predicate = idProperty.reduce((accumulator, field) => {
accumulator[field.name] = result[columnPrefix + field.column];
return accumulator;
}, {});
let mappedObject = mappedCollection.find(item => {
for (let k in predicate) {
if (item[k] !== predicate[k]) {
return false;
}
}
return true;
});
// Inject only if the value of idProperty is not null (ignore joins to null records)
let isIdPropertyNotNull = idProperty.every(field => result[columnPrefix + field.column] !== null);
if (isIdPropertyNotNull) {
// Create mappedObject if it does not exist in mappedCollection
if (!mappedObject) {
mappedObject = createMappedObject(resultMap);
mappedCollection.push(mappedObject);
}
// Inject result in object
injectResultInObject(result, mappedObject, maps, mapId, columnPrefix);
}
}
|
[
"function",
"injectResultInCollection",
"(",
"result",
",",
"mappedCollection",
",",
"maps",
",",
"mapId",
",",
"columnPrefix",
"=",
"''",
")",
"{",
"// Check if the object is already in mappedCollection",
"let",
"resultMap",
"=",
"maps",
".",
"find",
"(",
"map",
"=>",
"map",
".",
"mapId",
"===",
"mapId",
")",
";",
"let",
"idProperty",
"=",
"getIdProperty",
"(",
"resultMap",
")",
";",
"let",
"predicate",
"=",
"idProperty",
".",
"reduce",
"(",
"(",
"accumulator",
",",
"field",
")",
"=>",
"{",
"accumulator",
"[",
"field",
".",
"name",
"]",
"=",
"result",
"[",
"columnPrefix",
"+",
"field",
".",
"column",
"]",
";",
"return",
"accumulator",
";",
"}",
",",
"{",
"}",
")",
";",
"let",
"mappedObject",
"=",
"mappedCollection",
".",
"find",
"(",
"item",
"=>",
"{",
"for",
"(",
"let",
"k",
"in",
"predicate",
")",
"{",
"if",
"(",
"item",
"[",
"k",
"]",
"!==",
"predicate",
"[",
"k",
"]",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}",
")",
";",
"// Inject only if the value of idProperty is not null (ignore joins to null records)",
"let",
"isIdPropertyNotNull",
"=",
"idProperty",
".",
"every",
"(",
"field",
"=>",
"result",
"[",
"columnPrefix",
"+",
"field",
".",
"column",
"]",
"!==",
"null",
")",
";",
"if",
"(",
"isIdPropertyNotNull",
")",
"{",
"// Create mappedObject if it does not exist in mappedCollection",
"if",
"(",
"!",
"mappedObject",
")",
"{",
"mappedObject",
"=",
"createMappedObject",
"(",
"resultMap",
")",
";",
"mappedCollection",
".",
"push",
"(",
"mappedObject",
")",
";",
"}",
"// Inject result in object",
"injectResultInObject",
"(",
"result",
",",
"mappedObject",
",",
"maps",
",",
"mapId",
",",
"columnPrefix",
")",
";",
"}",
"}"
] |
Maps a single database result to a single object using mapId and injects it into mappedCollection.
@param {Object} result - a single database result (one row)
@param {Array} mappedCollection - the collection in which the mapped object should be injected.
@param {Array} maps - an array of result maps
@param {String} mapId - mapId of the top-level objects in the resultSet
@param {String} [columnPrefix] - prefix that should be applied to the column names of the top-level objects
|
[
"Maps",
"a",
"single",
"database",
"result",
"to",
"a",
"single",
"object",
"using",
"mapId",
"and",
"injects",
"it",
"into",
"mappedCollection",
"."
] |
3f55faa1178121436c8a51889b291cfef604a87f
|
https://github.com/archfirst/joinjs/blob/3f55faa1178121436c8a51889b291cfef604a87f/src/index.js#L70-L102
|
16,343
|
archfirst/joinjs
|
src/index.js
|
injectResultInObject
|
function injectResultInObject(result, mappedObject, maps, mapId, columnPrefix = '') {
// Get the resultMap for this object
let resultMap = maps.find(map => map.mapId === mapId);
// Copy id property
let idProperty = getIdProperty(resultMap);
idProperty.forEach(field => {
if (!mappedObject[field.name]) {
mappedObject[field.name] = result[columnPrefix + field.column];
}
});
const {properties, associations, collections} = resultMap;
// Copy other properties
properties && properties.forEach(property => {
// If property is a string, convert it to an object
if (typeof property === 'string') {
// eslint-disable-next-line
property = {name: property, column: property};
}
// Copy only if property does not exist already
if (!mappedObject[property.name]) {
// The default for column name is property name
let column = (property.column) ? property.column : property.name;
mappedObject[property.name] = result[columnPrefix + column];
}
});
// Copy associations
associations && associations.forEach(association => {
let associatedObject = mappedObject[association.name];
if (!associatedObject) {
let associatedResultMap = maps.find(map => map.mapId === association.mapId);
let associatedObjectIdProperty = getIdProperty(associatedResultMap);
mappedObject[association.name] = null;
// Don't create associated object if it's key value is null
let isAssociatedObjectIdPropertyNotNull = associatedObjectIdProperty.every(field =>
result[association.columnPrefix + field.column] !== null
);
if (isAssociatedObjectIdPropertyNotNull) {
associatedObject = createMappedObject(associatedResultMap);
mappedObject[association.name] = associatedObject;
}
}
if (associatedObject) {
injectResultInObject(result, associatedObject, maps, association.mapId, association.columnPrefix);
}
});
// Copy collections
collections && collections.forEach(collection => {
let mappedCollection = mappedObject[collection.name];
if (!mappedCollection) {
mappedCollection = [];
mappedObject[collection.name] = mappedCollection;
}
injectResultInCollection(result, mappedCollection, maps, collection.mapId, collection.columnPrefix);
});
}
|
javascript
|
function injectResultInObject(result, mappedObject, maps, mapId, columnPrefix = '') {
// Get the resultMap for this object
let resultMap = maps.find(map => map.mapId === mapId);
// Copy id property
let idProperty = getIdProperty(resultMap);
idProperty.forEach(field => {
if (!mappedObject[field.name]) {
mappedObject[field.name] = result[columnPrefix + field.column];
}
});
const {properties, associations, collections} = resultMap;
// Copy other properties
properties && properties.forEach(property => {
// If property is a string, convert it to an object
if (typeof property === 'string') {
// eslint-disable-next-line
property = {name: property, column: property};
}
// Copy only if property does not exist already
if (!mappedObject[property.name]) {
// The default for column name is property name
let column = (property.column) ? property.column : property.name;
mappedObject[property.name] = result[columnPrefix + column];
}
});
// Copy associations
associations && associations.forEach(association => {
let associatedObject = mappedObject[association.name];
if (!associatedObject) {
let associatedResultMap = maps.find(map => map.mapId === association.mapId);
let associatedObjectIdProperty = getIdProperty(associatedResultMap);
mappedObject[association.name] = null;
// Don't create associated object if it's key value is null
let isAssociatedObjectIdPropertyNotNull = associatedObjectIdProperty.every(field =>
result[association.columnPrefix + field.column] !== null
);
if (isAssociatedObjectIdPropertyNotNull) {
associatedObject = createMappedObject(associatedResultMap);
mappedObject[association.name] = associatedObject;
}
}
if (associatedObject) {
injectResultInObject(result, associatedObject, maps, association.mapId, association.columnPrefix);
}
});
// Copy collections
collections && collections.forEach(collection => {
let mappedCollection = mappedObject[collection.name];
if (!mappedCollection) {
mappedCollection = [];
mappedObject[collection.name] = mappedCollection;
}
injectResultInCollection(result, mappedCollection, maps, collection.mapId, collection.columnPrefix);
});
}
|
[
"function",
"injectResultInObject",
"(",
"result",
",",
"mappedObject",
",",
"maps",
",",
"mapId",
",",
"columnPrefix",
"=",
"''",
")",
"{",
"// Get the resultMap for this object",
"let",
"resultMap",
"=",
"maps",
".",
"find",
"(",
"map",
"=>",
"map",
".",
"mapId",
"===",
"mapId",
")",
";",
"// Copy id property",
"let",
"idProperty",
"=",
"getIdProperty",
"(",
"resultMap",
")",
";",
"idProperty",
".",
"forEach",
"(",
"field",
"=>",
"{",
"if",
"(",
"!",
"mappedObject",
"[",
"field",
".",
"name",
"]",
")",
"{",
"mappedObject",
"[",
"field",
".",
"name",
"]",
"=",
"result",
"[",
"columnPrefix",
"+",
"field",
".",
"column",
"]",
";",
"}",
"}",
")",
";",
"const",
"{",
"properties",
",",
"associations",
",",
"collections",
"}",
"=",
"resultMap",
";",
"// Copy other properties",
"properties",
"&&",
"properties",
".",
"forEach",
"(",
"property",
"=>",
"{",
"// If property is a string, convert it to an object",
"if",
"(",
"typeof",
"property",
"===",
"'string'",
")",
"{",
"// eslint-disable-next-line",
"property",
"=",
"{",
"name",
":",
"property",
",",
"column",
":",
"property",
"}",
";",
"}",
"// Copy only if property does not exist already",
"if",
"(",
"!",
"mappedObject",
"[",
"property",
".",
"name",
"]",
")",
"{",
"// The default for column name is property name",
"let",
"column",
"=",
"(",
"property",
".",
"column",
")",
"?",
"property",
".",
"column",
":",
"property",
".",
"name",
";",
"mappedObject",
"[",
"property",
".",
"name",
"]",
"=",
"result",
"[",
"columnPrefix",
"+",
"column",
"]",
";",
"}",
"}",
")",
";",
"// Copy associations",
"associations",
"&&",
"associations",
".",
"forEach",
"(",
"association",
"=>",
"{",
"let",
"associatedObject",
"=",
"mappedObject",
"[",
"association",
".",
"name",
"]",
";",
"if",
"(",
"!",
"associatedObject",
")",
"{",
"let",
"associatedResultMap",
"=",
"maps",
".",
"find",
"(",
"map",
"=>",
"map",
".",
"mapId",
"===",
"association",
".",
"mapId",
")",
";",
"let",
"associatedObjectIdProperty",
"=",
"getIdProperty",
"(",
"associatedResultMap",
")",
";",
"mappedObject",
"[",
"association",
".",
"name",
"]",
"=",
"null",
";",
"// Don't create associated object if it's key value is null",
"let",
"isAssociatedObjectIdPropertyNotNull",
"=",
"associatedObjectIdProperty",
".",
"every",
"(",
"field",
"=>",
"result",
"[",
"association",
".",
"columnPrefix",
"+",
"field",
".",
"column",
"]",
"!==",
"null",
")",
";",
"if",
"(",
"isAssociatedObjectIdPropertyNotNull",
")",
"{",
"associatedObject",
"=",
"createMappedObject",
"(",
"associatedResultMap",
")",
";",
"mappedObject",
"[",
"association",
".",
"name",
"]",
"=",
"associatedObject",
";",
"}",
"}",
"if",
"(",
"associatedObject",
")",
"{",
"injectResultInObject",
"(",
"result",
",",
"associatedObject",
",",
"maps",
",",
"association",
".",
"mapId",
",",
"association",
".",
"columnPrefix",
")",
";",
"}",
"}",
")",
";",
"// Copy collections",
"collections",
"&&",
"collections",
".",
"forEach",
"(",
"collection",
"=>",
"{",
"let",
"mappedCollection",
"=",
"mappedObject",
"[",
"collection",
".",
"name",
"]",
";",
"if",
"(",
"!",
"mappedCollection",
")",
"{",
"mappedCollection",
"=",
"[",
"]",
";",
"mappedObject",
"[",
"collection",
".",
"name",
"]",
"=",
"mappedCollection",
";",
"}",
"injectResultInCollection",
"(",
"result",
",",
"mappedCollection",
",",
"maps",
",",
"collection",
".",
"mapId",
",",
"collection",
".",
"columnPrefix",
")",
";",
"}",
")",
";",
"}"
] |
Injects id, properties, associations and collections to the supplied mapped object.
@param {Object} result - a single database result (one row)
@param {Object} mappedObject - the object in which result needs to be injected
@param {Array} maps - an array of result maps
@param {String} mapId - mapId of the top-level objects in the resultSet
@param {String} [columnPrefix] - prefix that should be applied to the column names of the top-level objects
|
[
"Injects",
"id",
"properties",
"associations",
"and",
"collections",
"to",
"the",
"supplied",
"mapped",
"object",
"."
] |
3f55faa1178121436c8a51889b291cfef604a87f
|
https://github.com/archfirst/joinjs/blob/3f55faa1178121436c8a51889b291cfef604a87f/src/index.js#L113-L186
|
16,344
|
mikedeboer/jsDAV
|
lib/CalDAV/calendarQueryValidator.js
|
function (vObject, filter) {
/**
* Definition:
* <!ELEMENT filter (comp-filter)>
*/
if (filter) {
if (vObject.name == filter.name) {
return this._validateFilterSet(vObject, filter["comp-filters"], this._validateCompFilter) &&
this._validateFilterSet(vObject, filter["prop-filters"], this._validatePropFilter);
}
else
return false;
}
else
return true;
}
|
javascript
|
function (vObject, filter) {
/**
* Definition:
* <!ELEMENT filter (comp-filter)>
*/
if (filter) {
if (vObject.name == filter.name) {
return this._validateFilterSet(vObject, filter["comp-filters"], this._validateCompFilter) &&
this._validateFilterSet(vObject, filter["prop-filters"], this._validatePropFilter);
}
else
return false;
}
else
return true;
}
|
[
"function",
"(",
"vObject",
",",
"filter",
")",
"{",
"/**\n * Definition:\n * <!ELEMENT filter (comp-filter)>\n */",
"if",
"(",
"filter",
")",
"{",
"if",
"(",
"vObject",
".",
"name",
"==",
"filter",
".",
"name",
")",
"{",
"return",
"this",
".",
"_validateFilterSet",
"(",
"vObject",
",",
"filter",
"[",
"\"comp-filters\"",
"]",
",",
"this",
".",
"_validateCompFilter",
")",
"&&",
"this",
".",
"_validateFilterSet",
"(",
"vObject",
",",
"filter",
"[",
"\"prop-filters\"",
"]",
",",
"this",
".",
"_validatePropFilter",
")",
";",
"}",
"else",
"return",
"false",
";",
"}",
"else",
"return",
"true",
";",
"}"
] |
Verify if a list of filters applies to the calendar data object
The list of filters must be formatted as parsed by \Sabre\CalDAV\CalendarQueryParser
@param {jsVObject_Component} vObject
@param {Array} filter
@return bool
|
[
"Verify",
"if",
"a",
"list",
"of",
"filters",
"applies",
"to",
"the",
"calendar",
"data",
"object"
] |
1fe585dff008184d3ea03332c50b4fcceadf8b76
|
https://github.com/mikedeboer/jsDAV/blob/1fe585dff008184d3ea03332c50b4fcceadf8b76/lib/CalDAV/calendarQueryValidator.js#L55-L72
|
|
16,345
|
mikedeboer/jsDAV
|
lib/CalDAV/calendarQueryValidator.js
|
function (component, textMatch) {
if (component.hasFeature && component.hasFeature(jsVObject_Node))
component = component.getValue();
var isMatching = Util.textMatch(component, textMatch.value, textMatch["match-type"]);
return (textMatch["negate-condition"] ^ isMatching);
}
|
javascript
|
function (component, textMatch) {
if (component.hasFeature && component.hasFeature(jsVObject_Node))
component = component.getValue();
var isMatching = Util.textMatch(component, textMatch.value, textMatch["match-type"]);
return (textMatch["negate-condition"] ^ isMatching);
}
|
[
"function",
"(",
"component",
",",
"textMatch",
")",
"{",
"if",
"(",
"component",
".",
"hasFeature",
"&&",
"component",
".",
"hasFeature",
"(",
"jsVObject_Node",
")",
")",
"component",
"=",
"component",
".",
"getValue",
"(",
")",
";",
"var",
"isMatching",
"=",
"Util",
".",
"textMatch",
"(",
"component",
",",
"textMatch",
".",
"value",
",",
"textMatch",
"[",
"\"match-type\"",
"]",
")",
";",
"return",
"(",
"textMatch",
"[",
"\"negate-condition\"",
"]",
"^",
"isMatching",
")",
";",
"}"
] |
This method checks the validity of a text-match.
A single text-match should be specified as well as the specific property
or parameter we need to validate.
@param {jsVObject_Node|String} component Value to check against.
@param {Object} textMatch
@return bool
|
[
"This",
"method",
"checks",
"the",
"validity",
"of",
"a",
"text",
"-",
"match",
"."
] |
1fe585dff008184d3ea03332c50b4fcceadf8b76
|
https://github.com/mikedeboer/jsDAV/blob/1fe585dff008184d3ea03332c50b4fcceadf8b76/lib/CalDAV/calendarQueryValidator.js#L169-L175
|
|
16,346
|
mikedeboer/jsDAV
|
lib/CalDAV/calendarQueryValidator.js
|
function (component, filter) {
if (!filter)
return true;
var start = filter.start, end = filter.end;
if (!start)
start = new Date(1900, 1, 1);
if (!end)
end = new Date(3000, 1, 1);
switch (component.name) {
case "VEVENT" :
case "VTODO" :
case "VJOURNAL" :
return component.isInTimeRange(start, end);
case "VALARM" :
/*
// If the valarm is wrapped in a recurring event, we need to
// expand the recursions, and validate each.
//
// Our datamodel doesn't easily allow us to do this straight
// in the VALARM component code, so this is a hack, and an
// expensive one too.
if (component.parent.name === 'VEVENT' && component.parent.RRULE) {
// Fire up the iterator!
it = new VObject\RecurrenceIterator(component.parent.parent, (string)
component.parent.UID
)
;
while (it.valid()) {
expandedEvent = it.getEventObject();
// We need to check from these expanded alarms, which
// one is the first to trigger. Based on this, we can
// determine if we can 'give up' expanding events.
firstAlarm = null;
if (expandedEvent.VALARM !== null) {
foreach(expandedEvent.VALARM
as
expandedAlarm
)
{
effectiveTrigger = expandedAlarm.getEffectiveTriggerTime();
if (expandedAlarm.isInTimeRange(start, end)) {
return true;
}
if ((string)expandedAlarm.TRIGGER['VALUE'] === 'DATE-TIME'
)
{
// This is an alarm with a non-relative trigger
// time, likely created by a buggy client. The
// implication is that every alarm in this
// recurring event trigger at the exact same
// time. It doesn't make sense to traverse
// further.
}
else
{
// We store the first alarm as a means to
// figure out when we can stop traversing.
if (!firstAlarm || effectiveTrigger < firstAlarm) {
firstAlarm = effectiveTrigger;
}
}
}
}
if (is_null(firstAlarm)) {
// No alarm was found.
//
// Or technically: No alarm that will change for
// every instance of the recurrence was found,
// which means we can assume there was no match.
return false;
}
if (firstAlarm > end) {
return false;
}
it.next();
}
return false;
} else {
return component.isInTimeRange(start, end);
}
*/
case "VFREEBUSY" :
throw new Exc.NotImplemented("time-range filters are currently not supported on " + component.name + " components");
case "COMPLETED" :
case "CREATED" :
case "DTEND" :
case "DTSTAMP" :
case "DTSTART" :
case "DUE" :
case "LAST-MODIFIED" :
return (start <= component.getDateTime() && end >= component.getDateTime());
default :
// throw new Exc.BadRequest("You cannot create a time-range filter on a " + component.name + " component");
return false;
}
}
|
javascript
|
function (component, filter) {
if (!filter)
return true;
var start = filter.start, end = filter.end;
if (!start)
start = new Date(1900, 1, 1);
if (!end)
end = new Date(3000, 1, 1);
switch (component.name) {
case "VEVENT" :
case "VTODO" :
case "VJOURNAL" :
return component.isInTimeRange(start, end);
case "VALARM" :
/*
// If the valarm is wrapped in a recurring event, we need to
// expand the recursions, and validate each.
//
// Our datamodel doesn't easily allow us to do this straight
// in the VALARM component code, so this is a hack, and an
// expensive one too.
if (component.parent.name === 'VEVENT' && component.parent.RRULE) {
// Fire up the iterator!
it = new VObject\RecurrenceIterator(component.parent.parent, (string)
component.parent.UID
)
;
while (it.valid()) {
expandedEvent = it.getEventObject();
// We need to check from these expanded alarms, which
// one is the first to trigger. Based on this, we can
// determine if we can 'give up' expanding events.
firstAlarm = null;
if (expandedEvent.VALARM !== null) {
foreach(expandedEvent.VALARM
as
expandedAlarm
)
{
effectiveTrigger = expandedAlarm.getEffectiveTriggerTime();
if (expandedAlarm.isInTimeRange(start, end)) {
return true;
}
if ((string)expandedAlarm.TRIGGER['VALUE'] === 'DATE-TIME'
)
{
// This is an alarm with a non-relative trigger
// time, likely created by a buggy client. The
// implication is that every alarm in this
// recurring event trigger at the exact same
// time. It doesn't make sense to traverse
// further.
}
else
{
// We store the first alarm as a means to
// figure out when we can stop traversing.
if (!firstAlarm || effectiveTrigger < firstAlarm) {
firstAlarm = effectiveTrigger;
}
}
}
}
if (is_null(firstAlarm)) {
// No alarm was found.
//
// Or technically: No alarm that will change for
// every instance of the recurrence was found,
// which means we can assume there was no match.
return false;
}
if (firstAlarm > end) {
return false;
}
it.next();
}
return false;
} else {
return component.isInTimeRange(start, end);
}
*/
case "VFREEBUSY" :
throw new Exc.NotImplemented("time-range filters are currently not supported on " + component.name + " components");
case "COMPLETED" :
case "CREATED" :
case "DTEND" :
case "DTSTAMP" :
case "DTSTART" :
case "DUE" :
case "LAST-MODIFIED" :
return (start <= component.getDateTime() && end >= component.getDateTime());
default :
// throw new Exc.BadRequest("You cannot create a time-range filter on a " + component.name + " component");
return false;
}
}
|
[
"function",
"(",
"component",
",",
"filter",
")",
"{",
"if",
"(",
"!",
"filter",
")",
"return",
"true",
";",
"var",
"start",
"=",
"filter",
".",
"start",
",",
"end",
"=",
"filter",
".",
"end",
";",
"if",
"(",
"!",
"start",
")",
"start",
"=",
"new",
"Date",
"(",
"1900",
",",
"1",
",",
"1",
")",
";",
"if",
"(",
"!",
"end",
")",
"end",
"=",
"new",
"Date",
"(",
"3000",
",",
"1",
",",
"1",
")",
";",
"switch",
"(",
"component",
".",
"name",
")",
"{",
"case",
"\"VEVENT\"",
":",
"case",
"\"VTODO\"",
":",
"case",
"\"VJOURNAL\"",
":",
"return",
"component",
".",
"isInTimeRange",
"(",
"start",
",",
"end",
")",
";",
"case",
"\"VALARM\"",
":",
"/*\n // If the valarm is wrapped in a recurring event, we need to\n // expand the recursions, and validate each.\n //\n // Our datamodel doesn't easily allow us to do this straight\n // in the VALARM component code, so this is a hack, and an\n // expensive one too.\n if (component.parent.name === 'VEVENT' && component.parent.RRULE) {\n\n // Fire up the iterator!\n it = new VObject\\RecurrenceIterator(component.parent.parent, (string)\n component.parent.UID\n )\n ;\n while (it.valid()) {\n expandedEvent = it.getEventObject();\n\n // We need to check from these expanded alarms, which\n // one is the first to trigger. Based on this, we can\n // determine if we can 'give up' expanding events.\n firstAlarm = null;\n if (expandedEvent.VALARM !== null) {\n foreach(expandedEvent.VALARM\n as\n expandedAlarm\n )\n {\n\n effectiveTrigger = expandedAlarm.getEffectiveTriggerTime();\n if (expandedAlarm.isInTimeRange(start, end)) {\n return true;\n }\n\n if ((string)expandedAlarm.TRIGGER['VALUE'] === 'DATE-TIME'\n )\n {\n // This is an alarm with a non-relative trigger\n // time, likely created by a buggy client. The\n // implication is that every alarm in this\n // recurring event trigger at the exact same\n // time. It doesn't make sense to traverse\n // further.\n }\n else\n {\n // We store the first alarm as a means to\n // figure out when we can stop traversing.\n if (!firstAlarm || effectiveTrigger < firstAlarm) {\n firstAlarm = effectiveTrigger;\n }\n }\n }\n }\n if (is_null(firstAlarm)) {\n // No alarm was found.\n //\n // Or technically: No alarm that will change for\n // every instance of the recurrence was found,\n // which means we can assume there was no match.\n return false;\n }\n if (firstAlarm > end) {\n return false;\n }\n it.next();\n }\n return false;\n } else {\n return component.isInTimeRange(start, end);\n }\n */",
"case",
"\"VFREEBUSY\"",
":",
"throw",
"new",
"Exc",
".",
"NotImplemented",
"(",
"\"time-range filters are currently not supported on \"",
"+",
"component",
".",
"name",
"+",
"\" components\"",
")",
";",
"case",
"\"COMPLETED\"",
":",
"case",
"\"CREATED\"",
":",
"case",
"\"DTEND\"",
":",
"case",
"\"DTSTAMP\"",
":",
"case",
"\"DTSTART\"",
":",
"case",
"\"DUE\"",
":",
"case",
"\"LAST-MODIFIED\"",
":",
"return",
"(",
"start",
"<=",
"component",
".",
"getDateTime",
"(",
")",
"&&",
"end",
">=",
"component",
".",
"getDateTime",
"(",
")",
")",
";",
"default",
":",
"// throw new Exc.BadRequest(\"You cannot create a time-range filter on a \" + component.name + \" component\");",
"return",
"false",
";",
"}",
"}"
] |
Validates if a component matches the given time range.
This is all based on the rules specified in rfc4791, which are quite
complex.
@param {jsVObject_Node} component
@param {Object} [filter]
@param {Date} [filter.start]
@param {Date} [filter.end]
@return bool
|
[
"Validates",
"if",
"a",
"component",
"matches",
"the",
"given",
"time",
"range",
"."
] |
1fe585dff008184d3ea03332c50b4fcceadf8b76
|
https://github.com/mikedeboer/jsDAV/blob/1fe585dff008184d3ea03332c50b4fcceadf8b76/lib/CalDAV/calendarQueryValidator.js#L189-L291
|
|
16,347
|
mikedeboer/jsDAV
|
lib/DAV/backends/fsext/directory.js
|
function(name, data, enc, cbfscreatefile) {
jsDAV_FS_Directory.createFile.call(this, name, data, enc,
afterCreateFile.bind(this, name, cbfscreatefile));
}
|
javascript
|
function(name, data, enc, cbfscreatefile) {
jsDAV_FS_Directory.createFile.call(this, name, data, enc,
afterCreateFile.bind(this, name, cbfscreatefile));
}
|
[
"function",
"(",
"name",
",",
"data",
",",
"enc",
",",
"cbfscreatefile",
")",
"{",
"jsDAV_FS_Directory",
".",
"createFile",
".",
"call",
"(",
"this",
",",
"name",
",",
"data",
",",
"enc",
",",
"afterCreateFile",
".",
"bind",
"(",
"this",
",",
"name",
",",
"cbfscreatefile",
")",
")",
";",
"}"
] |
Creates a new file in the directory
data is a Buffer resource
@param {String} name Name of the file
@param {Buffer} data Initial payload
@param {String} [enc]
@param {Function} cbfscreatefile
@return void
|
[
"Creates",
"a",
"new",
"file",
"in",
"the",
"directory"
] |
1fe585dff008184d3ea03332c50b4fcceadf8b76
|
https://github.com/mikedeboer/jsDAV/blob/1fe585dff008184d3ea03332c50b4fcceadf8b76/lib/DAV/backends/fsext/directory.js#L44-L47
|
|
16,348
|
mikedeboer/jsDAV
|
lib/DAV/backends/fsext/directory.js
|
function(handler, name, enc, cbfscreatefile) {
jsDAV_FS_Directory.createFileStream.call(this, handler, name, enc,
afterCreateFile.bind(this, name, cbfscreatefile));
}
|
javascript
|
function(handler, name, enc, cbfscreatefile) {
jsDAV_FS_Directory.createFileStream.call(this, handler, name, enc,
afterCreateFile.bind(this, name, cbfscreatefile));
}
|
[
"function",
"(",
"handler",
",",
"name",
",",
"enc",
",",
"cbfscreatefile",
")",
"{",
"jsDAV_FS_Directory",
".",
"createFileStream",
".",
"call",
"(",
"this",
",",
"handler",
",",
"name",
",",
"enc",
",",
"afterCreateFile",
".",
"bind",
"(",
"this",
",",
"name",
",",
"cbfscreatefile",
")",
")",
";",
"}"
] |
Creates a new file in the directory whilst writing to a stream instead of
from Buffer objects that reside in memory.
@param {jsDAV_Handler} handler
@param {String} name Name of the file
@param {String} [enc]
@param {Function} cbfscreatefile
@return void
|
[
"Creates",
"a",
"new",
"file",
"in",
"the",
"directory",
"whilst",
"writing",
"to",
"a",
"stream",
"instead",
"of",
"from",
"Buffer",
"objects",
"that",
"reside",
"in",
"memory",
"."
] |
1fe585dff008184d3ea03332c50b4fcceadf8b76
|
https://github.com/mikedeboer/jsDAV/blob/1fe585dff008184d3ea03332c50b4fcceadf8b76/lib/DAV/backends/fsext/directory.js#L60-L63
|
|
16,349
|
mikedeboer/jsDAV
|
lib/DAV/backends/fsext/directory.js
|
function(name, cbfsgetchild) {
var path = Path.join(this.path, name);
Fs.stat(path, function(err, stat) {
if (err || typeof stat == "undefined") {
return cbfsgetchild(new Exc.FileNotFound("File with name "
+ path + " could not be located"));
}
cbfsgetchild(null, stat.isDirectory()
? jsDAV_FSExt_Directory.new(path)
: jsDAV_FSExt_File.new(path))
});
}
|
javascript
|
function(name, cbfsgetchild) {
var path = Path.join(this.path, name);
Fs.stat(path, function(err, stat) {
if (err || typeof stat == "undefined") {
return cbfsgetchild(new Exc.FileNotFound("File with name "
+ path + " could not be located"));
}
cbfsgetchild(null, stat.isDirectory()
? jsDAV_FSExt_Directory.new(path)
: jsDAV_FSExt_File.new(path))
});
}
|
[
"function",
"(",
"name",
",",
"cbfsgetchild",
")",
"{",
"var",
"path",
"=",
"Path",
".",
"join",
"(",
"this",
".",
"path",
",",
"name",
")",
";",
"Fs",
".",
"stat",
"(",
"path",
",",
"function",
"(",
"err",
",",
"stat",
")",
"{",
"if",
"(",
"err",
"||",
"typeof",
"stat",
"==",
"\"undefined\"",
")",
"{",
"return",
"cbfsgetchild",
"(",
"new",
"Exc",
".",
"FileNotFound",
"(",
"\"File with name \"",
"+",
"path",
"+",
"\" could not be located\"",
")",
")",
";",
"}",
"cbfsgetchild",
"(",
"null",
",",
"stat",
".",
"isDirectory",
"(",
")",
"?",
"jsDAV_FSExt_Directory",
".",
"new",
"(",
"path",
")",
":",
"jsDAV_FSExt_File",
".",
"new",
"(",
"path",
")",
")",
"}",
")",
";",
"}"
] |
Returns a specific child node, referenced by its name
@param {String} name
@throws Sabre_DAV_Exception_FileNotFound
@return Sabre_DAV_INode
|
[
"Returns",
"a",
"specific",
"child",
"node",
"referenced",
"by",
"its",
"name"
] |
1fe585dff008184d3ea03332c50b4fcceadf8b76
|
https://github.com/mikedeboer/jsDAV/blob/1fe585dff008184d3ea03332c50b4fcceadf8b76/lib/DAV/backends/fsext/directory.js#L88-L100
|
|
16,350
|
mikedeboer/jsDAV
|
lib/DAV/backends/fsext/directory.js
|
function(cbfsgetchildren) {
var nodes = [];
Async.readdir(this.path)
.stat()
.filter(function(file) {
return file.indexOf(jsDAV_FSExt_File.PROPS_DIR) !== 0;
})
.each(function(file, cbnextdirch) {
nodes.push(file.stat.isDirectory()
? jsDAV_FSExt_Directory.new(file.path)
: jsDAV_FSExt_File.new(file.path)
);
cbnextdirch();
})
.end(function() {
cbfsgetchildren(null, nodes);
});
}
|
javascript
|
function(cbfsgetchildren) {
var nodes = [];
Async.readdir(this.path)
.stat()
.filter(function(file) {
return file.indexOf(jsDAV_FSExt_File.PROPS_DIR) !== 0;
})
.each(function(file, cbnextdirch) {
nodes.push(file.stat.isDirectory()
? jsDAV_FSExt_Directory.new(file.path)
: jsDAV_FSExt_File.new(file.path)
);
cbnextdirch();
})
.end(function() {
cbfsgetchildren(null, nodes);
});
}
|
[
"function",
"(",
"cbfsgetchildren",
")",
"{",
"var",
"nodes",
"=",
"[",
"]",
";",
"Async",
".",
"readdir",
"(",
"this",
".",
"path",
")",
".",
"stat",
"(",
")",
".",
"filter",
"(",
"function",
"(",
"file",
")",
"{",
"return",
"file",
".",
"indexOf",
"(",
"jsDAV_FSExt_File",
".",
"PROPS_DIR",
")",
"!==",
"0",
";",
"}",
")",
".",
"each",
"(",
"function",
"(",
"file",
",",
"cbnextdirch",
")",
"{",
"nodes",
".",
"push",
"(",
"file",
".",
"stat",
".",
"isDirectory",
"(",
")",
"?",
"jsDAV_FSExt_Directory",
".",
"new",
"(",
"file",
".",
"path",
")",
":",
"jsDAV_FSExt_File",
".",
"new",
"(",
"file",
".",
"path",
")",
")",
";",
"cbnextdirch",
"(",
")",
";",
"}",
")",
".",
"end",
"(",
"function",
"(",
")",
"{",
"cbfsgetchildren",
"(",
"null",
",",
"nodes",
")",
";",
"}",
")",
";",
"}"
] |
Returns an array with all the child nodes
@return jsDAV_iNode[]
|
[
"Returns",
"an",
"array",
"with",
"all",
"the",
"child",
"nodes"
] |
1fe585dff008184d3ea03332c50b4fcceadf8b76
|
https://github.com/mikedeboer/jsDAV/blob/1fe585dff008184d3ea03332c50b4fcceadf8b76/lib/DAV/backends/fsext/directory.js#L107-L124
|
|
16,351
|
mikedeboer/jsDAV
|
lib/DAV/backends/fsext/directory.js
|
function(cbfsdel) {
var self = this;
Async.rmtree(this.path, function(err) {
if (err)
return cbfsdel(err);
self.deleteResourceData(cbfsdel);
});
}
|
javascript
|
function(cbfsdel) {
var self = this;
Async.rmtree(this.path, function(err) {
if (err)
return cbfsdel(err);
self.deleteResourceData(cbfsdel);
});
}
|
[
"function",
"(",
"cbfsdel",
")",
"{",
"var",
"self",
"=",
"this",
";",
"Async",
".",
"rmtree",
"(",
"this",
".",
"path",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cbfsdel",
"(",
"err",
")",
";",
"self",
".",
"deleteResourceData",
"(",
"cbfsdel",
")",
";",
"}",
")",
";",
"}"
] |
Deletes all files in this directory, and then itself
@return void
|
[
"Deletes",
"all",
"files",
"in",
"this",
"directory",
"and",
"then",
"itself"
] |
1fe585dff008184d3ea03332c50b4fcceadf8b76
|
https://github.com/mikedeboer/jsDAV/blob/1fe585dff008184d3ea03332c50b4fcceadf8b76/lib/DAV/backends/fsext/directory.js#L131-L138
|
|
16,352
|
mikedeboer/jsDAV
|
lib/DAV/plugins/auth/abstractDigest.js
|
getDigest
|
function getDigest(req) {
// most other servers
var digest = req.headers["authorization"];
if (digest && digest.toLowerCase().indexOf("digest") === 0)
return digest.substr(7);
else
return null;
}
|
javascript
|
function getDigest(req) {
// most other servers
var digest = req.headers["authorization"];
if (digest && digest.toLowerCase().indexOf("digest") === 0)
return digest.substr(7);
else
return null;
}
|
[
"function",
"getDigest",
"(",
"req",
")",
"{",
"// most other servers",
"var",
"digest",
"=",
"req",
".",
"headers",
"[",
"\"authorization\"",
"]",
";",
"if",
"(",
"digest",
"&&",
"digest",
".",
"toLowerCase",
"(",
")",
".",
"indexOf",
"(",
"\"digest\"",
")",
"===",
"0",
")",
"return",
"digest",
".",
"substr",
"(",
"7",
")",
";",
"else",
"return",
"null",
";",
"}"
] |
This method returns the full digest string.
If the header could not be found, null will be returned
@return mixed
|
[
"This",
"method",
"returns",
"the",
"full",
"digest",
"string",
"."
] |
1fe585dff008184d3ea03332c50b4fcceadf8b76
|
https://github.com/mikedeboer/jsDAV/blob/1fe585dff008184d3ea03332c50b4fcceadf8b76/lib/DAV/plugins/auth/abstractDigest.js#L28-L35
|
16,353
|
mikedeboer/jsDAV
|
lib/DAV/plugins/auth/abstractDigest.js
|
parseDigest
|
function parseDigest(digest) {
if (!digest)
return false;
// protect against missing data
var needed_parts = {"nonce": 1, "nc": 1, "cnonce": 1, "qop": 1,
"username": 1, "uri": 1, "response": 1};
var data = {};
digest.replace(/(\w+)=(?:(?:")([^"]+)"|([^\s,]+))/g, function(m, m1, m2, m3) {
data[m1] = m2 ? m2 : m3;
delete needed_parts[m1];
return m;
});
return Object.keys(needed_parts).length ? false : data;
}
|
javascript
|
function parseDigest(digest) {
if (!digest)
return false;
// protect against missing data
var needed_parts = {"nonce": 1, "nc": 1, "cnonce": 1, "qop": 1,
"username": 1, "uri": 1, "response": 1};
var data = {};
digest.replace(/(\w+)=(?:(?:")([^"]+)"|([^\s,]+))/g, function(m, m1, m2, m3) {
data[m1] = m2 ? m2 : m3;
delete needed_parts[m1];
return m;
});
return Object.keys(needed_parts).length ? false : data;
}
|
[
"function",
"parseDigest",
"(",
"digest",
")",
"{",
"if",
"(",
"!",
"digest",
")",
"return",
"false",
";",
"// protect against missing data",
"var",
"needed_parts",
"=",
"{",
"\"nonce\"",
":",
"1",
",",
"\"nc\"",
":",
"1",
",",
"\"cnonce\"",
":",
"1",
",",
"\"qop\"",
":",
"1",
",",
"\"username\"",
":",
"1",
",",
"\"uri\"",
":",
"1",
",",
"\"response\"",
":",
"1",
"}",
";",
"var",
"data",
"=",
"{",
"}",
";",
"digest",
".",
"replace",
"(",
"/",
"(\\w+)=(?:(?:\")([^\"]+)\"|([^\\s,]+))",
"/",
"g",
",",
"function",
"(",
"m",
",",
"m1",
",",
"m2",
",",
"m3",
")",
"{",
"data",
"[",
"m1",
"]",
"=",
"m2",
"?",
"m2",
":",
"m3",
";",
"delete",
"needed_parts",
"[",
"m1",
"]",
";",
"return",
"m",
";",
"}",
")",
";",
"return",
"Object",
".",
"keys",
"(",
"needed_parts",
")",
".",
"length",
"?",
"false",
":",
"data",
";",
"}"
] |
Parses the different pieces of the digest string into an array.
This method returns false if an incomplete digest was supplied
@param {String} digest
@return mixed
|
[
"Parses",
"the",
"different",
"pieces",
"of",
"the",
"digest",
"string",
"into",
"an",
"array",
"."
] |
1fe585dff008184d3ea03332c50b4fcceadf8b76
|
https://github.com/mikedeboer/jsDAV/blob/1fe585dff008184d3ea03332c50b4fcceadf8b76/lib/DAV/plugins/auth/abstractDigest.js#L45-L60
|
16,354
|
mikedeboer/jsDAV
|
lib/DAV/plugins/auth/abstractDigest.js
|
function(realm, req) {
this.realm = realm;
this.opaque = Util.createHash(this.realm);
this.digest = getDigest(req);
this.digestParts = parseDigest(this.digest);
}
|
javascript
|
function(realm, req) {
this.realm = realm;
this.opaque = Util.createHash(this.realm);
this.digest = getDigest(req);
this.digestParts = parseDigest(this.digest);
}
|
[
"function",
"(",
"realm",
",",
"req",
")",
"{",
"this",
".",
"realm",
"=",
"realm",
";",
"this",
".",
"opaque",
"=",
"Util",
".",
"createHash",
"(",
"this",
".",
"realm",
")",
";",
"this",
".",
"digest",
"=",
"getDigest",
"(",
"req",
")",
";",
"this",
".",
"digestParts",
"=",
"parseDigest",
"(",
"this",
".",
"digest",
")",
";",
"}"
] |
Gathers all information from the headers
This method needs to be called prior to anything else.
@return void
|
[
"Gathers",
"all",
"information",
"from",
"the",
"headers"
] |
1fe585dff008184d3ea03332c50b4fcceadf8b76
|
https://github.com/mikedeboer/jsDAV/blob/1fe585dff008184d3ea03332c50b4fcceadf8b76/lib/DAV/plugins/auth/abstractDigest.js#L92-L97
|
|
16,355
|
mikedeboer/jsDAV
|
lib/DAV/plugins/auth/abstractDigest.js
|
function(handler, password, cbvalidpass) {
this.A1 = Util.createHash(this.digestParts["username"] + ":" + this.realm + ":" + password);
this.validate(handler, cbvalidpass);
}
|
javascript
|
function(handler, password, cbvalidpass) {
this.A1 = Util.createHash(this.digestParts["username"] + ":" + this.realm + ":" + password);
this.validate(handler, cbvalidpass);
}
|
[
"function",
"(",
"handler",
",",
"password",
",",
"cbvalidpass",
")",
"{",
"this",
".",
"A1",
"=",
"Util",
".",
"createHash",
"(",
"this",
".",
"digestParts",
"[",
"\"username\"",
"]",
"+",
"\":\"",
"+",
"this",
".",
"realm",
"+",
"\":\"",
"+",
"password",
")",
";",
"this",
".",
"validate",
"(",
"handler",
",",
"cbvalidpass",
")",
";",
"}"
] |
Validates authentication through a password. The actual password must be provided here.
It is strongly recommended not store the password in plain-text and use validateA1 instead.
@param {String} password
@return bool
|
[
"Validates",
"authentication",
"through",
"a",
"password",
".",
"The",
"actual",
"password",
"must",
"be",
"provided",
"here",
".",
"It",
"is",
"strongly",
"recommended",
"not",
"store",
"the",
"password",
"in",
"plain",
"-",
"text",
"and",
"use",
"validateA1",
"instead",
"."
] |
1fe585dff008184d3ea03332c50b4fcceadf8b76
|
https://github.com/mikedeboer/jsDAV/blob/1fe585dff008184d3ea03332c50b4fcceadf8b76/lib/DAV/plugins/auth/abstractDigest.js#L139-L142
|
|
16,356
|
mikedeboer/jsDAV
|
lib/DAV/plugins/auth/abstractDigest.js
|
function(handler, cbvalidate) {
var req = handler.httpRequest;
var A2 = req.method + ":" + this.digestParts["uri"];
var self = this;
if (this.digestParts["qop"] == "auth-int") {
// Making sure we support this qop value
if (!(this.qop & QOP_AUTHINT))
return cbvalidate(false);
// We need to add an md5 of the entire request body to the A2 part of the hash
handler.getRequestBody("utf8", null, false, function(noop, body) {
A2 += ":" + Util.createHash(body);
afterBody();
});
}
else {
// We need to make sure we support this qop value
if (!(this.qop & QOP_AUTH))
return cbvalidate(false);
afterBody();
}
function afterBody() {
A2 = Util.createHash(A2);
var validResponse = Util.createHash(self.A1 + ":" + self.digestParts["nonce"] + ":"
+ self.digestParts["nc"] + ":" + self.digestParts["cnonce"] + ":"
+ self.digestParts["qop"] + ":" + A2);
cbvalidate(self.digestParts["response"] == validResponse);
}
}
|
javascript
|
function(handler, cbvalidate) {
var req = handler.httpRequest;
var A2 = req.method + ":" + this.digestParts["uri"];
var self = this;
if (this.digestParts["qop"] == "auth-int") {
// Making sure we support this qop value
if (!(this.qop & QOP_AUTHINT))
return cbvalidate(false);
// We need to add an md5 of the entire request body to the A2 part of the hash
handler.getRequestBody("utf8", null, false, function(noop, body) {
A2 += ":" + Util.createHash(body);
afterBody();
});
}
else {
// We need to make sure we support this qop value
if (!(this.qop & QOP_AUTH))
return cbvalidate(false);
afterBody();
}
function afterBody() {
A2 = Util.createHash(A2);
var validResponse = Util.createHash(self.A1 + ":" + self.digestParts["nonce"] + ":"
+ self.digestParts["nc"] + ":" + self.digestParts["cnonce"] + ":"
+ self.digestParts["qop"] + ":" + A2);
cbvalidate(self.digestParts["response"] == validResponse);
}
}
|
[
"function",
"(",
"handler",
",",
"cbvalidate",
")",
"{",
"var",
"req",
"=",
"handler",
".",
"httpRequest",
";",
"var",
"A2",
"=",
"req",
".",
"method",
"+",
"\":\"",
"+",
"this",
".",
"digestParts",
"[",
"\"uri\"",
"]",
";",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"this",
".",
"digestParts",
"[",
"\"qop\"",
"]",
"==",
"\"auth-int\"",
")",
"{",
"// Making sure we support this qop value",
"if",
"(",
"!",
"(",
"this",
".",
"qop",
"&",
"QOP_AUTHINT",
")",
")",
"return",
"cbvalidate",
"(",
"false",
")",
";",
"// We need to add an md5 of the entire request body to the A2 part of the hash",
"handler",
".",
"getRequestBody",
"(",
"\"utf8\"",
",",
"null",
",",
"false",
",",
"function",
"(",
"noop",
",",
"body",
")",
"{",
"A2",
"+=",
"\":\"",
"+",
"Util",
".",
"createHash",
"(",
"body",
")",
";",
"afterBody",
"(",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"// We need to make sure we support this qop value",
"if",
"(",
"!",
"(",
"this",
".",
"qop",
"&",
"QOP_AUTH",
")",
")",
"return",
"cbvalidate",
"(",
"false",
")",
";",
"afterBody",
"(",
")",
";",
"}",
"function",
"afterBody",
"(",
")",
"{",
"A2",
"=",
"Util",
".",
"createHash",
"(",
"A2",
")",
";",
"var",
"validResponse",
"=",
"Util",
".",
"createHash",
"(",
"self",
".",
"A1",
"+",
"\":\"",
"+",
"self",
".",
"digestParts",
"[",
"\"nonce\"",
"]",
"+",
"\":\"",
"+",
"self",
".",
"digestParts",
"[",
"\"nc\"",
"]",
"+",
"\":\"",
"+",
"self",
".",
"digestParts",
"[",
"\"cnonce\"",
"]",
"+",
"\":\"",
"+",
"self",
".",
"digestParts",
"[",
"\"qop\"",
"]",
"+",
"\":\"",
"+",
"A2",
")",
";",
"cbvalidate",
"(",
"self",
".",
"digestParts",
"[",
"\"response\"",
"]",
"==",
"validResponse",
")",
";",
"}",
"}"
] |
Validates the digest challenge
@return bool
|
[
"Validates",
"the",
"digest",
"challenge"
] |
1fe585dff008184d3ea03332c50b4fcceadf8b76
|
https://github.com/mikedeboer/jsDAV/blob/1fe585dff008184d3ea03332c50b4fcceadf8b76/lib/DAV/plugins/auth/abstractDigest.js#L158-L189
|
|
16,357
|
mikedeboer/jsDAV
|
lib/DAV/plugins/auth/abstractDigest.js
|
function(realm, err, cbreqauth) {
if (!(err instanceof Exc.jsDAV_Exception))
err = new Exc.NotAuthenticated(err);
var currQop = "";
switch (this.qop) {
case QOP_AUTH:
currQop = "auth";
break;
case QOP_AUTHINT:
currQop = "auth-int";
break;
case QOP_AUTH | QOP_AUTHINT:
currQop = "auth,auth-int";
break;
}
err.addHeader("WWW-Authenticate", "Digest realm=\"" + realm +
"\",qop=\"" + currQop + "\",nonce=\"" + this.nonce +
"\",opaque=\"" + this.opaque + "\"");
cbreqauth(err, false);
}
|
javascript
|
function(realm, err, cbreqauth) {
if (!(err instanceof Exc.jsDAV_Exception))
err = new Exc.NotAuthenticated(err);
var currQop = "";
switch (this.qop) {
case QOP_AUTH:
currQop = "auth";
break;
case QOP_AUTHINT:
currQop = "auth-int";
break;
case QOP_AUTH | QOP_AUTHINT:
currQop = "auth,auth-int";
break;
}
err.addHeader("WWW-Authenticate", "Digest realm=\"" + realm +
"\",qop=\"" + currQop + "\",nonce=\"" + this.nonce +
"\",opaque=\"" + this.opaque + "\"");
cbreqauth(err, false);
}
|
[
"function",
"(",
"realm",
",",
"err",
",",
"cbreqauth",
")",
"{",
"if",
"(",
"!",
"(",
"err",
"instanceof",
"Exc",
".",
"jsDAV_Exception",
")",
")",
"err",
"=",
"new",
"Exc",
".",
"NotAuthenticated",
"(",
"err",
")",
";",
"var",
"currQop",
"=",
"\"\"",
";",
"switch",
"(",
"this",
".",
"qop",
")",
"{",
"case",
"QOP_AUTH",
":",
"currQop",
"=",
"\"auth\"",
";",
"break",
";",
"case",
"QOP_AUTHINT",
":",
"currQop",
"=",
"\"auth-int\"",
";",
"break",
";",
"case",
"QOP_AUTH",
"|",
"QOP_AUTHINT",
":",
"currQop",
"=",
"\"auth,auth-int\"",
";",
"break",
";",
"}",
"err",
".",
"addHeader",
"(",
"\"WWW-Authenticate\"",
",",
"\"Digest realm=\\\"\"",
"+",
"realm",
"+",
"\"\\\",qop=\\\"\"",
"+",
"currQop",
"+",
"\"\\\",nonce=\\\"\"",
"+",
"this",
".",
"nonce",
"+",
"\"\\\",opaque=\\\"\"",
"+",
"this",
".",
"opaque",
"+",
"\"\\\"\"",
")",
";",
"cbreqauth",
"(",
"err",
",",
"false",
")",
";",
"}"
] |
Returns an HTTP 401 header, forcing login
This should be called when username and password are incorrect, or not supplied at all
@return void
|
[
"Returns",
"an",
"HTTP",
"401",
"header",
"forcing",
"login"
] |
1fe585dff008184d3ea03332c50b4fcceadf8b76
|
https://github.com/mikedeboer/jsDAV/blob/1fe585dff008184d3ea03332c50b4fcceadf8b76/lib/DAV/plugins/auth/abstractDigest.js#L209-L230
|
|
16,358
|
mikedeboer/jsDAV
|
lib/DAV/plugins/auth/abstractDigest.js
|
function(handler, realm, cbauth) {
var req = handler.httpRequest;
this.init(realm, req);
var username = this.digestParts["username"];
// No username was given
if (!username)
return this.requireAuth(realm, "No digest authentication headers were found", cbauth);
var self = this;
this.getDigestHash(realm, username, function(err, hash) {
// If this was false, the user account didn't exist
if (err || !hash)
return self.requireAuth(realm, err || "The supplied username was not on file", cbauth);
if (typeof hash != "string") {
handler.handleError(new Exc.jsDAV_Exception(
"The returned value from getDigestHash must be a string or null"));
return cbauth(null, false);
}
// If this was false, the password or part of the hash was incorrect.
self.validateA1(handler, hash, function(isValid) {
if (!isValid)
return self.requireAuth(realm, "Incorrect username", cbauth);
self.currentUser = username;
cbauth(null, true);
});
});
}
|
javascript
|
function(handler, realm, cbauth) {
var req = handler.httpRequest;
this.init(realm, req);
var username = this.digestParts["username"];
// No username was given
if (!username)
return this.requireAuth(realm, "No digest authentication headers were found", cbauth);
var self = this;
this.getDigestHash(realm, username, function(err, hash) {
// If this was false, the user account didn't exist
if (err || !hash)
return self.requireAuth(realm, err || "The supplied username was not on file", cbauth);
if (typeof hash != "string") {
handler.handleError(new Exc.jsDAV_Exception(
"The returned value from getDigestHash must be a string or null"));
return cbauth(null, false);
}
// If this was false, the password or part of the hash was incorrect.
self.validateA1(handler, hash, function(isValid) {
if (!isValid)
return self.requireAuth(realm, "Incorrect username", cbauth);
self.currentUser = username;
cbauth(null, true);
});
});
}
|
[
"function",
"(",
"handler",
",",
"realm",
",",
"cbauth",
")",
"{",
"var",
"req",
"=",
"handler",
".",
"httpRequest",
";",
"this",
".",
"init",
"(",
"realm",
",",
"req",
")",
";",
"var",
"username",
"=",
"this",
".",
"digestParts",
"[",
"\"username\"",
"]",
";",
"// No username was given",
"if",
"(",
"!",
"username",
")",
"return",
"this",
".",
"requireAuth",
"(",
"realm",
",",
"\"No digest authentication headers were found\"",
",",
"cbauth",
")",
";",
"var",
"self",
"=",
"this",
";",
"this",
".",
"getDigestHash",
"(",
"realm",
",",
"username",
",",
"function",
"(",
"err",
",",
"hash",
")",
"{",
"// If this was false, the user account didn't exist",
"if",
"(",
"err",
"||",
"!",
"hash",
")",
"return",
"self",
".",
"requireAuth",
"(",
"realm",
",",
"err",
"||",
"\"The supplied username was not on file\"",
",",
"cbauth",
")",
";",
"if",
"(",
"typeof",
"hash",
"!=",
"\"string\"",
")",
"{",
"handler",
".",
"handleError",
"(",
"new",
"Exc",
".",
"jsDAV_Exception",
"(",
"\"The returned value from getDigestHash must be a string or null\"",
")",
")",
";",
"return",
"cbauth",
"(",
"null",
",",
"false",
")",
";",
"}",
"// If this was false, the password or part of the hash was incorrect.",
"self",
".",
"validateA1",
"(",
"handler",
",",
"hash",
",",
"function",
"(",
"isValid",
")",
"{",
"if",
"(",
"!",
"isValid",
")",
"return",
"self",
".",
"requireAuth",
"(",
"realm",
",",
"\"Incorrect username\"",
",",
"cbauth",
")",
";",
"self",
".",
"currentUser",
"=",
"username",
";",
"cbauth",
"(",
"null",
",",
"true",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Authenticates the user based on the current request.
If authentication is succesful, true must be returned.
If authentication fails, an exception must be thrown.
@throws Sabre_DAV_Exception_NotAuthenticated
@return bool
|
[
"Authenticates",
"the",
"user",
"based",
"on",
"the",
"current",
"request",
"."
] |
1fe585dff008184d3ea03332c50b4fcceadf8b76
|
https://github.com/mikedeboer/jsDAV/blob/1fe585dff008184d3ea03332c50b4fcceadf8b76/lib/DAV/plugins/auth/abstractDigest.js#L241-L271
|
|
16,359
|
rain1017/memdb
|
lib/autoconnection.js
|
function(opts){
opts = opts || {};
this.db = opts.db;
this.config = {
maxConnection : opts.maxConnection || DEFAULT_MAX_CONNECTION,
connectionIdleTimeout : opts.connectionIdleTimeout || DEFAULT_CONNECTION_IDLE_TIMEOUT,
maxPendingTask : opts.maxPendingTask || DEFAULT_MAX_PENDING_TASK,
reconnectInterval : opts.reconnectInterval || DEFAULT_RECONNECT_INTERVAL,
// allow concurrent request inside one connection, internal use only
concurrentInConnection : opts.concurrentInConnection || false,
// {shardId : {host : '127.0.0.1', port : 31017}}
shards : opts.shards || {},
};
if(this.config.concurrentInConnection){
this.config.maxConnection = 1;
}
var shardIds = Object.keys(this.config.shards);
if(shardIds.length === 0){
throw new Error('please specify opts.shards');
}
var shards = {};
shardIds.forEach(function(shardId){
shards[shardId] = {
connections : {}, // {connId : connection}
freeConnections : {}, // {connId : true}
connectionTimeouts : {}, // {connId : timeout}
pendingTasks : [],
reconnectInterval : null,
};
});
this.shards = shards;
this.openConnectionLock = new AsyncLock({Promise : P, maxPending : 10000});
this.collections = {};
}
|
javascript
|
function(opts){
opts = opts || {};
this.db = opts.db;
this.config = {
maxConnection : opts.maxConnection || DEFAULT_MAX_CONNECTION,
connectionIdleTimeout : opts.connectionIdleTimeout || DEFAULT_CONNECTION_IDLE_TIMEOUT,
maxPendingTask : opts.maxPendingTask || DEFAULT_MAX_PENDING_TASK,
reconnectInterval : opts.reconnectInterval || DEFAULT_RECONNECT_INTERVAL,
// allow concurrent request inside one connection, internal use only
concurrentInConnection : opts.concurrentInConnection || false,
// {shardId : {host : '127.0.0.1', port : 31017}}
shards : opts.shards || {},
};
if(this.config.concurrentInConnection){
this.config.maxConnection = 1;
}
var shardIds = Object.keys(this.config.shards);
if(shardIds.length === 0){
throw new Error('please specify opts.shards');
}
var shards = {};
shardIds.forEach(function(shardId){
shards[shardId] = {
connections : {}, // {connId : connection}
freeConnections : {}, // {connId : true}
connectionTimeouts : {}, // {connId : timeout}
pendingTasks : [],
reconnectInterval : null,
};
});
this.shards = shards;
this.openConnectionLock = new AsyncLock({Promise : P, maxPending : 10000});
this.collections = {};
}
|
[
"function",
"(",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"this",
".",
"db",
"=",
"opts",
".",
"db",
";",
"this",
".",
"config",
"=",
"{",
"maxConnection",
":",
"opts",
".",
"maxConnection",
"||",
"DEFAULT_MAX_CONNECTION",
",",
"connectionIdleTimeout",
":",
"opts",
".",
"connectionIdleTimeout",
"||",
"DEFAULT_CONNECTION_IDLE_TIMEOUT",
",",
"maxPendingTask",
":",
"opts",
".",
"maxPendingTask",
"||",
"DEFAULT_MAX_PENDING_TASK",
",",
"reconnectInterval",
":",
"opts",
".",
"reconnectInterval",
"||",
"DEFAULT_RECONNECT_INTERVAL",
",",
"// allow concurrent request inside one connection, internal use only",
"concurrentInConnection",
":",
"opts",
".",
"concurrentInConnection",
"||",
"false",
",",
"// {shardId : {host : '127.0.0.1', port : 31017}}",
"shards",
":",
"opts",
".",
"shards",
"||",
"{",
"}",
",",
"}",
";",
"if",
"(",
"this",
".",
"config",
".",
"concurrentInConnection",
")",
"{",
"this",
".",
"config",
".",
"maxConnection",
"=",
"1",
";",
"}",
"var",
"shardIds",
"=",
"Object",
".",
"keys",
"(",
"this",
".",
"config",
".",
"shards",
")",
";",
"if",
"(",
"shardIds",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'please specify opts.shards'",
")",
";",
"}",
"var",
"shards",
"=",
"{",
"}",
";",
"shardIds",
".",
"forEach",
"(",
"function",
"(",
"shardId",
")",
"{",
"shards",
"[",
"shardId",
"]",
"=",
"{",
"connections",
":",
"{",
"}",
",",
"// {connId : connection}",
"freeConnections",
":",
"{",
"}",
",",
"// {connId : true}",
"connectionTimeouts",
":",
"{",
"}",
",",
"// {connId : timeout}",
"pendingTasks",
":",
"[",
"]",
",",
"reconnectInterval",
":",
"null",
",",
"}",
";",
"}",
")",
";",
"this",
".",
"shards",
"=",
"shards",
";",
"this",
".",
"openConnectionLock",
"=",
"new",
"AsyncLock",
"(",
"{",
"Promise",
":",
"P",
",",
"maxPending",
":",
"10000",
"}",
")",
";",
"this",
".",
"collections",
"=",
"{",
"}",
";",
"}"
] |
Use one connection per transaction Route request to shards
|
[
"Use",
"one",
"connection",
"per",
"transaction",
"Route",
"request",
"to",
"shards"
] |
bded437d0e6aa286ec15238c71a91f96ded8e14e
|
https://github.com/rain1017/memdb/blob/bded437d0e6aa286ec15238c71a91f96ded8e14e/lib/autoconnection.js#L38-L79
|
|
16,360
|
aragon/aragon-cli
|
packages/aragon-cli/src/commands/apm_cmds/publish.js
|
prepareFilesForPublishing
|
async function prepareFilesForPublishing(
tmpDir,
files = [],
ignorePatterns = null
) {
// Ignored files filter
const filter = ignore().add(ignorePatterns)
const projectRoot = findProjectRoot()
function createFilter(files, ignorePath) {
let f = fs.readFileSync(ignorePath).toString()
files.forEach(file => {
f = f.concat(`\n!${file}`)
})
return f
}
const ipfsignorePath = path.resolve(projectRoot, '.ipfsignore')
if (pathExistsSync(ipfsignorePath)) {
filter.add(createFilter(files, ipfsignorePath))
} else {
const gitignorePath = path.resolve(projectRoot, '.gitignore')
if (pathExistsSync(gitignorePath)) {
filter.add(createFilter(files, gitignorePath))
}
}
const replaceRootRegex = new RegExp(`^${projectRoot}`)
function filterIgnoredFiles(src) {
const relativeSrc = src.replace(replaceRootRegex, '.')
return !filter.ignores(relativeSrc)
}
// Copy files
await Promise.all(
files.map(async file => {
const stats = await promisify(fs.lstat)(file)
let destination = tmpDir
if (stats.isFile()) {
destination = path.resolve(tmpDir, file)
}
return copy(file, destination, {
filter: filterIgnoredFiles,
})
})
)
const manifestOrigin = path.resolve(projectRoot, MANIFEST_FILE)
const manifestDst = path.resolve(tmpDir, MANIFEST_FILE)
if (!pathExistsSync(manifestDst) && pathExistsSync(manifestOrigin)) {
await copy(manifestOrigin, manifestDst)
}
const artifactOrigin = path.resolve(projectRoot, ARTIFACT_FILE)
const artifactDst = path.resolve(tmpDir, ARTIFACT_FILE)
if (!pathExistsSync(artifactDst) && pathExistsSync(artifactOrigin)) {
await copy(artifactOrigin, artifactDst)
}
return tmpDir
}
|
javascript
|
async function prepareFilesForPublishing(
tmpDir,
files = [],
ignorePatterns = null
) {
// Ignored files filter
const filter = ignore().add(ignorePatterns)
const projectRoot = findProjectRoot()
function createFilter(files, ignorePath) {
let f = fs.readFileSync(ignorePath).toString()
files.forEach(file => {
f = f.concat(`\n!${file}`)
})
return f
}
const ipfsignorePath = path.resolve(projectRoot, '.ipfsignore')
if (pathExistsSync(ipfsignorePath)) {
filter.add(createFilter(files, ipfsignorePath))
} else {
const gitignorePath = path.resolve(projectRoot, '.gitignore')
if (pathExistsSync(gitignorePath)) {
filter.add(createFilter(files, gitignorePath))
}
}
const replaceRootRegex = new RegExp(`^${projectRoot}`)
function filterIgnoredFiles(src) {
const relativeSrc = src.replace(replaceRootRegex, '.')
return !filter.ignores(relativeSrc)
}
// Copy files
await Promise.all(
files.map(async file => {
const stats = await promisify(fs.lstat)(file)
let destination = tmpDir
if (stats.isFile()) {
destination = path.resolve(tmpDir, file)
}
return copy(file, destination, {
filter: filterIgnoredFiles,
})
})
)
const manifestOrigin = path.resolve(projectRoot, MANIFEST_FILE)
const manifestDst = path.resolve(tmpDir, MANIFEST_FILE)
if (!pathExistsSync(manifestDst) && pathExistsSync(manifestOrigin)) {
await copy(manifestOrigin, manifestDst)
}
const artifactOrigin = path.resolve(projectRoot, ARTIFACT_FILE)
const artifactDst = path.resolve(tmpDir, ARTIFACT_FILE)
if (!pathExistsSync(artifactDst) && pathExistsSync(artifactOrigin)) {
await copy(artifactOrigin, artifactDst)
}
return tmpDir
}
|
[
"async",
"function",
"prepareFilesForPublishing",
"(",
"tmpDir",
",",
"files",
"=",
"[",
"]",
",",
"ignorePatterns",
"=",
"null",
")",
"{",
"// Ignored files filter",
"const",
"filter",
"=",
"ignore",
"(",
")",
".",
"add",
"(",
"ignorePatterns",
")",
"const",
"projectRoot",
"=",
"findProjectRoot",
"(",
")",
"function",
"createFilter",
"(",
"files",
",",
"ignorePath",
")",
"{",
"let",
"f",
"=",
"fs",
".",
"readFileSync",
"(",
"ignorePath",
")",
".",
"toString",
"(",
")",
"files",
".",
"forEach",
"(",
"file",
"=>",
"{",
"f",
"=",
"f",
".",
"concat",
"(",
"`",
"\\n",
"${",
"file",
"}",
"`",
")",
"}",
")",
"return",
"f",
"}",
"const",
"ipfsignorePath",
"=",
"path",
".",
"resolve",
"(",
"projectRoot",
",",
"'.ipfsignore'",
")",
"if",
"(",
"pathExistsSync",
"(",
"ipfsignorePath",
")",
")",
"{",
"filter",
".",
"add",
"(",
"createFilter",
"(",
"files",
",",
"ipfsignorePath",
")",
")",
"}",
"else",
"{",
"const",
"gitignorePath",
"=",
"path",
".",
"resolve",
"(",
"projectRoot",
",",
"'.gitignore'",
")",
"if",
"(",
"pathExistsSync",
"(",
"gitignorePath",
")",
")",
"{",
"filter",
".",
"add",
"(",
"createFilter",
"(",
"files",
",",
"gitignorePath",
")",
")",
"}",
"}",
"const",
"replaceRootRegex",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"projectRoot",
"}",
"`",
")",
"function",
"filterIgnoredFiles",
"(",
"src",
")",
"{",
"const",
"relativeSrc",
"=",
"src",
".",
"replace",
"(",
"replaceRootRegex",
",",
"'.'",
")",
"return",
"!",
"filter",
".",
"ignores",
"(",
"relativeSrc",
")",
"}",
"// Copy files",
"await",
"Promise",
".",
"all",
"(",
"files",
".",
"map",
"(",
"async",
"file",
"=>",
"{",
"const",
"stats",
"=",
"await",
"promisify",
"(",
"fs",
".",
"lstat",
")",
"(",
"file",
")",
"let",
"destination",
"=",
"tmpDir",
"if",
"(",
"stats",
".",
"isFile",
"(",
")",
")",
"{",
"destination",
"=",
"path",
".",
"resolve",
"(",
"tmpDir",
",",
"file",
")",
"}",
"return",
"copy",
"(",
"file",
",",
"destination",
",",
"{",
"filter",
":",
"filterIgnoredFiles",
",",
"}",
")",
"}",
")",
")",
"const",
"manifestOrigin",
"=",
"path",
".",
"resolve",
"(",
"projectRoot",
",",
"MANIFEST_FILE",
")",
"const",
"manifestDst",
"=",
"path",
".",
"resolve",
"(",
"tmpDir",
",",
"MANIFEST_FILE",
")",
"if",
"(",
"!",
"pathExistsSync",
"(",
"manifestDst",
")",
"&&",
"pathExistsSync",
"(",
"manifestOrigin",
")",
")",
"{",
"await",
"copy",
"(",
"manifestOrigin",
",",
"manifestDst",
")",
"}",
"const",
"artifactOrigin",
"=",
"path",
".",
"resolve",
"(",
"projectRoot",
",",
"ARTIFACT_FILE",
")",
"const",
"artifactDst",
"=",
"path",
".",
"resolve",
"(",
"tmpDir",
",",
"ARTIFACT_FILE",
")",
"if",
"(",
"!",
"pathExistsSync",
"(",
"artifactDst",
")",
"&&",
"pathExistsSync",
"(",
"artifactOrigin",
")",
")",
"{",
"await",
"copy",
"(",
"artifactOrigin",
",",
"artifactDst",
")",
"}",
"return",
"tmpDir",
"}"
] |
Moves the specified files to a temporary directory and returns the path to
the temporary directory.
@param {string} tmpDir Temporary directory
@param {Array<string>} files An array of file paths to include
@param {string} ignorePatterns An array of glob-like pattern of files to ignore
@return {string} The path to the temporary directory
|
[
"Moves",
"the",
"specified",
"files",
"to",
"a",
"temporary",
"directory",
"and",
"returns",
"the",
"path",
"to",
"the",
"temporary",
"directory",
"."
] |
88b5a33255df94cd2b95f43e40fda8ac5b9be99a
|
https://github.com/aragon/aragon-cli/blob/88b5a33255df94cd2b95f43e40fda8ac5b9be99a/packages/aragon-cli/src/commands/apm_cmds/publish.js#L215-L279
|
16,361
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
moduleDefine
|
function moduleDefine(exports, name, members) {
var target = [exports];
var publicNS = null;
if (name) {
publicNS = createNamespace(_Global, name);
target.push(publicNS);
}
initializeProperties(target, members, name || "<ANONYMOUS>");
return publicNS;
}
|
javascript
|
function moduleDefine(exports, name, members) {
var target = [exports];
var publicNS = null;
if (name) {
publicNS = createNamespace(_Global, name);
target.push(publicNS);
}
initializeProperties(target, members, name || "<ANONYMOUS>");
return publicNS;
}
|
[
"function",
"moduleDefine",
"(",
"exports",
",",
"name",
",",
"members",
")",
"{",
"var",
"target",
"=",
"[",
"exports",
"]",
";",
"var",
"publicNS",
"=",
"null",
";",
"if",
"(",
"name",
")",
"{",
"publicNS",
"=",
"createNamespace",
"(",
"_Global",
",",
"name",
")",
";",
"target",
".",
"push",
"(",
"publicNS",
")",
";",
"}",
"initializeProperties",
"(",
"target",
",",
"members",
",",
"name",
"||",
"\"<ANONYMOUS>\"",
")",
";",
"return",
"publicNS",
";",
"}"
] |
helper for defining AMD module members
|
[
"helper",
"for",
"defining",
"AMD",
"module",
"members"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L369-L378
|
16,362
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
completed
|
function completed(promise, value) {
var targetState;
if (value && typeof value === "object" && typeof value.then === "function") {
targetState = state_waiting;
} else {
targetState = state_success_notify;
}
promise._value = value;
promise._setState(targetState);
}
|
javascript
|
function completed(promise, value) {
var targetState;
if (value && typeof value === "object" && typeof value.then === "function") {
targetState = state_waiting;
} else {
targetState = state_success_notify;
}
promise._value = value;
promise._setState(targetState);
}
|
[
"function",
"completed",
"(",
"promise",
",",
"value",
")",
"{",
"var",
"targetState",
";",
"if",
"(",
"value",
"&&",
"typeof",
"value",
"===",
"\"object\"",
"&&",
"typeof",
"value",
".",
"then",
"===",
"\"function\"",
")",
"{",
"targetState",
"=",
"state_waiting",
";",
"}",
"else",
"{",
"targetState",
"=",
"state_success_notify",
";",
"}",
"promise",
".",
"_value",
"=",
"value",
";",
"promise",
".",
"_setState",
"(",
"targetState",
")",
";",
"}"
] |
Implementations of shared state machine code.
|
[
"Implementations",
"of",
"shared",
"state",
"machine",
"code",
"."
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L2023-L2032
|
16,363
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
timeout
|
function timeout(timeoutMS) {
var id;
return new Promise(
function (c) {
if (timeoutMS) {
id = _Global.setTimeout(c, timeoutMS);
} else {
_BaseCoreUtils._setImmediate(c);
}
},
function () {
if (id) {
_Global.clearTimeout(id);
}
}
);
}
|
javascript
|
function timeout(timeoutMS) {
var id;
return new Promise(
function (c) {
if (timeoutMS) {
id = _Global.setTimeout(c, timeoutMS);
} else {
_BaseCoreUtils._setImmediate(c);
}
},
function () {
if (id) {
_Global.clearTimeout(id);
}
}
);
}
|
[
"function",
"timeout",
"(",
"timeoutMS",
")",
"{",
"var",
"id",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"c",
")",
"{",
"if",
"(",
"timeoutMS",
")",
"{",
"id",
"=",
"_Global",
".",
"setTimeout",
"(",
"c",
",",
"timeoutMS",
")",
";",
"}",
"else",
"{",
"_BaseCoreUtils",
".",
"_setImmediate",
"(",
"c",
")",
";",
"}",
"}",
",",
"function",
"(",
")",
"{",
"if",
"(",
"id",
")",
"{",
"_Global",
".",
"clearTimeout",
"(",
"id",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Promise is the user-creatable WinJS.Promise object.
|
[
"Promise",
"is",
"the",
"user",
"-",
"creatable",
"WinJS",
".",
"Promise",
"object",
"."
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L2525-L2541
|
16,364
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
setState
|
function setState(state) {
return function (job, arg0, arg1) {
job._setState(state, arg0, arg1);
};
}
|
javascript
|
function setState(state) {
return function (job, arg0, arg1) {
job._setState(state, arg0, arg1);
};
}
|
[
"function",
"setState",
"(",
"state",
")",
"{",
"return",
"function",
"(",
"job",
",",
"arg0",
",",
"arg1",
")",
"{",
"job",
".",
"_setState",
"(",
"state",
",",
"arg0",
",",
"arg1",
")",
";",
"}",
";",
"}"
] |
Helper which yields a function that transitions to the specified state
|
[
"Helper",
"which",
"yields",
"a",
"function",
"that",
"transitions",
"to",
"the",
"specified",
"state"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L3520-L3524
|
16,365
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
notifyCurrentDrainListener
|
function notifyCurrentDrainListener() {
var listener = drainQueue.shift();
if (listener) {
drainStopping(listener);
drainQueue[0] && drainStarting(drainQueue[0]);
listener.complete();
}
}
|
javascript
|
function notifyCurrentDrainListener() {
var listener = drainQueue.shift();
if (listener) {
drainStopping(listener);
drainQueue[0] && drainStarting(drainQueue[0]);
listener.complete();
}
}
|
[
"function",
"notifyCurrentDrainListener",
"(",
")",
"{",
"var",
"listener",
"=",
"drainQueue",
".",
"shift",
"(",
")",
";",
"if",
"(",
"listener",
")",
"{",
"drainStopping",
"(",
"listener",
")",
";",
"drainQueue",
"[",
"0",
"]",
"&&",
"drainStarting",
"(",
"drainQueue",
"[",
"0",
"]",
")",
";",
"listener",
".",
"complete",
"(",
")",
";",
"}",
"}"
] |
Notifies and removes the current drain listener
|
[
"Notifies",
"and",
"removes",
"the",
"current",
"drain",
"listener"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L4135-L4143
|
16,366
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
notifyDrainListeners
|
function notifyDrainListeners() {
var notifiedSomebody = false;
if (!!drainQueue.length) {
// As we exhaust priority levels, notify the appropriate drain listeners.
//
var drainPriority = currentDrainPriority();
while (+drainPriority === drainPriority && drainPriority > highWaterMark) {
pumpingPriority = drainPriority;
notifyCurrentDrainListener();
notifiedSomebody = true;
drainPriority = currentDrainPriority();
}
}
return notifiedSomebody;
}
|
javascript
|
function notifyDrainListeners() {
var notifiedSomebody = false;
if (!!drainQueue.length) {
// As we exhaust priority levels, notify the appropriate drain listeners.
//
var drainPriority = currentDrainPriority();
while (+drainPriority === drainPriority && drainPriority > highWaterMark) {
pumpingPriority = drainPriority;
notifyCurrentDrainListener();
notifiedSomebody = true;
drainPriority = currentDrainPriority();
}
}
return notifiedSomebody;
}
|
[
"function",
"notifyDrainListeners",
"(",
")",
"{",
"var",
"notifiedSomebody",
"=",
"false",
";",
"if",
"(",
"!",
"!",
"drainQueue",
".",
"length",
")",
"{",
"// As we exhaust priority levels, notify the appropriate drain listeners.",
"//",
"var",
"drainPriority",
"=",
"currentDrainPriority",
"(",
")",
";",
"while",
"(",
"+",
"drainPriority",
"===",
"drainPriority",
"&&",
"drainPriority",
">",
"highWaterMark",
")",
"{",
"pumpingPriority",
"=",
"drainPriority",
";",
"notifyCurrentDrainListener",
"(",
")",
";",
"notifiedSomebody",
"=",
"true",
";",
"drainPriority",
"=",
"currentDrainPriority",
"(",
")",
";",
"}",
"}",
"return",
"notifiedSomebody",
";",
"}"
] |
Notifies all drain listeners which are at a priority > highWaterMark. Returns whether or not any drain listeners were notified. This function sets pumpingPriority and reads highWaterMark. Note that it may call into user code which may call back into the scheduler.
|
[
"Notifies",
"all",
"drain",
"listeners",
"which",
"are",
"at",
"a",
"priority",
">",
"highWaterMark",
".",
"Returns",
"whether",
"or",
"not",
"any",
"drain",
"listeners",
"were",
"notified",
".",
"This",
"function",
"sets",
"pumpingPriority",
"and",
"reads",
"highWaterMark",
".",
"Note",
"that",
"it",
"may",
"call",
"into",
"user",
"code",
"which",
"may",
"call",
"back",
"into",
"the",
"scheduler",
"."
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L4150-L4164
|
16,367
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
addJobAtHeadOfPriority
|
function addJobAtHeadOfPriority(node, priority) {
var marker = markerFromPriority(priority);
if (marker.priority > highWaterMark) {
highWaterMark = marker.priority;
immediateYield = true;
}
marker._insertJobAfter(node);
}
|
javascript
|
function addJobAtHeadOfPriority(node, priority) {
var marker = markerFromPriority(priority);
if (marker.priority > highWaterMark) {
highWaterMark = marker.priority;
immediateYield = true;
}
marker._insertJobAfter(node);
}
|
[
"function",
"addJobAtHeadOfPriority",
"(",
"node",
",",
"priority",
")",
"{",
"var",
"marker",
"=",
"markerFromPriority",
"(",
"priority",
")",
";",
"if",
"(",
"marker",
".",
"priority",
">",
"highWaterMark",
")",
"{",
"highWaterMark",
"=",
"marker",
".",
"priority",
";",
"immediateYield",
"=",
"true",
";",
"}",
"marker",
".",
"_insertJobAfter",
"(",
"node",
")",
";",
"}"
] |
Mechanism for the scheduler
|
[
"Mechanism",
"for",
"the",
"scheduler"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L4246-L4253
|
16,368
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
setAttribute
|
function setAttribute(element, attribute, value) {
if (element.getAttribute(attribute) !== "" + value) {
element.setAttribute(attribute, value);
}
}
|
javascript
|
function setAttribute(element, attribute, value) {
if (element.getAttribute(attribute) !== "" + value) {
element.setAttribute(attribute, value);
}
}
|
[
"function",
"setAttribute",
"(",
"element",
",",
"attribute",
",",
"value",
")",
"{",
"if",
"(",
"element",
".",
"getAttribute",
"(",
"attribute",
")",
"!==",
"\"\"",
"+",
"value",
")",
"{",
"element",
".",
"setAttribute",
"(",
"attribute",
",",
"value",
")",
";",
"}",
"}"
] |
Only set the attribute if its value has changed
|
[
"Only",
"set",
"the",
"attribute",
"if",
"its",
"value",
"has",
"changed"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L5687-L5691
|
16,369
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
addListenerToEventMap
|
function addListenerToEventMap(element, type, listener, useCapture, data) {
var eventNameLowercase = type.toLowerCase();
if (!element._eventsMap) {
element._eventsMap = {};
}
if (!element._eventsMap[eventNameLowercase]) {
element._eventsMap[eventNameLowercase] = [];
}
element._eventsMap[eventNameLowercase].push({
listener: listener,
useCapture: useCapture,
data: data
});
}
|
javascript
|
function addListenerToEventMap(element, type, listener, useCapture, data) {
var eventNameLowercase = type.toLowerCase();
if (!element._eventsMap) {
element._eventsMap = {};
}
if (!element._eventsMap[eventNameLowercase]) {
element._eventsMap[eventNameLowercase] = [];
}
element._eventsMap[eventNameLowercase].push({
listener: listener,
useCapture: useCapture,
data: data
});
}
|
[
"function",
"addListenerToEventMap",
"(",
"element",
",",
"type",
",",
"listener",
",",
"useCapture",
",",
"data",
")",
"{",
"var",
"eventNameLowercase",
"=",
"type",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"!",
"element",
".",
"_eventsMap",
")",
"{",
"element",
".",
"_eventsMap",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"!",
"element",
".",
"_eventsMap",
"[",
"eventNameLowercase",
"]",
")",
"{",
"element",
".",
"_eventsMap",
"[",
"eventNameLowercase",
"]",
"=",
"[",
"]",
";",
"}",
"element",
".",
"_eventsMap",
"[",
"eventNameLowercase",
"]",
".",
"push",
"(",
"{",
"listener",
":",
"listener",
",",
"useCapture",
":",
"useCapture",
",",
"data",
":",
"data",
"}",
")",
";",
"}"
] |
Helpers for managing element._eventsMap for custom events
|
[
"Helpers",
"for",
"managing",
"element",
".",
"_eventsMap",
"for",
"custom",
"events"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L5776-L5789
|
16,370
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
function (element) {
var hiddenElement = _Global.document.createElement("div");
hiddenElement.style[_BaseUtils._browserStyleEquivalents["animation-name"].scriptName] = "WinJS-node-inserted";
hiddenElement.style[_BaseUtils._browserStyleEquivalents["animation-duration"].scriptName] = "0.01s";
hiddenElement.style["position"] = "absolute";
element.appendChild(hiddenElement);
exports._addEventListener(hiddenElement, "animationStart", function (e) {
if (e.animationName === "WinJS-node-inserted") {
var e = _Global.document.createEvent("Event");
e.initEvent("WinJSNodeInserted", false, true);
element.dispatchEvent(e);
}
}, false);
return hiddenElement;
}
|
javascript
|
function (element) {
var hiddenElement = _Global.document.createElement("div");
hiddenElement.style[_BaseUtils._browserStyleEquivalents["animation-name"].scriptName] = "WinJS-node-inserted";
hiddenElement.style[_BaseUtils._browserStyleEquivalents["animation-duration"].scriptName] = "0.01s";
hiddenElement.style["position"] = "absolute";
element.appendChild(hiddenElement);
exports._addEventListener(hiddenElement, "animationStart", function (e) {
if (e.animationName === "WinJS-node-inserted") {
var e = _Global.document.createEvent("Event");
e.initEvent("WinJSNodeInserted", false, true);
element.dispatchEvent(e);
}
}, false);
return hiddenElement;
}
|
[
"function",
"(",
"element",
")",
"{",
"var",
"hiddenElement",
"=",
"_Global",
".",
"document",
".",
"createElement",
"(",
"\"div\"",
")",
";",
"hiddenElement",
".",
"style",
"[",
"_BaseUtils",
".",
"_browserStyleEquivalents",
"[",
"\"animation-name\"",
"]",
".",
"scriptName",
"]",
"=",
"\"WinJS-node-inserted\"",
";",
"hiddenElement",
".",
"style",
"[",
"_BaseUtils",
".",
"_browserStyleEquivalents",
"[",
"\"animation-duration\"",
"]",
".",
"scriptName",
"]",
"=",
"\"0.01s\"",
";",
"hiddenElement",
".",
"style",
"[",
"\"position\"",
"]",
"=",
"\"absolute\"",
";",
"element",
".",
"appendChild",
"(",
"hiddenElement",
")",
";",
"exports",
".",
"_addEventListener",
"(",
"hiddenElement",
",",
"\"animationStart\"",
",",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"e",
".",
"animationName",
"===",
"\"WinJS-node-inserted\"",
")",
"{",
"var",
"e",
"=",
"_Global",
".",
"document",
".",
"createEvent",
"(",
"\"Event\"",
")",
";",
"e",
".",
"initEvent",
"(",
"\"WinJSNodeInserted\"",
",",
"false",
",",
"true",
")",
";",
"element",
".",
"dispatchEvent",
"(",
"e",
")",
";",
"}",
"}",
",",
"false",
")",
";",
"return",
"hiddenElement",
";",
"}"
] |
Appends a hidden child to the given element that will listen for being added to the DOM. When the hidden element is added to the DOM, it will dispatch a "WinJSNodeInserted" event on the provided element.
|
[
"Appends",
"a",
"hidden",
"child",
"to",
"the",
"given",
"element",
"that",
"will",
"listen",
"for",
"being",
"added",
"to",
"the",
"DOM",
".",
"When",
"the",
"hidden",
"element",
"is",
"added",
"to",
"the",
"DOM",
"it",
"will",
"dispatch",
"a",
"WinJSNodeInserted",
"event",
"on",
"the",
"provided",
"element",
"."
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L6723-L6739
|
|
16,371
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
readWhitespace
|
function readWhitespace(text, offset, limit) {
while (offset < limit) {
var code = text.charCodeAt(offset);
switch (code) {
case 0x0009: // tab
case 0x000B: // vertical tab
case 0x000C: // form feed
case 0x0020: // space
case 0x00A0: // no-breaking space
case 0xFEFF: // BOM
break;
// There are no category Zs between 0x00A0 and 0x1680.
//
case (code < 0x1680) && code:
return offset;
// Unicode category Zs
//
case 0x1680:
case 0x180e:
case (code >= 0x2000 && code <= 0x200a) && code:
case 0x202f:
case 0x205f:
case 0x3000:
break;
default:
return offset;
}
offset++;
}
return offset;
}
|
javascript
|
function readWhitespace(text, offset, limit) {
while (offset < limit) {
var code = text.charCodeAt(offset);
switch (code) {
case 0x0009: // tab
case 0x000B: // vertical tab
case 0x000C: // form feed
case 0x0020: // space
case 0x00A0: // no-breaking space
case 0xFEFF: // BOM
break;
// There are no category Zs between 0x00A0 and 0x1680.
//
case (code < 0x1680) && code:
return offset;
// Unicode category Zs
//
case 0x1680:
case 0x180e:
case (code >= 0x2000 && code <= 0x200a) && code:
case 0x202f:
case 0x205f:
case 0x3000:
break;
default:
return offset;
}
offset++;
}
return offset;
}
|
[
"function",
"readWhitespace",
"(",
"text",
",",
"offset",
",",
"limit",
")",
"{",
"while",
"(",
"offset",
"<",
"limit",
")",
"{",
"var",
"code",
"=",
"text",
".",
"charCodeAt",
"(",
"offset",
")",
";",
"switch",
"(",
"code",
")",
"{",
"case",
"0x0009",
":",
"// tab",
"case",
"0x000B",
":",
"// vertical tab",
"case",
"0x000C",
":",
"// form feed",
"case",
"0x0020",
":",
"// space",
"case",
"0x00A0",
":",
"// no-breaking space",
"case",
"0xFEFF",
":",
"// BOM",
"break",
";",
"// There are no category Zs between 0x00A0 and 0x1680.",
"//",
"case",
"(",
"code",
"<",
"0x1680",
")",
"&&",
"code",
":",
"return",
"offset",
";",
"// Unicode category Zs",
"//",
"case",
"0x1680",
":",
"case",
"0x180e",
":",
"case",
"(",
"code",
">=",
"0x2000",
"&&",
"code",
"<=",
"0x200a",
")",
"&&",
"code",
":",
"case",
"0x202f",
":",
"case",
"0x205f",
":",
"case",
"0x3000",
":",
"break",
";",
"default",
":",
"return",
"offset",
";",
"}",
"offset",
"++",
";",
"}",
"return",
"offset",
";",
"}"
] |
Hand-inlined isWhitespace.
|
[
"Hand",
"-",
"inlined",
"isWhitespace",
"."
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L8698-L8731
|
16,372
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
function () {
if (this._notificationsSent && !this._externalBegin && !this._endNotificationsPosted) {
this._endNotificationsPosted = true;
var that = this;
Scheduler.schedule(function ItemsManager_async_endNotifications() {
that._endNotificationsPosted = false;
that._endNotifications();
}, Scheduler.Priority.high, null, "WinJS.UI._ItemsManager._postEndNotifications");
}
}
|
javascript
|
function () {
if (this._notificationsSent && !this._externalBegin && !this._endNotificationsPosted) {
this._endNotificationsPosted = true;
var that = this;
Scheduler.schedule(function ItemsManager_async_endNotifications() {
that._endNotificationsPosted = false;
that._endNotifications();
}, Scheduler.Priority.high, null, "WinJS.UI._ItemsManager._postEndNotifications");
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"_notificationsSent",
"&&",
"!",
"this",
".",
"_externalBegin",
"&&",
"!",
"this",
".",
"_endNotificationsPosted",
")",
"{",
"this",
".",
"_endNotificationsPosted",
"=",
"true",
";",
"var",
"that",
"=",
"this",
";",
"Scheduler",
".",
"schedule",
"(",
"function",
"ItemsManager_async_endNotifications",
"(",
")",
"{",
"that",
".",
"_endNotificationsPosted",
"=",
"false",
";",
"that",
".",
"_endNotifications",
"(",
")",
";",
"}",
",",
"Scheduler",
".",
"Priority",
".",
"high",
",",
"null",
",",
"\"WinJS.UI._ItemsManager._postEndNotifications\"",
")",
";",
"}",
"}"
] |
Some functions may be called synchronously or asynchronously, so it's best to post _endNotifications to avoid calling it prematurely.
|
[
"Some",
"functions",
"may",
"be",
"called",
"synchronously",
"or",
"asynchronously",
"so",
"it",
"s",
"best",
"to",
"post",
"_endNotifications",
"to",
"avoid",
"calling",
"it",
"prematurely",
"."
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L11291-L11300
|
|
16,373
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
tabbableElementsNodeFilter
|
function tabbableElementsNodeFilter(node) {
var nodeStyle = _ElementUtilities._getComputedStyle(node);
if (nodeStyle.display === "none" || nodeStyle.visibility === "hidden") {
return _Global.NodeFilter.FILTER_REJECT;
}
if (node._tabContainer) {
return _Global.NodeFilter.FILTER_ACCEPT;
}
if (node.parentNode && node.parentNode._tabContainer) {
var managedTarget = node.parentNode._tabContainer.childFocus;
// Ignore subtrees that are under a tab manager but not the child focus. If a node is contained in the child focus, either accept it (if it's tabbable itself), or skip it and find tabbable content inside of it.
if (managedTarget && node.contains(managedTarget)) {
return (getTabIndex(node) >= 0 ? _Global.NodeFilter.FILTER_ACCEPT : _Global.NodeFilter.FILTER_SKIP);
}
return _Global.NodeFilter.FILTER_REJECT;
}
var tabIndex = getTabIndex(node);
if (tabIndex >= 0) {
return _Global.NodeFilter.FILTER_ACCEPT;
}
return _Global.NodeFilter.FILTER_SKIP;
}
|
javascript
|
function tabbableElementsNodeFilter(node) {
var nodeStyle = _ElementUtilities._getComputedStyle(node);
if (nodeStyle.display === "none" || nodeStyle.visibility === "hidden") {
return _Global.NodeFilter.FILTER_REJECT;
}
if (node._tabContainer) {
return _Global.NodeFilter.FILTER_ACCEPT;
}
if (node.parentNode && node.parentNode._tabContainer) {
var managedTarget = node.parentNode._tabContainer.childFocus;
// Ignore subtrees that are under a tab manager but not the child focus. If a node is contained in the child focus, either accept it (if it's tabbable itself), or skip it and find tabbable content inside of it.
if (managedTarget && node.contains(managedTarget)) {
return (getTabIndex(node) >= 0 ? _Global.NodeFilter.FILTER_ACCEPT : _Global.NodeFilter.FILTER_SKIP);
}
return _Global.NodeFilter.FILTER_REJECT;
}
var tabIndex = getTabIndex(node);
if (tabIndex >= 0) {
return _Global.NodeFilter.FILTER_ACCEPT;
}
return _Global.NodeFilter.FILTER_SKIP;
}
|
[
"function",
"tabbableElementsNodeFilter",
"(",
"node",
")",
"{",
"var",
"nodeStyle",
"=",
"_ElementUtilities",
".",
"_getComputedStyle",
"(",
"node",
")",
";",
"if",
"(",
"nodeStyle",
".",
"display",
"===",
"\"none\"",
"||",
"nodeStyle",
".",
"visibility",
"===",
"\"hidden\"",
")",
"{",
"return",
"_Global",
".",
"NodeFilter",
".",
"FILTER_REJECT",
";",
"}",
"if",
"(",
"node",
".",
"_tabContainer",
")",
"{",
"return",
"_Global",
".",
"NodeFilter",
".",
"FILTER_ACCEPT",
";",
"}",
"if",
"(",
"node",
".",
"parentNode",
"&&",
"node",
".",
"parentNode",
".",
"_tabContainer",
")",
"{",
"var",
"managedTarget",
"=",
"node",
".",
"parentNode",
".",
"_tabContainer",
".",
"childFocus",
";",
"// Ignore subtrees that are under a tab manager but not the child focus. If a node is contained in the child focus, either accept it (if it's tabbable itself), or skip it and find tabbable content inside of it.",
"if",
"(",
"managedTarget",
"&&",
"node",
".",
"contains",
"(",
"managedTarget",
")",
")",
"{",
"return",
"(",
"getTabIndex",
"(",
"node",
")",
">=",
"0",
"?",
"_Global",
".",
"NodeFilter",
".",
"FILTER_ACCEPT",
":",
"_Global",
".",
"NodeFilter",
".",
"FILTER_SKIP",
")",
";",
"}",
"return",
"_Global",
".",
"NodeFilter",
".",
"FILTER_REJECT",
";",
"}",
"var",
"tabIndex",
"=",
"getTabIndex",
"(",
"node",
")",
";",
"if",
"(",
"tabIndex",
">=",
"0",
")",
"{",
"return",
"_Global",
".",
"NodeFilter",
".",
"FILTER_ACCEPT",
";",
"}",
"return",
"_Global",
".",
"NodeFilter",
".",
"FILTER_SKIP",
";",
"}"
] |
tabbableElementsNodeFilter works with the TreeWalker to create a view of the DOM tree that is built up of what we want the focusable tree to look like. When it runs into a tab contained area, it rejects anything except the childFocus element so that any potentially tabbable things that the TabContainer doesn't want tabbed to get ignored.
|
[
"tabbableElementsNodeFilter",
"works",
"with",
"the",
"TreeWalker",
"to",
"create",
"a",
"view",
"of",
"the",
"DOM",
"tree",
"that",
"is",
"built",
"up",
"of",
"what",
"we",
"want",
"the",
"focusable",
"tree",
"to",
"look",
"like",
".",
"When",
"it",
"runs",
"into",
"a",
"tab",
"contained",
"area",
"it",
"rejects",
"anything",
"except",
"the",
"childFocus",
"element",
"so",
"that",
"any",
"potentially",
"tabbable",
"things",
"that",
"the",
"TabContainer",
"doesn",
"t",
"want",
"tabbed",
"to",
"get",
"ignored",
"."
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L11381-L11402
|
16,374
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
drainQueue
|
function drainQueue(jobInfo) {
function drainNext() {
return drainQueue;
}
var queue = jobInfo.job._queue;
if (queue.length === 0 && eventQueue.length > 0) {
queue = jobInfo.job._queue = copyAndClearQueue();
}
jobInfo.setPromise(drainOneEvent(queue).then(drainNext, drainNext));
}
|
javascript
|
function drainQueue(jobInfo) {
function drainNext() {
return drainQueue;
}
var queue = jobInfo.job._queue;
if (queue.length === 0 && eventQueue.length > 0) {
queue = jobInfo.job._queue = copyAndClearQueue();
}
jobInfo.setPromise(drainOneEvent(queue).then(drainNext, drainNext));
}
|
[
"function",
"drainQueue",
"(",
"jobInfo",
")",
"{",
"function",
"drainNext",
"(",
")",
"{",
"return",
"drainQueue",
";",
"}",
"var",
"queue",
"=",
"jobInfo",
".",
"job",
".",
"_queue",
";",
"if",
"(",
"queue",
".",
"length",
"===",
"0",
"&&",
"eventQueue",
".",
"length",
">",
"0",
")",
"{",
"queue",
"=",
"jobInfo",
".",
"job",
".",
"_queue",
"=",
"copyAndClearQueue",
"(",
")",
";",
"}",
"jobInfo",
".",
"setPromise",
"(",
"drainOneEvent",
"(",
"queue",
")",
".",
"then",
"(",
"drainNext",
",",
"drainNext",
")",
")",
";",
"}"
] |
Drains the event queue via the scheduler
|
[
"Drains",
"the",
"event",
"queue",
"via",
"the",
"scheduler"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L14908-L14920
|
16,375
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
activatedHandler
|
function activatedHandler(e) {
var def = captureDeferral(e.activatedOperation);
_State._loadState(e).then(function () {
queueEvent({ type: activatedET, detail: e, _deferral: def.deferral, _deferralID: def.id });
});
}
|
javascript
|
function activatedHandler(e) {
var def = captureDeferral(e.activatedOperation);
_State._loadState(e).then(function () {
queueEvent({ type: activatedET, detail: e, _deferral: def.deferral, _deferralID: def.id });
});
}
|
[
"function",
"activatedHandler",
"(",
"e",
")",
"{",
"var",
"def",
"=",
"captureDeferral",
"(",
"e",
".",
"activatedOperation",
")",
";",
"_State",
".",
"_loadState",
"(",
"e",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"queueEvent",
"(",
"{",
"type",
":",
"activatedET",
",",
"detail",
":",
"e",
",",
"_deferral",
":",
"def",
".",
"deferral",
",",
"_deferralID",
":",
"def",
".",
"id",
"}",
")",
";",
"}",
")",
";",
"}"
] |
loaded == DOMContentLoaded activated == after WinRT Activated ready == after all of the above
|
[
"loaded",
"==",
"DOMContentLoaded",
"activated",
"==",
"after",
"WinRT",
"Activated",
"ready",
"==",
"after",
"all",
"of",
"the",
"above"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L15022-L15027
|
16,376
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
transformWithTransition
|
function transformWithTransition(element, transition) {
// transition's properties:
// - duration: Number representing the duration of the animation in milliseconds.
// - timing: String representing the CSS timing function that controls the progress of the animation.
// - to: The value of *element*'s transform property after the animation.
var duration = transition.duration * _TransitionAnimation._animationFactor;
var transitionProperty = _BaseUtils._browserStyleEquivalents["transition"].scriptName;
element.style[transitionProperty] = duration + "ms " + transformNames.cssName + " " + transition.timing;
element.style[transformNames.scriptName] = transition.to;
var finish;
return new Promise(function (c) {
var onTransitionEnd = function (eventObject) {
if (eventObject.target === element && eventObject.propertyName === transformNames.cssName) {
finish();
}
};
var didFinish = false;
finish = function () {
if (!didFinish) {
_Global.clearTimeout(timeoutId);
element.removeEventListener(_BaseUtils._browserEventEquivalents["transitionEnd"], onTransitionEnd);
element.style[transitionProperty] = "";
didFinish = true;
}
c();
};
// Watch dog timeout
var timeoutId = _Global.setTimeout(function () {
timeoutId = _Global.setTimeout(finish, duration);
}, 50);
element.addEventListener(_BaseUtils._browserEventEquivalents["transitionEnd"], onTransitionEnd);
}, function () {
finish(); // On cancelation, complete the promise successfully to match PVL
});
}
|
javascript
|
function transformWithTransition(element, transition) {
// transition's properties:
// - duration: Number representing the duration of the animation in milliseconds.
// - timing: String representing the CSS timing function that controls the progress of the animation.
// - to: The value of *element*'s transform property after the animation.
var duration = transition.duration * _TransitionAnimation._animationFactor;
var transitionProperty = _BaseUtils._browserStyleEquivalents["transition"].scriptName;
element.style[transitionProperty] = duration + "ms " + transformNames.cssName + " " + transition.timing;
element.style[transformNames.scriptName] = transition.to;
var finish;
return new Promise(function (c) {
var onTransitionEnd = function (eventObject) {
if (eventObject.target === element && eventObject.propertyName === transformNames.cssName) {
finish();
}
};
var didFinish = false;
finish = function () {
if (!didFinish) {
_Global.clearTimeout(timeoutId);
element.removeEventListener(_BaseUtils._browserEventEquivalents["transitionEnd"], onTransitionEnd);
element.style[transitionProperty] = "";
didFinish = true;
}
c();
};
// Watch dog timeout
var timeoutId = _Global.setTimeout(function () {
timeoutId = _Global.setTimeout(finish, duration);
}, 50);
element.addEventListener(_BaseUtils._browserEventEquivalents["transitionEnd"], onTransitionEnd);
}, function () {
finish(); // On cancelation, complete the promise successfully to match PVL
});
}
|
[
"function",
"transformWithTransition",
"(",
"element",
",",
"transition",
")",
"{",
"// transition's properties:",
"// - duration: Number representing the duration of the animation in milliseconds.",
"// - timing: String representing the CSS timing function that controls the progress of the animation.",
"// - to: The value of *element*'s transform property after the animation.",
"var",
"duration",
"=",
"transition",
".",
"duration",
"*",
"_TransitionAnimation",
".",
"_animationFactor",
";",
"var",
"transitionProperty",
"=",
"_BaseUtils",
".",
"_browserStyleEquivalents",
"[",
"\"transition\"",
"]",
".",
"scriptName",
";",
"element",
".",
"style",
"[",
"transitionProperty",
"]",
"=",
"duration",
"+",
"\"ms \"",
"+",
"transformNames",
".",
"cssName",
"+",
"\" \"",
"+",
"transition",
".",
"timing",
";",
"element",
".",
"style",
"[",
"transformNames",
".",
"scriptName",
"]",
"=",
"transition",
".",
"to",
";",
"var",
"finish",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"c",
")",
"{",
"var",
"onTransitionEnd",
"=",
"function",
"(",
"eventObject",
")",
"{",
"if",
"(",
"eventObject",
".",
"target",
"===",
"element",
"&&",
"eventObject",
".",
"propertyName",
"===",
"transformNames",
".",
"cssName",
")",
"{",
"finish",
"(",
")",
";",
"}",
"}",
";",
"var",
"didFinish",
"=",
"false",
";",
"finish",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"didFinish",
")",
"{",
"_Global",
".",
"clearTimeout",
"(",
"timeoutId",
")",
";",
"element",
".",
"removeEventListener",
"(",
"_BaseUtils",
".",
"_browserEventEquivalents",
"[",
"\"transitionEnd\"",
"]",
",",
"onTransitionEnd",
")",
";",
"element",
".",
"style",
"[",
"transitionProperty",
"]",
"=",
"\"\"",
";",
"didFinish",
"=",
"true",
";",
"}",
"c",
"(",
")",
";",
"}",
";",
"// Watch dog timeout",
"var",
"timeoutId",
"=",
"_Global",
".",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"timeoutId",
"=",
"_Global",
".",
"setTimeout",
"(",
"finish",
",",
"duration",
")",
";",
"}",
",",
"50",
")",
";",
"element",
".",
"addEventListener",
"(",
"_BaseUtils",
".",
"_browserEventEquivalents",
"[",
"\"transitionEnd\"",
"]",
",",
"onTransitionEnd",
")",
";",
"}",
",",
"function",
"(",
")",
"{",
"finish",
"(",
")",
";",
"// On cancelation, complete the promise successfully to match PVL",
"}",
")",
";",
"}"
] |
Resize animation The resize animation requires 2 animations to run simultaneously in sync with each other. It's implemented without PVL because PVL doesn't provide a way to guarantee that 2 animations will start at the same time.
|
[
"Resize",
"animation",
"The",
"resize",
"animation",
"requires",
"2",
"animations",
"to",
"run",
"simultaneously",
"in",
"sync",
"with",
"each",
"other",
".",
"It",
"s",
"implemented",
"without",
"PVL",
"because",
"PVL",
"doesn",
"t",
"provide",
"a",
"way",
"to",
"guarantee",
"that",
"2",
"animations",
"will",
"start",
"at",
"the",
"same",
"time",
"."
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L16645-L16683
|
16,377
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
disposeInstance
|
function disposeInstance(container, workPromise, renderCompletePromise) {
var bindings = _ElementUtilities.data(container).bindTokens;
if (bindings) {
bindings.forEach(function (binding) {
if (binding && binding.cancel) {
binding.cancel();
}
});
}
if (workPromise) {
workPromise.cancel();
}
if (renderCompletePromise) {
renderCompletePromise.cancel();
}
}
|
javascript
|
function disposeInstance(container, workPromise, renderCompletePromise) {
var bindings = _ElementUtilities.data(container).bindTokens;
if (bindings) {
bindings.forEach(function (binding) {
if (binding && binding.cancel) {
binding.cancel();
}
});
}
if (workPromise) {
workPromise.cancel();
}
if (renderCompletePromise) {
renderCompletePromise.cancel();
}
}
|
[
"function",
"disposeInstance",
"(",
"container",
",",
"workPromise",
",",
"renderCompletePromise",
")",
"{",
"var",
"bindings",
"=",
"_ElementUtilities",
".",
"data",
"(",
"container",
")",
".",
"bindTokens",
";",
"if",
"(",
"bindings",
")",
"{",
"bindings",
".",
"forEach",
"(",
"function",
"(",
"binding",
")",
"{",
"if",
"(",
"binding",
"&&",
"binding",
".",
"cancel",
")",
"{",
"binding",
".",
"cancel",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"workPromise",
")",
"{",
"workPromise",
".",
"cancel",
"(",
")",
";",
"}",
"if",
"(",
"renderCompletePromise",
")",
"{",
"renderCompletePromise",
".",
"cancel",
"(",
")",
";",
"}",
"}"
] |
Runtime helper functions
|
[
"Runtime",
"helper",
"functions"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L20559-L20574
|
16,378
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/base.js
|
PageControl_ctor
|
function PageControl_ctor(element, options, complete, parentedPromise) {
var that = this;
this._disposed = false;
this.element = element = element || _Global.document.createElement("div");
_ElementUtilities.addClass(element, "win-disposable");
element.msSourceLocation = uri;
this.uri = uri;
this.selfhost = selfhost(uri);
element.winControl = this;
_ElementUtilities.addClass(element, "pagecontrol");
var profilerMarkIdentifier = " uri='" + uri + "'" + _BaseUtils._getProfilerMarkIdentifier(this.element);
_WriteProfilerMark("WinJS.UI.Pages:createPage" + profilerMarkIdentifier + ",StartTM");
var load = Promise.wrap().
then(function Pages_load() { return that.load(uri); });
var renderCalled = load.then(function Pages_init(loadResult) {
return Promise.join({
loadResult: loadResult,
initResult: that.init(element, options)
});
}).then(function Pages_render(result) {
return that.render(element, options, result.loadResult);
});
this.elementReady = renderCalled.then(function () { return element; });
this.renderComplete = renderCalled.
then(function Pages_process() {
return that.process(element, options);
}).then(function Pages_processed() {
return that.processed(element, options);
}).then(function () {
return that;
});
var callComplete = function () {
complete && complete(that);
_WriteProfilerMark("WinJS.UI.Pages:createPage" + profilerMarkIdentifier + ",StopTM");
};
// promises guarantee order, so this will be called prior to ready path below
//
this.renderComplete.then(callComplete, callComplete);
this.readyComplete = this.renderComplete.then(function () {
return parentedPromise;
}).then(function Pages_ready() {
that.ready(element, options);
return that;
}).then(
null,
function Pages_error(err) {
return that.error(err);
}
);
}
|
javascript
|
function PageControl_ctor(element, options, complete, parentedPromise) {
var that = this;
this._disposed = false;
this.element = element = element || _Global.document.createElement("div");
_ElementUtilities.addClass(element, "win-disposable");
element.msSourceLocation = uri;
this.uri = uri;
this.selfhost = selfhost(uri);
element.winControl = this;
_ElementUtilities.addClass(element, "pagecontrol");
var profilerMarkIdentifier = " uri='" + uri + "'" + _BaseUtils._getProfilerMarkIdentifier(this.element);
_WriteProfilerMark("WinJS.UI.Pages:createPage" + profilerMarkIdentifier + ",StartTM");
var load = Promise.wrap().
then(function Pages_load() { return that.load(uri); });
var renderCalled = load.then(function Pages_init(loadResult) {
return Promise.join({
loadResult: loadResult,
initResult: that.init(element, options)
});
}).then(function Pages_render(result) {
return that.render(element, options, result.loadResult);
});
this.elementReady = renderCalled.then(function () { return element; });
this.renderComplete = renderCalled.
then(function Pages_process() {
return that.process(element, options);
}).then(function Pages_processed() {
return that.processed(element, options);
}).then(function () {
return that;
});
var callComplete = function () {
complete && complete(that);
_WriteProfilerMark("WinJS.UI.Pages:createPage" + profilerMarkIdentifier + ",StopTM");
};
// promises guarantee order, so this will be called prior to ready path below
//
this.renderComplete.then(callComplete, callComplete);
this.readyComplete = this.renderComplete.then(function () {
return parentedPromise;
}).then(function Pages_ready() {
that.ready(element, options);
return that;
}).then(
null,
function Pages_error(err) {
return that.error(err);
}
);
}
|
[
"function",
"PageControl_ctor",
"(",
"element",
",",
"options",
",",
"complete",
",",
"parentedPromise",
")",
"{",
"var",
"that",
"=",
"this",
";",
"this",
".",
"_disposed",
"=",
"false",
";",
"this",
".",
"element",
"=",
"element",
"=",
"element",
"||",
"_Global",
".",
"document",
".",
"createElement",
"(",
"\"div\"",
")",
";",
"_ElementUtilities",
".",
"addClass",
"(",
"element",
",",
"\"win-disposable\"",
")",
";",
"element",
".",
"msSourceLocation",
"=",
"uri",
";",
"this",
".",
"uri",
"=",
"uri",
";",
"this",
".",
"selfhost",
"=",
"selfhost",
"(",
"uri",
")",
";",
"element",
".",
"winControl",
"=",
"this",
";",
"_ElementUtilities",
".",
"addClass",
"(",
"element",
",",
"\"pagecontrol\"",
")",
";",
"var",
"profilerMarkIdentifier",
"=",
"\" uri='\"",
"+",
"uri",
"+",
"\"'\"",
"+",
"_BaseUtils",
".",
"_getProfilerMarkIdentifier",
"(",
"this",
".",
"element",
")",
";",
"_WriteProfilerMark",
"(",
"\"WinJS.UI.Pages:createPage\"",
"+",
"profilerMarkIdentifier",
"+",
"\",StartTM\"",
")",
";",
"var",
"load",
"=",
"Promise",
".",
"wrap",
"(",
")",
".",
"then",
"(",
"function",
"Pages_load",
"(",
")",
"{",
"return",
"that",
".",
"load",
"(",
"uri",
")",
";",
"}",
")",
";",
"var",
"renderCalled",
"=",
"load",
".",
"then",
"(",
"function",
"Pages_init",
"(",
"loadResult",
")",
"{",
"return",
"Promise",
".",
"join",
"(",
"{",
"loadResult",
":",
"loadResult",
",",
"initResult",
":",
"that",
".",
"init",
"(",
"element",
",",
"options",
")",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"Pages_render",
"(",
"result",
")",
"{",
"return",
"that",
".",
"render",
"(",
"element",
",",
"options",
",",
"result",
".",
"loadResult",
")",
";",
"}",
")",
";",
"this",
".",
"elementReady",
"=",
"renderCalled",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"element",
";",
"}",
")",
";",
"this",
".",
"renderComplete",
"=",
"renderCalled",
".",
"then",
"(",
"function",
"Pages_process",
"(",
")",
"{",
"return",
"that",
".",
"process",
"(",
"element",
",",
"options",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"Pages_processed",
"(",
")",
"{",
"return",
"that",
".",
"processed",
"(",
"element",
",",
"options",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"that",
";",
"}",
")",
";",
"var",
"callComplete",
"=",
"function",
"(",
")",
"{",
"complete",
"&&",
"complete",
"(",
"that",
")",
";",
"_WriteProfilerMark",
"(",
"\"WinJS.UI.Pages:createPage\"",
"+",
"profilerMarkIdentifier",
"+",
"\",StopTM\"",
")",
";",
"}",
";",
"// promises guarantee order, so this will be called prior to ready path below",
"//",
"this",
".",
"renderComplete",
".",
"then",
"(",
"callComplete",
",",
"callComplete",
")",
";",
"this",
".",
"readyComplete",
"=",
"this",
".",
"renderComplete",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"parentedPromise",
";",
"}",
")",
".",
"then",
"(",
"function",
"Pages_ready",
"(",
")",
"{",
"that",
".",
"ready",
"(",
"element",
",",
"options",
")",
";",
"return",
"that",
";",
"}",
")",
".",
"then",
"(",
"null",
",",
"function",
"Pages_error",
"(",
"err",
")",
"{",
"return",
"that",
".",
"error",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
] |
This needs to follow the WinJS.UI.processAll "async constructor" pattern to interop nicely in the "Views.Control" use case.
|
[
"This",
"needs",
"to",
"follow",
"the",
"WinJS",
".",
"UI",
".",
"processAll",
"async",
"constructor",
"pattern",
"to",
"interop",
"nicely",
"in",
"the",
"Views",
".",
"Control",
"use",
"case",
"."
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/base.js#L26466-L26524
|
16,379
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
moveSequenceBefore
|
function moveSequenceBefore(slotNext, slotFirst, slotLast) {
slotFirst.prev.next = slotLast.next;
slotLast.next.prev = slotFirst.prev;
slotFirst.prev = slotNext.prev;
slotLast.next = slotNext;
slotFirst.prev.next = slotFirst;
slotNext.prev = slotLast;
return true;
}
|
javascript
|
function moveSequenceBefore(slotNext, slotFirst, slotLast) {
slotFirst.prev.next = slotLast.next;
slotLast.next.prev = slotFirst.prev;
slotFirst.prev = slotNext.prev;
slotLast.next = slotNext;
slotFirst.prev.next = slotFirst;
slotNext.prev = slotLast;
return true;
}
|
[
"function",
"moveSequenceBefore",
"(",
"slotNext",
",",
"slotFirst",
",",
"slotLast",
")",
"{",
"slotFirst",
".",
"prev",
".",
"next",
"=",
"slotLast",
".",
"next",
";",
"slotLast",
".",
"next",
".",
"prev",
"=",
"slotFirst",
".",
"prev",
";",
"slotFirst",
".",
"prev",
"=",
"slotNext",
".",
"prev",
";",
"slotLast",
".",
"next",
"=",
"slotNext",
";",
"slotFirst",
".",
"prev",
".",
"next",
"=",
"slotFirst",
";",
"slotNext",
".",
"prev",
"=",
"slotLast",
";",
"return",
"true",
";",
"}"
] |
Does a little careful surgery to the slot sequence from slotFirst to slotLast before slotNext
|
[
"Does",
"a",
"little",
"careful",
"surgery",
"to",
"the",
"slot",
"sequence",
"from",
"slotFirst",
"to",
"slotLast",
"before",
"slotNext"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L322-L333
|
16,380
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
moveSequenceAfter
|
function moveSequenceAfter(slotPrev, slotFirst, slotLast) {
slotFirst.prev.next = slotLast.next;
slotLast.next.prev = slotFirst.prev;
slotFirst.prev = slotPrev;
slotLast.next = slotPrev.next;
slotPrev.next = slotFirst;
slotLast.next.prev = slotLast;
return true;
}
|
javascript
|
function moveSequenceAfter(slotPrev, slotFirst, slotLast) {
slotFirst.prev.next = slotLast.next;
slotLast.next.prev = slotFirst.prev;
slotFirst.prev = slotPrev;
slotLast.next = slotPrev.next;
slotPrev.next = slotFirst;
slotLast.next.prev = slotLast;
return true;
}
|
[
"function",
"moveSequenceAfter",
"(",
"slotPrev",
",",
"slotFirst",
",",
"slotLast",
")",
"{",
"slotFirst",
".",
"prev",
".",
"next",
"=",
"slotLast",
".",
"next",
";",
"slotLast",
".",
"next",
".",
"prev",
"=",
"slotFirst",
".",
"prev",
";",
"slotFirst",
".",
"prev",
"=",
"slotPrev",
";",
"slotLast",
".",
"next",
"=",
"slotPrev",
".",
"next",
";",
"slotPrev",
".",
"next",
"=",
"slotFirst",
";",
"slotLast",
".",
"next",
".",
"prev",
"=",
"slotLast",
";",
"return",
"true",
";",
"}"
] |
Does a little careful surgery to the slot sequence from slotFirst to slotLast after slotPrev
|
[
"Does",
"a",
"little",
"careful",
"surgery",
"to",
"the",
"slot",
"sequence",
"from",
"slotFirst",
"to",
"slotLast",
"after",
"slotPrev"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L336-L347
|
16,381
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
insertAndMergeSlot
|
function insertAndMergeSlot(slot, slotNext, mergeWithPrev, mergeWithNext) {
insertSlot(slot, slotNext);
var slotPrev = slot.prev;
if (slotPrev.lastInSequence) {
if (mergeWithPrev) {
delete slotPrev.lastInSequence;
} else {
slot.firstInSequence = true;
}
if (mergeWithNext) {
delete slotNext.firstInSequence;
} else {
slot.lastInSequence = true;
}
}
}
|
javascript
|
function insertAndMergeSlot(slot, slotNext, mergeWithPrev, mergeWithNext) {
insertSlot(slot, slotNext);
var slotPrev = slot.prev;
if (slotPrev.lastInSequence) {
if (mergeWithPrev) {
delete slotPrev.lastInSequence;
} else {
slot.firstInSequence = true;
}
if (mergeWithNext) {
delete slotNext.firstInSequence;
} else {
slot.lastInSequence = true;
}
}
}
|
[
"function",
"insertAndMergeSlot",
"(",
"slot",
",",
"slotNext",
",",
"mergeWithPrev",
",",
"mergeWithNext",
")",
"{",
"insertSlot",
"(",
"slot",
",",
"slotNext",
")",
";",
"var",
"slotPrev",
"=",
"slot",
".",
"prev",
";",
"if",
"(",
"slotPrev",
".",
"lastInSequence",
")",
"{",
"if",
"(",
"mergeWithPrev",
")",
"{",
"delete",
"slotPrev",
".",
"lastInSequence",
";",
"}",
"else",
"{",
"slot",
".",
"firstInSequence",
"=",
"true",
";",
"}",
"if",
"(",
"mergeWithNext",
")",
"{",
"delete",
"slotNext",
".",
"firstInSequence",
";",
"}",
"else",
"{",
"slot",
".",
"lastInSequence",
"=",
"true",
";",
"}",
"}",
"}"
] |
Inserts a slot in the middle of a sequence or between sequences. If the latter, mergeWithPrev and mergeWithNext parameters specify whether to merge the slot with the previous sequence, or next, or neither.
|
[
"Inserts",
"a",
"slot",
"in",
"the",
"middle",
"of",
"a",
"sequence",
"or",
"between",
"sequences",
".",
"If",
"the",
"latter",
"mergeWithPrev",
"and",
"mergeWithNext",
"parameters",
"specify",
"whether",
"to",
"merge",
"the",
"slot",
"with",
"the",
"previous",
"sequence",
"or",
"next",
"or",
"neither",
"."
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L368-L386
|
16,382
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
setSlotKey
|
function setSlotKey(slot, key) {
slot.key = key;
// Add the slot to the keyMap, so it is possible to quickly find the slot given its key
keyMap[slot.key] = slot;
}
|
javascript
|
function setSlotKey(slot, key) {
slot.key = key;
// Add the slot to the keyMap, so it is possible to quickly find the slot given its key
keyMap[slot.key] = slot;
}
|
[
"function",
"setSlotKey",
"(",
"slot",
",",
"key",
")",
"{",
"slot",
".",
"key",
"=",
"key",
";",
"// Add the slot to the keyMap, so it is possible to quickly find the slot given its key",
"keyMap",
"[",
"slot",
".",
"key",
"]",
"=",
"slot",
";",
"}"
] |
Keys and Indices
|
[
"Keys",
"and",
"Indices"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L390-L395
|
16,383
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
createAndAddSlot
|
function createAndAddSlot(slotNext, indexMapForSlot) {
var slotNew = (indexMapForSlot === indexMap ? createPrimarySlot() : createSlot());
insertSlot(slotNew, slotNext);
return slotNew;
}
|
javascript
|
function createAndAddSlot(slotNext, indexMapForSlot) {
var slotNew = (indexMapForSlot === indexMap ? createPrimarySlot() : createSlot());
insertSlot(slotNew, slotNext);
return slotNew;
}
|
[
"function",
"createAndAddSlot",
"(",
"slotNext",
",",
"indexMapForSlot",
")",
"{",
"var",
"slotNew",
"=",
"(",
"indexMapForSlot",
"===",
"indexMap",
"?",
"createPrimarySlot",
"(",
")",
":",
"createSlot",
"(",
")",
")",
";",
"insertSlot",
"(",
"slotNew",
",",
"slotNext",
")",
";",
"return",
"slotNew",
";",
"}"
] |
Creates a new slot and adds it to the slot list before slotNext
|
[
"Creates",
"a",
"new",
"slot",
"and",
"adds",
"it",
"to",
"the",
"slot",
"list",
"before",
"slotNext"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L418-L424
|
16,384
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
adjustedIndex
|
function adjustedIndex(slot) {
var undefinedIndex;
if (!slot) {
return undefinedIndex;
}
var delta = 0;
while (!slot.firstInSequence) {
delta++;
slot = slot.prev;
}
return (
typeof slot.indexNew === "number" ?
slot.indexNew + delta :
typeof slot.index === "number" ?
slot.index + delta :
undefinedIndex
);
}
|
javascript
|
function adjustedIndex(slot) {
var undefinedIndex;
if (!slot) {
return undefinedIndex;
}
var delta = 0;
while (!slot.firstInSequence) {
delta++;
slot = slot.prev;
}
return (
typeof slot.indexNew === "number" ?
slot.indexNew + delta :
typeof slot.index === "number" ?
slot.index + delta :
undefinedIndex
);
}
|
[
"function",
"adjustedIndex",
"(",
"slot",
")",
"{",
"var",
"undefinedIndex",
";",
"if",
"(",
"!",
"slot",
")",
"{",
"return",
"undefinedIndex",
";",
"}",
"var",
"delta",
"=",
"0",
";",
"while",
"(",
"!",
"slot",
".",
"firstInSequence",
")",
"{",
"delta",
"++",
";",
"slot",
"=",
"slot",
".",
"prev",
";",
"}",
"return",
"(",
"typeof",
"slot",
".",
"indexNew",
"===",
"\"number\"",
"?",
"slot",
".",
"indexNew",
"+",
"delta",
":",
"typeof",
"slot",
".",
"index",
"===",
"\"number\"",
"?",
"slot",
".",
"index",
"+",
"delta",
":",
"undefinedIndex",
")",
";",
"}"
] |
Deferred Index Updates Returns the index of the slot taking into account any outstanding index updates
|
[
"Deferred",
"Index",
"Updates",
"Returns",
"the",
"index",
"of",
"the",
"slot",
"taking",
"into",
"account",
"any",
"outstanding",
"index",
"updates"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L952-L972
|
16,385
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
updateNewIndicesAfterSlot
|
function updateNewIndicesAfterSlot(slot, indexDelta) {
// Adjust all the indexNews after this slot
for (slot = slot.next; slot; slot = slot.next) {
if (slot.firstInSequence) {
var indexNew = (slot.indexNew !== undefined ? slot.indexNew : slot.index);
if (indexNew !== undefined) {
slot.indexNew = indexNew + indexDelta;
}
}
}
// Adjust the overall count
countDelta += indexDelta;
indexUpdateDeferred = true;
// Increment currentRefreshID so any outstanding fetches don't cause trouble. If a refresh is in progress,
// restart it (which will also increment currentRefreshID).
if (refreshInProgress) {
beginRefresh();
} else {
currentRefreshID++;
}
}
|
javascript
|
function updateNewIndicesAfterSlot(slot, indexDelta) {
// Adjust all the indexNews after this slot
for (slot = slot.next; slot; slot = slot.next) {
if (slot.firstInSequence) {
var indexNew = (slot.indexNew !== undefined ? slot.indexNew : slot.index);
if (indexNew !== undefined) {
slot.indexNew = indexNew + indexDelta;
}
}
}
// Adjust the overall count
countDelta += indexDelta;
indexUpdateDeferred = true;
// Increment currentRefreshID so any outstanding fetches don't cause trouble. If a refresh is in progress,
// restart it (which will also increment currentRefreshID).
if (refreshInProgress) {
beginRefresh();
} else {
currentRefreshID++;
}
}
|
[
"function",
"updateNewIndicesAfterSlot",
"(",
"slot",
",",
"indexDelta",
")",
"{",
"// Adjust all the indexNews after this slot",
"for",
"(",
"slot",
"=",
"slot",
".",
"next",
";",
"slot",
";",
"slot",
"=",
"slot",
".",
"next",
")",
"{",
"if",
"(",
"slot",
".",
"firstInSequence",
")",
"{",
"var",
"indexNew",
"=",
"(",
"slot",
".",
"indexNew",
"!==",
"undefined",
"?",
"slot",
".",
"indexNew",
":",
"slot",
".",
"index",
")",
";",
"if",
"(",
"indexNew",
"!==",
"undefined",
")",
"{",
"slot",
".",
"indexNew",
"=",
"indexNew",
"+",
"indexDelta",
";",
"}",
"}",
"}",
"// Adjust the overall count",
"countDelta",
"+=",
"indexDelta",
";",
"indexUpdateDeferred",
"=",
"true",
";",
"// Increment currentRefreshID so any outstanding fetches don't cause trouble. If a refresh is in progress,",
"// restart it (which will also increment currentRefreshID).",
"if",
"(",
"refreshInProgress",
")",
"{",
"beginRefresh",
"(",
")",
";",
"}",
"else",
"{",
"currentRefreshID",
"++",
";",
"}",
"}"
] |
Updates the new index of the first slot in each sequence after the given slot
|
[
"Updates",
"the",
"new",
"index",
"of",
"the",
"first",
"slot",
"in",
"each",
"sequence",
"after",
"the",
"given",
"slot"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L975-L998
|
16,386
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
updateNewIndices
|
function updateNewIndices(slot, indexDelta) {
// If this slot is at the start of a sequence, transfer the indexNew
if (slot.firstInSequence) {
var indexNew;
if (indexDelta < 0) {
// The given slot is about to be removed
indexNew = slot.indexNew;
if (indexNew !== undefined) {
delete slot.indexNew;
} else {
indexNew = slot.index;
}
if (!slot.lastInSequence) {
// Update the next slot now
slot = slot.next;
if (indexNew !== undefined) {
slot.indexNew = indexNew;
}
}
} else {
// The given slot was just inserted
if (!slot.lastInSequence) {
var slotNext = slot.next;
indexNew = slotNext.indexNew;
if (indexNew !== undefined) {
delete slotNext.indexNew;
} else {
indexNew = slotNext.index;
}
if (indexNew !== undefined) {
slot.indexNew = indexNew;
}
}
}
}
updateNewIndicesAfterSlot(slot, indexDelta);
}
|
javascript
|
function updateNewIndices(slot, indexDelta) {
// If this slot is at the start of a sequence, transfer the indexNew
if (slot.firstInSequence) {
var indexNew;
if (indexDelta < 0) {
// The given slot is about to be removed
indexNew = slot.indexNew;
if (indexNew !== undefined) {
delete slot.indexNew;
} else {
indexNew = slot.index;
}
if (!slot.lastInSequence) {
// Update the next slot now
slot = slot.next;
if (indexNew !== undefined) {
slot.indexNew = indexNew;
}
}
} else {
// The given slot was just inserted
if (!slot.lastInSequence) {
var slotNext = slot.next;
indexNew = slotNext.indexNew;
if (indexNew !== undefined) {
delete slotNext.indexNew;
} else {
indexNew = slotNext.index;
}
if (indexNew !== undefined) {
slot.indexNew = indexNew;
}
}
}
}
updateNewIndicesAfterSlot(slot, indexDelta);
}
|
[
"function",
"updateNewIndices",
"(",
"slot",
",",
"indexDelta",
")",
"{",
"// If this slot is at the start of a sequence, transfer the indexNew",
"if",
"(",
"slot",
".",
"firstInSequence",
")",
"{",
"var",
"indexNew",
";",
"if",
"(",
"indexDelta",
"<",
"0",
")",
"{",
"// The given slot is about to be removed",
"indexNew",
"=",
"slot",
".",
"indexNew",
";",
"if",
"(",
"indexNew",
"!==",
"undefined",
")",
"{",
"delete",
"slot",
".",
"indexNew",
";",
"}",
"else",
"{",
"indexNew",
"=",
"slot",
".",
"index",
";",
"}",
"if",
"(",
"!",
"slot",
".",
"lastInSequence",
")",
"{",
"// Update the next slot now",
"slot",
"=",
"slot",
".",
"next",
";",
"if",
"(",
"indexNew",
"!==",
"undefined",
")",
"{",
"slot",
".",
"indexNew",
"=",
"indexNew",
";",
"}",
"}",
"}",
"else",
"{",
"// The given slot was just inserted",
"if",
"(",
"!",
"slot",
".",
"lastInSequence",
")",
"{",
"var",
"slotNext",
"=",
"slot",
".",
"next",
";",
"indexNew",
"=",
"slotNext",
".",
"indexNew",
";",
"if",
"(",
"indexNew",
"!==",
"undefined",
")",
"{",
"delete",
"slotNext",
".",
"indexNew",
";",
"}",
"else",
"{",
"indexNew",
"=",
"slotNext",
".",
"index",
";",
"}",
"if",
"(",
"indexNew",
"!==",
"undefined",
")",
"{",
"slot",
".",
"indexNew",
"=",
"indexNew",
";",
"}",
"}",
"}",
"}",
"updateNewIndicesAfterSlot",
"(",
"slot",
",",
"indexDelta",
")",
";",
"}"
] |
Updates the new index of the given slot if necessary, and all subsequent new indices
|
[
"Updates",
"the",
"new",
"index",
"of",
"the",
"given",
"slot",
"if",
"necessary",
"and",
"all",
"subsequent",
"new",
"indices"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L1001-L1042
|
16,387
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
updateNewIndicesFromIndex
|
function updateNewIndicesFromIndex(index, indexDelta) {
for (var slot = slotsStart; slot !== slotListEnd; slot = slot.next) {
var indexNew = slot.indexNew;
if (indexNew !== undefined && index <= indexNew) {
updateNewIndicesAfterSlot(slot, indexDelta);
break;
}
}
}
|
javascript
|
function updateNewIndicesFromIndex(index, indexDelta) {
for (var slot = slotsStart; slot !== slotListEnd; slot = slot.next) {
var indexNew = slot.indexNew;
if (indexNew !== undefined && index <= indexNew) {
updateNewIndicesAfterSlot(slot, indexDelta);
break;
}
}
}
|
[
"function",
"updateNewIndicesFromIndex",
"(",
"index",
",",
"indexDelta",
")",
"{",
"for",
"(",
"var",
"slot",
"=",
"slotsStart",
";",
"slot",
"!==",
"slotListEnd",
";",
"slot",
"=",
"slot",
".",
"next",
")",
"{",
"var",
"indexNew",
"=",
"slot",
".",
"indexNew",
";",
"if",
"(",
"indexNew",
"!==",
"undefined",
"&&",
"index",
"<=",
"indexNew",
")",
"{",
"updateNewIndicesAfterSlot",
"(",
"slot",
",",
"indexDelta",
")",
";",
"break",
";",
"}",
"}",
"}"
] |
Updates the new index of the first slot in each sequence after the given new index
|
[
"Updates",
"the",
"new",
"index",
"of",
"the",
"first",
"slot",
"in",
"each",
"sequence",
"after",
"the",
"given",
"new",
"index"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L1045-L1054
|
16,388
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
updateIndices
|
function updateIndices() {
var slot,
slotFirstInSequence,
indexNew;
for (slot = slotsStart; ; slot = slot.next) {
if (slot.firstInSequence) {
slotFirstInSequence = slot;
if (slot.indexNew !== undefined) {
indexNew = slot.indexNew;
delete slot.indexNew;
if (isNaN(indexNew)) {
break;
}
} else {
indexNew = slot.index;
}
// See if this sequence should be merged with the previous one
if (slot !== slotsStart && slot.prev.index === indexNew - 1) {
mergeSequences(slot.prev);
}
}
if (slot.lastInSequence) {
var index = indexNew;
for (var slotUpdate = slotFirstInSequence; slotUpdate !== slot.next; slotUpdate = slotUpdate.next) {
if (index !== slotUpdate.index) {
changeSlotIndex(slotUpdate, index);
}
if (+index === index) {
index++;
}
}
}
if (slot === slotListEnd) {
break;
}
}
// Clear any indices on slots that were moved adjacent to slots without indices
for (; slot !== slotsEnd; slot = slot.next) {
if (slot.index !== undefined && slot !== slotListEnd) {
changeSlotIndex(slot, undefined);
}
}
indexUpdateDeferred = false;
if (countDelta && +knownCount === knownCount) {
if (getCountPromise) {
getCountPromise.reset();
} else {
changeCount(knownCount + countDelta);
}
countDelta = 0;
}
}
|
javascript
|
function updateIndices() {
var slot,
slotFirstInSequence,
indexNew;
for (slot = slotsStart; ; slot = slot.next) {
if (slot.firstInSequence) {
slotFirstInSequence = slot;
if (slot.indexNew !== undefined) {
indexNew = slot.indexNew;
delete slot.indexNew;
if (isNaN(indexNew)) {
break;
}
} else {
indexNew = slot.index;
}
// See if this sequence should be merged with the previous one
if (slot !== slotsStart && slot.prev.index === indexNew - 1) {
mergeSequences(slot.prev);
}
}
if (slot.lastInSequence) {
var index = indexNew;
for (var slotUpdate = slotFirstInSequence; slotUpdate !== slot.next; slotUpdate = slotUpdate.next) {
if (index !== slotUpdate.index) {
changeSlotIndex(slotUpdate, index);
}
if (+index === index) {
index++;
}
}
}
if (slot === slotListEnd) {
break;
}
}
// Clear any indices on slots that were moved adjacent to slots without indices
for (; slot !== slotsEnd; slot = slot.next) {
if (slot.index !== undefined && slot !== slotListEnd) {
changeSlotIndex(slot, undefined);
}
}
indexUpdateDeferred = false;
if (countDelta && +knownCount === knownCount) {
if (getCountPromise) {
getCountPromise.reset();
} else {
changeCount(knownCount + countDelta);
}
countDelta = 0;
}
}
|
[
"function",
"updateIndices",
"(",
")",
"{",
"var",
"slot",
",",
"slotFirstInSequence",
",",
"indexNew",
";",
"for",
"(",
"slot",
"=",
"slotsStart",
";",
";",
"slot",
"=",
"slot",
".",
"next",
")",
"{",
"if",
"(",
"slot",
".",
"firstInSequence",
")",
"{",
"slotFirstInSequence",
"=",
"slot",
";",
"if",
"(",
"slot",
".",
"indexNew",
"!==",
"undefined",
")",
"{",
"indexNew",
"=",
"slot",
".",
"indexNew",
";",
"delete",
"slot",
".",
"indexNew",
";",
"if",
"(",
"isNaN",
"(",
"indexNew",
")",
")",
"{",
"break",
";",
"}",
"}",
"else",
"{",
"indexNew",
"=",
"slot",
".",
"index",
";",
"}",
"// See if this sequence should be merged with the previous one",
"if",
"(",
"slot",
"!==",
"slotsStart",
"&&",
"slot",
".",
"prev",
".",
"index",
"===",
"indexNew",
"-",
"1",
")",
"{",
"mergeSequences",
"(",
"slot",
".",
"prev",
")",
";",
"}",
"}",
"if",
"(",
"slot",
".",
"lastInSequence",
")",
"{",
"var",
"index",
"=",
"indexNew",
";",
"for",
"(",
"var",
"slotUpdate",
"=",
"slotFirstInSequence",
";",
"slotUpdate",
"!==",
"slot",
".",
"next",
";",
"slotUpdate",
"=",
"slotUpdate",
".",
"next",
")",
"{",
"if",
"(",
"index",
"!==",
"slotUpdate",
".",
"index",
")",
"{",
"changeSlotIndex",
"(",
"slotUpdate",
",",
"index",
")",
";",
"}",
"if",
"(",
"+",
"index",
"===",
"index",
")",
"{",
"index",
"++",
";",
"}",
"}",
"}",
"if",
"(",
"slot",
"===",
"slotListEnd",
")",
"{",
"break",
";",
"}",
"}",
"// Clear any indices on slots that were moved adjacent to slots without indices",
"for",
"(",
";",
"slot",
"!==",
"slotsEnd",
";",
"slot",
"=",
"slot",
".",
"next",
")",
"{",
"if",
"(",
"slot",
".",
"index",
"!==",
"undefined",
"&&",
"slot",
"!==",
"slotListEnd",
")",
"{",
"changeSlotIndex",
"(",
"slot",
",",
"undefined",
")",
";",
"}",
"}",
"indexUpdateDeferred",
"=",
"false",
";",
"if",
"(",
"countDelta",
"&&",
"+",
"knownCount",
"===",
"knownCount",
")",
"{",
"if",
"(",
"getCountPromise",
")",
"{",
"getCountPromise",
".",
"reset",
"(",
")",
";",
"}",
"else",
"{",
"changeCount",
"(",
"knownCount",
"+",
"countDelta",
")",
";",
"}",
"countDelta",
"=",
"0",
";",
"}",
"}"
] |
Adjust the indices of all slots to be consistent with any indexNew properties, and strip off the indexNews
|
[
"Adjust",
"the",
"indices",
"of",
"all",
"slots",
"to",
"be",
"consistent",
"with",
"any",
"indexNew",
"properties",
"and",
"strip",
"off",
"the",
"indexNews"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L1057-L1116
|
16,389
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
addMarkers
|
function addMarkers(fetchResult) {
var items = fetchResult.items,
offset = fetchResult.offset,
totalCount = fetchResult.totalCount,
absoluteIndex = fetchResult.absoluteIndex,
atStart = fetchResult.atStart,
atEnd = fetchResult.atEnd;
if (isNonNegativeNumber(absoluteIndex)) {
if (isNonNegativeNumber(totalCount)) {
var itemsLength = items.length;
if (absoluteIndex - offset + itemsLength === totalCount) {
atEnd = true;
}
}
if (offset === absoluteIndex) {
atStart = true;
}
}
if (atStart) {
items.unshift(startMarker);
fetchResult.offset++;
}
if (atEnd) {
items.push(endMarker);
}
}
|
javascript
|
function addMarkers(fetchResult) {
var items = fetchResult.items,
offset = fetchResult.offset,
totalCount = fetchResult.totalCount,
absoluteIndex = fetchResult.absoluteIndex,
atStart = fetchResult.atStart,
atEnd = fetchResult.atEnd;
if (isNonNegativeNumber(absoluteIndex)) {
if (isNonNegativeNumber(totalCount)) {
var itemsLength = items.length;
if (absoluteIndex - offset + itemsLength === totalCount) {
atEnd = true;
}
}
if (offset === absoluteIndex) {
atStart = true;
}
}
if (atStart) {
items.unshift(startMarker);
fetchResult.offset++;
}
if (atEnd) {
items.push(endMarker);
}
}
|
[
"function",
"addMarkers",
"(",
"fetchResult",
")",
"{",
"var",
"items",
"=",
"fetchResult",
".",
"items",
",",
"offset",
"=",
"fetchResult",
".",
"offset",
",",
"totalCount",
"=",
"fetchResult",
".",
"totalCount",
",",
"absoluteIndex",
"=",
"fetchResult",
".",
"absoluteIndex",
",",
"atStart",
"=",
"fetchResult",
".",
"atStart",
",",
"atEnd",
"=",
"fetchResult",
".",
"atEnd",
";",
"if",
"(",
"isNonNegativeNumber",
"(",
"absoluteIndex",
")",
")",
"{",
"if",
"(",
"isNonNegativeNumber",
"(",
"totalCount",
")",
")",
"{",
"var",
"itemsLength",
"=",
"items",
".",
"length",
";",
"if",
"(",
"absoluteIndex",
"-",
"offset",
"+",
"itemsLength",
"===",
"totalCount",
")",
"{",
"atEnd",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"offset",
"===",
"absoluteIndex",
")",
"{",
"atStart",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"atStart",
")",
"{",
"items",
".",
"unshift",
"(",
"startMarker",
")",
";",
"fetchResult",
".",
"offset",
"++",
";",
"}",
"if",
"(",
"atEnd",
")",
"{",
"items",
".",
"push",
"(",
"endMarker",
")",
";",
"}",
"}"
] |
Adds markers on behalf of the data adapter if their presence can be deduced
|
[
"Adds",
"markers",
"on",
"behalf",
"of",
"the",
"data",
"adapter",
"if",
"their",
"presence",
"can",
"be",
"deduced"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L1433-L1462
|
16,390
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
itemChanged
|
function itemChanged(slot) {
var itemNew = slot.itemNew;
if (!itemNew) {
return false;
}
var item = slot.item;
for (var property in item) {
switch (property) {
case "data":
// This is handled below
break;
default:
if (item[property] !== itemNew[property]) {
return true;
}
break;
}
}
return (
listDataAdapter.compareByIdentity ?
item.data !== itemNew.data :
slot.signature !== itemSignature(itemNew)
);
}
|
javascript
|
function itemChanged(slot) {
var itemNew = slot.itemNew;
if (!itemNew) {
return false;
}
var item = slot.item;
for (var property in item) {
switch (property) {
case "data":
// This is handled below
break;
default:
if (item[property] !== itemNew[property]) {
return true;
}
break;
}
}
return (
listDataAdapter.compareByIdentity ?
item.data !== itemNew.data :
slot.signature !== itemSignature(itemNew)
);
}
|
[
"function",
"itemChanged",
"(",
"slot",
")",
"{",
"var",
"itemNew",
"=",
"slot",
".",
"itemNew",
";",
"if",
"(",
"!",
"itemNew",
")",
"{",
"return",
"false",
";",
"}",
"var",
"item",
"=",
"slot",
".",
"item",
";",
"for",
"(",
"var",
"property",
"in",
"item",
")",
"{",
"switch",
"(",
"property",
")",
"{",
"case",
"\"data\"",
":",
"// This is handled below",
"break",
";",
"default",
":",
"if",
"(",
"item",
"[",
"property",
"]",
"!==",
"itemNew",
"[",
"property",
"]",
")",
"{",
"return",
"true",
";",
"}",
"break",
";",
"}",
"}",
"return",
"(",
"listDataAdapter",
".",
"compareByIdentity",
"?",
"item",
".",
"data",
"!==",
"itemNew",
".",
"data",
":",
"slot",
".",
"signature",
"!==",
"itemSignature",
"(",
"itemNew",
")",
")",
";",
"}"
] |
Fetch Result Processing
|
[
"Fetch",
"Result",
"Processing"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L1726-L1754
|
16,391
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
removeMirageIndices
|
function removeMirageIndices(countMax, indexFirstKnown) {
var placeholdersAtEnd = 0;
function removePlaceholdersAfterSlot(slotRemoveAfter) {
for (var slot2 = slotListEnd.prev; !(slot2.index < countMax) && slot2 !== slotRemoveAfter;) {
var slotPrev2 = slot2.prev;
if (slot2.index !== undefined) {
deleteSlot(slot2, true);
}
slot2 = slotPrev2;
}
placeholdersAtEnd = 0;
}
for (var slot = slotListEnd.prev; !(slot.index < countMax) || placeholdersAtEnd > 0;) {
var slotPrev = slot.prev;
if (slot === slotsStart) {
removePlaceholdersAfterSlot(slotsStart);
break;
} else if (slot.key) {
if (slot.index >= countMax) {
beginRefresh();
return false;
} else if (slot.index >= indexFirstKnown) {
removePlaceholdersAfterSlot(slot);
} else {
if (itemsFromKey) {
fetchItemsFromKey(slot, 0, placeholdersAtEnd);
} else {
fetchItemsFromIndex(slot, 0, placeholdersAtEnd);
}
// Wait until the fetch has completed before doing anything
return false;
}
} else if (slot.indexRequested || slot.firstInSequence) {
removePlaceholdersAfterSlot(slotPrev);
} else {
placeholdersAtEnd++;
}
slot = slotPrev;
}
return true;
}
|
javascript
|
function removeMirageIndices(countMax, indexFirstKnown) {
var placeholdersAtEnd = 0;
function removePlaceholdersAfterSlot(slotRemoveAfter) {
for (var slot2 = slotListEnd.prev; !(slot2.index < countMax) && slot2 !== slotRemoveAfter;) {
var slotPrev2 = slot2.prev;
if (slot2.index !== undefined) {
deleteSlot(slot2, true);
}
slot2 = slotPrev2;
}
placeholdersAtEnd = 0;
}
for (var slot = slotListEnd.prev; !(slot.index < countMax) || placeholdersAtEnd > 0;) {
var slotPrev = slot.prev;
if (slot === slotsStart) {
removePlaceholdersAfterSlot(slotsStart);
break;
} else if (slot.key) {
if (slot.index >= countMax) {
beginRefresh();
return false;
} else if (slot.index >= indexFirstKnown) {
removePlaceholdersAfterSlot(slot);
} else {
if (itemsFromKey) {
fetchItemsFromKey(slot, 0, placeholdersAtEnd);
} else {
fetchItemsFromIndex(slot, 0, placeholdersAtEnd);
}
// Wait until the fetch has completed before doing anything
return false;
}
} else if (slot.indexRequested || slot.firstInSequence) {
removePlaceholdersAfterSlot(slotPrev);
} else {
placeholdersAtEnd++;
}
slot = slotPrev;
}
return true;
}
|
[
"function",
"removeMirageIndices",
"(",
"countMax",
",",
"indexFirstKnown",
")",
"{",
"var",
"placeholdersAtEnd",
"=",
"0",
";",
"function",
"removePlaceholdersAfterSlot",
"(",
"slotRemoveAfter",
")",
"{",
"for",
"(",
"var",
"slot2",
"=",
"slotListEnd",
".",
"prev",
";",
"!",
"(",
"slot2",
".",
"index",
"<",
"countMax",
")",
"&&",
"slot2",
"!==",
"slotRemoveAfter",
";",
")",
"{",
"var",
"slotPrev2",
"=",
"slot2",
".",
"prev",
";",
"if",
"(",
"slot2",
".",
"index",
"!==",
"undefined",
")",
"{",
"deleteSlot",
"(",
"slot2",
",",
"true",
")",
";",
"}",
"slot2",
"=",
"slotPrev2",
";",
"}",
"placeholdersAtEnd",
"=",
"0",
";",
"}",
"for",
"(",
"var",
"slot",
"=",
"slotListEnd",
".",
"prev",
";",
"!",
"(",
"slot",
".",
"index",
"<",
"countMax",
")",
"||",
"placeholdersAtEnd",
">",
"0",
";",
")",
"{",
"var",
"slotPrev",
"=",
"slot",
".",
"prev",
";",
"if",
"(",
"slot",
"===",
"slotsStart",
")",
"{",
"removePlaceholdersAfterSlot",
"(",
"slotsStart",
")",
";",
"break",
";",
"}",
"else",
"if",
"(",
"slot",
".",
"key",
")",
"{",
"if",
"(",
"slot",
".",
"index",
">=",
"countMax",
")",
"{",
"beginRefresh",
"(",
")",
";",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"slot",
".",
"index",
">=",
"indexFirstKnown",
")",
"{",
"removePlaceholdersAfterSlot",
"(",
"slot",
")",
";",
"}",
"else",
"{",
"if",
"(",
"itemsFromKey",
")",
"{",
"fetchItemsFromKey",
"(",
"slot",
",",
"0",
",",
"placeholdersAtEnd",
")",
";",
"}",
"else",
"{",
"fetchItemsFromIndex",
"(",
"slot",
",",
"0",
",",
"placeholdersAtEnd",
")",
";",
"}",
"// Wait until the fetch has completed before doing anything",
"return",
"false",
";",
"}",
"}",
"else",
"if",
"(",
"slot",
".",
"indexRequested",
"||",
"slot",
".",
"firstInSequence",
")",
"{",
"removePlaceholdersAfterSlot",
"(",
"slotPrev",
")",
";",
"}",
"else",
"{",
"placeholdersAtEnd",
"++",
";",
"}",
"slot",
"=",
"slotPrev",
";",
"}",
"return",
"true",
";",
"}"
] |
Removes any placeholders with indices that exceed the given upper bound on the count
|
[
"Removes",
"any",
"placeholders",
"with",
"indices",
"that",
"exceed",
"the",
"given",
"upper",
"bound",
"on",
"the",
"count"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L2100-L2147
|
16,392
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
lastRefreshInsertionPoint
|
function lastRefreshInsertionPoint() {
var slotNext = refreshEnd;
while (!slotNext.firstInSequence) {
slotNext = slotNext.prev;
if (slotNext === refreshStart) {
return null;
}
}
return slotNext;
}
|
javascript
|
function lastRefreshInsertionPoint() {
var slotNext = refreshEnd;
while (!slotNext.firstInSequence) {
slotNext = slotNext.prev;
if (slotNext === refreshStart) {
return null;
}
}
return slotNext;
}
|
[
"function",
"lastRefreshInsertionPoint",
"(",
")",
"{",
"var",
"slotNext",
"=",
"refreshEnd",
";",
"while",
"(",
"!",
"slotNext",
".",
"firstInSequence",
")",
"{",
"slotNext",
"=",
"slotNext",
".",
"prev",
";",
"if",
"(",
"slotNext",
"===",
"refreshStart",
")",
"{",
"return",
"null",
";",
"}",
"}",
"return",
"slotNext",
";",
"}"
] |
Returns the slot after the last insertion point between sequences
|
[
"Returns",
"the",
"slot",
"after",
"the",
"last",
"insertion",
"point",
"between",
"sequences"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L2934-L2945
|
16,393
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
queueEdit
|
function queueEdit(applyEdit, editType, complete, error, keyUpdate, updateSlots, undo) {
var editQueueTail = editQueue.prev,
edit = {
prev: editQueueTail,
next: editQueue,
applyEdit: applyEdit,
editType: editType,
complete: complete,
error: error,
keyUpdate: keyUpdate
};
editQueueTail.next = edit;
editQueue.prev = edit;
editsQueued = true;
// If there's a refresh in progress, abandon it, but request that a new one be started once the edits complete
if (refreshRequested || refreshInProgress) {
currentRefreshID++;
refreshInProgress = false;
refreshRequested = true;
}
if (editQueue.next === edit) {
// Attempt the edit immediately, in case it completes synchronously
applyNextEdit();
}
// If the edit succeeded or is still pending, apply it to the slots (in the latter case, "optimistically")
if (!edit.failed) {
updateSlots();
// Supply the undo function now
edit.undo = undo;
}
if (!editsInProgress) {
completeEdits();
}
}
|
javascript
|
function queueEdit(applyEdit, editType, complete, error, keyUpdate, updateSlots, undo) {
var editQueueTail = editQueue.prev,
edit = {
prev: editQueueTail,
next: editQueue,
applyEdit: applyEdit,
editType: editType,
complete: complete,
error: error,
keyUpdate: keyUpdate
};
editQueueTail.next = edit;
editQueue.prev = edit;
editsQueued = true;
// If there's a refresh in progress, abandon it, but request that a new one be started once the edits complete
if (refreshRequested || refreshInProgress) {
currentRefreshID++;
refreshInProgress = false;
refreshRequested = true;
}
if (editQueue.next === edit) {
// Attempt the edit immediately, in case it completes synchronously
applyNextEdit();
}
// If the edit succeeded or is still pending, apply it to the slots (in the latter case, "optimistically")
if (!edit.failed) {
updateSlots();
// Supply the undo function now
edit.undo = undo;
}
if (!editsInProgress) {
completeEdits();
}
}
|
[
"function",
"queueEdit",
"(",
"applyEdit",
",",
"editType",
",",
"complete",
",",
"error",
",",
"keyUpdate",
",",
"updateSlots",
",",
"undo",
")",
"{",
"var",
"editQueueTail",
"=",
"editQueue",
".",
"prev",
",",
"edit",
"=",
"{",
"prev",
":",
"editQueueTail",
",",
"next",
":",
"editQueue",
",",
"applyEdit",
":",
"applyEdit",
",",
"editType",
":",
"editType",
",",
"complete",
":",
"complete",
",",
"error",
":",
"error",
",",
"keyUpdate",
":",
"keyUpdate",
"}",
";",
"editQueueTail",
".",
"next",
"=",
"edit",
";",
"editQueue",
".",
"prev",
"=",
"edit",
";",
"editsQueued",
"=",
"true",
";",
"// If there's a refresh in progress, abandon it, but request that a new one be started once the edits complete",
"if",
"(",
"refreshRequested",
"||",
"refreshInProgress",
")",
"{",
"currentRefreshID",
"++",
";",
"refreshInProgress",
"=",
"false",
";",
"refreshRequested",
"=",
"true",
";",
"}",
"if",
"(",
"editQueue",
".",
"next",
"===",
"edit",
")",
"{",
"// Attempt the edit immediately, in case it completes synchronously",
"applyNextEdit",
"(",
")",
";",
"}",
"// If the edit succeeded or is still pending, apply it to the slots (in the latter case, \"optimistically\")",
"if",
"(",
"!",
"edit",
".",
"failed",
")",
"{",
"updateSlots",
"(",
")",
";",
"// Supply the undo function now",
"edit",
".",
"undo",
"=",
"undo",
";",
"}",
"if",
"(",
"!",
"editsInProgress",
")",
"{",
"completeEdits",
"(",
")",
";",
"}",
"}"
] |
Edit Queue Queues an edit and immediately "optimistically" apply it to the slots list, sending re-entrant notifications
|
[
"Edit",
"Queue",
"Queues",
"an",
"edit",
"and",
"immediately",
"optimistically",
"apply",
"it",
"to",
"the",
"slots",
"list",
"sending",
"re",
"-",
"entrant",
"notifications"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L4145-L4183
|
16,394
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
discardEditQueue
|
function discardEditQueue() {
while (editQueue.prev !== editQueue) {
var editLast = editQueue.prev;
if (editLast.error) {
editLast.error(new _ErrorFromName(EditError.canceled));
}
// Edits that haven't been applied to the slots yet don't need to be undone
if (editLast.undo && !refreshRequested) {
editLast.undo();
}
editQueue.prev = editLast.prev;
}
editQueue.next = editQueue;
editsInProgress = false;
completeEdits();
}
|
javascript
|
function discardEditQueue() {
while (editQueue.prev !== editQueue) {
var editLast = editQueue.prev;
if (editLast.error) {
editLast.error(new _ErrorFromName(EditError.canceled));
}
// Edits that haven't been applied to the slots yet don't need to be undone
if (editLast.undo && !refreshRequested) {
editLast.undo();
}
editQueue.prev = editLast.prev;
}
editQueue.next = editQueue;
editsInProgress = false;
completeEdits();
}
|
[
"function",
"discardEditQueue",
"(",
")",
"{",
"while",
"(",
"editQueue",
".",
"prev",
"!==",
"editQueue",
")",
"{",
"var",
"editLast",
"=",
"editQueue",
".",
"prev",
";",
"if",
"(",
"editLast",
".",
"error",
")",
"{",
"editLast",
".",
"error",
"(",
"new",
"_ErrorFromName",
"(",
"EditError",
".",
"canceled",
")",
")",
";",
"}",
"// Edits that haven't been applied to the slots yet don't need to be undone",
"if",
"(",
"editLast",
".",
"undo",
"&&",
"!",
"refreshRequested",
")",
"{",
"editLast",
".",
"undo",
"(",
")",
";",
"}",
"editQueue",
".",
"prev",
"=",
"editLast",
".",
"prev",
";",
"}",
"editQueue",
".",
"next",
"=",
"editQueue",
";",
"editsInProgress",
"=",
"false",
";",
"completeEdits",
"(",
")",
";",
"}"
] |
Undo all queued edits, starting with the most recent
|
[
"Undo",
"all",
"queued",
"edits",
"starting",
"with",
"the",
"most",
"recent"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L4195-L4215
|
16,395
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
concludeEdits
|
function concludeEdits() {
editsQueued = false;
if (listDataAdapter.endEdits && beginEditsCalled && !editsInProgress) {
beginEditsCalled = false;
listDataAdapter.endEdits();
}
// See if there's a refresh that needs to begin
if (refreshRequested) {
refreshRequested = false;
beginRefresh();
} else {
// Otherwise, see if anything needs to be fetched
postFetch();
}
}
|
javascript
|
function concludeEdits() {
editsQueued = false;
if (listDataAdapter.endEdits && beginEditsCalled && !editsInProgress) {
beginEditsCalled = false;
listDataAdapter.endEdits();
}
// See if there's a refresh that needs to begin
if (refreshRequested) {
refreshRequested = false;
beginRefresh();
} else {
// Otherwise, see if anything needs to be fetched
postFetch();
}
}
|
[
"function",
"concludeEdits",
"(",
")",
"{",
"editsQueued",
"=",
"false",
";",
"if",
"(",
"listDataAdapter",
".",
"endEdits",
"&&",
"beginEditsCalled",
"&&",
"!",
"editsInProgress",
")",
"{",
"beginEditsCalled",
"=",
"false",
";",
"listDataAdapter",
".",
"endEdits",
"(",
")",
";",
"}",
"// See if there's a refresh that needs to begin",
"if",
"(",
"refreshRequested",
")",
"{",
"refreshRequested",
"=",
"false",
";",
"beginRefresh",
"(",
")",
";",
"}",
"else",
"{",
"// Otherwise, see if anything needs to be fetched",
"postFetch",
"(",
")",
";",
"}",
"}"
] |
Once the edit queue has emptied, update state appropriately and resume normal operation
|
[
"Once",
"the",
"edit",
"queue",
"has",
"emptied",
"update",
"state",
"appropriately",
"and",
"resume",
"normal",
"operation"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L4363-L4379
|
16,396
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
function (incomingPromise, dataSource) {
var signal = new _Signal();
incomingPromise.then(
function (v) { signal.complete(v); },
function (e) { signal.error(e); }
);
var resultPromise = signal.promise.then(null, function (e) {
if (e.name === "WinJS.UI.VirtualizedDataSource.resetCount") {
getCountPromise = null;
return incomingPromise = dataSource.getCount();
}
return Promise.wrapError(e);
});
var count = 0;
var currentGetCountPromise = {
get: function () {
count++;
return new Promise(
function (c, e) { resultPromise.then(c, e); },
function () {
if (--count === 0) {
// when the count reaches zero cancel the incoming promise
signal.promise.cancel();
incomingPromise.cancel();
if (currentGetCountPromise === getCountPromise) {
getCountPromise = null;
}
}
}
);
},
reset: function () {
signal.error(new _ErrorFromName("WinJS.UI.VirtualizedDataSource.resetCount"));
},
cancel: function () {
// if explicitly asked to cancel the incoming promise
signal.promise.cancel();
incomingPromise.cancel();
if (currentGetCountPromise === getCountPromise) {
getCountPromise = null;
}
}
};
return currentGetCountPromise;
}
|
javascript
|
function (incomingPromise, dataSource) {
var signal = new _Signal();
incomingPromise.then(
function (v) { signal.complete(v); },
function (e) { signal.error(e); }
);
var resultPromise = signal.promise.then(null, function (e) {
if (e.name === "WinJS.UI.VirtualizedDataSource.resetCount") {
getCountPromise = null;
return incomingPromise = dataSource.getCount();
}
return Promise.wrapError(e);
});
var count = 0;
var currentGetCountPromise = {
get: function () {
count++;
return new Promise(
function (c, e) { resultPromise.then(c, e); },
function () {
if (--count === 0) {
// when the count reaches zero cancel the incoming promise
signal.promise.cancel();
incomingPromise.cancel();
if (currentGetCountPromise === getCountPromise) {
getCountPromise = null;
}
}
}
);
},
reset: function () {
signal.error(new _ErrorFromName("WinJS.UI.VirtualizedDataSource.resetCount"));
},
cancel: function () {
// if explicitly asked to cancel the incoming promise
signal.promise.cancel();
incomingPromise.cancel();
if (currentGetCountPromise === getCountPromise) {
getCountPromise = null;
}
}
};
return currentGetCountPromise;
}
|
[
"function",
"(",
"incomingPromise",
",",
"dataSource",
")",
"{",
"var",
"signal",
"=",
"new",
"_Signal",
"(",
")",
";",
"incomingPromise",
".",
"then",
"(",
"function",
"(",
"v",
")",
"{",
"signal",
".",
"complete",
"(",
"v",
")",
";",
"}",
",",
"function",
"(",
"e",
")",
"{",
"signal",
".",
"error",
"(",
"e",
")",
";",
"}",
")",
";",
"var",
"resultPromise",
"=",
"signal",
".",
"promise",
".",
"then",
"(",
"null",
",",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"e",
".",
"name",
"===",
"\"WinJS.UI.VirtualizedDataSource.resetCount\"",
")",
"{",
"getCountPromise",
"=",
"null",
";",
"return",
"incomingPromise",
"=",
"dataSource",
".",
"getCount",
"(",
")",
";",
"}",
"return",
"Promise",
".",
"wrapError",
"(",
"e",
")",
";",
"}",
")",
";",
"var",
"count",
"=",
"0",
";",
"var",
"currentGetCountPromise",
"=",
"{",
"get",
":",
"function",
"(",
")",
"{",
"count",
"++",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"c",
",",
"e",
")",
"{",
"resultPromise",
".",
"then",
"(",
"c",
",",
"e",
")",
";",
"}",
",",
"function",
"(",
")",
"{",
"if",
"(",
"--",
"count",
"===",
"0",
")",
"{",
"// when the count reaches zero cancel the incoming promise",
"signal",
".",
"promise",
".",
"cancel",
"(",
")",
";",
"incomingPromise",
".",
"cancel",
"(",
")",
";",
"if",
"(",
"currentGetCountPromise",
"===",
"getCountPromise",
")",
"{",
"getCountPromise",
"=",
"null",
";",
"}",
"}",
"}",
")",
";",
"}",
",",
"reset",
":",
"function",
"(",
")",
"{",
"signal",
".",
"error",
"(",
"new",
"_ErrorFromName",
"(",
"\"WinJS.UI.VirtualizedDataSource.resetCount\"",
")",
")",
";",
"}",
",",
"cancel",
":",
"function",
"(",
")",
"{",
"// if explicitly asked to cancel the incoming promise",
"signal",
".",
"promise",
".",
"cancel",
"(",
")",
";",
"incomingPromise",
".",
"cancel",
"(",
")",
";",
"if",
"(",
"currentGetCountPromise",
"===",
"getCountPromise",
")",
"{",
"getCountPromise",
"=",
"null",
";",
"}",
"}",
"}",
";",
"return",
"currentGetCountPromise",
";",
"}"
] |
Create a helper which issues new promises for the result of the input promise but have their cancelations ref-counted so that any given consumer canceling their promise doesn't result in the incoming promise being canceled unless all consumers are no longer interested in the result.
|
[
"Create",
"a",
"helper",
"which",
"issues",
"new",
"promises",
"for",
"the",
"result",
"of",
"the",
"input",
"promise",
"but",
"have",
"their",
"cancelations",
"ref",
"-",
"counted",
"so",
"that",
"any",
"given",
"consumer",
"canceling",
"their",
"promise",
"doesn",
"t",
"result",
"in",
"the",
"incoming",
"promise",
"being",
"canceled",
"unless",
"all",
"consumers",
"are",
"no",
"longer",
"interested",
"in",
"the",
"result",
"."
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L5441-L5485
|
|
16,397
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
ItemEventsHandler_toggleItemSelection
|
function ItemEventsHandler_toggleItemSelection(itemIndex) {
var site = this._site,
selection = site.selection,
selected = selection._isIncluded(itemIndex);
if (site.selectionMode === _UI.SelectionMode.single) {
if (!selected) {
selection.set(itemIndex);
} else {
selection.clear();
}
} else {
if (!selected) {
selection.add(itemIndex);
} else {
selection.remove(itemIndex);
}
}
}
|
javascript
|
function ItemEventsHandler_toggleItemSelection(itemIndex) {
var site = this._site,
selection = site.selection,
selected = selection._isIncluded(itemIndex);
if (site.selectionMode === _UI.SelectionMode.single) {
if (!selected) {
selection.set(itemIndex);
} else {
selection.clear();
}
} else {
if (!selected) {
selection.add(itemIndex);
} else {
selection.remove(itemIndex);
}
}
}
|
[
"function",
"ItemEventsHandler_toggleItemSelection",
"(",
"itemIndex",
")",
"{",
"var",
"site",
"=",
"this",
".",
"_site",
",",
"selection",
"=",
"site",
".",
"selection",
",",
"selected",
"=",
"selection",
".",
"_isIncluded",
"(",
"itemIndex",
")",
";",
"if",
"(",
"site",
".",
"selectionMode",
"===",
"_UI",
".",
"SelectionMode",
".",
"single",
")",
"{",
"if",
"(",
"!",
"selected",
")",
"{",
"selection",
".",
"set",
"(",
"itemIndex",
")",
";",
"}",
"else",
"{",
"selection",
".",
"clear",
"(",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"!",
"selected",
")",
"{",
"selection",
".",
"add",
"(",
"itemIndex",
")",
";",
"}",
"else",
"{",
"selection",
".",
"remove",
"(",
"itemIndex",
")",
";",
"}",
"}",
"}"
] |
In single selection mode, in addition to itemIndex's selection state being toggled, all other items will become deselected
|
[
"In",
"single",
"selection",
"mode",
"in",
"addition",
"to",
"itemIndex",
"s",
"selection",
"state",
"being",
"toggled",
"all",
"other",
"items",
"will",
"become",
"deselected"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L8499-L8517
|
16,398
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
function (groupKey, itemKey, itemIndex) {
this._lastFocusedItemKey = itemKey;
this._lastFocusedItemIndex = itemIndex;
itemIndex = "" + itemIndex;
this._itemToIndex[itemKey] = itemIndex;
this._groupToItem[groupKey] = itemKey;
}
|
javascript
|
function (groupKey, itemKey, itemIndex) {
this._lastFocusedItemKey = itemKey;
this._lastFocusedItemIndex = itemIndex;
itemIndex = "" + itemIndex;
this._itemToIndex[itemKey] = itemIndex;
this._groupToItem[groupKey] = itemKey;
}
|
[
"function",
"(",
"groupKey",
",",
"itemKey",
",",
"itemIndex",
")",
"{",
"this",
".",
"_lastFocusedItemKey",
"=",
"itemKey",
";",
"this",
".",
"_lastFocusedItemIndex",
"=",
"itemIndex",
";",
"itemIndex",
"=",
"\"\"",
"+",
"itemIndex",
";",
"this",
".",
"_itemToIndex",
"[",
"itemKey",
"]",
"=",
"itemIndex",
";",
"this",
".",
"_groupToItem",
"[",
"groupKey",
"]",
"=",
"itemKey",
";",
"}"
] |
We store indices as strings in the cache so index=0 does not evaluate to false as when we check for the existance of an index in the cache. The index is converted back into a number when calling getIndexForGroup
|
[
"We",
"store",
"indices",
"as",
"strings",
"in",
"the",
"cache",
"so",
"index",
"=",
"0",
"does",
"not",
"evaluate",
"to",
"false",
"as",
"when",
"we",
"check",
"for",
"the",
"existance",
"of",
"an",
"index",
"in",
"the",
"cache",
".",
"The",
"index",
"is",
"converted",
"back",
"into",
"a",
"number",
"when",
"calling",
"getIndexForGroup"
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L11052-L11058
|
|
16,399
|
sitewaerts/cordova-plugin-document-viewer
|
src/common/js/winjs/js/ui.js
|
flushDynamicCssRules
|
function flushDynamicCssRules() {
var rules = layoutStyleElem.sheet.cssRules,
classCount = staleClassNames.length,
i,
j,
ruleSuffix;
for (i = 0; i < classCount; i++) {
ruleSuffix = "." + staleClassNames[i] + " ";
for (j = rules.length - 1; j >= 0; j--) {
if (rules[j].selectorText.indexOf(ruleSuffix) !== -1) {
layoutStyleElem.sheet.deleteRule(j);
}
}
}
staleClassNames = [];
}
|
javascript
|
function flushDynamicCssRules() {
var rules = layoutStyleElem.sheet.cssRules,
classCount = staleClassNames.length,
i,
j,
ruleSuffix;
for (i = 0; i < classCount; i++) {
ruleSuffix = "." + staleClassNames[i] + " ";
for (j = rules.length - 1; j >= 0; j--) {
if (rules[j].selectorText.indexOf(ruleSuffix) !== -1) {
layoutStyleElem.sheet.deleteRule(j);
}
}
}
staleClassNames = [];
}
|
[
"function",
"flushDynamicCssRules",
"(",
")",
"{",
"var",
"rules",
"=",
"layoutStyleElem",
".",
"sheet",
".",
"cssRules",
",",
"classCount",
"=",
"staleClassNames",
".",
"length",
",",
"i",
",",
"j",
",",
"ruleSuffix",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"classCount",
";",
"i",
"++",
")",
"{",
"ruleSuffix",
"=",
"\".\"",
"+",
"staleClassNames",
"[",
"i",
"]",
"+",
"\" \"",
";",
"for",
"(",
"j",
"=",
"rules",
".",
"length",
"-",
"1",
";",
"j",
">=",
"0",
";",
"j",
"--",
")",
"{",
"if",
"(",
"rules",
"[",
"j",
"]",
".",
"selectorText",
".",
"indexOf",
"(",
"ruleSuffix",
")",
"!==",
"-",
"1",
")",
"{",
"layoutStyleElem",
".",
"sheet",
".",
"deleteRule",
"(",
"j",
")",
";",
"}",
"}",
"}",
"staleClassNames",
"=",
"[",
"]",
";",
"}"
] |
Removes the dynamic CSS rules corresponding to the classes in staleClassNames from the DOM.
|
[
"Removes",
"the",
"dynamic",
"CSS",
"rules",
"corresponding",
"to",
"the",
"classes",
"in",
"staleClassNames",
"from",
"the",
"DOM",
"."
] |
25b82d959c20d7880d513100c2b979e1e15349dc
|
https://github.com/sitewaerts/cordova-plugin-document-viewer/blob/25b82d959c20d7880d513100c2b979e1e15349dc/src/common/js/winjs/js/ui.js#L11968-L11984
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.