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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
13,400
|
jriecken/sat-js
|
examples/examples.js
|
function () {
if (this.data instanceof SAT.Circle) {
this.displayAttrs.cx = this.data.pos.x;
this.displayAttrs.cy = this.data.pos.y;
this.displayAttrs.r = this.data.r;
} else {
this.displayAttrs.path = poly2path(this.data);
}
this.display.attr(this.displayAttrs);
}
|
javascript
|
function () {
if (this.data instanceof SAT.Circle) {
this.displayAttrs.cx = this.data.pos.x;
this.displayAttrs.cy = this.data.pos.y;
this.displayAttrs.r = this.data.r;
} else {
this.displayAttrs.path = poly2path(this.data);
}
this.display.attr(this.displayAttrs);
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"data",
"instanceof",
"SAT",
".",
"Circle",
")",
"{",
"this",
".",
"displayAttrs",
".",
"cx",
"=",
"this",
".",
"data",
".",
"pos",
".",
"x",
";",
"this",
".",
"displayAttrs",
".",
"cy",
"=",
"this",
".",
"data",
".",
"pos",
".",
"y",
";",
"this",
".",
"displayAttrs",
".",
"r",
"=",
"this",
".",
"data",
".",
"r",
";",
"}",
"else",
"{",
"this",
".",
"displayAttrs",
".",
"path",
"=",
"poly2path",
"(",
"this",
".",
"data",
")",
";",
"}",
"this",
".",
"display",
".",
"attr",
"(",
"this",
".",
"displayAttrs",
")",
";",
"}"
] |
Call this to update the display after changing the underlying data.
|
[
"Call",
"this",
"to",
"update",
"the",
"display",
"after",
"changing",
"the",
"underlying",
"data",
"."
] |
4e06e0a81ae38d6630469d94beb1a46d7b5f74bb
|
https://github.com/jriecken/sat-js/blob/4e06e0a81ae38d6630469d94beb1a46d7b5f74bb/examples/examples.js#L73-L82
|
|
13,401
|
poppinss/indicative
|
src/core/starToIndex.js
|
starToIndex
|
function starToIndex (pairs, data, i, out) {
if (!data) {
return []
}
i = i || 0
let curr = pairs[i++]
const next = pairs[i]
/**
* When out is not defined, then start
* with the current node
*/
if (!out) {
out = [curr]
curr = ''
}
/**
* Keep on adding to the out array. The reason we call reduce
* operation, as we have to modify the existing keys inside
* the `out` array.
*/
out = out.reduce((result, existingNode) => {
const nName = curr ? `${existingNode}.${curr}` : existingNode
/**
* We pull childs when `next` is not undefined, otherwise
* we assume the end of `*` expression
*/
if (next !== undefined) {
const value = prop(data, nName)
if (Array.isArray(value)) {
const dataLength = value.length
for (let i = 0; i < dataLength; i++) {
result.push(`${nName}.${i}`)
}
}
} else {
result.push(nName)
}
return result
}, [])
/**
* Recursively call this method until we loop through the entire
* array.
*/
return i === pairs.length ? out : starToIndex(pairs, data, i, out)
}
|
javascript
|
function starToIndex (pairs, data, i, out) {
if (!data) {
return []
}
i = i || 0
let curr = pairs[i++]
const next = pairs[i]
/**
* When out is not defined, then start
* with the current node
*/
if (!out) {
out = [curr]
curr = ''
}
/**
* Keep on adding to the out array. The reason we call reduce
* operation, as we have to modify the existing keys inside
* the `out` array.
*/
out = out.reduce((result, existingNode) => {
const nName = curr ? `${existingNode}.${curr}` : existingNode
/**
* We pull childs when `next` is not undefined, otherwise
* we assume the end of `*` expression
*/
if (next !== undefined) {
const value = prop(data, nName)
if (Array.isArray(value)) {
const dataLength = value.length
for (let i = 0; i < dataLength; i++) {
result.push(`${nName}.${i}`)
}
}
} else {
result.push(nName)
}
return result
}, [])
/**
* Recursively call this method until we loop through the entire
* array.
*/
return i === pairs.length ? out : starToIndex(pairs, data, i, out)
}
|
[
"function",
"starToIndex",
"(",
"pairs",
",",
"data",
",",
"i",
",",
"out",
")",
"{",
"if",
"(",
"!",
"data",
")",
"{",
"return",
"[",
"]",
"}",
"i",
"=",
"i",
"||",
"0",
"let",
"curr",
"=",
"pairs",
"[",
"i",
"++",
"]",
"const",
"next",
"=",
"pairs",
"[",
"i",
"]",
"/**\n * When out is not defined, then start\n * with the current node\n */",
"if",
"(",
"!",
"out",
")",
"{",
"out",
"=",
"[",
"curr",
"]",
"curr",
"=",
"''",
"}",
"/**\n * Keep on adding to the out array. The reason we call reduce\n * operation, as we have to modify the existing keys inside\n * the `out` array.\n */",
"out",
"=",
"out",
".",
"reduce",
"(",
"(",
"result",
",",
"existingNode",
")",
"=>",
"{",
"const",
"nName",
"=",
"curr",
"?",
"`",
"${",
"existingNode",
"}",
"${",
"curr",
"}",
"`",
":",
"existingNode",
"/**\n * We pull childs when `next` is not undefined, otherwise\n * we assume the end of `*` expression\n */",
"if",
"(",
"next",
"!==",
"undefined",
")",
"{",
"const",
"value",
"=",
"prop",
"(",
"data",
",",
"nName",
")",
"if",
"(",
"Array",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"const",
"dataLength",
"=",
"value",
".",
"length",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"dataLength",
";",
"i",
"++",
")",
"{",
"result",
".",
"push",
"(",
"`",
"${",
"nName",
"}",
"${",
"i",
"}",
"`",
")",
"}",
"}",
"}",
"else",
"{",
"result",
".",
"push",
"(",
"nName",
")",
"}",
"return",
"result",
"}",
",",
"[",
"]",
")",
"/**\n * Recursively call this method until we loop through the entire\n * array.\n */",
"return",
"i",
"===",
"pairs",
".",
"length",
"?",
"out",
":",
"starToIndex",
"(",
"pairs",
",",
"data",
",",
"i",
",",
"out",
")",
"}"
] |
This method loops over an array and build properties based upon
values available inside the data object.
This method is supposed to never throw any exceptions, and instead
skip a property when data or pairs are not in right format.
@method starToIndex
@param {Array} pairs
@param {Object} data
@param {Number} i
@param {Out} out
@example
const pairs = ['users', 'username']
const data = { users: [ { username: 'foo' }, { username: 'bar' } ] }
startToIndex(pairs, data)
// output ['users.0.username', 'users.1.username']
|
[
"This",
"method",
"loops",
"over",
"an",
"array",
"and",
"build",
"properties",
"based",
"upon",
"values",
"available",
"inside",
"the",
"data",
"object",
"."
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/starToIndex.js#L35-L84
|
13,402
|
poppinss/indicative
|
src/core/pSeries.js
|
onRejected
|
function onRejected (error) {
return {
fullFilled: false,
rejected: true,
value: null,
reason: error
}
}
|
javascript
|
function onRejected (error) {
return {
fullFilled: false,
rejected: true,
value: null,
reason: error
}
}
|
[
"function",
"onRejected",
"(",
"error",
")",
"{",
"return",
"{",
"fullFilled",
":",
"false",
",",
"rejected",
":",
"true",
",",
"value",
":",
"null",
",",
"reason",
":",
"error",
"}",
"}"
] |
Returns an object containing enough info whether
the promises was rejected or not.
@method onRejected
@param {Object} error
@returns {Object}
|
[
"Returns",
"an",
"object",
"containing",
"enough",
"info",
"whether",
"the",
"promises",
"was",
"rejected",
"or",
"not",
"."
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/pSeries.js#L41-L48
|
13,403
|
poppinss/indicative
|
src/core/pSeries.js
|
pSeries
|
function pSeries (iterable, bail) {
const result = []
const iterableLength = iterable.length
function noop (index, bail) {
/**
* End of promises
*/
if (index >= iterableLength) {
return Promise.resolve(result)
}
return iterable[index]
.then((output) => {
result.push(onResolved(output))
return noop(index + 1, bail)
})
.catch((error) => {
result.push(onRejected(error))
/**
*
* When bail is false, we continue after rejections
* too.
*/
if (!bail) {
return noop(index + 1, bail)
}
/**
* Otherwise we resolve the promise
*/
return Promise.resolve(result)
})
}
return noop(0, bail)
}
|
javascript
|
function pSeries (iterable, bail) {
const result = []
const iterableLength = iterable.length
function noop (index, bail) {
/**
* End of promises
*/
if (index >= iterableLength) {
return Promise.resolve(result)
}
return iterable[index]
.then((output) => {
result.push(onResolved(output))
return noop(index + 1, bail)
})
.catch((error) => {
result.push(onRejected(error))
/**
*
* When bail is false, we continue after rejections
* too.
*/
if (!bail) {
return noop(index + 1, bail)
}
/**
* Otherwise we resolve the promise
*/
return Promise.resolve(result)
})
}
return noop(0, bail)
}
|
[
"function",
"pSeries",
"(",
"iterable",
",",
"bail",
")",
"{",
"const",
"result",
"=",
"[",
"]",
"const",
"iterableLength",
"=",
"iterable",
".",
"length",
"function",
"noop",
"(",
"index",
",",
"bail",
")",
"{",
"/**\n * End of promises\n */",
"if",
"(",
"index",
">=",
"iterableLength",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"result",
")",
"}",
"return",
"iterable",
"[",
"index",
"]",
".",
"then",
"(",
"(",
"output",
")",
"=>",
"{",
"result",
".",
"push",
"(",
"onResolved",
"(",
"output",
")",
")",
"return",
"noop",
"(",
"index",
"+",
"1",
",",
"bail",
")",
"}",
")",
".",
"catch",
"(",
"(",
"error",
")",
"=>",
"{",
"result",
".",
"push",
"(",
"onRejected",
"(",
"error",
")",
")",
"/**\n *\n * When bail is false, we continue after rejections\n * too.\n */",
"if",
"(",
"!",
"bail",
")",
"{",
"return",
"noop",
"(",
"index",
"+",
"1",
",",
"bail",
")",
"}",
"/**\n * Otherwise we resolve the promise\n */",
"return",
"Promise",
".",
"resolve",
"(",
"result",
")",
"}",
")",
"}",
"return",
"noop",
"(",
"0",
",",
"bail",
")",
"}"
] |
Here we run an array of promises in sequence until the last
promise is finished.
When `bail=true`, it will break the chain when first promise returns
the error/exception.
## Why serial?
Since the validations have to be executed one after the other, the
promises execution has to be in sequence
## Why wait for all promises?
The `validateAll` method of the library allows to run all validations,
even when they fail. So this method handles that too.
## Note
This method will never reject, instead returns an array of objects, which
has `rejected` and `fullFilled` properties to find whether the promise
was rejected or not.
@method pSeries
@param {Array} iterable
@param {Boolean} bail
@return {Object[]} result - Array of objects holding promises results
@property {Boolean} result.fullFilled
@property {Boolean} result.rejected
@property {Mixed} result.value - Resolved value if fullFilled
@property {Mixed} result.reason - Error value if rejected
@example
pSeries([p1, p2])
.then((result) => {
const errors = result.filter((item) => item.rejected)
if (errors.length) {
console.log(errors)
}
})
// stopping after first failure
pSeries([p1, p2], true)
.then((result) => {
const errors = result.filter((item) => item.rejected)
if (errors.length) {
console.log(errors[0])
}
})
|
[
"Here",
"we",
"run",
"an",
"array",
"of",
"promises",
"in",
"sequence",
"until",
"the",
"last",
"promise",
"is",
"finished",
"."
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/pSeries.js#L99-L136
|
13,404
|
poppinss/indicative
|
bin/qunit.js
|
start
|
async function start () {
let exitCode = 0
const port = process.env.PORT || 3000
console.log(chalk`{magenta creating app bundle}`)
/**
* Creating rollup bundle by bundling `test/qunit/index.js` file.
*/
const bundle = await rollup.rollup({
input: path.join(__dirname, '../test', 'qunit', 'index'),
plugins: require('../rollupPlugins')
})
const { code } = await bundle.generate({
file: path.join(__dirname, '../tmp', 'qunit.js'),
format: 'umd',
name: 'indicativeSpec'
})
const server = await sauceLabs.serve(qUnitTemplate(code), port)
console.log(chalk`started app server on {green http://localhost:${port}}`)
/**
* Starting the HTTP server. If `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY`
* env variables exists, we will run tests on sauce, otherwise
* we will run them on user machine.
*/
if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
console.log(chalk`{yellow pass SAUCE_USERNAME & SAUCE_ACCESS_KEY to run tests on saucelabs}`)
opn(`http://localhost:${port}`)
return
}
const ngrok = require('ngrok')
try {
/**
* Ngrok url
*/
const publicUrl = await sauceLabs.getPublicUrl(port)
console.log(chalk`started ngrok tunnel on {green ${publicUrl}}`)
/**
* Creating jobs with sauce labs
*/
const jobs = await sauceLabs.createTestsJob(browsers, publicUrl)
console.log(chalk`created {green ${jobs.length} jobs}`)
/**
* Monitoring jobs for results
*/
console.log(chalk`{magenta monitoring jobs}`)
const results = await sauceLabs.getJobsResult(jobs)
/**
* Got some results
*/
results.forEach((result) => {
console.log('')
console.log(chalk`{bold ${result.platform.join(' ')}}`)
console.log(chalk` {green Passed ${result.result.passed}}`)
console.log(chalk` {red Failed ${result.result.failed}}`)
console.log(` Total ${result.result.total}`)
})
/**
* Creating a new build to be annotated
*/
const buildId = `build-${new Date().getTime()}`
console.log('annotating jobs result')
for (let result of results) {
await sauceLabs.annotateJob(result.job_id, buildId, result.result.failed === 0)
}
console.log(chalk`{green done}`)
} catch (error) {
console.log(chalk` {red Reaceived error}`)
console.log(error)
exitCode = 1
}
/**
* Cleanup
*/
ngrok.kill()
server.close()
process.exit(exitCode)
}
|
javascript
|
async function start () {
let exitCode = 0
const port = process.env.PORT || 3000
console.log(chalk`{magenta creating app bundle}`)
/**
* Creating rollup bundle by bundling `test/qunit/index.js` file.
*/
const bundle = await rollup.rollup({
input: path.join(__dirname, '../test', 'qunit', 'index'),
plugins: require('../rollupPlugins')
})
const { code } = await bundle.generate({
file: path.join(__dirname, '../tmp', 'qunit.js'),
format: 'umd',
name: 'indicativeSpec'
})
const server = await sauceLabs.serve(qUnitTemplate(code), port)
console.log(chalk`started app server on {green http://localhost:${port}}`)
/**
* Starting the HTTP server. If `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY`
* env variables exists, we will run tests on sauce, otherwise
* we will run them on user machine.
*/
if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
console.log(chalk`{yellow pass SAUCE_USERNAME & SAUCE_ACCESS_KEY to run tests on saucelabs}`)
opn(`http://localhost:${port}`)
return
}
const ngrok = require('ngrok')
try {
/**
* Ngrok url
*/
const publicUrl = await sauceLabs.getPublicUrl(port)
console.log(chalk`started ngrok tunnel on {green ${publicUrl}}`)
/**
* Creating jobs with sauce labs
*/
const jobs = await sauceLabs.createTestsJob(browsers, publicUrl)
console.log(chalk`created {green ${jobs.length} jobs}`)
/**
* Monitoring jobs for results
*/
console.log(chalk`{magenta monitoring jobs}`)
const results = await sauceLabs.getJobsResult(jobs)
/**
* Got some results
*/
results.forEach((result) => {
console.log('')
console.log(chalk`{bold ${result.platform.join(' ')}}`)
console.log(chalk` {green Passed ${result.result.passed}}`)
console.log(chalk` {red Failed ${result.result.failed}}`)
console.log(` Total ${result.result.total}`)
})
/**
* Creating a new build to be annotated
*/
const buildId = `build-${new Date().getTime()}`
console.log('annotating jobs result')
for (let result of results) {
await sauceLabs.annotateJob(result.job_id, buildId, result.result.failed === 0)
}
console.log(chalk`{green done}`)
} catch (error) {
console.log(chalk` {red Reaceived error}`)
console.log(error)
exitCode = 1
}
/**
* Cleanup
*/
ngrok.kill()
server.close()
process.exit(exitCode)
}
|
[
"async",
"function",
"start",
"(",
")",
"{",
"let",
"exitCode",
"=",
"0",
"const",
"port",
"=",
"process",
".",
"env",
".",
"PORT",
"||",
"3000",
"console",
".",
"log",
"(",
"chalk",
"`",
"`",
")",
"/**\n * Creating rollup bundle by bundling `test/qunit/index.js` file.\n */",
"const",
"bundle",
"=",
"await",
"rollup",
".",
"rollup",
"(",
"{",
"input",
":",
"path",
".",
"join",
"(",
"__dirname",
",",
"'../test'",
",",
"'qunit'",
",",
"'index'",
")",
",",
"plugins",
":",
"require",
"(",
"'../rollupPlugins'",
")",
"}",
")",
"const",
"{",
"code",
"}",
"=",
"await",
"bundle",
".",
"generate",
"(",
"{",
"file",
":",
"path",
".",
"join",
"(",
"__dirname",
",",
"'../tmp'",
",",
"'qunit.js'",
")",
",",
"format",
":",
"'umd'",
",",
"name",
":",
"'indicativeSpec'",
"}",
")",
"const",
"server",
"=",
"await",
"sauceLabs",
".",
"serve",
"(",
"qUnitTemplate",
"(",
"code",
")",
",",
"port",
")",
"console",
".",
"log",
"(",
"chalk",
"`",
"${",
"port",
"}",
"`",
")",
"/**\n * Starting the HTTP server. If `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY`\n * env variables exists, we will run tests on sauce, otherwise\n * we will run them on user machine.\n */",
"if",
"(",
"!",
"process",
".",
"env",
".",
"SAUCE_USERNAME",
"||",
"!",
"process",
".",
"env",
".",
"SAUCE_ACCESS_KEY",
")",
"{",
"console",
".",
"log",
"(",
"chalk",
"`",
"`",
")",
"opn",
"(",
"`",
"${",
"port",
"}",
"`",
")",
"return",
"}",
"const",
"ngrok",
"=",
"require",
"(",
"'ngrok'",
")",
"try",
"{",
"/**\n * Ngrok url\n */",
"const",
"publicUrl",
"=",
"await",
"sauceLabs",
".",
"getPublicUrl",
"(",
"port",
")",
"console",
".",
"log",
"(",
"chalk",
"`",
"${",
"publicUrl",
"}",
"`",
")",
"/**\n * Creating jobs with sauce labs\n */",
"const",
"jobs",
"=",
"await",
"sauceLabs",
".",
"createTestsJob",
"(",
"browsers",
",",
"publicUrl",
")",
"console",
".",
"log",
"(",
"chalk",
"`",
"${",
"jobs",
".",
"length",
"}",
"`",
")",
"/**\n * Monitoring jobs for results\n */",
"console",
".",
"log",
"(",
"chalk",
"`",
"`",
")",
"const",
"results",
"=",
"await",
"sauceLabs",
".",
"getJobsResult",
"(",
"jobs",
")",
"/**\n * Got some results\n */",
"results",
".",
"forEach",
"(",
"(",
"result",
")",
"=>",
"{",
"console",
".",
"log",
"(",
"''",
")",
"console",
".",
"log",
"(",
"chalk",
"`",
"${",
"result",
".",
"platform",
".",
"join",
"(",
"' '",
")",
"}",
"`",
")",
"console",
".",
"log",
"(",
"chalk",
"`",
"${",
"result",
".",
"result",
".",
"passed",
"}",
"`",
")",
"console",
".",
"log",
"(",
"chalk",
"`",
"${",
"result",
".",
"result",
".",
"failed",
"}",
"`",
")",
"console",
".",
"log",
"(",
"`",
"${",
"result",
".",
"result",
".",
"total",
"}",
"`",
")",
"}",
")",
"/**\n * Creating a new build to be annotated\n */",
"const",
"buildId",
"=",
"`",
"${",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"}",
"`",
"console",
".",
"log",
"(",
"'annotating jobs result'",
")",
"for",
"(",
"let",
"result",
"of",
"results",
")",
"{",
"await",
"sauceLabs",
".",
"annotateJob",
"(",
"result",
".",
"job_id",
",",
"buildId",
",",
"result",
".",
"result",
".",
"failed",
"===",
"0",
")",
"}",
"console",
".",
"log",
"(",
"chalk",
"`",
"`",
")",
"}",
"catch",
"(",
"error",
")",
"{",
"console",
".",
"log",
"(",
"chalk",
"`",
"`",
")",
"console",
".",
"log",
"(",
"error",
")",
"exitCode",
"=",
"1",
"}",
"/**\n * Cleanup\n */",
"ngrok",
".",
"kill",
"(",
")",
"server",
".",
"close",
"(",
")",
"process",
".",
"exit",
"(",
"exitCode",
")",
"}"
] |
Start of the process
@method start
|
[
"Start",
"of",
"the",
"process"
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/bin/qunit.js#L79-L165
|
13,405
|
poppinss/indicative
|
src/core/configure.js
|
setConfig
|
function setConfig (options) {
Object.keys(options).forEach((option) => {
if (config[option] !== undefined) {
config[option] = options[option]
}
})
}
|
javascript
|
function setConfig (options) {
Object.keys(options).forEach((option) => {
if (config[option] !== undefined) {
config[option] = options[option]
}
})
}
|
[
"function",
"setConfig",
"(",
"options",
")",
"{",
"Object",
".",
"keys",
"(",
"options",
")",
".",
"forEach",
"(",
"(",
"option",
")",
"=>",
"{",
"if",
"(",
"config",
"[",
"option",
"]",
"!==",
"undefined",
")",
"{",
"config",
"[",
"option",
"]",
"=",
"options",
"[",
"option",
"]",
"}",
"}",
")",
"}"
] |
Override configuration values
@method setConfig
@param {Object}
|
[
"Override",
"configuration",
"values"
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/configure.js#L21-L27
|
13,406
|
poppinss/indicative
|
src/core/validator.js
|
validationFn
|
function validationFn (validations, {name, args}, field, data, messages, formatter) {
return new PLazy((resolve, reject) => {
const camelizedName = snakeToCamelCase(name)
const validation = validations[camelizedName]
if (typeof (validation) !== 'function') {
const error = new Error(`${camelizedName} is not defined as a validation rule`)
formatter.addError(error, field, camelizedName, args)
reject(error)
return
}
validation(data, field, getMessage(messages, field, name, args), args, prop)
.then(resolve)
.catch((error) => {
formatter.addError(error, field, camelizedName, args)
reject(error)
})
})
}
|
javascript
|
function validationFn (validations, {name, args}, field, data, messages, formatter) {
return new PLazy((resolve, reject) => {
const camelizedName = snakeToCamelCase(name)
const validation = validations[camelizedName]
if (typeof (validation) !== 'function') {
const error = new Error(`${camelizedName} is not defined as a validation rule`)
formatter.addError(error, field, camelizedName, args)
reject(error)
return
}
validation(data, field, getMessage(messages, field, name, args), args, prop)
.then(resolve)
.catch((error) => {
formatter.addError(error, field, camelizedName, args)
reject(error)
})
})
}
|
[
"function",
"validationFn",
"(",
"validations",
",",
"{",
"name",
",",
"args",
"}",
",",
"field",
",",
"data",
",",
"messages",
",",
"formatter",
")",
"{",
"return",
"new",
"PLazy",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"camelizedName",
"=",
"snakeToCamelCase",
"(",
"name",
")",
"const",
"validation",
"=",
"validations",
"[",
"camelizedName",
"]",
"if",
"(",
"typeof",
"(",
"validation",
")",
"!==",
"'function'",
")",
"{",
"const",
"error",
"=",
"new",
"Error",
"(",
"`",
"${",
"camelizedName",
"}",
"`",
")",
"formatter",
".",
"addError",
"(",
"error",
",",
"field",
",",
"camelizedName",
",",
"args",
")",
"reject",
"(",
"error",
")",
"return",
"}",
"validation",
"(",
"data",
",",
"field",
",",
"getMessage",
"(",
"messages",
",",
"field",
",",
"name",
",",
"args",
")",
",",
"args",
",",
"prop",
")",
".",
"then",
"(",
"resolve",
")",
".",
"catch",
"(",
"(",
"error",
")",
"=>",
"{",
"formatter",
".",
"addError",
"(",
"error",
",",
"field",
",",
"camelizedName",
",",
"args",
")",
"reject",
"(",
"error",
")",
"}",
")",
"}",
")",
"}"
] |
Returns a lazy promise which runs the validation on a field
for a given rule. This method will register promise
rejections with the formatter.
@method validationFn
@param {Object} validations
@param {Object} rule
@property {String} rule.name
@property {Array} rule.args
@param {String} field
@param {Object} data
@param {Object} messages
@param {Object} formatter
@returns {Promise}
|
[
"Returns",
"a",
"lazy",
"promise",
"which",
"runs",
"the",
"validation",
"on",
"a",
"field",
"for",
"a",
"given",
"rule",
".",
"This",
"method",
"will",
"register",
"promise",
"rejections",
"with",
"the",
"formatter",
"."
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/validator.js#L38-L57
|
13,407
|
poppinss/indicative
|
src/core/validator.js
|
getValidationsStack
|
function getValidationsStack (validations, fields, data, messages, formatter) {
return Object
.keys(fields)
.reduce((flatValidations, field) => {
fields[field].map((rule) => {
flatValidations.push(validationFn(validations, rule, field, data, messages, formatter))
})
return flatValidations
}, [])
}
|
javascript
|
function getValidationsStack (validations, fields, data, messages, formatter) {
return Object
.keys(fields)
.reduce((flatValidations, field) => {
fields[field].map((rule) => {
flatValidations.push(validationFn(validations, rule, field, data, messages, formatter))
})
return flatValidations
}, [])
}
|
[
"function",
"getValidationsStack",
"(",
"validations",
",",
"fields",
",",
"data",
",",
"messages",
",",
"formatter",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"fields",
")",
".",
"reduce",
"(",
"(",
"flatValidations",
",",
"field",
")",
"=>",
"{",
"fields",
"[",
"field",
"]",
".",
"map",
"(",
"(",
"rule",
")",
"=>",
"{",
"flatValidations",
".",
"push",
"(",
"validationFn",
"(",
"validations",
",",
"rule",
",",
"field",
",",
"data",
",",
"messages",
",",
"formatter",
")",
")",
"}",
")",
"return",
"flatValidations",
"}",
",",
"[",
"]",
")",
"}"
] |
This method loops over the fields and returns a flat stack of
validations for each field and multiple rules on that field.
Also all validation methods are wrapped inside a Lazy promise,
so they are executed when `.then` or `.catch` is called on
them.
@method getValidationsStack
@param {Object} validations - Object of available validations
@param {Object} data - Data to validate
@param {Object} fields - Fields and their rules
@param {Object} messages - Custom messages
@param {Object} formatter - Formatter to be used
@returns {Promise[]} An array of lazy promises
|
[
"This",
"method",
"loops",
"over",
"the",
"fields",
"and",
"returns",
"a",
"flat",
"stack",
"of",
"validations",
"for",
"each",
"field",
"and",
"multiple",
"rules",
"on",
"that",
"field",
"."
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/validator.js#L77-L86
|
13,408
|
poppinss/indicative
|
src/core/validator.js
|
validate
|
function validate (validations, bail, data, fields, messages, formatter) {
return new Promise((resolve, reject) => {
messages = messages || {}
/**
* This is expanded form of fields and rules
* applied on them
*/
const parsedFields = parse(fields, data)
/**
* A flat validations stack, each node is a lazy promise
*/
const validationsStack = getValidationsStack(validations, parsedFields, data, messages, formatter)
pSeries(validationsStack, bail)
.then((response) => {
const errors = formatter.toJSON()
if (errors) {
return reject(errors)
}
resolve(data)
})
})
}
|
javascript
|
function validate (validations, bail, data, fields, messages, formatter) {
return new Promise((resolve, reject) => {
messages = messages || {}
/**
* This is expanded form of fields and rules
* applied on them
*/
const parsedFields = parse(fields, data)
/**
* A flat validations stack, each node is a lazy promise
*/
const validationsStack = getValidationsStack(validations, parsedFields, data, messages, formatter)
pSeries(validationsStack, bail)
.then((response) => {
const errors = formatter.toJSON()
if (errors) {
return reject(errors)
}
resolve(data)
})
})
}
|
[
"function",
"validate",
"(",
"validations",
",",
"bail",
",",
"data",
",",
"fields",
",",
"messages",
",",
"formatter",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"messages",
"=",
"messages",
"||",
"{",
"}",
"/**\n * This is expanded form of fields and rules\n * applied on them\n */",
"const",
"parsedFields",
"=",
"parse",
"(",
"fields",
",",
"data",
")",
"/**\n * A flat validations stack, each node is a lazy promise\n */",
"const",
"validationsStack",
"=",
"getValidationsStack",
"(",
"validations",
",",
"parsedFields",
",",
"data",
",",
"messages",
",",
"formatter",
")",
"pSeries",
"(",
"validationsStack",
",",
"bail",
")",
".",
"then",
"(",
"(",
"response",
")",
"=>",
"{",
"const",
"errors",
"=",
"formatter",
".",
"toJSON",
"(",
")",
"if",
"(",
"errors",
")",
"{",
"return",
"reject",
"(",
"errors",
")",
"}",
"resolve",
"(",
"data",
")",
"}",
")",
"}",
")",
"}"
] |
Run `validations` on `data` using rules defined on `fields`.
@method validate
@param {Object} validations - Object of available validations
@param {Boolean} bail - Whether to bail on first error or not
@param {Object} data - Data to validate
@param {Object} fields - Fields and their rules
@param {Object} messages - Custom messages
@param {Object} formatter - Formatter to be used
@returns {Promise} Promise is rejected with an array of errors or resolved with original data
|
[
"Run",
"validations",
"on",
"data",
"using",
"rules",
"defined",
"on",
"fields",
"."
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/validator.js#L102-L126
|
13,409
|
poppinss/indicative
|
src/core/sanitizor.js
|
sanitizeField
|
function sanitizeField (sanitizations, value, rules) {
let result = value
rules.forEach((rule) => {
const ruleFn = snakeToCamelCase(rule.name)
if (typeof (sanitizations[ruleFn]) !== 'function') {
throw new Error(`${ruleFn} is not a sanitization method`)
}
result = sanitizations[ruleFn](result, rule.args)
})
return result
}
|
javascript
|
function sanitizeField (sanitizations, value, rules) {
let result = value
rules.forEach((rule) => {
const ruleFn = snakeToCamelCase(rule.name)
if (typeof (sanitizations[ruleFn]) !== 'function') {
throw new Error(`${ruleFn} is not a sanitization method`)
}
result = sanitizations[ruleFn](result, rule.args)
})
return result
}
|
[
"function",
"sanitizeField",
"(",
"sanitizations",
",",
"value",
",",
"rules",
")",
"{",
"let",
"result",
"=",
"value",
"rules",
".",
"forEach",
"(",
"(",
"rule",
")",
"=>",
"{",
"const",
"ruleFn",
"=",
"snakeToCamelCase",
"(",
"rule",
".",
"name",
")",
"if",
"(",
"typeof",
"(",
"sanitizations",
"[",
"ruleFn",
"]",
")",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"ruleFn",
"}",
"`",
")",
"}",
"result",
"=",
"sanitizations",
"[",
"ruleFn",
"]",
"(",
"result",
",",
"rule",
".",
"args",
")",
"}",
")",
"return",
"result",
"}"
] |
Runs a bunch of sanitization rules on a given value
@method sanitizeField
@param {Object} sanitizations
@param {Mixed} value
@param {Array} rules
@return {Mixed}
@throws {Exception} If sanitization rule doesnt exists
|
[
"Runs",
"a",
"bunch",
"of",
"sanitization",
"rules",
"on",
"a",
"given",
"value"
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/sanitizor.js#L93-L105
|
13,410
|
poppinss/indicative
|
bin/inlineDocs.js
|
getFiles
|
function getFiles (location, filterFn) {
return new Promise((resolve, reject) => {
const files = []
klaw(location)
.on('data', (item) => {
if (!item.stats.isDirectory() && filterFn(item)) {
files.push(item.path)
}
})
.on('end', () => resolve(files))
.on('error', reject)
})
}
|
javascript
|
function getFiles (location, filterFn) {
return new Promise((resolve, reject) => {
const files = []
klaw(location)
.on('data', (item) => {
if (!item.stats.isDirectory() && filterFn(item)) {
files.push(item.path)
}
})
.on('end', () => resolve(files))
.on('error', reject)
})
}
|
[
"function",
"getFiles",
"(",
"location",
",",
"filterFn",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"files",
"=",
"[",
"]",
"klaw",
"(",
"location",
")",
".",
"on",
"(",
"'data'",
",",
"(",
"item",
")",
"=>",
"{",
"if",
"(",
"!",
"item",
".",
"stats",
".",
"isDirectory",
"(",
")",
"&&",
"filterFn",
"(",
"item",
")",
")",
"{",
"files",
".",
"push",
"(",
"item",
".",
"path",
")",
"}",
"}",
")",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"resolve",
"(",
"files",
")",
")",
".",
"on",
"(",
"'error'",
",",
"reject",
")",
"}",
")",
"}"
] |
Walks over a location and reads all .js files
@method getFiles
@param {String} location
@param {Function} filterFn
@return {Array}
|
[
"Walks",
"over",
"a",
"location",
"and",
"reads",
"all",
".",
"js",
"files"
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/bin/inlineDocs.js#L50-L62
|
13,411
|
poppinss/indicative
|
bin/inlineDocs.js
|
readFiles
|
async function readFiles (locations) {
return Promise.all(locations.map((location) => {
return fs.readFile(location, 'utf-8')
}))
}
|
javascript
|
async function readFiles (locations) {
return Promise.all(locations.map((location) => {
return fs.readFile(location, 'utf-8')
}))
}
|
[
"async",
"function",
"readFiles",
"(",
"locations",
")",
"{",
"return",
"Promise",
".",
"all",
"(",
"locations",
".",
"map",
"(",
"(",
"location",
")",
"=>",
"{",
"return",
"fs",
".",
"readFile",
"(",
"location",
",",
"'utf-8'",
")",
"}",
")",
")",
"}"
] |
Returns an array of files in parallel
@method readFiles
@param {Array} locations
@return {Array}
|
[
"Returns",
"an",
"array",
"of",
"files",
"in",
"parallel"
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/bin/inlineDocs.js#L73-L77
|
13,412
|
poppinss/indicative
|
bin/inlineDocs.js
|
extractComments
|
function extractComments (contents) {
let context = 'idle'
const lines = []
contents.split('\n').forEach((line) => {
if (line.trim() === '/**') {
context = 'in'
return
}
if (line.trim() === '*/') {
context = 'out'
return
}
if (context === 'in') {
lines.push(line.replace(/\*/g, '').replace(/^\s\s/, ''))
}
})
return lines.join('\n')
}
|
javascript
|
function extractComments (contents) {
let context = 'idle'
const lines = []
contents.split('\n').forEach((line) => {
if (line.trim() === '/**') {
context = 'in'
return
}
if (line.trim() === '*/') {
context = 'out'
return
}
if (context === 'in') {
lines.push(line.replace(/\*/g, '').replace(/^\s\s/, ''))
}
})
return lines.join('\n')
}
|
[
"function",
"extractComments",
"(",
"contents",
")",
"{",
"let",
"context",
"=",
"'idle'",
"const",
"lines",
"=",
"[",
"]",
"contents",
".",
"split",
"(",
"'\\n'",
")",
".",
"forEach",
"(",
"(",
"line",
")",
"=>",
"{",
"if",
"(",
"line",
".",
"trim",
"(",
")",
"===",
"'/**'",
")",
"{",
"context",
"=",
"'in'",
"return",
"}",
"if",
"(",
"line",
".",
"trim",
"(",
")",
"===",
"'*/'",
")",
"{",
"context",
"=",
"'out'",
"return",
"}",
"if",
"(",
"context",
"===",
"'in'",
")",
"{",
"lines",
".",
"push",
"(",
"line",
".",
"replace",
"(",
"/",
"\\*",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"/",
"^\\s\\s",
"/",
",",
"''",
")",
")",
"}",
"}",
")",
"return",
"lines",
".",
"join",
"(",
"'\\n'",
")",
"}"
] |
Extract comments from the top of the file. Also this method
assumes, each block of content has only one top of comments
section.
@method extractComments
@param {String} contents
@return {String}
|
[
"Extract",
"comments",
"from",
"the",
"top",
"of",
"the",
"file",
".",
"Also",
"this",
"method",
"assumes",
"each",
"block",
"of",
"content",
"has",
"only",
"one",
"top",
"of",
"comments",
"section",
"."
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/bin/inlineDocs.js#L90-L109
|
13,413
|
poppinss/indicative
|
bin/inlineDocs.js
|
writeDocs
|
async function writeDocs (basePath, nodes) {
Promise.all(nodes.map((node) => {
const location = path.join(basePath, node.location.replace(srcPath, '').replace(/\.js$/, '.adoc'))
return fs.outputFile(location, node.comments)
}))
}
|
javascript
|
async function writeDocs (basePath, nodes) {
Promise.all(nodes.map((node) => {
const location = path.join(basePath, node.location.replace(srcPath, '').replace(/\.js$/, '.adoc'))
return fs.outputFile(location, node.comments)
}))
}
|
[
"async",
"function",
"writeDocs",
"(",
"basePath",
",",
"nodes",
")",
"{",
"Promise",
".",
"all",
"(",
"nodes",
".",
"map",
"(",
"(",
"node",
")",
"=>",
"{",
"const",
"location",
"=",
"path",
".",
"join",
"(",
"basePath",
",",
"node",
".",
"location",
".",
"replace",
"(",
"srcPath",
",",
"''",
")",
".",
"replace",
"(",
"/",
"\\.js$",
"/",
",",
"'.adoc'",
")",
")",
"return",
"fs",
".",
"outputFile",
"(",
"location",
",",
"node",
".",
"comments",
")",
"}",
")",
")",
"}"
] |
Writes all docs to their respective files
@method writeDocs
@param {String} basePath
@param {Array} nodes
@return {void}
|
[
"Writes",
"all",
"docs",
"to",
"their",
"respective",
"files"
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/bin/inlineDocs.js#L121-L126
|
13,414
|
poppinss/indicative
|
bin/inlineDocs.js
|
srcToDocs
|
async function srcToDocs (dir) {
const location = path.join(srcPath, dir)
const srcFiles = await getFiles(location, (item) => item.path.endsWith('.js') && !item.path.endsWith('index.js'))
const filesContents = await readFiles(srcFiles)
const filesComments = srcFiles.map((location, index) => {
const fnName = path.basename(location).replace(/\.js$/, '')
const matter = getMatter(fnName, dir)
const doc = matter.concat(extractComments(filesContents[index])).concat(getRuleImport(fnName))
return { comments: doc.join('\n'), location }
})
await writeDocs(docsDir, filesComments)
}
|
javascript
|
async function srcToDocs (dir) {
const location = path.join(srcPath, dir)
const srcFiles = await getFiles(location, (item) => item.path.endsWith('.js') && !item.path.endsWith('index.js'))
const filesContents = await readFiles(srcFiles)
const filesComments = srcFiles.map((location, index) => {
const fnName = path.basename(location).replace(/\.js$/, '')
const matter = getMatter(fnName, dir)
const doc = matter.concat(extractComments(filesContents[index])).concat(getRuleImport(fnName))
return { comments: doc.join('\n'), location }
})
await writeDocs(docsDir, filesComments)
}
|
[
"async",
"function",
"srcToDocs",
"(",
"dir",
")",
"{",
"const",
"location",
"=",
"path",
".",
"join",
"(",
"srcPath",
",",
"dir",
")",
"const",
"srcFiles",
"=",
"await",
"getFiles",
"(",
"location",
",",
"(",
"item",
")",
"=>",
"item",
".",
"path",
".",
"endsWith",
"(",
"'.js'",
")",
"&&",
"!",
"item",
".",
"path",
".",
"endsWith",
"(",
"'index.js'",
")",
")",
"const",
"filesContents",
"=",
"await",
"readFiles",
"(",
"srcFiles",
")",
"const",
"filesComments",
"=",
"srcFiles",
".",
"map",
"(",
"(",
"location",
",",
"index",
")",
"=>",
"{",
"const",
"fnName",
"=",
"path",
".",
"basename",
"(",
"location",
")",
".",
"replace",
"(",
"/",
"\\.js$",
"/",
",",
"''",
")",
"const",
"matter",
"=",
"getMatter",
"(",
"fnName",
",",
"dir",
")",
"const",
"doc",
"=",
"matter",
".",
"concat",
"(",
"extractComments",
"(",
"filesContents",
"[",
"index",
"]",
")",
")",
".",
"concat",
"(",
"getRuleImport",
"(",
"fnName",
")",
")",
"return",
"{",
"comments",
":",
"doc",
".",
"join",
"(",
"'\\n'",
")",
",",
"location",
"}",
"}",
")",
"await",
"writeDocs",
"(",
"docsDir",
",",
"filesComments",
")",
"}"
] |
Converts all source files inside a directory to `.adoc`
files inside docs directory
@method srcToDocs
@param {String} dir
@return {void}
|
[
"Converts",
"all",
"source",
"files",
"inside",
"a",
"directory",
"to",
".",
"adoc",
"files",
"inside",
"docs",
"directory"
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/bin/inlineDocs.js#L138-L149
|
13,415
|
poppinss/indicative
|
src/core/parse.js
|
parseRules
|
function parseRules (fields, data) {
data = data || {}
return Object.keys(fields).reduce((result, field) => {
let rules = fields[field]
/**
* Strings are passed to haye for further processing
* and if rules are not an array or a string, then
* we should blow.
*/
if (typeof (rules) === 'string') {
rules = Pipe(rules, new ArrayPresenter())
} else if (!Array.isArray(rules)) {
throw new Error('Rules must be defined as a string or an array')
}
/**
* When field name has a star in it, we need to do some heavy
* lifting and expand the field to dot properties based upon
* the available data inside the data object.
*/
if (field.indexOf('*') > -1) {
const nodes = field.split(/\.\*\.?/)
starToIndex(nodes, data).forEach((f) => { result[f] = rules })
} else {
result[field] = rules
}
return result
}, {})
}
|
javascript
|
function parseRules (fields, data) {
data = data || {}
return Object.keys(fields).reduce((result, field) => {
let rules = fields[field]
/**
* Strings are passed to haye for further processing
* and if rules are not an array or a string, then
* we should blow.
*/
if (typeof (rules) === 'string') {
rules = Pipe(rules, new ArrayPresenter())
} else if (!Array.isArray(rules)) {
throw new Error('Rules must be defined as a string or an array')
}
/**
* When field name has a star in it, we need to do some heavy
* lifting and expand the field to dot properties based upon
* the available data inside the data object.
*/
if (field.indexOf('*') > -1) {
const nodes = field.split(/\.\*\.?/)
starToIndex(nodes, data).forEach((f) => { result[f] = rules })
} else {
result[field] = rules
}
return result
}, {})
}
|
[
"function",
"parseRules",
"(",
"fields",
",",
"data",
")",
"{",
"data",
"=",
"data",
"||",
"{",
"}",
"return",
"Object",
".",
"keys",
"(",
"fields",
")",
".",
"reduce",
"(",
"(",
"result",
",",
"field",
")",
"=>",
"{",
"let",
"rules",
"=",
"fields",
"[",
"field",
"]",
"/**\n * Strings are passed to haye for further processing\n * and if rules are not an array or a string, then\n * we should blow.\n */",
"if",
"(",
"typeof",
"(",
"rules",
")",
"===",
"'string'",
")",
"{",
"rules",
"=",
"Pipe",
"(",
"rules",
",",
"new",
"ArrayPresenter",
"(",
")",
")",
"}",
"else",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"rules",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Rules must be defined as a string or an array'",
")",
"}",
"/**\n * When field name has a star in it, we need to do some heavy\n * lifting and expand the field to dot properties based upon\n * the available data inside the data object.\n */",
"if",
"(",
"field",
".",
"indexOf",
"(",
"'*'",
")",
">",
"-",
"1",
")",
"{",
"const",
"nodes",
"=",
"field",
".",
"split",
"(",
"/",
"\\.\\*\\.?",
"/",
")",
"starToIndex",
"(",
"nodes",
",",
"data",
")",
".",
"forEach",
"(",
"(",
"f",
")",
"=>",
"{",
"result",
"[",
"f",
"]",
"=",
"rules",
"}",
")",
"}",
"else",
"{",
"result",
"[",
"field",
"]",
"=",
"rules",
"}",
"return",
"result",
"}",
",",
"{",
"}",
")",
"}"
] |
This method parses the rules object into a new object with
expanded field names and transformed rules.
### Expanding fields
One can define `*` expression to denote an array of fields
to be validated.
The `*` expression is expanded based upon the available data.
For example
```js
const rules = {
'users.*.username': required
}
// ( users.length = 2 )
const data = {
users: [{}, {}]
}
output = {
'users.0.username' : [{ name: 'required', args: [] }],
'users.1.username' : [{ name: 'required', args: [] }]
}
```
@param {Object} fields
@param {Object} [data = {}]
@method parseRules
@example
```js
rules = { username: 'required|alpha' }
output = {
username: [{ name: 'required', args: [] }, { name: 'alpha',args: [] }]
}
```
@throws {Error} when rules are not defined as a string or pre-expanded array
|
[
"This",
"method",
"parses",
"the",
"rules",
"object",
"into",
"a",
"new",
"object",
"with",
"expanded",
"field",
"names",
"and",
"transformed",
"rules",
"."
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/parse.js#L59-L90
|
13,416
|
poppinss/indicative
|
bin/sauceLabs.js
|
function (route, body, method = 'post') {
return got(`https://saucelabs.com/rest/v1/${process.env.SAUCE_USERNAME}/${route}`, {
method,
json: true,
body,
headers: {
Authorization: `Basic ${getCredentials()}`
}
}).then((response) => {
return response.body
}).catch((error) => {
throw error.response.body
})
}
|
javascript
|
function (route, body, method = 'post') {
return got(`https://saucelabs.com/rest/v1/${process.env.SAUCE_USERNAME}/${route}`, {
method,
json: true,
body,
headers: {
Authorization: `Basic ${getCredentials()}`
}
}).then((response) => {
return response.body
}).catch((error) => {
throw error.response.body
})
}
|
[
"function",
"(",
"route",
",",
"body",
",",
"method",
"=",
"'post'",
")",
"{",
"return",
"got",
"(",
"`",
"${",
"process",
".",
"env",
".",
"SAUCE_USERNAME",
"}",
"${",
"route",
"}",
"`",
",",
"{",
"method",
",",
"json",
":",
"true",
",",
"body",
",",
"headers",
":",
"{",
"Authorization",
":",
"`",
"${",
"getCredentials",
"(",
")",
"}",
"`",
"}",
"}",
")",
".",
"then",
"(",
"(",
"response",
")",
"=>",
"{",
"return",
"response",
".",
"body",
"}",
")",
".",
"catch",
"(",
"(",
"error",
")",
"=>",
"{",
"throw",
"error",
".",
"response",
".",
"body",
"}",
")",
"}"
] |
Makes an http request to sauceLabs
@method makeHttpRequest
@param {String} route
@param {Object} body
@param {String} [method = 'post']
@return {Promise}
|
[
"Makes",
"an",
"http",
"request",
"to",
"sauceLabs"
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/bin/sauceLabs.js#L37-L50
|
|
13,417
|
poppinss/indicative
|
src/core/getMessage.js
|
getMessage
|
function getMessage (messages, field, validation, args) {
/**
* Since we allow array expression as `*`, we want all index of the
* current field to be replaced with `.*`, so that we get the
* right message.
*/
const originalField = field.replace(/\.\d/g, '.*')
const camelizedValidation = snakeToCamelCase(validation)
const message = messages[`${originalField}.${validation}`] ||
messages[`${originalField}.${camelizedValidation}`] ||
messages[validation] ||
messages[camelizedValidation] ||
'{{validation}} validation failed on {{ field }}'
return typeof (message) === 'function'
? message(originalField, validation, args)
: pope(message, { field, validation, argument: args })
}
|
javascript
|
function getMessage (messages, field, validation, args) {
/**
* Since we allow array expression as `*`, we want all index of the
* current field to be replaced with `.*`, so that we get the
* right message.
*/
const originalField = field.replace(/\.\d/g, '.*')
const camelizedValidation = snakeToCamelCase(validation)
const message = messages[`${originalField}.${validation}`] ||
messages[`${originalField}.${camelizedValidation}`] ||
messages[validation] ||
messages[camelizedValidation] ||
'{{validation}} validation failed on {{ field }}'
return typeof (message) === 'function'
? message(originalField, validation, args)
: pope(message, { field, validation, argument: args })
}
|
[
"function",
"getMessage",
"(",
"messages",
",",
"field",
",",
"validation",
",",
"args",
")",
"{",
"/**\n * Since we allow array expression as `*`, we want all index of the\n * current field to be replaced with `.*`, so that we get the\n * right message.\n */",
"const",
"originalField",
"=",
"field",
".",
"replace",
"(",
"/",
"\\.\\d",
"/",
"g",
",",
"'.*'",
")",
"const",
"camelizedValidation",
"=",
"snakeToCamelCase",
"(",
"validation",
")",
"const",
"message",
"=",
"messages",
"[",
"`",
"${",
"originalField",
"}",
"${",
"validation",
"}",
"`",
"]",
"||",
"messages",
"[",
"`",
"${",
"originalField",
"}",
"${",
"camelizedValidation",
"}",
"`",
"]",
"||",
"messages",
"[",
"validation",
"]",
"||",
"messages",
"[",
"camelizedValidation",
"]",
"||",
"'{{validation}} validation failed on {{ field }}'",
"return",
"typeof",
"(",
"message",
")",
"===",
"'function'",
"?",
"message",
"(",
"originalField",
",",
"validation",
",",
"args",
")",
":",
"pope",
"(",
"message",
",",
"{",
"field",
",",
"validation",
",",
"argument",
":",
"args",
"}",
")",
"}"
] |
Returns message for a given field and a validation rule. The priority is
defined as follows in order from top to bottom.
1. Message for `field.validation`
2. Message for validation
3. Default message
### Templating
Support dynamic placeholders in messages as shown below.
```
{{ validation }} validation failed on {{ field }}
```
1. validation - Validation name
2. field - Field under validation
3. argument - An array of values/args passed to the validation.
### Closure
Also you can define a closure for a message, which receives
following arguments.
```
required: function (field, validation, args) {
return `${validation} failed on ${field}`
}
```
@method getMessage
@param {Object} messages
@param {String} field
@param {String} validation
@param {Array} args
@returns String
|
[
"Returns",
"message",
"for",
"a",
"given",
"field",
"and",
"a",
"validation",
"rule",
".",
"The",
"priority",
"is",
"defined",
"as",
"follows",
"in",
"order",
"from",
"top",
"to",
"bottom",
"."
] |
bb3e149ced03e8e0c51e5169e1e2a7282b956d9a
|
https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/getMessage.js#L52-L70
|
13,418
|
brehaut/color-js
|
color.js
|
function(bytes) {
bytes = bytes || 2;
var max = Math.pow(16, bytes) - 1;
var css = [
"#",
pad(Math.round(this.red * max).toString(16).toUpperCase(), bytes),
pad(Math.round(this.green * max).toString(16).toUpperCase(), bytes),
pad(Math.round(this.blue * max).toString(16).toUpperCase(), bytes)
];
return css.join('');
}
|
javascript
|
function(bytes) {
bytes = bytes || 2;
var max = Math.pow(16, bytes) - 1;
var css = [
"#",
pad(Math.round(this.red * max).toString(16).toUpperCase(), bytes),
pad(Math.round(this.green * max).toString(16).toUpperCase(), bytes),
pad(Math.round(this.blue * max).toString(16).toUpperCase(), bytes)
];
return css.join('');
}
|
[
"function",
"(",
"bytes",
")",
"{",
"bytes",
"=",
"bytes",
"||",
"2",
";",
"var",
"max",
"=",
"Math",
".",
"pow",
"(",
"16",
",",
"bytes",
")",
"-",
"1",
";",
"var",
"css",
"=",
"[",
"\"#\"",
",",
"pad",
"(",
"Math",
".",
"round",
"(",
"this",
".",
"red",
"*",
"max",
")",
".",
"toString",
"(",
"16",
")",
".",
"toUpperCase",
"(",
")",
",",
"bytes",
")",
",",
"pad",
"(",
"Math",
".",
"round",
"(",
"this",
".",
"green",
"*",
"max",
")",
".",
"toString",
"(",
"16",
")",
".",
"toUpperCase",
"(",
")",
",",
"bytes",
")",
",",
"pad",
"(",
"Math",
".",
"round",
"(",
"this",
".",
"blue",
"*",
"max",
")",
".",
"toString",
"(",
"16",
")",
".",
"toUpperCase",
"(",
")",
",",
"bytes",
")",
"]",
";",
"return",
"css",
".",
"join",
"(",
"''",
")",
";",
"}"
] |
convert to a CSS string. defaults to two bytes a value
|
[
"convert",
"to",
"a",
"CSS",
"string",
".",
"defaults",
"to",
"two",
"bytes",
"a",
"value"
] |
23fc53428d972efb9f1f365781d8ba0407ae7213
|
https://github.com/brehaut/color-js/blob/23fc53428d972efb9f1f365781d8ba0407ae7213/color.js#L412-L424
|
|
13,419
|
chevex-archived/mongoose-auto-increment
|
index.js
|
function (callback) {
IdentityCounter.findOneAndUpdate(
{ model: settings.model, field: settings.field },
{ count: settings.startAt - settings.incrementBy },
{ new: true }, // new: true specifies that the callback should get the updated counter.
function (err) {
if (err) return callback(err);
callback(null, settings.startAt);
}
);
}
|
javascript
|
function (callback) {
IdentityCounter.findOneAndUpdate(
{ model: settings.model, field: settings.field },
{ count: settings.startAt - settings.incrementBy },
{ new: true }, // new: true specifies that the callback should get the updated counter.
function (err) {
if (err) return callback(err);
callback(null, settings.startAt);
}
);
}
|
[
"function",
"(",
"callback",
")",
"{",
"IdentityCounter",
".",
"findOneAndUpdate",
"(",
"{",
"model",
":",
"settings",
".",
"model",
",",
"field",
":",
"settings",
".",
"field",
"}",
",",
"{",
"count",
":",
"settings",
".",
"startAt",
"-",
"settings",
".",
"incrementBy",
"}",
",",
"{",
"new",
":",
"true",
"}",
",",
"// new: true specifies that the callback should get the updated counter.",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"callback",
"(",
"null",
",",
"settings",
".",
"startAt",
")",
";",
"}",
")",
";",
"}"
] |
Declare a function to reset counter at the start value - increment value.
|
[
"Declare",
"a",
"function",
"to",
"reset",
"counter",
"at",
"the",
"start",
"value",
"-",
"increment",
"value",
"."
] |
50bd2a642c7565cf0a9f2c368d437b83160ad0a6
|
https://github.com/chevex-archived/mongoose-auto-increment/blob/50bd2a642c7565cf0a9f2c368d437b83160ad0a6/index.js#L104-L114
|
|
13,420
|
chevex-archived/mongoose-auto-increment
|
index.js
|
function (err, updatedIdentityCounter) {
if (err) return next(err);
// If there are no errors then go ahead and set the document's field to the current count.
doc[settings.field] = updatedIdentityCounter.count;
// Continue with default document save functionality.
next();
}
|
javascript
|
function (err, updatedIdentityCounter) {
if (err) return next(err);
// If there are no errors then go ahead and set the document's field to the current count.
doc[settings.field] = updatedIdentityCounter.count;
// Continue with default document save functionality.
next();
}
|
[
"function",
"(",
"err",
",",
"updatedIdentityCounter",
")",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"err",
")",
";",
"// If there are no errors then go ahead and set the document's field to the current count.",
"doc",
"[",
"settings",
".",
"field",
"]",
"=",
"updatedIdentityCounter",
".",
"count",
";",
"// Continue with default document save functionality.",
"next",
"(",
")",
";",
"}"
] |
Receive the updated counter.
|
[
"Receive",
"the",
"updated",
"counter",
"."
] |
50bd2a642c7565cf0a9f2c368d437b83160ad0a6
|
https://github.com/chevex-archived/mongoose-auto-increment/blob/50bd2a642c7565cf0a9f2c368d437b83160ad0a6/index.js#L157-L163
|
|
13,421
|
StephanWagner/jBox
|
dist/jBox.all.js
|
addUnscrollClassName
|
function addUnscrollClassName() {
if (document.getElementById('unscroll-class-name')) {
return;
}
var css = '.unscrollable { overflow-y: hidden !important; }',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
style.setAttribute('id', 'unscroll-class-name');
style.appendChild(document.createTextNode(css));
head.appendChild(style);
}
|
javascript
|
function addUnscrollClassName() {
if (document.getElementById('unscroll-class-name')) {
return;
}
var css = '.unscrollable { overflow-y: hidden !important; }',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
style.setAttribute('id', 'unscroll-class-name');
style.appendChild(document.createTextNode(css));
head.appendChild(style);
}
|
[
"function",
"addUnscrollClassName",
"(",
")",
"{",
"if",
"(",
"document",
".",
"getElementById",
"(",
"'unscroll-class-name'",
")",
")",
"{",
"return",
";",
"}",
"var",
"css",
"=",
"'.unscrollable { overflow-y: hidden !important; }'",
",",
"head",
"=",
"document",
".",
"head",
"||",
"document",
".",
"getElementsByTagName",
"(",
"'head'",
")",
"[",
"0",
"]",
",",
"style",
"=",
"document",
".",
"createElement",
"(",
"'style'",
")",
";",
"style",
".",
"type",
"=",
"'text/css'",
";",
"style",
".",
"setAttribute",
"(",
"'id'",
",",
"'unscroll-class-name'",
")",
";",
"style",
".",
"appendChild",
"(",
"document",
".",
"createTextNode",
"(",
"css",
")",
")",
";",
"head",
".",
"appendChild",
"(",
"style",
")",
";",
"}"
] |
Add unscroll class to head
|
[
"Add",
"unscroll",
"class",
"to",
"head"
] |
63857f9529ad8f9c491d5a5bc7fe44135f74e927
|
https://github.com/StephanWagner/jBox/blob/63857f9529ad8f9c491d5a5bc7fe44135f74e927/dist/jBox.all.js#L49-L60
|
13,422
|
StephanWagner/jBox
|
dist/jBox.all.js
|
function (el)
{
// Extract the href or the onclick event if no submit event is passed
if (!this.options.confirm) {
var submit = el.attr('onclick') ? el.attr('onclick') : (el.attr('href') ? (el.attr('target') ? 'window.open("' + el.attr('href') + '", "' + el.attr('target') + '");' : 'window.location.href = "' + el.attr('href') + '";') : '');
el.prop('onclick', null).data('jBox-Confirm-submit', submit);
}
}
|
javascript
|
function (el)
{
// Extract the href or the onclick event if no submit event is passed
if (!this.options.confirm) {
var submit = el.attr('onclick') ? el.attr('onclick') : (el.attr('href') ? (el.attr('target') ? 'window.open("' + el.attr('href') + '", "' + el.attr('target') + '");' : 'window.location.href = "' + el.attr('href') + '";') : '');
el.prop('onclick', null).data('jBox-Confirm-submit', submit);
}
}
|
[
"function",
"(",
"el",
")",
"{",
"// Extract the href or the onclick event if no submit event is passed",
"if",
"(",
"!",
"this",
".",
"options",
".",
"confirm",
")",
"{",
"var",
"submit",
"=",
"el",
".",
"attr",
"(",
"'onclick'",
")",
"?",
"el",
".",
"attr",
"(",
"'onclick'",
")",
":",
"(",
"el",
".",
"attr",
"(",
"'href'",
")",
"?",
"(",
"el",
".",
"attr",
"(",
"'target'",
")",
"?",
"'window.open(\"'",
"+",
"el",
".",
"attr",
"(",
"'href'",
")",
"+",
"'\", \"'",
"+",
"el",
".",
"attr",
"(",
"'target'",
")",
"+",
"'\");'",
":",
"'window.location.href = \"'",
"+",
"el",
".",
"attr",
"(",
"'href'",
")",
"+",
"'\";'",
")",
":",
"''",
")",
";",
"el",
".",
"prop",
"(",
"'onclick'",
",",
"null",
")",
".",
"data",
"(",
"'jBox-Confirm-submit'",
",",
"submit",
")",
";",
"}",
"}"
] |
Triggered when jBox is attached to the element
|
[
"Triggered",
"when",
"jBox",
"is",
"attached",
"to",
"the",
"element"
] |
63857f9529ad8f9c491d5a5bc7fe44135f74e927
|
https://github.com/StephanWagner/jBox/blob/63857f9529ad8f9c491d5a5bc7fe44135f74e927/dist/jBox.all.js#L2222-L2229
|
|
13,423
|
StephanWagner/jBox
|
dist/jBox.all.js
|
function ()
{
// Set the new action for the submit button
this.submitButton.off('click.jBox-Confirm' + this.id).on('click.jBox-Confirm' + this.id, function () { this.options.confirm ? this.options.confirm() : eval(this.source.data('jBox-Confirm-submit')); this.options.closeOnConfirm && this.close(); }.bind(this));
}
|
javascript
|
function ()
{
// Set the new action for the submit button
this.submitButton.off('click.jBox-Confirm' + this.id).on('click.jBox-Confirm' + this.id, function () { this.options.confirm ? this.options.confirm() : eval(this.source.data('jBox-Confirm-submit')); this.options.closeOnConfirm && this.close(); }.bind(this));
}
|
[
"function",
"(",
")",
"{",
"// Set the new action for the submit button",
"this",
".",
"submitButton",
".",
"off",
"(",
"'click.jBox-Confirm'",
"+",
"this",
".",
"id",
")",
".",
"on",
"(",
"'click.jBox-Confirm'",
"+",
"this",
".",
"id",
",",
"function",
"(",
")",
"{",
"this",
".",
"options",
".",
"confirm",
"?",
"this",
".",
"options",
".",
"confirm",
"(",
")",
":",
"eval",
"(",
"this",
".",
"source",
".",
"data",
"(",
"'jBox-Confirm-submit'",
")",
")",
";",
"this",
".",
"options",
".",
"closeOnConfirm",
"&&",
"this",
".",
"close",
"(",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] |
Triggered when jBox is opened
|
[
"Triggered",
"when",
"jBox",
"is",
"opened"
] |
63857f9529ad8f9c491d5a5bc7fe44135f74e927
|
https://github.com/StephanWagner/jBox/blob/63857f9529ad8f9c491d5a5bc7fe44135f74e927/dist/jBox.all.js#L2249-L2253
|
|
13,424
|
StephanWagner/jBox
|
dist/jBox.all.js
|
function ()
{
// Append image label containers
this.imageLabel = jQuery('<div/>', {'class': 'jBox-image-label-container'}).appendTo(this.wrapper);
this.imageLabel.append(jQuery('<div/>', {'class': 'jBox-image-pointer-prev', click: function () { this.showImage('prev'); }.bind(this)})).append(jQuery('<div/>', {'class': 'jBox-image-pointer-next', click: function () { this.showImage('next'); }.bind(this)}));
// Append the download button
if (this.options.downloadButton) {
this.downloadButton = jQuery('<div/>', {'class': 'jBox-image-download-button-wrapper'})
.appendTo(this.wrapper)
.append(
this.options.downloadButtonText ? jQuery('<div/>', {'class': 'jBox-image-download-button-text'}).html(this.options.downloadButtonText) : null
)
.append(
jQuery('<div/>', {'class': 'jBox-image-download-button-icon'})
).on('click touchdown', function () {
if (this.images[this.currentImage.gallery][this.currentImage.id].downloadUrl) {
var currentImageUrl = this.images[this.currentImage.gallery][this.currentImage.id].downloadUrl;
} else {
var currentImage = this.wrapper.find('.jBox-image-default-current');
var currentImageStyle = currentImage[0].style.backgroundImage;
var currentImageUrl = currentImageStyle.slice(4, -1).replace(/["']/g, '');
}
this.downloadImage(currentImageUrl);
}.bind(this));
}
// Creating the image counter containers
if (this.options.imageCounter) {
this.imageCounter = jQuery('<div/>', {'class': 'jBox-image-counter-container'}).appendTo(this.wrapper);
this.imageCounter.append(jQuery('<span/>', {'class': 'jBox-image-counter-current'})).append(jQuery('<span/>').html(this.options.imageCounterSeparator)).append(jQuery('<span/>', {'class': 'jBox-image-counter-all'}));
}
}
|
javascript
|
function ()
{
// Append image label containers
this.imageLabel = jQuery('<div/>', {'class': 'jBox-image-label-container'}).appendTo(this.wrapper);
this.imageLabel.append(jQuery('<div/>', {'class': 'jBox-image-pointer-prev', click: function () { this.showImage('prev'); }.bind(this)})).append(jQuery('<div/>', {'class': 'jBox-image-pointer-next', click: function () { this.showImage('next'); }.bind(this)}));
// Append the download button
if (this.options.downloadButton) {
this.downloadButton = jQuery('<div/>', {'class': 'jBox-image-download-button-wrapper'})
.appendTo(this.wrapper)
.append(
this.options.downloadButtonText ? jQuery('<div/>', {'class': 'jBox-image-download-button-text'}).html(this.options.downloadButtonText) : null
)
.append(
jQuery('<div/>', {'class': 'jBox-image-download-button-icon'})
).on('click touchdown', function () {
if (this.images[this.currentImage.gallery][this.currentImage.id].downloadUrl) {
var currentImageUrl = this.images[this.currentImage.gallery][this.currentImage.id].downloadUrl;
} else {
var currentImage = this.wrapper.find('.jBox-image-default-current');
var currentImageStyle = currentImage[0].style.backgroundImage;
var currentImageUrl = currentImageStyle.slice(4, -1).replace(/["']/g, '');
}
this.downloadImage(currentImageUrl);
}.bind(this));
}
// Creating the image counter containers
if (this.options.imageCounter) {
this.imageCounter = jQuery('<div/>', {'class': 'jBox-image-counter-container'}).appendTo(this.wrapper);
this.imageCounter.append(jQuery('<span/>', {'class': 'jBox-image-counter-current'})).append(jQuery('<span/>').html(this.options.imageCounterSeparator)).append(jQuery('<span/>', {'class': 'jBox-image-counter-all'}));
}
}
|
[
"function",
"(",
")",
"{",
"// Append image label containers",
"this",
".",
"imageLabel",
"=",
"jQuery",
"(",
"'<div/>'",
",",
"{",
"'class'",
":",
"'jBox-image-label-container'",
"}",
")",
".",
"appendTo",
"(",
"this",
".",
"wrapper",
")",
";",
"this",
".",
"imageLabel",
".",
"append",
"(",
"jQuery",
"(",
"'<div/>'",
",",
"{",
"'class'",
":",
"'jBox-image-pointer-prev'",
",",
"click",
":",
"function",
"(",
")",
"{",
"this",
".",
"showImage",
"(",
"'prev'",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
"}",
")",
")",
".",
"append",
"(",
"jQuery",
"(",
"'<div/>'",
",",
"{",
"'class'",
":",
"'jBox-image-pointer-next'",
",",
"click",
":",
"function",
"(",
")",
"{",
"this",
".",
"showImage",
"(",
"'next'",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
"}",
")",
")",
";",
"// Append the download button",
"if",
"(",
"this",
".",
"options",
".",
"downloadButton",
")",
"{",
"this",
".",
"downloadButton",
"=",
"jQuery",
"(",
"'<div/>'",
",",
"{",
"'class'",
":",
"'jBox-image-download-button-wrapper'",
"}",
")",
".",
"appendTo",
"(",
"this",
".",
"wrapper",
")",
".",
"append",
"(",
"this",
".",
"options",
".",
"downloadButtonText",
"?",
"jQuery",
"(",
"'<div/>'",
",",
"{",
"'class'",
":",
"'jBox-image-download-button-text'",
"}",
")",
".",
"html",
"(",
"this",
".",
"options",
".",
"downloadButtonText",
")",
":",
"null",
")",
".",
"append",
"(",
"jQuery",
"(",
"'<div/>'",
",",
"{",
"'class'",
":",
"'jBox-image-download-button-icon'",
"}",
")",
")",
".",
"on",
"(",
"'click touchdown'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"images",
"[",
"this",
".",
"currentImage",
".",
"gallery",
"]",
"[",
"this",
".",
"currentImage",
".",
"id",
"]",
".",
"downloadUrl",
")",
"{",
"var",
"currentImageUrl",
"=",
"this",
".",
"images",
"[",
"this",
".",
"currentImage",
".",
"gallery",
"]",
"[",
"this",
".",
"currentImage",
".",
"id",
"]",
".",
"downloadUrl",
";",
"}",
"else",
"{",
"var",
"currentImage",
"=",
"this",
".",
"wrapper",
".",
"find",
"(",
"'.jBox-image-default-current'",
")",
";",
"var",
"currentImageStyle",
"=",
"currentImage",
"[",
"0",
"]",
".",
"style",
".",
"backgroundImage",
";",
"var",
"currentImageUrl",
"=",
"currentImageStyle",
".",
"slice",
"(",
"4",
",",
"-",
"1",
")",
".",
"replace",
"(",
"/",
"[\"']",
"/",
"g",
",",
"''",
")",
";",
"}",
"this",
".",
"downloadImage",
"(",
"currentImageUrl",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
"// Creating the image counter containers",
"if",
"(",
"this",
".",
"options",
".",
"imageCounter",
")",
"{",
"this",
".",
"imageCounter",
"=",
"jQuery",
"(",
"'<div/>'",
",",
"{",
"'class'",
":",
"'jBox-image-counter-container'",
"}",
")",
".",
"appendTo",
"(",
"this",
".",
"wrapper",
")",
";",
"this",
".",
"imageCounter",
".",
"append",
"(",
"jQuery",
"(",
"'<span/>'",
",",
"{",
"'class'",
":",
"'jBox-image-counter-current'",
"}",
")",
")",
".",
"append",
"(",
"jQuery",
"(",
"'<span/>'",
")",
".",
"html",
"(",
"this",
".",
"options",
".",
"imageCounterSeparator",
")",
")",
".",
"append",
"(",
"jQuery",
"(",
"'<span/>'",
",",
"{",
"'class'",
":",
"'jBox-image-counter-all'",
"}",
")",
")",
";",
"}",
"}"
] |
Triggered when jBox was created
|
[
"Triggered",
"when",
"jBox",
"was",
"created"
] |
63857f9529ad8f9c491d5a5bc7fe44135f74e927
|
https://github.com/StephanWagner/jBox/blob/63857f9529ad8f9c491d5a5bc7fe44135f74e927/dist/jBox.all.js#L2507-L2539
|
|
13,425
|
StephanWagner/jBox
|
dist/jBox.all.js
|
function ()
{
// Add key events
jQuery(document).on('keyup.jBox-Image-' + this.id, function (ev) {
(ev.keyCode == 37) && this.showImage('prev');
(ev.keyCode == 39) && this.showImage('next');
}.bind(this));
// Load the image from the attached element
this.showImage('open');
}
|
javascript
|
function ()
{
// Add key events
jQuery(document).on('keyup.jBox-Image-' + this.id, function (ev) {
(ev.keyCode == 37) && this.showImage('prev');
(ev.keyCode == 39) && this.showImage('next');
}.bind(this));
// Load the image from the attached element
this.showImage('open');
}
|
[
"function",
"(",
")",
"{",
"// Add key events",
"jQuery",
"(",
"document",
")",
".",
"on",
"(",
"'keyup.jBox-Image-'",
"+",
"this",
".",
"id",
",",
"function",
"(",
"ev",
")",
"{",
"(",
"ev",
".",
"keyCode",
"==",
"37",
")",
"&&",
"this",
".",
"showImage",
"(",
"'prev'",
")",
";",
"(",
"ev",
".",
"keyCode",
"==",
"39",
")",
"&&",
"this",
".",
"showImage",
"(",
"'next'",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"// Load the image from the attached element",
"this",
".",
"showImage",
"(",
"'open'",
")",
";",
"}"
] |
Triggered when jBox opens
|
[
"Triggered",
"when",
"jBox",
"opens"
] |
63857f9529ad8f9c491d5a5bc7fe44135f74e927
|
https://github.com/StephanWagner/jBox/blob/63857f9529ad8f9c491d5a5bc7fe44135f74e927/dist/jBox.all.js#L2544-L2554
|
|
13,426
|
StephanWagner/jBox
|
dist/jBox.all.js
|
function ()
{
// Cache position values
this.defaultNoticePosition = jQuery.extend({}, this.options.position);
// Type Notice has its own adjust position function
this._adjustNoticePositon = function () {
var win = jQuery(window);
var windowDimensions = {
x: win.width(),
y: win.height()
};
// Reset default position
this.options.position = jQuery.extend({}, this.defaultNoticePosition);
// Adjust depending on viewport
jQuery.each(this.options.responsivePositions, function (viewport, position) {
if (windowDimensions.x <= viewport) {
this.options.position = position;
return false;
}
}.bind(this));
// Set new padding options
this.options.adjustDistance = {
top: this.options.position.y,
right: this.options.position.x,
bottom: this.options.position.y,
left: this.options.position.x
};
};
// If jBox grabs an element as content, crab a clone instead
this.options.content instanceof jQuery && (this.options.content = this.options.content.clone().attr('id', ''));
// Adjust paddings when window resizes
jQuery(window).on('resize.responsivejBoxNotice-' + this.id, function (ev) { if (this.isOpen) { this._adjustNoticePositon(); } }.bind(this));
this.open();
}
|
javascript
|
function ()
{
// Cache position values
this.defaultNoticePosition = jQuery.extend({}, this.options.position);
// Type Notice has its own adjust position function
this._adjustNoticePositon = function () {
var win = jQuery(window);
var windowDimensions = {
x: win.width(),
y: win.height()
};
// Reset default position
this.options.position = jQuery.extend({}, this.defaultNoticePosition);
// Adjust depending on viewport
jQuery.each(this.options.responsivePositions, function (viewport, position) {
if (windowDimensions.x <= viewport) {
this.options.position = position;
return false;
}
}.bind(this));
// Set new padding options
this.options.adjustDistance = {
top: this.options.position.y,
right: this.options.position.x,
bottom: this.options.position.y,
left: this.options.position.x
};
};
// If jBox grabs an element as content, crab a clone instead
this.options.content instanceof jQuery && (this.options.content = this.options.content.clone().attr('id', ''));
// Adjust paddings when window resizes
jQuery(window).on('resize.responsivejBoxNotice-' + this.id, function (ev) { if (this.isOpen) { this._adjustNoticePositon(); } }.bind(this));
this.open();
}
|
[
"function",
"(",
")",
"{",
"// Cache position values",
"this",
".",
"defaultNoticePosition",
"=",
"jQuery",
".",
"extend",
"(",
"{",
"}",
",",
"this",
".",
"options",
".",
"position",
")",
";",
"// Type Notice has its own adjust position function",
"this",
".",
"_adjustNoticePositon",
"=",
"function",
"(",
")",
"{",
"var",
"win",
"=",
"jQuery",
"(",
"window",
")",
";",
"var",
"windowDimensions",
"=",
"{",
"x",
":",
"win",
".",
"width",
"(",
")",
",",
"y",
":",
"win",
".",
"height",
"(",
")",
"}",
";",
"// Reset default position",
"this",
".",
"options",
".",
"position",
"=",
"jQuery",
".",
"extend",
"(",
"{",
"}",
",",
"this",
".",
"defaultNoticePosition",
")",
";",
"// Adjust depending on viewport",
"jQuery",
".",
"each",
"(",
"this",
".",
"options",
".",
"responsivePositions",
",",
"function",
"(",
"viewport",
",",
"position",
")",
"{",
"if",
"(",
"windowDimensions",
".",
"x",
"<=",
"viewport",
")",
"{",
"this",
".",
"options",
".",
"position",
"=",
"position",
";",
"return",
"false",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"// Set new padding options",
"this",
".",
"options",
".",
"adjustDistance",
"=",
"{",
"top",
":",
"this",
".",
"options",
".",
"position",
".",
"y",
",",
"right",
":",
"this",
".",
"options",
".",
"position",
".",
"x",
",",
"bottom",
":",
"this",
".",
"options",
".",
"position",
".",
"y",
",",
"left",
":",
"this",
".",
"options",
".",
"position",
".",
"x",
"}",
";",
"}",
";",
"// If jBox grabs an element as content, crab a clone instead",
"this",
".",
"options",
".",
"content",
"instanceof",
"jQuery",
"&&",
"(",
"this",
".",
"options",
".",
"content",
"=",
"this",
".",
"options",
".",
"content",
".",
"clone",
"(",
")",
".",
"attr",
"(",
"'id'",
",",
"''",
")",
")",
";",
"// Adjust paddings when window resizes",
"jQuery",
"(",
"window",
")",
".",
"on",
"(",
"'resize.responsivejBoxNotice-'",
"+",
"this",
".",
"id",
",",
"function",
"(",
"ev",
")",
"{",
"if",
"(",
"this",
".",
"isOpen",
")",
"{",
"this",
".",
"_adjustNoticePositon",
"(",
")",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"open",
"(",
")",
";",
"}"
] |
Triggered when notice is initialized
|
[
"Triggered",
"when",
"notice",
"is",
"initialized"
] |
63857f9529ad8f9c491d5a5bc7fe44135f74e927
|
https://github.com/StephanWagner/jBox/blob/63857f9529ad8f9c491d5a5bc7fe44135f74e927/dist/jBox.all.js#L2626-L2666
|
|
13,427
|
StephanWagner/jBox
|
dist/jBox.all.js
|
function ()
{
// Bail if we're stacking
if (this.options.stack) {
return;
}
// Adjust position when opening
this._adjustNoticePositon();
// Loop through notices at same window corner destroy them
jQuery.each(jQuery('.jBox-Notice'), function (index, el)
{
el = jQuery(el);
// Abort if the element is this notice or when it's not at the same position
if (el.attr('id') == this.id || el.data('jBox-Notice-position') != this.options.attributes.x + '-' + this.options.attributes.y) {
return;
}
// Remove notice when we don't wont to stack them
if (!this.options.stack) {
el.data('jBox').close({ignoreDelay: true});
return;
}
}.bind(this));
}
|
javascript
|
function ()
{
// Bail if we're stacking
if (this.options.stack) {
return;
}
// Adjust position when opening
this._adjustNoticePositon();
// Loop through notices at same window corner destroy them
jQuery.each(jQuery('.jBox-Notice'), function (index, el)
{
el = jQuery(el);
// Abort if the element is this notice or when it's not at the same position
if (el.attr('id') == this.id || el.data('jBox-Notice-position') != this.options.attributes.x + '-' + this.options.attributes.y) {
return;
}
// Remove notice when we don't wont to stack them
if (!this.options.stack) {
el.data('jBox').close({ignoreDelay: true});
return;
}
}.bind(this));
}
|
[
"function",
"(",
")",
"{",
"// Bail if we're stacking",
"if",
"(",
"this",
".",
"options",
".",
"stack",
")",
"{",
"return",
";",
"}",
"// Adjust position when opening",
"this",
".",
"_adjustNoticePositon",
"(",
")",
";",
"// Loop through notices at same window corner destroy them",
"jQuery",
".",
"each",
"(",
"jQuery",
"(",
"'.jBox-Notice'",
")",
",",
"function",
"(",
"index",
",",
"el",
")",
"{",
"el",
"=",
"jQuery",
"(",
"el",
")",
";",
"// Abort if the element is this notice or when it's not at the same position",
"if",
"(",
"el",
".",
"attr",
"(",
"'id'",
")",
"==",
"this",
".",
"id",
"||",
"el",
".",
"data",
"(",
"'jBox-Notice-position'",
")",
"!=",
"this",
".",
"options",
".",
"attributes",
".",
"x",
"+",
"'-'",
"+",
"this",
".",
"options",
".",
"attributes",
".",
"y",
")",
"{",
"return",
";",
"}",
"// Remove notice when we don't wont to stack them",
"if",
"(",
"!",
"this",
".",
"options",
".",
"stack",
")",
"{",
"el",
".",
"data",
"(",
"'jBox'",
")",
".",
"close",
"(",
"{",
"ignoreDelay",
":",
"true",
"}",
")",
";",
"return",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] |
Triggered when notice opens
|
[
"Triggered",
"when",
"notice",
"opens"
] |
63857f9529ad8f9c491d5a5bc7fe44135f74e927
|
https://github.com/StephanWagner/jBox/blob/63857f9529ad8f9c491d5a5bc7fe44135f74e927/dist/jBox.all.js#L2683-L2709
|
|
13,428
|
StephanWagner/jBox
|
dist/jBox.all.js
|
function ()
{
var stacks = {};
jQuery.each(jQuery('.jBox-Notice'), function (index, el)
{
el = jQuery(el);
var pos = el.data('jBox-Notice-position');
if (!stacks[pos]) {
stacks[pos] = [];
}
stacks[pos].push(el);
});
for (var pos in stacks) {
var position = pos.split('-');
var direction = position[1];
stacks[pos].reverse();
var margin = 0;
for (var i in stacks[pos]) {
el = stacks[pos][i];
el.css('margin-' + direction, margin);
margin += el.outerHeight() + this.options.stackSpacing;
}
}
}
|
javascript
|
function ()
{
var stacks = {};
jQuery.each(jQuery('.jBox-Notice'), function (index, el)
{
el = jQuery(el);
var pos = el.data('jBox-Notice-position');
if (!stacks[pos]) {
stacks[pos] = [];
}
stacks[pos].push(el);
});
for (var pos in stacks) {
var position = pos.split('-');
var direction = position[1];
stacks[pos].reverse();
var margin = 0;
for (var i in stacks[pos]) {
el = stacks[pos][i];
el.css('margin-' + direction, margin);
margin += el.outerHeight() + this.options.stackSpacing;
}
}
}
|
[
"function",
"(",
")",
"{",
"var",
"stacks",
"=",
"{",
"}",
";",
"jQuery",
".",
"each",
"(",
"jQuery",
"(",
"'.jBox-Notice'",
")",
",",
"function",
"(",
"index",
",",
"el",
")",
"{",
"el",
"=",
"jQuery",
"(",
"el",
")",
";",
"var",
"pos",
"=",
"el",
".",
"data",
"(",
"'jBox-Notice-position'",
")",
";",
"if",
"(",
"!",
"stacks",
"[",
"pos",
"]",
")",
"{",
"stacks",
"[",
"pos",
"]",
"=",
"[",
"]",
";",
"}",
"stacks",
"[",
"pos",
"]",
".",
"push",
"(",
"el",
")",
";",
"}",
")",
";",
"for",
"(",
"var",
"pos",
"in",
"stacks",
")",
"{",
"var",
"position",
"=",
"pos",
".",
"split",
"(",
"'-'",
")",
";",
"var",
"direction",
"=",
"position",
"[",
"1",
"]",
";",
"stacks",
"[",
"pos",
"]",
".",
"reverse",
"(",
")",
";",
"var",
"margin",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"in",
"stacks",
"[",
"pos",
"]",
")",
"{",
"el",
"=",
"stacks",
"[",
"pos",
"]",
"[",
"i",
"]",
";",
"el",
".",
"css",
"(",
"'margin-'",
"+",
"direction",
",",
"margin",
")",
";",
"margin",
"+=",
"el",
".",
"outerHeight",
"(",
")",
"+",
"this",
".",
"options",
".",
"stackSpacing",
";",
"}",
"}",
"}"
] |
Triggered when resizing window etc.
|
[
"Triggered",
"when",
"resizing",
"window",
"etc",
"."
] |
63857f9529ad8f9c491d5a5bc7fe44135f74e927
|
https://github.com/StephanWagner/jBox/blob/63857f9529ad8f9c491d5a5bc7fe44135f74e927/dist/jBox.all.js#L2713-L2736
|
|
13,429
|
StephanWagner/jBox
|
Demo/Playground/Playground.Avatars.js
|
function () {
// Create the containers for the liked or disliked avatars
if (initial) {
$('<div id="LikedAvatars" class="AvatarsCollection"/>').appendTo($('body'));
$('<div id="DislikedAvatars" class="AvatarsCollection"/>').appendTo($('body'));
}
$.each(this.footer.find('button'), function (index, el) {
// Adding the click events for the buttons in the footer
$(el).on('click', function () {
// Storing a global var that the user clicked on a button
DemoAvatars.clicked = true;
// When a user clicks a button close the tooltips
DemoAvatars.AvatarsTooltipLike && DemoAvatars.AvatarsTooltipLike.close();
DemoAvatars.AvatarsTooltipDislike && DemoAvatars.AvatarsTooltipDislike.close();
// When we click a button, the jBox disappears, let's tell this jBox that we removed it
this.AvatarRemoved = true;
// Did we like or dislike the avatar?
var liked = $(el).hasClass('button-heart');
// Slide the jBox to the left or right depending on which button the user clicked
this.animate('slide' + (liked ? 'Right' : 'Left'), {
// Once the jBox is removed, hide it and show the avatar in the collection
complete: function () {
this.wrapper.css('display', 'none');
// Which container to use
var collectionContainer = liked ? $('#LikedAvatars') : $('#DislikedAvatars');
// If there if not enough space for the avatars to show in one line remove the first one
if (collectionContainer.find('div[data-avatar-tooltip]').length && ((collectionContainer.find('div[data-avatar-tooltip]').length + 1) * $(collectionContainer.find('div[data-avatar-tooltip]')[0]).outerWidth(true) > collectionContainer.outerWidth())) {
$(collectionContainer.find('div[data-avatar-tooltip]')[0]).remove();
}
// Add the avatar to the collection
this.animate('popIn', {
element: $('<div data-avatar-tooltip="You ' + (liked ? 'liked' : 'disliked') + ' ' + DemoAvatars.Avatars[this.AvatarIndex] + '"/>').append($('<div/>').html('<img src="https://stephanwagner.me/img/jBox/avatar/' + DemoAvatars.Avatars[this.AvatarIndex] + '.svg"/>')).appendTo(collectionContainer)
});
// Attach the avatar tooltip
DemoAvatars.AvatarsTooltip && DemoAvatars.AvatarsTooltip.attach();
}.bind(this)
});
// Open another Avatar jBox
generateAvatarJBox();
}.bind(this));
}.bind(this));
}
|
javascript
|
function () {
// Create the containers for the liked or disliked avatars
if (initial) {
$('<div id="LikedAvatars" class="AvatarsCollection"/>').appendTo($('body'));
$('<div id="DislikedAvatars" class="AvatarsCollection"/>').appendTo($('body'));
}
$.each(this.footer.find('button'), function (index, el) {
// Adding the click events for the buttons in the footer
$(el).on('click', function () {
// Storing a global var that the user clicked on a button
DemoAvatars.clicked = true;
// When a user clicks a button close the tooltips
DemoAvatars.AvatarsTooltipLike && DemoAvatars.AvatarsTooltipLike.close();
DemoAvatars.AvatarsTooltipDislike && DemoAvatars.AvatarsTooltipDislike.close();
// When we click a button, the jBox disappears, let's tell this jBox that we removed it
this.AvatarRemoved = true;
// Did we like or dislike the avatar?
var liked = $(el).hasClass('button-heart');
// Slide the jBox to the left or right depending on which button the user clicked
this.animate('slide' + (liked ? 'Right' : 'Left'), {
// Once the jBox is removed, hide it and show the avatar in the collection
complete: function () {
this.wrapper.css('display', 'none');
// Which container to use
var collectionContainer = liked ? $('#LikedAvatars') : $('#DislikedAvatars');
// If there if not enough space for the avatars to show in one line remove the first one
if (collectionContainer.find('div[data-avatar-tooltip]').length && ((collectionContainer.find('div[data-avatar-tooltip]').length + 1) * $(collectionContainer.find('div[data-avatar-tooltip]')[0]).outerWidth(true) > collectionContainer.outerWidth())) {
$(collectionContainer.find('div[data-avatar-tooltip]')[0]).remove();
}
// Add the avatar to the collection
this.animate('popIn', {
element: $('<div data-avatar-tooltip="You ' + (liked ? 'liked' : 'disliked') + ' ' + DemoAvatars.Avatars[this.AvatarIndex] + '"/>').append($('<div/>').html('<img src="https://stephanwagner.me/img/jBox/avatar/' + DemoAvatars.Avatars[this.AvatarIndex] + '.svg"/>')).appendTo(collectionContainer)
});
// Attach the avatar tooltip
DemoAvatars.AvatarsTooltip && DemoAvatars.AvatarsTooltip.attach();
}.bind(this)
});
// Open another Avatar jBox
generateAvatarJBox();
}.bind(this));
}.bind(this));
}
|
[
"function",
"(",
")",
"{",
"// Create the containers for the liked or disliked avatars",
"if",
"(",
"initial",
")",
"{",
"$",
"(",
"'<div id=\"LikedAvatars\" class=\"AvatarsCollection\"/>'",
")",
".",
"appendTo",
"(",
"$",
"(",
"'body'",
")",
")",
";",
"$",
"(",
"'<div id=\"DislikedAvatars\" class=\"AvatarsCollection\"/>'",
")",
".",
"appendTo",
"(",
"$",
"(",
"'body'",
")",
")",
";",
"}",
"$",
".",
"each",
"(",
"this",
".",
"footer",
".",
"find",
"(",
"'button'",
")",
",",
"function",
"(",
"index",
",",
"el",
")",
"{",
"// Adding the click events for the buttons in the footer",
"$",
"(",
"el",
")",
".",
"on",
"(",
"'click'",
",",
"function",
"(",
")",
"{",
"// Storing a global var that the user clicked on a button",
"DemoAvatars",
".",
"clicked",
"=",
"true",
";",
"// When a user clicks a button close the tooltips",
"DemoAvatars",
".",
"AvatarsTooltipLike",
"&&",
"DemoAvatars",
".",
"AvatarsTooltipLike",
".",
"close",
"(",
")",
";",
"DemoAvatars",
".",
"AvatarsTooltipDislike",
"&&",
"DemoAvatars",
".",
"AvatarsTooltipDislike",
".",
"close",
"(",
")",
";",
"// When we click a button, the jBox disappears, let's tell this jBox that we removed it",
"this",
".",
"AvatarRemoved",
"=",
"true",
";",
"// Did we like or dislike the avatar?",
"var",
"liked",
"=",
"$",
"(",
"el",
")",
".",
"hasClass",
"(",
"'button-heart'",
")",
";",
"// Slide the jBox to the left or right depending on which button the user clicked",
"this",
".",
"animate",
"(",
"'slide'",
"+",
"(",
"liked",
"?",
"'Right'",
":",
"'Left'",
")",
",",
"{",
"// Once the jBox is removed, hide it and show the avatar in the collection",
"complete",
":",
"function",
"(",
")",
"{",
"this",
".",
"wrapper",
".",
"css",
"(",
"'display'",
",",
"'none'",
")",
";",
"// Which container to use",
"var",
"collectionContainer",
"=",
"liked",
"?",
"$",
"(",
"'#LikedAvatars'",
")",
":",
"$",
"(",
"'#DislikedAvatars'",
")",
";",
"// If there if not enough space for the avatars to show in one line remove the first one",
"if",
"(",
"collectionContainer",
".",
"find",
"(",
"'div[data-avatar-tooltip]'",
")",
".",
"length",
"&&",
"(",
"(",
"collectionContainer",
".",
"find",
"(",
"'div[data-avatar-tooltip]'",
")",
".",
"length",
"+",
"1",
")",
"*",
"$",
"(",
"collectionContainer",
".",
"find",
"(",
"'div[data-avatar-tooltip]'",
")",
"[",
"0",
"]",
")",
".",
"outerWidth",
"(",
"true",
")",
">",
"collectionContainer",
".",
"outerWidth",
"(",
")",
")",
")",
"{",
"$",
"(",
"collectionContainer",
".",
"find",
"(",
"'div[data-avatar-tooltip]'",
")",
"[",
"0",
"]",
")",
".",
"remove",
"(",
")",
";",
"}",
"// Add the avatar to the collection",
"this",
".",
"animate",
"(",
"'popIn'",
",",
"{",
"element",
":",
"$",
"(",
"'<div data-avatar-tooltip=\"You '",
"+",
"(",
"liked",
"?",
"'liked'",
":",
"'disliked'",
")",
"+",
"' '",
"+",
"DemoAvatars",
".",
"Avatars",
"[",
"this",
".",
"AvatarIndex",
"]",
"+",
"'\"/>'",
")",
".",
"append",
"(",
"$",
"(",
"'<div/>'",
")",
".",
"html",
"(",
"'<img src=\"https://stephanwagner.me/img/jBox/avatar/'",
"+",
"DemoAvatars",
".",
"Avatars",
"[",
"this",
".",
"AvatarIndex",
"]",
"+",
"'.svg\"/>'",
")",
")",
".",
"appendTo",
"(",
"collectionContainer",
")",
"}",
")",
";",
"// Attach the avatar tooltip",
"DemoAvatars",
".",
"AvatarsTooltip",
"&&",
"DemoAvatars",
".",
"AvatarsTooltip",
".",
"attach",
"(",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
"}",
")",
";",
"// Open another Avatar jBox",
"generateAvatarJBox",
"(",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] |
When the jBox is created, add the click events to the buttons
|
[
"When",
"the",
"jBox",
"is",
"created",
"add",
"the",
"click",
"events",
"to",
"the",
"buttons"
] |
63857f9529ad8f9c491d5a5bc7fe44135f74e927
|
https://github.com/StephanWagner/jBox/blob/63857f9529ad8f9c491d5a5bc7fe44135f74e927/Demo/Playground/Playground.Avatars.js#L124-L181
|
|
13,430
|
StephanWagner/jBox
|
Demo/Playground/Playground.Avatars.js
|
function () {
// Set title and content depending on current index
this.setTitle(DemoAvatars.Avatars[DemoAvatars.current]);
this.content.css({backgroundImage: 'url(https://stephanwagner.me/img/jBox/avatar/' + DemoAvatars.Avatars[DemoAvatars.current] + '.svg)'});
// If it's the inital jBox, show the tooltips after a short delay
initial && setTimeout(function () {
// We are creating the two tooltips in a loop as they are very similar
$.each(['Dislike', 'Like'], function (index, item) {
// We store the tooltips in the global var so we can refer to them later
DemoAvatars['AvatarsTooltip' + item] = new jBox('Tooltip', {
theme: 'TooltipBorder',
addClass: 'AvatarsTooltip AvatarsTooltip' + item,
minWidth: 110,
content: item,
position: {
y: 'bottom'
},
offset: {
y: 5
},
target: '#AvatarsInitial .jBox-footer .button-' + (item == 'Like' ? 'heart' : 'cross'),
animation: 'move',
zIndex: 11000,
// Abort opening the tooltips when we clicked on a like or dislike button already
onOpen: function () {
DemoAvatars.clicked && this.close();
}
}).open();
});
}, 500);
}
|
javascript
|
function () {
// Set title and content depending on current index
this.setTitle(DemoAvatars.Avatars[DemoAvatars.current]);
this.content.css({backgroundImage: 'url(https://stephanwagner.me/img/jBox/avatar/' + DemoAvatars.Avatars[DemoAvatars.current] + '.svg)'});
// If it's the inital jBox, show the tooltips after a short delay
initial && setTimeout(function () {
// We are creating the two tooltips in a loop as they are very similar
$.each(['Dislike', 'Like'], function (index, item) {
// We store the tooltips in the global var so we can refer to them later
DemoAvatars['AvatarsTooltip' + item] = new jBox('Tooltip', {
theme: 'TooltipBorder',
addClass: 'AvatarsTooltip AvatarsTooltip' + item,
minWidth: 110,
content: item,
position: {
y: 'bottom'
},
offset: {
y: 5
},
target: '#AvatarsInitial .jBox-footer .button-' + (item == 'Like' ? 'heart' : 'cross'),
animation: 'move',
zIndex: 11000,
// Abort opening the tooltips when we clicked on a like or dislike button already
onOpen: function () {
DemoAvatars.clicked && this.close();
}
}).open();
});
}, 500);
}
|
[
"function",
"(",
")",
"{",
"// Set title and content depending on current index",
"this",
".",
"setTitle",
"(",
"DemoAvatars",
".",
"Avatars",
"[",
"DemoAvatars",
".",
"current",
"]",
")",
";",
"this",
".",
"content",
".",
"css",
"(",
"{",
"backgroundImage",
":",
"'url(https://stephanwagner.me/img/jBox/avatar/'",
"+",
"DemoAvatars",
".",
"Avatars",
"[",
"DemoAvatars",
".",
"current",
"]",
"+",
"'.svg)'",
"}",
")",
";",
"// If it's the inital jBox, show the tooltips after a short delay",
"initial",
"&&",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"// We are creating the two tooltips in a loop as they are very similar",
"$",
".",
"each",
"(",
"[",
"'Dislike'",
",",
"'Like'",
"]",
",",
"function",
"(",
"index",
",",
"item",
")",
"{",
"// We store the tooltips in the global var so we can refer to them later",
"DemoAvatars",
"[",
"'AvatarsTooltip'",
"+",
"item",
"]",
"=",
"new",
"jBox",
"(",
"'Tooltip'",
",",
"{",
"theme",
":",
"'TooltipBorder'",
",",
"addClass",
":",
"'AvatarsTooltip AvatarsTooltip'",
"+",
"item",
",",
"minWidth",
":",
"110",
",",
"content",
":",
"item",
",",
"position",
":",
"{",
"y",
":",
"'bottom'",
"}",
",",
"offset",
":",
"{",
"y",
":",
"5",
"}",
",",
"target",
":",
"'#AvatarsInitial .jBox-footer .button-'",
"+",
"(",
"item",
"==",
"'Like'",
"?",
"'heart'",
":",
"'cross'",
")",
",",
"animation",
":",
"'move'",
",",
"zIndex",
":",
"11000",
",",
"// Abort opening the tooltips when we clicked on a like or dislike button already",
"onOpen",
":",
"function",
"(",
")",
"{",
"DemoAvatars",
".",
"clicked",
"&&",
"this",
".",
"close",
"(",
")",
";",
"}",
"}",
")",
".",
"open",
"(",
")",
";",
"}",
")",
";",
"}",
",",
"500",
")",
";",
"}"
] |
When we open the jBox, set the new content and show the tooltips if it's the initial jBox
|
[
"When",
"we",
"open",
"the",
"jBox",
"set",
"the",
"new",
"content",
"and",
"show",
"the",
"tooltips",
"if",
"it",
"s",
"the",
"initial",
"jBox"
] |
63857f9529ad8f9c491d5a5bc7fe44135f74e927
|
https://github.com/StephanWagner/jBox/blob/63857f9529ad8f9c491d5a5bc7fe44135f74e927/Demo/Playground/Playground.Avatars.js#L184-L221
|
|
13,431
|
minio/minio-js
|
src/main/signing.js
|
getCredential
|
function getCredential(accessKey, region, requestDate) {
if (!isString(accessKey)) {
throw new TypeError('accessKey should be of type "string"')
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"')
}
if (!isObject(requestDate)) {
throw new TypeError('requestDate should be of type "object"')
}
return `${accessKey}/${getScope(region, requestDate)}`
}
|
javascript
|
function getCredential(accessKey, region, requestDate) {
if (!isString(accessKey)) {
throw new TypeError('accessKey should be of type "string"')
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"')
}
if (!isObject(requestDate)) {
throw new TypeError('requestDate should be of type "object"')
}
return `${accessKey}/${getScope(region, requestDate)}`
}
|
[
"function",
"getCredential",
"(",
"accessKey",
",",
"region",
",",
"requestDate",
")",
"{",
"if",
"(",
"!",
"isString",
"(",
"accessKey",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'accessKey should be of type \"string\"'",
")",
"}",
"if",
"(",
"!",
"isString",
"(",
"region",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'region should be of type \"string\"'",
")",
"}",
"if",
"(",
"!",
"isObject",
"(",
"requestDate",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'requestDate should be of type \"object\"'",
")",
"}",
"return",
"`",
"${",
"accessKey",
"}",
"${",
"getScope",
"(",
"region",
",",
"requestDate",
")",
"}",
"`",
"}"
] |
generate a credential string
|
[
"generate",
"a",
"credential",
"string"
] |
84a3e57809499c8dafb8afb4abf5162dd22c95ef
|
https://github.com/minio/minio-js/blob/84a3e57809499c8dafb8afb4abf5162dd22c95ef/src/main/signing.js#L79-L90
|
13,432
|
minio/minio-js
|
src/main/signing.js
|
getSignedHeaders
|
function getSignedHeaders(headers) {
if (!isObject(headers)) {
throw new TypeError('request should be of type "object"')
}
// Excerpts from @lsegal - https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258
//
// User-Agent:
//
// This is ignored from signing because signing this causes problems with generating pre-signed URLs
// (that are executed by other agents) or when customers pass requests through proxies, which may
// modify the user-agent.
//
// Content-Length:
//
// This is ignored from signing because generating a pre-signed URL should not provide a content-length
// constraint, specifically when vending a S3 pre-signed PUT URL. The corollary to this is that when
// sending regular requests (non-pre-signed), the signature contains a checksum of the body, which
// implicitly validates the payload length (since changing the number of bytes would change the checksum)
// and therefore this header is not valuable in the signature.
//
// Content-Type:
//
// Signing this header causes quite a number of problems in browser environments, where browsers
// like to modify and normalize the content-type header in different ways. There is more information
// on this in https://github.com/aws/aws-sdk-js/issues/244. Avoiding this field simplifies logic
// and reduces the possibility of future bugs
//
// Authorization:
//
// Is skipped for obvious reasons
var ignoredHeaders = ['authorization', 'content-length', 'content-type', 'user-agent']
return _.map(headers, (v, header) => header)
.filter(header => ignoredHeaders.indexOf(header) === -1)
.sort()
}
|
javascript
|
function getSignedHeaders(headers) {
if (!isObject(headers)) {
throw new TypeError('request should be of type "object"')
}
// Excerpts from @lsegal - https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258
//
// User-Agent:
//
// This is ignored from signing because signing this causes problems with generating pre-signed URLs
// (that are executed by other agents) or when customers pass requests through proxies, which may
// modify the user-agent.
//
// Content-Length:
//
// This is ignored from signing because generating a pre-signed URL should not provide a content-length
// constraint, specifically when vending a S3 pre-signed PUT URL. The corollary to this is that when
// sending regular requests (non-pre-signed), the signature contains a checksum of the body, which
// implicitly validates the payload length (since changing the number of bytes would change the checksum)
// and therefore this header is not valuable in the signature.
//
// Content-Type:
//
// Signing this header causes quite a number of problems in browser environments, where browsers
// like to modify and normalize the content-type header in different ways. There is more information
// on this in https://github.com/aws/aws-sdk-js/issues/244. Avoiding this field simplifies logic
// and reduces the possibility of future bugs
//
// Authorization:
//
// Is skipped for obvious reasons
var ignoredHeaders = ['authorization', 'content-length', 'content-type', 'user-agent']
return _.map(headers, (v, header) => header)
.filter(header => ignoredHeaders.indexOf(header) === -1)
.sort()
}
|
[
"function",
"getSignedHeaders",
"(",
"headers",
")",
"{",
"if",
"(",
"!",
"isObject",
"(",
"headers",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'request should be of type \"object\"'",
")",
"}",
"// Excerpts from @lsegal - https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258",
"//",
"// User-Agent:",
"//",
"// This is ignored from signing because signing this causes problems with generating pre-signed URLs",
"// (that are executed by other agents) or when customers pass requests through proxies, which may",
"// modify the user-agent.",
"//",
"// Content-Length:",
"//",
"// This is ignored from signing because generating a pre-signed URL should not provide a content-length",
"// constraint, specifically when vending a S3 pre-signed PUT URL. The corollary to this is that when",
"// sending regular requests (non-pre-signed), the signature contains a checksum of the body, which",
"// implicitly validates the payload length (since changing the number of bytes would change the checksum)",
"// and therefore this header is not valuable in the signature.",
"//",
"// Content-Type:",
"//",
"// Signing this header causes quite a number of problems in browser environments, where browsers",
"// like to modify and normalize the content-type header in different ways. There is more information",
"// on this in https://github.com/aws/aws-sdk-js/issues/244. Avoiding this field simplifies logic",
"// and reduces the possibility of future bugs",
"//",
"// Authorization:",
"//",
"// Is skipped for obvious reasons",
"var",
"ignoredHeaders",
"=",
"[",
"'authorization'",
",",
"'content-length'",
",",
"'content-type'",
",",
"'user-agent'",
"]",
"return",
"_",
".",
"map",
"(",
"headers",
",",
"(",
"v",
",",
"header",
")",
"=>",
"header",
")",
".",
"filter",
"(",
"header",
"=>",
"ignoredHeaders",
".",
"indexOf",
"(",
"header",
")",
"===",
"-",
"1",
")",
".",
"sort",
"(",
")",
"}"
] |
Returns signed headers array - alphabetically sorted
|
[
"Returns",
"signed",
"headers",
"array",
"-",
"alphabetically",
"sorted"
] |
84a3e57809499c8dafb8afb4abf5162dd22c95ef
|
https://github.com/minio/minio-js/blob/84a3e57809499c8dafb8afb4abf5162dd22c95ef/src/main/signing.js#L93-L128
|
13,433
|
minio/minio-js
|
src/main/signing.js
|
getSigningKey
|
function getSigningKey(date, region, secretKey) {
if (!isObject(date)) {
throw new TypeError('date should be of type "object"')
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"')
}
if (!isString(secretKey)) {
throw new TypeError('secretKey should be of type "string"')
}
var dateLine = makeDateShort(date),
hmac1 = Crypto.createHmac('sha256', 'AWS4' + secretKey).update(dateLine).digest(),
hmac2 = Crypto.createHmac('sha256', hmac1).update(region).digest(),
hmac3 = Crypto.createHmac('sha256', hmac2).update('s3').digest()
return Crypto.createHmac('sha256', hmac3).update('aws4_request').digest()
}
|
javascript
|
function getSigningKey(date, region, secretKey) {
if (!isObject(date)) {
throw new TypeError('date should be of type "object"')
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"')
}
if (!isString(secretKey)) {
throw new TypeError('secretKey should be of type "string"')
}
var dateLine = makeDateShort(date),
hmac1 = Crypto.createHmac('sha256', 'AWS4' + secretKey).update(dateLine).digest(),
hmac2 = Crypto.createHmac('sha256', hmac1).update(region).digest(),
hmac3 = Crypto.createHmac('sha256', hmac2).update('s3').digest()
return Crypto.createHmac('sha256', hmac3).update('aws4_request').digest()
}
|
[
"function",
"getSigningKey",
"(",
"date",
",",
"region",
",",
"secretKey",
")",
"{",
"if",
"(",
"!",
"isObject",
"(",
"date",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'date should be of type \"object\"'",
")",
"}",
"if",
"(",
"!",
"isString",
"(",
"region",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'region should be of type \"string\"'",
")",
"}",
"if",
"(",
"!",
"isString",
"(",
"secretKey",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'secretKey should be of type \"string\"'",
")",
"}",
"var",
"dateLine",
"=",
"makeDateShort",
"(",
"date",
")",
",",
"hmac1",
"=",
"Crypto",
".",
"createHmac",
"(",
"'sha256'",
",",
"'AWS4'",
"+",
"secretKey",
")",
".",
"update",
"(",
"dateLine",
")",
".",
"digest",
"(",
")",
",",
"hmac2",
"=",
"Crypto",
".",
"createHmac",
"(",
"'sha256'",
",",
"hmac1",
")",
".",
"update",
"(",
"region",
")",
".",
"digest",
"(",
")",
",",
"hmac3",
"=",
"Crypto",
".",
"createHmac",
"(",
"'sha256'",
",",
"hmac2",
")",
".",
"update",
"(",
"'s3'",
")",
".",
"digest",
"(",
")",
"return",
"Crypto",
".",
"createHmac",
"(",
"'sha256'",
",",
"hmac3",
")",
".",
"update",
"(",
"'aws4_request'",
")",
".",
"digest",
"(",
")",
"}"
] |
returns the key used for calculating signature
|
[
"returns",
"the",
"key",
"used",
"for",
"calculating",
"signature"
] |
84a3e57809499c8dafb8afb4abf5162dd22c95ef
|
https://github.com/minio/minio-js/blob/84a3e57809499c8dafb8afb4abf5162dd22c95ef/src/main/signing.js#L131-L146
|
13,434
|
minio/minio-js
|
src/main/signing.js
|
getStringToSign
|
function getStringToSign(canonicalRequest, requestDate, region) {
if (!isString(canonicalRequest)) {
throw new TypeError('canonicalRequest should be of type "string"')
}
if (!isObject(requestDate)) {
throw new TypeError('requestDate should be of type "object"')
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"')
}
var hash = Crypto.createHash('sha256').update(canonicalRequest).digest('hex')
var scope = getScope(region, requestDate)
var stringToSign = []
stringToSign.push(signV4Algorithm)
stringToSign.push(makeDateLong(requestDate))
stringToSign.push(scope)
stringToSign.push(hash)
return stringToSign.join('\n')
}
|
javascript
|
function getStringToSign(canonicalRequest, requestDate, region) {
if (!isString(canonicalRequest)) {
throw new TypeError('canonicalRequest should be of type "string"')
}
if (!isObject(requestDate)) {
throw new TypeError('requestDate should be of type "object"')
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"')
}
var hash = Crypto.createHash('sha256').update(canonicalRequest).digest('hex')
var scope = getScope(region, requestDate)
var stringToSign = []
stringToSign.push(signV4Algorithm)
stringToSign.push(makeDateLong(requestDate))
stringToSign.push(scope)
stringToSign.push(hash)
return stringToSign.join('\n')
}
|
[
"function",
"getStringToSign",
"(",
"canonicalRequest",
",",
"requestDate",
",",
"region",
")",
"{",
"if",
"(",
"!",
"isString",
"(",
"canonicalRequest",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'canonicalRequest should be of type \"string\"'",
")",
"}",
"if",
"(",
"!",
"isObject",
"(",
"requestDate",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'requestDate should be of type \"object\"'",
")",
"}",
"if",
"(",
"!",
"isString",
"(",
"region",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'region should be of type \"string\"'",
")",
"}",
"var",
"hash",
"=",
"Crypto",
".",
"createHash",
"(",
"'sha256'",
")",
".",
"update",
"(",
"canonicalRequest",
")",
".",
"digest",
"(",
"'hex'",
")",
"var",
"scope",
"=",
"getScope",
"(",
"region",
",",
"requestDate",
")",
"var",
"stringToSign",
"=",
"[",
"]",
"stringToSign",
".",
"push",
"(",
"signV4Algorithm",
")",
"stringToSign",
".",
"push",
"(",
"makeDateLong",
"(",
"requestDate",
")",
")",
"stringToSign",
".",
"push",
"(",
"scope",
")",
"stringToSign",
".",
"push",
"(",
"hash",
")",
"return",
"stringToSign",
".",
"join",
"(",
"'\\n'",
")",
"}"
] |
returns the string that needs to be signed
|
[
"returns",
"the",
"string",
"that",
"needs",
"to",
"be",
"signed"
] |
84a3e57809499c8dafb8afb4abf5162dd22c95ef
|
https://github.com/minio/minio-js/blob/84a3e57809499c8dafb8afb4abf5162dd22c95ef/src/main/signing.js#L149-L167
|
13,435
|
watson/bonjour
|
lib/registry.js
|
probe
|
function probe (mdns, service, cb) {
var sent = false
var retries = 0
var timer
mdns.on('response', onresponse)
setTimeout(send, Math.random() * 250)
function send () {
// abort if the service have or is being stopped in the meantime
if (!service._activated || service._destroyed) return
mdns.query(service.fqdn, 'ANY', function () {
// This function will optionally be called with an error object. We'll
// just silently ignore it and retry as we normally would
sent = true
timer = setTimeout(++retries < 3 ? send : done, 250)
timer.unref()
})
}
function onresponse (packet) {
// Apparently conflicting Multicast DNS responses received *before*
// the first probe packet is sent MUST be silently ignored (see
// discussion of stale probe packets in RFC 6762 Section 8.2,
// "Simultaneous Probe Tiebreaking" at
// https://tools.ietf.org/html/rfc6762#section-8.2
if (!sent) return
if (packet.answers.some(matchRR) || packet.additionals.some(matchRR)) done(true)
}
function matchRR (rr) {
return dnsEqual(rr.name, service.fqdn)
}
function done (exists) {
mdns.removeListener('response', onresponse)
clearTimeout(timer)
cb(!!exists)
}
}
|
javascript
|
function probe (mdns, service, cb) {
var sent = false
var retries = 0
var timer
mdns.on('response', onresponse)
setTimeout(send, Math.random() * 250)
function send () {
// abort if the service have or is being stopped in the meantime
if (!service._activated || service._destroyed) return
mdns.query(service.fqdn, 'ANY', function () {
// This function will optionally be called with an error object. We'll
// just silently ignore it and retry as we normally would
sent = true
timer = setTimeout(++retries < 3 ? send : done, 250)
timer.unref()
})
}
function onresponse (packet) {
// Apparently conflicting Multicast DNS responses received *before*
// the first probe packet is sent MUST be silently ignored (see
// discussion of stale probe packets in RFC 6762 Section 8.2,
// "Simultaneous Probe Tiebreaking" at
// https://tools.ietf.org/html/rfc6762#section-8.2
if (!sent) return
if (packet.answers.some(matchRR) || packet.additionals.some(matchRR)) done(true)
}
function matchRR (rr) {
return dnsEqual(rr.name, service.fqdn)
}
function done (exists) {
mdns.removeListener('response', onresponse)
clearTimeout(timer)
cb(!!exists)
}
}
|
[
"function",
"probe",
"(",
"mdns",
",",
"service",
",",
"cb",
")",
"{",
"var",
"sent",
"=",
"false",
"var",
"retries",
"=",
"0",
"var",
"timer",
"mdns",
".",
"on",
"(",
"'response'",
",",
"onresponse",
")",
"setTimeout",
"(",
"send",
",",
"Math",
".",
"random",
"(",
")",
"*",
"250",
")",
"function",
"send",
"(",
")",
"{",
"// abort if the service have or is being stopped in the meantime",
"if",
"(",
"!",
"service",
".",
"_activated",
"||",
"service",
".",
"_destroyed",
")",
"return",
"mdns",
".",
"query",
"(",
"service",
".",
"fqdn",
",",
"'ANY'",
",",
"function",
"(",
")",
"{",
"// This function will optionally be called with an error object. We'll",
"// just silently ignore it and retry as we normally would",
"sent",
"=",
"true",
"timer",
"=",
"setTimeout",
"(",
"++",
"retries",
"<",
"3",
"?",
"send",
":",
"done",
",",
"250",
")",
"timer",
".",
"unref",
"(",
")",
"}",
")",
"}",
"function",
"onresponse",
"(",
"packet",
")",
"{",
"// Apparently conflicting Multicast DNS responses received *before*",
"// the first probe packet is sent MUST be silently ignored (see",
"// discussion of stale probe packets in RFC 6762 Section 8.2,",
"// \"Simultaneous Probe Tiebreaking\" at",
"// https://tools.ietf.org/html/rfc6762#section-8.2",
"if",
"(",
"!",
"sent",
")",
"return",
"if",
"(",
"packet",
".",
"answers",
".",
"some",
"(",
"matchRR",
")",
"||",
"packet",
".",
"additionals",
".",
"some",
"(",
"matchRR",
")",
")",
"done",
"(",
"true",
")",
"}",
"function",
"matchRR",
"(",
"rr",
")",
"{",
"return",
"dnsEqual",
"(",
"rr",
".",
"name",
",",
"service",
".",
"fqdn",
")",
"}",
"function",
"done",
"(",
"exists",
")",
"{",
"mdns",
".",
"removeListener",
"(",
"'response'",
",",
"onresponse",
")",
"clearTimeout",
"(",
"timer",
")",
"cb",
"(",
"!",
"!",
"exists",
")",
"}",
"}"
] |
Check if a service name is already in use on the network.
Used before announcing the new service.
To guard against race conditions where multiple services are started
simultaneously on the network, wait a random amount of time (between
0 and 250 ms) before probing.
TODO: Add support for Simultaneous Probe Tiebreaking:
https://tools.ietf.org/html/rfc6762#section-8.2
|
[
"Check",
"if",
"a",
"service",
"name",
"is",
"already",
"in",
"use",
"on",
"the",
"network",
"."
] |
bdc467a4f3c7b9fe8bc54468b6fc4d80b8f1c098
|
https://github.com/watson/bonjour/blob/bdc467a4f3c7b9fe8bc54468b6fc4d80b8f1c098/lib/registry.js#L78-L119
|
13,436
|
watson/bonjour
|
lib/registry.js
|
announce
|
function announce (server, service) {
var delay = 1000
var packet = service._records()
server.register(packet)
;(function broadcast () {
// abort if the service have or is being stopped in the meantime
if (!service._activated || service._destroyed) return
server.mdns.respond(packet, function () {
// This function will optionally be called with an error object. We'll
// just silently ignore it and retry as we normally would
if (!service.published) {
service._activated = true
service.published = true
service.emit('up')
}
delay = delay * REANNOUNCE_FACTOR
if (delay < REANNOUNCE_MAX_MS && !service._destroyed) {
setTimeout(broadcast, delay).unref()
}
})
})()
}
|
javascript
|
function announce (server, service) {
var delay = 1000
var packet = service._records()
server.register(packet)
;(function broadcast () {
// abort if the service have or is being stopped in the meantime
if (!service._activated || service._destroyed) return
server.mdns.respond(packet, function () {
// This function will optionally be called with an error object. We'll
// just silently ignore it and retry as we normally would
if (!service.published) {
service._activated = true
service.published = true
service.emit('up')
}
delay = delay * REANNOUNCE_FACTOR
if (delay < REANNOUNCE_MAX_MS && !service._destroyed) {
setTimeout(broadcast, delay).unref()
}
})
})()
}
|
[
"function",
"announce",
"(",
"server",
",",
"service",
")",
"{",
"var",
"delay",
"=",
"1000",
"var",
"packet",
"=",
"service",
".",
"_records",
"(",
")",
"server",
".",
"register",
"(",
"packet",
")",
";",
"(",
"function",
"broadcast",
"(",
")",
"{",
"// abort if the service have or is being stopped in the meantime",
"if",
"(",
"!",
"service",
".",
"_activated",
"||",
"service",
".",
"_destroyed",
")",
"return",
"server",
".",
"mdns",
".",
"respond",
"(",
"packet",
",",
"function",
"(",
")",
"{",
"// This function will optionally be called with an error object. We'll",
"// just silently ignore it and retry as we normally would",
"if",
"(",
"!",
"service",
".",
"published",
")",
"{",
"service",
".",
"_activated",
"=",
"true",
"service",
".",
"published",
"=",
"true",
"service",
".",
"emit",
"(",
"'up'",
")",
"}",
"delay",
"=",
"delay",
"*",
"REANNOUNCE_FACTOR",
"if",
"(",
"delay",
"<",
"REANNOUNCE_MAX_MS",
"&&",
"!",
"service",
".",
"_destroyed",
")",
"{",
"setTimeout",
"(",
"broadcast",
",",
"delay",
")",
".",
"unref",
"(",
")",
"}",
"}",
")",
"}",
")",
"(",
")",
"}"
] |
Initial service announcement
Used to announce new services when they are first registered.
Broadcasts right away, then after 3 seconds, 9 seconds, 27 seconds,
and so on, up to a maximum interval of one hour.
|
[
"Initial",
"service",
"announcement"
] |
bdc467a4f3c7b9fe8bc54468b6fc4d80b8f1c098
|
https://github.com/watson/bonjour/blob/bdc467a4f3c7b9fe8bc54468b6fc4d80b8f1c098/lib/registry.js#L129-L153
|
13,437
|
watson/bonjour
|
lib/registry.js
|
teardown
|
function teardown (server, services, cb) {
if (!Array.isArray(services)) services = [services]
services = services.filter(function (service) {
return service._activated // ignore services not currently starting or started
})
var records = flatten.depth(services.map(function (service) {
service._activated = false
var records = service._records()
records.forEach(function (record) {
record.ttl = 0 // prepare goodbye message
})
return records
}), 1)
if (records.length === 0) return cb && cb()
server.unregister(records)
// send goodbye message
server.mdns.respond(records, function () {
services.forEach(function (service) {
service.published = false
})
if (cb) cb.apply(null, arguments)
})
}
|
javascript
|
function teardown (server, services, cb) {
if (!Array.isArray(services)) services = [services]
services = services.filter(function (service) {
return service._activated // ignore services not currently starting or started
})
var records = flatten.depth(services.map(function (service) {
service._activated = false
var records = service._records()
records.forEach(function (record) {
record.ttl = 0 // prepare goodbye message
})
return records
}), 1)
if (records.length === 0) return cb && cb()
server.unregister(records)
// send goodbye message
server.mdns.respond(records, function () {
services.forEach(function (service) {
service.published = false
})
if (cb) cb.apply(null, arguments)
})
}
|
[
"function",
"teardown",
"(",
"server",
",",
"services",
",",
"cb",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"services",
")",
")",
"services",
"=",
"[",
"services",
"]",
"services",
"=",
"services",
".",
"filter",
"(",
"function",
"(",
"service",
")",
"{",
"return",
"service",
".",
"_activated",
"// ignore services not currently starting or started",
"}",
")",
"var",
"records",
"=",
"flatten",
".",
"depth",
"(",
"services",
".",
"map",
"(",
"function",
"(",
"service",
")",
"{",
"service",
".",
"_activated",
"=",
"false",
"var",
"records",
"=",
"service",
".",
"_records",
"(",
")",
"records",
".",
"forEach",
"(",
"function",
"(",
"record",
")",
"{",
"record",
".",
"ttl",
"=",
"0",
"// prepare goodbye message",
"}",
")",
"return",
"records",
"}",
")",
",",
"1",
")",
"if",
"(",
"records",
".",
"length",
"===",
"0",
")",
"return",
"cb",
"&&",
"cb",
"(",
")",
"server",
".",
"unregister",
"(",
"records",
")",
"// send goodbye message",
"server",
".",
"mdns",
".",
"respond",
"(",
"records",
",",
"function",
"(",
")",
"{",
"services",
".",
"forEach",
"(",
"function",
"(",
"service",
")",
"{",
"service",
".",
"published",
"=",
"false",
"}",
")",
"if",
"(",
"cb",
")",
"cb",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
"}",
")",
"}"
] |
Stop the given services
Besides removing a service from the mDNS registry, a "goodbye"
message is sent for each service to let the network know about the
shutdown.
|
[
"Stop",
"the",
"given",
"services"
] |
bdc467a4f3c7b9fe8bc54468b6fc4d80b8f1c098
|
https://github.com/watson/bonjour/blob/bdc467a4f3c7b9fe8bc54468b6fc4d80b8f1c098/lib/registry.js#L162-L189
|
13,438
|
watson/bonjour
|
lib/browser.js
|
Browser
|
function Browser (mdns, opts, onup) {
if (typeof opts === 'function') return new Browser(mdns, null, opts)
EventEmitter.call(this)
this._mdns = mdns
this._onresponse = null
this._serviceMap = {}
this._txt = dnsTxt(opts.txt)
if (!opts || !opts.type) {
this._name = WILDCARD
this._wildcard = true
} else {
this._name = serviceName.stringify(opts.type, opts.protocol || 'tcp') + TLD
if (opts.name) this._name = opts.name + '.' + this._name
this._wildcard = false
}
this.services = []
if (onup) this.on('up', onup)
this.start()
}
|
javascript
|
function Browser (mdns, opts, onup) {
if (typeof opts === 'function') return new Browser(mdns, null, opts)
EventEmitter.call(this)
this._mdns = mdns
this._onresponse = null
this._serviceMap = {}
this._txt = dnsTxt(opts.txt)
if (!opts || !opts.type) {
this._name = WILDCARD
this._wildcard = true
} else {
this._name = serviceName.stringify(opts.type, opts.protocol || 'tcp') + TLD
if (opts.name) this._name = opts.name + '.' + this._name
this._wildcard = false
}
this.services = []
if (onup) this.on('up', onup)
this.start()
}
|
[
"function",
"Browser",
"(",
"mdns",
",",
"opts",
",",
"onup",
")",
"{",
"if",
"(",
"typeof",
"opts",
"===",
"'function'",
")",
"return",
"new",
"Browser",
"(",
"mdns",
",",
"null",
",",
"opts",
")",
"EventEmitter",
".",
"call",
"(",
"this",
")",
"this",
".",
"_mdns",
"=",
"mdns",
"this",
".",
"_onresponse",
"=",
"null",
"this",
".",
"_serviceMap",
"=",
"{",
"}",
"this",
".",
"_txt",
"=",
"dnsTxt",
"(",
"opts",
".",
"txt",
")",
"if",
"(",
"!",
"opts",
"||",
"!",
"opts",
".",
"type",
")",
"{",
"this",
".",
"_name",
"=",
"WILDCARD",
"this",
".",
"_wildcard",
"=",
"true",
"}",
"else",
"{",
"this",
".",
"_name",
"=",
"serviceName",
".",
"stringify",
"(",
"opts",
".",
"type",
",",
"opts",
".",
"protocol",
"||",
"'tcp'",
")",
"+",
"TLD",
"if",
"(",
"opts",
".",
"name",
")",
"this",
".",
"_name",
"=",
"opts",
".",
"name",
"+",
"'.'",
"+",
"this",
".",
"_name",
"this",
".",
"_wildcard",
"=",
"false",
"}",
"this",
".",
"services",
"=",
"[",
"]",
"if",
"(",
"onup",
")",
"this",
".",
"on",
"(",
"'up'",
",",
"onup",
")",
"this",
".",
"start",
"(",
")",
"}"
] |
Start a browser
The browser listens for services by querying for PTR records of a given
type, protocol and domain, e.g. _http._tcp.local.
If no type is given, a wild card search is performed.
An internal list of online services is kept which starts out empty. When
ever a new service is discovered, it's added to the list and an "up" event
is emitted with that service. When it's discovered that the service is no
longer available, it is removed from the list and a "down" event is emitted
with that service.
|
[
"Start",
"a",
"browser"
] |
bdc467a4f3c7b9fe8bc54468b6fc4d80b8f1c098
|
https://github.com/watson/bonjour/blob/bdc467a4f3c7b9fe8bc54468b6fc4d80b8f1c098/lib/browser.js#L30-L54
|
13,439
|
ocombe/ocLazyLoad
|
examples/requireJSExample/js/ng-grid-2.0.11.debug.js
|
function (obj, columnName) {
if (typeof obj !== "object" || typeof columnName !== "string") {
return obj;
}
var args = columnName.split('.');
var cObj = obj;
if (args.length > 1) {
for (var i = 1, len = args.length; i < len; i++) {
cObj = cObj[args[i]];
if (!cObj) {
return obj;
}
}
return cObj;
}
return obj;
}
|
javascript
|
function (obj, columnName) {
if (typeof obj !== "object" || typeof columnName !== "string") {
return obj;
}
var args = columnName.split('.');
var cObj = obj;
if (args.length > 1) {
for (var i = 1, len = args.length; i < len; i++) {
cObj = cObj[args[i]];
if (!cObj) {
return obj;
}
}
return cObj;
}
return obj;
}
|
[
"function",
"(",
"obj",
",",
"columnName",
")",
"{",
"if",
"(",
"typeof",
"obj",
"!==",
"\"object\"",
"||",
"typeof",
"columnName",
"!==",
"\"string\"",
")",
"{",
"return",
"obj",
";",
"}",
"var",
"args",
"=",
"columnName",
".",
"split",
"(",
"'.'",
")",
";",
"var",
"cObj",
"=",
"obj",
";",
"if",
"(",
"args",
".",
"length",
">",
"1",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"1",
",",
"len",
"=",
"args",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"cObj",
"=",
"cObj",
"[",
"args",
"[",
"i",
"]",
"]",
";",
"if",
"(",
"!",
"cObj",
")",
"{",
"return",
"obj",
";",
"}",
"}",
"return",
"cObj",
";",
"}",
"return",
"obj",
";",
"}"
] |
Traversing through the object to find the value that we want. If fail, then return the original object.
|
[
"Traversing",
"through",
"the",
"object",
"to",
"find",
"the",
"value",
"that",
"we",
"want",
".",
"If",
"fail",
"then",
"return",
"the",
"original",
"object",
"."
] |
c282f8f47736c195a4079024f62f3c9e16420619
|
https://github.com/ocombe/ocLazyLoad/blob/c282f8f47736c195a4079024f62f3c9e16420619/examples/requireJSExample/js/ng-grid-2.0.11.debug.js#L2686-L2702
|
|
13,440
|
ocombe/ocLazyLoad
|
dist/ocLazyLoad.require.js
|
stringify
|
function stringify(obj) {
try {
return JSON.stringify(obj);
} catch (e) {
var cache = [];
return JSON.stringify(obj, function (key, value) {
if (angular.isObject(value) && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
}
}
|
javascript
|
function stringify(obj) {
try {
return JSON.stringify(obj);
} catch (e) {
var cache = [];
return JSON.stringify(obj, function (key, value) {
if (angular.isObject(value) && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
}
}
|
[
"function",
"stringify",
"(",
"obj",
")",
"{",
"try",
"{",
"return",
"JSON",
".",
"stringify",
"(",
"obj",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"var",
"cache",
"=",
"[",
"]",
";",
"return",
"JSON",
".",
"stringify",
"(",
"obj",
",",
"function",
"(",
"key",
",",
"value",
")",
"{",
"if",
"(",
"angular",
".",
"isObject",
"(",
"value",
")",
"&&",
"value",
"!==",
"null",
")",
"{",
"if",
"(",
"cache",
".",
"indexOf",
"(",
"value",
")",
"!==",
"-",
"1",
")",
"{",
"// Circular reference found, discard key",
"return",
";",
"}",
"// Store value in our collection",
"cache",
".",
"push",
"(",
"value",
")",
";",
"}",
"return",
"value",
";",
"}",
")",
";",
"}",
"}"
] |
Like JSON.stringify but that doesn't throw on circular references
@param obj
|
[
"Like",
"JSON",
".",
"stringify",
"but",
"that",
"doesn",
"t",
"throw",
"on",
"circular",
"references"
] |
c282f8f47736c195a4079024f62f3c9e16420619
|
https://github.com/ocombe/ocLazyLoad/blob/c282f8f47736c195a4079024f62f3c9e16420619/dist/ocLazyLoad.require.js#L139-L156
|
13,441
|
ocombe/ocLazyLoad
|
dist/ocLazyLoad.require.js
|
getModuleConfig
|
function getModuleConfig(moduleName) {
if (!angular.isString(moduleName)) {
throw new Error('You need to give the name of the module to get');
}
if (!modules[moduleName]) {
return null;
}
return angular.copy(modules[moduleName]);
}
|
javascript
|
function getModuleConfig(moduleName) {
if (!angular.isString(moduleName)) {
throw new Error('You need to give the name of the module to get');
}
if (!modules[moduleName]) {
return null;
}
return angular.copy(modules[moduleName]);
}
|
[
"function",
"getModuleConfig",
"(",
"moduleName",
")",
"{",
"if",
"(",
"!",
"angular",
".",
"isString",
"(",
"moduleName",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'You need to give the name of the module to get'",
")",
";",
"}",
"if",
"(",
"!",
"modules",
"[",
"moduleName",
"]",
")",
"{",
"return",
"null",
";",
"}",
"return",
"angular",
".",
"copy",
"(",
"modules",
"[",
"moduleName",
"]",
")",
";",
"}"
] |
Let you get a module config object
@param moduleName String the name of the module
@returns {*}
|
[
"Let",
"you",
"get",
"a",
"module",
"config",
"object"
] |
c282f8f47736c195a4079024f62f3c9e16420619
|
https://github.com/ocombe/ocLazyLoad/blob/c282f8f47736c195a4079024f62f3c9e16420619/dist/ocLazyLoad.require.js#L420-L428
|
13,442
|
ocombe/ocLazyLoad
|
dist/ocLazyLoad.require.js
|
setModuleConfig
|
function setModuleConfig(moduleConfig) {
if (!angular.isObject(moduleConfig)) {
throw new Error('You need to give the module config object to set');
}
modules[moduleConfig.name] = moduleConfig;
return moduleConfig;
}
|
javascript
|
function setModuleConfig(moduleConfig) {
if (!angular.isObject(moduleConfig)) {
throw new Error('You need to give the module config object to set');
}
modules[moduleConfig.name] = moduleConfig;
return moduleConfig;
}
|
[
"function",
"setModuleConfig",
"(",
"moduleConfig",
")",
"{",
"if",
"(",
"!",
"angular",
".",
"isObject",
"(",
"moduleConfig",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'You need to give the module config object to set'",
")",
";",
"}",
"modules",
"[",
"moduleConfig",
".",
"name",
"]",
"=",
"moduleConfig",
";",
"return",
"moduleConfig",
";",
"}"
] |
Let you define a module config object
@param moduleConfig Object the module config object
@returns {*}
|
[
"Let",
"you",
"define",
"a",
"module",
"config",
"object"
] |
c282f8f47736c195a4079024f62f3c9e16420619
|
https://github.com/ocombe/ocLazyLoad/blob/c282f8f47736c195a4079024f62f3c9e16420619/dist/ocLazyLoad.require.js#L435-L441
|
13,443
|
ocombe/ocLazyLoad
|
dist/ocLazyLoad.require.js
|
isLoaded
|
function isLoaded(modulesNames) {
var moduleLoaded = function moduleLoaded(module) {
var isLoaded = regModules.indexOf(module) > -1;
if (!isLoaded) {
isLoaded = !!moduleExists(module);
}
return isLoaded;
};
if (angular.isString(modulesNames)) {
modulesNames = [modulesNames];
}
if (angular.isArray(modulesNames)) {
var i, len;
for (i = 0, len = modulesNames.length; i < len; i++) {
if (!moduleLoaded(modulesNames[i])) {
return false;
}
}
return true;
} else {
throw new Error('You need to define the module(s) name(s)');
}
}
|
javascript
|
function isLoaded(modulesNames) {
var moduleLoaded = function moduleLoaded(module) {
var isLoaded = regModules.indexOf(module) > -1;
if (!isLoaded) {
isLoaded = !!moduleExists(module);
}
return isLoaded;
};
if (angular.isString(modulesNames)) {
modulesNames = [modulesNames];
}
if (angular.isArray(modulesNames)) {
var i, len;
for (i = 0, len = modulesNames.length; i < len; i++) {
if (!moduleLoaded(modulesNames[i])) {
return false;
}
}
return true;
} else {
throw new Error('You need to define the module(s) name(s)');
}
}
|
[
"function",
"isLoaded",
"(",
"modulesNames",
")",
"{",
"var",
"moduleLoaded",
"=",
"function",
"moduleLoaded",
"(",
"module",
")",
"{",
"var",
"isLoaded",
"=",
"regModules",
".",
"indexOf",
"(",
"module",
")",
">",
"-",
"1",
";",
"if",
"(",
"!",
"isLoaded",
")",
"{",
"isLoaded",
"=",
"!",
"!",
"moduleExists",
"(",
"module",
")",
";",
"}",
"return",
"isLoaded",
";",
"}",
";",
"if",
"(",
"angular",
".",
"isString",
"(",
"modulesNames",
")",
")",
"{",
"modulesNames",
"=",
"[",
"modulesNames",
"]",
";",
"}",
"if",
"(",
"angular",
".",
"isArray",
"(",
"modulesNames",
")",
")",
"{",
"var",
"i",
",",
"len",
";",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"modulesNames",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"moduleLoaded",
"(",
"modulesNames",
"[",
"i",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'You need to define the module(s) name(s)'",
")",
";",
"}",
"}"
] |
Let you check if a module has been loaded into Angular or not
@param modulesNames String/Object a module name, or a list of module names
@returns {boolean}
|
[
"Let",
"you",
"check",
"if",
"a",
"module",
"has",
"been",
"loaded",
"into",
"Angular",
"or",
"not"
] |
c282f8f47736c195a4079024f62f3c9e16420619
|
https://github.com/ocombe/ocLazyLoad/blob/c282f8f47736c195a4079024f62f3c9e16420619/dist/ocLazyLoad.require.js#L456-L478
|
13,444
|
ocombe/ocLazyLoad
|
dist/ocLazyLoad.require.js
|
getModule
|
function getModule(moduleName) {
try {
return ngModuleFct(moduleName);
} catch (e) {
// this error message really suxx
if (/No module/.test(e) || e.message.indexOf('$injector:nomod') > -1) {
e.message = 'The module "' + stringify(moduleName) + '" that you are trying to load does not exist. ' + e.message;
}
throw e;
}
}
|
javascript
|
function getModule(moduleName) {
try {
return ngModuleFct(moduleName);
} catch (e) {
// this error message really suxx
if (/No module/.test(e) || e.message.indexOf('$injector:nomod') > -1) {
e.message = 'The module "' + stringify(moduleName) + '" that you are trying to load does not exist. ' + e.message;
}
throw e;
}
}
|
[
"function",
"getModule",
"(",
"moduleName",
")",
"{",
"try",
"{",
"return",
"ngModuleFct",
"(",
"moduleName",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// this error message really suxx",
"if",
"(",
"/",
"No module",
"/",
".",
"test",
"(",
"e",
")",
"||",
"e",
".",
"message",
".",
"indexOf",
"(",
"'$injector:nomod'",
")",
">",
"-",
"1",
")",
"{",
"e",
".",
"message",
"=",
"'The module \"'",
"+",
"stringify",
"(",
"moduleName",
")",
"+",
"'\" that you are trying to load does not exist. '",
"+",
"e",
".",
"message",
";",
"}",
"throw",
"e",
";",
"}",
"}"
] |
Returns a module if it exists
@param moduleName
@returns {module}
|
[
"Returns",
"a",
"module",
"if",
"it",
"exists"
] |
c282f8f47736c195a4079024f62f3c9e16420619
|
https://github.com/ocombe/ocLazyLoad/blob/c282f8f47736c195a4079024f62f3c9e16420619/dist/ocLazyLoad.require.js#L492-L502
|
13,445
|
ocombe/ocLazyLoad
|
dist/ocLazyLoad.require.js
|
inject
|
function inject(moduleName) {
var localParams = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var real = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
var self = this,
deferred = $q.defer();
if (angular.isDefined(moduleName) && moduleName !== null) {
if (angular.isArray(moduleName)) {
var promisesList = [];
angular.forEach(moduleName, function (module) {
promisesList.push(self.inject(module, localParams, real));
});
return $q.all(promisesList);
} else {
self._addToLoadList(self._getModuleName(moduleName), true, real);
}
}
if (modulesToLoad.length > 0) {
var res = modulesToLoad.slice(); // clean copy
var loadNext = function loadNext(moduleName) {
moduleCache.push(moduleName);
modulePromises[moduleName] = deferred.promise;
self._loadDependencies(moduleName, localParams).then(function success() {
try {
justLoaded = [];
_register(providers, moduleCache, localParams);
} catch (e) {
self._$log.error(e.message);
deferred.reject(e);
return;
}
if (modulesToLoad.length > 0) {
loadNext(modulesToLoad.shift()); // load the next in list
} else {
deferred.resolve(res); // everything has been loaded, resolve
}
}, function error(err) {
deferred.reject(err);
});
};
// load the first in list
loadNext(modulesToLoad.shift());
} else if (localParams && localParams.name && modulePromises[localParams.name]) {
return modulePromises[localParams.name];
} else {
deferred.resolve();
}
return deferred.promise;
}
|
javascript
|
function inject(moduleName) {
var localParams = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var real = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
var self = this,
deferred = $q.defer();
if (angular.isDefined(moduleName) && moduleName !== null) {
if (angular.isArray(moduleName)) {
var promisesList = [];
angular.forEach(moduleName, function (module) {
promisesList.push(self.inject(module, localParams, real));
});
return $q.all(promisesList);
} else {
self._addToLoadList(self._getModuleName(moduleName), true, real);
}
}
if (modulesToLoad.length > 0) {
var res = modulesToLoad.slice(); // clean copy
var loadNext = function loadNext(moduleName) {
moduleCache.push(moduleName);
modulePromises[moduleName] = deferred.promise;
self._loadDependencies(moduleName, localParams).then(function success() {
try {
justLoaded = [];
_register(providers, moduleCache, localParams);
} catch (e) {
self._$log.error(e.message);
deferred.reject(e);
return;
}
if (modulesToLoad.length > 0) {
loadNext(modulesToLoad.shift()); // load the next in list
} else {
deferred.resolve(res); // everything has been loaded, resolve
}
}, function error(err) {
deferred.reject(err);
});
};
// load the first in list
loadNext(modulesToLoad.shift());
} else if (localParams && localParams.name && modulePromises[localParams.name]) {
return modulePromises[localParams.name];
} else {
deferred.resolve();
}
return deferred.promise;
}
|
[
"function",
"inject",
"(",
"moduleName",
")",
"{",
"var",
"localParams",
"=",
"arguments",
".",
"length",
"<=",
"1",
"||",
"arguments",
"[",
"1",
"]",
"===",
"undefined",
"?",
"{",
"}",
":",
"arguments",
"[",
"1",
"]",
";",
"var",
"real",
"=",
"arguments",
".",
"length",
"<=",
"2",
"||",
"arguments",
"[",
"2",
"]",
"===",
"undefined",
"?",
"false",
":",
"arguments",
"[",
"2",
"]",
";",
"var",
"self",
"=",
"this",
",",
"deferred",
"=",
"$q",
".",
"defer",
"(",
")",
";",
"if",
"(",
"angular",
".",
"isDefined",
"(",
"moduleName",
")",
"&&",
"moduleName",
"!==",
"null",
")",
"{",
"if",
"(",
"angular",
".",
"isArray",
"(",
"moduleName",
")",
")",
"{",
"var",
"promisesList",
"=",
"[",
"]",
";",
"angular",
".",
"forEach",
"(",
"moduleName",
",",
"function",
"(",
"module",
")",
"{",
"promisesList",
".",
"push",
"(",
"self",
".",
"inject",
"(",
"module",
",",
"localParams",
",",
"real",
")",
")",
";",
"}",
")",
";",
"return",
"$q",
".",
"all",
"(",
"promisesList",
")",
";",
"}",
"else",
"{",
"self",
".",
"_addToLoadList",
"(",
"self",
".",
"_getModuleName",
"(",
"moduleName",
")",
",",
"true",
",",
"real",
")",
";",
"}",
"}",
"if",
"(",
"modulesToLoad",
".",
"length",
">",
"0",
")",
"{",
"var",
"res",
"=",
"modulesToLoad",
".",
"slice",
"(",
")",
";",
"// clean copy",
"var",
"loadNext",
"=",
"function",
"loadNext",
"(",
"moduleName",
")",
"{",
"moduleCache",
".",
"push",
"(",
"moduleName",
")",
";",
"modulePromises",
"[",
"moduleName",
"]",
"=",
"deferred",
".",
"promise",
";",
"self",
".",
"_loadDependencies",
"(",
"moduleName",
",",
"localParams",
")",
".",
"then",
"(",
"function",
"success",
"(",
")",
"{",
"try",
"{",
"justLoaded",
"=",
"[",
"]",
";",
"_register",
"(",
"providers",
",",
"moduleCache",
",",
"localParams",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"self",
".",
"_$log",
".",
"error",
"(",
"e",
".",
"message",
")",
";",
"deferred",
".",
"reject",
"(",
"e",
")",
";",
"return",
";",
"}",
"if",
"(",
"modulesToLoad",
".",
"length",
">",
"0",
")",
"{",
"loadNext",
"(",
"modulesToLoad",
".",
"shift",
"(",
")",
")",
";",
"// load the next in list",
"}",
"else",
"{",
"deferred",
".",
"resolve",
"(",
"res",
")",
";",
"// everything has been loaded, resolve",
"}",
"}",
",",
"function",
"error",
"(",
"err",
")",
"{",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
";",
"// load the first in list",
"loadNext",
"(",
"modulesToLoad",
".",
"shift",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"localParams",
"&&",
"localParams",
".",
"name",
"&&",
"modulePromises",
"[",
"localParams",
".",
"name",
"]",
")",
"{",
"return",
"modulePromises",
"[",
"localParams",
".",
"name",
"]",
";",
"}",
"else",
"{",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
"return",
"deferred",
".",
"promise",
";",
"}"
] |
Inject new modules into Angular
@param moduleName
@param localParams
@param real
|
[
"Inject",
"new",
"modules",
"into",
"Angular"
] |
c282f8f47736c195a4079024f62f3c9e16420619
|
https://github.com/ocombe/ocLazyLoad/blob/c282f8f47736c195a4079024f62f3c9e16420619/dist/ocLazyLoad.require.js#L622-L672
|
13,446
|
webpack-contrib/less-loader
|
src/getOptions.js
|
getOptions
|
function getOptions(loaderContext) {
const options = {
plugins: [],
relativeUrls: true,
...clone(loaderUtils.getOptions(loaderContext)),
};
// We need to set the filename because otherwise our WebpackFileManager will receive an undefined path for the entry
options.filename = loaderContext.resource;
// When no paths are given, we use the webpack resolver
if ('paths' in options === false) {
// It's safe to mutate the array now because it has already been cloned
options.plugins.push(createWebpackLessPlugin(loaderContext));
}
if (options.sourceMap) {
if (typeof options.sourceMap === 'boolean') {
options.sourceMap = {};
}
if ('outputSourceFiles' in options.sourceMap === false) {
// Include source files as `sourceContents` as sane default since this makes source maps "just work" in most cases
options.sourceMap.outputSourceFiles = true;
}
}
return options;
}
|
javascript
|
function getOptions(loaderContext) {
const options = {
plugins: [],
relativeUrls: true,
...clone(loaderUtils.getOptions(loaderContext)),
};
// We need to set the filename because otherwise our WebpackFileManager will receive an undefined path for the entry
options.filename = loaderContext.resource;
// When no paths are given, we use the webpack resolver
if ('paths' in options === false) {
// It's safe to mutate the array now because it has already been cloned
options.plugins.push(createWebpackLessPlugin(loaderContext));
}
if (options.sourceMap) {
if (typeof options.sourceMap === 'boolean') {
options.sourceMap = {};
}
if ('outputSourceFiles' in options.sourceMap === false) {
// Include source files as `sourceContents` as sane default since this makes source maps "just work" in most cases
options.sourceMap.outputSourceFiles = true;
}
}
return options;
}
|
[
"function",
"getOptions",
"(",
"loaderContext",
")",
"{",
"const",
"options",
"=",
"{",
"plugins",
":",
"[",
"]",
",",
"relativeUrls",
":",
"true",
",",
"...",
"clone",
"(",
"loaderUtils",
".",
"getOptions",
"(",
"loaderContext",
")",
")",
",",
"}",
";",
"// We need to set the filename because otherwise our WebpackFileManager will receive an undefined path for the entry",
"options",
".",
"filename",
"=",
"loaderContext",
".",
"resource",
";",
"// When no paths are given, we use the webpack resolver",
"if",
"(",
"'paths'",
"in",
"options",
"===",
"false",
")",
"{",
"// It's safe to mutate the array now because it has already been cloned",
"options",
".",
"plugins",
".",
"push",
"(",
"createWebpackLessPlugin",
"(",
"loaderContext",
")",
")",
";",
"}",
"if",
"(",
"options",
".",
"sourceMap",
")",
"{",
"if",
"(",
"typeof",
"options",
".",
"sourceMap",
"===",
"'boolean'",
")",
"{",
"options",
".",
"sourceMap",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"'outputSourceFiles'",
"in",
"options",
".",
"sourceMap",
"===",
"false",
")",
"{",
"// Include source files as `sourceContents` as sane default since this makes source maps \"just work\" in most cases",
"options",
".",
"sourceMap",
".",
"outputSourceFiles",
"=",
"true",
";",
"}",
"}",
"return",
"options",
";",
"}"
] |
Retrieves the options from the loaderContext, makes a deep copy of it and normalizes it for further consumption.
@param {LoaderContext} loaderContext
|
[
"Retrieves",
"the",
"options",
"from",
"the",
"loaderContext",
"makes",
"a",
"deep",
"copy",
"of",
"it",
"and",
"normalizes",
"it",
"for",
"further",
"consumption",
"."
] |
821c12d407b36f49aacc506737a02d1dc46aee56
|
https://github.com/webpack-contrib/less-loader/blob/821c12d407b36f49aacc506737a02d1dc46aee56/src/getOptions.js#L11-L38
|
13,447
|
webpack-contrib/less-loader
|
src/createWebpackLessPlugin.js
|
createWebpackLessPlugin
|
function createWebpackLessPlugin(loaderContext) {
const { fs } = loaderContext;
const resolve = pify(loaderContext.resolve.bind(loaderContext));
const loadModule = pify(loaderContext.loadModule.bind(loaderContext));
const readFile = pify(fs.readFile.bind(fs));
class WebpackFileManager extends less.FileManager {
supports() {
// Our WebpackFileManager handles all the files
return true;
}
// Sync resolving is used at least by the `data-uri` function.
// This file manager doesn't know how to do it, so let's delegate it
// to the default file manager of Less.
// We could probably use loaderContext.resolveSync, but it's deprecated,
// see https://webpack.js.org/api/loaders/#this-resolvesync
supportsSync() {
return false;
}
loadFile(filename, currentDirectory, options) {
let url;
if (less.version[0] >= 3) {
if (options.ext && !isModuleName.test(filename)) {
url = this.tryAppendExtension(filename, options.ext);
} else {
url = filename;
}
} else {
url = filename.replace(matchMalformedModuleFilename, '$1');
}
const moduleRequest = loaderUtils.urlToRequest(
url,
url.charAt(0) === '/' ? '' : null
);
// Less is giving us trailing slashes, but the context should have no trailing slash
const context = currentDirectory.replace(trailingSlash, '');
let resolvedFilename;
return resolve(context, moduleRequest)
.then((f) => {
resolvedFilename = f;
loaderContext.addDependency(resolvedFilename);
if (isLessCompatible.test(resolvedFilename)) {
return readFile(resolvedFilename).then((contents) =>
contents.toString('utf8')
);
}
return loadModule([stringifyLoader, resolvedFilename].join('!')).then(
JSON.parse
);
})
.then((contents) => {
return {
contents,
filename: resolvedFilename,
};
});
}
}
return {
install(lessInstance, pluginManager) {
pluginManager.addFileManager(new WebpackFileManager());
},
minVersion: [2, 1, 1],
};
}
|
javascript
|
function createWebpackLessPlugin(loaderContext) {
const { fs } = loaderContext;
const resolve = pify(loaderContext.resolve.bind(loaderContext));
const loadModule = pify(loaderContext.loadModule.bind(loaderContext));
const readFile = pify(fs.readFile.bind(fs));
class WebpackFileManager extends less.FileManager {
supports() {
// Our WebpackFileManager handles all the files
return true;
}
// Sync resolving is used at least by the `data-uri` function.
// This file manager doesn't know how to do it, so let's delegate it
// to the default file manager of Less.
// We could probably use loaderContext.resolveSync, but it's deprecated,
// see https://webpack.js.org/api/loaders/#this-resolvesync
supportsSync() {
return false;
}
loadFile(filename, currentDirectory, options) {
let url;
if (less.version[0] >= 3) {
if (options.ext && !isModuleName.test(filename)) {
url = this.tryAppendExtension(filename, options.ext);
} else {
url = filename;
}
} else {
url = filename.replace(matchMalformedModuleFilename, '$1');
}
const moduleRequest = loaderUtils.urlToRequest(
url,
url.charAt(0) === '/' ? '' : null
);
// Less is giving us trailing slashes, but the context should have no trailing slash
const context = currentDirectory.replace(trailingSlash, '');
let resolvedFilename;
return resolve(context, moduleRequest)
.then((f) => {
resolvedFilename = f;
loaderContext.addDependency(resolvedFilename);
if (isLessCompatible.test(resolvedFilename)) {
return readFile(resolvedFilename).then((contents) =>
contents.toString('utf8')
);
}
return loadModule([stringifyLoader, resolvedFilename].join('!')).then(
JSON.parse
);
})
.then((contents) => {
return {
contents,
filename: resolvedFilename,
};
});
}
}
return {
install(lessInstance, pluginManager) {
pluginManager.addFileManager(new WebpackFileManager());
},
minVersion: [2, 1, 1],
};
}
|
[
"function",
"createWebpackLessPlugin",
"(",
"loaderContext",
")",
"{",
"const",
"{",
"fs",
"}",
"=",
"loaderContext",
";",
"const",
"resolve",
"=",
"pify",
"(",
"loaderContext",
".",
"resolve",
".",
"bind",
"(",
"loaderContext",
")",
")",
";",
"const",
"loadModule",
"=",
"pify",
"(",
"loaderContext",
".",
"loadModule",
".",
"bind",
"(",
"loaderContext",
")",
")",
";",
"const",
"readFile",
"=",
"pify",
"(",
"fs",
".",
"readFile",
".",
"bind",
"(",
"fs",
")",
")",
";",
"class",
"WebpackFileManager",
"extends",
"less",
".",
"FileManager",
"{",
"supports",
"(",
")",
"{",
"// Our WebpackFileManager handles all the files",
"return",
"true",
";",
"}",
"// Sync resolving is used at least by the `data-uri` function.",
"// This file manager doesn't know how to do it, so let's delegate it",
"// to the default file manager of Less.",
"// We could probably use loaderContext.resolveSync, but it's deprecated,",
"// see https://webpack.js.org/api/loaders/#this-resolvesync",
"supportsSync",
"(",
")",
"{",
"return",
"false",
";",
"}",
"loadFile",
"(",
"filename",
",",
"currentDirectory",
",",
"options",
")",
"{",
"let",
"url",
";",
"if",
"(",
"less",
".",
"version",
"[",
"0",
"]",
">=",
"3",
")",
"{",
"if",
"(",
"options",
".",
"ext",
"&&",
"!",
"isModuleName",
".",
"test",
"(",
"filename",
")",
")",
"{",
"url",
"=",
"this",
".",
"tryAppendExtension",
"(",
"filename",
",",
"options",
".",
"ext",
")",
";",
"}",
"else",
"{",
"url",
"=",
"filename",
";",
"}",
"}",
"else",
"{",
"url",
"=",
"filename",
".",
"replace",
"(",
"matchMalformedModuleFilename",
",",
"'$1'",
")",
";",
"}",
"const",
"moduleRequest",
"=",
"loaderUtils",
".",
"urlToRequest",
"(",
"url",
",",
"url",
".",
"charAt",
"(",
"0",
")",
"===",
"'/'",
"?",
"''",
":",
"null",
")",
";",
"// Less is giving us trailing slashes, but the context should have no trailing slash",
"const",
"context",
"=",
"currentDirectory",
".",
"replace",
"(",
"trailingSlash",
",",
"''",
")",
";",
"let",
"resolvedFilename",
";",
"return",
"resolve",
"(",
"context",
",",
"moduleRequest",
")",
".",
"then",
"(",
"(",
"f",
")",
"=>",
"{",
"resolvedFilename",
"=",
"f",
";",
"loaderContext",
".",
"addDependency",
"(",
"resolvedFilename",
")",
";",
"if",
"(",
"isLessCompatible",
".",
"test",
"(",
"resolvedFilename",
")",
")",
"{",
"return",
"readFile",
"(",
"resolvedFilename",
")",
".",
"then",
"(",
"(",
"contents",
")",
"=>",
"contents",
".",
"toString",
"(",
"'utf8'",
")",
")",
";",
"}",
"return",
"loadModule",
"(",
"[",
"stringifyLoader",
",",
"resolvedFilename",
"]",
".",
"join",
"(",
"'!'",
")",
")",
".",
"then",
"(",
"JSON",
".",
"parse",
")",
";",
"}",
")",
".",
"then",
"(",
"(",
"contents",
")",
"=>",
"{",
"return",
"{",
"contents",
",",
"filename",
":",
"resolvedFilename",
",",
"}",
";",
"}",
")",
";",
"}",
"}",
"return",
"{",
"install",
"(",
"lessInstance",
",",
"pluginManager",
")",
"{",
"pluginManager",
".",
"addFileManager",
"(",
"new",
"WebpackFileManager",
"(",
")",
")",
";",
"}",
",",
"minVersion",
":",
"[",
"2",
",",
"1",
",",
"1",
"]",
",",
"}",
";",
"}"
] |
Creates a Less plugin that uses webpack's resolving engine that is provided by the loaderContext.
@param {LoaderContext} loaderContext
@param {string=} root
@returns {LessPlugin}
|
[
"Creates",
"a",
"Less",
"plugin",
"that",
"uses",
"webpack",
"s",
"resolving",
"engine",
"that",
"is",
"provided",
"by",
"the",
"loaderContext",
"."
] |
821c12d407b36f49aacc506737a02d1dc46aee56
|
https://github.com/webpack-contrib/less-loader/blob/821c12d407b36f49aacc506737a02d1dc46aee56/src/createWebpackLessPlugin.js#L30-L100
|
13,448
|
webpack-contrib/less-loader
|
src/processResult.js
|
processResult
|
function processResult(loaderContext, resultPromise) {
const { callback } = loaderContext;
resultPromise
.then(
({ css, map, imports }) => {
imports.forEach(loaderContext.addDependency, loaderContext);
return {
// Removing the sourceMappingURL comment.
// See removeSourceMappingUrl.js for the reasoning behind this.
css: removeSourceMappingUrl(css),
map: typeof map === 'string' ? JSON.parse(map) : map,
};
},
(lessError) => {
if (lessError.filename) {
loaderContext.addDependency(lessError.filename);
}
throw formatLessError(lessError);
}
)
.then(({ css, map }) => {
callback(null, css, map);
}, callback);
}
|
javascript
|
function processResult(loaderContext, resultPromise) {
const { callback } = loaderContext;
resultPromise
.then(
({ css, map, imports }) => {
imports.forEach(loaderContext.addDependency, loaderContext);
return {
// Removing the sourceMappingURL comment.
// See removeSourceMappingUrl.js for the reasoning behind this.
css: removeSourceMappingUrl(css),
map: typeof map === 'string' ? JSON.parse(map) : map,
};
},
(lessError) => {
if (lessError.filename) {
loaderContext.addDependency(lessError.filename);
}
throw formatLessError(lessError);
}
)
.then(({ css, map }) => {
callback(null, css, map);
}, callback);
}
|
[
"function",
"processResult",
"(",
"loaderContext",
",",
"resultPromise",
")",
"{",
"const",
"{",
"callback",
"}",
"=",
"loaderContext",
";",
"resultPromise",
".",
"then",
"(",
"(",
"{",
"css",
",",
"map",
",",
"imports",
"}",
")",
"=>",
"{",
"imports",
".",
"forEach",
"(",
"loaderContext",
".",
"addDependency",
",",
"loaderContext",
")",
";",
"return",
"{",
"// Removing the sourceMappingURL comment.",
"// See removeSourceMappingUrl.js for the reasoning behind this.",
"css",
":",
"removeSourceMappingUrl",
"(",
"css",
")",
",",
"map",
":",
"typeof",
"map",
"===",
"'string'",
"?",
"JSON",
".",
"parse",
"(",
"map",
")",
":",
"map",
",",
"}",
";",
"}",
",",
"(",
"lessError",
")",
"=>",
"{",
"if",
"(",
"lessError",
".",
"filename",
")",
"{",
"loaderContext",
".",
"addDependency",
"(",
"lessError",
".",
"filename",
")",
";",
"}",
"throw",
"formatLessError",
"(",
"lessError",
")",
";",
"}",
")",
".",
"then",
"(",
"(",
"{",
"css",
",",
"map",
"}",
")",
"=>",
"{",
"callback",
"(",
"null",
",",
"css",
",",
"map",
")",
";",
"}",
",",
"callback",
")",
";",
"}"
] |
Removes the sourceMappingURL from the generated CSS, parses the source map and calls the next loader.
@param {loaderContext} loaderContext
@param {Promise<LessResult>} resultPromise
|
[
"Removes",
"the",
"sourceMappingURL",
"from",
"the",
"generated",
"CSS",
"parses",
"the",
"source",
"map",
"and",
"calls",
"the",
"next",
"loader",
"."
] |
821c12d407b36f49aacc506737a02d1dc46aee56
|
https://github.com/webpack-contrib/less-loader/blob/821c12d407b36f49aacc506737a02d1dc46aee56/src/processResult.js#L10-L34
|
13,449
|
webpack-contrib/less-loader
|
src/formatLessError.js
|
formatLessError
|
function formatLessError(err) {
/* eslint-disable no-param-reassign */
const msg = err.message;
// Instruct webpack to hide the JS stack from the console
// Usually you're only interested in the SASS stack in this case.
err.hideStack = true;
err.message = [
os.EOL,
...getFileExcerptIfPossible(err),
msg.charAt(0).toUpperCase() + msg.slice(1),
` in ${err.filename} (line ${err.line}, column ${err.column})`,
].join(os.EOL);
return err;
}
|
javascript
|
function formatLessError(err) {
/* eslint-disable no-param-reassign */
const msg = err.message;
// Instruct webpack to hide the JS stack from the console
// Usually you're only interested in the SASS stack in this case.
err.hideStack = true;
err.message = [
os.EOL,
...getFileExcerptIfPossible(err),
msg.charAt(0).toUpperCase() + msg.slice(1),
` in ${err.filename} (line ${err.line}, column ${err.column})`,
].join(os.EOL);
return err;
}
|
[
"function",
"formatLessError",
"(",
"err",
")",
"{",
"/* eslint-disable no-param-reassign */",
"const",
"msg",
"=",
"err",
".",
"message",
";",
"// Instruct webpack to hide the JS stack from the console",
"// Usually you're only interested in the SASS stack in this case.",
"err",
".",
"hideStack",
"=",
"true",
";",
"err",
".",
"message",
"=",
"[",
"os",
".",
"EOL",
",",
"...",
"getFileExcerptIfPossible",
"(",
"err",
")",
",",
"msg",
".",
"charAt",
"(",
"0",
")",
".",
"toUpperCase",
"(",
")",
"+",
"msg",
".",
"slice",
"(",
"1",
")",
",",
"`",
"${",
"err",
".",
"filename",
"}",
"${",
"err",
".",
"line",
"}",
"${",
"err",
".",
"column",
"}",
"`",
",",
"]",
".",
"join",
"(",
"os",
".",
"EOL",
")",
";",
"return",
"err",
";",
"}"
] |
Beautifies the error message from Less.
@param {LessError} lessErr
@param {string} lessErr.type - e.g. 'Name'
@param {string} lessErr.message - e.g. '.undefined-mixin is undefined'
@param {string} lessErr.filename - e.g. '/path/to/style.less'
@param {number} lessErr.index - e.g. 352
@param {number} lessErr.line - e.g. 31
@param {number} lessErr.callLine - e.g. NaN
@param {string} lessErr.callExtract - e.g. undefined
@param {number} lessErr.column - e.g. 6
@param {Array<string>} lessErr.extract - e.g. [' .my-style {', ' .undefined-mixin;', ' display: block;']
@returns {LessError}
|
[
"Beautifies",
"the",
"error",
"message",
"from",
"Less",
"."
] |
821c12d407b36f49aacc506737a02d1dc46aee56
|
https://github.com/webpack-contrib/less-loader/blob/821c12d407b36f49aacc506737a02d1dc46aee56/src/formatLessError.js#L45-L61
|
13,450
|
GriddleGriddle/Griddle
|
src/utils/columnUtils.js
|
getColumnPropertiesFromColumnArray
|
function getColumnPropertiesFromColumnArray(columnProperties, columns) {
return columns.reduce((previous, current, i) => {
previous[current] = { id: current, order: offset + i };
return previous;
},
columnProperties);
}
|
javascript
|
function getColumnPropertiesFromColumnArray(columnProperties, columns) {
return columns.reduce((previous, current, i) => {
previous[current] = { id: current, order: offset + i };
return previous;
},
columnProperties);
}
|
[
"function",
"getColumnPropertiesFromColumnArray",
"(",
"columnProperties",
",",
"columns",
")",
"{",
"return",
"columns",
".",
"reduce",
"(",
"(",
"previous",
",",
"current",
",",
"i",
")",
"=>",
"{",
"previous",
"[",
"current",
"]",
"=",
"{",
"id",
":",
"current",
",",
"order",
":",
"offset",
"+",
"i",
"}",
";",
"return",
"previous",
";",
"}",
",",
"columnProperties",
")",
";",
"}"
] |
Gets a column properties object from an array of columnNames
@param {Array<string>} columns - array of column names
|
[
"Gets",
"a",
"column",
"properties",
"object",
"from",
"an",
"array",
"of",
"columnNames"
] |
f836fc3d3e1e05357ae60c9a7b3c106e5c5c8891
|
https://github.com/GriddleGriddle/Griddle/blob/f836fc3d3e1e05357ae60c9a7b3c106e5c5c8891/src/utils/columnUtils.js#L6-L12
|
13,451
|
GriddleGriddle/Griddle
|
src/utils/compositionUtils.js
|
buildGriddleReducerObject
|
function buildGriddleReducerObject(reducerObjects) {
let reducerMethodsWithoutHooks = [];
let beforeHooks = [];
let afterHooks = [];
let beforeReduceAll = [];
let afterReduceAll = [];
if (reducerObjects.length > 0) {
// remove the hooks and extend the object
for(const key in reducerObjects) {
const reducer = reducerObjects[key];
reducerMethodsWithoutHooks.push(removeHooksFromObject(reducer));
beforeHooks.push(getBeforeHooksFromObject(reducer));
afterHooks.push(getAfterHooksFromObject(reducer));
beforeReduceAll.push(getBeforeReduceHooksFromObject(reducer));
afterReduceAll.push(getAfterReduceHooksFromObject(reducer));
}
}
const composedBeforeHooks = composeReducerObjects(beforeHooks);
const composedAfterHooks = composeReducerObjects(afterHooks);
const composedBeforeReduceAll = composeReducerObjects(beforeReduceAll);
const composedAfterReduceAll = composeReducerObjects(afterReduceAll);
// combine the reducers without hooks
const combinedReducer = extendArray(reducerMethodsWithoutHooks);
const composed = composeReducerObjects([
composedBeforeReduceAll,
composedBeforeHooks,
combinedReducer,
composedAfterHooks,
composedAfterReduceAll
]);
return composed;
}
|
javascript
|
function buildGriddleReducerObject(reducerObjects) {
let reducerMethodsWithoutHooks = [];
let beforeHooks = [];
let afterHooks = [];
let beforeReduceAll = [];
let afterReduceAll = [];
if (reducerObjects.length > 0) {
// remove the hooks and extend the object
for(const key in reducerObjects) {
const reducer = reducerObjects[key];
reducerMethodsWithoutHooks.push(removeHooksFromObject(reducer));
beforeHooks.push(getBeforeHooksFromObject(reducer));
afterHooks.push(getAfterHooksFromObject(reducer));
beforeReduceAll.push(getBeforeReduceHooksFromObject(reducer));
afterReduceAll.push(getAfterReduceHooksFromObject(reducer));
}
}
const composedBeforeHooks = composeReducerObjects(beforeHooks);
const composedAfterHooks = composeReducerObjects(afterHooks);
const composedBeforeReduceAll = composeReducerObjects(beforeReduceAll);
const composedAfterReduceAll = composeReducerObjects(afterReduceAll);
// combine the reducers without hooks
const combinedReducer = extendArray(reducerMethodsWithoutHooks);
const composed = composeReducerObjects([
composedBeforeReduceAll,
composedBeforeHooks,
combinedReducer,
composedAfterHooks,
composedAfterReduceAll
]);
return composed;
}
|
[
"function",
"buildGriddleReducerObject",
"(",
"reducerObjects",
")",
"{",
"let",
"reducerMethodsWithoutHooks",
"=",
"[",
"]",
";",
"let",
"beforeHooks",
"=",
"[",
"]",
";",
"let",
"afterHooks",
"=",
"[",
"]",
";",
"let",
"beforeReduceAll",
"=",
"[",
"]",
";",
"let",
"afterReduceAll",
"=",
"[",
"]",
";",
"if",
"(",
"reducerObjects",
".",
"length",
">",
"0",
")",
"{",
"// remove the hooks and extend the object",
"for",
"(",
"const",
"key",
"in",
"reducerObjects",
")",
"{",
"const",
"reducer",
"=",
"reducerObjects",
"[",
"key",
"]",
";",
"reducerMethodsWithoutHooks",
".",
"push",
"(",
"removeHooksFromObject",
"(",
"reducer",
")",
")",
";",
"beforeHooks",
".",
"push",
"(",
"getBeforeHooksFromObject",
"(",
"reducer",
")",
")",
";",
"afterHooks",
".",
"push",
"(",
"getAfterHooksFromObject",
"(",
"reducer",
")",
")",
";",
"beforeReduceAll",
".",
"push",
"(",
"getBeforeReduceHooksFromObject",
"(",
"reducer",
")",
")",
";",
"afterReduceAll",
".",
"push",
"(",
"getAfterReduceHooksFromObject",
"(",
"reducer",
")",
")",
";",
"}",
"}",
"const",
"composedBeforeHooks",
"=",
"composeReducerObjects",
"(",
"beforeHooks",
")",
";",
"const",
"composedAfterHooks",
"=",
"composeReducerObjects",
"(",
"afterHooks",
")",
";",
"const",
"composedBeforeReduceAll",
"=",
"composeReducerObjects",
"(",
"beforeReduceAll",
")",
";",
"const",
"composedAfterReduceAll",
"=",
"composeReducerObjects",
"(",
"afterReduceAll",
")",
";",
"// combine the reducers without hooks",
"const",
"combinedReducer",
"=",
"extendArray",
"(",
"reducerMethodsWithoutHooks",
")",
";",
"const",
"composed",
"=",
"composeReducerObjects",
"(",
"[",
"composedBeforeReduceAll",
",",
"composedBeforeHooks",
",",
"combinedReducer",
",",
"composedAfterHooks",
",",
"composedAfterReduceAll",
"]",
")",
";",
"return",
"composed",
";",
"}"
] |
Builds a new reducer that composes hooks and extends standard reducers between reducerObjects
@param {Object <array>} reducers - An array of reducerObjects
Note: this used to be exported, but the same properties are available from buildGriddleReducer.
TODO: This method should be broken down a bit -- it's doing too much currently
|
[
"Builds",
"a",
"new",
"reducer",
"that",
"composes",
"hooks",
"and",
"extends",
"standard",
"reducers",
"between",
"reducerObjects"
] |
f836fc3d3e1e05357ae60c9a7b3c106e5c5c8891
|
https://github.com/GriddleGriddle/Griddle/blob/f836fc3d3e1e05357ae60c9a7b3c106e5c5c8891/src/utils/compositionUtils.js#L177-L216
|
13,452
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/platforms/ios/www/plugins/cordova-plugin-file/www/FileEntry.js
|
function(name, fullPath, fileSystem, nativeURL) {
// remove trailing slash if it is present
if (fullPath && /\/$/.test(fullPath)) {
fullPath = fullPath.substring(0, fullPath.length - 1);
}
if (nativeURL && /\/$/.test(nativeURL)) {
nativeURL = nativeURL.substring(0, nativeURL.length - 1);
}
FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath, fileSystem, nativeURL]);
}
|
javascript
|
function(name, fullPath, fileSystem, nativeURL) {
// remove trailing slash if it is present
if (fullPath && /\/$/.test(fullPath)) {
fullPath = fullPath.substring(0, fullPath.length - 1);
}
if (nativeURL && /\/$/.test(nativeURL)) {
nativeURL = nativeURL.substring(0, nativeURL.length - 1);
}
FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath, fileSystem, nativeURL]);
}
|
[
"function",
"(",
"name",
",",
"fullPath",
",",
"fileSystem",
",",
"nativeURL",
")",
"{",
"// remove trailing slash if it is present",
"if",
"(",
"fullPath",
"&&",
"/",
"\\/$",
"/",
".",
"test",
"(",
"fullPath",
")",
")",
"{",
"fullPath",
"=",
"fullPath",
".",
"substring",
"(",
"0",
",",
"fullPath",
".",
"length",
"-",
"1",
")",
";",
"}",
"if",
"(",
"nativeURL",
"&&",
"/",
"\\/$",
"/",
".",
"test",
"(",
"nativeURL",
")",
")",
"{",
"nativeURL",
"=",
"nativeURL",
".",
"substring",
"(",
"0",
",",
"nativeURL",
".",
"length",
"-",
"1",
")",
";",
"}",
"FileEntry",
".",
"__super__",
".",
"constructor",
".",
"apply",
"(",
"this",
",",
"[",
"true",
",",
"false",
",",
"name",
",",
"fullPath",
",",
"fileSystem",
",",
"nativeURL",
"]",
")",
";",
"}"
] |
An interface representing a file on the file system.
{boolean} isFile always true (readonly)
{boolean} isDirectory always false (readonly)
{DOMString} name of the file, excluding the path leading to it (readonly)
{DOMString} fullPath the absolute full path to the file (readonly)
{FileSystem} filesystem on which the file resides (readonly)
|
[
"An",
"interface",
"representing",
"a",
"file",
"on",
"the",
"file",
"system",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/platforms/ios/www/plugins/cordova-plugin-file/www/FileEntry.js#L39-L49
|
|
13,453
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/hooks/afterPrepare.js
|
run
|
function run(context) {
const preferences = configPreferences.read(context);
const platforms = context.opts.cordova.platforms;
platforms.forEach(platform => {
if (platform === ANDROID) {
androidManifest.writePreferences(context, preferences);
}
if (platform === IOS) {
iosDevelopmentTeam.addDevelopmentTeam(preferences);
}
});
}
|
javascript
|
function run(context) {
const preferences = configPreferences.read(context);
const platforms = context.opts.cordova.platforms;
platforms.forEach(platform => {
if (platform === ANDROID) {
androidManifest.writePreferences(context, preferences);
}
if (platform === IOS) {
iosDevelopmentTeam.addDevelopmentTeam(preferences);
}
});
}
|
[
"function",
"run",
"(",
"context",
")",
"{",
"const",
"preferences",
"=",
"configPreferences",
".",
"read",
"(",
"context",
")",
";",
"const",
"platforms",
"=",
"context",
".",
"opts",
".",
"cordova",
".",
"platforms",
";",
"platforms",
".",
"forEach",
"(",
"platform",
"=>",
"{",
"if",
"(",
"platform",
"===",
"ANDROID",
")",
"{",
"androidManifest",
".",
"writePreferences",
"(",
"context",
",",
"preferences",
")",
";",
"}",
"if",
"(",
"platform",
"===",
"IOS",
")",
"{",
"iosDevelopmentTeam",
".",
"addDevelopmentTeam",
"(",
"preferences",
")",
";",
"}",
"}",
")",
";",
"}"
] |
builds after platform config
|
[
"builds",
"after",
"platform",
"config"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/hooks/afterPrepare.js#L14-L26
|
13,454
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/index.js
|
execute
|
function execute(method, params) {
var output = !params ? [] : params;
if (method == "getStandardEvents") {
return new Promise(function promise(resolve, reject) {
resolve(standardEvent);
});
}
return new Promise(function promise(resolve, reject) {
exec(
function success(res) {
resolve(res);
},
function failure(err) {
reject(err);
},
API_CLASS,
method,
output
);
});
}
|
javascript
|
function execute(method, params) {
var output = !params ? [] : params;
if (method == "getStandardEvents") {
return new Promise(function promise(resolve, reject) {
resolve(standardEvent);
});
}
return new Promise(function promise(resolve, reject) {
exec(
function success(res) {
resolve(res);
},
function failure(err) {
reject(err);
},
API_CLASS,
method,
output
);
});
}
|
[
"function",
"execute",
"(",
"method",
",",
"params",
")",
"{",
"var",
"output",
"=",
"!",
"params",
"?",
"[",
"]",
":",
"params",
";",
"if",
"(",
"method",
"==",
"\"getStandardEvents\"",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"promise",
"(",
"resolve",
",",
"reject",
")",
"{",
"resolve",
"(",
"standardEvent",
")",
";",
"}",
")",
";",
"}",
"return",
"new",
"Promise",
"(",
"function",
"promise",
"(",
"resolve",
",",
"reject",
")",
"{",
"exec",
"(",
"function",
"success",
"(",
"res",
")",
"{",
"resolve",
"(",
"res",
")",
";",
"}",
",",
"function",
"failure",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
",",
"API_CLASS",
",",
"method",
",",
"output",
")",
";",
"}",
")",
";",
"}"
] |
JavsSript to SDK wrappers
|
[
"JavsSript",
"to",
"SDK",
"wrappers"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/index.js#L33-L55
|
13,455
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-file/www/FileReader.js
|
function() {
this._readyState = 0;
this._error = null;
this._result = null;
this._progress = null;
this._localURL = '';
this._realReader = origFileReader ? new origFileReader() : {};
}
|
javascript
|
function() {
this._readyState = 0;
this._error = null;
this._result = null;
this._progress = null;
this._localURL = '';
this._realReader = origFileReader ? new origFileReader() : {};
}
|
[
"function",
"(",
")",
"{",
"this",
".",
"_readyState",
"=",
"0",
";",
"this",
".",
"_error",
"=",
"null",
";",
"this",
".",
"_result",
"=",
"null",
";",
"this",
".",
"_progress",
"=",
"null",
";",
"this",
".",
"_localURL",
"=",
"''",
";",
"this",
".",
"_realReader",
"=",
"origFileReader",
"?",
"new",
"origFileReader",
"(",
")",
":",
"{",
"}",
";",
"}"
] |
This class reads the mobile device file system.
For Android:
The root directory is the root of the file system.
To read from the SD card, the file name is "sdcard/my_file.txt"
@constructor
|
[
"This",
"class",
"reads",
"the",
"mobile",
"device",
"file",
"system",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-file/www/FileReader.js#L37-L44
|
|
13,456
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/ios/updateDevelopmentTeam.js
|
addDevelopmentTeam
|
function addDevelopmentTeam(preferences) {
const file = path.join(preferences.projectRoot, FILENAME);
let content = getBuildJson(file);
content = convertStringToJson(content);
createDefaultBuildJson(content);
updateDevelopmentTeam(content, preferences);
content = convertJsonToString(content);
setBuildJson(file, content);
}
|
javascript
|
function addDevelopmentTeam(preferences) {
const file = path.join(preferences.projectRoot, FILENAME);
let content = getBuildJson(file);
content = convertStringToJson(content);
createDefaultBuildJson(content);
updateDevelopmentTeam(content, preferences);
content = convertJsonToString(content);
setBuildJson(file, content);
}
|
[
"function",
"addDevelopmentTeam",
"(",
"preferences",
")",
"{",
"const",
"file",
"=",
"path",
".",
"join",
"(",
"preferences",
".",
"projectRoot",
",",
"FILENAME",
")",
";",
"let",
"content",
"=",
"getBuildJson",
"(",
"file",
")",
";",
"content",
"=",
"convertStringToJson",
"(",
"content",
")",
";",
"createDefaultBuildJson",
"(",
"content",
")",
";",
"updateDevelopmentTeam",
"(",
"content",
",",
"preferences",
")",
";",
"content",
"=",
"convertJsonToString",
"(",
"content",
")",
";",
"setBuildJson",
"(",
"file",
",",
"content",
")",
";",
"}"
] |
updates the development team for Universal Links
|
[
"updates",
"the",
"development",
"team",
"for",
"Universal",
"Links"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/ios/updateDevelopmentTeam.js#L14-L23
|
13,457
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/ios/updateDevelopmentTeam.js
|
updateDevelopmentTeam
|
function updateDevelopmentTeam(content, preferences) {
const release = preferences.iosTeamRelease;
const debug = preferences.iosTeamDebug
? preferences.iosTeamDebug
: preferences.iosTeamRelease;
if (release === null) {
throw new Error(
'BRANCH SDK: Invalid "ios-team-release" in <branch-config> in your config.xml. Docs https://goo.gl/GijGKP'
);
}
content.ios.release.developmentTeam = release;
content.ios.debug.developmentTeam = debug;
}
|
javascript
|
function updateDevelopmentTeam(content, preferences) {
const release = preferences.iosTeamRelease;
const debug = preferences.iosTeamDebug
? preferences.iosTeamDebug
: preferences.iosTeamRelease;
if (release === null) {
throw new Error(
'BRANCH SDK: Invalid "ios-team-release" in <branch-config> in your config.xml. Docs https://goo.gl/GijGKP'
);
}
content.ios.release.developmentTeam = release;
content.ios.debug.developmentTeam = debug;
}
|
[
"function",
"updateDevelopmentTeam",
"(",
"content",
",",
"preferences",
")",
"{",
"const",
"release",
"=",
"preferences",
".",
"iosTeamRelease",
";",
"const",
"debug",
"=",
"preferences",
".",
"iosTeamDebug",
"?",
"preferences",
".",
"iosTeamDebug",
":",
"preferences",
".",
"iosTeamRelease",
";",
"if",
"(",
"release",
"===",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'BRANCH SDK: Invalid \"ios-team-release\" in <branch-config> in your config.xml. Docs https://goo.gl/GijGKP'",
")",
";",
"}",
"content",
".",
"ios",
".",
"release",
".",
"developmentTeam",
"=",
"release",
";",
"content",
".",
"ios",
".",
"debug",
".",
"developmentTeam",
"=",
"debug",
";",
"}"
] |
update build.json with developmentTeam from config.xml
|
[
"update",
"build",
".",
"json",
"with",
"developmentTeam",
"from",
"config",
".",
"xml"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/ios/updateDevelopmentTeam.js#L88-L102
|
13,458
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-globalization/src/blackberry10/index.js
|
function (successCB, failureCB, args, env) {
var result = new PluginResult(args, env);
var response = g11n.getInstance().InvokeMethod('getPreferredLanguage', args);
var data = JSON.parse(response);
console.log('getPreferredLanguage: ' + JSON.stringify(response));
if (data.error !== undefined) {
result.error({
code: data.error.code,
message: data.error.message
});
} else {
result.ok({
value: data.result
});
}
}
|
javascript
|
function (successCB, failureCB, args, env) {
var result = new PluginResult(args, env);
var response = g11n.getInstance().InvokeMethod('getPreferredLanguage', args);
var data = JSON.parse(response);
console.log('getPreferredLanguage: ' + JSON.stringify(response));
if (data.error !== undefined) {
result.error({
code: data.error.code,
message: data.error.message
});
} else {
result.ok({
value: data.result
});
}
}
|
[
"function",
"(",
"successCB",
",",
"failureCB",
",",
"args",
",",
"env",
")",
"{",
"var",
"result",
"=",
"new",
"PluginResult",
"(",
"args",
",",
"env",
")",
";",
"var",
"response",
"=",
"g11n",
".",
"getInstance",
"(",
")",
".",
"InvokeMethod",
"(",
"'getPreferredLanguage'",
",",
"args",
")",
";",
"var",
"data",
"=",
"JSON",
".",
"parse",
"(",
"response",
")",
";",
"console",
".",
"log",
"(",
"'getPreferredLanguage: '",
"+",
"JSON",
".",
"stringify",
"(",
"response",
")",
")",
";",
"if",
"(",
"data",
".",
"error",
"!==",
"undefined",
")",
"{",
"result",
".",
"error",
"(",
"{",
"code",
":",
"data",
".",
"error",
".",
"code",
",",
"message",
":",
"data",
".",
"error",
".",
"message",
"}",
")",
";",
"}",
"else",
"{",
"result",
".",
"ok",
"(",
"{",
"value",
":",
"data",
".",
"result",
"}",
")",
";",
"}",
"}"
] |
Returns the string identifier for the client's current language.
It returns the language identifier string to the successCB callback with a
properties object as a parameter. If there is an error getting the language,
then the errorCB callback is invoked.
@param {Function} successCB
@param {Function} errorCB
@return Object.value {String}: The language identifier
@error GlobalizationError.UNKNOWN_ERROR
Example
globalization.getPreferredLanguage(function (language) {alert('language:' + language.value + '\n');},
function () {});
|
[
"Returns",
"the",
"string",
"identifier",
"for",
"the",
"client",
"s",
"current",
"language",
".",
"It",
"returns",
"the",
"language",
"identifier",
"string",
"to",
"the",
"successCB",
"callback",
"with",
"a",
"properties",
"object",
"as",
"a",
"parameter",
".",
"If",
"there",
"is",
"an",
"error",
"getting",
"the",
"language",
"then",
"the",
"errorCB",
"callback",
"is",
"invoked",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-globalization/src/blackberry10/index.js#L44-L60
|
|
13,459
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-globalization/src/blackberry10/index.js
|
function (successCB, failureCB, args, env) {
var result = new PluginResult(args, env);
var response = g11n.getInstance().InvokeMethod('getNumberPattern', args);
var data = JSON.parse(response);
console.log('getNumberPattern: ' + JSON.stringify(response));
if (data.error !== undefined) {
result.error({
code: data.error.code,
message: data.error.message
});
} else {
result.ok({
pattern: data.result.pattern,
symbol: data.result.symbol,
fraction: data.result.fraction,
rounding: data.result.rounding,
positive: data.result.positive,
negative: data.result.negative,
decimal: data.result.decimal,
grouping: data.result.grouping
});
}
}
|
javascript
|
function (successCB, failureCB, args, env) {
var result = new PluginResult(args, env);
var response = g11n.getInstance().InvokeMethod('getNumberPattern', args);
var data = JSON.parse(response);
console.log('getNumberPattern: ' + JSON.stringify(response));
if (data.error !== undefined) {
result.error({
code: data.error.code,
message: data.error.message
});
} else {
result.ok({
pattern: data.result.pattern,
symbol: data.result.symbol,
fraction: data.result.fraction,
rounding: data.result.rounding,
positive: data.result.positive,
negative: data.result.negative,
decimal: data.result.decimal,
grouping: data.result.grouping
});
}
}
|
[
"function",
"(",
"successCB",
",",
"failureCB",
",",
"args",
",",
"env",
")",
"{",
"var",
"result",
"=",
"new",
"PluginResult",
"(",
"args",
",",
"env",
")",
";",
"var",
"response",
"=",
"g11n",
".",
"getInstance",
"(",
")",
".",
"InvokeMethod",
"(",
"'getNumberPattern'",
",",
"args",
")",
";",
"var",
"data",
"=",
"JSON",
".",
"parse",
"(",
"response",
")",
";",
"console",
".",
"log",
"(",
"'getNumberPattern: '",
"+",
"JSON",
".",
"stringify",
"(",
"response",
")",
")",
";",
"if",
"(",
"data",
".",
"error",
"!==",
"undefined",
")",
"{",
"result",
".",
"error",
"(",
"{",
"code",
":",
"data",
".",
"error",
".",
"code",
",",
"message",
":",
"data",
".",
"error",
".",
"message",
"}",
")",
";",
"}",
"else",
"{",
"result",
".",
"ok",
"(",
"{",
"pattern",
":",
"data",
".",
"result",
".",
"pattern",
",",
"symbol",
":",
"data",
".",
"result",
".",
"symbol",
",",
"fraction",
":",
"data",
".",
"result",
".",
"fraction",
",",
"rounding",
":",
"data",
".",
"result",
".",
"rounding",
",",
"positive",
":",
"data",
".",
"result",
".",
"positive",
",",
"negative",
":",
"data",
".",
"result",
".",
"negative",
",",
"decimal",
":",
"data",
".",
"result",
".",
"decimal",
",",
"grouping",
":",
"data",
".",
"result",
".",
"grouping",
"}",
")",
";",
"}",
"}"
] |
Returns a pattern string for formatting and parsing numbers according to the client's user
preferences. It returns the pattern to the successCB callback with a properties object as a
parameter. If there is an error obtaining the pattern, then the errorCB callback is invoked.
The defaults are: type="decimal"
@param {Function} successCB
@param {Function} errorCB
@param {Object} options {optional}
type {String}: 'decimal', "percent", or 'currency'
@return Object.pattern {String}: The number pattern for formatting and parsing numbers.
The patterns follow Unicode Technical Standard #35.
http://unicode.org/reports/tr35/tr35-4.html
Object.symbol {String}: The symbol to be used when formatting and parsing
e.g., percent or currency symbol.
Object.fraction {Number}: The number of fractional digits to use when parsing and
formatting numbers.
Object.rounding {Number}: The rounding increment to use when parsing and formatting.
Object.positive {String}: The symbol to use for positive numbers when parsing and formatting.
Object.negative: {String}: The symbol to use for negative numbers when parsing and formatting.
Object.decimal: {String}: The decimal symbol to use for parsing and formatting.
Object.grouping: {String}: The grouping symbol to use for parsing and formatting.
@error GlobalizationError.PATTERN_ERROR
Example
globalization.getNumberPattern(
function (pattern) {alert('Pattern:' + pattern.pattern + '\n');},
function () {});
|
[
"Returns",
"a",
"pattern",
"string",
"for",
"formatting",
"and",
"parsing",
"numbers",
"according",
"to",
"the",
"client",
"s",
"user",
"preferences",
".",
"It",
"returns",
"the",
"pattern",
"to",
"the",
"successCB",
"callback",
"with",
"a",
"properties",
"object",
"as",
"a",
"parameter",
".",
"If",
"there",
"is",
"an",
"error",
"obtaining",
"the",
"pattern",
"then",
"the",
"errorCB",
"callback",
"is",
"invoked",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-globalization/src/blackberry10/index.js#L483-L506
|
|
13,460
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/platforms/ios/www/plugins/cordova-plugin-globalization/www/globalization.js
|
function (date, successCB, failureCB, options) {
argscheck.checkArgs('dfFO', 'Globalization.dateToString', arguments);
var dateValue = date.valueOf();
exec(successCB, failureCB, 'Globalization', 'dateToString', [{'date': dateValue, 'options': options}]);
}
|
javascript
|
function (date, successCB, failureCB, options) {
argscheck.checkArgs('dfFO', 'Globalization.dateToString', arguments);
var dateValue = date.valueOf();
exec(successCB, failureCB, 'Globalization', 'dateToString', [{'date': dateValue, 'options': options}]);
}
|
[
"function",
"(",
"date",
",",
"successCB",
",",
"failureCB",
",",
"options",
")",
"{",
"argscheck",
".",
"checkArgs",
"(",
"'dfFO'",
",",
"'Globalization.dateToString'",
",",
"arguments",
")",
";",
"var",
"dateValue",
"=",
"date",
".",
"valueOf",
"(",
")",
";",
"exec",
"(",
"successCB",
",",
"failureCB",
",",
"'Globalization'",
",",
"'dateToString'",
",",
"[",
"{",
"'date'",
":",
"dateValue",
",",
"'options'",
":",
"options",
"}",
"]",
")",
";",
"}"
] |
Returns a date formatted as a string according to the client's user preferences and
calendar using the time zone of the client. It returns the formatted date string to the
successCB callback with a properties object as a parameter. If there is an error
formatting the date, then the errorCB callback is invoked.
The defaults are: formatLenght="short" and selector="date and time"
@param {Date} date
@param {Function} successCB
@param {Function} errorCB
@param {Object} options {optional}
formatLength {String}: 'short', 'medium', 'long', or 'full'
selector {String}: 'date', 'time', or 'date and time'
@return Object.value {String}: The localized date string
@error GlobalizationError.FORMATTING_ERROR
Example
globalization.dateToString(new Date(),
function (date) {alert('date:' + date.value + '\n');},
function (errorCode) {alert(errorCode);},
{formatLength:'short'});
|
[
"Returns",
"a",
"date",
"formatted",
"as",
"a",
"string",
"according",
"to",
"the",
"client",
"s",
"user",
"preferences",
"and",
"calendar",
"using",
"the",
"time",
"zone",
"of",
"the",
"client",
".",
"It",
"returns",
"the",
"formatted",
"date",
"string",
"to",
"the",
"successCB",
"callback",
"with",
"a",
"properties",
"object",
"as",
"a",
"parameter",
".",
"If",
"there",
"is",
"an",
"error",
"formatting",
"the",
"date",
"then",
"the",
"errorCB",
"callback",
"is",
"invoked",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/platforms/ios/www/plugins/cordova-plugin-globalization/www/globalization.js#L97-L101
|
|
13,461
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/platforms/ios/www/plugins/cordova-plugin-globalization/www/globalization.js
|
function (currencyCode, successCB, failureCB) {
argscheck.checkArgs('sfF', 'Globalization.getCurrencyPattern', arguments);
exec(successCB, failureCB, 'Globalization', 'getCurrencyPattern', [{'currencyCode': currencyCode}]);
}
|
javascript
|
function (currencyCode, successCB, failureCB) {
argscheck.checkArgs('sfF', 'Globalization.getCurrencyPattern', arguments);
exec(successCB, failureCB, 'Globalization', 'getCurrencyPattern', [{'currencyCode': currencyCode}]);
}
|
[
"function",
"(",
"currencyCode",
",",
"successCB",
",",
"failureCB",
")",
"{",
"argscheck",
".",
"checkArgs",
"(",
"'sfF'",
",",
"'Globalization.getCurrencyPattern'",
",",
"arguments",
")",
";",
"exec",
"(",
"successCB",
",",
"failureCB",
",",
"'Globalization'",
",",
"'getCurrencyPattern'",
",",
"[",
"{",
"'currencyCode'",
":",
"currencyCode",
"}",
"]",
")",
";",
"}"
] |
Returns a pattern string for formatting and parsing currency values according to the client's
user preferences and ISO 4217 currency code. It returns the pattern to the successCB callback with a
properties object as a parameter. If there is an error obtaining the pattern, then the errorCB
callback is invoked.
@param {String} currencyCode
@param {Function} successCB
@param {Function} errorCB
@return Object.pattern {String}: The currency pattern for formatting and parsing currency values.
The patterns follow Unicode Technical Standard #35
http://unicode.org/reports/tr35/tr35-4.html
Object.code {String}: The ISO 4217 currency code for the pattern.
Object.fraction {Number}: The number of fractional digits to use when parsing and
formatting currency.
Object.rounding {Number}: The rounding increment to use when parsing and formatting.
Object.decimal: {String}: The decimal symbol to use for parsing and formatting.
Object.grouping: {String}: The grouping symbol to use for parsing and formatting.
@error GlobalizationError.FORMATTING_ERROR
Example
globalization.getCurrencyPattern('EUR',
function (currency) {alert('Pattern:' + currency.pattern + '\n');}
function () {});
|
[
"Returns",
"a",
"pattern",
"string",
"for",
"formatting",
"and",
"parsing",
"currency",
"values",
"according",
"to",
"the",
"client",
"s",
"user",
"preferences",
"and",
"ISO",
"4217",
"currency",
"code",
".",
"It",
"returns",
"the",
"pattern",
"to",
"the",
"successCB",
"callback",
"with",
"a",
"properties",
"object",
"as",
"a",
"parameter",
".",
"If",
"there",
"is",
"an",
"error",
"obtaining",
"the",
"pattern",
"then",
"the",
"errorCB",
"callback",
"is",
"invoked",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/platforms/ios/www/plugins/cordova-plugin-globalization/www/globalization.js#L379-L382
|
|
13,462
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-media-capture/www/MediaFile.js
|
function(name, localURL, type, lastModifiedDate, size){
MediaFile.__super__.constructor.apply(this, arguments);
}
|
javascript
|
function(name, localURL, type, lastModifiedDate, size){
MediaFile.__super__.constructor.apply(this, arguments);
}
|
[
"function",
"(",
"name",
",",
"localURL",
",",
"type",
",",
"lastModifiedDate",
",",
"size",
")",
"{",
"MediaFile",
".",
"__super__",
".",
"constructor",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}"
] |
Represents a single file.
name {DOMString} name of the file, without path information
fullPath {DOMString} the full path of the file, including the name
type {DOMString} mime type
lastModifiedDate {Date} last modified date
size {Number} size of the file in bytes
|
[
"Represents",
"a",
"single",
"file",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-media-capture/www/MediaFile.js#L35-L37
|
|
13,463
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
collectEventData
|
function collectEventData(element, eventType, touches, ev) {
// find out pointerType
var pointerType = ionic.Gestures.POINTER_TOUCH;
if(ev.type.match(/mouse/) || ionic.Gestures.PointerEvent.matchType(ionic.Gestures.POINTER_MOUSE, ev)) {
pointerType = ionic.Gestures.POINTER_MOUSE;
}
return {
center: ionic.Gestures.utils.getCenter(touches),
timeStamp: new Date().getTime(),
target: ev.target,
touches: touches,
eventType: eventType,
pointerType: pointerType,
srcEvent: ev,
/**
* prevent the browser default actions
* mostly used to disable scrolling of the browser
*/
preventDefault: function() {
if(this.srcEvent.preventManipulation) {
this.srcEvent.preventManipulation();
}
if(this.srcEvent.preventDefault) {
// this.srcEvent.preventDefault();
}
},
/**
* stop bubbling the event up to its parents
*/
stopPropagation: function() {
this.srcEvent.stopPropagation();
},
/**
* immediately stop gesture detection
* might be useful after a swipe was detected
* @return {*}
*/
stopDetect: function() {
return ionic.Gestures.detection.stopDetect();
}
};
}
|
javascript
|
function collectEventData(element, eventType, touches, ev) {
// find out pointerType
var pointerType = ionic.Gestures.POINTER_TOUCH;
if(ev.type.match(/mouse/) || ionic.Gestures.PointerEvent.matchType(ionic.Gestures.POINTER_MOUSE, ev)) {
pointerType = ionic.Gestures.POINTER_MOUSE;
}
return {
center: ionic.Gestures.utils.getCenter(touches),
timeStamp: new Date().getTime(),
target: ev.target,
touches: touches,
eventType: eventType,
pointerType: pointerType,
srcEvent: ev,
/**
* prevent the browser default actions
* mostly used to disable scrolling of the browser
*/
preventDefault: function() {
if(this.srcEvent.preventManipulation) {
this.srcEvent.preventManipulation();
}
if(this.srcEvent.preventDefault) {
// this.srcEvent.preventDefault();
}
},
/**
* stop bubbling the event up to its parents
*/
stopPropagation: function() {
this.srcEvent.stopPropagation();
},
/**
* immediately stop gesture detection
* might be useful after a swipe was detected
* @return {*}
*/
stopDetect: function() {
return ionic.Gestures.detection.stopDetect();
}
};
}
|
[
"function",
"collectEventData",
"(",
"element",
",",
"eventType",
",",
"touches",
",",
"ev",
")",
"{",
"// find out pointerType",
"var",
"pointerType",
"=",
"ionic",
".",
"Gestures",
".",
"POINTER_TOUCH",
";",
"if",
"(",
"ev",
".",
"type",
".",
"match",
"(",
"/",
"mouse",
"/",
")",
"||",
"ionic",
".",
"Gestures",
".",
"PointerEvent",
".",
"matchType",
"(",
"ionic",
".",
"Gestures",
".",
"POINTER_MOUSE",
",",
"ev",
")",
")",
"{",
"pointerType",
"=",
"ionic",
".",
"Gestures",
".",
"POINTER_MOUSE",
";",
"}",
"return",
"{",
"center",
":",
"ionic",
".",
"Gestures",
".",
"utils",
".",
"getCenter",
"(",
"touches",
")",
",",
"timeStamp",
":",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
",",
"target",
":",
"ev",
".",
"target",
",",
"touches",
":",
"touches",
",",
"eventType",
":",
"eventType",
",",
"pointerType",
":",
"pointerType",
",",
"srcEvent",
":",
"ev",
",",
"/**\n * prevent the browser default actions\n * mostly used to disable scrolling of the browser\n */",
"preventDefault",
":",
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"srcEvent",
".",
"preventManipulation",
")",
"{",
"this",
".",
"srcEvent",
".",
"preventManipulation",
"(",
")",
";",
"}",
"if",
"(",
"this",
".",
"srcEvent",
".",
"preventDefault",
")",
"{",
"// this.srcEvent.preventDefault();",
"}",
"}",
",",
"/**\n * stop bubbling the event up to its parents\n */",
"stopPropagation",
":",
"function",
"(",
")",
"{",
"this",
".",
"srcEvent",
".",
"stopPropagation",
"(",
")",
";",
"}",
",",
"/**\n * immediately stop gesture detection\n * might be useful after a swipe was detected\n * @return {*}\n */",
"stopDetect",
":",
"function",
"(",
")",
"{",
"return",
"ionic",
".",
"Gestures",
".",
"detection",
".",
"stopDetect",
"(",
")",
";",
"}",
"}",
";",
"}"
] |
collect event data for ionic.Gestures js
@param {HTMLElement} element
@param {String} eventType like ionic.Gestures.EVENT_MOVE
@param {Object} eventData
|
[
"collect",
"event",
"data",
"for",
"ionic",
".",
"Gestures",
"js"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L1032-L1079
|
13,464
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
function() {
if (keyboardHasPlugin()) {
window.removeEventListener('native.keyboardshow', debouncedKeyboardNativeShow );
window.removeEventListener('native.keyboardhide', keyboardFocusOut);
} else {
document.body.removeEventListener('focusout', keyboardFocusOut);
}
document.body.removeEventListener('ionic.focusin', debouncedKeyboardFocusIn);
document.body.removeEventListener('focusin', debouncedKeyboardFocusIn);
window.removeEventListener('orientationchange', keyboardOrientationChange);
if ( window.navigator.msPointerEnabled ) {
document.removeEventListener("MSPointerDown", keyboardInit);
} else {
document.removeEventListener('touchstart', keyboardInit);
}
ionic.keyboard.isInitialized = false;
}
|
javascript
|
function() {
if (keyboardHasPlugin()) {
window.removeEventListener('native.keyboardshow', debouncedKeyboardNativeShow );
window.removeEventListener('native.keyboardhide', keyboardFocusOut);
} else {
document.body.removeEventListener('focusout', keyboardFocusOut);
}
document.body.removeEventListener('ionic.focusin', debouncedKeyboardFocusIn);
document.body.removeEventListener('focusin', debouncedKeyboardFocusIn);
window.removeEventListener('orientationchange', keyboardOrientationChange);
if ( window.navigator.msPointerEnabled ) {
document.removeEventListener("MSPointerDown", keyboardInit);
} else {
document.removeEventListener('touchstart', keyboardInit);
}
ionic.keyboard.isInitialized = false;
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"keyboardHasPlugin",
"(",
")",
")",
"{",
"window",
".",
"removeEventListener",
"(",
"'native.keyboardshow'",
",",
"debouncedKeyboardNativeShow",
")",
";",
"window",
".",
"removeEventListener",
"(",
"'native.keyboardhide'",
",",
"keyboardFocusOut",
")",
";",
"}",
"else",
"{",
"document",
".",
"body",
".",
"removeEventListener",
"(",
"'focusout'",
",",
"keyboardFocusOut",
")",
";",
"}",
"document",
".",
"body",
".",
"removeEventListener",
"(",
"'ionic.focusin'",
",",
"debouncedKeyboardFocusIn",
")",
";",
"document",
".",
"body",
".",
"removeEventListener",
"(",
"'focusin'",
",",
"debouncedKeyboardFocusIn",
")",
";",
"window",
".",
"removeEventListener",
"(",
"'orientationchange'",
",",
"keyboardOrientationChange",
")",
";",
"if",
"(",
"window",
".",
"navigator",
".",
"msPointerEnabled",
")",
"{",
"document",
".",
"removeEventListener",
"(",
"\"MSPointerDown\"",
",",
"keyboardInit",
")",
";",
"}",
"else",
"{",
"document",
".",
"removeEventListener",
"(",
"'touchstart'",
",",
"keyboardInit",
")",
";",
"}",
"ionic",
".",
"keyboard",
".",
"isInitialized",
"=",
"false",
";",
"}"
] |
Remove all keyboard related event listeners, effectively disabling Ionic's
keyboard adjustments.
|
[
"Remove",
"all",
"keyboard",
"related",
"event",
"listeners",
"effectively",
"disabling",
"Ionic",
"s",
"keyboard",
"adjustments",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L3776-L3795
|
|
13,465
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
keyboardNativeShow
|
function keyboardNativeShow(e) {
clearTimeout(keyboardFocusOutTimer);
//console.log("keyboardNativeShow fired at: " + Date.now());
//console.log("keyboardNativeshow window.innerHeight: " + window.innerHeight);
if (!ionic.keyboard.isOpen || ionic.keyboard.isClosing) {
ionic.keyboard.isOpening = true;
ionic.keyboard.isClosing = false;
}
ionic.keyboard.height = e.keyboardHeight;
//console.log('nativeshow keyboard height:' + e.keyboardHeight);
if (wasOrientationChange) {
keyboardWaitForResize(keyboardUpdateViewportHeight, true);
} else {
keyboardWaitForResize(keyboardShow, true);
}
}
|
javascript
|
function keyboardNativeShow(e) {
clearTimeout(keyboardFocusOutTimer);
//console.log("keyboardNativeShow fired at: " + Date.now());
//console.log("keyboardNativeshow window.innerHeight: " + window.innerHeight);
if (!ionic.keyboard.isOpen || ionic.keyboard.isClosing) {
ionic.keyboard.isOpening = true;
ionic.keyboard.isClosing = false;
}
ionic.keyboard.height = e.keyboardHeight;
//console.log('nativeshow keyboard height:' + e.keyboardHeight);
if (wasOrientationChange) {
keyboardWaitForResize(keyboardUpdateViewportHeight, true);
} else {
keyboardWaitForResize(keyboardShow, true);
}
}
|
[
"function",
"keyboardNativeShow",
"(",
"e",
")",
"{",
"clearTimeout",
"(",
"keyboardFocusOutTimer",
")",
";",
"//console.log(\"keyboardNativeShow fired at: \" + Date.now());",
"//console.log(\"keyboardNativeshow window.innerHeight: \" + window.innerHeight);",
"if",
"(",
"!",
"ionic",
".",
"keyboard",
".",
"isOpen",
"||",
"ionic",
".",
"keyboard",
".",
"isClosing",
")",
"{",
"ionic",
".",
"keyboard",
".",
"isOpening",
"=",
"true",
";",
"ionic",
".",
"keyboard",
".",
"isClosing",
"=",
"false",
";",
"}",
"ionic",
".",
"keyboard",
".",
"height",
"=",
"e",
".",
"keyboardHeight",
";",
"//console.log('nativeshow keyboard height:' + e.keyboardHeight);",
"if",
"(",
"wasOrientationChange",
")",
"{",
"keyboardWaitForResize",
"(",
"keyboardUpdateViewportHeight",
",",
"true",
")",
";",
"}",
"else",
"{",
"keyboardWaitForResize",
"(",
"keyboardShow",
",",
"true",
")",
";",
"}",
"}"
] |
Event handler for 'native.keyboardshow' event, sets keyboard.height to the
reported height and keyboard.isOpening to true. Then calls
keyboardWaitForResize with keyboardShow or keyboardUpdateViewportHeight as
the callback depending on whether the event was triggered by a focusin or
an orientationchange.
|
[
"Event",
"handler",
"for",
"native",
".",
"keyboardshow",
"event",
"sets",
"keyboard",
".",
"height",
"to",
"the",
"reported",
"height",
"and",
"keyboard",
".",
"isOpening",
"to",
"true",
".",
"Then",
"calls",
"keyboardWaitForResize",
"with",
"keyboardShow",
"or",
"keyboardUpdateViewportHeight",
"as",
"the",
"callback",
"depending",
"on",
"whether",
"the",
"event",
"was",
"triggered",
"by",
"a",
"focusin",
"or",
"an",
"orientationchange",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L3847-L3865
|
13,466
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
keyboardFocusOut
|
function keyboardFocusOut() {
clearTimeout(keyboardFocusOutTimer);
//console.log("keyboardFocusOut fired at: " + Date.now());
//console.log("keyboardFocusOut event type: " + e.type);
if (ionic.keyboard.isOpen || ionic.keyboard.isOpening) {
ionic.keyboard.isClosing = true;
ionic.keyboard.isOpening = false;
}
// Call keyboardHide with a slight delay because sometimes on focus or
// orientation change focusin is called immediately after, so we give it time
// to cancel keyboardHide
keyboardFocusOutTimer = setTimeout(function() {
ionic.requestAnimationFrame(function() {
// focusOut during or right after an orientationchange, so we didn't get
// a chance to update the viewport height yet, do it and keyboardHide
//console.log("focusOut, wasOrientationChange: " + wasOrientationChange);
if (wasOrientationChange) {
keyboardWaitForResize(function(){
keyboardUpdateViewportHeight();
keyboardHide();
}, false);
} else {
keyboardWaitForResize(keyboardHide, false);
}
});
}, 50);
}
|
javascript
|
function keyboardFocusOut() {
clearTimeout(keyboardFocusOutTimer);
//console.log("keyboardFocusOut fired at: " + Date.now());
//console.log("keyboardFocusOut event type: " + e.type);
if (ionic.keyboard.isOpen || ionic.keyboard.isOpening) {
ionic.keyboard.isClosing = true;
ionic.keyboard.isOpening = false;
}
// Call keyboardHide with a slight delay because sometimes on focus or
// orientation change focusin is called immediately after, so we give it time
// to cancel keyboardHide
keyboardFocusOutTimer = setTimeout(function() {
ionic.requestAnimationFrame(function() {
// focusOut during or right after an orientationchange, so we didn't get
// a chance to update the viewport height yet, do it and keyboardHide
//console.log("focusOut, wasOrientationChange: " + wasOrientationChange);
if (wasOrientationChange) {
keyboardWaitForResize(function(){
keyboardUpdateViewportHeight();
keyboardHide();
}, false);
} else {
keyboardWaitForResize(keyboardHide, false);
}
});
}, 50);
}
|
[
"function",
"keyboardFocusOut",
"(",
")",
"{",
"clearTimeout",
"(",
"keyboardFocusOutTimer",
")",
";",
"//console.log(\"keyboardFocusOut fired at: \" + Date.now());",
"//console.log(\"keyboardFocusOut event type: \" + e.type);",
"if",
"(",
"ionic",
".",
"keyboard",
".",
"isOpen",
"||",
"ionic",
".",
"keyboard",
".",
"isOpening",
")",
"{",
"ionic",
".",
"keyboard",
".",
"isClosing",
"=",
"true",
";",
"ionic",
".",
"keyboard",
".",
"isOpening",
"=",
"false",
";",
"}",
"// Call keyboardHide with a slight delay because sometimes on focus or",
"// orientation change focusin is called immediately after, so we give it time",
"// to cancel keyboardHide",
"keyboardFocusOutTimer",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"ionic",
".",
"requestAnimationFrame",
"(",
"function",
"(",
")",
"{",
"// focusOut during or right after an orientationchange, so we didn't get",
"// a chance to update the viewport height yet, do it and keyboardHide",
"//console.log(\"focusOut, wasOrientationChange: \" + wasOrientationChange);",
"if",
"(",
"wasOrientationChange",
")",
"{",
"keyboardWaitForResize",
"(",
"function",
"(",
")",
"{",
"keyboardUpdateViewportHeight",
"(",
")",
";",
"keyboardHide",
"(",
")",
";",
"}",
",",
"false",
")",
";",
"}",
"else",
"{",
"keyboardWaitForResize",
"(",
"keyboardHide",
",",
"false",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"50",
")",
";",
"}"
] |
Event handler for 'focusout' events. Sets keyboard.isClosing to true and
calls keyboardWaitForResize with keyboardHide as the callback after a small
timeout.
|
[
"Event",
"handler",
"for",
"focusout",
"events",
".",
"Sets",
"keyboard",
".",
"isClosing",
"to",
"true",
"and",
"calls",
"keyboardWaitForResize",
"with",
"keyboardHide",
"as",
"the",
"callback",
"after",
"a",
"small",
"timeout",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L3944-L3972
|
13,467
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
keyboardOrientationChange
|
function keyboardOrientationChange() {
//console.log("orientationchange fired at: " + Date.now());
//console.log("orientation was: " + (ionic.keyboard.isLandscape ? "landscape" : "portrait"));
// toggle orientation
ionic.keyboard.isLandscape = !ionic.keyboard.isLandscape;
// //console.log("now orientation is: " + (ionic.keyboard.isLandscape ? "landscape" : "portrait"));
// no need to wait for resizing on iOS, and orientationchange always fires
// after the keyboard has opened, so it doesn't matter if it's open or not
if (ionic.Platform.isIOS()) {
keyboardUpdateViewportHeight();
}
// On Android, if the keyboard isn't open or we aren't using the keyboard
// plugin, update the viewport height once everything has resized. If the
// keyboard is open and we are using the keyboard plugin do nothing and let
// nativeShow handle it using an accurate keyboard height.
if ( ionic.Platform.isAndroid()) {
if (!ionic.keyboard.isOpen || !keyboardHasPlugin()) {
keyboardWaitForResize(keyboardUpdateViewportHeight, false);
} else {
wasOrientationChange = true;
}
}
}
|
javascript
|
function keyboardOrientationChange() {
//console.log("orientationchange fired at: " + Date.now());
//console.log("orientation was: " + (ionic.keyboard.isLandscape ? "landscape" : "portrait"));
// toggle orientation
ionic.keyboard.isLandscape = !ionic.keyboard.isLandscape;
// //console.log("now orientation is: " + (ionic.keyboard.isLandscape ? "landscape" : "portrait"));
// no need to wait for resizing on iOS, and orientationchange always fires
// after the keyboard has opened, so it doesn't matter if it's open or not
if (ionic.Platform.isIOS()) {
keyboardUpdateViewportHeight();
}
// On Android, if the keyboard isn't open or we aren't using the keyboard
// plugin, update the viewport height once everything has resized. If the
// keyboard is open and we are using the keyboard plugin do nothing and let
// nativeShow handle it using an accurate keyboard height.
if ( ionic.Platform.isAndroid()) {
if (!ionic.keyboard.isOpen || !keyboardHasPlugin()) {
keyboardWaitForResize(keyboardUpdateViewportHeight, false);
} else {
wasOrientationChange = true;
}
}
}
|
[
"function",
"keyboardOrientationChange",
"(",
")",
"{",
"//console.log(\"orientationchange fired at: \" + Date.now());",
"//console.log(\"orientation was: \" + (ionic.keyboard.isLandscape ? \"landscape\" : \"portrait\"));",
"// toggle orientation",
"ionic",
".",
"keyboard",
".",
"isLandscape",
"=",
"!",
"ionic",
".",
"keyboard",
".",
"isLandscape",
";",
"// //console.log(\"now orientation is: \" + (ionic.keyboard.isLandscape ? \"landscape\" : \"portrait\"));",
"// no need to wait for resizing on iOS, and orientationchange always fires",
"// after the keyboard has opened, so it doesn't matter if it's open or not",
"if",
"(",
"ionic",
".",
"Platform",
".",
"isIOS",
"(",
")",
")",
"{",
"keyboardUpdateViewportHeight",
"(",
")",
";",
"}",
"// On Android, if the keyboard isn't open or we aren't using the keyboard",
"// plugin, update the viewport height once everything has resized. If the",
"// keyboard is open and we are using the keyboard plugin do nothing and let",
"// nativeShow handle it using an accurate keyboard height.",
"if",
"(",
"ionic",
".",
"Platform",
".",
"isAndroid",
"(",
")",
")",
"{",
"if",
"(",
"!",
"ionic",
".",
"keyboard",
".",
"isOpen",
"||",
"!",
"keyboardHasPlugin",
"(",
")",
")",
"{",
"keyboardWaitForResize",
"(",
"keyboardUpdateViewportHeight",
",",
"false",
")",
";",
"}",
"else",
"{",
"wasOrientationChange",
"=",
"true",
";",
"}",
"}",
"}"
] |
Event handler for 'orientationchange' events. If using the keyboard plugin
and the keyboard is open on Android, sets wasOrientationChange to true so
nativeShow can update the viewport height with an accurate keyboard height.
If the keyboard isn't open or keyboard plugin isn't being used,
waits for the window to resize before updating the viewport height.
On iOS, where orientationchange fires after the keyboard has already shown,
updates the viewport immediately, regardless of if the keyboard is already
open.
|
[
"Event",
"handler",
"for",
"orientationchange",
"events",
".",
"If",
"using",
"the",
"keyboard",
"plugin",
"and",
"the",
"keyboard",
"is",
"open",
"on",
"Android",
"sets",
"wasOrientationChange",
"to",
"true",
"so",
"nativeShow",
"can",
"update",
"the",
"viewport",
"height",
"with",
"an",
"accurate",
"keyboard",
"height",
".",
"If",
"the",
"keyboard",
"isn",
"t",
"open",
"or",
"keyboard",
"plugin",
"isn",
"t",
"being",
"used",
"waits",
"for",
"the",
"window",
"to",
"resize",
"before",
"updating",
"the",
"viewport",
"height",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L3985-L4010
|
13,468
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
keyboardShow
|
function keyboardShow() {
ionic.keyboard.isOpen = true;
ionic.keyboard.isOpening = false;
var details = {
keyboardHeight: keyboardGetHeight(),
viewportHeight: keyboardCurrentViewportHeight
};
if (keyboardActiveElement) {
details.target = keyboardActiveElement;
var elementBounds = keyboardActiveElement.getBoundingClientRect();
details.elementTop = Math.round(elementBounds.top);
details.elementBottom = Math.round(elementBounds.bottom);
details.windowHeight = details.viewportHeight - details.keyboardHeight;
//console.log("keyboardShow viewportHeight: " + details.viewportHeight +
//", windowHeight: " + details.windowHeight +
//", keyboardHeight: " + details.keyboardHeight);
// figure out if the element is under the keyboard
details.isElementUnderKeyboard = (details.elementBottom > details.windowHeight);
//console.log("isUnderKeyboard: " + details.isElementUnderKeyboard);
//console.log("elementBottom: " + details.elementBottom);
// send event so the scroll view adjusts
ionic.trigger('scrollChildIntoView', details, true);
}
setTimeout(function(){
document.body.classList.add(KEYBOARD_OPEN_CSS);
}, 400);
return details; //for testing
}
|
javascript
|
function keyboardShow() {
ionic.keyboard.isOpen = true;
ionic.keyboard.isOpening = false;
var details = {
keyboardHeight: keyboardGetHeight(),
viewportHeight: keyboardCurrentViewportHeight
};
if (keyboardActiveElement) {
details.target = keyboardActiveElement;
var elementBounds = keyboardActiveElement.getBoundingClientRect();
details.elementTop = Math.round(elementBounds.top);
details.elementBottom = Math.round(elementBounds.bottom);
details.windowHeight = details.viewportHeight - details.keyboardHeight;
//console.log("keyboardShow viewportHeight: " + details.viewportHeight +
//", windowHeight: " + details.windowHeight +
//", keyboardHeight: " + details.keyboardHeight);
// figure out if the element is under the keyboard
details.isElementUnderKeyboard = (details.elementBottom > details.windowHeight);
//console.log("isUnderKeyboard: " + details.isElementUnderKeyboard);
//console.log("elementBottom: " + details.elementBottom);
// send event so the scroll view adjusts
ionic.trigger('scrollChildIntoView', details, true);
}
setTimeout(function(){
document.body.classList.add(KEYBOARD_OPEN_CSS);
}, 400);
return details; //for testing
}
|
[
"function",
"keyboardShow",
"(",
")",
"{",
"ionic",
".",
"keyboard",
".",
"isOpen",
"=",
"true",
";",
"ionic",
".",
"keyboard",
".",
"isOpening",
"=",
"false",
";",
"var",
"details",
"=",
"{",
"keyboardHeight",
":",
"keyboardGetHeight",
"(",
")",
",",
"viewportHeight",
":",
"keyboardCurrentViewportHeight",
"}",
";",
"if",
"(",
"keyboardActiveElement",
")",
"{",
"details",
".",
"target",
"=",
"keyboardActiveElement",
";",
"var",
"elementBounds",
"=",
"keyboardActiveElement",
".",
"getBoundingClientRect",
"(",
")",
";",
"details",
".",
"elementTop",
"=",
"Math",
".",
"round",
"(",
"elementBounds",
".",
"top",
")",
";",
"details",
".",
"elementBottom",
"=",
"Math",
".",
"round",
"(",
"elementBounds",
".",
"bottom",
")",
";",
"details",
".",
"windowHeight",
"=",
"details",
".",
"viewportHeight",
"-",
"details",
".",
"keyboardHeight",
";",
"//console.log(\"keyboardShow viewportHeight: \" + details.viewportHeight +",
"//\", windowHeight: \" + details.windowHeight +",
"//\", keyboardHeight: \" + details.keyboardHeight);",
"// figure out if the element is under the keyboard",
"details",
".",
"isElementUnderKeyboard",
"=",
"(",
"details",
".",
"elementBottom",
">",
"details",
".",
"windowHeight",
")",
";",
"//console.log(\"isUnderKeyboard: \" + details.isElementUnderKeyboard);",
"//console.log(\"elementBottom: \" + details.elementBottom);",
"// send event so the scroll view adjusts",
"ionic",
".",
"trigger",
"(",
"'scrollChildIntoView'",
",",
"details",
",",
"true",
")",
";",
"}",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"document",
".",
"body",
".",
"classList",
".",
"add",
"(",
"KEYBOARD_OPEN_CSS",
")",
";",
"}",
",",
"400",
")",
";",
"return",
"details",
";",
"//for testing",
"}"
] |
On keyboard open sets keyboard state to open, adds CSS to the body
indicating the keyboard is open and tells the scroll view to resize and
the currently focused input into view if necessary.
|
[
"On",
"keyboard",
"open",
"sets",
"keyboard",
"state",
"to",
"open",
"adds",
"CSS",
"to",
"the",
"body",
"indicating",
"the",
"keyboard",
"is",
"open",
"and",
"tells",
"the",
"scroll",
"view",
"to",
"resize",
"and",
"the",
"currently",
"focused",
"input",
"into",
"view",
"if",
"necessary",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L4156-L4193
|
13,469
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
function(touches, timeStamp) {
var self = this;
// remember if the deceleration was just stopped
self.__decStopped = !!(self.__isDecelerating || self.__isAnimating);
self.hintResize();
if (timeStamp instanceof Date) {
timeStamp = timeStamp.valueOf();
}
if (typeof timeStamp !== "number") {
timeStamp = Date.now();
}
// Reset interruptedAnimation flag
self.__interruptedAnimation = true;
// Stop deceleration
if (self.__isDecelerating) {
zyngaCore.effect.Animate.stop(self.__isDecelerating);
self.__isDecelerating = false;
self.__interruptedAnimation = true;
}
// Stop animation
if (self.__isAnimating) {
zyngaCore.effect.Animate.stop(self.__isAnimating);
self.__isAnimating = false;
self.__interruptedAnimation = true;
}
// Use center point when dealing with two fingers
var currentTouchLeft, currentTouchTop;
var isSingleTouch = touches.length === 1;
if (isSingleTouch) {
currentTouchLeft = touches[0].pageX;
currentTouchTop = touches[0].pageY;
} else {
currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2;
currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2;
}
// Store initial positions
self.__initialTouchLeft = currentTouchLeft;
self.__initialTouchTop = currentTouchTop;
// Store initial touchList for scale calculation
self.__initialTouches = touches;
// Store current zoom level
self.__zoomLevelStart = self.__zoomLevel;
// Store initial touch positions
self.__lastTouchLeft = currentTouchLeft;
self.__lastTouchTop = currentTouchTop;
// Store initial move time stamp
self.__lastTouchMove = timeStamp;
// Reset initial scale
self.__lastScale = 1;
// Reset locking flags
self.__enableScrollX = !isSingleTouch && self.options.scrollingX;
self.__enableScrollY = !isSingleTouch && self.options.scrollingY;
// Reset tracking flag
self.__isTracking = true;
// Reset deceleration complete flag
self.__didDecelerationComplete = false;
// Dragging starts directly with two fingers, otherwise lazy with an offset
self.__isDragging = !isSingleTouch;
// Some features are disabled in multi touch scenarios
self.__isSingleTouch = isSingleTouch;
// Clearing data structure
self.__positions = [];
}
|
javascript
|
function(touches, timeStamp) {
var self = this;
// remember if the deceleration was just stopped
self.__decStopped = !!(self.__isDecelerating || self.__isAnimating);
self.hintResize();
if (timeStamp instanceof Date) {
timeStamp = timeStamp.valueOf();
}
if (typeof timeStamp !== "number") {
timeStamp = Date.now();
}
// Reset interruptedAnimation flag
self.__interruptedAnimation = true;
// Stop deceleration
if (self.__isDecelerating) {
zyngaCore.effect.Animate.stop(self.__isDecelerating);
self.__isDecelerating = false;
self.__interruptedAnimation = true;
}
// Stop animation
if (self.__isAnimating) {
zyngaCore.effect.Animate.stop(self.__isAnimating);
self.__isAnimating = false;
self.__interruptedAnimation = true;
}
// Use center point when dealing with two fingers
var currentTouchLeft, currentTouchTop;
var isSingleTouch = touches.length === 1;
if (isSingleTouch) {
currentTouchLeft = touches[0].pageX;
currentTouchTop = touches[0].pageY;
} else {
currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2;
currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2;
}
// Store initial positions
self.__initialTouchLeft = currentTouchLeft;
self.__initialTouchTop = currentTouchTop;
// Store initial touchList for scale calculation
self.__initialTouches = touches;
// Store current zoom level
self.__zoomLevelStart = self.__zoomLevel;
// Store initial touch positions
self.__lastTouchLeft = currentTouchLeft;
self.__lastTouchTop = currentTouchTop;
// Store initial move time stamp
self.__lastTouchMove = timeStamp;
// Reset initial scale
self.__lastScale = 1;
// Reset locking flags
self.__enableScrollX = !isSingleTouch && self.options.scrollingX;
self.__enableScrollY = !isSingleTouch && self.options.scrollingY;
// Reset tracking flag
self.__isTracking = true;
// Reset deceleration complete flag
self.__didDecelerationComplete = false;
// Dragging starts directly with two fingers, otherwise lazy with an offset
self.__isDragging = !isSingleTouch;
// Some features are disabled in multi touch scenarios
self.__isSingleTouch = isSingleTouch;
// Clearing data structure
self.__positions = [];
}
|
[
"function",
"(",
"touches",
",",
"timeStamp",
")",
"{",
"var",
"self",
"=",
"this",
";",
"// remember if the deceleration was just stopped",
"self",
".",
"__decStopped",
"=",
"!",
"!",
"(",
"self",
".",
"__isDecelerating",
"||",
"self",
".",
"__isAnimating",
")",
";",
"self",
".",
"hintResize",
"(",
")",
";",
"if",
"(",
"timeStamp",
"instanceof",
"Date",
")",
"{",
"timeStamp",
"=",
"timeStamp",
".",
"valueOf",
"(",
")",
";",
"}",
"if",
"(",
"typeof",
"timeStamp",
"!==",
"\"number\"",
")",
"{",
"timeStamp",
"=",
"Date",
".",
"now",
"(",
")",
";",
"}",
"// Reset interruptedAnimation flag",
"self",
".",
"__interruptedAnimation",
"=",
"true",
";",
"// Stop deceleration",
"if",
"(",
"self",
".",
"__isDecelerating",
")",
"{",
"zyngaCore",
".",
"effect",
".",
"Animate",
".",
"stop",
"(",
"self",
".",
"__isDecelerating",
")",
";",
"self",
".",
"__isDecelerating",
"=",
"false",
";",
"self",
".",
"__interruptedAnimation",
"=",
"true",
";",
"}",
"// Stop animation",
"if",
"(",
"self",
".",
"__isAnimating",
")",
"{",
"zyngaCore",
".",
"effect",
".",
"Animate",
".",
"stop",
"(",
"self",
".",
"__isAnimating",
")",
";",
"self",
".",
"__isAnimating",
"=",
"false",
";",
"self",
".",
"__interruptedAnimation",
"=",
"true",
";",
"}",
"// Use center point when dealing with two fingers",
"var",
"currentTouchLeft",
",",
"currentTouchTop",
";",
"var",
"isSingleTouch",
"=",
"touches",
".",
"length",
"===",
"1",
";",
"if",
"(",
"isSingleTouch",
")",
"{",
"currentTouchLeft",
"=",
"touches",
"[",
"0",
"]",
".",
"pageX",
";",
"currentTouchTop",
"=",
"touches",
"[",
"0",
"]",
".",
"pageY",
";",
"}",
"else",
"{",
"currentTouchLeft",
"=",
"Math",
".",
"abs",
"(",
"touches",
"[",
"0",
"]",
".",
"pageX",
"+",
"touches",
"[",
"1",
"]",
".",
"pageX",
")",
"/",
"2",
";",
"currentTouchTop",
"=",
"Math",
".",
"abs",
"(",
"touches",
"[",
"0",
"]",
".",
"pageY",
"+",
"touches",
"[",
"1",
"]",
".",
"pageY",
")",
"/",
"2",
";",
"}",
"// Store initial positions",
"self",
".",
"__initialTouchLeft",
"=",
"currentTouchLeft",
";",
"self",
".",
"__initialTouchTop",
"=",
"currentTouchTop",
";",
"// Store initial touchList for scale calculation",
"self",
".",
"__initialTouches",
"=",
"touches",
";",
"// Store current zoom level",
"self",
".",
"__zoomLevelStart",
"=",
"self",
".",
"__zoomLevel",
";",
"// Store initial touch positions",
"self",
".",
"__lastTouchLeft",
"=",
"currentTouchLeft",
";",
"self",
".",
"__lastTouchTop",
"=",
"currentTouchTop",
";",
"// Store initial move time stamp",
"self",
".",
"__lastTouchMove",
"=",
"timeStamp",
";",
"// Reset initial scale",
"self",
".",
"__lastScale",
"=",
"1",
";",
"// Reset locking flags",
"self",
".",
"__enableScrollX",
"=",
"!",
"isSingleTouch",
"&&",
"self",
".",
"options",
".",
"scrollingX",
";",
"self",
".",
"__enableScrollY",
"=",
"!",
"isSingleTouch",
"&&",
"self",
".",
"options",
".",
"scrollingY",
";",
"// Reset tracking flag",
"self",
".",
"__isTracking",
"=",
"true",
";",
"// Reset deceleration complete flag",
"self",
".",
"__didDecelerationComplete",
"=",
"false",
";",
"// Dragging starts directly with two fingers, otherwise lazy with an offset",
"self",
".",
"__isDragging",
"=",
"!",
"isSingleTouch",
";",
"// Some features are disabled in multi touch scenarios",
"self",
".",
"__isSingleTouch",
"=",
"isSingleTouch",
";",
"// Clearing data structure",
"self",
".",
"__positions",
"=",
"[",
"]",
";",
"}"
] |
Touch start handler for scrolling support
|
[
"Touch",
"start",
"handler",
"for",
"scrolling",
"support"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L6199-L6281
|
|
13,470
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
function(left, top, animate) {
var self = this;
if (!animate) {
self.el.scrollTop = top;
self.el.scrollLeft = left;
self.resize();
return;
}
var oldOverflowX = self.el.style.overflowX;
var oldOverflowY = self.el.style.overflowY;
clearTimeout(self.__scrollToCleanupTimeout);
self.__scrollToCleanupTimeout = setTimeout(function() {
self.el.style.overflowX = oldOverflowX;
self.el.style.overflowY = oldOverflowY;
}, 500);
self.el.style.overflowY = 'hidden';
self.el.style.overflowX = 'hidden';
animateScroll(top, left);
function animateScroll(Y, X) {
// scroll animation loop w/ easing
// credit https://gist.github.com/dezinezync/5487119
var start = Date.now(),
duration = 250, //milliseconds
fromY = self.el.scrollTop,
fromX = self.el.scrollLeft;
if (fromY === Y && fromX === X) {
self.el.style.overflowX = oldOverflowX;
self.el.style.overflowY = oldOverflowY;
self.resize();
return; /* Prevent scrolling to the Y point if already there */
}
// decelerating to zero velocity
function easeOutCubic(t) {
return (--t) * t * t + 1;
}
// scroll loop
function animateScrollStep() {
var currentTime = Date.now(),
time = Math.min(1, ((currentTime - start) / duration)),
// where .5 would be 50% of time on a linear scale easedT gives a
// fraction based on the easing method
easedT = easeOutCubic(time);
if (fromY != Y) {
self.el.scrollTop = parseInt((easedT * (Y - fromY)) + fromY, 10);
}
if (fromX != X) {
self.el.scrollLeft = parseInt((easedT * (X - fromX)) + fromX, 10);
}
if (time < 1) {
ionic.requestAnimationFrame(animateScrollStep);
} else {
// done
ionic.tap.removeClonedInputs(self.__container, self);
self.el.style.overflowX = oldOverflowX;
self.el.style.overflowY = oldOverflowY;
self.resize();
}
}
// start scroll loop
ionic.requestAnimationFrame(animateScrollStep);
}
}
|
javascript
|
function(left, top, animate) {
var self = this;
if (!animate) {
self.el.scrollTop = top;
self.el.scrollLeft = left;
self.resize();
return;
}
var oldOverflowX = self.el.style.overflowX;
var oldOverflowY = self.el.style.overflowY;
clearTimeout(self.__scrollToCleanupTimeout);
self.__scrollToCleanupTimeout = setTimeout(function() {
self.el.style.overflowX = oldOverflowX;
self.el.style.overflowY = oldOverflowY;
}, 500);
self.el.style.overflowY = 'hidden';
self.el.style.overflowX = 'hidden';
animateScroll(top, left);
function animateScroll(Y, X) {
// scroll animation loop w/ easing
// credit https://gist.github.com/dezinezync/5487119
var start = Date.now(),
duration = 250, //milliseconds
fromY = self.el.scrollTop,
fromX = self.el.scrollLeft;
if (fromY === Y && fromX === X) {
self.el.style.overflowX = oldOverflowX;
self.el.style.overflowY = oldOverflowY;
self.resize();
return; /* Prevent scrolling to the Y point if already there */
}
// decelerating to zero velocity
function easeOutCubic(t) {
return (--t) * t * t + 1;
}
// scroll loop
function animateScrollStep() {
var currentTime = Date.now(),
time = Math.min(1, ((currentTime - start) / duration)),
// where .5 would be 50% of time on a linear scale easedT gives a
// fraction based on the easing method
easedT = easeOutCubic(time);
if (fromY != Y) {
self.el.scrollTop = parseInt((easedT * (Y - fromY)) + fromY, 10);
}
if (fromX != X) {
self.el.scrollLeft = parseInt((easedT * (X - fromX)) + fromX, 10);
}
if (time < 1) {
ionic.requestAnimationFrame(animateScrollStep);
} else {
// done
ionic.tap.removeClonedInputs(self.__container, self);
self.el.style.overflowX = oldOverflowX;
self.el.style.overflowY = oldOverflowY;
self.resize();
}
}
// start scroll loop
ionic.requestAnimationFrame(animateScrollStep);
}
}
|
[
"function",
"(",
"left",
",",
"top",
",",
"animate",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"!",
"animate",
")",
"{",
"self",
".",
"el",
".",
"scrollTop",
"=",
"top",
";",
"self",
".",
"el",
".",
"scrollLeft",
"=",
"left",
";",
"self",
".",
"resize",
"(",
")",
";",
"return",
";",
"}",
"var",
"oldOverflowX",
"=",
"self",
".",
"el",
".",
"style",
".",
"overflowX",
";",
"var",
"oldOverflowY",
"=",
"self",
".",
"el",
".",
"style",
".",
"overflowY",
";",
"clearTimeout",
"(",
"self",
".",
"__scrollToCleanupTimeout",
")",
";",
"self",
".",
"__scrollToCleanupTimeout",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"self",
".",
"el",
".",
"style",
".",
"overflowX",
"=",
"oldOverflowX",
";",
"self",
".",
"el",
".",
"style",
".",
"overflowY",
"=",
"oldOverflowY",
";",
"}",
",",
"500",
")",
";",
"self",
".",
"el",
".",
"style",
".",
"overflowY",
"=",
"'hidden'",
";",
"self",
".",
"el",
".",
"style",
".",
"overflowX",
"=",
"'hidden'",
";",
"animateScroll",
"(",
"top",
",",
"left",
")",
";",
"function",
"animateScroll",
"(",
"Y",
",",
"X",
")",
"{",
"// scroll animation loop w/ easing",
"// credit https://gist.github.com/dezinezync/5487119",
"var",
"start",
"=",
"Date",
".",
"now",
"(",
")",
",",
"duration",
"=",
"250",
",",
"//milliseconds",
"fromY",
"=",
"self",
".",
"el",
".",
"scrollTop",
",",
"fromX",
"=",
"self",
".",
"el",
".",
"scrollLeft",
";",
"if",
"(",
"fromY",
"===",
"Y",
"&&",
"fromX",
"===",
"X",
")",
"{",
"self",
".",
"el",
".",
"style",
".",
"overflowX",
"=",
"oldOverflowX",
";",
"self",
".",
"el",
".",
"style",
".",
"overflowY",
"=",
"oldOverflowY",
";",
"self",
".",
"resize",
"(",
")",
";",
"return",
";",
"/* Prevent scrolling to the Y point if already there */",
"}",
"// decelerating to zero velocity",
"function",
"easeOutCubic",
"(",
"t",
")",
"{",
"return",
"(",
"--",
"t",
")",
"*",
"t",
"*",
"t",
"+",
"1",
";",
"}",
"// scroll loop",
"function",
"animateScrollStep",
"(",
")",
"{",
"var",
"currentTime",
"=",
"Date",
".",
"now",
"(",
")",
",",
"time",
"=",
"Math",
".",
"min",
"(",
"1",
",",
"(",
"(",
"currentTime",
"-",
"start",
")",
"/",
"duration",
")",
")",
",",
"// where .5 would be 50% of time on a linear scale easedT gives a",
"// fraction based on the easing method",
"easedT",
"=",
"easeOutCubic",
"(",
"time",
")",
";",
"if",
"(",
"fromY",
"!=",
"Y",
")",
"{",
"self",
".",
"el",
".",
"scrollTop",
"=",
"parseInt",
"(",
"(",
"easedT",
"*",
"(",
"Y",
"-",
"fromY",
")",
")",
"+",
"fromY",
",",
"10",
")",
";",
"}",
"if",
"(",
"fromX",
"!=",
"X",
")",
"{",
"self",
".",
"el",
".",
"scrollLeft",
"=",
"parseInt",
"(",
"(",
"easedT",
"*",
"(",
"X",
"-",
"fromX",
")",
")",
"+",
"fromX",
",",
"10",
")",
";",
"}",
"if",
"(",
"time",
"<",
"1",
")",
"{",
"ionic",
".",
"requestAnimationFrame",
"(",
"animateScrollStep",
")",
";",
"}",
"else",
"{",
"// done",
"ionic",
".",
"tap",
".",
"removeClonedInputs",
"(",
"self",
".",
"__container",
",",
"self",
")",
";",
"self",
".",
"el",
".",
"style",
".",
"overflowX",
"=",
"oldOverflowX",
";",
"self",
".",
"el",
".",
"style",
".",
"overflowY",
"=",
"oldOverflowY",
";",
"self",
".",
"resize",
"(",
")",
";",
"}",
"}",
"// start scroll loop",
"ionic",
".",
"requestAnimationFrame",
"(",
"animateScrollStep",
")",
";",
"}",
"}"
] |
Scrolls to the given position in px.
@param left {Number} Horizontal scroll position, keeps current if value is <code>null</code>
@param top {Number} Vertical scroll position, keeps current if value is <code>null</code>
@param animate {Boolean} Whether the scrolling should happen using an animation
|
[
"Scrolls",
"to",
"the",
"given",
"position",
"in",
"px",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L7204-L7277
|
|
13,471
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
function() {
this.el = this.listEl = this.scrollEl = this.scrollView = null;
// ensure no scrolls have been left frozen
if (this.isScrollFreeze) {
self.scrollView.freeze(false);
}
}
|
javascript
|
function() {
this.el = this.listEl = this.scrollEl = this.scrollView = null;
// ensure no scrolls have been left frozen
if (this.isScrollFreeze) {
self.scrollView.freeze(false);
}
}
|
[
"function",
"(",
")",
"{",
"this",
".",
"el",
"=",
"this",
".",
"listEl",
"=",
"this",
".",
"scrollEl",
"=",
"this",
".",
"scrollView",
"=",
"null",
";",
"// ensure no scrolls have been left frozen",
"if",
"(",
"this",
".",
"isScrollFreeze",
")",
"{",
"self",
".",
"scrollView",
".",
"freeze",
"(",
"false",
")",
";",
"}",
"}"
] |
Be sure to cleanup references.
|
[
"Be",
"sure",
"to",
"cleanup",
"references",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L7984-L7991
|
|
13,472
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
function(isInstant) {
if (this._lastDragOp) {
this._lastDragOp.clean && this._lastDragOp.clean(isInstant);
this._lastDragOp.deregister && this._lastDragOp.deregister();
this._lastDragOp = null;
}
}
|
javascript
|
function(isInstant) {
if (this._lastDragOp) {
this._lastDragOp.clean && this._lastDragOp.clean(isInstant);
this._lastDragOp.deregister && this._lastDragOp.deregister();
this._lastDragOp = null;
}
}
|
[
"function",
"(",
"isInstant",
")",
"{",
"if",
"(",
"this",
".",
"_lastDragOp",
")",
"{",
"this",
".",
"_lastDragOp",
".",
"clean",
"&&",
"this",
".",
"_lastDragOp",
".",
"clean",
"(",
"isInstant",
")",
";",
"this",
".",
"_lastDragOp",
".",
"deregister",
"&&",
"this",
".",
"_lastDragOp",
".",
"deregister",
"(",
")",
";",
"this",
".",
"_lastDragOp",
"=",
"null",
";",
"}",
"}"
] |
Clear any active drag effects on the list.
|
[
"Clear",
"any",
"active",
"drag",
"effects",
"on",
"the",
"list",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L8052-L8058
|
|
13,473
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
compilationGenerator
|
function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
var compiled;
if (eager) {
return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
}
return function lazyCompilation() {
if (!compiled) {
compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
// Null out all of these references in order to make them eligible for garbage collection
// since this is a potentially long lived closure
$compileNodes = transcludeFn = previousCompileContext = null;
}
return compiled.apply(this, arguments);
};
}
|
javascript
|
function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
var compiled;
if (eager) {
return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
}
return function lazyCompilation() {
if (!compiled) {
compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
// Null out all of these references in order to make them eligible for garbage collection
// since this is a potentially long lived closure
$compileNodes = transcludeFn = previousCompileContext = null;
}
return compiled.apply(this, arguments);
};
}
|
[
"function",
"compilationGenerator",
"(",
"eager",
",",
"$compileNodes",
",",
"transcludeFn",
",",
"maxPriority",
",",
"ignoreDirective",
",",
"previousCompileContext",
")",
"{",
"var",
"compiled",
";",
"if",
"(",
"eager",
")",
"{",
"return",
"compile",
"(",
"$compileNodes",
",",
"transcludeFn",
",",
"maxPriority",
",",
"ignoreDirective",
",",
"previousCompileContext",
")",
";",
"}",
"return",
"function",
"lazyCompilation",
"(",
")",
"{",
"if",
"(",
"!",
"compiled",
")",
"{",
"compiled",
"=",
"compile",
"(",
"$compileNodes",
",",
"transcludeFn",
",",
"maxPriority",
",",
"ignoreDirective",
",",
"previousCompileContext",
")",
";",
"// Null out all of these references in order to make them eligible for garbage collection",
"// since this is a potentially long lived closure",
"$compileNodes",
"=",
"transcludeFn",
"=",
"previousCompileContext",
"=",
"null",
";",
"}",
"return",
"compiled",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
";",
"}"
] |
A function generator that is used to support both eager and lazy compilation
linking function.
@param eager
@param $compileNodes
@param transcludeFn
@param maxPriority
@param ignoreDirective
@param previousCompileContext
@returns {Function}
|
[
"A",
"function",
"generator",
"that",
"is",
"used",
"to",
"support",
"both",
"eager",
"and",
"lazy",
"compilation",
"linking",
"function",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L21912-L21928
|
13,474
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
roundNumber
|
function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
var digits = parsedNumber.d;
var fractionLen = digits.length - parsedNumber.i;
// determine fractionSize if it is not specified; `+fractionSize` converts it to a number
fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
// The index of the digit to where rounding is to occur
var roundAt = fractionSize + parsedNumber.i;
var digit = digits[roundAt];
if (roundAt > 0) {
// Drop fractional digits beyond `roundAt`
digits.splice(Math.max(parsedNumber.i, roundAt));
// Set non-fractional digits beyond `roundAt` to 0
for (var j = roundAt; j < digits.length; j++) {
digits[j] = 0;
}
} else {
// We rounded to zero so reset the parsedNumber
fractionLen = Math.max(0, fractionLen);
parsedNumber.i = 1;
digits.length = Math.max(1, roundAt = fractionSize + 1);
digits[0] = 0;
for (var i = 1; i < roundAt; i++) digits[i] = 0;
}
if (digit >= 5) {
if (roundAt - 1 < 0) {
for (var k = 0; k > roundAt; k--) {
digits.unshift(0);
parsedNumber.i++;
}
digits.unshift(1);
parsedNumber.i++;
} else {
digits[roundAt - 1]++;
}
}
// Pad out with zeros to get the required fraction length
for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
// Do any carrying, e.g. a digit was rounded up to 10
var carry = digits.reduceRight(function(carry, d, i, digits) {
d = d + carry;
digits[i] = d % 10;
return Math.floor(d / 10);
}, 0);
if (carry) {
digits.unshift(carry);
parsedNumber.i++;
}
}
|
javascript
|
function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
var digits = parsedNumber.d;
var fractionLen = digits.length - parsedNumber.i;
// determine fractionSize if it is not specified; `+fractionSize` converts it to a number
fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
// The index of the digit to where rounding is to occur
var roundAt = fractionSize + parsedNumber.i;
var digit = digits[roundAt];
if (roundAt > 0) {
// Drop fractional digits beyond `roundAt`
digits.splice(Math.max(parsedNumber.i, roundAt));
// Set non-fractional digits beyond `roundAt` to 0
for (var j = roundAt; j < digits.length; j++) {
digits[j] = 0;
}
} else {
// We rounded to zero so reset the parsedNumber
fractionLen = Math.max(0, fractionLen);
parsedNumber.i = 1;
digits.length = Math.max(1, roundAt = fractionSize + 1);
digits[0] = 0;
for (var i = 1; i < roundAt; i++) digits[i] = 0;
}
if (digit >= 5) {
if (roundAt - 1 < 0) {
for (var k = 0; k > roundAt; k--) {
digits.unshift(0);
parsedNumber.i++;
}
digits.unshift(1);
parsedNumber.i++;
} else {
digits[roundAt - 1]++;
}
}
// Pad out with zeros to get the required fraction length
for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
// Do any carrying, e.g. a digit was rounded up to 10
var carry = digits.reduceRight(function(carry, d, i, digits) {
d = d + carry;
digits[i] = d % 10;
return Math.floor(d / 10);
}, 0);
if (carry) {
digits.unshift(carry);
parsedNumber.i++;
}
}
|
[
"function",
"roundNumber",
"(",
"parsedNumber",
",",
"fractionSize",
",",
"minFrac",
",",
"maxFrac",
")",
"{",
"var",
"digits",
"=",
"parsedNumber",
".",
"d",
";",
"var",
"fractionLen",
"=",
"digits",
".",
"length",
"-",
"parsedNumber",
".",
"i",
";",
"// determine fractionSize if it is not specified; `+fractionSize` converts it to a number",
"fractionSize",
"=",
"(",
"isUndefined",
"(",
"fractionSize",
")",
")",
"?",
"Math",
".",
"min",
"(",
"Math",
".",
"max",
"(",
"minFrac",
",",
"fractionLen",
")",
",",
"maxFrac",
")",
":",
"+",
"fractionSize",
";",
"// The index of the digit to where rounding is to occur",
"var",
"roundAt",
"=",
"fractionSize",
"+",
"parsedNumber",
".",
"i",
";",
"var",
"digit",
"=",
"digits",
"[",
"roundAt",
"]",
";",
"if",
"(",
"roundAt",
">",
"0",
")",
"{",
"// Drop fractional digits beyond `roundAt`",
"digits",
".",
"splice",
"(",
"Math",
".",
"max",
"(",
"parsedNumber",
".",
"i",
",",
"roundAt",
")",
")",
";",
"// Set non-fractional digits beyond `roundAt` to 0",
"for",
"(",
"var",
"j",
"=",
"roundAt",
";",
"j",
"<",
"digits",
".",
"length",
";",
"j",
"++",
")",
"{",
"digits",
"[",
"j",
"]",
"=",
"0",
";",
"}",
"}",
"else",
"{",
"// We rounded to zero so reset the parsedNumber",
"fractionLen",
"=",
"Math",
".",
"max",
"(",
"0",
",",
"fractionLen",
")",
";",
"parsedNumber",
".",
"i",
"=",
"1",
";",
"digits",
".",
"length",
"=",
"Math",
".",
"max",
"(",
"1",
",",
"roundAt",
"=",
"fractionSize",
"+",
"1",
")",
";",
"digits",
"[",
"0",
"]",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"roundAt",
";",
"i",
"++",
")",
"digits",
"[",
"i",
"]",
"=",
"0",
";",
"}",
"if",
"(",
"digit",
">=",
"5",
")",
"{",
"if",
"(",
"roundAt",
"-",
"1",
"<",
"0",
")",
"{",
"for",
"(",
"var",
"k",
"=",
"0",
";",
"k",
">",
"roundAt",
";",
"k",
"--",
")",
"{",
"digits",
".",
"unshift",
"(",
"0",
")",
";",
"parsedNumber",
".",
"i",
"++",
";",
"}",
"digits",
".",
"unshift",
"(",
"1",
")",
";",
"parsedNumber",
".",
"i",
"++",
";",
"}",
"else",
"{",
"digits",
"[",
"roundAt",
"-",
"1",
"]",
"++",
";",
"}",
"}",
"// Pad out with zeros to get the required fraction length",
"for",
"(",
";",
"fractionLen",
"<",
"Math",
".",
"max",
"(",
"0",
",",
"fractionSize",
")",
";",
"fractionLen",
"++",
")",
"digits",
".",
"push",
"(",
"0",
")",
";",
"// Do any carrying, e.g. a digit was rounded up to 10",
"var",
"carry",
"=",
"digits",
".",
"reduceRight",
"(",
"function",
"(",
"carry",
",",
"d",
",",
"i",
",",
"digits",
")",
"{",
"d",
"=",
"d",
"+",
"carry",
";",
"digits",
"[",
"i",
"]",
"=",
"d",
"%",
"10",
";",
"return",
"Math",
".",
"floor",
"(",
"d",
"/",
"10",
")",
";",
"}",
",",
"0",
")",
";",
"if",
"(",
"carry",
")",
"{",
"digits",
".",
"unshift",
"(",
"carry",
")",
";",
"parsedNumber",
".",
"i",
"++",
";",
"}",
"}"
] |
Round the parsed number to the specified number of decimal places
This function changed the parsedNumber in-place
|
[
"Round",
"the",
"parsed",
"number",
"to",
"the",
"specified",
"number",
"of",
"decimal",
"places",
"This",
"function",
"changed",
"the",
"parsedNumber",
"in",
"-",
"place"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L33195-L33250
|
13,475
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
function(scope, $element, attrs, ctrl, $transclude) {
var previousElement, previousScope;
scope.$watchCollection(attrs.ngAnimateSwap || attrs['for'], function(value) {
if (previousElement) {
$animate.leave(previousElement);
}
if (previousScope) {
previousScope.$destroy();
previousScope = null;
}
if (value || value === 0) {
previousScope = scope.$new();
$transclude(previousScope, function(element) {
previousElement = element;
$animate.enter(element, null, $element);
});
}
});
}
|
javascript
|
function(scope, $element, attrs, ctrl, $transclude) {
var previousElement, previousScope;
scope.$watchCollection(attrs.ngAnimateSwap || attrs['for'], function(value) {
if (previousElement) {
$animate.leave(previousElement);
}
if (previousScope) {
previousScope.$destroy();
previousScope = null;
}
if (value || value === 0) {
previousScope = scope.$new();
$transclude(previousScope, function(element) {
previousElement = element;
$animate.enter(element, null, $element);
});
}
});
}
|
[
"function",
"(",
"scope",
",",
"$element",
",",
"attrs",
",",
"ctrl",
",",
"$transclude",
")",
"{",
"var",
"previousElement",
",",
"previousScope",
";",
"scope",
".",
"$watchCollection",
"(",
"attrs",
".",
"ngAnimateSwap",
"||",
"attrs",
"[",
"'for'",
"]",
",",
"function",
"(",
"value",
")",
"{",
"if",
"(",
"previousElement",
")",
"{",
"$animate",
".",
"leave",
"(",
"previousElement",
")",
";",
"}",
"if",
"(",
"previousScope",
")",
"{",
"previousScope",
".",
"$destroy",
"(",
")",
";",
"previousScope",
"=",
"null",
";",
"}",
"if",
"(",
"value",
"||",
"value",
"===",
"0",
")",
"{",
"previousScope",
"=",
"scope",
".",
"$new",
"(",
")",
";",
"$transclude",
"(",
"previousScope",
",",
"function",
"(",
"element",
")",
"{",
"previousElement",
"=",
"element",
";",
"$animate",
".",
"enter",
"(",
"element",
",",
"null",
",",
"$element",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] |
we use 600 here to ensure that the directive is caught before others
|
[
"we",
"use",
"600",
"here",
"to",
"ensure",
"that",
"the",
"directive",
"is",
"caught",
"before",
"others"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L47433-L47451
|
|
13,476
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
run
|
function run() {
var template;
$ionicTemplateCache._runCount++;
hasRun = true;
// ignore if race condition already zeroed out array
if (toCache.length === 0) return;
var i = 0;
while (i < 4 && (template = toCache.pop())) {
// note that inline templates are ignored by this request
if (isString(template)) $http.get(template, { cache: $templateCache });
i++;
}
// only preload 3 templates a second
if (toCache.length) {
$timeout(run, 1000);
}
}
|
javascript
|
function run() {
var template;
$ionicTemplateCache._runCount++;
hasRun = true;
// ignore if race condition already zeroed out array
if (toCache.length === 0) return;
var i = 0;
while (i < 4 && (template = toCache.pop())) {
// note that inline templates are ignored by this request
if (isString(template)) $http.get(template, { cache: $templateCache });
i++;
}
// only preload 3 templates a second
if (toCache.length) {
$timeout(run, 1000);
}
}
|
[
"function",
"run",
"(",
")",
"{",
"var",
"template",
";",
"$ionicTemplateCache",
".",
"_runCount",
"++",
";",
"hasRun",
"=",
"true",
";",
"// ignore if race condition already zeroed out array",
"if",
"(",
"toCache",
".",
"length",
"===",
"0",
")",
"return",
";",
"var",
"i",
"=",
"0",
";",
"while",
"(",
"i",
"<",
"4",
"&&",
"(",
"template",
"=",
"toCache",
".",
"pop",
"(",
")",
")",
")",
"{",
"// note that inline templates are ignored by this request",
"if",
"(",
"isString",
"(",
"template",
")",
")",
"$http",
".",
"get",
"(",
"template",
",",
"{",
"cache",
":",
"$templateCache",
"}",
")",
";",
"i",
"++",
";",
"}",
"// only preload 3 templates a second",
"if",
"(",
"toCache",
".",
"length",
")",
"{",
"$timeout",
"(",
"run",
",",
"1000",
")",
";",
"}",
"}"
] |
run through methods - internal method
|
[
"run",
"through",
"methods",
"-",
"internal",
"method"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L57615-L57633
|
13,477
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
checkInfiniteBounds
|
function checkInfiniteBounds() {
if (self.isLoading) return;
var maxScroll = {};
if (self.jsScrolling) {
maxScroll = self.getJSMaxScroll();
var scrollValues = self.scrollView.getValues();
if ((maxScroll.left !== -1 && scrollValues.left >= maxScroll.left) ||
(maxScroll.top !== -1 && scrollValues.top >= maxScroll.top)) {
onInfinite();
}
} else {
maxScroll = self.getNativeMaxScroll();
if ((
maxScroll.left !== -1 &&
self.scrollEl.scrollLeft >= maxScroll.left - self.scrollEl.clientWidth
) || (
maxScroll.top !== -1 &&
self.scrollEl.scrollTop >= maxScroll.top - self.scrollEl.clientHeight
)) {
onInfinite();
}
}
}
|
javascript
|
function checkInfiniteBounds() {
if (self.isLoading) return;
var maxScroll = {};
if (self.jsScrolling) {
maxScroll = self.getJSMaxScroll();
var scrollValues = self.scrollView.getValues();
if ((maxScroll.left !== -1 && scrollValues.left >= maxScroll.left) ||
(maxScroll.top !== -1 && scrollValues.top >= maxScroll.top)) {
onInfinite();
}
} else {
maxScroll = self.getNativeMaxScroll();
if ((
maxScroll.left !== -1 &&
self.scrollEl.scrollLeft >= maxScroll.left - self.scrollEl.clientWidth
) || (
maxScroll.top !== -1 &&
self.scrollEl.scrollTop >= maxScroll.top - self.scrollEl.clientHeight
)) {
onInfinite();
}
}
}
|
[
"function",
"checkInfiniteBounds",
"(",
")",
"{",
"if",
"(",
"self",
".",
"isLoading",
")",
"return",
";",
"var",
"maxScroll",
"=",
"{",
"}",
";",
"if",
"(",
"self",
".",
"jsScrolling",
")",
"{",
"maxScroll",
"=",
"self",
".",
"getJSMaxScroll",
"(",
")",
";",
"var",
"scrollValues",
"=",
"self",
".",
"scrollView",
".",
"getValues",
"(",
")",
";",
"if",
"(",
"(",
"maxScroll",
".",
"left",
"!==",
"-",
"1",
"&&",
"scrollValues",
".",
"left",
">=",
"maxScroll",
".",
"left",
")",
"||",
"(",
"maxScroll",
".",
"top",
"!==",
"-",
"1",
"&&",
"scrollValues",
".",
"top",
">=",
"maxScroll",
".",
"top",
")",
")",
"{",
"onInfinite",
"(",
")",
";",
"}",
"}",
"else",
"{",
"maxScroll",
"=",
"self",
".",
"getNativeMaxScroll",
"(",
")",
";",
"if",
"(",
"(",
"maxScroll",
".",
"left",
"!==",
"-",
"1",
"&&",
"self",
".",
"scrollEl",
".",
"scrollLeft",
">=",
"maxScroll",
".",
"left",
"-",
"self",
".",
"scrollEl",
".",
"clientWidth",
")",
"||",
"(",
"maxScroll",
".",
"top",
"!==",
"-",
"1",
"&&",
"self",
".",
"scrollEl",
".",
"scrollTop",
">=",
"maxScroll",
".",
"top",
"-",
"self",
".",
"scrollEl",
".",
"clientHeight",
")",
")",
"{",
"onInfinite",
"(",
")",
";",
"}",
"}",
"}"
] |
check if we've scrolled far enough to trigger an infinite scroll
|
[
"check",
"if",
"we",
"ve",
"scrolled",
"far",
"enough",
"to",
"trigger",
"an",
"infinite",
"scroll"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L58934-L58957
|
13,478
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
calculateMaxValue
|
function calculateMaxValue(maximum) {
var distance = ($attrs.distance || '2.5%').trim();
var isPercent = distance.indexOf('%') !== -1;
return isPercent ?
maximum * (1 - parseFloat(distance) / 100) :
maximum - parseFloat(distance);
}
|
javascript
|
function calculateMaxValue(maximum) {
var distance = ($attrs.distance || '2.5%').trim();
var isPercent = distance.indexOf('%') !== -1;
return isPercent ?
maximum * (1 - parseFloat(distance) / 100) :
maximum - parseFloat(distance);
}
|
[
"function",
"calculateMaxValue",
"(",
"maximum",
")",
"{",
"var",
"distance",
"=",
"(",
"$attrs",
".",
"distance",
"||",
"'2.5%'",
")",
".",
"trim",
"(",
")",
";",
"var",
"isPercent",
"=",
"distance",
".",
"indexOf",
"(",
"'%'",
")",
"!==",
"-",
"1",
";",
"return",
"isPercent",
"?",
"maximum",
"*",
"(",
"1",
"-",
"parseFloat",
"(",
"distance",
")",
"/",
"100",
")",
":",
"maximum",
"-",
"parseFloat",
"(",
"distance",
")",
";",
"}"
] |
determine pixel refresh distance based on % or value
|
[
"determine",
"pixel",
"refresh",
"distance",
"based",
"on",
"%",
"or",
"value"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L58994-L59000
|
13,479
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
function(newWidth, newHeight) {
var requiresRefresh = self.dataLength && newWidth && newHeight &&
(newWidth !== self.width || newHeight !== self.height);
self.width = newWidth;
self.height = newHeight;
return !!requiresRefresh;
}
|
javascript
|
function(newWidth, newHeight) {
var requiresRefresh = self.dataLength && newWidth && newHeight &&
(newWidth !== self.width || newHeight !== self.height);
self.width = newWidth;
self.height = newHeight;
return !!requiresRefresh;
}
|
[
"function",
"(",
"newWidth",
",",
"newHeight",
")",
"{",
"var",
"requiresRefresh",
"=",
"self",
".",
"dataLength",
"&&",
"newWidth",
"&&",
"newHeight",
"&&",
"(",
"newWidth",
"!==",
"self",
".",
"width",
"||",
"newHeight",
"!==",
"self",
".",
"height",
")",
";",
"self",
".",
"width",
"=",
"newWidth",
";",
"self",
".",
"height",
"=",
"newHeight",
";",
"return",
"!",
"!",
"requiresRefresh",
";",
"}"
] |
A resize triggers a refresh only if we have data, the scrollView has size, and the size has changed.
|
[
"A",
"resize",
"triggers",
"a",
"refresh",
"only",
"if",
"we",
"have",
"data",
"the",
"scrollView",
"has",
"size",
"and",
"the",
"size",
"has",
"changed",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L62226-L62234
|
|
13,480
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/ionic1/www/lib/ionic/js/ionic.bundle.js
|
function(newData) {
var requiresRefresh = newData.length > 0 || newData.length < self.dataLength;
self.dataLength = newData.length;
return !!requiresRefresh;
}
|
javascript
|
function(newData) {
var requiresRefresh = newData.length > 0 || newData.length < self.dataLength;
self.dataLength = newData.length;
return !!requiresRefresh;
}
|
[
"function",
"(",
"newData",
")",
"{",
"var",
"requiresRefresh",
"=",
"newData",
".",
"length",
">",
"0",
"||",
"newData",
".",
"length",
"<",
"self",
".",
"dataLength",
";",
"self",
".",
"dataLength",
"=",
"newData",
".",
"length",
";",
"return",
"!",
"!",
"requiresRefresh",
";",
"}"
] |
A change in data only triggers a refresh if the data has length, or if the data's length is less than before.
|
[
"A",
"change",
"in",
"data",
"only",
"triggers",
"a",
"refresh",
"if",
"the",
"data",
"has",
"length",
"or",
"if",
"the",
"data",
"s",
"length",
"is",
"less",
"than",
"before",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/ionic1/www/lib/ionic/js/ionic.bundle.js#L62237-L62243
|
|
13,481
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-media-capture/src/windows/CaptureProxy.js
|
toggleElements
|
function toggleElements() {
// convert arguments to array
var args = Array.prototype.slice.call(arguments);
args.forEach(function(buttonId) {
var buttonEl = document.getElementById(buttonId);
if (buttonEl) {
var curDisplayStyle = buttonEl.style.display;
buttonEl.style.display = curDisplayStyle === 'none' ? 'block' : 'none';
}
});
}
|
javascript
|
function toggleElements() {
// convert arguments to array
var args = Array.prototype.slice.call(arguments);
args.forEach(function(buttonId) {
var buttonEl = document.getElementById(buttonId);
if (buttonEl) {
var curDisplayStyle = buttonEl.style.display;
buttonEl.style.display = curDisplayStyle === 'none' ? 'block' : 'none';
}
});
}
|
[
"function",
"toggleElements",
"(",
")",
"{",
"// convert arguments to array",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"args",
".",
"forEach",
"(",
"function",
"(",
"buttonId",
")",
"{",
"var",
"buttonEl",
"=",
"document",
".",
"getElementById",
"(",
"buttonId",
")",
";",
"if",
"(",
"buttonEl",
")",
"{",
"var",
"curDisplayStyle",
"=",
"buttonEl",
".",
"style",
".",
"display",
";",
"buttonEl",
".",
"style",
".",
"display",
"=",
"curDisplayStyle",
"===",
"'none'",
"?",
"'block'",
":",
"'none'",
";",
"}",
"}",
")",
";",
"}"
] |
Helper function that toggles visibility of DOM elements with provided ids
@param {String} variable number of elements' ids which visibility needs to be toggled
|
[
"Helper",
"function",
"that",
"toggles",
"visibility",
"of",
"DOM",
"elements",
"with",
"provided",
"ids"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-media-capture/src/windows/CaptureProxy.js#L50-L60
|
13,482
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-media-capture/src/windows/CaptureProxy.js
|
startCameraPreview
|
function startCameraPreview(takeCallback, errorCallback, selectCallback, retakeCallback) {
// try to select appropriate device for capture
// rear camera is preferred option
var expectedPanel = Windows.Devices.Enumeration.Panel.back;
Windows.Devices.Enumeration.DeviceInformation.findAllAsync(Windows.Devices.Enumeration.DeviceClass.videoCapture).done(function (devices) {
if (devices.length > 0) {
devices.forEach(function (currDev) {
if (currDev.enclosureLocation && currDev.enclosureLocation.panel && currDev.enclosureLocation.panel == expectedPanel) {
captureSettings.videoDeviceId = currDev.id;
}
});
capture.initializeAsync(captureSettings).done(function () {
// This is necessary since WP8.1 MediaCapture outputs video stream rotated 90 degrees CCW
// TODO: This can be not consistent across devices, need additional testing on various devices
// msdn.microsoft.com/en-us/library/windows/apps/hh452807.aspx
capture.setPreviewRotation(Windows.Media.Capture.VideoRotation.clockwise90Degrees);
capturePreview.msZoom = true;
capturePreview.src = URL.createObjectURL(capture);
capturePreview.play();
previewContainer.style.display = 'block';
// Bind events to controls
capturePreview.onclick = takeCallback;
document.getElementById('takePicture').onclick = takeCallback;
document.getElementById('cancelCapture').onclick = function () {
errorCallback(CaptureError.CAPTURE_NO_MEDIA_FILES);
};
document.getElementById('selectPicture').onclick = selectCallback;
document.getElementById('retakePicture').onclick = retakeCallback;
}, function (err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
} else {
// no appropriate devices found
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR);
}
});
}
|
javascript
|
function startCameraPreview(takeCallback, errorCallback, selectCallback, retakeCallback) {
// try to select appropriate device for capture
// rear camera is preferred option
var expectedPanel = Windows.Devices.Enumeration.Panel.back;
Windows.Devices.Enumeration.DeviceInformation.findAllAsync(Windows.Devices.Enumeration.DeviceClass.videoCapture).done(function (devices) {
if (devices.length > 0) {
devices.forEach(function (currDev) {
if (currDev.enclosureLocation && currDev.enclosureLocation.panel && currDev.enclosureLocation.panel == expectedPanel) {
captureSettings.videoDeviceId = currDev.id;
}
});
capture.initializeAsync(captureSettings).done(function () {
// This is necessary since WP8.1 MediaCapture outputs video stream rotated 90 degrees CCW
// TODO: This can be not consistent across devices, need additional testing on various devices
// msdn.microsoft.com/en-us/library/windows/apps/hh452807.aspx
capture.setPreviewRotation(Windows.Media.Capture.VideoRotation.clockwise90Degrees);
capturePreview.msZoom = true;
capturePreview.src = URL.createObjectURL(capture);
capturePreview.play();
previewContainer.style.display = 'block';
// Bind events to controls
capturePreview.onclick = takeCallback;
document.getElementById('takePicture').onclick = takeCallback;
document.getElementById('cancelCapture').onclick = function () {
errorCallback(CaptureError.CAPTURE_NO_MEDIA_FILES);
};
document.getElementById('selectPicture').onclick = selectCallback;
document.getElementById('retakePicture').onclick = retakeCallback;
}, function (err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
} else {
// no appropriate devices found
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR);
}
});
}
|
[
"function",
"startCameraPreview",
"(",
"takeCallback",
",",
"errorCallback",
",",
"selectCallback",
",",
"retakeCallback",
")",
"{",
"// try to select appropriate device for capture",
"// rear camera is preferred option",
"var",
"expectedPanel",
"=",
"Windows",
".",
"Devices",
".",
"Enumeration",
".",
"Panel",
".",
"back",
";",
"Windows",
".",
"Devices",
".",
"Enumeration",
".",
"DeviceInformation",
".",
"findAllAsync",
"(",
"Windows",
".",
"Devices",
".",
"Enumeration",
".",
"DeviceClass",
".",
"videoCapture",
")",
".",
"done",
"(",
"function",
"(",
"devices",
")",
"{",
"if",
"(",
"devices",
".",
"length",
">",
"0",
")",
"{",
"devices",
".",
"forEach",
"(",
"function",
"(",
"currDev",
")",
"{",
"if",
"(",
"currDev",
".",
"enclosureLocation",
"&&",
"currDev",
".",
"enclosureLocation",
".",
"panel",
"&&",
"currDev",
".",
"enclosureLocation",
".",
"panel",
"==",
"expectedPanel",
")",
"{",
"captureSettings",
".",
"videoDeviceId",
"=",
"currDev",
".",
"id",
";",
"}",
"}",
")",
";",
"capture",
".",
"initializeAsync",
"(",
"captureSettings",
")",
".",
"done",
"(",
"function",
"(",
")",
"{",
"// This is necessary since WP8.1 MediaCapture outputs video stream rotated 90 degrees CCW",
"// TODO: This can be not consistent across devices, need additional testing on various devices",
"// msdn.microsoft.com/en-us/library/windows/apps/hh452807.aspx",
"capture",
".",
"setPreviewRotation",
"(",
"Windows",
".",
"Media",
".",
"Capture",
".",
"VideoRotation",
".",
"clockwise90Degrees",
")",
";",
"capturePreview",
".",
"msZoom",
"=",
"true",
";",
"capturePreview",
".",
"src",
"=",
"URL",
".",
"createObjectURL",
"(",
"capture",
")",
";",
"capturePreview",
".",
"play",
"(",
")",
";",
"previewContainer",
".",
"style",
".",
"display",
"=",
"'block'",
";",
"// Bind events to controls",
"capturePreview",
".",
"onclick",
"=",
"takeCallback",
";",
"document",
".",
"getElementById",
"(",
"'takePicture'",
")",
".",
"onclick",
"=",
"takeCallback",
";",
"document",
".",
"getElementById",
"(",
"'cancelCapture'",
")",
".",
"onclick",
"=",
"function",
"(",
")",
"{",
"errorCallback",
"(",
"CaptureError",
".",
"CAPTURE_NO_MEDIA_FILES",
")",
";",
"}",
";",
"document",
".",
"getElementById",
"(",
"'selectPicture'",
")",
".",
"onclick",
"=",
"selectCallback",
";",
"document",
".",
"getElementById",
"(",
"'retakePicture'",
")",
".",
"onclick",
"=",
"retakeCallback",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"destroyCameraPreview",
"(",
")",
";",
"errorCallback",
"(",
"CaptureError",
".",
"CAPTURE_INTERNAL_ERR",
",",
"err",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"// no appropriate devices found",
"destroyCameraPreview",
"(",
")",
";",
"errorCallback",
"(",
"CaptureError",
".",
"CAPTURE_INTERNAL_ERR",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Starts camera preview and binds provided callbacks to controls
@param {function} takeCallback Callback for Take button
@param {function} errorCallback Callback for Cancel button + default error callback
@param {function} selectCallback Callback for Select button
@param {function} retakeCallback Callback for Retake button
|
[
"Starts",
"camera",
"preview",
"and",
"binds",
"provided",
"callbacks",
"to",
"controls"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-media-capture/src/windows/CaptureProxy.js#L102-L144
|
13,483
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-media-capture/src/windows/CaptureProxy.js
|
destroyCameraPreview
|
function destroyCameraPreview() {
capturePreview.pause();
capturePreview.src = null;
if (previewContainer) {
document.body.removeChild(previewContainer);
}
if (capture) {
capture.stopRecordAsync();
capture = null;
}
}
|
javascript
|
function destroyCameraPreview() {
capturePreview.pause();
capturePreview.src = null;
if (previewContainer) {
document.body.removeChild(previewContainer);
}
if (capture) {
capture.stopRecordAsync();
capture = null;
}
}
|
[
"function",
"destroyCameraPreview",
"(",
")",
"{",
"capturePreview",
".",
"pause",
"(",
")",
";",
"capturePreview",
".",
"src",
"=",
"null",
";",
"if",
"(",
"previewContainer",
")",
"{",
"document",
".",
"body",
".",
"removeChild",
"(",
"previewContainer",
")",
";",
"}",
"if",
"(",
"capture",
")",
"{",
"capture",
".",
"stopRecordAsync",
"(",
")",
";",
"capture",
"=",
"null",
";",
"}",
"}"
] |
Destroys camera preview, removes all elements created
|
[
"Destroys",
"camera",
"preview",
"removes",
"all",
"elements",
"created"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-media-capture/src/windows/CaptureProxy.js#L149-L159
|
13,484
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-media-capture/src/windows/CaptureProxy.js
|
function (successCallback, errorCallback) {
try {
createCameraUI();
startCameraPreview(function () {
// This callback called twice: whem video capture started and when it ended
// so we need to check capture status
if (!captureStarted) {
// remove cancel button and rename 'Take' button to 'Stop'
toggleElements('cancelCapture');
document.getElementById('takePicture').text = 'Stop';
var encodingProperties = Windows.Media.MediaProperties.MediaEncodingProfile.createMp4(Windows.Media.MediaProperties.VideoEncodingQuality.auto),
generateUniqueCollisionOption = Windows.Storage.CreationCollisionOption.generateUniqueName,
localFolder = Windows.Storage.ApplicationData.current.localFolder;
localFolder.createFileAsync("cameraCaptureVideo.mp4", generateUniqueCollisionOption).done(function(capturedFile) {
capture.startRecordToStorageFileAsync(encodingProperties, capturedFile).done(function() {
capturedVideoFile = capturedFile;
captureStarted = true;
}, function(err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
}, function(err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
} else {
capture.stopRecordAsync().done(function () {
destroyCameraPreview();
successCallback(capturedVideoFile);
});
}
}, errorCallback);
} catch (ex) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, ex);
}
}
|
javascript
|
function (successCallback, errorCallback) {
try {
createCameraUI();
startCameraPreview(function () {
// This callback called twice: whem video capture started and when it ended
// so we need to check capture status
if (!captureStarted) {
// remove cancel button and rename 'Take' button to 'Stop'
toggleElements('cancelCapture');
document.getElementById('takePicture').text = 'Stop';
var encodingProperties = Windows.Media.MediaProperties.MediaEncodingProfile.createMp4(Windows.Media.MediaProperties.VideoEncodingQuality.auto),
generateUniqueCollisionOption = Windows.Storage.CreationCollisionOption.generateUniqueName,
localFolder = Windows.Storage.ApplicationData.current.localFolder;
localFolder.createFileAsync("cameraCaptureVideo.mp4", generateUniqueCollisionOption).done(function(capturedFile) {
capture.startRecordToStorageFileAsync(encodingProperties, capturedFile).done(function() {
capturedVideoFile = capturedFile;
captureStarted = true;
}, function(err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
}, function(err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
} else {
capture.stopRecordAsync().done(function () {
destroyCameraPreview();
successCallback(capturedVideoFile);
});
}
}, errorCallback);
} catch (ex) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, ex);
}
}
|
[
"function",
"(",
"successCallback",
",",
"errorCallback",
")",
"{",
"try",
"{",
"createCameraUI",
"(",
")",
";",
"startCameraPreview",
"(",
"function",
"(",
")",
"{",
"// This callback called twice: whem video capture started and when it ended",
"// so we need to check capture status",
"if",
"(",
"!",
"captureStarted",
")",
"{",
"// remove cancel button and rename 'Take' button to 'Stop'",
"toggleElements",
"(",
"'cancelCapture'",
")",
";",
"document",
".",
"getElementById",
"(",
"'takePicture'",
")",
".",
"text",
"=",
"'Stop'",
";",
"var",
"encodingProperties",
"=",
"Windows",
".",
"Media",
".",
"MediaProperties",
".",
"MediaEncodingProfile",
".",
"createMp4",
"(",
"Windows",
".",
"Media",
".",
"MediaProperties",
".",
"VideoEncodingQuality",
".",
"auto",
")",
",",
"generateUniqueCollisionOption",
"=",
"Windows",
".",
"Storage",
".",
"CreationCollisionOption",
".",
"generateUniqueName",
",",
"localFolder",
"=",
"Windows",
".",
"Storage",
".",
"ApplicationData",
".",
"current",
".",
"localFolder",
";",
"localFolder",
".",
"createFileAsync",
"(",
"\"cameraCaptureVideo.mp4\"",
",",
"generateUniqueCollisionOption",
")",
".",
"done",
"(",
"function",
"(",
"capturedFile",
")",
"{",
"capture",
".",
"startRecordToStorageFileAsync",
"(",
"encodingProperties",
",",
"capturedFile",
")",
".",
"done",
"(",
"function",
"(",
")",
"{",
"capturedVideoFile",
"=",
"capturedFile",
";",
"captureStarted",
"=",
"true",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"destroyCameraPreview",
"(",
")",
";",
"errorCallback",
"(",
"CaptureError",
".",
"CAPTURE_INTERNAL_ERR",
",",
"err",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"destroyCameraPreview",
"(",
")",
";",
"errorCallback",
"(",
"CaptureError",
".",
"CAPTURE_INTERNAL_ERR",
",",
"err",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"capture",
".",
"stopRecordAsync",
"(",
")",
".",
"done",
"(",
"function",
"(",
")",
"{",
"destroyCameraPreview",
"(",
")",
";",
"successCallback",
"(",
"capturedVideoFile",
")",
";",
"}",
")",
";",
"}",
"}",
",",
"errorCallback",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"destroyCameraPreview",
"(",
")",
";",
"errorCallback",
"(",
"CaptureError",
".",
"CAPTURE_INTERNAL_ERR",
",",
"ex",
")",
";",
"}",
"}"
] |
Initiate video capture using MediaCapture class
@param {function} successCallback Called, when user clicked on preview, with captured file object
@param {function} errorCallback Called on any error
|
[
"Initiate",
"video",
"capture",
"using",
"MediaCapture",
"class"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-media-capture/src/windows/CaptureProxy.js#L167-L205
|
|
13,485
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-media-capture/src/windows/CaptureProxy.js
|
function (successCallback, errorCallback) {
try {
createCameraUI();
startCameraPreview(
// Callback for Take button - captures intermediate image file.
function () {
var encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createJpeg(),
overwriteCollisionOption = Windows.Storage.CreationCollisionOption.replaceExisting,
tempFolder = Windows.Storage.ApplicationData.current.temporaryFolder;
tempFolder.createFileAsync("cameraCaptureImage.jpg", overwriteCollisionOption).done(function (capturedFile) {
capture.capturePhotoToStorageFileAsync(encodingProperties, capturedFile).done(function () {
// store intermediate result in object's global variable
capturedPictureFile = capturedFile;
// show pre-captured image and toggle visibility of all buttons
previewContainer.style.backgroundImage = 'url("' + 'ms-appdata:///temp/' + capturedFile.name + '")';
toggleElements('capturePreview', 'takePicture', 'cancelCapture', 'selectPicture', 'retakePicture');
}, function (err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
}, function (err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
},
// error + cancel callback
function (err) {
destroyCameraPreview();
errorCallback(err);
},
// Callback for Select button - copies intermediate file into persistent application's storage
function () {
var generateUniqueCollisionOption = Windows.Storage.CreationCollisionOption.generateUniqueName,
localFolder = Windows.Storage.ApplicationData.current.localFolder;
capturedPictureFile.copyAsync(localFolder, capturedPictureFile.name, generateUniqueCollisionOption).done(function (copiedFile) {
destroyCameraPreview();
successCallback(copiedFile);
}, function(err) {
destroyCameraPreview();
errorCallback(err);
});
},
// Callback for retake button - just toggles visibility of necessary elements
function () {
toggleElements('capturePreview', 'takePicture', 'cancelCapture', 'selectPicture', 'retakePicture');
}
);
} catch (ex) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, ex);
}
}
|
javascript
|
function (successCallback, errorCallback) {
try {
createCameraUI();
startCameraPreview(
// Callback for Take button - captures intermediate image file.
function () {
var encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createJpeg(),
overwriteCollisionOption = Windows.Storage.CreationCollisionOption.replaceExisting,
tempFolder = Windows.Storage.ApplicationData.current.temporaryFolder;
tempFolder.createFileAsync("cameraCaptureImage.jpg", overwriteCollisionOption).done(function (capturedFile) {
capture.capturePhotoToStorageFileAsync(encodingProperties, capturedFile).done(function () {
// store intermediate result in object's global variable
capturedPictureFile = capturedFile;
// show pre-captured image and toggle visibility of all buttons
previewContainer.style.backgroundImage = 'url("' + 'ms-appdata:///temp/' + capturedFile.name + '")';
toggleElements('capturePreview', 'takePicture', 'cancelCapture', 'selectPicture', 'retakePicture');
}, function (err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
}, function (err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
},
// error + cancel callback
function (err) {
destroyCameraPreview();
errorCallback(err);
},
// Callback for Select button - copies intermediate file into persistent application's storage
function () {
var generateUniqueCollisionOption = Windows.Storage.CreationCollisionOption.generateUniqueName,
localFolder = Windows.Storage.ApplicationData.current.localFolder;
capturedPictureFile.copyAsync(localFolder, capturedPictureFile.name, generateUniqueCollisionOption).done(function (copiedFile) {
destroyCameraPreview();
successCallback(copiedFile);
}, function(err) {
destroyCameraPreview();
errorCallback(err);
});
},
// Callback for retake button - just toggles visibility of necessary elements
function () {
toggleElements('capturePreview', 'takePicture', 'cancelCapture', 'selectPicture', 'retakePicture');
}
);
} catch (ex) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, ex);
}
}
|
[
"function",
"(",
"successCallback",
",",
"errorCallback",
")",
"{",
"try",
"{",
"createCameraUI",
"(",
")",
";",
"startCameraPreview",
"(",
"// Callback for Take button - captures intermediate image file.",
"function",
"(",
")",
"{",
"var",
"encodingProperties",
"=",
"Windows",
".",
"Media",
".",
"MediaProperties",
".",
"ImageEncodingProperties",
".",
"createJpeg",
"(",
")",
",",
"overwriteCollisionOption",
"=",
"Windows",
".",
"Storage",
".",
"CreationCollisionOption",
".",
"replaceExisting",
",",
"tempFolder",
"=",
"Windows",
".",
"Storage",
".",
"ApplicationData",
".",
"current",
".",
"temporaryFolder",
";",
"tempFolder",
".",
"createFileAsync",
"(",
"\"cameraCaptureImage.jpg\"",
",",
"overwriteCollisionOption",
")",
".",
"done",
"(",
"function",
"(",
"capturedFile",
")",
"{",
"capture",
".",
"capturePhotoToStorageFileAsync",
"(",
"encodingProperties",
",",
"capturedFile",
")",
".",
"done",
"(",
"function",
"(",
")",
"{",
"// store intermediate result in object's global variable",
"capturedPictureFile",
"=",
"capturedFile",
";",
"// show pre-captured image and toggle visibility of all buttons",
"previewContainer",
".",
"style",
".",
"backgroundImage",
"=",
"'url(\"'",
"+",
"'ms-appdata:///temp/'",
"+",
"capturedFile",
".",
"name",
"+",
"'\")'",
";",
"toggleElements",
"(",
"'capturePreview'",
",",
"'takePicture'",
",",
"'cancelCapture'",
",",
"'selectPicture'",
",",
"'retakePicture'",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"destroyCameraPreview",
"(",
")",
";",
"errorCallback",
"(",
"CaptureError",
".",
"CAPTURE_INTERNAL_ERR",
",",
"err",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"destroyCameraPreview",
"(",
")",
";",
"errorCallback",
"(",
"CaptureError",
".",
"CAPTURE_INTERNAL_ERR",
",",
"err",
")",
";",
"}",
")",
";",
"}",
",",
"// error + cancel callback",
"function",
"(",
"err",
")",
"{",
"destroyCameraPreview",
"(",
")",
";",
"errorCallback",
"(",
"err",
")",
";",
"}",
",",
"// Callback for Select button - copies intermediate file into persistent application's storage",
"function",
"(",
")",
"{",
"var",
"generateUniqueCollisionOption",
"=",
"Windows",
".",
"Storage",
".",
"CreationCollisionOption",
".",
"generateUniqueName",
",",
"localFolder",
"=",
"Windows",
".",
"Storage",
".",
"ApplicationData",
".",
"current",
".",
"localFolder",
";",
"capturedPictureFile",
".",
"copyAsync",
"(",
"localFolder",
",",
"capturedPictureFile",
".",
"name",
",",
"generateUniqueCollisionOption",
")",
".",
"done",
"(",
"function",
"(",
"copiedFile",
")",
"{",
"destroyCameraPreview",
"(",
")",
";",
"successCallback",
"(",
"copiedFile",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"destroyCameraPreview",
"(",
")",
";",
"errorCallback",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
",",
"// Callback for retake button - just toggles visibility of necessary elements",
"function",
"(",
")",
"{",
"toggleElements",
"(",
"'capturePreview'",
",",
"'takePicture'",
",",
"'cancelCapture'",
",",
"'selectPicture'",
",",
"'retakePicture'",
")",
";",
"}",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"destroyCameraPreview",
"(",
")",
";",
"errorCallback",
"(",
"CaptureError",
".",
"CAPTURE_INTERNAL_ERR",
",",
"ex",
")",
";",
"}",
"}"
] |
Initiate image capture using MediaCapture class
@param {function} successCallback Called, when user clicked on preview, with captured file object
@param {function} errorCallback Called on any error
|
[
"Initiate",
"image",
"capture",
"using",
"MediaCapture",
"class"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-media-capture/src/windows/CaptureProxy.js#L212-L265
|
|
13,486
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-media-capture/src/windows/CaptureProxy.js
|
function () {
var encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createJpeg(),
overwriteCollisionOption = Windows.Storage.CreationCollisionOption.replaceExisting,
tempFolder = Windows.Storage.ApplicationData.current.temporaryFolder;
tempFolder.createFileAsync("cameraCaptureImage.jpg", overwriteCollisionOption).done(function (capturedFile) {
capture.capturePhotoToStorageFileAsync(encodingProperties, capturedFile).done(function () {
// store intermediate result in object's global variable
capturedPictureFile = capturedFile;
// show pre-captured image and toggle visibility of all buttons
previewContainer.style.backgroundImage = 'url("' + 'ms-appdata:///temp/' + capturedFile.name + '")';
toggleElements('capturePreview', 'takePicture', 'cancelCapture', 'selectPicture', 'retakePicture');
}, function (err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
}, function (err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
}
|
javascript
|
function () {
var encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createJpeg(),
overwriteCollisionOption = Windows.Storage.CreationCollisionOption.replaceExisting,
tempFolder = Windows.Storage.ApplicationData.current.temporaryFolder;
tempFolder.createFileAsync("cameraCaptureImage.jpg", overwriteCollisionOption).done(function (capturedFile) {
capture.capturePhotoToStorageFileAsync(encodingProperties, capturedFile).done(function () {
// store intermediate result in object's global variable
capturedPictureFile = capturedFile;
// show pre-captured image and toggle visibility of all buttons
previewContainer.style.backgroundImage = 'url("' + 'ms-appdata:///temp/' + capturedFile.name + '")';
toggleElements('capturePreview', 'takePicture', 'cancelCapture', 'selectPicture', 'retakePicture');
}, function (err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
}, function (err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
}
|
[
"function",
"(",
")",
"{",
"var",
"encodingProperties",
"=",
"Windows",
".",
"Media",
".",
"MediaProperties",
".",
"ImageEncodingProperties",
".",
"createJpeg",
"(",
")",
",",
"overwriteCollisionOption",
"=",
"Windows",
".",
"Storage",
".",
"CreationCollisionOption",
".",
"replaceExisting",
",",
"tempFolder",
"=",
"Windows",
".",
"Storage",
".",
"ApplicationData",
".",
"current",
".",
"temporaryFolder",
";",
"tempFolder",
".",
"createFileAsync",
"(",
"\"cameraCaptureImage.jpg\"",
",",
"overwriteCollisionOption",
")",
".",
"done",
"(",
"function",
"(",
"capturedFile",
")",
"{",
"capture",
".",
"capturePhotoToStorageFileAsync",
"(",
"encodingProperties",
",",
"capturedFile",
")",
".",
"done",
"(",
"function",
"(",
")",
"{",
"// store intermediate result in object's global variable",
"capturedPictureFile",
"=",
"capturedFile",
";",
"// show pre-captured image and toggle visibility of all buttons",
"previewContainer",
".",
"style",
".",
"backgroundImage",
"=",
"'url(\"'",
"+",
"'ms-appdata:///temp/'",
"+",
"capturedFile",
".",
"name",
"+",
"'\")'",
";",
"toggleElements",
"(",
"'capturePreview'",
",",
"'takePicture'",
",",
"'cancelCapture'",
",",
"'selectPicture'",
",",
"'retakePicture'",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"destroyCameraPreview",
"(",
")",
";",
"errorCallback",
"(",
"CaptureError",
".",
"CAPTURE_INTERNAL_ERR",
",",
"err",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"destroyCameraPreview",
"(",
")",
";",
"errorCallback",
"(",
"CaptureError",
".",
"CAPTURE_INTERNAL_ERR",
",",
"err",
")",
";",
"}",
")",
";",
"}"
] |
Callback for Take button - captures intermediate image file.
|
[
"Callback",
"for",
"Take",
"button",
"-",
"captures",
"intermediate",
"image",
"file",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-media-capture/src/windows/CaptureProxy.js#L217-L237
|
|
13,487
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-media-capture/src/windows/CaptureProxy.js
|
function () {
var generateUniqueCollisionOption = Windows.Storage.CreationCollisionOption.generateUniqueName,
localFolder = Windows.Storage.ApplicationData.current.localFolder;
capturedPictureFile.copyAsync(localFolder, capturedPictureFile.name, generateUniqueCollisionOption).done(function (copiedFile) {
destroyCameraPreview();
successCallback(copiedFile);
}, function(err) {
destroyCameraPreview();
errorCallback(err);
});
}
|
javascript
|
function () {
var generateUniqueCollisionOption = Windows.Storage.CreationCollisionOption.generateUniqueName,
localFolder = Windows.Storage.ApplicationData.current.localFolder;
capturedPictureFile.copyAsync(localFolder, capturedPictureFile.name, generateUniqueCollisionOption).done(function (copiedFile) {
destroyCameraPreview();
successCallback(copiedFile);
}, function(err) {
destroyCameraPreview();
errorCallback(err);
});
}
|
[
"function",
"(",
")",
"{",
"var",
"generateUniqueCollisionOption",
"=",
"Windows",
".",
"Storage",
".",
"CreationCollisionOption",
".",
"generateUniqueName",
",",
"localFolder",
"=",
"Windows",
".",
"Storage",
".",
"ApplicationData",
".",
"current",
".",
"localFolder",
";",
"capturedPictureFile",
".",
"copyAsync",
"(",
"localFolder",
",",
"capturedPictureFile",
".",
"name",
",",
"generateUniqueCollisionOption",
")",
".",
"done",
"(",
"function",
"(",
"copiedFile",
")",
"{",
"destroyCameraPreview",
"(",
")",
";",
"successCallback",
"(",
"copiedFile",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"destroyCameraPreview",
"(",
")",
";",
"errorCallback",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
] |
Callback for Select button - copies intermediate file into persistent application's storage
|
[
"Callback",
"for",
"Select",
"button",
"-",
"copies",
"intermediate",
"file",
"into",
"persistent",
"application",
"s",
"storage"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-media-capture/src/windows/CaptureProxy.js#L244-L255
|
|
13,488
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/hooks/beforePrepare.js
|
run
|
function run(context) {
const preferences = configPreferences.read(context);
const platforms = context.opts.cordova.platforms;
platforms.forEach(platform => {
if (platform === IOS) {
iosPlist.addBranchSettings(preferences);
iosCapabilities.enableAssociatedDomains(preferences);
iosAssociatedDomains.addAssociatedDomains(preferences);
}
});
}
|
javascript
|
function run(context) {
const preferences = configPreferences.read(context);
const platforms = context.opts.cordova.platforms;
platforms.forEach(platform => {
if (platform === IOS) {
iosPlist.addBranchSettings(preferences);
iosCapabilities.enableAssociatedDomains(preferences);
iosAssociatedDomains.addAssociatedDomains(preferences);
}
});
}
|
[
"function",
"run",
"(",
"context",
")",
"{",
"const",
"preferences",
"=",
"configPreferences",
".",
"read",
"(",
"context",
")",
";",
"const",
"platforms",
"=",
"context",
".",
"opts",
".",
"cordova",
".",
"platforms",
";",
"platforms",
".",
"forEach",
"(",
"platform",
"=>",
"{",
"if",
"(",
"platform",
"===",
"IOS",
")",
"{",
"iosPlist",
".",
"addBranchSettings",
"(",
"preferences",
")",
";",
"iosCapabilities",
".",
"enableAssociatedDomains",
"(",
"preferences",
")",
";",
"iosAssociatedDomains",
".",
"addAssociatedDomains",
"(",
"preferences",
")",
";",
"}",
"}",
")",
";",
"}"
] |
builds before platform config
|
[
"builds",
"before",
"platform",
"config"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/hooks/beforePrepare.js#L14-L25
|
13,489
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/android/updateAndroidManifest.js
|
writePreferences
|
function writePreferences(context, preferences) {
// read manifest
const manifest = getManifest(context);
// update manifest
manifest.file = updateBranchMetaData(manifest.file, preferences);
manifest.file = updateBranchReferrerTracking(manifest.file);
manifest.file = updateLaunchOptionToSingleTask(
manifest.file,
manifest.mainActivityIndex
);
manifest.file = updateBranchURIScheme(
manifest.file,
manifest.mainActivityIndex,
preferences
);
manifest.file = updateBranchAppLinks(
manifest.file,
manifest.mainActivityIndex,
preferences,
manifest.targetSdk
);
// save manifest
xmlHelper.writeJsonAsXml(manifest.path, manifest.file);
}
|
javascript
|
function writePreferences(context, preferences) {
// read manifest
const manifest = getManifest(context);
// update manifest
manifest.file = updateBranchMetaData(manifest.file, preferences);
manifest.file = updateBranchReferrerTracking(manifest.file);
manifest.file = updateLaunchOptionToSingleTask(
manifest.file,
manifest.mainActivityIndex
);
manifest.file = updateBranchURIScheme(
manifest.file,
manifest.mainActivityIndex,
preferences
);
manifest.file = updateBranchAppLinks(
manifest.file,
manifest.mainActivityIndex,
preferences,
manifest.targetSdk
);
// save manifest
xmlHelper.writeJsonAsXml(manifest.path, manifest.file);
}
|
[
"function",
"writePreferences",
"(",
"context",
",",
"preferences",
")",
"{",
"// read manifest",
"const",
"manifest",
"=",
"getManifest",
"(",
"context",
")",
";",
"// update manifest",
"manifest",
".",
"file",
"=",
"updateBranchMetaData",
"(",
"manifest",
".",
"file",
",",
"preferences",
")",
";",
"manifest",
".",
"file",
"=",
"updateBranchReferrerTracking",
"(",
"manifest",
".",
"file",
")",
";",
"manifest",
".",
"file",
"=",
"updateLaunchOptionToSingleTask",
"(",
"manifest",
".",
"file",
",",
"manifest",
".",
"mainActivityIndex",
")",
";",
"manifest",
".",
"file",
"=",
"updateBranchURIScheme",
"(",
"manifest",
".",
"file",
",",
"manifest",
".",
"mainActivityIndex",
",",
"preferences",
")",
";",
"manifest",
".",
"file",
"=",
"updateBranchAppLinks",
"(",
"manifest",
".",
"file",
",",
"manifest",
".",
"mainActivityIndex",
",",
"preferences",
",",
"manifest",
".",
"targetSdk",
")",
";",
"// save manifest",
"xmlHelper",
".",
"writeJsonAsXml",
"(",
"manifest",
".",
"path",
",",
"manifest",
".",
"file",
")",
";",
"}"
] |
injects config.xml preferences into AndroidManifest.xml file.
|
[
"injects",
"config",
".",
"xml",
"preferences",
"into",
"AndroidManifest",
".",
"xml",
"file",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/android/updateAndroidManifest.js#L13-L38
|
13,490
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/android/updateAndroidManifest.js
|
getManifest
|
function getManifest(context) {
let pathToManifest;
let manifest;
try {
// cordova platform add android@6.0.0
pathToManifest = path.join(
context.opts.projectRoot,
"platforms",
"android",
"AndroidManifest.xml"
);
manifest = xmlHelper.readXmlAsJson(pathToManifest);
} catch (e) {
try {
// cordova platform add android@7.0.0
pathToManifest = path.join(
context.opts.projectRoot,
"platforms",
"android",
"app",
"src",
"main",
"AndroidManifest.xml"
);
manifest = xmlHelper.readXmlAsJson(pathToManifest);
} catch (e) {
throw new Error(`BRANCH SDK: Cannot read AndroidManfiest.xml ${e}`);
}
}
const mainActivityIndex = getMainLaunchActivityIndex(
manifest.manifest.application[0].activity
);
const targetSdk =
manifest.manifest["uses-sdk"][0].$["android:targetSdkVersion"];
return {
file: manifest,
path: pathToManifest,
mainActivityIndex: mainActivityIndex,
targetSdk: targetSdk
};
}
|
javascript
|
function getManifest(context) {
let pathToManifest;
let manifest;
try {
// cordova platform add android@6.0.0
pathToManifest = path.join(
context.opts.projectRoot,
"platforms",
"android",
"AndroidManifest.xml"
);
manifest = xmlHelper.readXmlAsJson(pathToManifest);
} catch (e) {
try {
// cordova platform add android@7.0.0
pathToManifest = path.join(
context.opts.projectRoot,
"platforms",
"android",
"app",
"src",
"main",
"AndroidManifest.xml"
);
manifest = xmlHelper.readXmlAsJson(pathToManifest);
} catch (e) {
throw new Error(`BRANCH SDK: Cannot read AndroidManfiest.xml ${e}`);
}
}
const mainActivityIndex = getMainLaunchActivityIndex(
manifest.manifest.application[0].activity
);
const targetSdk =
manifest.manifest["uses-sdk"][0].$["android:targetSdkVersion"];
return {
file: manifest,
path: pathToManifest,
mainActivityIndex: mainActivityIndex,
targetSdk: targetSdk
};
}
|
[
"function",
"getManifest",
"(",
"context",
")",
"{",
"let",
"pathToManifest",
";",
"let",
"manifest",
";",
"try",
"{",
"// cordova platform add android@6.0.0",
"pathToManifest",
"=",
"path",
".",
"join",
"(",
"context",
".",
"opts",
".",
"projectRoot",
",",
"\"platforms\"",
",",
"\"android\"",
",",
"\"AndroidManifest.xml\"",
")",
";",
"manifest",
"=",
"xmlHelper",
".",
"readXmlAsJson",
"(",
"pathToManifest",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"try",
"{",
"// cordova platform add android@7.0.0",
"pathToManifest",
"=",
"path",
".",
"join",
"(",
"context",
".",
"opts",
".",
"projectRoot",
",",
"\"platforms\"",
",",
"\"android\"",
",",
"\"app\"",
",",
"\"src\"",
",",
"\"main\"",
",",
"\"AndroidManifest.xml\"",
")",
";",
"manifest",
"=",
"xmlHelper",
".",
"readXmlAsJson",
"(",
"pathToManifest",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"e",
"}",
"`",
")",
";",
"}",
"}",
"const",
"mainActivityIndex",
"=",
"getMainLaunchActivityIndex",
"(",
"manifest",
".",
"manifest",
".",
"application",
"[",
"0",
"]",
".",
"activity",
")",
";",
"const",
"targetSdk",
"=",
"manifest",
".",
"manifest",
"[",
"\"uses-sdk\"",
"]",
"[",
"0",
"]",
".",
"$",
"[",
"\"android:targetSdkVersion\"",
"]",
";",
"return",
"{",
"file",
":",
"manifest",
",",
"path",
":",
"pathToManifest",
",",
"mainActivityIndex",
":",
"mainActivityIndex",
",",
"targetSdk",
":",
"targetSdk",
"}",
";",
"}"
] |
get AndroidManifest.xml information
|
[
"get",
"AndroidManifest",
".",
"xml",
"information"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/android/updateAndroidManifest.js#L41-L83
|
13,491
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-file/www/FileWriter.js
|
function(file) {
this.fileName = "";
this.length = 0;
if (file) {
this.localURL = file.localURL || file;
this.length = file.size || 0;
}
// default is to write at the beginning of the file
this.position = 0;
this.readyState = 0; // EMPTY
this.result = null;
// Error
this.error = null;
// Event handlers
this.onwritestart = null; // When writing starts
this.onprogress = null; // While writing the file, and reporting partial file data
this.onwrite = null; // When the write has successfully completed.
this.onwriteend = null; // When the request has completed (either in success or failure).
this.onabort = null; // When the write has been aborted. For instance, by invoking the abort() method.
this.onerror = null; // When the write has failed (see errors).
}
|
javascript
|
function(file) {
this.fileName = "";
this.length = 0;
if (file) {
this.localURL = file.localURL || file;
this.length = file.size || 0;
}
// default is to write at the beginning of the file
this.position = 0;
this.readyState = 0; // EMPTY
this.result = null;
// Error
this.error = null;
// Event handlers
this.onwritestart = null; // When writing starts
this.onprogress = null; // While writing the file, and reporting partial file data
this.onwrite = null; // When the write has successfully completed.
this.onwriteend = null; // When the request has completed (either in success or failure).
this.onabort = null; // When the write has been aborted. For instance, by invoking the abort() method.
this.onerror = null; // When the write has failed (see errors).
}
|
[
"function",
"(",
"file",
")",
"{",
"this",
".",
"fileName",
"=",
"\"\"",
";",
"this",
".",
"length",
"=",
"0",
";",
"if",
"(",
"file",
")",
"{",
"this",
".",
"localURL",
"=",
"file",
".",
"localURL",
"||",
"file",
";",
"this",
".",
"length",
"=",
"file",
".",
"size",
"||",
"0",
";",
"}",
"// default is to write at the beginning of the file",
"this",
".",
"position",
"=",
"0",
";",
"this",
".",
"readyState",
"=",
"0",
";",
"// EMPTY",
"this",
".",
"result",
"=",
"null",
";",
"// Error",
"this",
".",
"error",
"=",
"null",
";",
"// Event handlers",
"this",
".",
"onwritestart",
"=",
"null",
";",
"// When writing starts",
"this",
".",
"onprogress",
"=",
"null",
";",
"// While writing the file, and reporting partial file data",
"this",
".",
"onwrite",
"=",
"null",
";",
"// When the write has successfully completed.",
"this",
".",
"onwriteend",
"=",
"null",
";",
"// When the request has completed (either in success or failure).",
"this",
".",
"onabort",
"=",
"null",
";",
"// When the write has been aborted. For instance, by invoking the abort() method.",
"this",
".",
"onerror",
"=",
"null",
";",
"// When the write has failed (see errors).",
"}"
] |
This class writes to the mobile device file system.
For Android:
The root directory is the root of the file system.
To write to the SD card, the file name is "sdcard/my_file.txt"
@constructor
@param file {File} File object containing file properties
@param append if true write to the end of the file, otherwise overwrite the file
|
[
"This",
"class",
"writes",
"to",
"the",
"mobile",
"device",
"file",
"system",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-file/www/FileWriter.js#L37-L61
|
|
13,492
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-dialogs/src/firefoxos/notification.js
|
makeCallbackButton
|
function makeCallbackButton (labelIndex) {
return function () {
if (modalWindow) {
modalWindow.removeEventListener('unload', onUnload, false);
modalWindow.close();
}
// checking if prompt
var promptInput = modalDocument.getElementById('prompt-input');
var response;
if (promptInput) {
response = {
input1: promptInput.value,
buttonIndex: labelIndex
};
}
response = response || labelIndex;
callback(response);
};
}
|
javascript
|
function makeCallbackButton (labelIndex) {
return function () {
if (modalWindow) {
modalWindow.removeEventListener('unload', onUnload, false);
modalWindow.close();
}
// checking if prompt
var promptInput = modalDocument.getElementById('prompt-input');
var response;
if (promptInput) {
response = {
input1: promptInput.value,
buttonIndex: labelIndex
};
}
response = response || labelIndex;
callback(response);
};
}
|
[
"function",
"makeCallbackButton",
"(",
"labelIndex",
")",
"{",
"return",
"function",
"(",
")",
"{",
"if",
"(",
"modalWindow",
")",
"{",
"modalWindow",
".",
"removeEventListener",
"(",
"'unload'",
",",
"onUnload",
",",
"false",
")",
";",
"modalWindow",
".",
"close",
"(",
")",
";",
"}",
"// checking if prompt",
"var",
"promptInput",
"=",
"modalDocument",
".",
"getElementById",
"(",
"'prompt-input'",
")",
";",
"var",
"response",
";",
"if",
"(",
"promptInput",
")",
"{",
"response",
"=",
"{",
"input1",
":",
"promptInput",
".",
"value",
",",
"buttonIndex",
":",
"labelIndex",
"}",
";",
"}",
"response",
"=",
"response",
"||",
"labelIndex",
";",
"callback",
"(",
"response",
")",
";",
"}",
";",
"}"
] |
call callback and destroy modal
|
[
"call",
"callback",
"and",
"destroy",
"modal"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-dialogs/src/firefoxos/notification.js#L93-L111
|
13,493
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/ios/enableEntitlements.js
|
enableAssociatedDomains
|
function enableAssociatedDomains(preferences) {
const entitlementsFile = path.join(
preferences.projectRoot,
"platforms",
"ios",
preferences.projectName,
"Resources",
`${preferences.projectName}.entitlements`
);
activateAssociativeDomains(
preferences.iosProjectModule.xcode,
entitlementsFile
);
addPbxReference(preferences.iosProjectModule.xcode, entitlementsFile);
preferences.iosProjectModule.write();
}
|
javascript
|
function enableAssociatedDomains(preferences) {
const entitlementsFile = path.join(
preferences.projectRoot,
"platforms",
"ios",
preferences.projectName,
"Resources",
`${preferences.projectName}.entitlements`
);
activateAssociativeDomains(
preferences.iosProjectModule.xcode,
entitlementsFile
);
addPbxReference(preferences.iosProjectModule.xcode, entitlementsFile);
preferences.iosProjectModule.write();
}
|
[
"function",
"enableAssociatedDomains",
"(",
"preferences",
")",
"{",
"const",
"entitlementsFile",
"=",
"path",
".",
"join",
"(",
"preferences",
".",
"projectRoot",
",",
"\"platforms\"",
",",
"\"ios\"",
",",
"preferences",
".",
"projectName",
",",
"\"Resources\"",
",",
"`",
"${",
"preferences",
".",
"projectName",
"}",
"`",
")",
";",
"activateAssociativeDomains",
"(",
"preferences",
".",
"iosProjectModule",
".",
"xcode",
",",
"entitlementsFile",
")",
";",
"addPbxReference",
"(",
"preferences",
".",
"iosProjectModule",
".",
"xcode",
",",
"entitlementsFile",
")",
";",
"preferences",
".",
"iosProjectModule",
".",
"write",
"(",
")",
";",
"}"
] |
updates the xcode preferences to allow associated domains
|
[
"updates",
"the",
"xcode",
"preferences",
"to",
"allow",
"associated",
"domains"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/ios/enableEntitlements.js#L16-L32
|
13,494
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/ios/enableEntitlements.js
|
activateAssociativeDomains
|
function activateAssociativeDomains(xcodeProject, entitlementsFile) {
const configurations = removeComments(
xcodeProject.pbxXCBuildConfigurationSection()
);
let config;
let buildSettings;
for (config in configurations) {
buildSettings = configurations[config].buildSettings;
buildSettings.CODE_SIGN_IDENTITY = `"${CODESIGNIDENTITY}"`;
buildSettings.CODE_SIGN_ENTITLEMENTS = `"${entitlementsFile}"`;
// if deployment target is less then the required one - increase it
if (buildSettings.IPHONEOS_DEPLOYMENT_TARGET) {
const buildDeploymentTarget = buildSettings.IPHONEOS_DEPLOYMENT_TARGET.toString();
if (compare(buildDeploymentTarget, IOS_DEPLOYMENT_TARGET) === -1) {
buildSettings.IPHONEOS_DEPLOYMENT_TARGET = IOS_DEPLOYMENT_TARGET;
}
} else {
buildSettings.IPHONEOS_DEPLOYMENT_TARGET = IOS_DEPLOYMENT_TARGET;
}
}
}
|
javascript
|
function activateAssociativeDomains(xcodeProject, entitlementsFile) {
const configurations = removeComments(
xcodeProject.pbxXCBuildConfigurationSection()
);
let config;
let buildSettings;
for (config in configurations) {
buildSettings = configurations[config].buildSettings;
buildSettings.CODE_SIGN_IDENTITY = `"${CODESIGNIDENTITY}"`;
buildSettings.CODE_SIGN_ENTITLEMENTS = `"${entitlementsFile}"`;
// if deployment target is less then the required one - increase it
if (buildSettings.IPHONEOS_DEPLOYMENT_TARGET) {
const buildDeploymentTarget = buildSettings.IPHONEOS_DEPLOYMENT_TARGET.toString();
if (compare(buildDeploymentTarget, IOS_DEPLOYMENT_TARGET) === -1) {
buildSettings.IPHONEOS_DEPLOYMENT_TARGET = IOS_DEPLOYMENT_TARGET;
}
} else {
buildSettings.IPHONEOS_DEPLOYMENT_TARGET = IOS_DEPLOYMENT_TARGET;
}
}
}
|
[
"function",
"activateAssociativeDomains",
"(",
"xcodeProject",
",",
"entitlementsFile",
")",
"{",
"const",
"configurations",
"=",
"removeComments",
"(",
"xcodeProject",
".",
"pbxXCBuildConfigurationSection",
"(",
")",
")",
";",
"let",
"config",
";",
"let",
"buildSettings",
";",
"for",
"(",
"config",
"in",
"configurations",
")",
"{",
"buildSettings",
"=",
"configurations",
"[",
"config",
"]",
".",
"buildSettings",
";",
"buildSettings",
".",
"CODE_SIGN_IDENTITY",
"=",
"`",
"${",
"CODESIGNIDENTITY",
"}",
"`",
";",
"buildSettings",
".",
"CODE_SIGN_ENTITLEMENTS",
"=",
"`",
"${",
"entitlementsFile",
"}",
"`",
";",
"// if deployment target is less then the required one - increase it",
"if",
"(",
"buildSettings",
".",
"IPHONEOS_DEPLOYMENT_TARGET",
")",
"{",
"const",
"buildDeploymentTarget",
"=",
"buildSettings",
".",
"IPHONEOS_DEPLOYMENT_TARGET",
".",
"toString",
"(",
")",
";",
"if",
"(",
"compare",
"(",
"buildDeploymentTarget",
",",
"IOS_DEPLOYMENT_TARGET",
")",
"===",
"-",
"1",
")",
"{",
"buildSettings",
".",
"IPHONEOS_DEPLOYMENT_TARGET",
"=",
"IOS_DEPLOYMENT_TARGET",
";",
"}",
"}",
"else",
"{",
"buildSettings",
".",
"IPHONEOS_DEPLOYMENT_TARGET",
"=",
"IOS_DEPLOYMENT_TARGET",
";",
"}",
"}",
"}"
] |
adds entitlement files to the xcode project
|
[
"adds",
"entitlement",
"files",
"to",
"the",
"xcode",
"project"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/ios/enableEntitlements.js#L35-L57
|
13,495
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/ios/enableEntitlements.js
|
removeComments
|
function removeComments(obj) {
const keys = Object.keys(obj);
const newObj = {};
for (let i = 0, len = keys.length; i < len; i++) {
if (!COMMENT_KEY.test(keys[i])) {
newObj[keys[i]] = obj[keys[i]];
}
}
return newObj;
}
|
javascript
|
function removeComments(obj) {
const keys = Object.keys(obj);
const newObj = {};
for (let i = 0, len = keys.length; i < len; i++) {
if (!COMMENT_KEY.test(keys[i])) {
newObj[keys[i]] = obj[keys[i]];
}
}
return newObj;
}
|
[
"function",
"removeComments",
"(",
"obj",
")",
"{",
"const",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
";",
"const",
"newObj",
"=",
"{",
"}",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"len",
"=",
"keys",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"COMMENT_KEY",
".",
"test",
"(",
"keys",
"[",
"i",
"]",
")",
")",
"{",
"newObj",
"[",
"keys",
"[",
"i",
"]",
"]",
"=",
"obj",
"[",
"keys",
"[",
"i",
"]",
"]",
";",
"}",
"}",
"return",
"newObj",
";",
"}"
] |
removes comments from .pbx file
|
[
"removes",
"comments",
"from",
".",
"pbx",
"file"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/ios/enableEntitlements.js#L89-L100
|
13,496
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/downloadNpmDependencies.js
|
install
|
function install(context) {
// set properties
const q = context.requireCordovaModule("q");
var async = new q.defer(); // eslint-disable-line
const installFlagLocation = path.join(
context.opts.projectRoot,
"plugins",
context.opts.plugin.id,
INSTALLFLAGNAME
);
const dependencies = require(path.join(
context.opts.projectRoot,
"plugins",
context.opts.plugin.id,
"package.json"
)).dependencies;
// only run once
if (getPackageInstalled(installFlagLocation)) return;
// install node modules
const modules = getNodeModulesToInstall(dependencies);
if (modules.length === 0) return async.promise;
installNodeModules(modules, () => {
// only run once
setPackageInstalled(installFlagLocation);
removeEtcDirectory();
async.resolve();
});
// wait until callbacks from the all the npm install complete
return async.promise;
}
|
javascript
|
function install(context) {
// set properties
const q = context.requireCordovaModule("q");
var async = new q.defer(); // eslint-disable-line
const installFlagLocation = path.join(
context.opts.projectRoot,
"plugins",
context.opts.plugin.id,
INSTALLFLAGNAME
);
const dependencies = require(path.join(
context.opts.projectRoot,
"plugins",
context.opts.plugin.id,
"package.json"
)).dependencies;
// only run once
if (getPackageInstalled(installFlagLocation)) return;
// install node modules
const modules = getNodeModulesToInstall(dependencies);
if (modules.length === 0) return async.promise;
installNodeModules(modules, () => {
// only run once
setPackageInstalled(installFlagLocation);
removeEtcDirectory();
async.resolve();
});
// wait until callbacks from the all the npm install complete
return async.promise;
}
|
[
"function",
"install",
"(",
"context",
")",
"{",
"// set properties",
"const",
"q",
"=",
"context",
".",
"requireCordovaModule",
"(",
"\"q\"",
")",
";",
"var",
"async",
"=",
"new",
"q",
".",
"defer",
"(",
")",
";",
"// eslint-disable-line",
"const",
"installFlagLocation",
"=",
"path",
".",
"join",
"(",
"context",
".",
"opts",
".",
"projectRoot",
",",
"\"plugins\"",
",",
"context",
".",
"opts",
".",
"plugin",
".",
"id",
",",
"INSTALLFLAGNAME",
")",
";",
"const",
"dependencies",
"=",
"require",
"(",
"path",
".",
"join",
"(",
"context",
".",
"opts",
".",
"projectRoot",
",",
"\"plugins\"",
",",
"context",
".",
"opts",
".",
"plugin",
".",
"id",
",",
"\"package.json\"",
")",
")",
".",
"dependencies",
";",
"// only run once",
"if",
"(",
"getPackageInstalled",
"(",
"installFlagLocation",
")",
")",
"return",
";",
"// install node modules",
"const",
"modules",
"=",
"getNodeModulesToInstall",
"(",
"dependencies",
")",
";",
"if",
"(",
"modules",
".",
"length",
"===",
"0",
")",
"return",
"async",
".",
"promise",
";",
"installNodeModules",
"(",
"modules",
",",
"(",
")",
"=>",
"{",
"// only run once",
"setPackageInstalled",
"(",
"installFlagLocation",
")",
";",
"removeEtcDirectory",
"(",
")",
";",
"async",
".",
"resolve",
"(",
")",
";",
"}",
")",
";",
"// wait until callbacks from the all the npm install complete",
"return",
"async",
".",
"promise",
";",
"}"
] |
install the node dependencies for Branch SDK
|
[
"install",
"the",
"node",
"dependencies",
"for",
"Branch",
"SDK"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/downloadNpmDependencies.js#L16-L49
|
13,497
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/downloadNpmDependencies.js
|
installNodeModules
|
function installNodeModules(modules, callback) {
// base case
if (modules.length <= 0) {
return callback();
}
// install one at a time
const module = modules.pop();
console.log(`BRANCH SDK: Installing node dependency ${module}`);
const install = `npm install --prefix ./plugins/${SDK} -D ${module}`;
exec(install, (err, stdout, stderr) => {
// handle error
if (err) {
throw new Error(
`BRANCH SDK: Failed to install Branch node dependency ${module}. Docs https://goo.gl/GijGKP`
);
} else {
// next module
installNodeModules(modules, callback);
}
});
}
|
javascript
|
function installNodeModules(modules, callback) {
// base case
if (modules.length <= 0) {
return callback();
}
// install one at a time
const module = modules.pop();
console.log(`BRANCH SDK: Installing node dependency ${module}`);
const install = `npm install --prefix ./plugins/${SDK} -D ${module}`;
exec(install, (err, stdout, stderr) => {
// handle error
if (err) {
throw new Error(
`BRANCH SDK: Failed to install Branch node dependency ${module}. Docs https://goo.gl/GijGKP`
);
} else {
// next module
installNodeModules(modules, callback);
}
});
}
|
[
"function",
"installNodeModules",
"(",
"modules",
",",
"callback",
")",
"{",
"// base case",
"if",
"(",
"modules",
".",
"length",
"<=",
"0",
")",
"{",
"return",
"callback",
"(",
")",
";",
"}",
"// install one at a time",
"const",
"module",
"=",
"modules",
".",
"pop",
"(",
")",
";",
"console",
".",
"log",
"(",
"`",
"${",
"module",
"}",
"`",
")",
";",
"const",
"install",
"=",
"`",
"${",
"SDK",
"}",
"${",
"module",
"}",
"`",
";",
"exec",
"(",
"install",
",",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
"=>",
"{",
"// handle error",
"if",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"module",
"}",
"`",
")",
";",
"}",
"else",
"{",
"// next module",
"installNodeModules",
"(",
"modules",
",",
"callback",
")",
";",
"}",
"}",
")",
";",
"}"
] |
installs the node modules via npm install one at a time
|
[
"installs",
"the",
"node",
"modules",
"via",
"npm",
"install",
"one",
"at",
"a",
"time"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/downloadNpmDependencies.js#L52-L74
|
13,498
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/downloadNpmDependencies.js
|
getNodeModulesToInstall
|
function getNodeModulesToInstall(dependencies) {
const modules = [];
for (const module in dependencies) {
if (dependencies.hasOwnProperty(module)) {
try {
require(module);
} catch (err) {
modules.push(module);
}
}
}
return modules;
}
|
javascript
|
function getNodeModulesToInstall(dependencies) {
const modules = [];
for (const module in dependencies) {
if (dependencies.hasOwnProperty(module)) {
try {
require(module);
} catch (err) {
modules.push(module);
}
}
}
return modules;
}
|
[
"function",
"getNodeModulesToInstall",
"(",
"dependencies",
")",
"{",
"const",
"modules",
"=",
"[",
"]",
";",
"for",
"(",
"const",
"module",
"in",
"dependencies",
")",
"{",
"if",
"(",
"dependencies",
".",
"hasOwnProperty",
"(",
"module",
")",
")",
"{",
"try",
"{",
"require",
"(",
"module",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"modules",
".",
"push",
"(",
"module",
")",
";",
"}",
"}",
"}",
"return",
"modules",
";",
"}"
] |
checks to see which node modules need to be installed from package.json.dependencies
|
[
"checks",
"to",
"see",
"which",
"node",
"modules",
"need",
"to",
"be",
"installed",
"from",
"package",
".",
"json",
".",
"dependencies"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/downloadNpmDependencies.js#L77-L89
|
13,499
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-camera/src/blackberry10/index.js
|
showCameraDialog
|
function showCameraDialog (done, cancel, fail) {
var wv = qnx.webplatform.createWebView(function () {
wv.url = 'local:///chrome/camera.html';
wv.allowQnxObject = true;
wv.allowRpc = true;
wv.zOrder = 1;
wv.setGeometry(0, 0, screen.width, screen.height);
wv.backgroundColor = 0x00000000;
wv.active = true;
wv.visible = true;
wv.on('UserMediaRequest', function (evt, args) {
wv.allowUserMedia(JSON.parse(args).id, 'CAMERA_UNIT_REAR');
});
wv.on('JavaScriptCallback', function (evt, data) {
var args = JSON.parse(data).args;
if (args[0] === 'cordova-plugin-camera') {
if (args[1] === 'cancel') {
cancel('User canceled');
} else if (args[1] === 'error') {
fail(args[2]);
} else {
saveImage(args[1], done, fail);
}
wv.un('JavaScriptCallback', arguments.callee);
wv.visible = false;
wv.destroy();
qnx.webplatform.getApplication().unlockRotation();
}
});
wv.on('Destroyed', function () {
wv.delete();
});
qnx.webplatform.getApplication().lockRotation();
qnx.webplatform.getController().dispatchEvent('webview.initialized', [wv]);
});
}
|
javascript
|
function showCameraDialog (done, cancel, fail) {
var wv = qnx.webplatform.createWebView(function () {
wv.url = 'local:///chrome/camera.html';
wv.allowQnxObject = true;
wv.allowRpc = true;
wv.zOrder = 1;
wv.setGeometry(0, 0, screen.width, screen.height);
wv.backgroundColor = 0x00000000;
wv.active = true;
wv.visible = true;
wv.on('UserMediaRequest', function (evt, args) {
wv.allowUserMedia(JSON.parse(args).id, 'CAMERA_UNIT_REAR');
});
wv.on('JavaScriptCallback', function (evt, data) {
var args = JSON.parse(data).args;
if (args[0] === 'cordova-plugin-camera') {
if (args[1] === 'cancel') {
cancel('User canceled');
} else if (args[1] === 'error') {
fail(args[2]);
} else {
saveImage(args[1], done, fail);
}
wv.un('JavaScriptCallback', arguments.callee);
wv.visible = false;
wv.destroy();
qnx.webplatform.getApplication().unlockRotation();
}
});
wv.on('Destroyed', function () {
wv.delete();
});
qnx.webplatform.getApplication().lockRotation();
qnx.webplatform.getController().dispatchEvent('webview.initialized', [wv]);
});
}
|
[
"function",
"showCameraDialog",
"(",
"done",
",",
"cancel",
",",
"fail",
")",
"{",
"var",
"wv",
"=",
"qnx",
".",
"webplatform",
".",
"createWebView",
"(",
"function",
"(",
")",
"{",
"wv",
".",
"url",
"=",
"'local:///chrome/camera.html'",
";",
"wv",
".",
"allowQnxObject",
"=",
"true",
";",
"wv",
".",
"allowRpc",
"=",
"true",
";",
"wv",
".",
"zOrder",
"=",
"1",
";",
"wv",
".",
"setGeometry",
"(",
"0",
",",
"0",
",",
"screen",
".",
"width",
",",
"screen",
".",
"height",
")",
";",
"wv",
".",
"backgroundColor",
"=",
"0x00000000",
";",
"wv",
".",
"active",
"=",
"true",
";",
"wv",
".",
"visible",
"=",
"true",
";",
"wv",
".",
"on",
"(",
"'UserMediaRequest'",
",",
"function",
"(",
"evt",
",",
"args",
")",
"{",
"wv",
".",
"allowUserMedia",
"(",
"JSON",
".",
"parse",
"(",
"args",
")",
".",
"id",
",",
"'CAMERA_UNIT_REAR'",
")",
";",
"}",
")",
";",
"wv",
".",
"on",
"(",
"'JavaScriptCallback'",
",",
"function",
"(",
"evt",
",",
"data",
")",
"{",
"var",
"args",
"=",
"JSON",
".",
"parse",
"(",
"data",
")",
".",
"args",
";",
"if",
"(",
"args",
"[",
"0",
"]",
"===",
"'cordova-plugin-camera'",
")",
"{",
"if",
"(",
"args",
"[",
"1",
"]",
"===",
"'cancel'",
")",
"{",
"cancel",
"(",
"'User canceled'",
")",
";",
"}",
"else",
"if",
"(",
"args",
"[",
"1",
"]",
"===",
"'error'",
")",
"{",
"fail",
"(",
"args",
"[",
"2",
"]",
")",
";",
"}",
"else",
"{",
"saveImage",
"(",
"args",
"[",
"1",
"]",
",",
"done",
",",
"fail",
")",
";",
"}",
"wv",
".",
"un",
"(",
"'JavaScriptCallback'",
",",
"arguments",
".",
"callee",
")",
";",
"wv",
".",
"visible",
"=",
"false",
";",
"wv",
".",
"destroy",
"(",
")",
";",
"qnx",
".",
"webplatform",
".",
"getApplication",
"(",
")",
".",
"unlockRotation",
"(",
")",
";",
"}",
"}",
")",
";",
"wv",
".",
"on",
"(",
"'Destroyed'",
",",
"function",
"(",
")",
"{",
"wv",
".",
"delete",
"(",
")",
";",
"}",
")",
";",
"qnx",
".",
"webplatform",
".",
"getApplication",
"(",
")",
".",
"lockRotation",
"(",
")",
";",
"qnx",
".",
"webplatform",
".",
"getController",
"(",
")",
".",
"dispatchEvent",
"(",
"'webview.initialized'",
",",
"[",
"wv",
"]",
")",
";",
"}",
")",
";",
"}"
] |
open a webview with getUserMedia camera card implementation when camera card not available
|
[
"open",
"a",
"webview",
"with",
"getUserMedia",
"camera",
"card",
"implementation",
"when",
"camera",
"card",
"not",
"available"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-camera/src/blackberry10/index.js#L51-L86
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.