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
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
jhipster/generator-jhipster
|
generators/docker-prompts.js
|
askForDockerRepositoryName
|
function askForDockerRepositoryName() {
if (this.regenerate) return;
const done = this.async();
const prompts = [
{
type: 'input',
name: 'dockerRepositoryName',
message: 'What should we use for the base Docker repository name?',
default: this.dockerRepositoryName
}
];
this.prompt(prompts).then(props => {
this.dockerRepositoryName = props.dockerRepositoryName;
done();
});
}
|
javascript
|
function askForDockerRepositoryName() {
if (this.regenerate) return;
const done = this.async();
const prompts = [
{
type: 'input',
name: 'dockerRepositoryName',
message: 'What should we use for the base Docker repository name?',
default: this.dockerRepositoryName
}
];
this.prompt(prompts).then(props => {
this.dockerRepositoryName = props.dockerRepositoryName;
done();
});
}
|
[
"function",
"askForDockerRepositoryName",
"(",
")",
"{",
"if",
"(",
"this",
".",
"regenerate",
")",
"return",
";",
"const",
"done",
"=",
"this",
".",
"async",
"(",
")",
";",
"const",
"prompts",
"=",
"[",
"{",
"type",
":",
"'input'",
",",
"name",
":",
"'dockerRepositoryName'",
",",
"message",
":",
"'What should we use for the base Docker repository name?'",
",",
"default",
":",
"this",
".",
"dockerRepositoryName",
"}",
"]",
";",
"this",
".",
"prompt",
"(",
"prompts",
")",
".",
"then",
"(",
"props",
"=>",
"{",
"this",
".",
"dockerRepositoryName",
"=",
"props",
".",
"dockerRepositoryName",
";",
"done",
"(",
")",
";",
"}",
")",
";",
"}"
] |
Ask For Docker Repository Name
|
[
"Ask",
"For",
"Docker",
"Repository",
"Name"
] |
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
|
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L401-L419
|
train
|
jhipster/generator-jhipster
|
generators/docker-prompts.js
|
askForDockerPushCommand
|
function askForDockerPushCommand() {
if (this.regenerate) return;
const done = this.async();
const prompts = [
{
type: 'input',
name: 'dockerPushCommand',
message: 'What command should we use for push Docker image to repository?',
default: this.dockerPushCommand ? this.dockerPushCommand : 'docker push'
}
];
this.prompt(prompts).then(props => {
this.dockerPushCommand = props.dockerPushCommand;
done();
});
}
|
javascript
|
function askForDockerPushCommand() {
if (this.regenerate) return;
const done = this.async();
const prompts = [
{
type: 'input',
name: 'dockerPushCommand',
message: 'What command should we use for push Docker image to repository?',
default: this.dockerPushCommand ? this.dockerPushCommand : 'docker push'
}
];
this.prompt(prompts).then(props => {
this.dockerPushCommand = props.dockerPushCommand;
done();
});
}
|
[
"function",
"askForDockerPushCommand",
"(",
")",
"{",
"if",
"(",
"this",
".",
"regenerate",
")",
"return",
";",
"const",
"done",
"=",
"this",
".",
"async",
"(",
")",
";",
"const",
"prompts",
"=",
"[",
"{",
"type",
":",
"'input'",
",",
"name",
":",
"'dockerPushCommand'",
",",
"message",
":",
"'What command should we use for push Docker image to repository?'",
",",
"default",
":",
"this",
".",
"dockerPushCommand",
"?",
"this",
".",
"dockerPushCommand",
":",
"'docker push'",
"}",
"]",
";",
"this",
".",
"prompt",
"(",
"prompts",
")",
".",
"then",
"(",
"props",
"=>",
"{",
"this",
".",
"dockerPushCommand",
"=",
"props",
".",
"dockerPushCommand",
";",
"done",
"(",
")",
";",
"}",
")",
";",
"}"
] |
Ask For Docker Push Command
|
[
"Ask",
"For",
"Docker",
"Push",
"Command"
] |
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
|
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L424-L442
|
train
|
jhipster/generator-jhipster
|
generators/docker-prompts.js
|
getAppFolders
|
function getAppFolders(input, deploymentApplicationType) {
const destinationPath = this.destinationPath(input);
const files = shelljs.ls('-l', destinationPath);
const appsFolders = [];
files.forEach(file => {
if (file.isDirectory()) {
if (shelljs.test('-f', `${destinationPath}/${file.name}/.yo-rc.json`)) {
try {
const fileData = this.fs.readJSON(`${destinationPath}/${file.name}/.yo-rc.json`);
if (
fileData['generator-jhipster'].baseName !== undefined &&
(deploymentApplicationType === undefined ||
deploymentApplicationType === fileData['generator-jhipster'].applicationType ||
(deploymentApplicationType === 'microservice' &&
fileData['generator-jhipster'].applicationType === 'gateway') ||
(deploymentApplicationType === 'microservice' && fileData['generator-jhipster'].applicationType === 'uaa'))
) {
appsFolders.push(file.name.match(/([^/]*)\/*$/)[1]);
}
} catch (err) {
this.log(chalk.red(`${file}: this .yo-rc.json can't be read`));
this.debug('Error:', err);
}
}
}
});
return appsFolders;
}
|
javascript
|
function getAppFolders(input, deploymentApplicationType) {
const destinationPath = this.destinationPath(input);
const files = shelljs.ls('-l', destinationPath);
const appsFolders = [];
files.forEach(file => {
if (file.isDirectory()) {
if (shelljs.test('-f', `${destinationPath}/${file.name}/.yo-rc.json`)) {
try {
const fileData = this.fs.readJSON(`${destinationPath}/${file.name}/.yo-rc.json`);
if (
fileData['generator-jhipster'].baseName !== undefined &&
(deploymentApplicationType === undefined ||
deploymentApplicationType === fileData['generator-jhipster'].applicationType ||
(deploymentApplicationType === 'microservice' &&
fileData['generator-jhipster'].applicationType === 'gateway') ||
(deploymentApplicationType === 'microservice' && fileData['generator-jhipster'].applicationType === 'uaa'))
) {
appsFolders.push(file.name.match(/([^/]*)\/*$/)[1]);
}
} catch (err) {
this.log(chalk.red(`${file}: this .yo-rc.json can't be read`));
this.debug('Error:', err);
}
}
}
});
return appsFolders;
}
|
[
"function",
"getAppFolders",
"(",
"input",
",",
"deploymentApplicationType",
")",
"{",
"const",
"destinationPath",
"=",
"this",
".",
"destinationPath",
"(",
"input",
")",
";",
"const",
"files",
"=",
"shelljs",
".",
"ls",
"(",
"'-l'",
",",
"destinationPath",
")",
";",
"const",
"appsFolders",
"=",
"[",
"]",
";",
"files",
".",
"forEach",
"(",
"file",
"=>",
"{",
"if",
"(",
"file",
".",
"isDirectory",
"(",
")",
")",
"{",
"if",
"(",
"shelljs",
".",
"test",
"(",
"'-f'",
",",
"`",
"${",
"destinationPath",
"}",
"${",
"file",
".",
"name",
"}",
"`",
")",
")",
"{",
"try",
"{",
"const",
"fileData",
"=",
"this",
".",
"fs",
".",
"readJSON",
"(",
"`",
"${",
"destinationPath",
"}",
"${",
"file",
".",
"name",
"}",
"`",
")",
";",
"if",
"(",
"fileData",
"[",
"'generator-jhipster'",
"]",
".",
"baseName",
"!==",
"undefined",
"&&",
"(",
"deploymentApplicationType",
"===",
"undefined",
"||",
"deploymentApplicationType",
"===",
"fileData",
"[",
"'generator-jhipster'",
"]",
".",
"applicationType",
"||",
"(",
"deploymentApplicationType",
"===",
"'microservice'",
"&&",
"fileData",
"[",
"'generator-jhipster'",
"]",
".",
"applicationType",
"===",
"'gateway'",
")",
"||",
"(",
"deploymentApplicationType",
"===",
"'microservice'",
"&&",
"fileData",
"[",
"'generator-jhipster'",
"]",
".",
"applicationType",
"===",
"'uaa'",
")",
")",
")",
"{",
"appsFolders",
".",
"push",
"(",
"file",
".",
"name",
".",
"match",
"(",
"/",
"([^/]*)\\/*$",
"/",
")",
"[",
"1",
"]",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"this",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"`",
"${",
"file",
"}",
"`",
")",
")",
";",
"this",
".",
"debug",
"(",
"'Error:'",
",",
"err",
")",
";",
"}",
"}",
"}",
"}",
")",
";",
"return",
"appsFolders",
";",
"}"
] |
Get App Folders
@param input path to join to destination path
@param deploymentApplicationType type of application being composed
@returns {Array} array of string representing app folders
|
[
"Get",
"App",
"Folders"
] |
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
|
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L450-L479
|
train
|
jhipster/generator-jhipster
|
generators/docker-base.js
|
configureImageNames
|
function configureImageNames() {
for (let i = 0; i < this.appsFolders.length; i++) {
const originalImageName = this.appConfigs[i].baseName.toLowerCase();
const targetImageName = this.dockerRepositoryName ? `${this.dockerRepositoryName}/${originalImageName}` : originalImageName;
this.appConfigs[i].targetImageName = targetImageName;
}
}
|
javascript
|
function configureImageNames() {
for (let i = 0; i < this.appsFolders.length; i++) {
const originalImageName = this.appConfigs[i].baseName.toLowerCase();
const targetImageName = this.dockerRepositoryName ? `${this.dockerRepositoryName}/${originalImageName}` : originalImageName;
this.appConfigs[i].targetImageName = targetImageName;
}
}
|
[
"function",
"configureImageNames",
"(",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"appsFolders",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"originalImageName",
"=",
"this",
".",
"appConfigs",
"[",
"i",
"]",
".",
"baseName",
".",
"toLowerCase",
"(",
")",
";",
"const",
"targetImageName",
"=",
"this",
".",
"dockerRepositoryName",
"?",
"`",
"${",
"this",
".",
"dockerRepositoryName",
"}",
"${",
"originalImageName",
"}",
"`",
":",
"originalImageName",
";",
"this",
".",
"appConfigs",
"[",
"i",
"]",
".",
"targetImageName",
"=",
"targetImageName",
";",
"}",
"}"
] |
Configure Image Names
|
[
"Configure",
"Image",
"Names"
] |
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
|
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-base.js#L73-L79
|
train
|
jhipster/generator-jhipster
|
generators/docker-base.js
|
setAppsFolderPaths
|
function setAppsFolderPaths() {
if (this.applicationType) return;
this.appsFolderPaths = [];
for (let i = 0; i < this.appsFolders.length; i++) {
const path = this.destinationPath(this.directoryPath + this.appsFolders[i]);
this.appsFolderPaths.push(path);
}
}
|
javascript
|
function setAppsFolderPaths() {
if (this.applicationType) return;
this.appsFolderPaths = [];
for (let i = 0; i < this.appsFolders.length; i++) {
const path = this.destinationPath(this.directoryPath + this.appsFolders[i]);
this.appsFolderPaths.push(path);
}
}
|
[
"function",
"setAppsFolderPaths",
"(",
")",
"{",
"if",
"(",
"this",
".",
"applicationType",
")",
"return",
";",
"this",
".",
"appsFolderPaths",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"appsFolders",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"path",
"=",
"this",
".",
"destinationPath",
"(",
"this",
".",
"directoryPath",
"+",
"this",
".",
"appsFolders",
"[",
"i",
"]",
")",
";",
"this",
".",
"appsFolderPaths",
".",
"push",
"(",
"path",
")",
";",
"}",
"}"
] |
Set Apps Folder Paths
|
[
"Set",
"Apps",
"Folder",
"Paths"
] |
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
|
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-base.js#L84-L91
|
train
|
jhipster/generator-jhipster
|
generators/docker-base.js
|
loadConfigs
|
function loadConfigs() {
this.appConfigs = [];
this.gatewayNb = 0;
this.monolithicNb = 0;
this.microserviceNb = 0;
this.uaaNb = 0;
// Loading configs
this.debug(`Apps folders: ${this.appsFolders}`);
this.appsFolders.forEach(appFolder => {
const path = this.destinationPath(`${this.directoryPath + appFolder}/.yo-rc.json`);
const fileData = this.fs.readJSON(path);
if (fileData) {
const config = fileData['generator-jhipster'];
if (config.applicationType === 'monolith') {
this.monolithicNb++;
} else if (config.applicationType === 'gateway') {
this.gatewayNb++;
} else if (config.applicationType === 'microservice') {
this.microserviceNb++;
} else if (config.applicationType === 'uaa') {
this.uaaNb++;
}
this.portsToBind = this.monolithicNb + this.gatewayNb;
config.appFolder = appFolder;
this.appConfigs.push(config);
} else {
this.error(`Application '${appFolder}' is not found in the path '${this.directoryPath}'`);
}
});
}
|
javascript
|
function loadConfigs() {
this.appConfigs = [];
this.gatewayNb = 0;
this.monolithicNb = 0;
this.microserviceNb = 0;
this.uaaNb = 0;
// Loading configs
this.debug(`Apps folders: ${this.appsFolders}`);
this.appsFolders.forEach(appFolder => {
const path = this.destinationPath(`${this.directoryPath + appFolder}/.yo-rc.json`);
const fileData = this.fs.readJSON(path);
if (fileData) {
const config = fileData['generator-jhipster'];
if (config.applicationType === 'monolith') {
this.monolithicNb++;
} else if (config.applicationType === 'gateway') {
this.gatewayNb++;
} else if (config.applicationType === 'microservice') {
this.microserviceNb++;
} else if (config.applicationType === 'uaa') {
this.uaaNb++;
}
this.portsToBind = this.monolithicNb + this.gatewayNb;
config.appFolder = appFolder;
this.appConfigs.push(config);
} else {
this.error(`Application '${appFolder}' is not found in the path '${this.directoryPath}'`);
}
});
}
|
[
"function",
"loadConfigs",
"(",
")",
"{",
"this",
".",
"appConfigs",
"=",
"[",
"]",
";",
"this",
".",
"gatewayNb",
"=",
"0",
";",
"this",
".",
"monolithicNb",
"=",
"0",
";",
"this",
".",
"microserviceNb",
"=",
"0",
";",
"this",
".",
"uaaNb",
"=",
"0",
";",
"this",
".",
"debug",
"(",
"`",
"${",
"this",
".",
"appsFolders",
"}",
"`",
")",
";",
"this",
".",
"appsFolders",
".",
"forEach",
"(",
"appFolder",
"=>",
"{",
"const",
"path",
"=",
"this",
".",
"destinationPath",
"(",
"`",
"${",
"this",
".",
"directoryPath",
"+",
"appFolder",
"}",
"`",
")",
";",
"const",
"fileData",
"=",
"this",
".",
"fs",
".",
"readJSON",
"(",
"path",
")",
";",
"if",
"(",
"fileData",
")",
"{",
"const",
"config",
"=",
"fileData",
"[",
"'generator-jhipster'",
"]",
";",
"if",
"(",
"config",
".",
"applicationType",
"===",
"'monolith'",
")",
"{",
"this",
".",
"monolithicNb",
"++",
";",
"}",
"else",
"if",
"(",
"config",
".",
"applicationType",
"===",
"'gateway'",
")",
"{",
"this",
".",
"gatewayNb",
"++",
";",
"}",
"else",
"if",
"(",
"config",
".",
"applicationType",
"===",
"'microservice'",
")",
"{",
"this",
".",
"microserviceNb",
"++",
";",
"}",
"else",
"if",
"(",
"config",
".",
"applicationType",
"===",
"'uaa'",
")",
"{",
"this",
".",
"uaaNb",
"++",
";",
"}",
"this",
".",
"portsToBind",
"=",
"this",
".",
"monolithicNb",
"+",
"this",
".",
"gatewayNb",
";",
"config",
".",
"appFolder",
"=",
"appFolder",
";",
"this",
".",
"appConfigs",
".",
"push",
"(",
"config",
")",
";",
"}",
"else",
"{",
"this",
".",
"error",
"(",
"`",
"${",
"appFolder",
"}",
"${",
"this",
".",
"directoryPath",
"}",
"`",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Load config from this.appFolders
|
[
"Load",
"config",
"from",
"this",
".",
"appFolders"
] |
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
|
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-base.js#L96-L128
|
train
|
material-components/material-components-web
|
scripts/cherry-pick-commits.js
|
shouldSkipCommit
|
function shouldSkipCommit(logLine, mode) {
const parsedCommit = parser.sync(logLine.message, parserOpts);
return (parsedCommit.type === 'feat' && mode === 'patch') || // feature commit
parsedCommit.notes.find((note) => note.title === 'BREAKING CHANGE') || // breaking change commit
(parsedCommit.type === 'chore' && parsedCommit.subject === 'Publish'); // Publish (version-rev) commit
}
|
javascript
|
function shouldSkipCommit(logLine, mode) {
const parsedCommit = parser.sync(logLine.message, parserOpts);
return (parsedCommit.type === 'feat' && mode === 'patch') || // feature commit
parsedCommit.notes.find((note) => note.title === 'BREAKING CHANGE') || // breaking change commit
(parsedCommit.type === 'chore' && parsedCommit.subject === 'Publish'); // Publish (version-rev) commit
}
|
[
"function",
"shouldSkipCommit",
"(",
"logLine",
",",
"mode",
")",
"{",
"const",
"parsedCommit",
"=",
"parser",
".",
"sync",
"(",
"logLine",
".",
"message",
",",
"parserOpts",
")",
";",
"return",
"(",
"parsedCommit",
".",
"type",
"===",
"'feat'",
"&&",
"mode",
"===",
"'patch'",
")",
"||",
"parsedCommit",
".",
"notes",
".",
"find",
"(",
"(",
"note",
")",
"=>",
"note",
".",
"title",
"===",
"'BREAKING CHANGE'",
")",
"||",
"(",
"parsedCommit",
".",
"type",
"===",
"'chore'",
"&&",
"parsedCommit",
".",
"subject",
"===",
"'Publish'",
")",
";",
"}"
] |
Returns true if commit should NOT be cherry-picked.
|
[
"Returns",
"true",
"if",
"commit",
"should",
"NOT",
"be",
"cherry",
"-",
"picked",
"."
] |
9f8b9ae5103ff86de4f6a5cb02e700d6eb851e5f
|
https://github.com/material-components/material-components-web/blob/9f8b9ae5103ff86de4f6a5cb02e700d6eb851e5f/scripts/cherry-pick-commits.js#L113-L118
|
train
|
material-components/material-components-web
|
scripts/cherry-pick-commits.js
|
attemptCherryPicks
|
async function attemptCherryPicks(tag, list, mode) {
const results = {
successful: [],
conflicted: [],
skipped: [],
};
console.log(`Checking out ${tag}`);
await simpleGit.checkout([tag]);
for (const logLine of list) {
if (shouldSkipCommit(logLine, mode)) {
results.skipped.push(logLine);
continue;
}
try {
await simpleGit.raw(['cherry-pick', '-x', logLine.hash]);
results.successful.push(logLine);
} catch (e) {
// Detect conflicted cherry-picks and abort them (e.message contains the command's output)
if (e.message.includes(CONFLICT_MESSAGE)) {
results.conflicted.push(logLine);
await simpleGit.raw(['cherry-pick', '--abort']);
} else if (e.message.includes('is a merge')) {
const logCommand = `\`git log --oneline --graph ${logLine.hash}\``;
console.warn(`Merge commit found! Run ${logCommand} and take note of commits on each parent,`);
console.warn('then compare to your detached history afterwards to ensure no commits of interest were skipped.');
results.skipped.push(logLine);
} else {
console.error(`${logLine.hash} unexpected failure!`, e);
}
}
}
return results;
}
|
javascript
|
async function attemptCherryPicks(tag, list, mode) {
const results = {
successful: [],
conflicted: [],
skipped: [],
};
console.log(`Checking out ${tag}`);
await simpleGit.checkout([tag]);
for (const logLine of list) {
if (shouldSkipCommit(logLine, mode)) {
results.skipped.push(logLine);
continue;
}
try {
await simpleGit.raw(['cherry-pick', '-x', logLine.hash]);
results.successful.push(logLine);
} catch (e) {
// Detect conflicted cherry-picks and abort them (e.message contains the command's output)
if (e.message.includes(CONFLICT_MESSAGE)) {
results.conflicted.push(logLine);
await simpleGit.raw(['cherry-pick', '--abort']);
} else if (e.message.includes('is a merge')) {
const logCommand = `\`git log --oneline --graph ${logLine.hash}\``;
console.warn(`Merge commit found! Run ${logCommand} and take note of commits on each parent,`);
console.warn('then compare to your detached history afterwards to ensure no commits of interest were skipped.');
results.skipped.push(logLine);
} else {
console.error(`${logLine.hash} unexpected failure!`, e);
}
}
}
return results;
}
|
[
"async",
"function",
"attemptCherryPicks",
"(",
"tag",
",",
"list",
",",
"mode",
")",
"{",
"const",
"results",
"=",
"{",
"successful",
":",
"[",
"]",
",",
"conflicted",
":",
"[",
"]",
",",
"skipped",
":",
"[",
"]",
",",
"}",
";",
"console",
".",
"log",
"(",
"`",
"${",
"tag",
"}",
"`",
")",
";",
"await",
"simpleGit",
".",
"checkout",
"(",
"[",
"tag",
"]",
")",
";",
"for",
"(",
"const",
"logLine",
"of",
"list",
")",
"{",
"if",
"(",
"shouldSkipCommit",
"(",
"logLine",
",",
"mode",
")",
")",
"{",
"results",
".",
"skipped",
".",
"push",
"(",
"logLine",
")",
";",
"continue",
";",
"}",
"try",
"{",
"await",
"simpleGit",
".",
"raw",
"(",
"[",
"'cherry-pick'",
",",
"'-x'",
",",
"logLine",
".",
"hash",
"]",
")",
";",
"results",
".",
"successful",
".",
"push",
"(",
"logLine",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"e",
".",
"message",
".",
"includes",
"(",
"CONFLICT_MESSAGE",
")",
")",
"{",
"results",
".",
"conflicted",
".",
"push",
"(",
"logLine",
")",
";",
"await",
"simpleGit",
".",
"raw",
"(",
"[",
"'cherry-pick'",
",",
"'--abort'",
"]",
")",
";",
"}",
"else",
"if",
"(",
"e",
".",
"message",
".",
"includes",
"(",
"'is a merge'",
")",
")",
"{",
"const",
"logCommand",
"=",
"`",
"\\`",
"${",
"logLine",
".",
"hash",
"}",
"\\`",
"`",
";",
"console",
".",
"warn",
"(",
"`",
"${",
"logCommand",
"}",
"`",
")",
";",
"console",
".",
"warn",
"(",
"'then compare to your detached history afterwards to ensure no commits of interest were skipped.'",
")",
";",
"results",
".",
"skipped",
".",
"push",
"(",
"logLine",
")",
";",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"`",
"${",
"logLine",
".",
"hash",
"}",
"`",
",",
"e",
")",
";",
"}",
"}",
"}",
"return",
"results",
";",
"}"
] |
Checks out the given tag and attempts to cherry-pick each commit in the list against it. If a conflict is encountered, that cherry-pick is aborted and processing moves on to the next commit.
|
[
"Checks",
"out",
"the",
"given",
"tag",
"and",
"attempts",
"to",
"cherry",
"-",
"pick",
"each",
"commit",
"in",
"the",
"list",
"against",
"it",
".",
"If",
"a",
"conflict",
"is",
"encountered",
"that",
"cherry",
"-",
"pick",
"is",
"aborted",
"and",
"processing",
"moves",
"on",
"to",
"the",
"next",
"commit",
"."
] |
9f8b9ae5103ff86de4f6a5cb02e700d6eb851e5f
|
https://github.com/material-components/material-components-web/blob/9f8b9ae5103ff86de4f6a5cb02e700d6eb851e5f/scripts/cherry-pick-commits.js#L122-L158
|
train
|
material-components/material-components-web
|
scripts/cp-pkgs.js
|
dtsBundler
|
function dtsBundler() {
const packageDirectories = fs.readdirSync(D_TS_DIRECTORY);
packageDirectories.forEach((packageDirectory) => {
const packagePath = path.join(PACKAGES_DIRECTORY, packageDirectory);
const name = JSON.parse(fs.readFileSync(path.join(packagePath, 'package.json'), 'utf8')).name;
const main = path.join(D_TS_DIRECTORY, packageDirectory, './index.d.ts');
const isAllInOne = packageDirectory === ALL_IN_ONE_PACKAGE;
const destBasename = isAllInOne ? packageDirectory : `mdc.${toCamelCase(packageDirectory.replace(/^mdc-/, ''))}`;
const destFilename = path.join(packagePath, 'dist', `${destBasename}.d.ts`);
console.log(`Writing UMD declarations in ${destFilename.replace(process.cwd() + '/', '')}`);
dts.bundle({
name,
main,
out: destFilename,
});
});
}
|
javascript
|
function dtsBundler() {
const packageDirectories = fs.readdirSync(D_TS_DIRECTORY);
packageDirectories.forEach((packageDirectory) => {
const packagePath = path.join(PACKAGES_DIRECTORY, packageDirectory);
const name = JSON.parse(fs.readFileSync(path.join(packagePath, 'package.json'), 'utf8')).name;
const main = path.join(D_TS_DIRECTORY, packageDirectory, './index.d.ts');
const isAllInOne = packageDirectory === ALL_IN_ONE_PACKAGE;
const destBasename = isAllInOne ? packageDirectory : `mdc.${toCamelCase(packageDirectory.replace(/^mdc-/, ''))}`;
const destFilename = path.join(packagePath, 'dist', `${destBasename}.d.ts`);
console.log(`Writing UMD declarations in ${destFilename.replace(process.cwd() + '/', '')}`);
dts.bundle({
name,
main,
out: destFilename,
});
});
}
|
[
"function",
"dtsBundler",
"(",
")",
"{",
"const",
"packageDirectories",
"=",
"fs",
".",
"readdirSync",
"(",
"D_TS_DIRECTORY",
")",
";",
"packageDirectories",
".",
"forEach",
"(",
"(",
"packageDirectory",
")",
"=>",
"{",
"const",
"packagePath",
"=",
"path",
".",
"join",
"(",
"PACKAGES_DIRECTORY",
",",
"packageDirectory",
")",
";",
"const",
"name",
"=",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"path",
".",
"join",
"(",
"packagePath",
",",
"'package.json'",
")",
",",
"'utf8'",
")",
")",
".",
"name",
";",
"const",
"main",
"=",
"path",
".",
"join",
"(",
"D_TS_DIRECTORY",
",",
"packageDirectory",
",",
"'./index.d.ts'",
")",
";",
"const",
"isAllInOne",
"=",
"packageDirectory",
"===",
"ALL_IN_ONE_PACKAGE",
";",
"const",
"destBasename",
"=",
"isAllInOne",
"?",
"packageDirectory",
":",
"`",
"${",
"toCamelCase",
"(",
"packageDirectory",
".",
"replace",
"(",
"/",
"^mdc-",
"/",
",",
"''",
")",
")",
"}",
"`",
";",
"const",
"destFilename",
"=",
"path",
".",
"join",
"(",
"packagePath",
",",
"'dist'",
",",
"`",
"${",
"destBasename",
"}",
"`",
")",
";",
"console",
".",
"log",
"(",
"`",
"${",
"destFilename",
".",
"replace",
"(",
"process",
".",
"cwd",
"(",
")",
"+",
"'/'",
",",
"''",
")",
"}",
"`",
")",
";",
"dts",
".",
"bundle",
"(",
"{",
"name",
",",
"main",
",",
"out",
":",
"destFilename",
",",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Imports all files in index.d.ts and compiles a bundled .d.ts file for UMD bundles.
|
[
"Imports",
"all",
"files",
"in",
"index",
".",
"d",
".",
"ts",
"and",
"compiles",
"a",
"bundled",
".",
"d",
".",
"ts",
"file",
"for",
"UMD",
"bundles",
"."
] |
9f8b9ae5103ff86de4f6a5cb02e700d6eb851e5f
|
https://github.com/material-components/material-components-web/blob/9f8b9ae5103ff86de4f6a5cb02e700d6eb851e5f/scripts/cp-pkgs.js#L112-L129
|
train
|
material-components/material-components-web
|
scripts/verify-pkg-main.js
|
verifyPath
|
function verifyPath(packageJson, jsonPath, packagePropertyKey) {
const isAtRoot = packagePropertyKey === 'module';
const packageJsonPropPath = path.join(path.dirname(jsonPath), packageJson[packagePropertyKey]);
let isInvalid = false;
if (!isAtRoot && packageJsonPropPath.indexOf('dist') === -1) {
isInvalid = true;
logError(`${jsonPath} ${packagePropertyKey} property does not reference a file under dist`);
} else if (isAtRoot && packageJsonPropPath.indexOf('dist') !== -1) {
isInvalid = true;
logError(`${jsonPath} ${packagePropertyKey} property should not reference a file under dist`);
}
if (!fs.existsSync(packageJsonPropPath)) {
isInvalid = true;
logError(`${jsonPath} ${packagePropertyKey} property points to nonexistent ${packageJsonPropPath}`);
}
if (isInvalid) {
// Multiple checks could have failed, but only increment the counter once for one package.
switch (packagePropertyKey) {
case 'main':
invalidMains++;
break;
case 'module':
invalidModules++;
break;
case 'types':
invalidTypes++;
break;
}
}
}
|
javascript
|
function verifyPath(packageJson, jsonPath, packagePropertyKey) {
const isAtRoot = packagePropertyKey === 'module';
const packageJsonPropPath = path.join(path.dirname(jsonPath), packageJson[packagePropertyKey]);
let isInvalid = false;
if (!isAtRoot && packageJsonPropPath.indexOf('dist') === -1) {
isInvalid = true;
logError(`${jsonPath} ${packagePropertyKey} property does not reference a file under dist`);
} else if (isAtRoot && packageJsonPropPath.indexOf('dist') !== -1) {
isInvalid = true;
logError(`${jsonPath} ${packagePropertyKey} property should not reference a file under dist`);
}
if (!fs.existsSync(packageJsonPropPath)) {
isInvalid = true;
logError(`${jsonPath} ${packagePropertyKey} property points to nonexistent ${packageJsonPropPath}`);
}
if (isInvalid) {
// Multiple checks could have failed, but only increment the counter once for one package.
switch (packagePropertyKey) {
case 'main':
invalidMains++;
break;
case 'module':
invalidModules++;
break;
case 'types':
invalidTypes++;
break;
}
}
}
|
[
"function",
"verifyPath",
"(",
"packageJson",
",",
"jsonPath",
",",
"packagePropertyKey",
")",
"{",
"const",
"isAtRoot",
"=",
"packagePropertyKey",
"===",
"'module'",
";",
"const",
"packageJsonPropPath",
"=",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"jsonPath",
")",
",",
"packageJson",
"[",
"packagePropertyKey",
"]",
")",
";",
"let",
"isInvalid",
"=",
"false",
";",
"if",
"(",
"!",
"isAtRoot",
"&&",
"packageJsonPropPath",
".",
"indexOf",
"(",
"'dist'",
")",
"===",
"-",
"1",
")",
"{",
"isInvalid",
"=",
"true",
";",
"logError",
"(",
"`",
"${",
"jsonPath",
"}",
"${",
"packagePropertyKey",
"}",
"`",
")",
";",
"}",
"else",
"if",
"(",
"isAtRoot",
"&&",
"packageJsonPropPath",
".",
"indexOf",
"(",
"'dist'",
")",
"!==",
"-",
"1",
")",
"{",
"isInvalid",
"=",
"true",
";",
"logError",
"(",
"`",
"${",
"jsonPath",
"}",
"${",
"packagePropertyKey",
"}",
"`",
")",
";",
"}",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"packageJsonPropPath",
")",
")",
"{",
"isInvalid",
"=",
"true",
";",
"logError",
"(",
"`",
"${",
"jsonPath",
"}",
"${",
"packagePropertyKey",
"}",
"${",
"packageJsonPropPath",
"}",
"`",
")",
";",
"}",
"if",
"(",
"isInvalid",
")",
"{",
"switch",
"(",
"packagePropertyKey",
")",
"{",
"case",
"'main'",
":",
"invalidMains",
"++",
";",
"break",
";",
"case",
"'module'",
":",
"invalidModules",
"++",
";",
"break",
";",
"case",
"'types'",
":",
"invalidTypes",
"++",
";",
"break",
";",
"}",
"}",
"}"
] |
Verifies that a file exists at the `packagePropertyKey`. If it does not
this function will log an error to the console.
@param {object} packageJson package.json in JSON format
@param {string} jsonPath filepath (relative to the root directory) to a component's package.json
@param {string} packagePropertyKey property key of package.json
|
[
"Verifies",
"that",
"a",
"file",
"exists",
"at",
"the",
"packagePropertyKey",
".",
"If",
"it",
"does",
"not",
"this",
"function",
"will",
"log",
"an",
"error",
"to",
"the",
"console",
"."
] |
9f8b9ae5103ff86de4f6a5cb02e700d6eb851e5f
|
https://github.com/material-components/material-components-web/blob/9f8b9ae5103ff86de4f6a5cb02e700d6eb851e5f/scripts/verify-pkg-main.js#L37-L68
|
train
|
airyland/vux
|
src/components/video/zy.media.js
|
timeFormat
|
function timeFormat(time, options) {
// Video's duration is Infinity in GiONEE(金立) device
if (!isFinite(time) || time < 0) {
time = 0;
}
// Get hours
var _time = options.alwaysShowHours ? [0] : [];
if (Math.floor(time / 3600) % 24) {
_time.push(Math.floor(time / 3600) % 24)
}
// Get minutes
_time.push(Math.floor(time / 60) % 60);
// Get seconds
_time.push(Math.floor(time % 60));
_time = _time.join(':');
// Fill '0'
if (options.timeFormatType == 1) {
_time = _time.replace(/(:|^)([0-9])(?=:|$)/g, '$10$2')
}
return _time
}
|
javascript
|
function timeFormat(time, options) {
// Video's duration is Infinity in GiONEE(金立) device
if (!isFinite(time) || time < 0) {
time = 0;
}
// Get hours
var _time = options.alwaysShowHours ? [0] : [];
if (Math.floor(time / 3600) % 24) {
_time.push(Math.floor(time / 3600) % 24)
}
// Get minutes
_time.push(Math.floor(time / 60) % 60);
// Get seconds
_time.push(Math.floor(time % 60));
_time = _time.join(':');
// Fill '0'
if (options.timeFormatType == 1) {
_time = _time.replace(/(:|^)([0-9])(?=:|$)/g, '$10$2')
}
return _time
}
|
[
"function",
"timeFormat",
"(",
"time",
",",
"options",
")",
"{",
"if",
"(",
"!",
"isFinite",
"(",
"time",
")",
"||",
"time",
"<",
"0",
")",
"{",
"time",
"=",
"0",
";",
"}",
"var",
"_time",
"=",
"options",
".",
"alwaysShowHours",
"?",
"[",
"0",
"]",
":",
"[",
"]",
";",
"if",
"(",
"Math",
".",
"floor",
"(",
"time",
"/",
"3600",
")",
"%",
"24",
")",
"{",
"_time",
".",
"push",
"(",
"Math",
".",
"floor",
"(",
"time",
"/",
"3600",
")",
"%",
"24",
")",
"}",
"_time",
".",
"push",
"(",
"Math",
".",
"floor",
"(",
"time",
"/",
"60",
")",
"%",
"60",
")",
";",
"_time",
".",
"push",
"(",
"Math",
".",
"floor",
"(",
"time",
"%",
"60",
")",
")",
";",
"_time",
"=",
"_time",
".",
"join",
"(",
"':'",
")",
";",
"if",
"(",
"options",
".",
"timeFormatType",
"==",
"1",
")",
"{",
"_time",
"=",
"_time",
".",
"replace",
"(",
"/",
"(:|^)([0-9])(?=:|$)",
"/",
"g",
",",
"'$10$2'",
")",
"}",
"return",
"_time",
"}"
] |
Get time format
|
[
"Get",
"time",
"format"
] |
484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6
|
https://github.com/airyland/vux/blob/484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6/src/components/video/zy.media.js#L138-L159
|
train
|
airyland/vux
|
src/components/video/zy.media.js
|
getTypeFromFileExtension
|
function getTypeFromFileExtension(url) {
url = url.toLowerCase().split('?')[0];
var _ext = url.substring(url.lastIndexOf('.') + 1);
var _av = /mp4|m4v|ogg|ogv|m3u8|webm|webmv|wmv|mpeg|mov/gi.test(_ext) ? 'video/' : 'audio/';
switch (_ext) {
case 'mp4':
case 'm4v':
case 'm4a':
return _av + 'mp4';
case 'webm':
case 'webma':
case 'webmv':
return _av + 'webm';
case 'ogg':
case 'oga':
case 'ogv':
return _av + 'ogg';
case 'm3u8':
return 'application/x-mpegurl';
case 'ts':
return _av + 'mp2t';
default:
return _av + _ext;
}
}
|
javascript
|
function getTypeFromFileExtension(url) {
url = url.toLowerCase().split('?')[0];
var _ext = url.substring(url.lastIndexOf('.') + 1);
var _av = /mp4|m4v|ogg|ogv|m3u8|webm|webmv|wmv|mpeg|mov/gi.test(_ext) ? 'video/' : 'audio/';
switch (_ext) {
case 'mp4':
case 'm4v':
case 'm4a':
return _av + 'mp4';
case 'webm':
case 'webma':
case 'webmv':
return _av + 'webm';
case 'ogg':
case 'oga':
case 'ogv':
return _av + 'ogg';
case 'm3u8':
return 'application/x-mpegurl';
case 'ts':
return _av + 'mp2t';
default:
return _av + _ext;
}
}
|
[
"function",
"getTypeFromFileExtension",
"(",
"url",
")",
"{",
"url",
"=",
"url",
".",
"toLowerCase",
"(",
")",
".",
"split",
"(",
"'?'",
")",
"[",
"0",
"]",
";",
"var",
"_ext",
"=",
"url",
".",
"substring",
"(",
"url",
".",
"lastIndexOf",
"(",
"'.'",
")",
"+",
"1",
")",
";",
"var",
"_av",
"=",
"/",
"mp4|m4v|ogg|ogv|m3u8|webm|webmv|wmv|mpeg|mov",
"/",
"gi",
".",
"test",
"(",
"_ext",
")",
"?",
"'video/'",
":",
"'audio/'",
";",
"switch",
"(",
"_ext",
")",
"{",
"case",
"'mp4'",
":",
"case",
"'m4v'",
":",
"case",
"'m4a'",
":",
"return",
"_av",
"+",
"'mp4'",
";",
"case",
"'webm'",
":",
"case",
"'webma'",
":",
"case",
"'webmv'",
":",
"return",
"_av",
"+",
"'webm'",
";",
"case",
"'ogg'",
":",
"case",
"'oga'",
":",
"case",
"'ogv'",
":",
"return",
"_av",
"+",
"'ogg'",
";",
"case",
"'m3u8'",
":",
"return",
"'application/x-mpegurl'",
";",
"case",
"'ts'",
":",
"return",
"_av",
"+",
"'mp2t'",
";",
"default",
":",
"return",
"_av",
"+",
"_ext",
";",
"}",
"}"
] |
Get media type from file extension
|
[
"Get",
"media",
"type",
"from",
"file",
"extension"
] |
484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6
|
https://github.com/airyland/vux/blob/484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6/src/components/video/zy.media.js#L167-L192
|
train
|
airyland/vux
|
src/components/video/zy.media.js
|
getType
|
function getType(url, type) {
// If no type is specified, try to get from the extension
if (url && !type) {
return getTypeFromFileExtension(url)
} else {
// Only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'))
} else {
return type
}
}
}
|
javascript
|
function getType(url, type) {
// If no type is specified, try to get from the extension
if (url && !type) {
return getTypeFromFileExtension(url)
} else {
// Only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'))
} else {
return type
}
}
}
|
[
"function",
"getType",
"(",
"url",
",",
"type",
")",
"{",
"if",
"(",
"url",
"&&",
"!",
"type",
")",
"{",
"return",
"getTypeFromFileExtension",
"(",
"url",
")",
"}",
"else",
"{",
"if",
"(",
"type",
"&&",
"~",
"type",
".",
"indexOf",
"(",
"';'",
")",
")",
"{",
"return",
"type",
".",
"substr",
"(",
"0",
",",
"type",
".",
"indexOf",
"(",
"';'",
")",
")",
"}",
"else",
"{",
"return",
"type",
"}",
"}",
"}"
] |
Get media type
|
[
"Get",
"media",
"type"
] |
484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6
|
https://github.com/airyland/vux/blob/484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6/src/components/video/zy.media.js#L195-L209
|
train
|
airyland/vux
|
src/components/video/zy.media.js
|
detectType
|
function detectType(media, options, src) {
var mediaFiles = [];
var i;
var n;
var isCanPlay;
// Get URL and type
if (options.type) {
// Accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({
type: options.type,
url: src
});
} else {
for (i = 0; i < options.type.length; i++) {
mediaFiles.push({
type: options.type[i],
url: src
});
}
}
} else if (src !== null) {
// If src attribute
mediaFiles.push({
type: getType(src, media.getAttribute('type')),
url: src
});
} else {
// If <source> elements
for (i = 0; i < media.children.length; i++) {
n = media.children[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
mediaFiles.push({
type: getType(src, n.getAttribute('type')),
url: src
});
}
}
}
// For Android which doesn't implement the canPlayType function (always returns '')
if (zyMedia.features.isBustedAndroid) {
media.canPlayType = function(type) {
return /video\/(mp4|m4v)/i.test(type) ? 'maybe' : ''
};
}
// For Chromium to specify natively supported video codecs (i.e. WebM and Theora)
if (zyMedia.features.isChromium) {
media.canPlayType = function(type) {
return /video\/(webm|ogv|ogg)/i.test(type) ? 'maybe' : ''
};
}
if (zyMedia.features.supportsCanPlayType) {
for (i = 0; i < mediaFiles.length; i++) {
// Normal detect
if (mediaFiles[i].type == "video/m3u8" || media.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// For Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| media.canPlayType(mediaFiles[i].type.replace(/mp3/, 'mpeg')).replace(/no/, '') !== ''
// For m4a supported by detecting mp4 support
|| media.canPlayType(mediaFiles[i].type.replace(/m4a/, 'mp4')).replace(/no/, '') !== '') {
isCanPlay = true;
break
}
}
}
return isCanPlay
}
|
javascript
|
function detectType(media, options, src) {
var mediaFiles = [];
var i;
var n;
var isCanPlay;
// Get URL and type
if (options.type) {
// Accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({
type: options.type,
url: src
});
} else {
for (i = 0; i < options.type.length; i++) {
mediaFiles.push({
type: options.type[i],
url: src
});
}
}
} else if (src !== null) {
// If src attribute
mediaFiles.push({
type: getType(src, media.getAttribute('type')),
url: src
});
} else {
// If <source> elements
for (i = 0; i < media.children.length; i++) {
n = media.children[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
mediaFiles.push({
type: getType(src, n.getAttribute('type')),
url: src
});
}
}
}
// For Android which doesn't implement the canPlayType function (always returns '')
if (zyMedia.features.isBustedAndroid) {
media.canPlayType = function(type) {
return /video\/(mp4|m4v)/i.test(type) ? 'maybe' : ''
};
}
// For Chromium to specify natively supported video codecs (i.e. WebM and Theora)
if (zyMedia.features.isChromium) {
media.canPlayType = function(type) {
return /video\/(webm|ogv|ogg)/i.test(type) ? 'maybe' : ''
};
}
if (zyMedia.features.supportsCanPlayType) {
for (i = 0; i < mediaFiles.length; i++) {
// Normal detect
if (mediaFiles[i].type == "video/m3u8" || media.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// For Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| media.canPlayType(mediaFiles[i].type.replace(/mp3/, 'mpeg')).replace(/no/, '') !== ''
// For m4a supported by detecting mp4 support
|| media.canPlayType(mediaFiles[i].type.replace(/m4a/, 'mp4')).replace(/no/, '') !== '') {
isCanPlay = true;
break
}
}
}
return isCanPlay
}
|
[
"function",
"detectType",
"(",
"media",
",",
"options",
",",
"src",
")",
"{",
"var",
"mediaFiles",
"=",
"[",
"]",
";",
"var",
"i",
";",
"var",
"n",
";",
"var",
"isCanPlay",
";",
"if",
"(",
"options",
".",
"type",
")",
"{",
"if",
"(",
"typeof",
"options",
".",
"type",
"==",
"'string'",
")",
"{",
"mediaFiles",
".",
"push",
"(",
"{",
"type",
":",
"options",
".",
"type",
",",
"url",
":",
"src",
"}",
")",
";",
"}",
"else",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"options",
".",
"type",
".",
"length",
";",
"i",
"++",
")",
"{",
"mediaFiles",
".",
"push",
"(",
"{",
"type",
":",
"options",
".",
"type",
"[",
"i",
"]",
",",
"url",
":",
"src",
"}",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"src",
"!==",
"null",
")",
"{",
"mediaFiles",
".",
"push",
"(",
"{",
"type",
":",
"getType",
"(",
"src",
",",
"media",
".",
"getAttribute",
"(",
"'type'",
")",
")",
",",
"url",
":",
"src",
"}",
")",
";",
"}",
"else",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"media",
".",
"children",
".",
"length",
";",
"i",
"++",
")",
"{",
"n",
"=",
"media",
".",
"children",
"[",
"i",
"]",
";",
"if",
"(",
"n",
".",
"nodeType",
"==",
"1",
"&&",
"n",
".",
"tagName",
".",
"toLowerCase",
"(",
")",
"==",
"'source'",
")",
"{",
"src",
"=",
"n",
".",
"getAttribute",
"(",
"'src'",
")",
";",
"mediaFiles",
".",
"push",
"(",
"{",
"type",
":",
"getType",
"(",
"src",
",",
"n",
".",
"getAttribute",
"(",
"'type'",
")",
")",
",",
"url",
":",
"src",
"}",
")",
";",
"}",
"}",
"}",
"if",
"(",
"zyMedia",
".",
"features",
".",
"isBustedAndroid",
")",
"{",
"media",
".",
"canPlayType",
"=",
"function",
"(",
"type",
")",
"{",
"return",
"/",
"video\\/(mp4|m4v)",
"/",
"i",
".",
"test",
"(",
"type",
")",
"?",
"'maybe'",
":",
"''",
"}",
";",
"}",
"if",
"(",
"zyMedia",
".",
"features",
".",
"isChromium",
")",
"{",
"media",
".",
"canPlayType",
"=",
"function",
"(",
"type",
")",
"{",
"return",
"/",
"video\\/(webm|ogv|ogg)",
"/",
"i",
".",
"test",
"(",
"type",
")",
"?",
"'maybe'",
":",
"''",
"}",
";",
"}",
"if",
"(",
"zyMedia",
".",
"features",
".",
"supportsCanPlayType",
")",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"mediaFiles",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"mediaFiles",
"[",
"i",
"]",
".",
"type",
"==",
"\"video/m3u8\"",
"||",
"media",
".",
"canPlayType",
"(",
"mediaFiles",
"[",
"i",
"]",
".",
"type",
")",
".",
"replace",
"(",
"/",
"no",
"/",
",",
"''",
")",
"!==",
"''",
"||",
"media",
".",
"canPlayType",
"(",
"mediaFiles",
"[",
"i",
"]",
".",
"type",
".",
"replace",
"(",
"/",
"mp3",
"/",
",",
"'mpeg'",
")",
")",
".",
"replace",
"(",
"/",
"no",
"/",
",",
"''",
")",
"!==",
"''",
"||",
"media",
".",
"canPlayType",
"(",
"mediaFiles",
"[",
"i",
"]",
".",
"type",
".",
"replace",
"(",
"/",
"m4a",
"/",
",",
"'mp4'",
")",
")",
".",
"replace",
"(",
"/",
"no",
"/",
",",
"''",
")",
"!==",
"''",
")",
"{",
"isCanPlay",
"=",
"true",
";",
"break",
"}",
"}",
"}",
"return",
"isCanPlay",
"}"
] |
Detect if current type is supported
|
[
"Detect",
"if",
"current",
"type",
"is",
"supported"
] |
484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6
|
https://github.com/airyland/vux/blob/484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6/src/components/video/zy.media.js#L212-L283
|
train
|
airyland/vux
|
src/components/range/lib/classes.js
|
ClassList
|
function ClassList (el) {
if (!el || !el.nodeType) {
throw new Error('A DOM element reference is required')
}
this.el = el
this.list = el.classList
}
|
javascript
|
function ClassList (el) {
if (!el || !el.nodeType) {
throw new Error('A DOM element reference is required')
}
this.el = el
this.list = el.classList
}
|
[
"function",
"ClassList",
"(",
"el",
")",
"{",
"if",
"(",
"!",
"el",
"||",
"!",
"el",
".",
"nodeType",
")",
"{",
"throw",
"new",
"Error",
"(",
"'A DOM element reference is required'",
")",
"}",
"this",
".",
"el",
"=",
"el",
"this",
".",
"list",
"=",
"el",
".",
"classList",
"}"
] |
Initialize a new ClassList for `el`.
@param {Element} el
@api private
|
[
"Initialize",
"a",
"new",
"ClassList",
"for",
"el",
"."
] |
484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6
|
https://github.com/airyland/vux/blob/484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6/src/components/range/lib/classes.js#L37-L43
|
train
|
airyland/vux
|
src/components/clocker/clocker.js
|
parseDateString
|
function parseDateString (dateString) {
// Pass through when a native object is sent
if (dateString instanceof Date) {
return dateString
}
// Caste string to date object
if (String(dateString).match(matchers)) {
// If looks like a milisecond value cast to number before
// final casting (Thanks to @msigley)
if (String(dateString).match(/^[0-9]*$/)) {
dateString = Number(dateString)
}
// Replace dashes to slashes
if (String(dateString).match(/-/)) {
dateString = String(dateString).replace(/-/g, '/')
}
return new Date(dateString)
} else {
throw new Error('Couldn\'t cast `' + dateString +
'` to a date object.')
}
}
|
javascript
|
function parseDateString (dateString) {
// Pass through when a native object is sent
if (dateString instanceof Date) {
return dateString
}
// Caste string to date object
if (String(dateString).match(matchers)) {
// If looks like a milisecond value cast to number before
// final casting (Thanks to @msigley)
if (String(dateString).match(/^[0-9]*$/)) {
dateString = Number(dateString)
}
// Replace dashes to slashes
if (String(dateString).match(/-/)) {
dateString = String(dateString).replace(/-/g, '/')
}
return new Date(dateString)
} else {
throw new Error('Couldn\'t cast `' + dateString +
'` to a date object.')
}
}
|
[
"function",
"parseDateString",
"(",
"dateString",
")",
"{",
"if",
"(",
"dateString",
"instanceof",
"Date",
")",
"{",
"return",
"dateString",
"}",
"if",
"(",
"String",
"(",
"dateString",
")",
".",
"match",
"(",
"matchers",
")",
")",
"{",
"if",
"(",
"String",
"(",
"dateString",
")",
".",
"match",
"(",
"/",
"^[0-9]*$",
"/",
")",
")",
"{",
"dateString",
"=",
"Number",
"(",
"dateString",
")",
"}",
"if",
"(",
"String",
"(",
"dateString",
")",
".",
"match",
"(",
"/",
"-",
"/",
")",
")",
"{",
"dateString",
"=",
"String",
"(",
"dateString",
")",
".",
"replace",
"(",
"/",
"-",
"/",
"g",
",",
"'/'",
")",
"}",
"return",
"new",
"Date",
"(",
"dateString",
")",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Couldn\\'t cast `'",
"+",
"\\'",
"+",
"dateString",
")",
"}",
"}"
] |
Parse a Date formatted has String to a native object
|
[
"Parse",
"a",
"Date",
"formatted",
"has",
"String",
"to",
"a",
"native",
"object"
] |
484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6
|
https://github.com/airyland/vux/blob/484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6/src/components/clocker/clocker.js#L19-L40
|
train
|
airyland/vux
|
src/components/clocker/clocker.js
|
strftime
|
function strftime (offsetObject) {
return function (format) {
var directives = format.match(/%(-|!)?[A-Z]{1}(:[^]+)?/gi)
var d2h = false
if (directives.indexOf('%D') < 0 && directives.indexOf('%H') >= 0) {
d2h = true
}
if (directives) {
for (var i = 0, len = directives.length; i < len; ++i) {
var directive = directives[i].match(/%(-|!)?([a-zA-Z]{1})(:[^]+)?/)
var regexp = escapedRegExp(directive[0])
var modifier = directive[1] || ''
var plural = directive[3] || ''
var value = null
var key = null
// Get the key
directive = directive[2]
// Swap shot-versions directives
if (DIRECTIVE_KEY_MAP.hasOwnProperty(directive)) {
key = DIRECTIVE_KEY_MAP[directive]
value = Number(offsetObject[key])
if (key === 'hours' && d2h) {
value += Number(offsetObject['days']) * 24
}
}
if (value !== null) {
// Pluralize
if (modifier === '!') {
value = pluralize(plural, value)
}
// Add zero-padding
if (modifier === '') {
if (value < 10) {
value = '0' + value.toString()
}
}
// Replace the directive
format = format.replace(regexp, value.toString())
}
}
}
format = format.replace('%_M1', offsetObject.minutes_1)
.replace('%_M2', offsetObject.minutes_2)
.replace('%_S1', offsetObject.seconds_1)
.replace('%_S2', offsetObject.seconds_2)
.replace('%_S3', offsetObject.seconds_3)
.replace('%_H1', offsetObject.hours_1)
.replace('%_H2', offsetObject.hours_2)
.replace('%_H3', offsetObject.hours_3)
.replace('%_D1', offsetObject.days_1)
.replace('%_D2', offsetObject.days_2)
.replace('%_D3', offsetObject.days_3)
format = format.replace(/%%/, '%')
return format
}
}
|
javascript
|
function strftime (offsetObject) {
return function (format) {
var directives = format.match(/%(-|!)?[A-Z]{1}(:[^]+)?/gi)
var d2h = false
if (directives.indexOf('%D') < 0 && directives.indexOf('%H') >= 0) {
d2h = true
}
if (directives) {
for (var i = 0, len = directives.length; i < len; ++i) {
var directive = directives[i].match(/%(-|!)?([a-zA-Z]{1})(:[^]+)?/)
var regexp = escapedRegExp(directive[0])
var modifier = directive[1] || ''
var plural = directive[3] || ''
var value = null
var key = null
// Get the key
directive = directive[2]
// Swap shot-versions directives
if (DIRECTIVE_KEY_MAP.hasOwnProperty(directive)) {
key = DIRECTIVE_KEY_MAP[directive]
value = Number(offsetObject[key])
if (key === 'hours' && d2h) {
value += Number(offsetObject['days']) * 24
}
}
if (value !== null) {
// Pluralize
if (modifier === '!') {
value = pluralize(plural, value)
}
// Add zero-padding
if (modifier === '') {
if (value < 10) {
value = '0' + value.toString()
}
}
// Replace the directive
format = format.replace(regexp, value.toString())
}
}
}
format = format.replace('%_M1', offsetObject.minutes_1)
.replace('%_M2', offsetObject.minutes_2)
.replace('%_S1', offsetObject.seconds_1)
.replace('%_S2', offsetObject.seconds_2)
.replace('%_S3', offsetObject.seconds_3)
.replace('%_H1', offsetObject.hours_1)
.replace('%_H2', offsetObject.hours_2)
.replace('%_H3', offsetObject.hours_3)
.replace('%_D1', offsetObject.days_1)
.replace('%_D2', offsetObject.days_2)
.replace('%_D3', offsetObject.days_3)
format = format.replace(/%%/, '%')
return format
}
}
|
[
"function",
"strftime",
"(",
"offsetObject",
")",
"{",
"return",
"function",
"(",
"format",
")",
"{",
"var",
"directives",
"=",
"format",
".",
"match",
"(",
"/",
"%(-|!)?[A-Z]{1}(:[^]+)?",
"/",
"gi",
")",
"var",
"d2h",
"=",
"false",
"if",
"(",
"directives",
".",
"indexOf",
"(",
"'%D'",
")",
"<",
"0",
"&&",
"directives",
".",
"indexOf",
"(",
"'%H'",
")",
">=",
"0",
")",
"{",
"d2h",
"=",
"true",
"}",
"if",
"(",
"directives",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"directives",
".",
"length",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"{",
"var",
"directive",
"=",
"directives",
"[",
"i",
"]",
".",
"match",
"(",
"/",
"%(-|!)?([a-zA-Z]{1})(:[^]+)?",
"/",
")",
"var",
"regexp",
"=",
"escapedRegExp",
"(",
"directive",
"[",
"0",
"]",
")",
"var",
"modifier",
"=",
"directive",
"[",
"1",
"]",
"||",
"''",
"var",
"plural",
"=",
"directive",
"[",
"3",
"]",
"||",
"''",
"var",
"value",
"=",
"null",
"var",
"key",
"=",
"null",
"directive",
"=",
"directive",
"[",
"2",
"]",
"if",
"(",
"DIRECTIVE_KEY_MAP",
".",
"hasOwnProperty",
"(",
"directive",
")",
")",
"{",
"key",
"=",
"DIRECTIVE_KEY_MAP",
"[",
"directive",
"]",
"value",
"=",
"Number",
"(",
"offsetObject",
"[",
"key",
"]",
")",
"if",
"(",
"key",
"===",
"'hours'",
"&&",
"d2h",
")",
"{",
"value",
"+=",
"Number",
"(",
"offsetObject",
"[",
"'days'",
"]",
")",
"*",
"24",
"}",
"}",
"if",
"(",
"value",
"!==",
"null",
")",
"{",
"if",
"(",
"modifier",
"===",
"'!'",
")",
"{",
"value",
"=",
"pluralize",
"(",
"plural",
",",
"value",
")",
"}",
"if",
"(",
"modifier",
"===",
"''",
")",
"{",
"if",
"(",
"value",
"<",
"10",
")",
"{",
"value",
"=",
"'0'",
"+",
"value",
".",
"toString",
"(",
")",
"}",
"}",
"format",
"=",
"format",
".",
"replace",
"(",
"regexp",
",",
"value",
".",
"toString",
"(",
")",
")",
"}",
"}",
"}",
"format",
"=",
"format",
".",
"replace",
"(",
"'%_M1'",
",",
"offsetObject",
".",
"minutes_1",
")",
".",
"replace",
"(",
"'%_M2'",
",",
"offsetObject",
".",
"minutes_2",
")",
".",
"replace",
"(",
"'%_S1'",
",",
"offsetObject",
".",
"seconds_1",
")",
".",
"replace",
"(",
"'%_S2'",
",",
"offsetObject",
".",
"seconds_2",
")",
".",
"replace",
"(",
"'%_S3'",
",",
"offsetObject",
".",
"seconds_3",
")",
".",
"replace",
"(",
"'%_H1'",
",",
"offsetObject",
".",
"hours_1",
")",
".",
"replace",
"(",
"'%_H2'",
",",
"offsetObject",
".",
"hours_2",
")",
".",
"replace",
"(",
"'%_H3'",
",",
"offsetObject",
".",
"hours_3",
")",
".",
"replace",
"(",
"'%_D1'",
",",
"offsetObject",
".",
"days_1",
")",
".",
"replace",
"(",
"'%_D2'",
",",
"offsetObject",
".",
"days_2",
")",
".",
"replace",
"(",
"'%_D3'",
",",
"offsetObject",
".",
"days_3",
")",
"format",
"=",
"format",
".",
"replace",
"(",
"/",
"%%",
"/",
",",
"'%'",
")",
"return",
"format",
"}",
"}"
] |
Time string formatter
|
[
"Time",
"string",
"formatter"
] |
484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6
|
https://github.com/airyland/vux/blob/484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6/src/components/clocker/clocker.js#L59-L114
|
train
|
airyland/vux
|
src/components/clocker/clocker.js
|
function (finalDate, option) {
option = option || {}
this.PRECISION = option.precision || 100 // 0.1 seconds, used to update the DOM
this.interval = null
this.offset = {}
// Register this instance
this.instanceNumber = instances.length
instances.push(this)
// Set the final date and start
this.setFinalDate(finalDate)
}
|
javascript
|
function (finalDate, option) {
option = option || {}
this.PRECISION = option.precision || 100 // 0.1 seconds, used to update the DOM
this.interval = null
this.offset = {}
// Register this instance
this.instanceNumber = instances.length
instances.push(this)
// Set the final date and start
this.setFinalDate(finalDate)
}
|
[
"function",
"(",
"finalDate",
",",
"option",
")",
"{",
"option",
"=",
"option",
"||",
"{",
"}",
"this",
".",
"PRECISION",
"=",
"option",
".",
"precision",
"||",
"100",
"this",
".",
"interval",
"=",
"null",
"this",
".",
"offset",
"=",
"{",
"}",
"this",
".",
"instanceNumber",
"=",
"instances",
".",
"length",
"instances",
".",
"push",
"(",
"this",
")",
"this",
".",
"setFinalDate",
"(",
"finalDate",
")",
"}"
] |
The Final Countdown
|
[
"The",
"Final",
"Countdown"
] |
484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6
|
https://github.com/airyland/vux/blob/484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6/src/components/clocker/clocker.js#L143-L153
|
train
|
|
airyland/vux
|
packages/loader/src/index.js
|
getBabelLoader
|
function getBabelLoader(projectRoot, name, isDev) {
name = name || 'vux'
if (!projectRoot) {
projectRoot = path.resolve(__dirname, '../../../')
if (/\.npm/.test(projectRoot)) {
projectRoot = path.resolve(projectRoot, '../../../')
}
}
let componentPath
let regex
if (!isDev) {
componentPath = fs.realpathSync(projectRoot + `/node_modules/${name}/`) // https://github.com/webpack/webpack/issues/1643
regex = new RegExp(`node_modules.*${name}.src.*?js$`)
} else {
componentPath = projectRoot
regex = new RegExp(`${projectRoot}.src.*?js$`)
}
return {
test: regex,
loader: 'babel-loader',
include: componentPath
}
}
|
javascript
|
function getBabelLoader(projectRoot, name, isDev) {
name = name || 'vux'
if (!projectRoot) {
projectRoot = path.resolve(__dirname, '../../../')
if (/\.npm/.test(projectRoot)) {
projectRoot = path.resolve(projectRoot, '../../../')
}
}
let componentPath
let regex
if (!isDev) {
componentPath = fs.realpathSync(projectRoot + `/node_modules/${name}/`) // https://github.com/webpack/webpack/issues/1643
regex = new RegExp(`node_modules.*${name}.src.*?js$`)
} else {
componentPath = projectRoot
regex = new RegExp(`${projectRoot}.src.*?js$`)
}
return {
test: regex,
loader: 'babel-loader',
include: componentPath
}
}
|
[
"function",
"getBabelLoader",
"(",
"projectRoot",
",",
"name",
",",
"isDev",
")",
"{",
"name",
"=",
"name",
"||",
"'vux'",
"if",
"(",
"!",
"projectRoot",
")",
"{",
"projectRoot",
"=",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"'../../../'",
")",
"if",
"(",
"/",
"\\.npm",
"/",
".",
"test",
"(",
"projectRoot",
")",
")",
"{",
"projectRoot",
"=",
"path",
".",
"resolve",
"(",
"projectRoot",
",",
"'../../../'",
")",
"}",
"}",
"let",
"componentPath",
"let",
"regex",
"if",
"(",
"!",
"isDev",
")",
"{",
"componentPath",
"=",
"fs",
".",
"realpathSync",
"(",
"projectRoot",
"+",
"`",
"${",
"name",
"}",
"`",
")",
"regex",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"name",
"}",
"`",
")",
"}",
"else",
"{",
"componentPath",
"=",
"projectRoot",
"regex",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"projectRoot",
"}",
"`",
")",
"}",
"return",
"{",
"test",
":",
"regex",
",",
"loader",
":",
"'babel-loader'",
",",
"include",
":",
"componentPath",
"}",
"}"
] |
use babel so component's js can be compiled
|
[
"use",
"babel",
"so",
"component",
"s",
"js",
"can",
"be",
"compiled"
] |
484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6
|
https://github.com/airyland/vux/blob/484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6/packages/loader/src/index.js#L589-L613
|
train
|
airyland/vux
|
src/components/range/lib/matches-selector.js
|
match
|
function match (el, selector) {
if (!el || el.nodeType !== 1) return false
if (vendor) return vendor.call(el, selector)
var nodes = all(selector, el.parentNode)
for (var i = 0; i < nodes.length; ++i) {
if (nodes[i] === el) return true
}
return false
}
|
javascript
|
function match (el, selector) {
if (!el || el.nodeType !== 1) return false
if (vendor) return vendor.call(el, selector)
var nodes = all(selector, el.parentNode)
for (var i = 0; i < nodes.length; ++i) {
if (nodes[i] === el) return true
}
return false
}
|
[
"function",
"match",
"(",
"el",
",",
"selector",
")",
"{",
"if",
"(",
"!",
"el",
"||",
"el",
".",
"nodeType",
"!==",
"1",
")",
"return",
"false",
"if",
"(",
"vendor",
")",
"return",
"vendor",
".",
"call",
"(",
"el",
",",
"selector",
")",
"var",
"nodes",
"=",
"all",
"(",
"selector",
",",
"el",
".",
"parentNode",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"nodes",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"nodes",
"[",
"i",
"]",
"===",
"el",
")",
"return",
"true",
"}",
"return",
"false",
"}"
] |
Match `el` to `selector`.
@param {Element} el
@param {String} selector
@return {Boolean}
@api public
|
[
"Match",
"el",
"to",
"selector",
"."
] |
484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6
|
https://github.com/airyland/vux/blob/484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6/src/components/range/lib/matches-selector.js#L38-L46
|
train
|
airyland/vux
|
src/components/range/lib/events.js
|
Events
|
function Events (el, obj) {
if (!(this instanceof Events)) return new Events(el, obj)
if (!el) throw new Error('element required')
if (!obj) throw new Error('object required')
this.el = el
this.obj = obj
this._events = {}
}
|
javascript
|
function Events (el, obj) {
if (!(this instanceof Events)) return new Events(el, obj)
if (!el) throw new Error('element required')
if (!obj) throw new Error('object required')
this.el = el
this.obj = obj
this._events = {}
}
|
[
"function",
"Events",
"(",
"el",
",",
"obj",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Events",
")",
")",
"return",
"new",
"Events",
"(",
"el",
",",
"obj",
")",
"if",
"(",
"!",
"el",
")",
"throw",
"new",
"Error",
"(",
"'element required'",
")",
"if",
"(",
"!",
"obj",
")",
"throw",
"new",
"Error",
"(",
"'object required'",
")",
"this",
".",
"el",
"=",
"el",
"this",
".",
"obj",
"=",
"obj",
"this",
".",
"_events",
"=",
"{",
"}",
"}"
] |
Initialize an `Events` with the given
`el` object which events will be bound to,
and the `obj` which will receive method calls.
@param {Object} el
@param {Object} obj
@api public
|
[
"Initialize",
"an",
"Events",
"with",
"the",
"given",
"el",
"object",
"which",
"events",
"will",
"be",
"bound",
"to",
"and",
"the",
"obj",
"which",
"will",
"receive",
"method",
"calls",
"."
] |
484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6
|
https://github.com/airyland/vux/blob/484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6/src/components/range/lib/events.js#L24-L31
|
train
|
airyland/vux
|
src/components/range/lib/events.js
|
parse
|
function parse (event) {
var parts = event.split(/ +/)
return {
name: parts.shift(),
selector: parts.join(' ')
}
}
|
javascript
|
function parse (event) {
var parts = event.split(/ +/)
return {
name: parts.shift(),
selector: parts.join(' ')
}
}
|
[
"function",
"parse",
"(",
"event",
")",
"{",
"var",
"parts",
"=",
"event",
".",
"split",
"(",
"/",
" +",
"/",
")",
"return",
"{",
"name",
":",
"parts",
".",
"shift",
"(",
")",
",",
"selector",
":",
"parts",
".",
"join",
"(",
"' '",
")",
"}",
"}"
] |
Parse `event`.
@param {String} event
@return {Object}
@api private
|
[
"Parse",
"event",
"."
] |
484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6
|
https://github.com/airyland/vux/blob/484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6/src/components/range/lib/events.js#L169-L175
|
train
|
ReactTraining/react-router
|
packages/react-router/modules/Prompt.js
|
Prompt
|
function Prompt({ message, when = true }) {
return (
<RouterContext.Consumer>
{context => {
invariant(context, "You should not use <Prompt> outside a <Router>");
if (!when || context.staticContext) return null;
const method = context.history.block;
return (
<Lifecycle
onMount={self => {
self.release = method(message);
}}
onUpdate={(self, prevProps) => {
if (prevProps.message !== message) {
self.release();
self.release = method(message);
}
}}
onUnmount={self => {
self.release();
}}
message={message}
/>
);
}}
</RouterContext.Consumer>
);
}
|
javascript
|
function Prompt({ message, when = true }) {
return (
<RouterContext.Consumer>
{context => {
invariant(context, "You should not use <Prompt> outside a <Router>");
if (!when || context.staticContext) return null;
const method = context.history.block;
return (
<Lifecycle
onMount={self => {
self.release = method(message);
}}
onUpdate={(self, prevProps) => {
if (prevProps.message !== message) {
self.release();
self.release = method(message);
}
}}
onUnmount={self => {
self.release();
}}
message={message}
/>
);
}}
</RouterContext.Consumer>
);
}
|
[
"function",
"Prompt",
"(",
"{",
"message",
",",
"when",
"=",
"true",
"}",
")",
"{",
"return",
"(",
"<",
"RouterContext",
".",
"Consumer",
">",
" ",
"{",
"context",
"=>",
"{",
"invariant",
"(",
"context",
",",
"\"You should not use <Prompt> outside a <Router>\"",
")",
";",
"if",
"(",
"!",
"when",
"||",
"context",
".",
"staticContext",
")",
"return",
"null",
";",
"const",
"method",
"=",
"context",
".",
"history",
".",
"block",
";",
"return",
"(",
"<",
"Lifecycle",
"onMount",
"=",
"{",
"self",
"=>",
"{",
"self",
".",
"release",
"=",
"method",
"(",
"message",
")",
";",
"}",
"}",
"onUpdate",
"=",
"{",
"(",
"self",
",",
"prevProps",
")",
"=>",
"{",
"if",
"(",
"prevProps",
".",
"message",
"!==",
"message",
")",
"{",
"self",
".",
"release",
"(",
")",
";",
"self",
".",
"release",
"=",
"method",
"(",
"message",
")",
";",
"}",
"}",
"}",
"onUnmount",
"=",
"{",
"self",
"=>",
"{",
"self",
".",
"release",
"(",
")",
";",
"}",
"}",
"message",
"=",
"{",
"message",
"}",
"/",
">",
")",
";",
"}",
"}",
" ",
"<",
"/",
"RouterContext",
".",
"Consumer",
">",
")",
";",
"}"
] |
The public API for prompting the user before navigating away from a screen.
|
[
"The",
"public",
"API",
"for",
"prompting",
"the",
"user",
"before",
"navigating",
"away",
"from",
"a",
"screen",
"."
] |
82ce94c3b4e74f71018d104df6dc999801fa9ab2
|
https://github.com/ReactTraining/react-router/blob/82ce94c3b4e74f71018d104df6dc999801fa9ab2/packages/react-router/modules/Prompt.js#L11-L41
|
train
|
ReactTraining/react-router
|
website/modules/components/Guide.js
|
Guide
|
function Guide({ match, data }) {
const {
params: { mod, header: headerParam, environment }
} = match;
const doc = data.guides.find(doc => mod === doc.title.slug);
const header =
doc && headerParam ? doc.headers.find(h => h.slug === headerParam) : null;
return !doc ? (
<Redirect to={`/${environment}`} />
) : (
<Block className="api-doc-wrapper" fontSize="80%">
<Block className="api-doc">
<ScrollToDoc doc={doc} header={header} />
<MarkdownViewer html={doc.markup} />
</Block>
<Route
path={`${match.path}/:header`}
render={({
match: {
params: { header: slug }
}
}) => {
const header = doc.headers.find(h => h.slug === slug);
return header ? (
<ScrollToDoc doc={doc} header={header} />
) : (
<Redirect to={`/${environment}/guides/${mod}`} />
);
}}
/>
</Block>
);
}
|
javascript
|
function Guide({ match, data }) {
const {
params: { mod, header: headerParam, environment }
} = match;
const doc = data.guides.find(doc => mod === doc.title.slug);
const header =
doc && headerParam ? doc.headers.find(h => h.slug === headerParam) : null;
return !doc ? (
<Redirect to={`/${environment}`} />
) : (
<Block className="api-doc-wrapper" fontSize="80%">
<Block className="api-doc">
<ScrollToDoc doc={doc} header={header} />
<MarkdownViewer html={doc.markup} />
</Block>
<Route
path={`${match.path}/:header`}
render={({
match: {
params: { header: slug }
}
}) => {
const header = doc.headers.find(h => h.slug === slug);
return header ? (
<ScrollToDoc doc={doc} header={header} />
) : (
<Redirect to={`/${environment}/guides/${mod}`} />
);
}}
/>
</Block>
);
}
|
[
"function",
"Guide",
"(",
"{",
"match",
",",
"data",
"}",
")",
"{",
"const",
"{",
"params",
":",
"{",
"mod",
",",
"header",
":",
"headerParam",
",",
"environment",
"}",
"}",
"=",
"match",
";",
"const",
"doc",
"=",
"data",
".",
"guides",
".",
"find",
"(",
"doc",
"=>",
"mod",
"===",
"doc",
".",
"title",
".",
"slug",
")",
";",
"const",
"header",
"=",
"doc",
"&&",
"headerParam",
"?",
"doc",
".",
"headers",
".",
"find",
"(",
"h",
"=>",
"h",
".",
"slug",
"===",
"headerParam",
")",
":",
"null",
";",
"return",
"!",
"doc",
"?",
"(",
"<",
"Redirect",
"to",
"=",
"{",
"`",
"${",
"environment",
"}",
"`",
"}",
"/",
">",
")",
":",
"(",
"<",
"Block",
"className",
"=",
"\"api-doc-wrapper\"",
"fontSize",
"=",
"\"80%\"",
">",
" ",
"<",
"Block",
"className",
"=",
"\"api-doc\"",
">",
" ",
"<",
"ScrollToDoc",
"doc",
"=",
"{",
"doc",
"}",
"header",
"=",
"{",
"header",
"}",
"/",
">",
" ",
"<",
"MarkdownViewer",
"html",
"=",
"{",
"doc",
".",
"markup",
"}",
"/",
">",
" ",
"<",
"/",
"Block",
">",
" ",
"<",
"Route",
"path",
"=",
"{",
"`",
"${",
"match",
".",
"path",
"}",
"`",
"}",
"render",
"=",
"{",
"(",
"{",
"match",
":",
"{",
"params",
":",
"{",
"header",
":",
"slug",
"}",
"}",
"}",
")",
"=>",
"{",
"const",
"header",
"=",
"doc",
".",
"headers",
".",
"find",
"(",
"h",
"=>",
"h",
".",
"slug",
"===",
"slug",
")",
";",
"return",
"header",
"?",
"(",
"<",
"ScrollToDoc",
"doc",
"=",
"{",
"doc",
"}",
"header",
"=",
"{",
"header",
"}",
"/",
">",
")",
":",
"(",
"<",
"Redirect",
"to",
"=",
"{",
"`",
"${",
"environment",
"}",
"${",
"mod",
"}",
"`",
"}",
"/",
">",
")",
";",
"}",
"}",
"/",
">",
" ",
"<",
"/",
"Block",
">",
")",
";",
"}"
] |
almost identical to `API`, but I'm lazy rn
|
[
"almost",
"identical",
"to",
"API",
"but",
"I",
"m",
"lazy",
"rn"
] |
82ce94c3b4e74f71018d104df6dc999801fa9ab2
|
https://github.com/ReactTraining/react-router/blob/82ce94c3b4e74f71018d104df6dc999801fa9ab2/website/modules/components/Guide.js#L10-L42
|
train
|
ReactTraining/react-router
|
packages/react-router/modules/generatePath.js
|
generatePath
|
function generatePath(path = "/", params = {}) {
return path === "/" ? path : compilePath(path)(params, { pretty: true });
}
|
javascript
|
function generatePath(path = "/", params = {}) {
return path === "/" ? path : compilePath(path)(params, { pretty: true });
}
|
[
"function",
"generatePath",
"(",
"path",
"=",
"\"/\"",
",",
"params",
"=",
"{",
"}",
")",
"{",
"return",
"path",
"===",
"\"/\"",
"?",
"path",
":",
"compilePath",
"(",
"path",
")",
"(",
"params",
",",
"{",
"pretty",
":",
"true",
"}",
")",
";",
"}"
] |
Public API for generating a URL pathname from a path and parameters.
|
[
"Public",
"API",
"for",
"generating",
"a",
"URL",
"pathname",
"from",
"a",
"path",
"and",
"parameters",
"."
] |
82ce94c3b4e74f71018d104df6dc999801fa9ab2
|
https://github.com/ReactTraining/react-router/blob/82ce94c3b4e74f71018d104df6dc999801fa9ab2/packages/react-router/modules/generatePath.js#L23-L25
|
train
|
ReactTraining/react-router
|
packages/react-router/modules/withRouter.js
|
withRouter
|
function withRouter(Component) {
const displayName = `withRouter(${Component.displayName || Component.name})`;
const C = props => {
const { wrappedComponentRef, ...remainingProps } = props;
return (
<RouterContext.Consumer>
{context => {
invariant(
context,
`You should not use <${displayName} /> outside a <Router>`
);
return (
<Component
{...remainingProps}
{...context}
ref={wrappedComponentRef}
/>
);
}}
</RouterContext.Consumer>
);
};
C.displayName = displayName;
C.WrappedComponent = Component;
if (__DEV__) {
C.propTypes = {
wrappedComponentRef: PropTypes.func
};
}
return hoistStatics(C, Component);
}
|
javascript
|
function withRouter(Component) {
const displayName = `withRouter(${Component.displayName || Component.name})`;
const C = props => {
const { wrappedComponentRef, ...remainingProps } = props;
return (
<RouterContext.Consumer>
{context => {
invariant(
context,
`You should not use <${displayName} /> outside a <Router>`
);
return (
<Component
{...remainingProps}
{...context}
ref={wrappedComponentRef}
/>
);
}}
</RouterContext.Consumer>
);
};
C.displayName = displayName;
C.WrappedComponent = Component;
if (__DEV__) {
C.propTypes = {
wrappedComponentRef: PropTypes.func
};
}
return hoistStatics(C, Component);
}
|
[
"function",
"withRouter",
"(",
"Component",
")",
"{",
"const",
"displayName",
"=",
"`",
"${",
"Component",
".",
"displayName",
"||",
"Component",
".",
"name",
"}",
"`",
";",
"const",
"C",
"=",
"props",
"=>",
"{",
"const",
"{",
"wrappedComponentRef",
",",
"...",
"remainingProps",
"}",
"=",
"props",
";",
"return",
"(",
"<",
"RouterContext",
".",
"Consumer",
">",
" ",
"{",
"context",
"=>",
"{",
"invariant",
"(",
"context",
",",
"`",
"${",
"displayName",
"}",
"`",
")",
";",
"return",
"(",
"<",
"Component",
"{",
"...",
"remainingProps",
"}",
"{",
"...",
"context",
"}",
"ref",
"=",
"{",
"wrappedComponentRef",
"}",
"/",
">",
")",
";",
"}",
"}",
" ",
"<",
"/",
"RouterContext",
".",
"Consumer",
">",
")",
";",
"}",
";",
"C",
".",
"displayName",
"=",
"displayName",
";",
"C",
".",
"WrappedComponent",
"=",
"Component",
";",
"if",
"(",
"__DEV__",
")",
"{",
"C",
".",
"propTypes",
"=",
"{",
"wrappedComponentRef",
":",
"PropTypes",
".",
"func",
"}",
";",
"}",
"return",
"hoistStatics",
"(",
"C",
",",
"Component",
")",
";",
"}"
] |
A public higher-order component to access the imperative API
|
[
"A",
"public",
"higher",
"-",
"order",
"component",
"to",
"access",
"the",
"imperative",
"API"
] |
82ce94c3b4e74f71018d104df6dc999801fa9ab2
|
https://github.com/ReactTraining/react-router/blob/82ce94c3b4e74f71018d104df6dc999801fa9ab2/packages/react-router/modules/withRouter.js#L10-L44
|
train
|
artf/grapesjs
|
src/commands/index.js
|
function(id, obj) {
if (isFunction(obj)) obj = { run: obj };
if (!obj.stop) obj.noStop = 1;
delete obj.initialize;
obj.id = id;
commands[id] = CommandAbstract.extend(obj);
return this;
}
|
javascript
|
function(id, obj) {
if (isFunction(obj)) obj = { run: obj };
if (!obj.stop) obj.noStop = 1;
delete obj.initialize;
obj.id = id;
commands[id] = CommandAbstract.extend(obj);
return this;
}
|
[
"function",
"(",
"id",
",",
"obj",
")",
"{",
"if",
"(",
"isFunction",
"(",
"obj",
")",
")",
"obj",
"=",
"{",
"run",
":",
"obj",
"}",
";",
"if",
"(",
"!",
"obj",
".",
"stop",
")",
"obj",
".",
"noStop",
"=",
"1",
";",
"delete",
"obj",
".",
"initialize",
";",
"obj",
".",
"id",
"=",
"id",
";",
"commands",
"[",
"id",
"]",
"=",
"CommandAbstract",
".",
"extend",
"(",
"obj",
")",
";",
"return",
"this",
";",
"}"
] |
Need it here as it would be used below
|
[
"Need",
"it",
"here",
"as",
"it",
"would",
"be",
"used",
"below"
] |
3f053af969ef6a688d526d158b9df7e6aa076838
|
https://github.com/artf/grapesjs/blob/3f053af969ef6a688d526d158b9df7e6aa076838/src/commands/index.js#L42-L49
|
train
|
|
tensorflow/tfjs-models
|
posenet/demos/demo_util.js
|
drawPoints
|
function drawPoints(ctx, points, radius, color) {
const data = points.buffer().values;
for (let i = 0; i < data.length; i += 2) {
const pointY = data[i];
const pointX = data[i + 1];
if (pointX !== 0 && pointY !== 0) {
ctx.beginPath();
ctx.arc(pointX, pointY, radius, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
}
}
}
|
javascript
|
function drawPoints(ctx, points, radius, color) {
const data = points.buffer().values;
for (let i = 0; i < data.length; i += 2) {
const pointY = data[i];
const pointX = data[i + 1];
if (pointX !== 0 && pointY !== 0) {
ctx.beginPath();
ctx.arc(pointX, pointY, radius, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
}
}
}
|
[
"function",
"drawPoints",
"(",
"ctx",
",",
"points",
",",
"radius",
",",
"color",
")",
"{",
"const",
"data",
"=",
"points",
".",
"buffer",
"(",
")",
".",
"values",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"data",
".",
"length",
";",
"i",
"+=",
"2",
")",
"{",
"const",
"pointY",
"=",
"data",
"[",
"i",
"]",
";",
"const",
"pointX",
"=",
"data",
"[",
"i",
"+",
"1",
"]",
";",
"if",
"(",
"pointX",
"!==",
"0",
"&&",
"pointY",
"!==",
"0",
")",
"{",
"ctx",
".",
"beginPath",
"(",
")",
";",
"ctx",
".",
"arc",
"(",
"pointX",
",",
"pointY",
",",
"radius",
",",
"0",
",",
"2",
"*",
"Math",
".",
"PI",
")",
";",
"ctx",
".",
"fillStyle",
"=",
"color",
";",
"ctx",
".",
"fill",
"(",
")",
";",
"}",
"}",
"}"
] |
Used by the drawHeatMapValues method to draw heatmap points on to
the canvas
|
[
"Used",
"by",
"the",
"drawHeatMapValues",
"method",
"to",
"draw",
"heatmap",
"points",
"on",
"to",
"the",
"canvas"
] |
af194797c90cc5bcac1060d3cd41b0258a34c7dc
|
https://github.com/tensorflow/tfjs-models/blob/af194797c90cc5bcac1060d3cd41b0258a34c7dc/posenet/demos/demo_util.js#L143-L157
|
train
|
tensorflow/tfjs-models
|
body-pix/demos/index.js
|
setupFPS
|
function setupFPS() {
stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
if (guiState.showFps) {
document.body.appendChild(stats.dom);
}
}
|
javascript
|
function setupFPS() {
stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
if (guiState.showFps) {
document.body.appendChild(stats.dom);
}
}
|
[
"function",
"setupFPS",
"(",
")",
"{",
"stats",
".",
"showPanel",
"(",
"0",
")",
";",
"if",
"(",
"guiState",
".",
"showFps",
")",
"{",
"document",
".",
"body",
".",
"appendChild",
"(",
"stats",
".",
"dom",
")",
";",
"}",
"}"
] |
Sets up a frames per second panel on the top-left of the window
|
[
"Sets",
"up",
"a",
"frames",
"per",
"second",
"panel",
"on",
"the",
"top",
"-",
"left",
"of",
"the",
"window"
] |
af194797c90cc5bcac1060d3cd41b0258a34c7dc
|
https://github.com/tensorflow/tfjs-models/blob/af194797c90cc5bcac1060d3cd41b0258a34c7dc/body-pix/demos/index.js#L342-L347
|
train
|
tensorflow/tfjs-models
|
body-pix/demos/index.js
|
segmentBodyInRealTime
|
function segmentBodyInRealTime() {
const canvas = document.getElementById('output');
// since images are being fed from a webcam
async function bodySegmentationFrame() {
// if changing the model or the camera, wait a second for it to complete
// then try again.
if (state.changingArchitecture || state.changingCamera) {
setTimeout(bodySegmentationFrame, 1000);
return;
}
// Begin monitoring code for frames per second
stats.begin();
// Scale an image down to a certain factor. Too large of an image will
// slow down the GPU
const outputStride = +guiState.input.outputStride;
const flipHorizontally = guiState.flipHorizontal;
switch (guiState.estimate) {
case 'segmentation':
const personSegmentation = await state.net.estimatePersonSegmentation(
state.video, outputStride,
guiState.segmentation.segmentationThreshold);
switch (guiState.segmentation.effect) {
case 'mask':
const mask = bodyPix.toMaskImageData(
personSegmentation, guiState.segmentation.maskBackground);
bodyPix.drawMask(
canvas, state.video, mask, guiState.segmentation.opacity,
guiState.segmentation.maskBlurAmount, flipHorizontally);
break;
case 'bokeh':
bodyPix.drawBokehEffect(
canvas, state.video, personSegmentation,
+guiState.segmentation.backgroundBlurAmount,
guiState.segmentation.edgeBlurAmount, flipHorizontally);
break;
}
break;
case 'partmap':
const partSegmentation = await state.net.estimatePartSegmentation(
state.video, outputStride, guiState.partMap.segmentationThreshold);
const coloredPartImageData = bodyPix.toColoredPartImageData(
partSegmentation, partColorScales[guiState.partMap.colorScale]);
const maskBlurAmount = 0;
if (guiState.partMap.applyPixelation) {
const pixelCellWidth = 10.0;
bodyPix.drawPixelatedMask(
canvas, video, coloredPartImageData, guiState.partMap.opacity,
maskBlurAmount, flipHorizontally, pixelCellWidth);
} else {
bodyPix.drawMask(
canvas, video, coloredPartImageData, guiState.opacity,
maskBlurAmount, flipHorizontally);
}
break;
default:
break;
}
// End monitoring code for frames per second
stats.end();
requestAnimationFrame(bodySegmentationFrame);
}
bodySegmentationFrame();
}
|
javascript
|
function segmentBodyInRealTime() {
const canvas = document.getElementById('output');
// since images are being fed from a webcam
async function bodySegmentationFrame() {
// if changing the model or the camera, wait a second for it to complete
// then try again.
if (state.changingArchitecture || state.changingCamera) {
setTimeout(bodySegmentationFrame, 1000);
return;
}
// Begin monitoring code for frames per second
stats.begin();
// Scale an image down to a certain factor. Too large of an image will
// slow down the GPU
const outputStride = +guiState.input.outputStride;
const flipHorizontally = guiState.flipHorizontal;
switch (guiState.estimate) {
case 'segmentation':
const personSegmentation = await state.net.estimatePersonSegmentation(
state.video, outputStride,
guiState.segmentation.segmentationThreshold);
switch (guiState.segmentation.effect) {
case 'mask':
const mask = bodyPix.toMaskImageData(
personSegmentation, guiState.segmentation.maskBackground);
bodyPix.drawMask(
canvas, state.video, mask, guiState.segmentation.opacity,
guiState.segmentation.maskBlurAmount, flipHorizontally);
break;
case 'bokeh':
bodyPix.drawBokehEffect(
canvas, state.video, personSegmentation,
+guiState.segmentation.backgroundBlurAmount,
guiState.segmentation.edgeBlurAmount, flipHorizontally);
break;
}
break;
case 'partmap':
const partSegmentation = await state.net.estimatePartSegmentation(
state.video, outputStride, guiState.partMap.segmentationThreshold);
const coloredPartImageData = bodyPix.toColoredPartImageData(
partSegmentation, partColorScales[guiState.partMap.colorScale]);
const maskBlurAmount = 0;
if (guiState.partMap.applyPixelation) {
const pixelCellWidth = 10.0;
bodyPix.drawPixelatedMask(
canvas, video, coloredPartImageData, guiState.partMap.opacity,
maskBlurAmount, flipHorizontally, pixelCellWidth);
} else {
bodyPix.drawMask(
canvas, video, coloredPartImageData, guiState.opacity,
maskBlurAmount, flipHorizontally);
}
break;
default:
break;
}
// End monitoring code for frames per second
stats.end();
requestAnimationFrame(bodySegmentationFrame);
}
bodySegmentationFrame();
}
|
[
"function",
"segmentBodyInRealTime",
"(",
")",
"{",
"const",
"canvas",
"=",
"document",
".",
"getElementById",
"(",
"'output'",
")",
";",
"async",
"function",
"bodySegmentationFrame",
"(",
")",
"{",
"if",
"(",
"state",
".",
"changingArchitecture",
"||",
"state",
".",
"changingCamera",
")",
"{",
"setTimeout",
"(",
"bodySegmentationFrame",
",",
"1000",
")",
";",
"return",
";",
"}",
"stats",
".",
"begin",
"(",
")",
";",
"const",
"outputStride",
"=",
"+",
"guiState",
".",
"input",
".",
"outputStride",
";",
"const",
"flipHorizontally",
"=",
"guiState",
".",
"flipHorizontal",
";",
"switch",
"(",
"guiState",
".",
"estimate",
")",
"{",
"case",
"'segmentation'",
":",
"const",
"personSegmentation",
"=",
"await",
"state",
".",
"net",
".",
"estimatePersonSegmentation",
"(",
"state",
".",
"video",
",",
"outputStride",
",",
"guiState",
".",
"segmentation",
".",
"segmentationThreshold",
")",
";",
"switch",
"(",
"guiState",
".",
"segmentation",
".",
"effect",
")",
"{",
"case",
"'mask'",
":",
"const",
"mask",
"=",
"bodyPix",
".",
"toMaskImageData",
"(",
"personSegmentation",
",",
"guiState",
".",
"segmentation",
".",
"maskBackground",
")",
";",
"bodyPix",
".",
"drawMask",
"(",
"canvas",
",",
"state",
".",
"video",
",",
"mask",
",",
"guiState",
".",
"segmentation",
".",
"opacity",
",",
"guiState",
".",
"segmentation",
".",
"maskBlurAmount",
",",
"flipHorizontally",
")",
";",
"break",
";",
"case",
"'bokeh'",
":",
"bodyPix",
".",
"drawBokehEffect",
"(",
"canvas",
",",
"state",
".",
"video",
",",
"personSegmentation",
",",
"+",
"guiState",
".",
"segmentation",
".",
"backgroundBlurAmount",
",",
"guiState",
".",
"segmentation",
".",
"edgeBlurAmount",
",",
"flipHorizontally",
")",
";",
"break",
";",
"}",
"break",
";",
"case",
"'partmap'",
":",
"const",
"partSegmentation",
"=",
"await",
"state",
".",
"net",
".",
"estimatePartSegmentation",
"(",
"state",
".",
"video",
",",
"outputStride",
",",
"guiState",
".",
"partMap",
".",
"segmentationThreshold",
")",
";",
"const",
"coloredPartImageData",
"=",
"bodyPix",
".",
"toColoredPartImageData",
"(",
"partSegmentation",
",",
"partColorScales",
"[",
"guiState",
".",
"partMap",
".",
"colorScale",
"]",
")",
";",
"const",
"maskBlurAmount",
"=",
"0",
";",
"if",
"(",
"guiState",
".",
"partMap",
".",
"applyPixelation",
")",
"{",
"const",
"pixelCellWidth",
"=",
"10.0",
";",
"bodyPix",
".",
"drawPixelatedMask",
"(",
"canvas",
",",
"video",
",",
"coloredPartImageData",
",",
"guiState",
".",
"partMap",
".",
"opacity",
",",
"maskBlurAmount",
",",
"flipHorizontally",
",",
"pixelCellWidth",
")",
";",
"}",
"else",
"{",
"bodyPix",
".",
"drawMask",
"(",
"canvas",
",",
"video",
",",
"coloredPartImageData",
",",
"guiState",
".",
"opacity",
",",
"maskBlurAmount",
",",
"flipHorizontally",
")",
";",
"}",
"break",
";",
"default",
":",
"break",
";",
"}",
"stats",
".",
"end",
"(",
")",
";",
"requestAnimationFrame",
"(",
"bodySegmentationFrame",
")",
";",
"}",
"bodySegmentationFrame",
"(",
")",
";",
"}"
] |
Feeds an image to BodyPix to estimate segmentation - this is where the
magic happens. This function loops with a requestAnimationFrame method.
|
[
"Feeds",
"an",
"image",
"to",
"BodyPix",
"to",
"estimate",
"segmentation",
"-",
"this",
"is",
"where",
"the",
"magic",
"happens",
".",
"This",
"function",
"loops",
"with",
"a",
"requestAnimationFrame",
"method",
"."
] |
af194797c90cc5bcac1060d3cd41b0258a34c7dc
|
https://github.com/tensorflow/tfjs-models/blob/af194797c90cc5bcac1060d3cd41b0258a34c7dc/body-pix/demos/index.js#L353-L429
|
train
|
tensorflow/tfjs-models
|
speech-commands/demo/dataset-vis.js
|
getCanvasClickRelativeXCoordinate
|
function getCanvasClickRelativeXCoordinate(canvasElement, event) {
let x;
if (event.pageX) {
x = event.pageX;
} else {
x = event.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
}
x -= canvasElement.offsetLeft;
return x / canvasElement.width;
}
|
javascript
|
function getCanvasClickRelativeXCoordinate(canvasElement, event) {
let x;
if (event.pageX) {
x = event.pageX;
} else {
x = event.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
}
x -= canvasElement.offsetLeft;
return x / canvasElement.width;
}
|
[
"function",
"getCanvasClickRelativeXCoordinate",
"(",
"canvasElement",
",",
"event",
")",
"{",
"let",
"x",
";",
"if",
"(",
"event",
".",
"pageX",
")",
"{",
"x",
"=",
"event",
".",
"pageX",
";",
"}",
"else",
"{",
"x",
"=",
"event",
".",
"clientX",
"+",
"document",
".",
"body",
".",
"scrollLeft",
"+",
"document",
".",
"documentElement",
".",
"scrollLeft",
";",
"}",
"x",
"-=",
"canvasElement",
".",
"offsetLeft",
";",
"return",
"x",
"/",
"canvasElement",
".",
"width",
";",
"}"
] |
Get the relative x-coordinate of a click event in a canvas.
@param {HTMLCanvasElement} canvasElement The canvas in which the click
event happened.
@param {Event} event The click event object.
@return {number} The relative x-coordinate: a `number` between 0 and 1.
|
[
"Get",
"the",
"relative",
"x",
"-",
"coordinate",
"of",
"a",
"click",
"event",
"in",
"a",
"canvas",
"."
] |
af194797c90cc5bcac1060d3cd41b0258a34c7dc
|
https://github.com/tensorflow/tfjs-models/blob/af194797c90cc5bcac1060d3cd41b0258a34c7dc/speech-commands/demo/dataset-vis.js#L41-L51
|
train
|
tensorflow/tfjs-models
|
posenet/demos/coco.js
|
drawResults
|
function drawResults(canvas, poses, minPartConfidence, minPoseConfidence) {
renderImageToCanvas(image, [513, 513], canvas);
poses.forEach((pose) => {
if (pose.score >= minPoseConfidence) {
if (guiState.showKeypoints) {
drawKeypoints(
pose.keypoints, minPartConfidence, canvas.getContext('2d'));
}
if (guiState.showSkeleton) {
drawSkeleton(
pose.keypoints, minPartConfidence, canvas.getContext('2d'));
}
if (guiState.showBoundingBox) {
drawBoundingBox(pose.keypoints, canvas.getContext('2d'));
}
}
});
}
|
javascript
|
function drawResults(canvas, poses, minPartConfidence, minPoseConfidence) {
renderImageToCanvas(image, [513, 513], canvas);
poses.forEach((pose) => {
if (pose.score >= minPoseConfidence) {
if (guiState.showKeypoints) {
drawKeypoints(
pose.keypoints, minPartConfidence, canvas.getContext('2d'));
}
if (guiState.showSkeleton) {
drawSkeleton(
pose.keypoints, minPartConfidence, canvas.getContext('2d'));
}
if (guiState.showBoundingBox) {
drawBoundingBox(pose.keypoints, canvas.getContext('2d'));
}
}
});
}
|
[
"function",
"drawResults",
"(",
"canvas",
",",
"poses",
",",
"minPartConfidence",
",",
"minPoseConfidence",
")",
"{",
"renderImageToCanvas",
"(",
"image",
",",
"[",
"513",
",",
"513",
"]",
",",
"canvas",
")",
";",
"poses",
".",
"forEach",
"(",
"(",
"pose",
")",
"=>",
"{",
"if",
"(",
"pose",
".",
"score",
">=",
"minPoseConfidence",
")",
"{",
"if",
"(",
"guiState",
".",
"showKeypoints",
")",
"{",
"drawKeypoints",
"(",
"pose",
".",
"keypoints",
",",
"minPartConfidence",
",",
"canvas",
".",
"getContext",
"(",
"'2d'",
")",
")",
";",
"}",
"if",
"(",
"guiState",
".",
"showSkeleton",
")",
"{",
"drawSkeleton",
"(",
"pose",
".",
"keypoints",
",",
"minPartConfidence",
",",
"canvas",
".",
"getContext",
"(",
"'2d'",
")",
")",
";",
"}",
"if",
"(",
"guiState",
".",
"showBoundingBox",
")",
"{",
"drawBoundingBox",
"(",
"pose",
".",
"keypoints",
",",
"canvas",
".",
"getContext",
"(",
"'2d'",
")",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] |
Draws a pose if it passes a minimum confidence onto a canvas.
Only the pose's keypoints that pass a minPartConfidence are drawn.
|
[
"Draws",
"a",
"pose",
"if",
"it",
"passes",
"a",
"minimum",
"confidence",
"onto",
"a",
"canvas",
".",
"Only",
"the",
"pose",
"s",
"keypoints",
"that",
"pass",
"a",
"minPartConfidence",
"are",
"drawn",
"."
] |
af194797c90cc5bcac1060d3cd41b0258a34c7dc
|
https://github.com/tensorflow/tfjs-models/blob/af194797c90cc5bcac1060d3cd41b0258a34c7dc/posenet/demos/coco.js#L67-L86
|
train
|
tensorflow/tfjs-models
|
posenet/demos/coco.js
|
drawSinglePoseResults
|
function drawSinglePoseResults(pose) {
const canvas = singlePersonCanvas();
drawResults(
canvas, [pose], guiState.singlePoseDetection.minPartConfidence,
guiState.singlePoseDetection.minPoseConfidence);
const {part, showHeatmap, showOffsets} = guiState.visualizeOutputs;
// displacements not used for single pose decoding
const showDisplacements = false;
const partId = +part;
visualizeOutputs(
partId, showHeatmap, showOffsets, showDisplacements,
canvas.getContext('2d'));
}
|
javascript
|
function drawSinglePoseResults(pose) {
const canvas = singlePersonCanvas();
drawResults(
canvas, [pose], guiState.singlePoseDetection.minPartConfidence,
guiState.singlePoseDetection.minPoseConfidence);
const {part, showHeatmap, showOffsets} = guiState.visualizeOutputs;
// displacements not used for single pose decoding
const showDisplacements = false;
const partId = +part;
visualizeOutputs(
partId, showHeatmap, showOffsets, showDisplacements,
canvas.getContext('2d'));
}
|
[
"function",
"drawSinglePoseResults",
"(",
"pose",
")",
"{",
"const",
"canvas",
"=",
"singlePersonCanvas",
"(",
")",
";",
"drawResults",
"(",
"canvas",
",",
"[",
"pose",
"]",
",",
"guiState",
".",
"singlePoseDetection",
".",
"minPartConfidence",
",",
"guiState",
".",
"singlePoseDetection",
".",
"minPoseConfidence",
")",
";",
"const",
"{",
"part",
",",
"showHeatmap",
",",
"showOffsets",
"}",
"=",
"guiState",
".",
"visualizeOutputs",
";",
"const",
"showDisplacements",
"=",
"false",
";",
"const",
"partId",
"=",
"+",
"part",
";",
"visualizeOutputs",
"(",
"partId",
",",
"showHeatmap",
",",
"showOffsets",
",",
"showDisplacements",
",",
"canvas",
".",
"getContext",
"(",
"'2d'",
")",
")",
";",
"}"
] |
Draw the results from the single-pose estimation on to a canvas
|
[
"Draw",
"the",
"results",
"from",
"the",
"single",
"-",
"pose",
"estimation",
"on",
"to",
"a",
"canvas"
] |
af194797c90cc5bcac1060d3cd41b0258a34c7dc
|
https://github.com/tensorflow/tfjs-models/blob/af194797c90cc5bcac1060d3cd41b0258a34c7dc/posenet/demos/coco.js#L115-L129
|
train
|
tensorflow/tfjs-models
|
posenet/demos/coco.js
|
drawMultiplePosesResults
|
function drawMultiplePosesResults(poses) {
const canvas = multiPersonCanvas();
drawResults(
canvas, poses, guiState.multiPoseDetection.minPartConfidence,
guiState.multiPoseDetection.minPoseConfidence);
const {part, showHeatmap, showOffsets, showDisplacements} =
guiState.visualizeOutputs;
const partId = +part;
visualizeOutputs(
partId, showHeatmap, showOffsets, showDisplacements,
canvas.getContext('2d'));
}
|
javascript
|
function drawMultiplePosesResults(poses) {
const canvas = multiPersonCanvas();
drawResults(
canvas, poses, guiState.multiPoseDetection.minPartConfidence,
guiState.multiPoseDetection.minPoseConfidence);
const {part, showHeatmap, showOffsets, showDisplacements} =
guiState.visualizeOutputs;
const partId = +part;
visualizeOutputs(
partId, showHeatmap, showOffsets, showDisplacements,
canvas.getContext('2d'));
}
|
[
"function",
"drawMultiplePosesResults",
"(",
"poses",
")",
"{",
"const",
"canvas",
"=",
"multiPersonCanvas",
"(",
")",
";",
"drawResults",
"(",
"canvas",
",",
"poses",
",",
"guiState",
".",
"multiPoseDetection",
".",
"minPartConfidence",
",",
"guiState",
".",
"multiPoseDetection",
".",
"minPoseConfidence",
")",
";",
"const",
"{",
"part",
",",
"showHeatmap",
",",
"showOffsets",
",",
"showDisplacements",
"}",
"=",
"guiState",
".",
"visualizeOutputs",
";",
"const",
"partId",
"=",
"+",
"part",
";",
"visualizeOutputs",
"(",
"partId",
",",
"showHeatmap",
",",
"showOffsets",
",",
"showDisplacements",
",",
"canvas",
".",
"getContext",
"(",
"'2d'",
")",
")",
";",
"}"
] |
Draw the results from the multi-pose estimation on to a canvas
|
[
"Draw",
"the",
"results",
"from",
"the",
"multi",
"-",
"pose",
"estimation",
"on",
"to",
"a",
"canvas"
] |
af194797c90cc5bcac1060d3cd41b0258a34c7dc
|
https://github.com/tensorflow/tfjs-models/blob/af194797c90cc5bcac1060d3cd41b0258a34c7dc/posenet/demos/coco.js#L134-L147
|
train
|
tensorflow/tfjs-models
|
posenet/demos/coco.js
|
visualizeOutputs
|
function visualizeOutputs(
partId, drawHeatmaps, drawOffsetVectors, drawDisplacements, ctx) {
const {heatmapScores, offsets, displacementFwd, displacementBwd} =
modelOutputs;
const outputStride = +guiState.outputStride;
const [height, width] = heatmapScores.shape;
ctx.globalAlpha = 0;
const heatmapScoresArr = heatmapScores.arraySync();
const offsetsArr = offsets.arraySync();
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const score = heatmapScoresArr[y][x][partId];
// to save on performance, don't draw anything with a low score.
if (score < 0.05) continue;
// set opacity of drawn elements based on the score
ctx.globalAlpha = score;
if (drawHeatmaps) {
drawPoint(ctx, y * outputStride, x * outputStride, 2, 'yellow');
}
const offsetsVectorY = offsetsArr[y][x][partId];
const offsetsVectorX = offsetsArr[y][x][partId + 17];
if (drawOffsetVectors) {
drawOffsetVector(
ctx, y, x, outputStride, offsetsVectorY, offsetsVectorX);
}
if (drawDisplacements) {
// exponentially affect the alpha of the displacements;
ctx.globalAlpha *= score;
drawDisplacementEdgesFrom(
ctx, partId, displacementFwd, outputStride, parentToChildEdges, y,
x, offsetsVectorY, offsetsVectorX);
drawDisplacementEdgesFrom(
ctx, partId, displacementBwd, outputStride, childToParentEdges, y,
x, offsetsVectorY, offsetsVectorX);
}
}
ctx.globalAlpha = 1;
}
}
|
javascript
|
function visualizeOutputs(
partId, drawHeatmaps, drawOffsetVectors, drawDisplacements, ctx) {
const {heatmapScores, offsets, displacementFwd, displacementBwd} =
modelOutputs;
const outputStride = +guiState.outputStride;
const [height, width] = heatmapScores.shape;
ctx.globalAlpha = 0;
const heatmapScoresArr = heatmapScores.arraySync();
const offsetsArr = offsets.arraySync();
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const score = heatmapScoresArr[y][x][partId];
// to save on performance, don't draw anything with a low score.
if (score < 0.05) continue;
// set opacity of drawn elements based on the score
ctx.globalAlpha = score;
if (drawHeatmaps) {
drawPoint(ctx, y * outputStride, x * outputStride, 2, 'yellow');
}
const offsetsVectorY = offsetsArr[y][x][partId];
const offsetsVectorX = offsetsArr[y][x][partId + 17];
if (drawOffsetVectors) {
drawOffsetVector(
ctx, y, x, outputStride, offsetsVectorY, offsetsVectorX);
}
if (drawDisplacements) {
// exponentially affect the alpha of the displacements;
ctx.globalAlpha *= score;
drawDisplacementEdgesFrom(
ctx, partId, displacementFwd, outputStride, parentToChildEdges, y,
x, offsetsVectorY, offsetsVectorX);
drawDisplacementEdgesFrom(
ctx, partId, displacementBwd, outputStride, childToParentEdges, y,
x, offsetsVectorY, offsetsVectorX);
}
}
ctx.globalAlpha = 1;
}
}
|
[
"function",
"visualizeOutputs",
"(",
"partId",
",",
"drawHeatmaps",
",",
"drawOffsetVectors",
",",
"drawDisplacements",
",",
"ctx",
")",
"{",
"const",
"{",
"heatmapScores",
",",
"offsets",
",",
"displacementFwd",
",",
"displacementBwd",
"}",
"=",
"modelOutputs",
";",
"const",
"outputStride",
"=",
"+",
"guiState",
".",
"outputStride",
";",
"const",
"[",
"height",
",",
"width",
"]",
"=",
"heatmapScores",
".",
"shape",
";",
"ctx",
".",
"globalAlpha",
"=",
"0",
";",
"const",
"heatmapScoresArr",
"=",
"heatmapScores",
".",
"arraySync",
"(",
")",
";",
"const",
"offsetsArr",
"=",
"offsets",
".",
"arraySync",
"(",
")",
";",
"for",
"(",
"let",
"y",
"=",
"0",
";",
"y",
"<",
"height",
";",
"y",
"++",
")",
"{",
"for",
"(",
"let",
"x",
"=",
"0",
";",
"x",
"<",
"width",
";",
"x",
"++",
")",
"{",
"const",
"score",
"=",
"heatmapScoresArr",
"[",
"y",
"]",
"[",
"x",
"]",
"[",
"partId",
"]",
";",
"if",
"(",
"score",
"<",
"0.05",
")",
"continue",
";",
"ctx",
".",
"globalAlpha",
"=",
"score",
";",
"if",
"(",
"drawHeatmaps",
")",
"{",
"drawPoint",
"(",
"ctx",
",",
"y",
"*",
"outputStride",
",",
"x",
"*",
"outputStride",
",",
"2",
",",
"'yellow'",
")",
";",
"}",
"const",
"offsetsVectorY",
"=",
"offsetsArr",
"[",
"y",
"]",
"[",
"x",
"]",
"[",
"partId",
"]",
";",
"const",
"offsetsVectorX",
"=",
"offsetsArr",
"[",
"y",
"]",
"[",
"x",
"]",
"[",
"partId",
"+",
"17",
"]",
";",
"if",
"(",
"drawOffsetVectors",
")",
"{",
"drawOffsetVector",
"(",
"ctx",
",",
"y",
",",
"x",
",",
"outputStride",
",",
"offsetsVectorY",
",",
"offsetsVectorX",
")",
";",
"}",
"if",
"(",
"drawDisplacements",
")",
"{",
"ctx",
".",
"globalAlpha",
"*=",
"score",
";",
"drawDisplacementEdgesFrom",
"(",
"ctx",
",",
"partId",
",",
"displacementFwd",
",",
"outputStride",
",",
"parentToChildEdges",
",",
"y",
",",
"x",
",",
"offsetsVectorY",
",",
"offsetsVectorX",
")",
";",
"drawDisplacementEdgesFrom",
"(",
"ctx",
",",
"partId",
",",
"displacementBwd",
",",
"outputStride",
",",
"childToParentEdges",
",",
"y",
",",
"x",
",",
"offsetsVectorY",
",",
"offsetsVectorX",
")",
";",
"}",
"}",
"ctx",
".",
"globalAlpha",
"=",
"1",
";",
"}",
"}"
] |
Visualizes the outputs from the model which are used for decoding poses.
Limited to visualizing the outputs for a single part.
@param partId The id of the part to visualize
|
[
"Visualizes",
"the",
"outputs",
"from",
"the",
"model",
"which",
"are",
"used",
"for",
"decoding",
"poses",
".",
"Limited",
"to",
"visualizing",
"the",
"outputs",
"for",
"a",
"single",
"part",
"."
] |
af194797c90cc5bcac1060d3cd41b0258a34c7dc
|
https://github.com/tensorflow/tfjs-models/blob/af194797c90cc5bcac1060d3cd41b0258a34c7dc/posenet/demos/coco.js#L227-L277
|
train
|
tensorflow/tfjs-models
|
posenet/demos/coco.js
|
decodeSinglePoseAndDrawResults
|
async function decodeSinglePoseAndDrawResults() {
if (!modelOutputs) {
return;
}
const pose = await posenet.decodeSinglePose(
modelOutputs.heatmapScores, modelOutputs.offsets, guiState.outputStride);
drawSinglePoseResults(pose);
}
|
javascript
|
async function decodeSinglePoseAndDrawResults() {
if (!modelOutputs) {
return;
}
const pose = await posenet.decodeSinglePose(
modelOutputs.heatmapScores, modelOutputs.offsets, guiState.outputStride);
drawSinglePoseResults(pose);
}
|
[
"async",
"function",
"decodeSinglePoseAndDrawResults",
"(",
")",
"{",
"if",
"(",
"!",
"modelOutputs",
")",
"{",
"return",
";",
"}",
"const",
"pose",
"=",
"await",
"posenet",
".",
"decodeSinglePose",
"(",
"modelOutputs",
".",
"heatmapScores",
",",
"modelOutputs",
".",
"offsets",
",",
"guiState",
".",
"outputStride",
")",
";",
"drawSinglePoseResults",
"(",
"pose",
")",
";",
"}"
] |
Converts the raw model output results into single-pose estimation results
|
[
"Converts",
"the",
"raw",
"model",
"output",
"results",
"into",
"single",
"-",
"pose",
"estimation",
"results"
] |
af194797c90cc5bcac1060d3cd41b0258a34c7dc
|
https://github.com/tensorflow/tfjs-models/blob/af194797c90cc5bcac1060d3cd41b0258a34c7dc/posenet/demos/coco.js#L282-L291
|
train
|
tensorflow/tfjs-models
|
posenet/demos/coco.js
|
decodeMultiplePosesAndDrawResults
|
async function decodeMultiplePosesAndDrawResults() {
if (!modelOutputs) {
return;
}
const poses = await posenet.decodeMultiplePoses(
modelOutputs.heatmapScores, modelOutputs.offsets,
modelOutputs.displacementFwd, modelOutputs.displacementBwd,
guiState.outputStride, guiState.multiPoseDetection.maxDetections,
guiState.multiPoseDetection);
drawMultiplePosesResults(poses);
}
|
javascript
|
async function decodeMultiplePosesAndDrawResults() {
if (!modelOutputs) {
return;
}
const poses = await posenet.decodeMultiplePoses(
modelOutputs.heatmapScores, modelOutputs.offsets,
modelOutputs.displacementFwd, modelOutputs.displacementBwd,
guiState.outputStride, guiState.multiPoseDetection.maxDetections,
guiState.multiPoseDetection);
drawMultiplePosesResults(poses);
}
|
[
"async",
"function",
"decodeMultiplePosesAndDrawResults",
"(",
")",
"{",
"if",
"(",
"!",
"modelOutputs",
")",
"{",
"return",
";",
"}",
"const",
"poses",
"=",
"await",
"posenet",
".",
"decodeMultiplePoses",
"(",
"modelOutputs",
".",
"heatmapScores",
",",
"modelOutputs",
".",
"offsets",
",",
"modelOutputs",
".",
"displacementFwd",
",",
"modelOutputs",
".",
"displacementBwd",
",",
"guiState",
".",
"outputStride",
",",
"guiState",
".",
"multiPoseDetection",
".",
"maxDetections",
",",
"guiState",
".",
"multiPoseDetection",
")",
";",
"drawMultiplePosesResults",
"(",
"poses",
")",
";",
"}"
] |
Converts the raw model output results into multi-pose estimation results
|
[
"Converts",
"the",
"raw",
"model",
"output",
"results",
"into",
"multi",
"-",
"pose",
"estimation",
"results"
] |
af194797c90cc5bcac1060d3cd41b0258a34c7dc
|
https://github.com/tensorflow/tfjs-models/blob/af194797c90cc5bcac1060d3cd41b0258a34c7dc/posenet/demos/coco.js#L296-L308
|
train
|
tensorflow/tfjs-models
|
posenet/demos/camera.js
|
detectPoseInRealTime
|
function detectPoseInRealTime(video, net) {
const canvas = document.getElementById('output');
const ctx = canvas.getContext('2d');
// since images are being fed from a webcam
const flipHorizontal = true;
canvas.width = videoWidth;
canvas.height = videoHeight;
async function poseDetectionFrame() {
if (guiState.changeToArchitecture) {
// Important to purge variables and free up GPU memory
guiState.net.dispose();
// Load the PoseNet model weights for either the 0.50, 0.75, 1.00, or 1.01
// version
guiState.net = await posenet.load(+guiState.changeToArchitecture);
guiState.changeToArchitecture = null;
}
// Begin monitoring code for frames per second
stats.begin();
// Scale an image down to a certain factor. Too large of an image will slow
// down the GPU
const imageScaleFactor = guiState.input.imageScaleFactor;
const outputStride = +guiState.input.outputStride;
let poses = [];
let minPoseConfidence;
let minPartConfidence;
switch (guiState.algorithm) {
case 'single-pose':
const pose = await guiState.net.estimateSinglePose(
video, imageScaleFactor, flipHorizontal, outputStride);
poses.push(pose);
minPoseConfidence = +guiState.singlePoseDetection.minPoseConfidence;
minPartConfidence = +guiState.singlePoseDetection.minPartConfidence;
break;
case 'multi-pose':
poses = await guiState.net.estimateMultiplePoses(
video, imageScaleFactor, flipHorizontal, outputStride,
guiState.multiPoseDetection.maxPoseDetections,
guiState.multiPoseDetection.minPartConfidence,
guiState.multiPoseDetection.nmsRadius);
minPoseConfidence = +guiState.multiPoseDetection.minPoseConfidence;
minPartConfidence = +guiState.multiPoseDetection.minPartConfidence;
break;
}
ctx.clearRect(0, 0, videoWidth, videoHeight);
if (guiState.output.showVideo) {
ctx.save();
ctx.scale(-1, 1);
ctx.translate(-videoWidth, 0);
ctx.drawImage(video, 0, 0, videoWidth, videoHeight);
ctx.restore();
}
// For each pose (i.e. person) detected in an image, loop through the poses
// and draw the resulting skeleton and keypoints if over certain confidence
// scores
poses.forEach(({score, keypoints}) => {
if (score >= minPoseConfidence) {
if (guiState.output.showPoints) {
drawKeypoints(keypoints, minPartConfidence, ctx);
}
if (guiState.output.showSkeleton) {
drawSkeleton(keypoints, minPartConfidence, ctx);
}
if (guiState.output.showBoundingBox) {
drawBoundingBox(keypoints, ctx);
}
}
});
// End monitoring code for frames per second
stats.end();
requestAnimationFrame(poseDetectionFrame);
}
poseDetectionFrame();
}
|
javascript
|
function detectPoseInRealTime(video, net) {
const canvas = document.getElementById('output');
const ctx = canvas.getContext('2d');
// since images are being fed from a webcam
const flipHorizontal = true;
canvas.width = videoWidth;
canvas.height = videoHeight;
async function poseDetectionFrame() {
if (guiState.changeToArchitecture) {
// Important to purge variables and free up GPU memory
guiState.net.dispose();
// Load the PoseNet model weights for either the 0.50, 0.75, 1.00, or 1.01
// version
guiState.net = await posenet.load(+guiState.changeToArchitecture);
guiState.changeToArchitecture = null;
}
// Begin monitoring code for frames per second
stats.begin();
// Scale an image down to a certain factor. Too large of an image will slow
// down the GPU
const imageScaleFactor = guiState.input.imageScaleFactor;
const outputStride = +guiState.input.outputStride;
let poses = [];
let minPoseConfidence;
let minPartConfidence;
switch (guiState.algorithm) {
case 'single-pose':
const pose = await guiState.net.estimateSinglePose(
video, imageScaleFactor, flipHorizontal, outputStride);
poses.push(pose);
minPoseConfidence = +guiState.singlePoseDetection.minPoseConfidence;
minPartConfidence = +guiState.singlePoseDetection.minPartConfidence;
break;
case 'multi-pose':
poses = await guiState.net.estimateMultiplePoses(
video, imageScaleFactor, flipHorizontal, outputStride,
guiState.multiPoseDetection.maxPoseDetections,
guiState.multiPoseDetection.minPartConfidence,
guiState.multiPoseDetection.nmsRadius);
minPoseConfidence = +guiState.multiPoseDetection.minPoseConfidence;
minPartConfidence = +guiState.multiPoseDetection.minPartConfidence;
break;
}
ctx.clearRect(0, 0, videoWidth, videoHeight);
if (guiState.output.showVideo) {
ctx.save();
ctx.scale(-1, 1);
ctx.translate(-videoWidth, 0);
ctx.drawImage(video, 0, 0, videoWidth, videoHeight);
ctx.restore();
}
// For each pose (i.e. person) detected in an image, loop through the poses
// and draw the resulting skeleton and keypoints if over certain confidence
// scores
poses.forEach(({score, keypoints}) => {
if (score >= minPoseConfidence) {
if (guiState.output.showPoints) {
drawKeypoints(keypoints, minPartConfidence, ctx);
}
if (guiState.output.showSkeleton) {
drawSkeleton(keypoints, minPartConfidence, ctx);
}
if (guiState.output.showBoundingBox) {
drawBoundingBox(keypoints, ctx);
}
}
});
// End monitoring code for frames per second
stats.end();
requestAnimationFrame(poseDetectionFrame);
}
poseDetectionFrame();
}
|
[
"function",
"detectPoseInRealTime",
"(",
"video",
",",
"net",
")",
"{",
"const",
"canvas",
"=",
"document",
".",
"getElementById",
"(",
"'output'",
")",
";",
"const",
"ctx",
"=",
"canvas",
".",
"getContext",
"(",
"'2d'",
")",
";",
"const",
"flipHorizontal",
"=",
"true",
";",
"canvas",
".",
"width",
"=",
"videoWidth",
";",
"canvas",
".",
"height",
"=",
"videoHeight",
";",
"async",
"function",
"poseDetectionFrame",
"(",
")",
"{",
"if",
"(",
"guiState",
".",
"changeToArchitecture",
")",
"{",
"guiState",
".",
"net",
".",
"dispose",
"(",
")",
";",
"guiState",
".",
"net",
"=",
"await",
"posenet",
".",
"load",
"(",
"+",
"guiState",
".",
"changeToArchitecture",
")",
";",
"guiState",
".",
"changeToArchitecture",
"=",
"null",
";",
"}",
"stats",
".",
"begin",
"(",
")",
";",
"const",
"imageScaleFactor",
"=",
"guiState",
".",
"input",
".",
"imageScaleFactor",
";",
"const",
"outputStride",
"=",
"+",
"guiState",
".",
"input",
".",
"outputStride",
";",
"let",
"poses",
"=",
"[",
"]",
";",
"let",
"minPoseConfidence",
";",
"let",
"minPartConfidence",
";",
"switch",
"(",
"guiState",
".",
"algorithm",
")",
"{",
"case",
"'single-pose'",
":",
"const",
"pose",
"=",
"await",
"guiState",
".",
"net",
".",
"estimateSinglePose",
"(",
"video",
",",
"imageScaleFactor",
",",
"flipHorizontal",
",",
"outputStride",
")",
";",
"poses",
".",
"push",
"(",
"pose",
")",
";",
"minPoseConfidence",
"=",
"+",
"guiState",
".",
"singlePoseDetection",
".",
"minPoseConfidence",
";",
"minPartConfidence",
"=",
"+",
"guiState",
".",
"singlePoseDetection",
".",
"minPartConfidence",
";",
"break",
";",
"case",
"'multi-pose'",
":",
"poses",
"=",
"await",
"guiState",
".",
"net",
".",
"estimateMultiplePoses",
"(",
"video",
",",
"imageScaleFactor",
",",
"flipHorizontal",
",",
"outputStride",
",",
"guiState",
".",
"multiPoseDetection",
".",
"maxPoseDetections",
",",
"guiState",
".",
"multiPoseDetection",
".",
"minPartConfidence",
",",
"guiState",
".",
"multiPoseDetection",
".",
"nmsRadius",
")",
";",
"minPoseConfidence",
"=",
"+",
"guiState",
".",
"multiPoseDetection",
".",
"minPoseConfidence",
";",
"minPartConfidence",
"=",
"+",
"guiState",
".",
"multiPoseDetection",
".",
"minPartConfidence",
";",
"break",
";",
"}",
"ctx",
".",
"clearRect",
"(",
"0",
",",
"0",
",",
"videoWidth",
",",
"videoHeight",
")",
";",
"if",
"(",
"guiState",
".",
"output",
".",
"showVideo",
")",
"{",
"ctx",
".",
"save",
"(",
")",
";",
"ctx",
".",
"scale",
"(",
"-",
"1",
",",
"1",
")",
";",
"ctx",
".",
"translate",
"(",
"-",
"videoWidth",
",",
"0",
")",
";",
"ctx",
".",
"drawImage",
"(",
"video",
",",
"0",
",",
"0",
",",
"videoWidth",
",",
"videoHeight",
")",
";",
"ctx",
".",
"restore",
"(",
")",
";",
"}",
"poses",
".",
"forEach",
"(",
"(",
"{",
"score",
",",
"keypoints",
"}",
")",
"=>",
"{",
"if",
"(",
"score",
">=",
"minPoseConfidence",
")",
"{",
"if",
"(",
"guiState",
".",
"output",
".",
"showPoints",
")",
"{",
"drawKeypoints",
"(",
"keypoints",
",",
"minPartConfidence",
",",
"ctx",
")",
";",
"}",
"if",
"(",
"guiState",
".",
"output",
".",
"showSkeleton",
")",
"{",
"drawSkeleton",
"(",
"keypoints",
",",
"minPartConfidence",
",",
"ctx",
")",
";",
"}",
"if",
"(",
"guiState",
".",
"output",
".",
"showBoundingBox",
")",
"{",
"drawBoundingBox",
"(",
"keypoints",
",",
"ctx",
")",
";",
"}",
"}",
"}",
")",
";",
"stats",
".",
"end",
"(",
")",
";",
"requestAnimationFrame",
"(",
"poseDetectionFrame",
")",
";",
"}",
"poseDetectionFrame",
"(",
")",
";",
"}"
] |
Feeds an image to posenet to estimate poses - this is where the magic
happens. This function loops with a requestAnimationFrame method.
|
[
"Feeds",
"an",
"image",
"to",
"posenet",
"to",
"estimate",
"poses",
"-",
"this",
"is",
"where",
"the",
"magic",
"happens",
".",
"This",
"function",
"loops",
"with",
"a",
"requestAnimationFrame",
"method",
"."
] |
af194797c90cc5bcac1060d3cd41b0258a34c7dc
|
https://github.com/tensorflow/tfjs-models/blob/af194797c90cc5bcac1060d3cd41b0258a34c7dc/posenet/demos/camera.js#L199-L286
|
train
|
tensorflow/tfjs-models
|
speech-commands/demo/index.js
|
scrollToPageBottom
|
function scrollToPageBottom() {
const scrollingElement = (document.scrollingElement || document.body);
scrollingElement.scrollTop = scrollingElement.scrollHeight;
}
|
javascript
|
function scrollToPageBottom() {
const scrollingElement = (document.scrollingElement || document.body);
scrollingElement.scrollTop = scrollingElement.scrollHeight;
}
|
[
"function",
"scrollToPageBottom",
"(",
")",
"{",
"const",
"scrollingElement",
"=",
"(",
"document",
".",
"scrollingElement",
"||",
"document",
".",
"body",
")",
";",
"scrollingElement",
".",
"scrollTop",
"=",
"scrollingElement",
".",
"scrollHeight",
";",
"}"
] |
Transfer learning logic.
Scroll to the bottom of the page
|
[
"Transfer",
"learning",
"logic",
".",
"Scroll",
"to",
"the",
"bottom",
"of",
"the",
"page"
] |
af194797c90cc5bcac1060d3cd41b0258a34c7dc
|
https://github.com/tensorflow/tfjs-models/blob/af194797c90cc5bcac1060d3cd41b0258a34c7dc/speech-commands/demo/index.js#L162-L165
|
train
|
tensorflow/tfjs-models
|
speech-commands/demo/index.js
|
getDateString
|
function getDateString() {
const d = new Date();
const year = `${d.getFullYear()}`;
let month = `${d.getMonth() + 1}`;
let day = `${d.getDate()}`;
if (month.length < 2) {
month = `0${month}`;
}
if (day.length < 2) {
day = `0${day}`;
}
let hour = `${d.getHours()}`;
if (hour.length < 2) {
hour = `0${hour}`;
}
let minute = `${d.getMinutes()}`;
if (minute.length < 2) {
minute = `0${minute}`;
}
let second = `${d.getSeconds()}`;
if (second.length < 2) {
second = `0${second}`;
}
return `${year}-${month}-${day}T${hour}.${minute}.${second}`;
}
|
javascript
|
function getDateString() {
const d = new Date();
const year = `${d.getFullYear()}`;
let month = `${d.getMonth() + 1}`;
let day = `${d.getDate()}`;
if (month.length < 2) {
month = `0${month}`;
}
if (day.length < 2) {
day = `0${day}`;
}
let hour = `${d.getHours()}`;
if (hour.length < 2) {
hour = `0${hour}`;
}
let minute = `${d.getMinutes()}`;
if (minute.length < 2) {
minute = `0${minute}`;
}
let second = `${d.getSeconds()}`;
if (second.length < 2) {
second = `0${second}`;
}
return `${year}-${month}-${day}T${hour}.${minute}.${second}`;
}
|
[
"function",
"getDateString",
"(",
")",
"{",
"const",
"d",
"=",
"new",
"Date",
"(",
")",
";",
"const",
"year",
"=",
"`",
"${",
"d",
".",
"getFullYear",
"(",
")",
"}",
"`",
";",
"let",
"month",
"=",
"`",
"${",
"d",
".",
"getMonth",
"(",
")",
"+",
"1",
"}",
"`",
";",
"let",
"day",
"=",
"`",
"${",
"d",
".",
"getDate",
"(",
")",
"}",
"`",
";",
"if",
"(",
"month",
".",
"length",
"<",
"2",
")",
"{",
"month",
"=",
"`",
"${",
"month",
"}",
"`",
";",
"}",
"if",
"(",
"day",
".",
"length",
"<",
"2",
")",
"{",
"day",
"=",
"`",
"${",
"day",
"}",
"`",
";",
"}",
"let",
"hour",
"=",
"`",
"${",
"d",
".",
"getHours",
"(",
")",
"}",
"`",
";",
"if",
"(",
"hour",
".",
"length",
"<",
"2",
")",
"{",
"hour",
"=",
"`",
"${",
"hour",
"}",
"`",
";",
"}",
"let",
"minute",
"=",
"`",
"${",
"d",
".",
"getMinutes",
"(",
")",
"}",
"`",
";",
"if",
"(",
"minute",
".",
"length",
"<",
"2",
")",
"{",
"minute",
"=",
"`",
"${",
"minute",
"}",
"`",
";",
"}",
"let",
"second",
"=",
"`",
"${",
"d",
".",
"getSeconds",
"(",
")",
"}",
"`",
";",
"if",
"(",
"second",
".",
"length",
"<",
"2",
")",
"{",
"second",
"=",
"`",
"${",
"second",
"}",
"`",
";",
"}",
"return",
"`",
"${",
"year",
"}",
"${",
"month",
"}",
"${",
"day",
"}",
"${",
"hour",
"}",
"${",
"minute",
"}",
"${",
"second",
"}",
"`",
";",
"}"
] |
Get the base name of the downloaded files based on current dataset.
|
[
"Get",
"the",
"base",
"name",
"of",
"the",
"downloaded",
"files",
"based",
"on",
"current",
"dataset",
"."
] |
af194797c90cc5bcac1060d3cd41b0258a34c7dc
|
https://github.com/tensorflow/tfjs-models/blob/af194797c90cc5bcac1060d3cd41b0258a34c7dc/speech-commands/demo/index.js#L496-L520
|
train
|
tensorflow/tfjs-models
|
knn-classifier/demo/camera.js
|
setupGui
|
function setupGui() {
// Create training buttons and info texts
for (let i = 0; i < NUM_CLASSES; i++) {
const div = document.createElement('div');
document.body.appendChild(div);
div.style.marginBottom = '10px';
// Create training button
const button = document.createElement('button');
button.innerText = 'Train ' + i;
div.appendChild(button);
// Listen for mouse events when clicking the button
button.addEventListener('click', () => {
training = i;
requestAnimationFrame(() => training = -1);
});
// Create info text
const infoText = document.createElement('span');
infoText.innerText = ' No examples added';
div.appendChild(infoText);
infoTexts.push(infoText);
}
}
|
javascript
|
function setupGui() {
// Create training buttons and info texts
for (let i = 0; i < NUM_CLASSES; i++) {
const div = document.createElement('div');
document.body.appendChild(div);
div.style.marginBottom = '10px';
// Create training button
const button = document.createElement('button');
button.innerText = 'Train ' + i;
div.appendChild(button);
// Listen for mouse events when clicking the button
button.addEventListener('click', () => {
training = i;
requestAnimationFrame(() => training = -1);
});
// Create info text
const infoText = document.createElement('span');
infoText.innerText = ' No examples added';
div.appendChild(infoText);
infoTexts.push(infoText);
}
}
|
[
"function",
"setupGui",
"(",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"NUM_CLASSES",
";",
"i",
"++",
")",
"{",
"const",
"div",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"document",
".",
"body",
".",
"appendChild",
"(",
"div",
")",
";",
"div",
".",
"style",
".",
"marginBottom",
"=",
"'10px'",
";",
"const",
"button",
"=",
"document",
".",
"createElement",
"(",
"'button'",
")",
";",
"button",
".",
"innerText",
"=",
"'Train '",
"+",
"i",
";",
"div",
".",
"appendChild",
"(",
"button",
")",
";",
"button",
".",
"addEventListener",
"(",
"'click'",
",",
"(",
")",
"=>",
"{",
"training",
"=",
"i",
";",
"requestAnimationFrame",
"(",
"(",
")",
"=>",
"training",
"=",
"-",
"1",
")",
";",
"}",
")",
";",
"const",
"infoText",
"=",
"document",
".",
"createElement",
"(",
"'span'",
")",
";",
"infoText",
".",
"innerText",
"=",
"' No examples added'",
";",
"div",
".",
"appendChild",
"(",
"infoText",
")",
";",
"infoTexts",
".",
"push",
"(",
"infoText",
")",
";",
"}",
"}"
] |
Setup training GUI. Adds a training button for each class,
and sets up mouse events.
|
[
"Setup",
"training",
"GUI",
".",
"Adds",
"a",
"training",
"button",
"for",
"each",
"class",
"and",
"sets",
"up",
"mouse",
"events",
"."
] |
af194797c90cc5bcac1060d3cd41b0258a34c7dc
|
https://github.com/tensorflow/tfjs-models/blob/af194797c90cc5bcac1060d3cd41b0258a34c7dc/knn-classifier/demo/camera.js#L87-L111
|
train
|
tensorflow/tfjs-models
|
knn-classifier/demo/camera.js
|
animate
|
async function animate() {
stats.begin();
// Get image data from video element
const image = tf.browser.fromPixels(video);
let logits;
// 'conv_preds' is the logits activation of MobileNet.
const infer = () => mobilenet.infer(image, 'conv_preds');
// Train class if one of the buttons is held down
if (training != -1) {
logits = infer();
// Add current image to classifier
classifier.addExample(logits, training);
}
// If the classifier has examples for any classes, make a prediction!
const numClasses = classifier.getNumClasses();
if (numClasses > 0) {
logits = infer();
const res = await classifier.predictClass(logits, TOPK);
for (let i = 0; i < NUM_CLASSES; i++) {
// Make the predicted class bold
if (res.classIndex == i) {
infoTexts[i].style.fontWeight = 'bold';
} else {
infoTexts[i].style.fontWeight = 'normal';
}
const classExampleCount = classifier.getClassExampleCount();
// Update info text
if (classExampleCount[i] > 0) {
const conf = res.confidences[i] * 100;
infoTexts[i].innerText = ` ${classExampleCount[i]} examples - ${conf}%`;
}
}
}
image.dispose();
if (logits != null) {
logits.dispose();
}
stats.end();
requestAnimationFrame(animate);
}
|
javascript
|
async function animate() {
stats.begin();
// Get image data from video element
const image = tf.browser.fromPixels(video);
let logits;
// 'conv_preds' is the logits activation of MobileNet.
const infer = () => mobilenet.infer(image, 'conv_preds');
// Train class if one of the buttons is held down
if (training != -1) {
logits = infer();
// Add current image to classifier
classifier.addExample(logits, training);
}
// If the classifier has examples for any classes, make a prediction!
const numClasses = classifier.getNumClasses();
if (numClasses > 0) {
logits = infer();
const res = await classifier.predictClass(logits, TOPK);
for (let i = 0; i < NUM_CLASSES; i++) {
// Make the predicted class bold
if (res.classIndex == i) {
infoTexts[i].style.fontWeight = 'bold';
} else {
infoTexts[i].style.fontWeight = 'normal';
}
const classExampleCount = classifier.getClassExampleCount();
// Update info text
if (classExampleCount[i] > 0) {
const conf = res.confidences[i] * 100;
infoTexts[i].innerText = ` ${classExampleCount[i]} examples - ${conf}%`;
}
}
}
image.dispose();
if (logits != null) {
logits.dispose();
}
stats.end();
requestAnimationFrame(animate);
}
|
[
"async",
"function",
"animate",
"(",
")",
"{",
"stats",
".",
"begin",
"(",
")",
";",
"const",
"image",
"=",
"tf",
".",
"browser",
".",
"fromPixels",
"(",
"video",
")",
";",
"let",
"logits",
";",
"const",
"infer",
"=",
"(",
")",
"=>",
"mobilenet",
".",
"infer",
"(",
"image",
",",
"'conv_preds'",
")",
";",
"if",
"(",
"training",
"!=",
"-",
"1",
")",
"{",
"logits",
"=",
"infer",
"(",
")",
";",
"classifier",
".",
"addExample",
"(",
"logits",
",",
"training",
")",
";",
"}",
"const",
"numClasses",
"=",
"classifier",
".",
"getNumClasses",
"(",
")",
";",
"if",
"(",
"numClasses",
">",
"0",
")",
"{",
"logits",
"=",
"infer",
"(",
")",
";",
"const",
"res",
"=",
"await",
"classifier",
".",
"predictClass",
"(",
"logits",
",",
"TOPK",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"NUM_CLASSES",
";",
"i",
"++",
")",
"{",
"if",
"(",
"res",
".",
"classIndex",
"==",
"i",
")",
"{",
"infoTexts",
"[",
"i",
"]",
".",
"style",
".",
"fontWeight",
"=",
"'bold'",
";",
"}",
"else",
"{",
"infoTexts",
"[",
"i",
"]",
".",
"style",
".",
"fontWeight",
"=",
"'normal'",
";",
"}",
"const",
"classExampleCount",
"=",
"classifier",
".",
"getClassExampleCount",
"(",
")",
";",
"if",
"(",
"classExampleCount",
"[",
"i",
"]",
">",
"0",
")",
"{",
"const",
"conf",
"=",
"res",
".",
"confidences",
"[",
"i",
"]",
"*",
"100",
";",
"infoTexts",
"[",
"i",
"]",
".",
"innerText",
"=",
"`",
"${",
"classExampleCount",
"[",
"i",
"]",
"}",
"${",
"conf",
"}",
"`",
";",
"}",
"}",
"}",
"image",
".",
"dispose",
"(",
")",
";",
"if",
"(",
"logits",
"!=",
"null",
")",
"{",
"logits",
".",
"dispose",
"(",
")",
";",
"}",
"stats",
".",
"end",
"(",
")",
";",
"requestAnimationFrame",
"(",
"animate",
")",
";",
"}"
] |
Animation function called on each frame, running prediction
|
[
"Animation",
"function",
"called",
"on",
"each",
"frame",
"running",
"prediction"
] |
af194797c90cc5bcac1060d3cd41b0258a34c7dc
|
https://github.com/tensorflow/tfjs-models/blob/af194797c90cc5bcac1060d3cd41b0258a34c7dc/knn-classifier/demo/camera.js#L124-L171
|
train
|
dvajs/dva
|
examples/user-dashboard/src/utils/request.js
|
request
|
async function request(url, options) {
const response = await fetch(url, options);
checkStatus(response);
const data = await response.json();
const ret = {
data,
headers: {},
};
if (response.headers.get('x-total-count')) {
ret.headers['x-total-count'] = response.headers.get('x-total-count');
}
return ret;
}
|
javascript
|
async function request(url, options) {
const response = await fetch(url, options);
checkStatus(response);
const data = await response.json();
const ret = {
data,
headers: {},
};
if (response.headers.get('x-total-count')) {
ret.headers['x-total-count'] = response.headers.get('x-total-count');
}
return ret;
}
|
[
"async",
"function",
"request",
"(",
"url",
",",
"options",
")",
"{",
"const",
"response",
"=",
"await",
"fetch",
"(",
"url",
",",
"options",
")",
";",
"checkStatus",
"(",
"response",
")",
";",
"const",
"data",
"=",
"await",
"response",
".",
"json",
"(",
")",
";",
"const",
"ret",
"=",
"{",
"data",
",",
"headers",
":",
"{",
"}",
",",
"}",
";",
"if",
"(",
"response",
".",
"headers",
".",
"get",
"(",
"'x-total-count'",
")",
")",
"{",
"ret",
".",
"headers",
"[",
"'x-total-count'",
"]",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"'x-total-count'",
")",
";",
"}",
"return",
"ret",
";",
"}"
] |
Requests a URL, returning a promise.
@param {string} url The URL we want to request
@param {object} [options] The options we want to pass to "fetch"
@return {object} An object containing either "data" or "err"
|
[
"Requests",
"a",
"URL",
"returning",
"a",
"promise",
"."
] |
99ec56cbedbdba7e3e91befe341f109e038363c6
|
https://github.com/dvajs/dva/blob/99ec56cbedbdba7e3e91befe341f109e038363c6/examples/user-dashboard/src/utils/request.js#L20-L37
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
addNodeTo
|
function addNodeTo ( target, className ) {
var div = document.createElement('div');
addClass(div, className);
target.appendChild(div);
return div;
}
|
javascript
|
function addNodeTo ( target, className ) {
var div = document.createElement('div');
addClass(div, className);
target.appendChild(div);
return div;
}
|
[
"function",
"addNodeTo",
"(",
"target",
",",
"className",
")",
"{",
"var",
"div",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"addClass",
"(",
"div",
",",
"className",
")",
";",
"target",
".",
"appendChild",
"(",
"div",
")",
";",
"return",
"div",
";",
"}"
] |
Creates a node, adds it to target, returns the new node.
|
[
"Creates",
"a",
"node",
"adds",
"it",
"to",
"target",
"returns",
"the",
"new",
"node",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L39-L44
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
offset
|
function offset ( elem, orientation ) {
var rect = elem.getBoundingClientRect(),
doc = elem.ownerDocument,
docElem = doc.documentElement,
pageOffset = getPageOffset();
// getBoundingClientRect contains left scroll in Chrome on Android.
// I haven't found a feature detection that proves this. Worst case
// scenario on mis-match: the 'tap' feature on horizontal sliders breaks.
if ( /webkit.*Chrome.*Mobile/i.test(navigator.userAgent) ) {
pageOffset.x = 0;
}
return orientation ? (rect.top + pageOffset.y - docElem.clientTop) : (rect.left + pageOffset.x - docElem.clientLeft);
}
|
javascript
|
function offset ( elem, orientation ) {
var rect = elem.getBoundingClientRect(),
doc = elem.ownerDocument,
docElem = doc.documentElement,
pageOffset = getPageOffset();
// getBoundingClientRect contains left scroll in Chrome on Android.
// I haven't found a feature detection that proves this. Worst case
// scenario on mis-match: the 'tap' feature on horizontal sliders breaks.
if ( /webkit.*Chrome.*Mobile/i.test(navigator.userAgent) ) {
pageOffset.x = 0;
}
return orientation ? (rect.top + pageOffset.y - docElem.clientTop) : (rect.left + pageOffset.x - docElem.clientLeft);
}
|
[
"function",
"offset",
"(",
"elem",
",",
"orientation",
")",
"{",
"var",
"rect",
"=",
"elem",
".",
"getBoundingClientRect",
"(",
")",
",",
"doc",
"=",
"elem",
".",
"ownerDocument",
",",
"docElem",
"=",
"doc",
".",
"documentElement",
",",
"pageOffset",
"=",
"getPageOffset",
"(",
")",
";",
"if",
"(",
"/",
"webkit.*Chrome.*Mobile",
"/",
"i",
".",
"test",
"(",
"navigator",
".",
"userAgent",
")",
")",
"{",
"pageOffset",
".",
"x",
"=",
"0",
";",
"}",
"return",
"orientation",
"?",
"(",
"rect",
".",
"top",
"+",
"pageOffset",
".",
"y",
"-",
"docElem",
".",
"clientTop",
")",
":",
"(",
"rect",
".",
"left",
"+",
"pageOffset",
".",
"x",
"-",
"docElem",
".",
"clientLeft",
")",
";",
"}"
] |
Current position of an element relative to the document.
|
[
"Current",
"position",
"of",
"an",
"element",
"relative",
"to",
"the",
"document",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L59-L74
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
Spectrum
|
function Spectrum ( entry, snap, direction, singleStep ) {
this.xPct = [];
this.xVal = [];
this.xSteps = [ singleStep || false ];
this.xNumSteps = [ false ];
this.xHighestCompleteStep = [];
this.snap = snap;
this.direction = direction;
var index, ordered = [ /* [0, 'min'], [1, '50%'], [2, 'max'] */ ];
// Map the object keys to an array.
for ( index in entry ) {
if ( entry.hasOwnProperty(index) ) {
ordered.push([entry[index], index]);
}
}
// Sort all entries by value (numeric sort).
if ( ordered.length && typeof ordered[0][0] === "object" ) {
ordered.sort(function(a, b) { return a[0][0] - b[0][0]; });
} else {
ordered.sort(function(a, b) { return a[0] - b[0]; });
}
// Convert all entries to subranges.
for ( index = 0; index < ordered.length; index++ ) {
handleEntryPoint(ordered[index][1], ordered[index][0], this);
}
// Store the actual step values.
// xSteps is sorted in the same order as xPct and xVal.
this.xNumSteps = this.xSteps.slice(0);
// Convert all numeric steps to the percentage of the subrange they represent.
for ( index = 0; index < this.xNumSteps.length; index++ ) {
handleStepPoint(index, this.xNumSteps[index], this);
}
}
|
javascript
|
function Spectrum ( entry, snap, direction, singleStep ) {
this.xPct = [];
this.xVal = [];
this.xSteps = [ singleStep || false ];
this.xNumSteps = [ false ];
this.xHighestCompleteStep = [];
this.snap = snap;
this.direction = direction;
var index, ordered = [ /* [0, 'min'], [1, '50%'], [2, 'max'] */ ];
// Map the object keys to an array.
for ( index in entry ) {
if ( entry.hasOwnProperty(index) ) {
ordered.push([entry[index], index]);
}
}
// Sort all entries by value (numeric sort).
if ( ordered.length && typeof ordered[0][0] === "object" ) {
ordered.sort(function(a, b) { return a[0][0] - b[0][0]; });
} else {
ordered.sort(function(a, b) { return a[0] - b[0]; });
}
// Convert all entries to subranges.
for ( index = 0; index < ordered.length; index++ ) {
handleEntryPoint(ordered[index][1], ordered[index][0], this);
}
// Store the actual step values.
// xSteps is sorted in the same order as xPct and xVal.
this.xNumSteps = this.xSteps.slice(0);
// Convert all numeric steps to the percentage of the subrange they represent.
for ( index = 0; index < this.xNumSteps.length; index++ ) {
handleStepPoint(index, this.xNumSteps[index], this);
}
}
|
[
"function",
"Spectrum",
"(",
"entry",
",",
"snap",
",",
"direction",
",",
"singleStep",
")",
"{",
"this",
".",
"xPct",
"=",
"[",
"]",
";",
"this",
".",
"xVal",
"=",
"[",
"]",
";",
"this",
".",
"xSteps",
"=",
"[",
"singleStep",
"||",
"false",
"]",
";",
"this",
".",
"xNumSteps",
"=",
"[",
"false",
"]",
";",
"this",
".",
"xHighestCompleteStep",
"=",
"[",
"]",
";",
"this",
".",
"snap",
"=",
"snap",
";",
"this",
".",
"direction",
"=",
"direction",
";",
"var",
"index",
",",
"ordered",
"=",
"[",
"]",
";",
"for",
"(",
"index",
"in",
"entry",
")",
"{",
"if",
"(",
"entry",
".",
"hasOwnProperty",
"(",
"index",
")",
")",
"{",
"ordered",
".",
"push",
"(",
"[",
"entry",
"[",
"index",
"]",
",",
"index",
"]",
")",
";",
"}",
"}",
"if",
"(",
"ordered",
".",
"length",
"&&",
"typeof",
"ordered",
"[",
"0",
"]",
"[",
"0",
"]",
"===",
"\"object\"",
")",
"{",
"ordered",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"a",
"[",
"0",
"]",
"[",
"0",
"]",
"-",
"b",
"[",
"0",
"]",
"[",
"0",
"]",
";",
"}",
")",
";",
"}",
"else",
"{",
"ordered",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"a",
"[",
"0",
"]",
"-",
"b",
"[",
"0",
"]",
";",
"}",
")",
";",
"}",
"for",
"(",
"index",
"=",
"0",
";",
"index",
"<",
"ordered",
".",
"length",
";",
"index",
"++",
")",
"{",
"handleEntryPoint",
"(",
"ordered",
"[",
"index",
"]",
"[",
"1",
"]",
",",
"ordered",
"[",
"index",
"]",
"[",
"0",
"]",
",",
"this",
")",
";",
"}",
"this",
".",
"xNumSteps",
"=",
"this",
".",
"xSteps",
".",
"slice",
"(",
"0",
")",
";",
"for",
"(",
"index",
"=",
"0",
";",
"index",
"<",
"this",
".",
"xNumSteps",
".",
"length",
";",
"index",
"++",
")",
"{",
"handleStepPoint",
"(",
"index",
",",
"this",
".",
"xNumSteps",
"[",
"index",
"]",
",",
"this",
")",
";",
"}",
"}"
] |
The interface to Spectrum handles all direction-based conversions, so the above values are unaware.
|
[
"The",
"interface",
"to",
"Spectrum",
"handles",
"all",
"direction",
"-",
"based",
"conversions",
"so",
"the",
"above",
"values",
"are",
"unaware",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L352-L393
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
addOrigin
|
function addOrigin ( base, handleNumber ) {
var origin = addNodeTo(base, options.cssClasses.origin);
var handle = addNodeTo(origin, options.cssClasses.handle);
addNodeTo(handle, options.cssClasses.handleTouchArea);
handle.setAttribute('data-handle', handleNumber);
if ( handleNumber === 0 ) {
addClass(handle, options.cssClasses.handleLower);
}
else if ( handleNumber === options.handles - 1 ) {
addClass(handle, options.cssClasses.handleUpper);
}
return origin;
}
|
javascript
|
function addOrigin ( base, handleNumber ) {
var origin = addNodeTo(base, options.cssClasses.origin);
var handle = addNodeTo(origin, options.cssClasses.handle);
addNodeTo(handle, options.cssClasses.handleTouchArea);
handle.setAttribute('data-handle', handleNumber);
if ( handleNumber === 0 ) {
addClass(handle, options.cssClasses.handleLower);
}
else if ( handleNumber === options.handles - 1 ) {
addClass(handle, options.cssClasses.handleUpper);
}
return origin;
}
|
[
"function",
"addOrigin",
"(",
"base",
",",
"handleNumber",
")",
"{",
"var",
"origin",
"=",
"addNodeTo",
"(",
"base",
",",
"options",
".",
"cssClasses",
".",
"origin",
")",
";",
"var",
"handle",
"=",
"addNodeTo",
"(",
"origin",
",",
"options",
".",
"cssClasses",
".",
"handle",
")",
";",
"addNodeTo",
"(",
"handle",
",",
"options",
".",
"cssClasses",
".",
"handleTouchArea",
")",
";",
"handle",
".",
"setAttribute",
"(",
"'data-handle'",
",",
"handleNumber",
")",
";",
"if",
"(",
"handleNumber",
"===",
"0",
")",
"{",
"addClass",
"(",
"handle",
",",
"options",
".",
"cssClasses",
".",
"handleLower",
")",
";",
"}",
"else",
"if",
"(",
"handleNumber",
"===",
"options",
".",
"handles",
"-",
"1",
")",
"{",
"addClass",
"(",
"handle",
",",
"options",
".",
"cssClasses",
".",
"handleUpper",
")",
";",
"}",
"return",
"origin",
";",
"}"
] |
Append a origin to the base
|
[
"Append",
"a",
"origin",
"to",
"the",
"base"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L911-L928
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
addConnect
|
function addConnect ( base, add ) {
if ( !add ) {
return false;
}
return addNodeTo(base, options.cssClasses.connect);
}
|
javascript
|
function addConnect ( base, add ) {
if ( !add ) {
return false;
}
return addNodeTo(base, options.cssClasses.connect);
}
|
[
"function",
"addConnect",
"(",
"base",
",",
"add",
")",
"{",
"if",
"(",
"!",
"add",
")",
"{",
"return",
"false",
";",
"}",
"return",
"addNodeTo",
"(",
"base",
",",
"options",
".",
"cssClasses",
".",
"connect",
")",
";",
"}"
] |
Insert nodes for connect elements
|
[
"Insert",
"nodes",
"for",
"connect",
"elements"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L931-L938
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
addElements
|
function addElements ( connectOptions, base ) {
scope_Handles = [];
scope_Connects = [];
scope_Connects.push(addConnect(base, connectOptions[0]));
// [::::O====O====O====]
// connectOptions = [0, 1, 1, 1]
for ( var i = 0; i < options.handles; i++ ) {
// Keep a list of all added handles.
scope_Handles.push(addOrigin(base, i));
scope_HandleNumbers[i] = i;
scope_Connects.push(addConnect(base, connectOptions[i + 1]));
}
}
|
javascript
|
function addElements ( connectOptions, base ) {
scope_Handles = [];
scope_Connects = [];
scope_Connects.push(addConnect(base, connectOptions[0]));
// [::::O====O====O====]
// connectOptions = [0, 1, 1, 1]
for ( var i = 0; i < options.handles; i++ ) {
// Keep a list of all added handles.
scope_Handles.push(addOrigin(base, i));
scope_HandleNumbers[i] = i;
scope_Connects.push(addConnect(base, connectOptions[i + 1]));
}
}
|
[
"function",
"addElements",
"(",
"connectOptions",
",",
"base",
")",
"{",
"scope_Handles",
"=",
"[",
"]",
";",
"scope_Connects",
"=",
"[",
"]",
";",
"scope_Connects",
".",
"push",
"(",
"addConnect",
"(",
"base",
",",
"connectOptions",
"[",
"0",
"]",
")",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"options",
".",
"handles",
";",
"i",
"++",
")",
"{",
"scope_Handles",
".",
"push",
"(",
"addOrigin",
"(",
"base",
",",
"i",
")",
")",
";",
"scope_HandleNumbers",
"[",
"i",
"]",
"=",
"i",
";",
"scope_Connects",
".",
"push",
"(",
"addConnect",
"(",
"base",
",",
"connectOptions",
"[",
"i",
"+",
"1",
"]",
")",
")",
";",
"}",
"}"
] |
Add handles to the slider base.
|
[
"Add",
"handles",
"to",
"the",
"slider",
"base",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L941-L957
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
addSlider
|
function addSlider ( target ) {
// Apply classes and data to the target.
addClass(target, options.cssClasses.target);
if ( options.dir === 0 ) {
addClass(target, options.cssClasses.ltr);
} else {
addClass(target, options.cssClasses.rtl);
}
if ( options.ort === 0 ) {
addClass(target, options.cssClasses.horizontal);
} else {
addClass(target, options.cssClasses.vertical);
}
scope_Base = addNodeTo(target, options.cssClasses.base);
}
|
javascript
|
function addSlider ( target ) {
// Apply classes and data to the target.
addClass(target, options.cssClasses.target);
if ( options.dir === 0 ) {
addClass(target, options.cssClasses.ltr);
} else {
addClass(target, options.cssClasses.rtl);
}
if ( options.ort === 0 ) {
addClass(target, options.cssClasses.horizontal);
} else {
addClass(target, options.cssClasses.vertical);
}
scope_Base = addNodeTo(target, options.cssClasses.base);
}
|
[
"function",
"addSlider",
"(",
"target",
")",
"{",
"addClass",
"(",
"target",
",",
"options",
".",
"cssClasses",
".",
"target",
")",
";",
"if",
"(",
"options",
".",
"dir",
"===",
"0",
")",
"{",
"addClass",
"(",
"target",
",",
"options",
".",
"cssClasses",
".",
"ltr",
")",
";",
"}",
"else",
"{",
"addClass",
"(",
"target",
",",
"options",
".",
"cssClasses",
".",
"rtl",
")",
";",
"}",
"if",
"(",
"options",
".",
"ort",
"===",
"0",
")",
"{",
"addClass",
"(",
"target",
",",
"options",
".",
"cssClasses",
".",
"horizontal",
")",
";",
"}",
"else",
"{",
"addClass",
"(",
"target",
",",
"options",
".",
"cssClasses",
".",
"vertical",
")",
";",
"}",
"scope_Base",
"=",
"addNodeTo",
"(",
"target",
",",
"options",
".",
"cssClasses",
".",
"base",
")",
";",
"}"
] |
Initialize a single slider.
|
[
"Initialize",
"a",
"single",
"slider",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L960-L978
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
tooltips
|
function tooltips ( ) {
// Tooltips are added with options.tooltips in original order.
var tips = scope_Handles.map(addTooltip);
bindEvent('update', function(values, handleNumber, unencoded) {
if ( !tips[handleNumber] ) {
return;
}
var formattedValue = values[handleNumber];
if ( options.tooltips[handleNumber] !== true ) {
formattedValue = options.tooltips[handleNumber].to(unencoded[handleNumber]);
}
tips[handleNumber].innerHTML = '<span>' + formattedValue + '</span>';
});
}
|
javascript
|
function tooltips ( ) {
// Tooltips are added with options.tooltips in original order.
var tips = scope_Handles.map(addTooltip);
bindEvent('update', function(values, handleNumber, unencoded) {
if ( !tips[handleNumber] ) {
return;
}
var formattedValue = values[handleNumber];
if ( options.tooltips[handleNumber] !== true ) {
formattedValue = options.tooltips[handleNumber].to(unencoded[handleNumber]);
}
tips[handleNumber].innerHTML = '<span>' + formattedValue + '</span>';
});
}
|
[
"function",
"tooltips",
"(",
")",
"{",
"var",
"tips",
"=",
"scope_Handles",
".",
"map",
"(",
"addTooltip",
")",
";",
"bindEvent",
"(",
"'update'",
",",
"function",
"(",
"values",
",",
"handleNumber",
",",
"unencoded",
")",
"{",
"if",
"(",
"!",
"tips",
"[",
"handleNumber",
"]",
")",
"{",
"return",
";",
"}",
"var",
"formattedValue",
"=",
"values",
"[",
"handleNumber",
"]",
";",
"if",
"(",
"options",
".",
"tooltips",
"[",
"handleNumber",
"]",
"!==",
"true",
")",
"{",
"formattedValue",
"=",
"options",
".",
"tooltips",
"[",
"handleNumber",
"]",
".",
"to",
"(",
"unencoded",
"[",
"handleNumber",
"]",
")",
";",
"}",
"tips",
"[",
"handleNumber",
"]",
".",
"innerHTML",
"=",
"'<span>'",
"+",
"formattedValue",
"+",
"'</span>'",
";",
"}",
")",
";",
"}"
] |
The tooltips option is a shorthand for using the 'update' event.
|
[
"The",
"tooltips",
"option",
"is",
"a",
"shorthand",
"for",
"using",
"the",
"update",
"event",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L991-L1010
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
baseSize
|
function baseSize ( ) {
var rect = scope_Base.getBoundingClientRect(), alt = 'offset' + ['Width', 'Height'][options.ort];
return options.ort === 0 ? (rect.width||scope_Base[alt]) : (rect.height||scope_Base[alt]);
}
|
javascript
|
function baseSize ( ) {
var rect = scope_Base.getBoundingClientRect(), alt = 'offset' + ['Width', 'Height'][options.ort];
return options.ort === 0 ? (rect.width||scope_Base[alt]) : (rect.height||scope_Base[alt]);
}
|
[
"function",
"baseSize",
"(",
")",
"{",
"var",
"rect",
"=",
"scope_Base",
".",
"getBoundingClientRect",
"(",
")",
",",
"alt",
"=",
"'offset'",
"+",
"[",
"'Width'",
",",
"'Height'",
"]",
"[",
"options",
".",
"ort",
"]",
";",
"return",
"options",
".",
"ort",
"===",
"0",
"?",
"(",
"rect",
".",
"width",
"||",
"scope_Base",
"[",
"alt",
"]",
")",
":",
"(",
"rect",
".",
"height",
"||",
"scope_Base",
"[",
"alt",
"]",
")",
";",
"}"
] |
Shorthand for base dimensions.
|
[
"Shorthand",
"for",
"base",
"dimensions",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1252-L1255
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
attachEvent
|
function attachEvent ( events, element, callback, data ) {
// This function can be used to 'filter' events to the slider.
// element is a node, not a nodeList
var method = function ( e ){
if ( scope_Target.hasAttribute('disabled') ) {
return false;
}
// Stop if an active 'tap' transition is taking place.
if ( hasClass(scope_Target, options.cssClasses.tap) ) {
return false;
}
e = fixEvent(e, data.pageOffset);
// Handle reject of multitouch
if ( !e ) {
return false;
}
// Ignore right or middle clicks on start #454
if ( events === actions.start && e.buttons !== undefined && e.buttons > 1 ) {
return false;
}
// Ignore right or middle clicks on start #454
if ( data.hover && e.buttons ) {
return false;
}
e.calcPoint = e.points[ options.ort ];
// Call the event handler with the event [ and additional data ].
callback ( e, data );
};
var methods = [];
// Bind a closure on the target for every event type.
events.split(' ').forEach(function( eventName ){
element.addEventListener(eventName, method, false);
methods.push([eventName, method]);
});
return methods;
}
|
javascript
|
function attachEvent ( events, element, callback, data ) {
// This function can be used to 'filter' events to the slider.
// element is a node, not a nodeList
var method = function ( e ){
if ( scope_Target.hasAttribute('disabled') ) {
return false;
}
// Stop if an active 'tap' transition is taking place.
if ( hasClass(scope_Target, options.cssClasses.tap) ) {
return false;
}
e = fixEvent(e, data.pageOffset);
// Handle reject of multitouch
if ( !e ) {
return false;
}
// Ignore right or middle clicks on start #454
if ( events === actions.start && e.buttons !== undefined && e.buttons > 1 ) {
return false;
}
// Ignore right or middle clicks on start #454
if ( data.hover && e.buttons ) {
return false;
}
e.calcPoint = e.points[ options.ort ];
// Call the event handler with the event [ and additional data ].
callback ( e, data );
};
var methods = [];
// Bind a closure on the target for every event type.
events.split(' ').forEach(function( eventName ){
element.addEventListener(eventName, method, false);
methods.push([eventName, method]);
});
return methods;
}
|
[
"function",
"attachEvent",
"(",
"events",
",",
"element",
",",
"callback",
",",
"data",
")",
"{",
"var",
"method",
"=",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"scope_Target",
".",
"hasAttribute",
"(",
"'disabled'",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"hasClass",
"(",
"scope_Target",
",",
"options",
".",
"cssClasses",
".",
"tap",
")",
")",
"{",
"return",
"false",
";",
"}",
"e",
"=",
"fixEvent",
"(",
"e",
",",
"data",
".",
"pageOffset",
")",
";",
"if",
"(",
"!",
"e",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"events",
"===",
"actions",
".",
"start",
"&&",
"e",
".",
"buttons",
"!==",
"undefined",
"&&",
"e",
".",
"buttons",
">",
"1",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"data",
".",
"hover",
"&&",
"e",
".",
"buttons",
")",
"{",
"return",
"false",
";",
"}",
"e",
".",
"calcPoint",
"=",
"e",
".",
"points",
"[",
"options",
".",
"ort",
"]",
";",
"callback",
"(",
"e",
",",
"data",
")",
";",
"}",
";",
"var",
"methods",
"=",
"[",
"]",
";",
"events",
".",
"split",
"(",
"' '",
")",
".",
"forEach",
"(",
"function",
"(",
"eventName",
")",
"{",
"element",
".",
"addEventListener",
"(",
"eventName",
",",
"method",
",",
"false",
")",
";",
"methods",
".",
"push",
"(",
"[",
"eventName",
",",
"method",
"]",
")",
";",
"}",
")",
";",
"return",
"methods",
";",
"}"
] |
Handler for attaching events trough a proxy.
|
[
"Handler",
"for",
"attaching",
"events",
"trough",
"a",
"proxy",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1258-L1306
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
function ( e ){
if ( scope_Target.hasAttribute('disabled') ) {
return false;
}
// Stop if an active 'tap' transition is taking place.
if ( hasClass(scope_Target, options.cssClasses.tap) ) {
return false;
}
e = fixEvent(e, data.pageOffset);
// Handle reject of multitouch
if ( !e ) {
return false;
}
// Ignore right or middle clicks on start #454
if ( events === actions.start && e.buttons !== undefined && e.buttons > 1 ) {
return false;
}
// Ignore right or middle clicks on start #454
if ( data.hover && e.buttons ) {
return false;
}
e.calcPoint = e.points[ options.ort ];
// Call the event handler with the event [ and additional data ].
callback ( e, data );
}
|
javascript
|
function ( e ){
if ( scope_Target.hasAttribute('disabled') ) {
return false;
}
// Stop if an active 'tap' transition is taking place.
if ( hasClass(scope_Target, options.cssClasses.tap) ) {
return false;
}
e = fixEvent(e, data.pageOffset);
// Handle reject of multitouch
if ( !e ) {
return false;
}
// Ignore right or middle clicks on start #454
if ( events === actions.start && e.buttons !== undefined && e.buttons > 1 ) {
return false;
}
// Ignore right or middle clicks on start #454
if ( data.hover && e.buttons ) {
return false;
}
e.calcPoint = e.points[ options.ort ];
// Call the event handler with the event [ and additional data ].
callback ( e, data );
}
|
[
"function",
"(",
"e",
")",
"{",
"if",
"(",
"scope_Target",
".",
"hasAttribute",
"(",
"'disabled'",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"hasClass",
"(",
"scope_Target",
",",
"options",
".",
"cssClasses",
".",
"tap",
")",
")",
"{",
"return",
"false",
";",
"}",
"e",
"=",
"fixEvent",
"(",
"e",
",",
"data",
".",
"pageOffset",
")",
";",
"if",
"(",
"!",
"e",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"events",
"===",
"actions",
".",
"start",
"&&",
"e",
".",
"buttons",
"!==",
"undefined",
"&&",
"e",
".",
"buttons",
">",
"1",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"data",
".",
"hover",
"&&",
"e",
".",
"buttons",
")",
"{",
"return",
"false",
";",
"}",
"e",
".",
"calcPoint",
"=",
"e",
".",
"points",
"[",
"options",
".",
"ort",
"]",
";",
"callback",
"(",
"e",
",",
"data",
")",
";",
"}"
] |
This function can be used to 'filter' events to the slider. element is a node, not a nodeList
|
[
"This",
"function",
"can",
"be",
"used",
"to",
"filter",
"events",
"to",
"the",
"slider",
".",
"element",
"is",
"a",
"node",
"not",
"a",
"nodeList"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1263-L1295
|
train
|
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
fixEvent
|
function fixEvent ( e, pageOffset ) {
// Prevent scrolling and panning on touch events, while
// attempting to slide. The tap event also depends on this.
e.preventDefault();
// Filter the event to register the type, which can be
// touch, mouse or pointer. Offset changes need to be
// made on an event specific basis.
var touch = e.type.indexOf('touch') === 0;
var mouse = e.type.indexOf('mouse') === 0;
var pointer = e.type.indexOf('pointer') === 0;
var x;
var y;
// IE10 implemented pointer events with a prefix;
if ( e.type.indexOf('MSPointer') === 0 ) {
pointer = true;
}
if ( touch ) {
// Fix bug when user touches with two or more fingers on mobile devices.
// It's useful when you have two or more sliders on one page,
// that can be touched simultaneously.
// #649, #663, #668
if ( e.touches.length > 1 ) {
return false;
}
// noUiSlider supports one movement at a time,
// so we can select the first 'changedTouch'.
x = e.changedTouches[0].pageX;
y = e.changedTouches[0].pageY;
}
pageOffset = pageOffset || getPageOffset();
if ( mouse || pointer ) {
x = e.clientX + pageOffset.x;
y = e.clientY + pageOffset.y;
}
e.pageOffset = pageOffset;
e.points = [x, y];
e.cursor = mouse || pointer; // Fix #435
return e;
}
|
javascript
|
function fixEvent ( e, pageOffset ) {
// Prevent scrolling and panning on touch events, while
// attempting to slide. The tap event also depends on this.
e.preventDefault();
// Filter the event to register the type, which can be
// touch, mouse or pointer. Offset changes need to be
// made on an event specific basis.
var touch = e.type.indexOf('touch') === 0;
var mouse = e.type.indexOf('mouse') === 0;
var pointer = e.type.indexOf('pointer') === 0;
var x;
var y;
// IE10 implemented pointer events with a prefix;
if ( e.type.indexOf('MSPointer') === 0 ) {
pointer = true;
}
if ( touch ) {
// Fix bug when user touches with two or more fingers on mobile devices.
// It's useful when you have two or more sliders on one page,
// that can be touched simultaneously.
// #649, #663, #668
if ( e.touches.length > 1 ) {
return false;
}
// noUiSlider supports one movement at a time,
// so we can select the first 'changedTouch'.
x = e.changedTouches[0].pageX;
y = e.changedTouches[0].pageY;
}
pageOffset = pageOffset || getPageOffset();
if ( mouse || pointer ) {
x = e.clientX + pageOffset.x;
y = e.clientY + pageOffset.y;
}
e.pageOffset = pageOffset;
e.points = [x, y];
e.cursor = mouse || pointer; // Fix #435
return e;
}
|
[
"function",
"fixEvent",
"(",
"e",
",",
"pageOffset",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
";",
"var",
"touch",
"=",
"e",
".",
"type",
".",
"indexOf",
"(",
"'touch'",
")",
"===",
"0",
";",
"var",
"mouse",
"=",
"e",
".",
"type",
".",
"indexOf",
"(",
"'mouse'",
")",
"===",
"0",
";",
"var",
"pointer",
"=",
"e",
".",
"type",
".",
"indexOf",
"(",
"'pointer'",
")",
"===",
"0",
";",
"var",
"x",
";",
"var",
"y",
";",
"if",
"(",
"e",
".",
"type",
".",
"indexOf",
"(",
"'MSPointer'",
")",
"===",
"0",
")",
"{",
"pointer",
"=",
"true",
";",
"}",
"if",
"(",
"touch",
")",
"{",
"if",
"(",
"e",
".",
"touches",
".",
"length",
">",
"1",
")",
"{",
"return",
"false",
";",
"}",
"x",
"=",
"e",
".",
"changedTouches",
"[",
"0",
"]",
".",
"pageX",
";",
"y",
"=",
"e",
".",
"changedTouches",
"[",
"0",
"]",
".",
"pageY",
";",
"}",
"pageOffset",
"=",
"pageOffset",
"||",
"getPageOffset",
"(",
")",
";",
"if",
"(",
"mouse",
"||",
"pointer",
")",
"{",
"x",
"=",
"e",
".",
"clientX",
"+",
"pageOffset",
".",
"x",
";",
"y",
"=",
"e",
".",
"clientY",
"+",
"pageOffset",
".",
"y",
";",
"}",
"e",
".",
"pageOffset",
"=",
"pageOffset",
";",
"e",
".",
"points",
"=",
"[",
"x",
",",
"y",
"]",
";",
"e",
".",
"cursor",
"=",
"mouse",
"||",
"pointer",
";",
"return",
"e",
";",
"}"
] |
Provide a clean event with standardized offset values.
|
[
"Provide",
"a",
"clean",
"event",
"with",
"standardized",
"offset",
"values",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1309-L1357
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
calcPointToPercentage
|
function calcPointToPercentage ( calcPoint ) {
var location = calcPoint - offset(scope_Base, options.ort);
var proposal = ( location * 100 ) / baseSize();
return options.dir ? 100 - proposal : proposal;
}
|
javascript
|
function calcPointToPercentage ( calcPoint ) {
var location = calcPoint - offset(scope_Base, options.ort);
var proposal = ( location * 100 ) / baseSize();
return options.dir ? 100 - proposal : proposal;
}
|
[
"function",
"calcPointToPercentage",
"(",
"calcPoint",
")",
"{",
"var",
"location",
"=",
"calcPoint",
"-",
"offset",
"(",
"scope_Base",
",",
"options",
".",
"ort",
")",
";",
"var",
"proposal",
"=",
"(",
"location",
"*",
"100",
")",
"/",
"baseSize",
"(",
")",
";",
"return",
"options",
".",
"dir",
"?",
"100",
"-",
"proposal",
":",
"proposal",
";",
"}"
] |
Translate a coordinate in the document to a percentage on the slider
|
[
"Translate",
"a",
"coordinate",
"in",
"the",
"document",
"to",
"a",
"percentage",
"on",
"the",
"slider"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1360-L1364
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
getClosestHandle
|
function getClosestHandle ( proposal ) {
var closest = 100;
var handleNumber = false;
scope_Handles.forEach(function(handle, index){
// Disabled handles are ignored
if ( handle.hasAttribute('disabled') ) {
return;
}
var pos = Math.abs(scope_Locations[index] - proposal);
if ( pos < closest ) {
handleNumber = index;
closest = pos;
}
});
return handleNumber;
}
|
javascript
|
function getClosestHandle ( proposal ) {
var closest = 100;
var handleNumber = false;
scope_Handles.forEach(function(handle, index){
// Disabled handles are ignored
if ( handle.hasAttribute('disabled') ) {
return;
}
var pos = Math.abs(scope_Locations[index] - proposal);
if ( pos < closest ) {
handleNumber = index;
closest = pos;
}
});
return handleNumber;
}
|
[
"function",
"getClosestHandle",
"(",
"proposal",
")",
"{",
"var",
"closest",
"=",
"100",
";",
"var",
"handleNumber",
"=",
"false",
";",
"scope_Handles",
".",
"forEach",
"(",
"function",
"(",
"handle",
",",
"index",
")",
"{",
"if",
"(",
"handle",
".",
"hasAttribute",
"(",
"'disabled'",
")",
")",
"{",
"return",
";",
"}",
"var",
"pos",
"=",
"Math",
".",
"abs",
"(",
"scope_Locations",
"[",
"index",
"]",
"-",
"proposal",
")",
";",
"if",
"(",
"pos",
"<",
"closest",
")",
"{",
"handleNumber",
"=",
"index",
";",
"closest",
"=",
"pos",
";",
"}",
"}",
")",
";",
"return",
"handleNumber",
";",
"}"
] |
Find handle closest to a certain percentage on the slider
|
[
"Find",
"handle",
"closest",
"to",
"a",
"certain",
"percentage",
"on",
"the",
"slider"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1367-L1388
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
fireEvent
|
function fireEvent ( eventName, handleNumber, tap ) {
Object.keys(scope_Events).forEach(function( targetEvent ) {
var eventType = targetEvent.split('.')[0];
if ( eventName === eventType ) {
scope_Events[targetEvent].forEach(function( callback ) {
callback.call(
// Use the slider public API as the scope ('this')
scope_Self,
// Return values as array, so arg_1[arg_2] is always valid.
scope_Values.map(options.format.to),
// Handle index, 0 or 1
handleNumber,
// Unformatted slider values
scope_Values.slice(),
// Event is fired by tap, true or false
tap || false,
// Left offset of the handle, in relation to the slider
scope_Locations.slice()
);
});
}
});
}
|
javascript
|
function fireEvent ( eventName, handleNumber, tap ) {
Object.keys(scope_Events).forEach(function( targetEvent ) {
var eventType = targetEvent.split('.')[0];
if ( eventName === eventType ) {
scope_Events[targetEvent].forEach(function( callback ) {
callback.call(
// Use the slider public API as the scope ('this')
scope_Self,
// Return values as array, so arg_1[arg_2] is always valid.
scope_Values.map(options.format.to),
// Handle index, 0 or 1
handleNumber,
// Unformatted slider values
scope_Values.slice(),
// Event is fired by tap, true or false
tap || false,
// Left offset of the handle, in relation to the slider
scope_Locations.slice()
);
});
}
});
}
|
[
"function",
"fireEvent",
"(",
"eventName",
",",
"handleNumber",
",",
"tap",
")",
"{",
"Object",
".",
"keys",
"(",
"scope_Events",
")",
".",
"forEach",
"(",
"function",
"(",
"targetEvent",
")",
"{",
"var",
"eventType",
"=",
"targetEvent",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
";",
"if",
"(",
"eventName",
"===",
"eventType",
")",
"{",
"scope_Events",
"[",
"targetEvent",
"]",
".",
"forEach",
"(",
"function",
"(",
"callback",
")",
"{",
"callback",
".",
"call",
"(",
"scope_Self",
",",
"scope_Values",
".",
"map",
"(",
"options",
".",
"format",
".",
"to",
")",
",",
"handleNumber",
",",
"scope_Values",
".",
"slice",
"(",
")",
",",
"tap",
"||",
"false",
",",
"scope_Locations",
".",
"slice",
"(",
")",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] |
External event handling
|
[
"External",
"event",
"handling"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1447-L1473
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
documentLeave
|
function documentLeave ( event, data ) {
if ( event.type === "mouseout" && event.target.nodeName === "HTML" && event.relatedTarget === null ){
eventEnd (event, data);
}
}
|
javascript
|
function documentLeave ( event, data ) {
if ( event.type === "mouseout" && event.target.nodeName === "HTML" && event.relatedTarget === null ){
eventEnd (event, data);
}
}
|
[
"function",
"documentLeave",
"(",
"event",
",",
"data",
")",
"{",
"if",
"(",
"event",
".",
"type",
"===",
"\"mouseout\"",
"&&",
"event",
".",
"target",
".",
"nodeName",
"===",
"\"HTML\"",
"&&",
"event",
".",
"relatedTarget",
"===",
"null",
")",
"{",
"eventEnd",
"(",
"event",
",",
"data",
")",
";",
"}",
"}"
] |
Fire 'end' when a mouse or pen leaves the document.
|
[
"Fire",
"end",
"when",
"a",
"mouse",
"or",
"pen",
"leaves",
"the",
"document",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1477-L1481
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
eventMove
|
function eventMove ( event, data ) {
// Fix #498
// Check value of .buttons in 'start' to work around a bug in IE10 mobile (data.buttonsProperty).
// https://connect.microsoft.com/IE/feedback/details/927005/mobile-ie10-windows-phone-buttons-property-of-pointermove-event-always-zero
// IE9 has .buttons and .which zero on mousemove.
// Firefox breaks the spec MDN defines.
if ( navigator.appVersion.indexOf("MSIE 9") === -1 && event.buttons === 0 && data.buttonsProperty !== 0 ) {
return eventEnd(event, data);
}
// Check if we are moving up or down
var movement = (options.dir ? -1 : 1) * (event.calcPoint - data.startCalcPoint);
// Convert the movement into a percentage of the slider width/height
var proposal = (movement * 100) / data.baseSize;
moveHandles(movement > 0, proposal, data.locations, data.handleNumbers);
}
|
javascript
|
function eventMove ( event, data ) {
// Fix #498
// Check value of .buttons in 'start' to work around a bug in IE10 mobile (data.buttonsProperty).
// https://connect.microsoft.com/IE/feedback/details/927005/mobile-ie10-windows-phone-buttons-property-of-pointermove-event-always-zero
// IE9 has .buttons and .which zero on mousemove.
// Firefox breaks the spec MDN defines.
if ( navigator.appVersion.indexOf("MSIE 9") === -1 && event.buttons === 0 && data.buttonsProperty !== 0 ) {
return eventEnd(event, data);
}
// Check if we are moving up or down
var movement = (options.dir ? -1 : 1) * (event.calcPoint - data.startCalcPoint);
// Convert the movement into a percentage of the slider width/height
var proposal = (movement * 100) / data.baseSize;
moveHandles(movement > 0, proposal, data.locations, data.handleNumbers);
}
|
[
"function",
"eventMove",
"(",
"event",
",",
"data",
")",
"{",
"if",
"(",
"navigator",
".",
"appVersion",
".",
"indexOf",
"(",
"\"MSIE 9\"",
")",
"===",
"-",
"1",
"&&",
"event",
".",
"buttons",
"===",
"0",
"&&",
"data",
".",
"buttonsProperty",
"!==",
"0",
")",
"{",
"return",
"eventEnd",
"(",
"event",
",",
"data",
")",
";",
"}",
"var",
"movement",
"=",
"(",
"options",
".",
"dir",
"?",
"-",
"1",
":",
"1",
")",
"*",
"(",
"event",
".",
"calcPoint",
"-",
"data",
".",
"startCalcPoint",
")",
";",
"var",
"proposal",
"=",
"(",
"movement",
"*",
"100",
")",
"/",
"data",
".",
"baseSize",
";",
"moveHandles",
"(",
"movement",
">",
"0",
",",
"proposal",
",",
"data",
".",
"locations",
",",
"data",
".",
"handleNumbers",
")",
";",
"}"
] |
Handle movement on document for handle and range drag.
|
[
"Handle",
"movement",
"on",
"document",
"for",
"handle",
"and",
"range",
"drag",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1484-L1502
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
eventEnd
|
function eventEnd ( event, data ) {
// The handle is no longer active, so remove the class.
if ( scope_ActiveHandle ) {
removeClass(scope_ActiveHandle, options.cssClasses.active);
scope_ActiveHandle = false;
}
// Remove cursor styles and text-selection events bound to the body.
if ( event.cursor ) {
document.body.style.cursor = '';
document.body.removeEventListener('selectstart', document.body.noUiListener);
}
// Unbind the move and end events, which are added on 'start'.
document.documentElement.noUiListeners.forEach(function( c ) {
document.documentElement.removeEventListener(c[0], c[1]);
});
// Remove dragging class.
removeClass(scope_Target, options.cssClasses.drag);
setZindex();
data.handleNumbers.forEach(function(handleNumber){
fireEvent('set', handleNumber);
fireEvent('change', handleNumber);
fireEvent('end', handleNumber);
});
}
|
javascript
|
function eventEnd ( event, data ) {
// The handle is no longer active, so remove the class.
if ( scope_ActiveHandle ) {
removeClass(scope_ActiveHandle, options.cssClasses.active);
scope_ActiveHandle = false;
}
// Remove cursor styles and text-selection events bound to the body.
if ( event.cursor ) {
document.body.style.cursor = '';
document.body.removeEventListener('selectstart', document.body.noUiListener);
}
// Unbind the move and end events, which are added on 'start'.
document.documentElement.noUiListeners.forEach(function( c ) {
document.documentElement.removeEventListener(c[0], c[1]);
});
// Remove dragging class.
removeClass(scope_Target, options.cssClasses.drag);
setZindex();
data.handleNumbers.forEach(function(handleNumber){
fireEvent('set', handleNumber);
fireEvent('change', handleNumber);
fireEvent('end', handleNumber);
});
}
|
[
"function",
"eventEnd",
"(",
"event",
",",
"data",
")",
"{",
"if",
"(",
"scope_ActiveHandle",
")",
"{",
"removeClass",
"(",
"scope_ActiveHandle",
",",
"options",
".",
"cssClasses",
".",
"active",
")",
";",
"scope_ActiveHandle",
"=",
"false",
";",
"}",
"if",
"(",
"event",
".",
"cursor",
")",
"{",
"document",
".",
"body",
".",
"style",
".",
"cursor",
"=",
"''",
";",
"document",
".",
"body",
".",
"removeEventListener",
"(",
"'selectstart'",
",",
"document",
".",
"body",
".",
"noUiListener",
")",
";",
"}",
"document",
".",
"documentElement",
".",
"noUiListeners",
".",
"forEach",
"(",
"function",
"(",
"c",
")",
"{",
"document",
".",
"documentElement",
".",
"removeEventListener",
"(",
"c",
"[",
"0",
"]",
",",
"c",
"[",
"1",
"]",
")",
";",
"}",
")",
";",
"removeClass",
"(",
"scope_Target",
",",
"options",
".",
"cssClasses",
".",
"drag",
")",
";",
"setZindex",
"(",
")",
";",
"data",
".",
"handleNumbers",
".",
"forEach",
"(",
"function",
"(",
"handleNumber",
")",
"{",
"fireEvent",
"(",
"'set'",
",",
"handleNumber",
")",
";",
"fireEvent",
"(",
"'change'",
",",
"handleNumber",
")",
";",
"fireEvent",
"(",
"'end'",
",",
"handleNumber",
")",
";",
"}",
")",
";",
"}"
] |
Unbind move events on document, call callbacks.
|
[
"Unbind",
"move",
"events",
"on",
"document",
"call",
"callbacks",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1505-L1534
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
eventStart
|
function eventStart ( event, data ) {
if ( data.handleNumbers.length === 1 ) {
var handle = scope_Handles[data.handleNumbers[0]];
// Ignore 'disabled' handles
if ( handle.hasAttribute('disabled') ) {
return false;
}
// Mark the handle as 'active' so it can be styled.
scope_ActiveHandle = handle.children[0];
addClass(scope_ActiveHandle, options.cssClasses.active);
}
// Fix #551, where a handle gets selected instead of dragged.
event.preventDefault();
// A drag should never propagate up to the 'tap' event.
event.stopPropagation();
// Attach the move and end events.
var moveEvent = attachEvent(actions.move, document.documentElement, eventMove, {
startCalcPoint: event.calcPoint,
baseSize: baseSize(),
pageOffset: event.pageOffset,
handleNumbers: data.handleNumbers,
buttonsProperty: event.buttons,
locations: scope_Locations.slice()
});
var endEvent = attachEvent(actions.end, document.documentElement, eventEnd, {
handleNumbers: data.handleNumbers
});
var outEvent = attachEvent("mouseout", document.documentElement, documentLeave, {
handleNumbers: data.handleNumbers
});
document.documentElement.noUiListeners = moveEvent.concat(endEvent, outEvent);
// Text selection isn't an issue on touch devices,
// so adding cursor styles can be skipped.
if ( event.cursor ) {
// Prevent the 'I' cursor and extend the range-drag cursor.
document.body.style.cursor = getComputedStyle(event.target).cursor;
// Mark the target with a dragging state.
if ( scope_Handles.length > 1 ) {
addClass(scope_Target, options.cssClasses.drag);
}
var f = function(){
return false;
};
document.body.noUiListener = f;
// Prevent text selection when dragging the handles.
document.body.addEventListener('selectstart', f, false);
}
data.handleNumbers.forEach(function(handleNumber){
fireEvent('start', handleNumber);
});
}
|
javascript
|
function eventStart ( event, data ) {
if ( data.handleNumbers.length === 1 ) {
var handle = scope_Handles[data.handleNumbers[0]];
// Ignore 'disabled' handles
if ( handle.hasAttribute('disabled') ) {
return false;
}
// Mark the handle as 'active' so it can be styled.
scope_ActiveHandle = handle.children[0];
addClass(scope_ActiveHandle, options.cssClasses.active);
}
// Fix #551, where a handle gets selected instead of dragged.
event.preventDefault();
// A drag should never propagate up to the 'tap' event.
event.stopPropagation();
// Attach the move and end events.
var moveEvent = attachEvent(actions.move, document.documentElement, eventMove, {
startCalcPoint: event.calcPoint,
baseSize: baseSize(),
pageOffset: event.pageOffset,
handleNumbers: data.handleNumbers,
buttonsProperty: event.buttons,
locations: scope_Locations.slice()
});
var endEvent = attachEvent(actions.end, document.documentElement, eventEnd, {
handleNumbers: data.handleNumbers
});
var outEvent = attachEvent("mouseout", document.documentElement, documentLeave, {
handleNumbers: data.handleNumbers
});
document.documentElement.noUiListeners = moveEvent.concat(endEvent, outEvent);
// Text selection isn't an issue on touch devices,
// so adding cursor styles can be skipped.
if ( event.cursor ) {
// Prevent the 'I' cursor and extend the range-drag cursor.
document.body.style.cursor = getComputedStyle(event.target).cursor;
// Mark the target with a dragging state.
if ( scope_Handles.length > 1 ) {
addClass(scope_Target, options.cssClasses.drag);
}
var f = function(){
return false;
};
document.body.noUiListener = f;
// Prevent text selection when dragging the handles.
document.body.addEventListener('selectstart', f, false);
}
data.handleNumbers.forEach(function(handleNumber){
fireEvent('start', handleNumber);
});
}
|
[
"function",
"eventStart",
"(",
"event",
",",
"data",
")",
"{",
"if",
"(",
"data",
".",
"handleNumbers",
".",
"length",
"===",
"1",
")",
"{",
"var",
"handle",
"=",
"scope_Handles",
"[",
"data",
".",
"handleNumbers",
"[",
"0",
"]",
"]",
";",
"if",
"(",
"handle",
".",
"hasAttribute",
"(",
"'disabled'",
")",
")",
"{",
"return",
"false",
";",
"}",
"scope_ActiveHandle",
"=",
"handle",
".",
"children",
"[",
"0",
"]",
";",
"addClass",
"(",
"scope_ActiveHandle",
",",
"options",
".",
"cssClasses",
".",
"active",
")",
";",
"}",
"event",
".",
"preventDefault",
"(",
")",
";",
"event",
".",
"stopPropagation",
"(",
")",
";",
"var",
"moveEvent",
"=",
"attachEvent",
"(",
"actions",
".",
"move",
",",
"document",
".",
"documentElement",
",",
"eventMove",
",",
"{",
"startCalcPoint",
":",
"event",
".",
"calcPoint",
",",
"baseSize",
":",
"baseSize",
"(",
")",
",",
"pageOffset",
":",
"event",
".",
"pageOffset",
",",
"handleNumbers",
":",
"data",
".",
"handleNumbers",
",",
"buttonsProperty",
":",
"event",
".",
"buttons",
",",
"locations",
":",
"scope_Locations",
".",
"slice",
"(",
")",
"}",
")",
";",
"var",
"endEvent",
"=",
"attachEvent",
"(",
"actions",
".",
"end",
",",
"document",
".",
"documentElement",
",",
"eventEnd",
",",
"{",
"handleNumbers",
":",
"data",
".",
"handleNumbers",
"}",
")",
";",
"var",
"outEvent",
"=",
"attachEvent",
"(",
"\"mouseout\"",
",",
"document",
".",
"documentElement",
",",
"documentLeave",
",",
"{",
"handleNumbers",
":",
"data",
".",
"handleNumbers",
"}",
")",
";",
"document",
".",
"documentElement",
".",
"noUiListeners",
"=",
"moveEvent",
".",
"concat",
"(",
"endEvent",
",",
"outEvent",
")",
";",
"if",
"(",
"event",
".",
"cursor",
")",
"{",
"document",
".",
"body",
".",
"style",
".",
"cursor",
"=",
"getComputedStyle",
"(",
"event",
".",
"target",
")",
".",
"cursor",
";",
"if",
"(",
"scope_Handles",
".",
"length",
">",
"1",
")",
"{",
"addClass",
"(",
"scope_Target",
",",
"options",
".",
"cssClasses",
".",
"drag",
")",
";",
"}",
"var",
"f",
"=",
"function",
"(",
")",
"{",
"return",
"false",
";",
"}",
";",
"document",
".",
"body",
".",
"noUiListener",
"=",
"f",
";",
"document",
".",
"body",
".",
"addEventListener",
"(",
"'selectstart'",
",",
"f",
",",
"false",
")",
";",
"}",
"data",
".",
"handleNumbers",
".",
"forEach",
"(",
"function",
"(",
"handleNumber",
")",
"{",
"fireEvent",
"(",
"'start'",
",",
"handleNumber",
")",
";",
"}",
")",
";",
"}"
] |
Bind move events on document.
|
[
"Bind",
"move",
"events",
"on",
"document",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1537-L1604
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
eventTap
|
function eventTap ( event ) {
// The tap event shouldn't propagate up
event.stopPropagation();
var proposal = calcPointToPercentage(event.calcPoint);
var handleNumber = getClosestHandle(proposal);
// Tackle the case that all handles are 'disabled'.
if ( handleNumber === false ) {
return false;
}
// Flag the slider as it is now in a transitional state.
// Transition takes a configurable amount of ms (default 300). Re-enable the slider after that.
if ( !options.events.snap ) {
addClassFor(scope_Target, options.cssClasses.tap, options.animationDuration);
}
setHandle(handleNumber, proposal, true, true);
setZindex();
fireEvent('slide', handleNumber, true);
fireEvent('set', handleNumber, true);
fireEvent('change', handleNumber, true);
fireEvent('update', handleNumber, true);
if ( options.events.snap ) {
eventStart(event, { handleNumbers: [handleNumber] });
}
}
|
javascript
|
function eventTap ( event ) {
// The tap event shouldn't propagate up
event.stopPropagation();
var proposal = calcPointToPercentage(event.calcPoint);
var handleNumber = getClosestHandle(proposal);
// Tackle the case that all handles are 'disabled'.
if ( handleNumber === false ) {
return false;
}
// Flag the slider as it is now in a transitional state.
// Transition takes a configurable amount of ms (default 300). Re-enable the slider after that.
if ( !options.events.snap ) {
addClassFor(scope_Target, options.cssClasses.tap, options.animationDuration);
}
setHandle(handleNumber, proposal, true, true);
setZindex();
fireEvent('slide', handleNumber, true);
fireEvent('set', handleNumber, true);
fireEvent('change', handleNumber, true);
fireEvent('update', handleNumber, true);
if ( options.events.snap ) {
eventStart(event, { handleNumbers: [handleNumber] });
}
}
|
[
"function",
"eventTap",
"(",
"event",
")",
"{",
"event",
".",
"stopPropagation",
"(",
")",
";",
"var",
"proposal",
"=",
"calcPointToPercentage",
"(",
"event",
".",
"calcPoint",
")",
";",
"var",
"handleNumber",
"=",
"getClosestHandle",
"(",
"proposal",
")",
";",
"if",
"(",
"handleNumber",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"options",
".",
"events",
".",
"snap",
")",
"{",
"addClassFor",
"(",
"scope_Target",
",",
"options",
".",
"cssClasses",
".",
"tap",
",",
"options",
".",
"animationDuration",
")",
";",
"}",
"setHandle",
"(",
"handleNumber",
",",
"proposal",
",",
"true",
",",
"true",
")",
";",
"setZindex",
"(",
")",
";",
"fireEvent",
"(",
"'slide'",
",",
"handleNumber",
",",
"true",
")",
";",
"fireEvent",
"(",
"'set'",
",",
"handleNumber",
",",
"true",
")",
";",
"fireEvent",
"(",
"'change'",
",",
"handleNumber",
",",
"true",
")",
";",
"fireEvent",
"(",
"'update'",
",",
"handleNumber",
",",
"true",
")",
";",
"if",
"(",
"options",
".",
"events",
".",
"snap",
")",
"{",
"eventStart",
"(",
"event",
",",
"{",
"handleNumbers",
":",
"[",
"handleNumber",
"]",
"}",
")",
";",
"}",
"}"
] |
Move closest handle to tapped location.
|
[
"Move",
"closest",
"handle",
"to",
"tapped",
"location",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1607-L1638
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
bindSliderEvents
|
function bindSliderEvents ( behaviour ) {
// Attach the standard drag event to the handles.
if ( !behaviour.fixed ) {
scope_Handles.forEach(function( handle, index ){
// These events are only bound to the visual handle
// element, not the 'real' origin element.
attachEvent ( actions.start, handle.children[0], eventStart, {
handleNumbers: [index]
});
});
}
// Attach the tap event to the slider base.
if ( behaviour.tap ) {
attachEvent (actions.start, scope_Base, eventTap, {});
}
// Fire hover events
if ( behaviour.hover ) {
attachEvent (actions.move, scope_Base, eventHover, { hover: true });
}
// Make the range draggable.
if ( behaviour.drag ){
scope_Connects.forEach(function( connect, index ){
if ( connect === false || index === 0 || index === scope_Connects.length - 1 ) {
return;
}
var handleBefore = scope_Handles[index - 1];
var handleAfter = scope_Handles[index];
var eventHolders = [connect];
addClass(connect, options.cssClasses.draggable);
// When the range is fixed, the entire range can
// be dragged by the handles. The handle in the first
// origin will propagate the start event upward,
// but it needs to be bound manually on the other.
if ( behaviour.fixed ) {
eventHolders.push(handleBefore.children[0]);
eventHolders.push(handleAfter.children[0]);
}
eventHolders.forEach(function( eventHolder ) {
attachEvent ( actions.start, eventHolder, eventStart, {
handles: [handleBefore, handleAfter],
handleNumbers: [index - 1, index]
});
});
});
}
}
|
javascript
|
function bindSliderEvents ( behaviour ) {
// Attach the standard drag event to the handles.
if ( !behaviour.fixed ) {
scope_Handles.forEach(function( handle, index ){
// These events are only bound to the visual handle
// element, not the 'real' origin element.
attachEvent ( actions.start, handle.children[0], eventStart, {
handleNumbers: [index]
});
});
}
// Attach the tap event to the slider base.
if ( behaviour.tap ) {
attachEvent (actions.start, scope_Base, eventTap, {});
}
// Fire hover events
if ( behaviour.hover ) {
attachEvent (actions.move, scope_Base, eventHover, { hover: true });
}
// Make the range draggable.
if ( behaviour.drag ){
scope_Connects.forEach(function( connect, index ){
if ( connect === false || index === 0 || index === scope_Connects.length - 1 ) {
return;
}
var handleBefore = scope_Handles[index - 1];
var handleAfter = scope_Handles[index];
var eventHolders = [connect];
addClass(connect, options.cssClasses.draggable);
// When the range is fixed, the entire range can
// be dragged by the handles. The handle in the first
// origin will propagate the start event upward,
// but it needs to be bound manually on the other.
if ( behaviour.fixed ) {
eventHolders.push(handleBefore.children[0]);
eventHolders.push(handleAfter.children[0]);
}
eventHolders.forEach(function( eventHolder ) {
attachEvent ( actions.start, eventHolder, eventStart, {
handles: [handleBefore, handleAfter],
handleNumbers: [index - 1, index]
});
});
});
}
}
|
[
"function",
"bindSliderEvents",
"(",
"behaviour",
")",
"{",
"if",
"(",
"!",
"behaviour",
".",
"fixed",
")",
"{",
"scope_Handles",
".",
"forEach",
"(",
"function",
"(",
"handle",
",",
"index",
")",
"{",
"attachEvent",
"(",
"actions",
".",
"start",
",",
"handle",
".",
"children",
"[",
"0",
"]",
",",
"eventStart",
",",
"{",
"handleNumbers",
":",
"[",
"index",
"]",
"}",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"behaviour",
".",
"tap",
")",
"{",
"attachEvent",
"(",
"actions",
".",
"start",
",",
"scope_Base",
",",
"eventTap",
",",
"{",
"}",
")",
";",
"}",
"if",
"(",
"behaviour",
".",
"hover",
")",
"{",
"attachEvent",
"(",
"actions",
".",
"move",
",",
"scope_Base",
",",
"eventHover",
",",
"{",
"hover",
":",
"true",
"}",
")",
";",
"}",
"if",
"(",
"behaviour",
".",
"drag",
")",
"{",
"scope_Connects",
".",
"forEach",
"(",
"function",
"(",
"connect",
",",
"index",
")",
"{",
"if",
"(",
"connect",
"===",
"false",
"||",
"index",
"===",
"0",
"||",
"index",
"===",
"scope_Connects",
".",
"length",
"-",
"1",
")",
"{",
"return",
";",
"}",
"var",
"handleBefore",
"=",
"scope_Handles",
"[",
"index",
"-",
"1",
"]",
";",
"var",
"handleAfter",
"=",
"scope_Handles",
"[",
"index",
"]",
";",
"var",
"eventHolders",
"=",
"[",
"connect",
"]",
";",
"addClass",
"(",
"connect",
",",
"options",
".",
"cssClasses",
".",
"draggable",
")",
";",
"if",
"(",
"behaviour",
".",
"fixed",
")",
"{",
"eventHolders",
".",
"push",
"(",
"handleBefore",
".",
"children",
"[",
"0",
"]",
")",
";",
"eventHolders",
".",
"push",
"(",
"handleAfter",
".",
"children",
"[",
"0",
"]",
")",
";",
"}",
"eventHolders",
".",
"forEach",
"(",
"function",
"(",
"eventHolder",
")",
"{",
"attachEvent",
"(",
"actions",
".",
"start",
",",
"eventHolder",
",",
"eventStart",
",",
"{",
"handles",
":",
"[",
"handleBefore",
",",
"handleAfter",
"]",
",",
"handleNumbers",
":",
"[",
"index",
"-",
"1",
",",
"index",
"]",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"}"
] |
Attach events to several slider parts.
|
[
"Attach",
"events",
"to",
"several",
"slider",
"parts",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1658-L1715
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
checkHandlePosition
|
function checkHandlePosition ( reference, handleNumber, to, lookBackward, lookForward ) {
// For sliders with multiple handles, limit movement to the other handle.
// Apply the margin option by adding it to the handle positions.
if ( scope_Handles.length > 1 ) {
if ( lookBackward && handleNumber > 0 ) {
to = Math.max(to, reference[handleNumber - 1] + options.margin);
}
if ( lookForward && handleNumber < scope_Handles.length - 1 ) {
to = Math.min(to, reference[handleNumber + 1] - options.margin);
}
}
// The limit option has the opposite effect, limiting handles to a
// maximum distance from another. Limit must be > 0, as otherwise
// handles would be unmoveable.
if ( scope_Handles.length > 1 && options.limit ) {
if ( lookBackward && handleNumber > 0 ) {
to = Math.min(to, reference[handleNumber - 1] + options.limit);
}
if ( lookForward && handleNumber < scope_Handles.length - 1 ) {
to = Math.max(to, reference[handleNumber + 1] - options.limit);
}
}
// The padding option keeps the handles a certain distance from the
// edges of the slider. Padding must be > 0.
if ( options.padding ) {
if ( handleNumber === 0 ) {
to = Math.max(to, options.padding);
}
if ( handleNumber === scope_Handles.length - 1 ) {
to = Math.min(to, 100 - options.padding);
}
}
to = scope_Spectrum.getStep(to);
// Limit percentage to the 0 - 100 range
to = limit(to);
// Return false if handle can't move
if ( to === reference[handleNumber] ) {
return false;
}
return to;
}
|
javascript
|
function checkHandlePosition ( reference, handleNumber, to, lookBackward, lookForward ) {
// For sliders with multiple handles, limit movement to the other handle.
// Apply the margin option by adding it to the handle positions.
if ( scope_Handles.length > 1 ) {
if ( lookBackward && handleNumber > 0 ) {
to = Math.max(to, reference[handleNumber - 1] + options.margin);
}
if ( lookForward && handleNumber < scope_Handles.length - 1 ) {
to = Math.min(to, reference[handleNumber + 1] - options.margin);
}
}
// The limit option has the opposite effect, limiting handles to a
// maximum distance from another. Limit must be > 0, as otherwise
// handles would be unmoveable.
if ( scope_Handles.length > 1 && options.limit ) {
if ( lookBackward && handleNumber > 0 ) {
to = Math.min(to, reference[handleNumber - 1] + options.limit);
}
if ( lookForward && handleNumber < scope_Handles.length - 1 ) {
to = Math.max(to, reference[handleNumber + 1] - options.limit);
}
}
// The padding option keeps the handles a certain distance from the
// edges of the slider. Padding must be > 0.
if ( options.padding ) {
if ( handleNumber === 0 ) {
to = Math.max(to, options.padding);
}
if ( handleNumber === scope_Handles.length - 1 ) {
to = Math.min(to, 100 - options.padding);
}
}
to = scope_Spectrum.getStep(to);
// Limit percentage to the 0 - 100 range
to = limit(to);
// Return false if handle can't move
if ( to === reference[handleNumber] ) {
return false;
}
return to;
}
|
[
"function",
"checkHandlePosition",
"(",
"reference",
",",
"handleNumber",
",",
"to",
",",
"lookBackward",
",",
"lookForward",
")",
"{",
"if",
"(",
"scope_Handles",
".",
"length",
">",
"1",
")",
"{",
"if",
"(",
"lookBackward",
"&&",
"handleNumber",
">",
"0",
")",
"{",
"to",
"=",
"Math",
".",
"max",
"(",
"to",
",",
"reference",
"[",
"handleNumber",
"-",
"1",
"]",
"+",
"options",
".",
"margin",
")",
";",
"}",
"if",
"(",
"lookForward",
"&&",
"handleNumber",
"<",
"scope_Handles",
".",
"length",
"-",
"1",
")",
"{",
"to",
"=",
"Math",
".",
"min",
"(",
"to",
",",
"reference",
"[",
"handleNumber",
"+",
"1",
"]",
"-",
"options",
".",
"margin",
")",
";",
"}",
"}",
"if",
"(",
"scope_Handles",
".",
"length",
">",
"1",
"&&",
"options",
".",
"limit",
")",
"{",
"if",
"(",
"lookBackward",
"&&",
"handleNumber",
">",
"0",
")",
"{",
"to",
"=",
"Math",
".",
"min",
"(",
"to",
",",
"reference",
"[",
"handleNumber",
"-",
"1",
"]",
"+",
"options",
".",
"limit",
")",
";",
"}",
"if",
"(",
"lookForward",
"&&",
"handleNumber",
"<",
"scope_Handles",
".",
"length",
"-",
"1",
")",
"{",
"to",
"=",
"Math",
".",
"max",
"(",
"to",
",",
"reference",
"[",
"handleNumber",
"+",
"1",
"]",
"-",
"options",
".",
"limit",
")",
";",
"}",
"}",
"if",
"(",
"options",
".",
"padding",
")",
"{",
"if",
"(",
"handleNumber",
"===",
"0",
")",
"{",
"to",
"=",
"Math",
".",
"max",
"(",
"to",
",",
"options",
".",
"padding",
")",
";",
"}",
"if",
"(",
"handleNumber",
"===",
"scope_Handles",
".",
"length",
"-",
"1",
")",
"{",
"to",
"=",
"Math",
".",
"min",
"(",
"to",
",",
"100",
"-",
"options",
".",
"padding",
")",
";",
"}",
"}",
"to",
"=",
"scope_Spectrum",
".",
"getStep",
"(",
"to",
")",
";",
"to",
"=",
"limit",
"(",
"to",
")",
";",
"if",
"(",
"to",
"===",
"reference",
"[",
"handleNumber",
"]",
")",
"{",
"return",
"false",
";",
"}",
"return",
"to",
";",
"}"
] |
Split out the handle positioning logic so the Move event can use it, too
|
[
"Split",
"out",
"the",
"handle",
"positioning",
"logic",
"so",
"the",
"Move",
"event",
"can",
"use",
"it",
"too"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1719-L1772
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
updateHandlePosition
|
function updateHandlePosition ( handleNumber, to ) {
// Update locations.
scope_Locations[handleNumber] = to;
// Convert the value to the slider stepping/range.
scope_Values[handleNumber] = scope_Spectrum.fromStepping(to);
// Called synchronously or on the next animationFrame
var stateUpdate = function() {
scope_Handles[handleNumber].style[options.style] = toPct(to);
updateConnect(handleNumber);
updateConnect(handleNumber + 1);
};
// Set the handle to the new position.
// Use requestAnimationFrame for efficient painting.
// No significant effect in Chrome, Edge sees dramatic performace improvements.
// Option to disable is useful for unit tests, and single-step debugging.
if ( window.requestAnimationFrame && options.useRequestAnimationFrame ) {
window.requestAnimationFrame(stateUpdate);
} else {
stateUpdate();
}
}
|
javascript
|
function updateHandlePosition ( handleNumber, to ) {
// Update locations.
scope_Locations[handleNumber] = to;
// Convert the value to the slider stepping/range.
scope_Values[handleNumber] = scope_Spectrum.fromStepping(to);
// Called synchronously or on the next animationFrame
var stateUpdate = function() {
scope_Handles[handleNumber].style[options.style] = toPct(to);
updateConnect(handleNumber);
updateConnect(handleNumber + 1);
};
// Set the handle to the new position.
// Use requestAnimationFrame for efficient painting.
// No significant effect in Chrome, Edge sees dramatic performace improvements.
// Option to disable is useful for unit tests, and single-step debugging.
if ( window.requestAnimationFrame && options.useRequestAnimationFrame ) {
window.requestAnimationFrame(stateUpdate);
} else {
stateUpdate();
}
}
|
[
"function",
"updateHandlePosition",
"(",
"handleNumber",
",",
"to",
")",
"{",
"scope_Locations",
"[",
"handleNumber",
"]",
"=",
"to",
";",
"scope_Values",
"[",
"handleNumber",
"]",
"=",
"scope_Spectrum",
".",
"fromStepping",
"(",
"to",
")",
";",
"var",
"stateUpdate",
"=",
"function",
"(",
")",
"{",
"scope_Handles",
"[",
"handleNumber",
"]",
".",
"style",
"[",
"options",
".",
"style",
"]",
"=",
"toPct",
"(",
"to",
")",
";",
"updateConnect",
"(",
"handleNumber",
")",
";",
"updateConnect",
"(",
"handleNumber",
"+",
"1",
")",
";",
"}",
";",
"if",
"(",
"window",
".",
"requestAnimationFrame",
"&&",
"options",
".",
"useRequestAnimationFrame",
")",
"{",
"window",
".",
"requestAnimationFrame",
"(",
"stateUpdate",
")",
";",
"}",
"else",
"{",
"stateUpdate",
"(",
")",
";",
"}",
"}"
] |
Updates scope_Locations and scope_Values, updates visual state
|
[
"Updates",
"scope_Locations",
"and",
"scope_Values",
"updates",
"visual",
"state"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1779-L1803
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
function() {
scope_Handles[handleNumber].style[options.style] = toPct(to);
updateConnect(handleNumber);
updateConnect(handleNumber + 1);
}
|
javascript
|
function() {
scope_Handles[handleNumber].style[options.style] = toPct(to);
updateConnect(handleNumber);
updateConnect(handleNumber + 1);
}
|
[
"function",
"(",
")",
"{",
"scope_Handles",
"[",
"handleNumber",
"]",
".",
"style",
"[",
"options",
".",
"style",
"]",
"=",
"toPct",
"(",
"to",
")",
";",
"updateConnect",
"(",
"handleNumber",
")",
";",
"updateConnect",
"(",
"handleNumber",
"+",
"1",
")",
";",
"}"
] |
Called synchronously or on the next animationFrame
|
[
"Called",
"synchronously",
"or",
"on",
"the",
"next",
"animationFrame"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1788-L1792
|
train
|
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
setHandle
|
function setHandle ( handleNumber, to, lookBackward, lookForward ) {
to = checkHandlePosition(scope_Locations, handleNumber, to, lookBackward, lookForward);
if ( to === false ) {
return false;
}
updateHandlePosition(handleNumber, to);
return true;
}
|
javascript
|
function setHandle ( handleNumber, to, lookBackward, lookForward ) {
to = checkHandlePosition(scope_Locations, handleNumber, to, lookBackward, lookForward);
if ( to === false ) {
return false;
}
updateHandlePosition(handleNumber, to);
return true;
}
|
[
"function",
"setHandle",
"(",
"handleNumber",
",",
"to",
",",
"lookBackward",
",",
"lookForward",
")",
"{",
"to",
"=",
"checkHandlePosition",
"(",
"scope_Locations",
",",
"handleNumber",
",",
"to",
",",
"lookBackward",
",",
"lookForward",
")",
";",
"if",
"(",
"to",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"updateHandlePosition",
"(",
"handleNumber",
",",
"to",
")",
";",
"return",
"true",
";",
"}"
] |
Test suggested values and apply margin, step.
|
[
"Test",
"suggested",
"values",
"and",
"apply",
"margin",
"step",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1818-L1829
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
updateConnect
|
function updateConnect ( index ) {
// Skip connects set to false
if ( !scope_Connects[index] ) {
return;
}
var l = 0;
var h = 100;
if ( index !== 0 ) {
l = scope_Locations[index - 1];
}
if ( index !== scope_Connects.length - 1 ) {
h = scope_Locations[index];
}
scope_Connects[index].style[options.style] = toPct(l);
scope_Connects[index].style[options.styleOposite] = toPct(100 - h);
}
|
javascript
|
function updateConnect ( index ) {
// Skip connects set to false
if ( !scope_Connects[index] ) {
return;
}
var l = 0;
var h = 100;
if ( index !== 0 ) {
l = scope_Locations[index - 1];
}
if ( index !== scope_Connects.length - 1 ) {
h = scope_Locations[index];
}
scope_Connects[index].style[options.style] = toPct(l);
scope_Connects[index].style[options.styleOposite] = toPct(100 - h);
}
|
[
"function",
"updateConnect",
"(",
"index",
")",
"{",
"if",
"(",
"!",
"scope_Connects",
"[",
"index",
"]",
")",
"{",
"return",
";",
"}",
"var",
"l",
"=",
"0",
";",
"var",
"h",
"=",
"100",
";",
"if",
"(",
"index",
"!==",
"0",
")",
"{",
"l",
"=",
"scope_Locations",
"[",
"index",
"-",
"1",
"]",
";",
"}",
"if",
"(",
"index",
"!==",
"scope_Connects",
".",
"length",
"-",
"1",
")",
"{",
"h",
"=",
"scope_Locations",
"[",
"index",
"]",
";",
"}",
"scope_Connects",
"[",
"index",
"]",
".",
"style",
"[",
"options",
".",
"style",
"]",
"=",
"toPct",
"(",
"l",
")",
";",
"scope_Connects",
"[",
"index",
"]",
".",
"style",
"[",
"options",
".",
"styleOposite",
"]",
"=",
"toPct",
"(",
"100",
"-",
"h",
")",
";",
"}"
] |
Updates style attribute for connect nodes
|
[
"Updates",
"style",
"attribute",
"for",
"connect",
"nodes"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1832-L1852
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
valueSet
|
function valueSet ( input, fireSetEvent ) {
var values = asArray(input);
var isInit = scope_Locations[0] === undefined;
// Event fires by default
fireSetEvent = (fireSetEvent === undefined ? true : !!fireSetEvent);
values.forEach(setValue);
// Animation is optional.
// Make sure the initial values were set before using animated placement.
if ( options.animate && !isInit ) {
addClassFor(scope_Target, options.cssClasses.tap, options.animationDuration);
}
// Now that all base values are set, apply constraints
scope_HandleNumbers.forEach(function(handleNumber){
setHandle(handleNumber, scope_Locations[handleNumber], true, false);
});
setZindex();
scope_HandleNumbers.forEach(function(handleNumber){
fireEvent('update', handleNumber);
// Fire the event only for handles that received a new value, as per #579
if ( values[handleNumber] !== null && fireSetEvent ) {
fireEvent('set', handleNumber);
}
});
}
|
javascript
|
function valueSet ( input, fireSetEvent ) {
var values = asArray(input);
var isInit = scope_Locations[0] === undefined;
// Event fires by default
fireSetEvent = (fireSetEvent === undefined ? true : !!fireSetEvent);
values.forEach(setValue);
// Animation is optional.
// Make sure the initial values were set before using animated placement.
if ( options.animate && !isInit ) {
addClassFor(scope_Target, options.cssClasses.tap, options.animationDuration);
}
// Now that all base values are set, apply constraints
scope_HandleNumbers.forEach(function(handleNumber){
setHandle(handleNumber, scope_Locations[handleNumber], true, false);
});
setZindex();
scope_HandleNumbers.forEach(function(handleNumber){
fireEvent('update', handleNumber);
// Fire the event only for handles that received a new value, as per #579
if ( values[handleNumber] !== null && fireSetEvent ) {
fireEvent('set', handleNumber);
}
});
}
|
[
"function",
"valueSet",
"(",
"input",
",",
"fireSetEvent",
")",
"{",
"var",
"values",
"=",
"asArray",
"(",
"input",
")",
";",
"var",
"isInit",
"=",
"scope_Locations",
"[",
"0",
"]",
"===",
"undefined",
";",
"fireSetEvent",
"=",
"(",
"fireSetEvent",
"===",
"undefined",
"?",
"true",
":",
"!",
"!",
"fireSetEvent",
")",
";",
"values",
".",
"forEach",
"(",
"setValue",
")",
";",
"if",
"(",
"options",
".",
"animate",
"&&",
"!",
"isInit",
")",
"{",
"addClassFor",
"(",
"scope_Target",
",",
"options",
".",
"cssClasses",
".",
"tap",
",",
"options",
".",
"animationDuration",
")",
";",
"}",
"scope_HandleNumbers",
".",
"forEach",
"(",
"function",
"(",
"handleNumber",
")",
"{",
"setHandle",
"(",
"handleNumber",
",",
"scope_Locations",
"[",
"handleNumber",
"]",
",",
"true",
",",
"false",
")",
";",
"}",
")",
";",
"setZindex",
"(",
")",
";",
"scope_HandleNumbers",
".",
"forEach",
"(",
"function",
"(",
"handleNumber",
")",
"{",
"fireEvent",
"(",
"'update'",
",",
"handleNumber",
")",
";",
"if",
"(",
"values",
"[",
"handleNumber",
"]",
"!==",
"null",
"&&",
"fireSetEvent",
")",
"{",
"fireEvent",
"(",
"'set'",
",",
"handleNumber",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Set the slider value.
|
[
"Set",
"the",
"slider",
"value",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1878-L1910
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
valueGet
|
function valueGet ( ) {
var values = scope_Values.map(options.format.to);
// If only one handle is used, return a single value.
if ( values.length === 1 ){
return values[0];
}
return values;
}
|
javascript
|
function valueGet ( ) {
var values = scope_Values.map(options.format.to);
// If only one handle is used, return a single value.
if ( values.length === 1 ){
return values[0];
}
return values;
}
|
[
"function",
"valueGet",
"(",
")",
"{",
"var",
"values",
"=",
"scope_Values",
".",
"map",
"(",
"options",
".",
"format",
".",
"to",
")",
";",
"if",
"(",
"values",
".",
"length",
"===",
"1",
")",
"{",
"return",
"values",
"[",
"0",
"]",
";",
"}",
"return",
"values",
";",
"}"
] |
Get the slider value.
|
[
"Get",
"the",
"slider",
"value",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1918-L1928
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
destroy
|
function destroy ( ) {
for ( var key in options.cssClasses ) {
if ( !options.cssClasses.hasOwnProperty(key) ) { continue; }
removeClass(scope_Target, options.cssClasses[key]);
}
while (scope_Target.firstChild) {
scope_Target.removeChild(scope_Target.firstChild);
}
delete scope_Target.noUiSlider;
}
|
javascript
|
function destroy ( ) {
for ( var key in options.cssClasses ) {
if ( !options.cssClasses.hasOwnProperty(key) ) { continue; }
removeClass(scope_Target, options.cssClasses[key]);
}
while (scope_Target.firstChild) {
scope_Target.removeChild(scope_Target.firstChild);
}
delete scope_Target.noUiSlider;
}
|
[
"function",
"destroy",
"(",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"options",
".",
"cssClasses",
")",
"{",
"if",
"(",
"!",
"options",
".",
"cssClasses",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"continue",
";",
"}",
"removeClass",
"(",
"scope_Target",
",",
"options",
".",
"cssClasses",
"[",
"key",
"]",
")",
";",
"}",
"while",
"(",
"scope_Target",
".",
"firstChild",
")",
"{",
"scope_Target",
".",
"removeChild",
"(",
"scope_Target",
".",
"firstChild",
")",
";",
"}",
"delete",
"scope_Target",
".",
"noUiSlider",
";",
"}"
] |
Removes classes from the root and empties it.
|
[
"Removes",
"classes",
"from",
"the",
"root",
"and",
"empties",
"it",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1931-L1943
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
getCurrentStep
|
function getCurrentStep ( ) {
// Check all locations, map them to their stepping point.
// Get the step point, then find it in the input list.
return scope_Locations.map(function( location, index ){
var nearbySteps = scope_Spectrum.getNearbySteps( location );
var value = scope_Values[index];
var increment = nearbySteps.thisStep.step;
var decrement = null;
// If the next value in this step moves into the next step,
// the increment is the start of the next step - the current value
if ( increment !== false ) {
if ( value + increment > nearbySteps.stepAfter.startValue ) {
increment = nearbySteps.stepAfter.startValue - value;
}
}
// If the value is beyond the starting point
if ( value > nearbySteps.thisStep.startValue ) {
decrement = nearbySteps.thisStep.step;
}
else if ( nearbySteps.stepBefore.step === false ) {
decrement = false;
}
// If a handle is at the start of a step, it always steps back into the previous step first
else {
decrement = value - nearbySteps.stepBefore.highestStep;
}
// Now, if at the slider edges, there is not in/decrement
if ( location === 100 ) {
increment = null;
}
else if ( location === 0 ) {
decrement = null;
}
// As per #391, the comparison for the decrement step can have some rounding issues.
var stepDecimals = scope_Spectrum.countStepDecimals();
// Round per #391
if ( increment !== null && increment !== false ) {
increment = Number(increment.toFixed(stepDecimals));
}
if ( decrement !== null && decrement !== false ) {
decrement = Number(decrement.toFixed(stepDecimals));
}
return [decrement, increment];
});
}
|
javascript
|
function getCurrentStep ( ) {
// Check all locations, map them to their stepping point.
// Get the step point, then find it in the input list.
return scope_Locations.map(function( location, index ){
var nearbySteps = scope_Spectrum.getNearbySteps( location );
var value = scope_Values[index];
var increment = nearbySteps.thisStep.step;
var decrement = null;
// If the next value in this step moves into the next step,
// the increment is the start of the next step - the current value
if ( increment !== false ) {
if ( value + increment > nearbySteps.stepAfter.startValue ) {
increment = nearbySteps.stepAfter.startValue - value;
}
}
// If the value is beyond the starting point
if ( value > nearbySteps.thisStep.startValue ) {
decrement = nearbySteps.thisStep.step;
}
else if ( nearbySteps.stepBefore.step === false ) {
decrement = false;
}
// If a handle is at the start of a step, it always steps back into the previous step first
else {
decrement = value - nearbySteps.stepBefore.highestStep;
}
// Now, if at the slider edges, there is not in/decrement
if ( location === 100 ) {
increment = null;
}
else if ( location === 0 ) {
decrement = null;
}
// As per #391, the comparison for the decrement step can have some rounding issues.
var stepDecimals = scope_Spectrum.countStepDecimals();
// Round per #391
if ( increment !== null && increment !== false ) {
increment = Number(increment.toFixed(stepDecimals));
}
if ( decrement !== null && decrement !== false ) {
decrement = Number(decrement.toFixed(stepDecimals));
}
return [decrement, increment];
});
}
|
[
"function",
"getCurrentStep",
"(",
")",
"{",
"return",
"scope_Locations",
".",
"map",
"(",
"function",
"(",
"location",
",",
"index",
")",
"{",
"var",
"nearbySteps",
"=",
"scope_Spectrum",
".",
"getNearbySteps",
"(",
"location",
")",
";",
"var",
"value",
"=",
"scope_Values",
"[",
"index",
"]",
";",
"var",
"increment",
"=",
"nearbySteps",
".",
"thisStep",
".",
"step",
";",
"var",
"decrement",
"=",
"null",
";",
"if",
"(",
"increment",
"!==",
"false",
")",
"{",
"if",
"(",
"value",
"+",
"increment",
">",
"nearbySteps",
".",
"stepAfter",
".",
"startValue",
")",
"{",
"increment",
"=",
"nearbySteps",
".",
"stepAfter",
".",
"startValue",
"-",
"value",
";",
"}",
"}",
"if",
"(",
"value",
">",
"nearbySteps",
".",
"thisStep",
".",
"startValue",
")",
"{",
"decrement",
"=",
"nearbySteps",
".",
"thisStep",
".",
"step",
";",
"}",
"else",
"if",
"(",
"nearbySteps",
".",
"stepBefore",
".",
"step",
"===",
"false",
")",
"{",
"decrement",
"=",
"false",
";",
"}",
"else",
"{",
"decrement",
"=",
"value",
"-",
"nearbySteps",
".",
"stepBefore",
".",
"highestStep",
";",
"}",
"if",
"(",
"location",
"===",
"100",
")",
"{",
"increment",
"=",
"null",
";",
"}",
"else",
"if",
"(",
"location",
"===",
"0",
")",
"{",
"decrement",
"=",
"null",
";",
"}",
"var",
"stepDecimals",
"=",
"scope_Spectrum",
".",
"countStepDecimals",
"(",
")",
";",
"if",
"(",
"increment",
"!==",
"null",
"&&",
"increment",
"!==",
"false",
")",
"{",
"increment",
"=",
"Number",
"(",
"increment",
".",
"toFixed",
"(",
"stepDecimals",
")",
")",
";",
"}",
"if",
"(",
"decrement",
"!==",
"null",
"&&",
"decrement",
"!==",
"false",
")",
"{",
"decrement",
"=",
"Number",
"(",
"decrement",
".",
"toFixed",
"(",
"stepDecimals",
")",
")",
";",
"}",
"return",
"[",
"decrement",
",",
"increment",
"]",
";",
"}",
")",
";",
"}"
] |
Get the current step size for the slider.
|
[
"Get",
"the",
"current",
"step",
"size",
"for",
"the",
"slider",
"."
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1946-L2004
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
bindEvent
|
function bindEvent ( namespacedEvent, callback ) {
scope_Events[namespacedEvent] = scope_Events[namespacedEvent] || [];
scope_Events[namespacedEvent].push(callback);
// If the event bound is 'update,' fire it immediately for all handles.
if ( namespacedEvent.split('.')[0] === 'update' ) {
scope_Handles.forEach(function(a, index){
fireEvent('update', index);
});
}
}
|
javascript
|
function bindEvent ( namespacedEvent, callback ) {
scope_Events[namespacedEvent] = scope_Events[namespacedEvent] || [];
scope_Events[namespacedEvent].push(callback);
// If the event bound is 'update,' fire it immediately for all handles.
if ( namespacedEvent.split('.')[0] === 'update' ) {
scope_Handles.forEach(function(a, index){
fireEvent('update', index);
});
}
}
|
[
"function",
"bindEvent",
"(",
"namespacedEvent",
",",
"callback",
")",
"{",
"scope_Events",
"[",
"namespacedEvent",
"]",
"=",
"scope_Events",
"[",
"namespacedEvent",
"]",
"||",
"[",
"]",
";",
"scope_Events",
"[",
"namespacedEvent",
"]",
".",
"push",
"(",
"callback",
")",
";",
"if",
"(",
"namespacedEvent",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"===",
"'update'",
")",
"{",
"scope_Handles",
".",
"forEach",
"(",
"function",
"(",
"a",
",",
"index",
")",
"{",
"fireEvent",
"(",
"'update'",
",",
"index",
")",
";",
"}",
")",
";",
"}",
"}"
] |
Attach an event to this slider, possibly including a namespace
|
[
"Attach",
"an",
"event",
"to",
"this",
"slider",
"possibly",
"including",
"a",
"namespace"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L2007-L2017
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
removeEvent
|
function removeEvent ( namespacedEvent ) {
var event = namespacedEvent && namespacedEvent.split('.')[0];
var namespace = event && namespacedEvent.substring(event.length);
Object.keys(scope_Events).forEach(function( bind ){
var tEvent = bind.split('.')[0],
tNamespace = bind.substring(tEvent.length);
if ( (!event || event === tEvent) && (!namespace || namespace === tNamespace) ) {
delete scope_Events[bind];
}
});
}
|
javascript
|
function removeEvent ( namespacedEvent ) {
var event = namespacedEvent && namespacedEvent.split('.')[0];
var namespace = event && namespacedEvent.substring(event.length);
Object.keys(scope_Events).forEach(function( bind ){
var tEvent = bind.split('.')[0],
tNamespace = bind.substring(tEvent.length);
if ( (!event || event === tEvent) && (!namespace || namespace === tNamespace) ) {
delete scope_Events[bind];
}
});
}
|
[
"function",
"removeEvent",
"(",
"namespacedEvent",
")",
"{",
"var",
"event",
"=",
"namespacedEvent",
"&&",
"namespacedEvent",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
";",
"var",
"namespace",
"=",
"event",
"&&",
"namespacedEvent",
".",
"substring",
"(",
"event",
".",
"length",
")",
";",
"Object",
".",
"keys",
"(",
"scope_Events",
")",
".",
"forEach",
"(",
"function",
"(",
"bind",
")",
"{",
"var",
"tEvent",
"=",
"bind",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
",",
"tNamespace",
"=",
"bind",
".",
"substring",
"(",
"tEvent",
".",
"length",
")",
";",
"if",
"(",
"(",
"!",
"event",
"||",
"event",
"===",
"tEvent",
")",
"&&",
"(",
"!",
"namespace",
"||",
"namespace",
"===",
"tNamespace",
")",
")",
"{",
"delete",
"scope_Events",
"[",
"bind",
"]",
";",
"}",
"}",
")",
";",
"}"
] |
Undo attachment of event
|
[
"Undo",
"attachment",
"of",
"event"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L2020-L2034
|
train
|
Dogfalo/materialize
|
extras/noUiSlider/nouislider.js
|
initialize
|
function initialize ( target, originalOptions ) {
if ( !target.nodeName ) {
throw new Error('noUiSlider.create requires a single element.');
}
if (originalOptions.tooltips === undefined) {
originalOptions.tooltips = true;
}
// Test the options and create the slider environment;
var options = testOptions( originalOptions, target );
var api = closure( target, options, originalOptions );
target.noUiSlider = api;
return api;
}
|
javascript
|
function initialize ( target, originalOptions ) {
if ( !target.nodeName ) {
throw new Error('noUiSlider.create requires a single element.');
}
if (originalOptions.tooltips === undefined) {
originalOptions.tooltips = true;
}
// Test the options and create the slider environment;
var options = testOptions( originalOptions, target );
var api = closure( target, options, originalOptions );
target.noUiSlider = api;
return api;
}
|
[
"function",
"initialize",
"(",
"target",
",",
"originalOptions",
")",
"{",
"if",
"(",
"!",
"target",
".",
"nodeName",
")",
"{",
"throw",
"new",
"Error",
"(",
"'noUiSlider.create requires a single element.'",
")",
";",
"}",
"if",
"(",
"originalOptions",
".",
"tooltips",
"===",
"undefined",
")",
"{",
"originalOptions",
".",
"tooltips",
"=",
"true",
";",
"}",
"var",
"options",
"=",
"testOptions",
"(",
"originalOptions",
",",
"target",
")",
";",
"var",
"api",
"=",
"closure",
"(",
"target",
",",
"options",
",",
"originalOptions",
")",
";",
"target",
".",
"noUiSlider",
"=",
"api",
";",
"return",
"api",
";",
"}"
] |
Run the standard initializer
|
[
"Run",
"the",
"standard",
"initializer"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L2123-L2140
|
train
|
Dogfalo/materialize
|
docs/js/init.js
|
rgb2hex
|
function rgb2hex(rgb) {
if (/^#[0-9A-F]{6}$/i.test(rgb)) {
return rgb;
}
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if (rgb === null) {
return 'N/A';
}
function hex(x) {
return ('0' + parseInt(x).toString(16)).slice(-2);
}
return '#' + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
|
javascript
|
function rgb2hex(rgb) {
if (/^#[0-9A-F]{6}$/i.test(rgb)) {
return rgb;
}
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if (rgb === null) {
return 'N/A';
}
function hex(x) {
return ('0' + parseInt(x).toString(16)).slice(-2);
}
return '#' + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
|
[
"function",
"rgb2hex",
"(",
"rgb",
")",
"{",
"if",
"(",
"/",
"^#[0-9A-F]{6}$",
"/",
"i",
".",
"test",
"(",
"rgb",
")",
")",
"{",
"return",
"rgb",
";",
"}",
"rgb",
"=",
"rgb",
".",
"match",
"(",
"/",
"^rgb\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)$",
"/",
")",
";",
"if",
"(",
"rgb",
"===",
"null",
")",
"{",
"return",
"'N/A'",
";",
"}",
"function",
"hex",
"(",
"x",
")",
"{",
"return",
"(",
"'0'",
"+",
"parseInt",
"(",
"x",
")",
".",
"toString",
"(",
"16",
")",
")",
".",
"slice",
"(",
"-",
"2",
")",
";",
"}",
"return",
"'#'",
"+",
"hex",
"(",
"rgb",
"[",
"1",
"]",
")",
"+",
"hex",
"(",
"rgb",
"[",
"2",
"]",
")",
"+",
"hex",
"(",
"rgb",
"[",
"3",
"]",
")",
";",
"}"
] |
convert rgb to hex value string
|
[
"convert",
"rgb",
"to",
"hex",
"value",
"string"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/docs/js/init.js#L6-L22
|
train
|
Dogfalo/materialize
|
dist/js/materialize.js
|
function (eventName, data) {
if (document.createEvent) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent(eventName, true, false);
evt = this.extend(evt, data);
return this.each(function (v) {
return v.dispatchEvent(evt);
});
}
}
|
javascript
|
function (eventName, data) {
if (document.createEvent) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent(eventName, true, false);
evt = this.extend(evt, data);
return this.each(function (v) {
return v.dispatchEvent(evt);
});
}
}
|
[
"function",
"(",
"eventName",
",",
"data",
")",
"{",
"if",
"(",
"document",
".",
"createEvent",
")",
"{",
"var",
"evt",
"=",
"document",
".",
"createEvent",
"(",
"'HTMLEvents'",
")",
";",
"evt",
".",
"initEvent",
"(",
"eventName",
",",
"true",
",",
"false",
")",
";",
"evt",
"=",
"this",
".",
"extend",
"(",
"evt",
",",
"data",
")",
";",
"return",
"this",
".",
"each",
"(",
"function",
"(",
"v",
")",
"{",
"return",
"v",
".",
"dispatchEvent",
"(",
"evt",
")",
";",
"}",
")",
";",
"}",
"}"
] |
Modified
Triggers browser event
@param String eventName
@param Object data - Add properties to event object
|
[
"Modified",
"Triggers",
"browser",
"event"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/dist/js/materialize.js#L636-L645
|
train
|
|
Dogfalo/materialize
|
dist/js/materialize.js
|
Component
|
function Component(classDef, el, options) {
_classCallCheck(this, Component);
// Display error if el is valid HTML Element
if (!(el instanceof Element)) {
console.error(Error(el + ' is not an HTML Element'));
}
// If exists, destroy and reinitialize in child
var ins = classDef.getInstance(el);
if (!!ins) {
ins.destroy();
}
this.el = el;
this.$el = cash(el);
}
|
javascript
|
function Component(classDef, el, options) {
_classCallCheck(this, Component);
// Display error if el is valid HTML Element
if (!(el instanceof Element)) {
console.error(Error(el + ' is not an HTML Element'));
}
// If exists, destroy and reinitialize in child
var ins = classDef.getInstance(el);
if (!!ins) {
ins.destroy();
}
this.el = el;
this.$el = cash(el);
}
|
[
"function",
"Component",
"(",
"classDef",
",",
"el",
",",
"options",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"Component",
")",
";",
"if",
"(",
"!",
"(",
"el",
"instanceof",
"Element",
")",
")",
"{",
"console",
".",
"error",
"(",
"Error",
"(",
"el",
"+",
"' is not an HTML Element'",
")",
")",
";",
"}",
"var",
"ins",
"=",
"classDef",
".",
"getInstance",
"(",
"el",
")",
";",
"if",
"(",
"!",
"!",
"ins",
")",
"{",
"ins",
".",
"destroy",
"(",
")",
";",
"}",
"this",
".",
"el",
"=",
"el",
";",
"this",
".",
"$el",
"=",
"cash",
"(",
"el",
")",
";",
"}"
] |
Generic constructor for all components
@constructor
@param {Element} el
@param {Object} options
|
[
"Generic",
"constructor",
"for",
"all",
"components"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/dist/js/materialize.js#L1014-L1030
|
train
|
Dogfalo/materialize
|
dist/js/materialize.js
|
Modal
|
function Modal(el, options) {
_classCallCheck(this, Modal);
var _this13 = _possibleConstructorReturn(this, (Modal.__proto__ || Object.getPrototypeOf(Modal)).call(this, Modal, el, options));
_this13.el.M_Modal = _this13;
/**
* Options for the modal
* @member Modal#options
* @prop {Number} [opacity=0.5] - Opacity of the modal overlay
* @prop {Number} [inDuration=250] - Length in ms of enter transition
* @prop {Number} [outDuration=250] - Length in ms of exit transition
* @prop {Function} onOpenStart - Callback function called before modal is opened
* @prop {Function} onOpenEnd - Callback function called after modal is opened
* @prop {Function} onCloseStart - Callback function called before modal is closed
* @prop {Function} onCloseEnd - Callback function called after modal is closed
* @prop {Boolean} [dismissible=true] - Allow modal to be dismissed by keyboard or overlay click
* @prop {String} [startingTop='4%'] - startingTop
* @prop {String} [endingTop='10%'] - endingTop
*/
_this13.options = $.extend({}, Modal.defaults, options);
/**
* Describes open/close state of modal
* @type {Boolean}
*/
_this13.isOpen = false;
_this13.id = _this13.$el.attr('id');
_this13._openingTrigger = undefined;
_this13.$overlay = $('<div class="modal-overlay"></div>');
_this13.el.tabIndex = 0;
_this13._nthModalOpened = 0;
Modal._count++;
_this13._setupEventHandlers();
return _this13;
}
|
javascript
|
function Modal(el, options) {
_classCallCheck(this, Modal);
var _this13 = _possibleConstructorReturn(this, (Modal.__proto__ || Object.getPrototypeOf(Modal)).call(this, Modal, el, options));
_this13.el.M_Modal = _this13;
/**
* Options for the modal
* @member Modal#options
* @prop {Number} [opacity=0.5] - Opacity of the modal overlay
* @prop {Number} [inDuration=250] - Length in ms of enter transition
* @prop {Number} [outDuration=250] - Length in ms of exit transition
* @prop {Function} onOpenStart - Callback function called before modal is opened
* @prop {Function} onOpenEnd - Callback function called after modal is opened
* @prop {Function} onCloseStart - Callback function called before modal is closed
* @prop {Function} onCloseEnd - Callback function called after modal is closed
* @prop {Boolean} [dismissible=true] - Allow modal to be dismissed by keyboard or overlay click
* @prop {String} [startingTop='4%'] - startingTop
* @prop {String} [endingTop='10%'] - endingTop
*/
_this13.options = $.extend({}, Modal.defaults, options);
/**
* Describes open/close state of modal
* @type {Boolean}
*/
_this13.isOpen = false;
_this13.id = _this13.$el.attr('id');
_this13._openingTrigger = undefined;
_this13.$overlay = $('<div class="modal-overlay"></div>');
_this13.el.tabIndex = 0;
_this13._nthModalOpened = 0;
Modal._count++;
_this13._setupEventHandlers();
return _this13;
}
|
[
"function",
"Modal",
"(",
"el",
",",
"options",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"Modal",
")",
";",
"var",
"_this13",
"=",
"_possibleConstructorReturn",
"(",
"this",
",",
"(",
"Modal",
".",
"__proto__",
"||",
"Object",
".",
"getPrototypeOf",
"(",
"Modal",
")",
")",
".",
"call",
"(",
"this",
",",
"Modal",
",",
"el",
",",
"options",
")",
")",
";",
"_this13",
".",
"el",
".",
"M_Modal",
"=",
"_this13",
";",
"_this13",
".",
"options",
"=",
"$",
".",
"extend",
"(",
"{",
"}",
",",
"Modal",
".",
"defaults",
",",
"options",
")",
";",
"_this13",
".",
"isOpen",
"=",
"false",
";",
"_this13",
".",
"id",
"=",
"_this13",
".",
"$el",
".",
"attr",
"(",
"'id'",
")",
";",
"_this13",
".",
"_openingTrigger",
"=",
"undefined",
";",
"_this13",
".",
"$overlay",
"=",
"$",
"(",
"'<div class=\"modal-overlay\"></div>'",
")",
";",
"_this13",
".",
"el",
".",
"tabIndex",
"=",
"0",
";",
"_this13",
".",
"_nthModalOpened",
"=",
"0",
";",
"Modal",
".",
"_count",
"++",
";",
"_this13",
".",
"_setupEventHandlers",
"(",
")",
";",
"return",
"_this13",
";",
"}"
] |
Construct Modal instance and set up overlay
@constructor
@param {Element} el
@param {Object} options
|
[
"Construct",
"Modal",
"instance",
"and",
"set",
"up",
"overlay"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/dist/js/materialize.js#L2893-L2931
|
train
|
Dogfalo/materialize
|
dist/js/materialize.js
|
function () {
if (typeof _this14.options.onOpenEnd === 'function') {
_this14.options.onOpenEnd.call(_this14, _this14.el, _this14._openingTrigger);
}
}
|
javascript
|
function () {
if (typeof _this14.options.onOpenEnd === 'function') {
_this14.options.onOpenEnd.call(_this14, _this14.el, _this14._openingTrigger);
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"typeof",
"_this14",
".",
"options",
".",
"onOpenEnd",
"===",
"'function'",
")",
"{",
"_this14",
".",
"options",
".",
"onOpenEnd",
".",
"call",
"(",
"_this14",
",",
"_this14",
".",
"el",
",",
"_this14",
".",
"_openingTrigger",
")",
";",
"}",
"}"
] |
Handle modal onOpenEnd callback
|
[
"Handle",
"modal",
"onOpenEnd",
"callback"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/dist/js/materialize.js#L3085-L3089
|
train
|
|
Dogfalo/materialize
|
dist/js/materialize.js
|
function () {
_this15.el.style.display = 'none';
_this15.$overlay.remove();
// Call onCloseEnd callback
if (typeof _this15.options.onCloseEnd === 'function') {
_this15.options.onCloseEnd.call(_this15, _this15.el);
}
}
|
javascript
|
function () {
_this15.el.style.display = 'none';
_this15.$overlay.remove();
// Call onCloseEnd callback
if (typeof _this15.options.onCloseEnd === 'function') {
_this15.options.onCloseEnd.call(_this15, _this15.el);
}
}
|
[
"function",
"(",
")",
"{",
"_this15",
".",
"el",
".",
"style",
".",
"display",
"=",
"'none'",
";",
"_this15",
".",
"$overlay",
".",
"remove",
"(",
")",
";",
"if",
"(",
"typeof",
"_this15",
".",
"options",
".",
"onCloseEnd",
"===",
"'function'",
")",
"{",
"_this15",
".",
"options",
".",
"onCloseEnd",
".",
"call",
"(",
"_this15",
",",
"_this15",
".",
"el",
")",
";",
"}",
"}"
] |
Handle modal ready callback
|
[
"Handle",
"modal",
"ready",
"callback"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/dist/js/materialize.js#L3135-L3143
|
train
|
|
Dogfalo/materialize
|
dist/js/materialize.js
|
Materialbox
|
function Materialbox(el, options) {
_classCallCheck(this, Materialbox);
var _this16 = _possibleConstructorReturn(this, (Materialbox.__proto__ || Object.getPrototypeOf(Materialbox)).call(this, Materialbox, el, options));
_this16.el.M_Materialbox = _this16;
/**
* Options for the modal
* @member Materialbox#options
* @prop {Number} [inDuration=275] - Length in ms of enter transition
* @prop {Number} [outDuration=200] - Length in ms of exit transition
* @prop {Function} onOpenStart - Callback function called before materialbox is opened
* @prop {Function} onOpenEnd - Callback function called after materialbox is opened
* @prop {Function} onCloseStart - Callback function called before materialbox is closed
* @prop {Function} onCloseEnd - Callback function called after materialbox is closed
*/
_this16.options = $.extend({}, Materialbox.defaults, options);
_this16.overlayActive = false;
_this16.doneAnimating = true;
_this16.placeholder = $('<div></div>').addClass('material-placeholder');
_this16.originalWidth = 0;
_this16.originalHeight = 0;
_this16.originInlineStyles = _this16.$el.attr('style');
_this16.caption = _this16.el.getAttribute('data-caption') || '';
// Wrap
_this16.$el.before(_this16.placeholder);
_this16.placeholder.append(_this16.$el);
_this16._setupEventHandlers();
return _this16;
}
|
javascript
|
function Materialbox(el, options) {
_classCallCheck(this, Materialbox);
var _this16 = _possibleConstructorReturn(this, (Materialbox.__proto__ || Object.getPrototypeOf(Materialbox)).call(this, Materialbox, el, options));
_this16.el.M_Materialbox = _this16;
/**
* Options for the modal
* @member Materialbox#options
* @prop {Number} [inDuration=275] - Length in ms of enter transition
* @prop {Number} [outDuration=200] - Length in ms of exit transition
* @prop {Function} onOpenStart - Callback function called before materialbox is opened
* @prop {Function} onOpenEnd - Callback function called after materialbox is opened
* @prop {Function} onCloseStart - Callback function called before materialbox is closed
* @prop {Function} onCloseEnd - Callback function called after materialbox is closed
*/
_this16.options = $.extend({}, Materialbox.defaults, options);
_this16.overlayActive = false;
_this16.doneAnimating = true;
_this16.placeholder = $('<div></div>').addClass('material-placeholder');
_this16.originalWidth = 0;
_this16.originalHeight = 0;
_this16.originInlineStyles = _this16.$el.attr('style');
_this16.caption = _this16.el.getAttribute('data-caption') || '';
// Wrap
_this16.$el.before(_this16.placeholder);
_this16.placeholder.append(_this16.$el);
_this16._setupEventHandlers();
return _this16;
}
|
[
"function",
"Materialbox",
"(",
"el",
",",
"options",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"Materialbox",
")",
";",
"var",
"_this16",
"=",
"_possibleConstructorReturn",
"(",
"this",
",",
"(",
"Materialbox",
".",
"__proto__",
"||",
"Object",
".",
"getPrototypeOf",
"(",
"Materialbox",
")",
")",
".",
"call",
"(",
"this",
",",
"Materialbox",
",",
"el",
",",
"options",
")",
")",
";",
"_this16",
".",
"el",
".",
"M_Materialbox",
"=",
"_this16",
";",
"_this16",
".",
"options",
"=",
"$",
".",
"extend",
"(",
"{",
"}",
",",
"Materialbox",
".",
"defaults",
",",
"options",
")",
";",
"_this16",
".",
"overlayActive",
"=",
"false",
";",
"_this16",
".",
"doneAnimating",
"=",
"true",
";",
"_this16",
".",
"placeholder",
"=",
"$",
"(",
"'<div></div>'",
")",
".",
"addClass",
"(",
"'material-placeholder'",
")",
";",
"_this16",
".",
"originalWidth",
"=",
"0",
";",
"_this16",
".",
"originalHeight",
"=",
"0",
";",
"_this16",
".",
"originInlineStyles",
"=",
"_this16",
".",
"$el",
".",
"attr",
"(",
"'style'",
")",
";",
"_this16",
".",
"caption",
"=",
"_this16",
".",
"el",
".",
"getAttribute",
"(",
"'data-caption'",
")",
"||",
"''",
";",
"_this16",
".",
"$el",
".",
"before",
"(",
"_this16",
".",
"placeholder",
")",
";",
"_this16",
".",
"placeholder",
".",
"append",
"(",
"_this16",
".",
"$el",
")",
";",
"_this16",
".",
"_setupEventHandlers",
"(",
")",
";",
"return",
"_this16",
";",
"}"
] |
Construct Materialbox instance
@constructor
@param {Element} el
@param {Object} options
|
[
"Construct",
"Materialbox",
"instance"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/dist/js/materialize.js#L3327-L3360
|
train
|
Dogfalo/materialize
|
dist/js/materialize.js
|
_createToast
|
function _createToast() {
var toast = document.createElement('div');
toast.classList.add('toast');
// Add custom classes onto toast
if (!!this.options.classes.length) {
$(toast).addClass(this.options.classes);
}
// Set content
if (typeof HTMLElement === 'object' ? this.message instanceof HTMLElement : this.message && typeof this.message === 'object' && this.message !== null && this.message.nodeType === 1 && typeof this.message.nodeName === 'string') {
toast.appendChild(this.message);
// Check if it is jQuery object
} else if (!!this.message.jquery) {
$(toast).append(this.message[0]);
// Insert as html;
} else {
toast.innerHTML = this.message;
}
// Append toasft
Toast._container.appendChild(toast);
return toast;
}
|
javascript
|
function _createToast() {
var toast = document.createElement('div');
toast.classList.add('toast');
// Add custom classes onto toast
if (!!this.options.classes.length) {
$(toast).addClass(this.options.classes);
}
// Set content
if (typeof HTMLElement === 'object' ? this.message instanceof HTMLElement : this.message && typeof this.message === 'object' && this.message !== null && this.message.nodeType === 1 && typeof this.message.nodeName === 'string') {
toast.appendChild(this.message);
// Check if it is jQuery object
} else if (!!this.message.jquery) {
$(toast).append(this.message[0]);
// Insert as html;
} else {
toast.innerHTML = this.message;
}
// Append toasft
Toast._container.appendChild(toast);
return toast;
}
|
[
"function",
"_createToast",
"(",
")",
"{",
"var",
"toast",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"toast",
".",
"classList",
".",
"add",
"(",
"'toast'",
")",
";",
"if",
"(",
"!",
"!",
"this",
".",
"options",
".",
"classes",
".",
"length",
")",
"{",
"$",
"(",
"toast",
")",
".",
"addClass",
"(",
"this",
".",
"options",
".",
"classes",
")",
";",
"}",
"if",
"(",
"typeof",
"HTMLElement",
"===",
"'object'",
"?",
"this",
".",
"message",
"instanceof",
"HTMLElement",
":",
"this",
".",
"message",
"&&",
"typeof",
"this",
".",
"message",
"===",
"'object'",
"&&",
"this",
".",
"message",
"!==",
"null",
"&&",
"this",
".",
"message",
".",
"nodeType",
"===",
"1",
"&&",
"typeof",
"this",
".",
"message",
".",
"nodeName",
"===",
"'string'",
")",
"{",
"toast",
".",
"appendChild",
"(",
"this",
".",
"message",
")",
";",
"}",
"else",
"if",
"(",
"!",
"!",
"this",
".",
"message",
".",
"jquery",
")",
"{",
"$",
"(",
"toast",
")",
".",
"append",
"(",
"this",
".",
"message",
"[",
"0",
"]",
")",
";",
"}",
"else",
"{",
"toast",
".",
"innerHTML",
"=",
"this",
".",
"message",
";",
"}",
"Toast",
".",
"_container",
".",
"appendChild",
"(",
"toast",
")",
";",
"return",
"toast",
";",
"}"
] |
Create toast and append it to toast container
|
[
"Create",
"toast",
"and",
"append",
"it",
"to",
"toast",
"container"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/dist/js/materialize.js#L5163-L5188
|
train
|
Dogfalo/materialize
|
dist/js/materialize.js
|
Sidenav
|
function Sidenav(el, options) {
_classCallCheck(this, Sidenav);
var _this31 = _possibleConstructorReturn(this, (Sidenav.__proto__ || Object.getPrototypeOf(Sidenav)).call(this, Sidenav, el, options));
_this31.el.M_Sidenav = _this31;
_this31.id = _this31.$el.attr('id');
/**
* Options for the Sidenav
* @member Sidenav#options
* @prop {String} [edge='left'] - Side of screen on which Sidenav appears
* @prop {Boolean} [draggable=true] - Allow swipe gestures to open/close Sidenav
* @prop {Number} [inDuration=250] - Length in ms of enter transition
* @prop {Number} [outDuration=200] - Length in ms of exit transition
* @prop {Function} onOpenStart - Function called when sidenav starts entering
* @prop {Function} onOpenEnd - Function called when sidenav finishes entering
* @prop {Function} onCloseStart - Function called when sidenav starts exiting
* @prop {Function} onCloseEnd - Function called when sidenav finishes exiting
*/
_this31.options = $.extend({}, Sidenav.defaults, options);
/**
* Describes open/close state of Sidenav
* @type {Boolean}
*/
_this31.isOpen = false;
/**
* Describes if Sidenav is fixed
* @type {Boolean}
*/
_this31.isFixed = _this31.el.classList.contains('sidenav-fixed');
/**
* Describes if Sidenav is being draggeed
* @type {Boolean}
*/
_this31.isDragged = false;
// Window size variables for window resize checks
_this31.lastWindowWidth = window.innerWidth;
_this31.lastWindowHeight = window.innerHeight;
_this31._createOverlay();
_this31._createDragTarget();
_this31._setupEventHandlers();
_this31._setupClasses();
_this31._setupFixed();
Sidenav._sidenavs.push(_this31);
return _this31;
}
|
javascript
|
function Sidenav(el, options) {
_classCallCheck(this, Sidenav);
var _this31 = _possibleConstructorReturn(this, (Sidenav.__proto__ || Object.getPrototypeOf(Sidenav)).call(this, Sidenav, el, options));
_this31.el.M_Sidenav = _this31;
_this31.id = _this31.$el.attr('id');
/**
* Options for the Sidenav
* @member Sidenav#options
* @prop {String} [edge='left'] - Side of screen on which Sidenav appears
* @prop {Boolean} [draggable=true] - Allow swipe gestures to open/close Sidenav
* @prop {Number} [inDuration=250] - Length in ms of enter transition
* @prop {Number} [outDuration=200] - Length in ms of exit transition
* @prop {Function} onOpenStart - Function called when sidenav starts entering
* @prop {Function} onOpenEnd - Function called when sidenav finishes entering
* @prop {Function} onCloseStart - Function called when sidenav starts exiting
* @prop {Function} onCloseEnd - Function called when sidenav finishes exiting
*/
_this31.options = $.extend({}, Sidenav.defaults, options);
/**
* Describes open/close state of Sidenav
* @type {Boolean}
*/
_this31.isOpen = false;
/**
* Describes if Sidenav is fixed
* @type {Boolean}
*/
_this31.isFixed = _this31.el.classList.contains('sidenav-fixed');
/**
* Describes if Sidenav is being draggeed
* @type {Boolean}
*/
_this31.isDragged = false;
// Window size variables for window resize checks
_this31.lastWindowWidth = window.innerWidth;
_this31.lastWindowHeight = window.innerHeight;
_this31._createOverlay();
_this31._createDragTarget();
_this31._setupEventHandlers();
_this31._setupClasses();
_this31._setupFixed();
Sidenav._sidenavs.push(_this31);
return _this31;
}
|
[
"function",
"Sidenav",
"(",
"el",
",",
"options",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"Sidenav",
")",
";",
"var",
"_this31",
"=",
"_possibleConstructorReturn",
"(",
"this",
",",
"(",
"Sidenav",
".",
"__proto__",
"||",
"Object",
".",
"getPrototypeOf",
"(",
"Sidenav",
")",
")",
".",
"call",
"(",
"this",
",",
"Sidenav",
",",
"el",
",",
"options",
")",
")",
";",
"_this31",
".",
"el",
".",
"M_Sidenav",
"=",
"_this31",
";",
"_this31",
".",
"id",
"=",
"_this31",
".",
"$el",
".",
"attr",
"(",
"'id'",
")",
";",
"_this31",
".",
"options",
"=",
"$",
".",
"extend",
"(",
"{",
"}",
",",
"Sidenav",
".",
"defaults",
",",
"options",
")",
";",
"_this31",
".",
"isOpen",
"=",
"false",
";",
"_this31",
".",
"isFixed",
"=",
"_this31",
".",
"el",
".",
"classList",
".",
"contains",
"(",
"'sidenav-fixed'",
")",
";",
"_this31",
".",
"isDragged",
"=",
"false",
";",
"_this31",
".",
"lastWindowWidth",
"=",
"window",
".",
"innerWidth",
";",
"_this31",
".",
"lastWindowHeight",
"=",
"window",
".",
"innerHeight",
";",
"_this31",
".",
"_createOverlay",
"(",
")",
";",
"_this31",
".",
"_createDragTarget",
"(",
")",
";",
"_this31",
".",
"_setupEventHandlers",
"(",
")",
";",
"_this31",
".",
"_setupClasses",
"(",
")",
";",
"_this31",
".",
"_setupFixed",
"(",
")",
";",
"Sidenav",
".",
"_sidenavs",
".",
"push",
"(",
"_this31",
")",
";",
"return",
"_this31",
";",
"}"
] |
Construct Sidenav instance and set up overlay
@constructor
@param {Element} el
@param {Object} options
|
[
"Construct",
"Sidenav",
"instance",
"and",
"set",
"up",
"overlay"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/dist/js/materialize.js#L5486-L5538
|
train
|
Dogfalo/materialize
|
dist/js/materialize.js
|
ScrollSpy
|
function ScrollSpy(el, options) {
_classCallCheck(this, ScrollSpy);
var _this35 = _possibleConstructorReturn(this, (ScrollSpy.__proto__ || Object.getPrototypeOf(ScrollSpy)).call(this, ScrollSpy, el, options));
_this35.el.M_ScrollSpy = _this35;
/**
* Options for the modal
* @member Modal#options
* @prop {Number} [throttle=100] - Throttle of scroll handler
* @prop {Number} [scrollOffset=200] - Offset for centering element when scrolled to
* @prop {String} [activeClass='active'] - Class applied to active elements
* @prop {Function} [getActiveElement] - Used to find active element
*/
_this35.options = $.extend({}, ScrollSpy.defaults, options);
// setup
ScrollSpy._elements.push(_this35);
ScrollSpy._count++;
ScrollSpy._increment++;
_this35.tickId = -1;
_this35.id = ScrollSpy._increment;
_this35._setupEventHandlers();
_this35._handleWindowScroll();
return _this35;
}
|
javascript
|
function ScrollSpy(el, options) {
_classCallCheck(this, ScrollSpy);
var _this35 = _possibleConstructorReturn(this, (ScrollSpy.__proto__ || Object.getPrototypeOf(ScrollSpy)).call(this, ScrollSpy, el, options));
_this35.el.M_ScrollSpy = _this35;
/**
* Options for the modal
* @member Modal#options
* @prop {Number} [throttle=100] - Throttle of scroll handler
* @prop {Number} [scrollOffset=200] - Offset for centering element when scrolled to
* @prop {String} [activeClass='active'] - Class applied to active elements
* @prop {Function} [getActiveElement] - Used to find active element
*/
_this35.options = $.extend({}, ScrollSpy.defaults, options);
// setup
ScrollSpy._elements.push(_this35);
ScrollSpy._count++;
ScrollSpy._increment++;
_this35.tickId = -1;
_this35.id = ScrollSpy._increment;
_this35._setupEventHandlers();
_this35._handleWindowScroll();
return _this35;
}
|
[
"function",
"ScrollSpy",
"(",
"el",
",",
"options",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"ScrollSpy",
")",
";",
"var",
"_this35",
"=",
"_possibleConstructorReturn",
"(",
"this",
",",
"(",
"ScrollSpy",
".",
"__proto__",
"||",
"Object",
".",
"getPrototypeOf",
"(",
"ScrollSpy",
")",
")",
".",
"call",
"(",
"this",
",",
"ScrollSpy",
",",
"el",
",",
"options",
")",
")",
";",
"_this35",
".",
"el",
".",
"M_ScrollSpy",
"=",
"_this35",
";",
"_this35",
".",
"options",
"=",
"$",
".",
"extend",
"(",
"{",
"}",
",",
"ScrollSpy",
".",
"defaults",
",",
"options",
")",
";",
"ScrollSpy",
".",
"_elements",
".",
"push",
"(",
"_this35",
")",
";",
"ScrollSpy",
".",
"_count",
"++",
";",
"ScrollSpy",
".",
"_increment",
"++",
";",
"_this35",
".",
"tickId",
"=",
"-",
"1",
";",
"_this35",
".",
"id",
"=",
"ScrollSpy",
".",
"_increment",
";",
"_this35",
".",
"_setupEventHandlers",
"(",
")",
";",
"_this35",
".",
"_handleWindowScroll",
"(",
")",
";",
"return",
"_this35",
";",
"}"
] |
Construct ScrollSpy instance
@constructor
@param {Element} el
@param {Object} options
|
[
"Construct",
"ScrollSpy",
"instance"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/dist/js/materialize.js#L6129-L6155
|
train
|
Dogfalo/materialize
|
dist/js/materialize.js
|
Slider
|
function Slider(el, options) {
_classCallCheck(this, Slider);
var _this40 = _possibleConstructorReturn(this, (Slider.__proto__ || Object.getPrototypeOf(Slider)).call(this, Slider, el, options));
_this40.el.M_Slider = _this40;
/**
* Options for the modal
* @member Slider#options
* @prop {Boolean} [indicators=true] - Show indicators
* @prop {Number} [height=400] - height of slider
* @prop {Number} [duration=500] - Length in ms of slide transition
* @prop {Number} [interval=6000] - Length in ms of slide interval
*/
_this40.options = $.extend({}, Slider.defaults, options);
// setup
_this40.$slider = _this40.$el.find('.slides');
_this40.$slides = _this40.$slider.children('li');
_this40.activeIndex = _this40.$slides.filter(function (item) {
return $(item).hasClass('active');
}).first().index();
if (_this40.activeIndex != -1) {
_this40.$active = _this40.$slides.eq(_this40.activeIndex);
}
_this40._setSliderHeight();
// Set initial positions of captions
_this40.$slides.find('.caption').each(function (el) {
_this40._animateCaptionIn(el, 0);
});
// Move img src into background-image
_this40.$slides.find('img').each(function (el) {
var placeholderBase64 = 'data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
if ($(el).attr('src') !== placeholderBase64) {
$(el).css('background-image', 'url("' + $(el).attr('src') + '")');
$(el).attr('src', placeholderBase64);
}
});
_this40._setupIndicators();
// Show active slide
if (_this40.$active) {
_this40.$active.css('display', 'block');
} else {
_this40.$slides.first().addClass('active');
anim({
targets: _this40.$slides.first()[0],
opacity: 1,
duration: _this40.options.duration,
easing: 'easeOutQuad'
});
_this40.activeIndex = 0;
_this40.$active = _this40.$slides.eq(_this40.activeIndex);
// Update indicators
if (_this40.options.indicators) {
_this40.$indicators.eq(_this40.activeIndex).addClass('active');
}
}
// Adjust height to current slide
_this40.$active.find('img').each(function (el) {
anim({
targets: _this40.$active.find('.caption')[0],
opacity: 1,
translateX: 0,
translateY: 0,
duration: _this40.options.duration,
easing: 'easeOutQuad'
});
});
_this40._setupEventHandlers();
// auto scroll
_this40.start();
return _this40;
}
|
javascript
|
function Slider(el, options) {
_classCallCheck(this, Slider);
var _this40 = _possibleConstructorReturn(this, (Slider.__proto__ || Object.getPrototypeOf(Slider)).call(this, Slider, el, options));
_this40.el.M_Slider = _this40;
/**
* Options for the modal
* @member Slider#options
* @prop {Boolean} [indicators=true] - Show indicators
* @prop {Number} [height=400] - height of slider
* @prop {Number} [duration=500] - Length in ms of slide transition
* @prop {Number} [interval=6000] - Length in ms of slide interval
*/
_this40.options = $.extend({}, Slider.defaults, options);
// setup
_this40.$slider = _this40.$el.find('.slides');
_this40.$slides = _this40.$slider.children('li');
_this40.activeIndex = _this40.$slides.filter(function (item) {
return $(item).hasClass('active');
}).first().index();
if (_this40.activeIndex != -1) {
_this40.$active = _this40.$slides.eq(_this40.activeIndex);
}
_this40._setSliderHeight();
// Set initial positions of captions
_this40.$slides.find('.caption').each(function (el) {
_this40._animateCaptionIn(el, 0);
});
// Move img src into background-image
_this40.$slides.find('img').each(function (el) {
var placeholderBase64 = 'data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
if ($(el).attr('src') !== placeholderBase64) {
$(el).css('background-image', 'url("' + $(el).attr('src') + '")');
$(el).attr('src', placeholderBase64);
}
});
_this40._setupIndicators();
// Show active slide
if (_this40.$active) {
_this40.$active.css('display', 'block');
} else {
_this40.$slides.first().addClass('active');
anim({
targets: _this40.$slides.first()[0],
opacity: 1,
duration: _this40.options.duration,
easing: 'easeOutQuad'
});
_this40.activeIndex = 0;
_this40.$active = _this40.$slides.eq(_this40.activeIndex);
// Update indicators
if (_this40.options.indicators) {
_this40.$indicators.eq(_this40.activeIndex).addClass('active');
}
}
// Adjust height to current slide
_this40.$active.find('img').each(function (el) {
anim({
targets: _this40.$active.find('.caption')[0],
opacity: 1,
translateX: 0,
translateY: 0,
duration: _this40.options.duration,
easing: 'easeOutQuad'
});
});
_this40._setupEventHandlers();
// auto scroll
_this40.start();
return _this40;
}
|
[
"function",
"Slider",
"(",
"el",
",",
"options",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"Slider",
")",
";",
"var",
"_this40",
"=",
"_possibleConstructorReturn",
"(",
"this",
",",
"(",
"Slider",
".",
"__proto__",
"||",
"Object",
".",
"getPrototypeOf",
"(",
"Slider",
")",
")",
".",
"call",
"(",
"this",
",",
"Slider",
",",
"el",
",",
"options",
")",
")",
";",
"_this40",
".",
"el",
".",
"M_Slider",
"=",
"_this40",
";",
"_this40",
".",
"options",
"=",
"$",
".",
"extend",
"(",
"{",
"}",
",",
"Slider",
".",
"defaults",
",",
"options",
")",
";",
"_this40",
".",
"$slider",
"=",
"_this40",
".",
"$el",
".",
"find",
"(",
"'.slides'",
")",
";",
"_this40",
".",
"$slides",
"=",
"_this40",
".",
"$slider",
".",
"children",
"(",
"'li'",
")",
";",
"_this40",
".",
"activeIndex",
"=",
"_this40",
".",
"$slides",
".",
"filter",
"(",
"function",
"(",
"item",
")",
"{",
"return",
"$",
"(",
"item",
")",
".",
"hasClass",
"(",
"'active'",
")",
";",
"}",
")",
".",
"first",
"(",
")",
".",
"index",
"(",
")",
";",
"if",
"(",
"_this40",
".",
"activeIndex",
"!=",
"-",
"1",
")",
"{",
"_this40",
".",
"$active",
"=",
"_this40",
".",
"$slides",
".",
"eq",
"(",
"_this40",
".",
"activeIndex",
")",
";",
"}",
"_this40",
".",
"_setSliderHeight",
"(",
")",
";",
"_this40",
".",
"$slides",
".",
"find",
"(",
"'.caption'",
")",
".",
"each",
"(",
"function",
"(",
"el",
")",
"{",
"_this40",
".",
"_animateCaptionIn",
"(",
"el",
",",
"0",
")",
";",
"}",
")",
";",
"_this40",
".",
"$slides",
".",
"find",
"(",
"'img'",
")",
".",
"each",
"(",
"function",
"(",
"el",
")",
"{",
"var",
"placeholderBase64",
"=",
"'data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='",
";",
"if",
"(",
"$",
"(",
"el",
")",
".",
"attr",
"(",
"'src'",
")",
"!==",
"placeholderBase64",
")",
"{",
"$",
"(",
"el",
")",
".",
"css",
"(",
"'background-image'",
",",
"'url(\"'",
"+",
"$",
"(",
"el",
")",
".",
"attr",
"(",
"'src'",
")",
"+",
"'\")'",
")",
";",
"$",
"(",
"el",
")",
".",
"attr",
"(",
"'src'",
",",
"placeholderBase64",
")",
";",
"}",
"}",
")",
";",
"_this40",
".",
"_setupIndicators",
"(",
")",
";",
"if",
"(",
"_this40",
".",
"$active",
")",
"{",
"_this40",
".",
"$active",
".",
"css",
"(",
"'display'",
",",
"'block'",
")",
";",
"}",
"else",
"{",
"_this40",
".",
"$slides",
".",
"first",
"(",
")",
".",
"addClass",
"(",
"'active'",
")",
";",
"anim",
"(",
"{",
"targets",
":",
"_this40",
".",
"$slides",
".",
"first",
"(",
")",
"[",
"0",
"]",
",",
"opacity",
":",
"1",
",",
"duration",
":",
"_this40",
".",
"options",
".",
"duration",
",",
"easing",
":",
"'easeOutQuad'",
"}",
")",
";",
"_this40",
".",
"activeIndex",
"=",
"0",
";",
"_this40",
".",
"$active",
"=",
"_this40",
".",
"$slides",
".",
"eq",
"(",
"_this40",
".",
"activeIndex",
")",
";",
"if",
"(",
"_this40",
".",
"options",
".",
"indicators",
")",
"{",
"_this40",
".",
"$indicators",
".",
"eq",
"(",
"_this40",
".",
"activeIndex",
")",
".",
"addClass",
"(",
"'active'",
")",
";",
"}",
"}",
"_this40",
".",
"$active",
".",
"find",
"(",
"'img'",
")",
".",
"each",
"(",
"function",
"(",
"el",
")",
"{",
"anim",
"(",
"{",
"targets",
":",
"_this40",
".",
"$active",
".",
"find",
"(",
"'.caption'",
")",
"[",
"0",
"]",
",",
"opacity",
":",
"1",
",",
"translateX",
":",
"0",
",",
"translateY",
":",
"0",
",",
"duration",
":",
"_this40",
".",
"options",
".",
"duration",
",",
"easing",
":",
"'easeOutQuad'",
"}",
")",
";",
"}",
")",
";",
"_this40",
".",
"_setupEventHandlers",
"(",
")",
";",
"_this40",
".",
"start",
"(",
")",
";",
"return",
"_this40",
";",
"}"
] |
Construct Slider instance and set up overlay
@constructor
@param {Element} el
@param {Object} options
|
[
"Construct",
"Slider",
"instance",
"and",
"set",
"up",
"overlay"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/dist/js/materialize.js#L7183-L7266
|
train
|
Dogfalo/materialize
|
dist/js/materialize.js
|
Pushpin
|
function Pushpin(el, options) {
_classCallCheck(this, Pushpin);
var _this47 = _possibleConstructorReturn(this, (Pushpin.__proto__ || Object.getPrototypeOf(Pushpin)).call(this, Pushpin, el, options));
_this47.el.M_Pushpin = _this47;
/**
* Options for the modal
* @member Pushpin#options
*/
_this47.options = $.extend({}, Pushpin.defaults, options);
_this47.originalOffset = _this47.el.offsetTop;
Pushpin._pushpins.push(_this47);
_this47._setupEventHandlers();
_this47._updatePosition();
return _this47;
}
|
javascript
|
function Pushpin(el, options) {
_classCallCheck(this, Pushpin);
var _this47 = _possibleConstructorReturn(this, (Pushpin.__proto__ || Object.getPrototypeOf(Pushpin)).call(this, Pushpin, el, options));
_this47.el.M_Pushpin = _this47;
/**
* Options for the modal
* @member Pushpin#options
*/
_this47.options = $.extend({}, Pushpin.defaults, options);
_this47.originalOffset = _this47.el.offsetTop;
Pushpin._pushpins.push(_this47);
_this47._setupEventHandlers();
_this47._updatePosition();
return _this47;
}
|
[
"function",
"Pushpin",
"(",
"el",
",",
"options",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"Pushpin",
")",
";",
"var",
"_this47",
"=",
"_possibleConstructorReturn",
"(",
"this",
",",
"(",
"Pushpin",
".",
"__proto__",
"||",
"Object",
".",
"getPrototypeOf",
"(",
"Pushpin",
")",
")",
".",
"call",
"(",
"this",
",",
"Pushpin",
",",
"el",
",",
"options",
")",
")",
";",
"_this47",
".",
"el",
".",
"M_Pushpin",
"=",
"_this47",
";",
"_this47",
".",
"options",
"=",
"$",
".",
"extend",
"(",
"{",
"}",
",",
"Pushpin",
".",
"defaults",
",",
"options",
")",
";",
"_this47",
".",
"originalOffset",
"=",
"_this47",
".",
"el",
".",
"offsetTop",
";",
"Pushpin",
".",
"_pushpins",
".",
"push",
"(",
"_this47",
")",
";",
"_this47",
".",
"_setupEventHandlers",
"(",
")",
";",
"_this47",
".",
"_updatePosition",
"(",
")",
";",
"return",
"_this47",
";",
"}"
] |
Construct Pushpin instance
@constructor
@param {Element} el
@param {Object} options
|
[
"Construct",
"Pushpin",
"instance"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/dist/js/materialize.js#L8185-L8203
|
train
|
Dogfalo/materialize
|
dist/js/materialize.js
|
FloatingActionButton
|
function FloatingActionButton(el, options) {
_classCallCheck(this, FloatingActionButton);
var _this48 = _possibleConstructorReturn(this, (FloatingActionButton.__proto__ || Object.getPrototypeOf(FloatingActionButton)).call(this, FloatingActionButton, el, options));
_this48.el.M_FloatingActionButton = _this48;
/**
* Options for the fab
* @member FloatingActionButton#options
* @prop {Boolean} [direction] - Direction fab menu opens
* @prop {Boolean} [hoverEnabled=true] - Enable hover vs click
* @prop {Boolean} [toolbarEnabled=false] - Enable toolbar transition
*/
_this48.options = $.extend({}, FloatingActionButton.defaults, options);
_this48.isOpen = false;
_this48.$anchor = _this48.$el.children('a').first();
_this48.$menu = _this48.$el.children('ul').first();
_this48.$floatingBtns = _this48.$el.find('ul .btn-floating');
_this48.$floatingBtnsReverse = _this48.$el.find('ul .btn-floating').reverse();
_this48.offsetY = 0;
_this48.offsetX = 0;
_this48.$el.addClass("direction-" + _this48.options.direction);
if (_this48.options.direction === 'top') {
_this48.offsetY = 40;
} else if (_this48.options.direction === 'right') {
_this48.offsetX = -40;
} else if (_this48.options.direction === 'bottom') {
_this48.offsetY = -40;
} else {
_this48.offsetX = 40;
}
_this48._setupEventHandlers();
return _this48;
}
|
javascript
|
function FloatingActionButton(el, options) {
_classCallCheck(this, FloatingActionButton);
var _this48 = _possibleConstructorReturn(this, (FloatingActionButton.__proto__ || Object.getPrototypeOf(FloatingActionButton)).call(this, FloatingActionButton, el, options));
_this48.el.M_FloatingActionButton = _this48;
/**
* Options for the fab
* @member FloatingActionButton#options
* @prop {Boolean} [direction] - Direction fab menu opens
* @prop {Boolean} [hoverEnabled=true] - Enable hover vs click
* @prop {Boolean} [toolbarEnabled=false] - Enable toolbar transition
*/
_this48.options = $.extend({}, FloatingActionButton.defaults, options);
_this48.isOpen = false;
_this48.$anchor = _this48.$el.children('a').first();
_this48.$menu = _this48.$el.children('ul').first();
_this48.$floatingBtns = _this48.$el.find('ul .btn-floating');
_this48.$floatingBtnsReverse = _this48.$el.find('ul .btn-floating').reverse();
_this48.offsetY = 0;
_this48.offsetX = 0;
_this48.$el.addClass("direction-" + _this48.options.direction);
if (_this48.options.direction === 'top') {
_this48.offsetY = 40;
} else if (_this48.options.direction === 'right') {
_this48.offsetX = -40;
} else if (_this48.options.direction === 'bottom') {
_this48.offsetY = -40;
} else {
_this48.offsetX = 40;
}
_this48._setupEventHandlers();
return _this48;
}
|
[
"function",
"FloatingActionButton",
"(",
"el",
",",
"options",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"FloatingActionButton",
")",
";",
"var",
"_this48",
"=",
"_possibleConstructorReturn",
"(",
"this",
",",
"(",
"FloatingActionButton",
".",
"__proto__",
"||",
"Object",
".",
"getPrototypeOf",
"(",
"FloatingActionButton",
")",
")",
".",
"call",
"(",
"this",
",",
"FloatingActionButton",
",",
"el",
",",
"options",
")",
")",
";",
"_this48",
".",
"el",
".",
"M_FloatingActionButton",
"=",
"_this48",
";",
"_this48",
".",
"options",
"=",
"$",
".",
"extend",
"(",
"{",
"}",
",",
"FloatingActionButton",
".",
"defaults",
",",
"options",
")",
";",
"_this48",
".",
"isOpen",
"=",
"false",
";",
"_this48",
".",
"$anchor",
"=",
"_this48",
".",
"$el",
".",
"children",
"(",
"'a'",
")",
".",
"first",
"(",
")",
";",
"_this48",
".",
"$menu",
"=",
"_this48",
".",
"$el",
".",
"children",
"(",
"'ul'",
")",
".",
"first",
"(",
")",
";",
"_this48",
".",
"$floatingBtns",
"=",
"_this48",
".",
"$el",
".",
"find",
"(",
"'ul .btn-floating'",
")",
";",
"_this48",
".",
"$floatingBtnsReverse",
"=",
"_this48",
".",
"$el",
".",
"find",
"(",
"'ul .btn-floating'",
")",
".",
"reverse",
"(",
")",
";",
"_this48",
".",
"offsetY",
"=",
"0",
";",
"_this48",
".",
"offsetX",
"=",
"0",
";",
"_this48",
".",
"$el",
".",
"addClass",
"(",
"\"direction-\"",
"+",
"_this48",
".",
"options",
".",
"direction",
")",
";",
"if",
"(",
"_this48",
".",
"options",
".",
"direction",
"===",
"'top'",
")",
"{",
"_this48",
".",
"offsetY",
"=",
"40",
";",
"}",
"else",
"if",
"(",
"_this48",
".",
"options",
".",
"direction",
"===",
"'right'",
")",
"{",
"_this48",
".",
"offsetX",
"=",
"-",
"40",
";",
"}",
"else",
"if",
"(",
"_this48",
".",
"options",
".",
"direction",
"===",
"'bottom'",
")",
"{",
"_this48",
".",
"offsetY",
"=",
"-",
"40",
";",
"}",
"else",
"{",
"_this48",
".",
"offsetX",
"=",
"40",
";",
"}",
"_this48",
".",
"_setupEventHandlers",
"(",
")",
";",
"return",
"_this48",
";",
"}"
] |
Construct FloatingActionButton instance
@constructor
@param {Element} el
@param {Object} options
|
[
"Construct",
"FloatingActionButton",
"instance"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/dist/js/materialize.js#L8352-L8388
|
train
|
Dogfalo/materialize
|
dist/js/materialize.js
|
CharacterCounter
|
function CharacterCounter(el, options) {
_classCallCheck(this, CharacterCounter);
var _this61 = _possibleConstructorReturn(this, (CharacterCounter.__proto__ || Object.getPrototypeOf(CharacterCounter)).call(this, CharacterCounter, el, options));
_this61.el.M_CharacterCounter = _this61;
/**
* Options for the character counter
*/
_this61.options = $.extend({}, CharacterCounter.defaults, options);
_this61.isInvalid = false;
_this61.isValidLength = false;
_this61._setupCounter();
_this61._setupEventHandlers();
return _this61;
}
|
javascript
|
function CharacterCounter(el, options) {
_classCallCheck(this, CharacterCounter);
var _this61 = _possibleConstructorReturn(this, (CharacterCounter.__proto__ || Object.getPrototypeOf(CharacterCounter)).call(this, CharacterCounter, el, options));
_this61.el.M_CharacterCounter = _this61;
/**
* Options for the character counter
*/
_this61.options = $.extend({}, CharacterCounter.defaults, options);
_this61.isInvalid = false;
_this61.isValidLength = false;
_this61._setupCounter();
_this61._setupEventHandlers();
return _this61;
}
|
[
"function",
"CharacterCounter",
"(",
"el",
",",
"options",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"CharacterCounter",
")",
";",
"var",
"_this61",
"=",
"_possibleConstructorReturn",
"(",
"this",
",",
"(",
"CharacterCounter",
".",
"__proto__",
"||",
"Object",
".",
"getPrototypeOf",
"(",
"CharacterCounter",
")",
")",
".",
"call",
"(",
"this",
",",
"CharacterCounter",
",",
"el",
",",
"options",
")",
")",
";",
"_this61",
".",
"el",
".",
"M_CharacterCounter",
"=",
"_this61",
";",
"_this61",
".",
"options",
"=",
"$",
".",
"extend",
"(",
"{",
"}",
",",
"CharacterCounter",
".",
"defaults",
",",
"options",
")",
";",
"_this61",
".",
"isInvalid",
"=",
"false",
";",
"_this61",
".",
"isValidLength",
"=",
"false",
";",
"_this61",
".",
"_setupCounter",
"(",
")",
";",
"_this61",
".",
"_setupEventHandlers",
"(",
")",
";",
"return",
"_this61",
";",
"}"
] |
Construct CharacterCounter instance
@constructor
@param {Element} el
@param {Object} options
|
[
"Construct",
"CharacterCounter",
"instance"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/dist/js/materialize.js#L10307-L10324
|
train
|
Dogfalo/materialize
|
dist/js/materialize.js
|
Carousel
|
function Carousel(el, options) {
_classCallCheck(this, Carousel);
var _this62 = _possibleConstructorReturn(this, (Carousel.__proto__ || Object.getPrototypeOf(Carousel)).call(this, Carousel, el, options));
_this62.el.M_Carousel = _this62;
/**
* Options for the carousel
* @member Carousel#options
* @prop {Number} duration
* @prop {Number} dist
* @prop {Number} shift
* @prop {Number} padding
* @prop {Number} numVisible
* @prop {Boolean} fullWidth
* @prop {Boolean} indicators
* @prop {Boolean} noWrap
* @prop {Function} onCycleTo
*/
_this62.options = $.extend({}, Carousel.defaults, options);
// Setup
_this62.hasMultipleSlides = _this62.$el.find('.carousel-item').length > 1;
_this62.showIndicators = _this62.options.indicators && _this62.hasMultipleSlides;
_this62.noWrap = _this62.options.noWrap || !_this62.hasMultipleSlides;
_this62.pressed = false;
_this62.dragged = false;
_this62.offset = _this62.target = 0;
_this62.images = [];
_this62.itemWidth = _this62.$el.find('.carousel-item').first().innerWidth();
_this62.itemHeight = _this62.$el.find('.carousel-item').first().innerHeight();
_this62.dim = _this62.itemWidth * 2 + _this62.options.padding || 1; // Make sure dim is non zero for divisions.
_this62._autoScrollBound = _this62._autoScroll.bind(_this62);
_this62._trackBound = _this62._track.bind(_this62);
// Full Width carousel setup
if (_this62.options.fullWidth) {
_this62.options.dist = 0;
_this62._setCarouselHeight();
// Offset fixed items when indicators.
if (_this62.showIndicators) {
_this62.$el.find('.carousel-fixed-item').addClass('with-indicators');
}
}
// Iterate through slides
_this62.$indicators = $('<ul class="indicators"></ul>');
_this62.$el.find('.carousel-item').each(function (el, i) {
_this62.images.push(el);
if (_this62.showIndicators) {
var $indicator = $('<li class="indicator-item"></li>');
// Add active to first by default.
if (i === 0) {
$indicator[0].classList.add('active');
}
_this62.$indicators.append($indicator);
}
});
if (_this62.showIndicators) {
_this62.$el.append(_this62.$indicators);
}
_this62.count = _this62.images.length;
// Cap numVisible at count
_this62.options.numVisible = Math.min(_this62.count, _this62.options.numVisible);
// Setup cross browser string
_this62.xform = 'transform';
['webkit', 'Moz', 'O', 'ms'].every(function (prefix) {
var e = prefix + 'Transform';
if (typeof document.body.style[e] !== 'undefined') {
_this62.xform = e;
return false;
}
return true;
});
_this62._setupEventHandlers();
_this62._scroll(_this62.offset);
return _this62;
}
|
javascript
|
function Carousel(el, options) {
_classCallCheck(this, Carousel);
var _this62 = _possibleConstructorReturn(this, (Carousel.__proto__ || Object.getPrototypeOf(Carousel)).call(this, Carousel, el, options));
_this62.el.M_Carousel = _this62;
/**
* Options for the carousel
* @member Carousel#options
* @prop {Number} duration
* @prop {Number} dist
* @prop {Number} shift
* @prop {Number} padding
* @prop {Number} numVisible
* @prop {Boolean} fullWidth
* @prop {Boolean} indicators
* @prop {Boolean} noWrap
* @prop {Function} onCycleTo
*/
_this62.options = $.extend({}, Carousel.defaults, options);
// Setup
_this62.hasMultipleSlides = _this62.$el.find('.carousel-item').length > 1;
_this62.showIndicators = _this62.options.indicators && _this62.hasMultipleSlides;
_this62.noWrap = _this62.options.noWrap || !_this62.hasMultipleSlides;
_this62.pressed = false;
_this62.dragged = false;
_this62.offset = _this62.target = 0;
_this62.images = [];
_this62.itemWidth = _this62.$el.find('.carousel-item').first().innerWidth();
_this62.itemHeight = _this62.$el.find('.carousel-item').first().innerHeight();
_this62.dim = _this62.itemWidth * 2 + _this62.options.padding || 1; // Make sure dim is non zero for divisions.
_this62._autoScrollBound = _this62._autoScroll.bind(_this62);
_this62._trackBound = _this62._track.bind(_this62);
// Full Width carousel setup
if (_this62.options.fullWidth) {
_this62.options.dist = 0;
_this62._setCarouselHeight();
// Offset fixed items when indicators.
if (_this62.showIndicators) {
_this62.$el.find('.carousel-fixed-item').addClass('with-indicators');
}
}
// Iterate through slides
_this62.$indicators = $('<ul class="indicators"></ul>');
_this62.$el.find('.carousel-item').each(function (el, i) {
_this62.images.push(el);
if (_this62.showIndicators) {
var $indicator = $('<li class="indicator-item"></li>');
// Add active to first by default.
if (i === 0) {
$indicator[0].classList.add('active');
}
_this62.$indicators.append($indicator);
}
});
if (_this62.showIndicators) {
_this62.$el.append(_this62.$indicators);
}
_this62.count = _this62.images.length;
// Cap numVisible at count
_this62.options.numVisible = Math.min(_this62.count, _this62.options.numVisible);
// Setup cross browser string
_this62.xform = 'transform';
['webkit', 'Moz', 'O', 'ms'].every(function (prefix) {
var e = prefix + 'Transform';
if (typeof document.body.style[e] !== 'undefined') {
_this62.xform = e;
return false;
}
return true;
});
_this62._setupEventHandlers();
_this62._scroll(_this62.offset);
return _this62;
}
|
[
"function",
"Carousel",
"(",
"el",
",",
"options",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"Carousel",
")",
";",
"var",
"_this62",
"=",
"_possibleConstructorReturn",
"(",
"this",
",",
"(",
"Carousel",
".",
"__proto__",
"||",
"Object",
".",
"getPrototypeOf",
"(",
"Carousel",
")",
")",
".",
"call",
"(",
"this",
",",
"Carousel",
",",
"el",
",",
"options",
")",
")",
";",
"_this62",
".",
"el",
".",
"M_Carousel",
"=",
"_this62",
";",
"_this62",
".",
"options",
"=",
"$",
".",
"extend",
"(",
"{",
"}",
",",
"Carousel",
".",
"defaults",
",",
"options",
")",
";",
"_this62",
".",
"hasMultipleSlides",
"=",
"_this62",
".",
"$el",
".",
"find",
"(",
"'.carousel-item'",
")",
".",
"length",
">",
"1",
";",
"_this62",
".",
"showIndicators",
"=",
"_this62",
".",
"options",
".",
"indicators",
"&&",
"_this62",
".",
"hasMultipleSlides",
";",
"_this62",
".",
"noWrap",
"=",
"_this62",
".",
"options",
".",
"noWrap",
"||",
"!",
"_this62",
".",
"hasMultipleSlides",
";",
"_this62",
".",
"pressed",
"=",
"false",
";",
"_this62",
".",
"dragged",
"=",
"false",
";",
"_this62",
".",
"offset",
"=",
"_this62",
".",
"target",
"=",
"0",
";",
"_this62",
".",
"images",
"=",
"[",
"]",
";",
"_this62",
".",
"itemWidth",
"=",
"_this62",
".",
"$el",
".",
"find",
"(",
"'.carousel-item'",
")",
".",
"first",
"(",
")",
".",
"innerWidth",
"(",
")",
";",
"_this62",
".",
"itemHeight",
"=",
"_this62",
".",
"$el",
".",
"find",
"(",
"'.carousel-item'",
")",
".",
"first",
"(",
")",
".",
"innerHeight",
"(",
")",
";",
"_this62",
".",
"dim",
"=",
"_this62",
".",
"itemWidth",
"*",
"2",
"+",
"_this62",
".",
"options",
".",
"padding",
"||",
"1",
";",
"_this62",
".",
"_autoScrollBound",
"=",
"_this62",
".",
"_autoScroll",
".",
"bind",
"(",
"_this62",
")",
";",
"_this62",
".",
"_trackBound",
"=",
"_this62",
".",
"_track",
".",
"bind",
"(",
"_this62",
")",
";",
"if",
"(",
"_this62",
".",
"options",
".",
"fullWidth",
")",
"{",
"_this62",
".",
"options",
".",
"dist",
"=",
"0",
";",
"_this62",
".",
"_setCarouselHeight",
"(",
")",
";",
"if",
"(",
"_this62",
".",
"showIndicators",
")",
"{",
"_this62",
".",
"$el",
".",
"find",
"(",
"'.carousel-fixed-item'",
")",
".",
"addClass",
"(",
"'with-indicators'",
")",
";",
"}",
"}",
"_this62",
".",
"$indicators",
"=",
"$",
"(",
"'<ul class=\"indicators\"></ul>'",
")",
";",
"_this62",
".",
"$el",
".",
"find",
"(",
"'.carousel-item'",
")",
".",
"each",
"(",
"function",
"(",
"el",
",",
"i",
")",
"{",
"_this62",
".",
"images",
".",
"push",
"(",
"el",
")",
";",
"if",
"(",
"_this62",
".",
"showIndicators",
")",
"{",
"var",
"$indicator",
"=",
"$",
"(",
"'<li class=\"indicator-item\"></li>'",
")",
";",
"if",
"(",
"i",
"===",
"0",
")",
"{",
"$indicator",
"[",
"0",
"]",
".",
"classList",
".",
"add",
"(",
"'active'",
")",
";",
"}",
"_this62",
".",
"$indicators",
".",
"append",
"(",
"$indicator",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"_this62",
".",
"showIndicators",
")",
"{",
"_this62",
".",
"$el",
".",
"append",
"(",
"_this62",
".",
"$indicators",
")",
";",
"}",
"_this62",
".",
"count",
"=",
"_this62",
".",
"images",
".",
"length",
";",
"_this62",
".",
"options",
".",
"numVisible",
"=",
"Math",
".",
"min",
"(",
"_this62",
".",
"count",
",",
"_this62",
".",
"options",
".",
"numVisible",
")",
";",
"_this62",
".",
"xform",
"=",
"'transform'",
";",
"[",
"'webkit'",
",",
"'Moz'",
",",
"'O'",
",",
"'ms'",
"]",
".",
"every",
"(",
"function",
"(",
"prefix",
")",
"{",
"var",
"e",
"=",
"prefix",
"+",
"'Transform'",
";",
"if",
"(",
"typeof",
"document",
".",
"body",
".",
"style",
"[",
"e",
"]",
"!==",
"'undefined'",
")",
"{",
"_this62",
".",
"xform",
"=",
"e",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}",
")",
";",
"_this62",
".",
"_setupEventHandlers",
"(",
")",
";",
"_this62",
".",
"_scroll",
"(",
"_this62",
".",
"offset",
")",
";",
"return",
"_this62",
";",
"}"
] |
Construct Carousel instance
@constructor
@param {Element} el
@param {Object} options
|
[
"Construct",
"Carousel",
"instance"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/dist/js/materialize.js#L10487-L10571
|
train
|
Dogfalo/materialize
|
dist/js/materialize.js
|
TapTarget
|
function TapTarget(el, options) {
_classCallCheck(this, TapTarget);
var _this67 = _possibleConstructorReturn(this, (TapTarget.__proto__ || Object.getPrototypeOf(TapTarget)).call(this, TapTarget, el, options));
_this67.el.M_TapTarget = _this67;
/**
* Options for the select
* @member TapTarget#options
* @prop {Function} onOpen - Callback function called when feature discovery is opened
* @prop {Function} onClose - Callback function called when feature discovery is closed
*/
_this67.options = $.extend({}, TapTarget.defaults, options);
_this67.isOpen = false;
// setup
_this67.$origin = $('#' + _this67.$el.attr('data-target'));
_this67._setup();
_this67._calculatePositioning();
_this67._setupEventHandlers();
return _this67;
}
|
javascript
|
function TapTarget(el, options) {
_classCallCheck(this, TapTarget);
var _this67 = _possibleConstructorReturn(this, (TapTarget.__proto__ || Object.getPrototypeOf(TapTarget)).call(this, TapTarget, el, options));
_this67.el.M_TapTarget = _this67;
/**
* Options for the select
* @member TapTarget#options
* @prop {Function} onOpen - Callback function called when feature discovery is opened
* @prop {Function} onClose - Callback function called when feature discovery is closed
*/
_this67.options = $.extend({}, TapTarget.defaults, options);
_this67.isOpen = false;
// setup
_this67.$origin = $('#' + _this67.$el.attr('data-target'));
_this67._setup();
_this67._calculatePositioning();
_this67._setupEventHandlers();
return _this67;
}
|
[
"function",
"TapTarget",
"(",
"el",
",",
"options",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"TapTarget",
")",
";",
"var",
"_this67",
"=",
"_possibleConstructorReturn",
"(",
"this",
",",
"(",
"TapTarget",
".",
"__proto__",
"||",
"Object",
".",
"getPrototypeOf",
"(",
"TapTarget",
")",
")",
".",
"call",
"(",
"this",
",",
"TapTarget",
",",
"el",
",",
"options",
")",
")",
";",
"_this67",
".",
"el",
".",
"M_TapTarget",
"=",
"_this67",
";",
"_this67",
".",
"options",
"=",
"$",
".",
"extend",
"(",
"{",
"}",
",",
"TapTarget",
".",
"defaults",
",",
"options",
")",
";",
"_this67",
".",
"isOpen",
"=",
"false",
";",
"_this67",
".",
"$origin",
"=",
"$",
"(",
"'#'",
"+",
"_this67",
".",
"$el",
".",
"attr",
"(",
"'data-target'",
")",
")",
";",
"_this67",
".",
"_setup",
"(",
")",
";",
"_this67",
".",
"_calculatePositioning",
"(",
")",
";",
"_this67",
".",
"_setupEventHandlers",
"(",
")",
";",
"return",
"_this67",
";",
"}"
] |
Construct TapTarget instance
@constructor
@param {Element} el
@param {Object} options
|
[
"Construct",
"TapTarget",
"instance"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/dist/js/materialize.js#L11267-L11291
|
train
|
Dogfalo/materialize
|
dist/js/materialize.js
|
FormSelect
|
function FormSelect(el, options) {
_classCallCheck(this, FormSelect);
// Don't init if browser default version
var _this68 = _possibleConstructorReturn(this, (FormSelect.__proto__ || Object.getPrototypeOf(FormSelect)).call(this, FormSelect, el, options));
if (_this68.$el.hasClass('browser-default')) {
return _possibleConstructorReturn(_this68);
}
_this68.el.M_FormSelect = _this68;
/**
* Options for the select
* @member FormSelect#options
*/
_this68.options = $.extend({}, FormSelect.defaults, options);
_this68.isMultiple = _this68.$el.prop('multiple');
// Setup
_this68.el.tabIndex = -1;
_this68._keysSelected = {};
_this68._valueDict = {}; // Maps key to original and generated option element.
_this68._setupDropdown();
_this68._setupEventHandlers();
return _this68;
}
|
javascript
|
function FormSelect(el, options) {
_classCallCheck(this, FormSelect);
// Don't init if browser default version
var _this68 = _possibleConstructorReturn(this, (FormSelect.__proto__ || Object.getPrototypeOf(FormSelect)).call(this, FormSelect, el, options));
if (_this68.$el.hasClass('browser-default')) {
return _possibleConstructorReturn(_this68);
}
_this68.el.M_FormSelect = _this68;
/**
* Options for the select
* @member FormSelect#options
*/
_this68.options = $.extend({}, FormSelect.defaults, options);
_this68.isMultiple = _this68.$el.prop('multiple');
// Setup
_this68.el.tabIndex = -1;
_this68._keysSelected = {};
_this68._valueDict = {}; // Maps key to original and generated option element.
_this68._setupDropdown();
_this68._setupEventHandlers();
return _this68;
}
|
[
"function",
"FormSelect",
"(",
"el",
",",
"options",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"FormSelect",
")",
";",
"var",
"_this68",
"=",
"_possibleConstructorReturn",
"(",
"this",
",",
"(",
"FormSelect",
".",
"__proto__",
"||",
"Object",
".",
"getPrototypeOf",
"(",
"FormSelect",
")",
")",
".",
"call",
"(",
"this",
",",
"FormSelect",
",",
"el",
",",
"options",
")",
")",
";",
"if",
"(",
"_this68",
".",
"$el",
".",
"hasClass",
"(",
"'browser-default'",
")",
")",
"{",
"return",
"_possibleConstructorReturn",
"(",
"_this68",
")",
";",
"}",
"_this68",
".",
"el",
".",
"M_FormSelect",
"=",
"_this68",
";",
"_this68",
".",
"options",
"=",
"$",
".",
"extend",
"(",
"{",
"}",
",",
"FormSelect",
".",
"defaults",
",",
"options",
")",
";",
"_this68",
".",
"isMultiple",
"=",
"_this68",
".",
"$el",
".",
"prop",
"(",
"'multiple'",
")",
";",
"_this68",
".",
"el",
".",
"tabIndex",
"=",
"-",
"1",
";",
"_this68",
".",
"_keysSelected",
"=",
"{",
"}",
";",
"_this68",
".",
"_valueDict",
"=",
"{",
"}",
";",
"_this68",
".",
"_setupDropdown",
"(",
")",
";",
"_this68",
".",
"_setupEventHandlers",
"(",
")",
";",
"return",
"_this68",
";",
"}"
] |
Construct FormSelect instance
@constructor
@param {Element} el
@param {Object} options
|
[
"Construct",
"FormSelect",
"instance"
] |
1122efadad8f1433d404696f7613e3cc13fb83a4
|
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/dist/js/materialize.js#L11621-L11649
|
train
|
dcloudio/mui
|
examples/hello-mui/js/mui.js
|
function(target) {
parentNode = target.parentNode;
if (parentNode) {
if (parentNode.classList.contains(CLASS_OFF_CANVAS_WRAP)) {
return parentNode;
} else {
parentNode = parentNode.parentNode;
if (parentNode.classList.contains(CLASS_OFF_CANVAS_WRAP)) {
return parentNode;
}
}
}
}
|
javascript
|
function(target) {
parentNode = target.parentNode;
if (parentNode) {
if (parentNode.classList.contains(CLASS_OFF_CANVAS_WRAP)) {
return parentNode;
} else {
parentNode = parentNode.parentNode;
if (parentNode.classList.contains(CLASS_OFF_CANVAS_WRAP)) {
return parentNode;
}
}
}
}
|
[
"function",
"(",
"target",
")",
"{",
"parentNode",
"=",
"target",
".",
"parentNode",
";",
"if",
"(",
"parentNode",
")",
"{",
"if",
"(",
"parentNode",
".",
"classList",
".",
"contains",
"(",
"CLASS_OFF_CANVAS_WRAP",
")",
")",
"{",
"return",
"parentNode",
";",
"}",
"else",
"{",
"parentNode",
"=",
"parentNode",
".",
"parentNode",
";",
"if",
"(",
"parentNode",
".",
"classList",
".",
"contains",
"(",
"CLASS_OFF_CANVAS_WRAP",
")",
")",
"{",
"return",
"parentNode",
";",
"}",
"}",
"}",
"}"
] |
hash to offcanvas
|
[
"hash",
"to",
"offcanvas"
] |
ff74c90a1671a552f3604b1288bf38a4126312d0
|
https://github.com/dcloudio/mui/blob/ff74c90a1671a552f3604b1288bf38a4126312d0/examples/hello-mui/js/mui.js#L6002-L6014
|
train
|
|
MoePlayer/DPlayer
|
demo/modernizr.js
|
computedStyle
|
function computedStyle(elem, pseudo, prop) {
var result;
if ('getComputedStyle' in window) {
result = getComputedStyle.call(window, elem, pseudo);
var console = window.console;
if (result !== null) {
if (prop) {
result = result.getPropertyValue(prop);
}
} else {
if (console) {
var method = console.error ? 'error' : 'log';
console[method].call(console, 'getComputedStyle returning null, its possible modernizr test results are inaccurate');
}
}
} else {
result = !pseudo && elem.currentStyle && elem.currentStyle[prop];
}
return result;
}
|
javascript
|
function computedStyle(elem, pseudo, prop) {
var result;
if ('getComputedStyle' in window) {
result = getComputedStyle.call(window, elem, pseudo);
var console = window.console;
if (result !== null) {
if (prop) {
result = result.getPropertyValue(prop);
}
} else {
if (console) {
var method = console.error ? 'error' : 'log';
console[method].call(console, 'getComputedStyle returning null, its possible modernizr test results are inaccurate');
}
}
} else {
result = !pseudo && elem.currentStyle && elem.currentStyle[prop];
}
return result;
}
|
[
"function",
"computedStyle",
"(",
"elem",
",",
"pseudo",
",",
"prop",
")",
"{",
"var",
"result",
";",
"if",
"(",
"'getComputedStyle'",
"in",
"window",
")",
"{",
"result",
"=",
"getComputedStyle",
".",
"call",
"(",
"window",
",",
"elem",
",",
"pseudo",
")",
";",
"var",
"console",
"=",
"window",
".",
"console",
";",
"if",
"(",
"result",
"!==",
"null",
")",
"{",
"if",
"(",
"prop",
")",
"{",
"result",
"=",
"result",
".",
"getPropertyValue",
"(",
"prop",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"console",
")",
"{",
"var",
"method",
"=",
"console",
".",
"error",
"?",
"'error'",
":",
"'log'",
";",
"console",
"[",
"method",
"]",
".",
"call",
"(",
"console",
",",
"'getComputedStyle returning null, its possible modernizr test results are inaccurate'",
")",
";",
"}",
"}",
"}",
"else",
"{",
"result",
"=",
"!",
"pseudo",
"&&",
"elem",
".",
"currentStyle",
"&&",
"elem",
".",
"currentStyle",
"[",
"prop",
"]",
";",
"}",
"return",
"result",
";",
"}"
] |
wrapper around getComputedStyle, to fix issues with Firefox returning null when
called inside of a hidden iframe
@access private
@function computedStyle
@param {HTMLElement|SVGElement} - The element we want to find the computed styles of
@param {string|null} [pseudoSelector]- An optional pseudo element selector (e.g. :before), of null if none
@returns {CSSStyleDeclaration}
|
[
"wrapper",
"around",
"getComputedStyle",
"to",
"fix",
"issues",
"with",
"Firefox",
"returning",
"null",
"when",
"called",
"inside",
"of",
"a",
"hidden",
"iframe"
] |
f5c53f082634a6e5af56cfc72978ad7bad49b989
|
https://github.com/MoePlayer/DPlayer/blob/f5c53f082634a6e5af56cfc72978ad7bad49b989/demo/modernizr.js#L817-L839
|
train
|
MoePlayer/DPlayer
|
demo/modernizr.js
|
getBody
|
function getBody() {
// After page load injecting a fake body doesn't work so check if body exists
var body = document.body;
if (!body) {
// Can't use the real body create a fake one.
body = createElement(isSVG ? 'svg' : 'body');
body.fake = true;
}
return body;
}
|
javascript
|
function getBody() {
// After page load injecting a fake body doesn't work so check if body exists
var body = document.body;
if (!body) {
// Can't use the real body create a fake one.
body = createElement(isSVG ? 'svg' : 'body');
body.fake = true;
}
return body;
}
|
[
"function",
"getBody",
"(",
")",
"{",
"var",
"body",
"=",
"document",
".",
"body",
";",
"if",
"(",
"!",
"body",
")",
"{",
"body",
"=",
"createElement",
"(",
"isSVG",
"?",
"'svg'",
":",
"'body'",
")",
";",
"body",
".",
"fake",
"=",
"true",
";",
"}",
"return",
"body",
";",
"}"
] |
getBody returns the body of a document, or an element that can stand in for
the body if a real body does not exist
@access private
@function getBody
@returns {HTMLElement|SVGElement} Returns the real body of a document, or an
artificially created element that stands in for the body
|
[
"getBody",
"returns",
"the",
"body",
"of",
"a",
"document",
"or",
"an",
"element",
"that",
"can",
"stand",
"in",
"for",
"the",
"body",
"if",
"a",
"real",
"body",
"does",
"not",
"exist"
] |
f5c53f082634a6e5af56cfc72978ad7bad49b989
|
https://github.com/MoePlayer/DPlayer/blob/f5c53f082634a6e5af56cfc72978ad7bad49b989/demo/modernizr.js#L853-L864
|
train
|
quilljs/quill
|
core/quill.js
|
modify
|
function modify(modifier, source, index, shift) {
if (
!this.isEnabled() &&
source === Emitter.sources.USER &&
!this.allowReadOnlyEdits
) {
return new Delta();
}
let range = index == null ? null : this.getSelection();
const oldDelta = this.editor.delta;
const change = modifier();
if (range != null) {
if (index === true) {
index = range.index; // eslint-disable-line prefer-destructuring
}
if (shift == null) {
range = shiftRange(range, change, source);
} else if (shift !== 0) {
range = shiftRange(range, index, shift, source);
}
this.setSelection(range, Emitter.sources.SILENT);
}
if (change.length() > 0) {
const args = [Emitter.events.TEXT_CHANGE, change, oldDelta, source];
this.emitter.emit(Emitter.events.EDITOR_CHANGE, ...args);
if (source !== Emitter.sources.SILENT) {
this.emitter.emit(...args);
}
}
return change;
}
|
javascript
|
function modify(modifier, source, index, shift) {
if (
!this.isEnabled() &&
source === Emitter.sources.USER &&
!this.allowReadOnlyEdits
) {
return new Delta();
}
let range = index == null ? null : this.getSelection();
const oldDelta = this.editor.delta;
const change = modifier();
if (range != null) {
if (index === true) {
index = range.index; // eslint-disable-line prefer-destructuring
}
if (shift == null) {
range = shiftRange(range, change, source);
} else if (shift !== 0) {
range = shiftRange(range, index, shift, source);
}
this.setSelection(range, Emitter.sources.SILENT);
}
if (change.length() > 0) {
const args = [Emitter.events.TEXT_CHANGE, change, oldDelta, source];
this.emitter.emit(Emitter.events.EDITOR_CHANGE, ...args);
if (source !== Emitter.sources.SILENT) {
this.emitter.emit(...args);
}
}
return change;
}
|
[
"function",
"modify",
"(",
"modifier",
",",
"source",
",",
"index",
",",
"shift",
")",
"{",
"if",
"(",
"!",
"this",
".",
"isEnabled",
"(",
")",
"&&",
"source",
"===",
"Emitter",
".",
"sources",
".",
"USER",
"&&",
"!",
"this",
".",
"allowReadOnlyEdits",
")",
"{",
"return",
"new",
"Delta",
"(",
")",
";",
"}",
"let",
"range",
"=",
"index",
"==",
"null",
"?",
"null",
":",
"this",
".",
"getSelection",
"(",
")",
";",
"const",
"oldDelta",
"=",
"this",
".",
"editor",
".",
"delta",
";",
"const",
"change",
"=",
"modifier",
"(",
")",
";",
"if",
"(",
"range",
"!=",
"null",
")",
"{",
"if",
"(",
"index",
"===",
"true",
")",
"{",
"index",
"=",
"range",
".",
"index",
";",
"}",
"if",
"(",
"shift",
"==",
"null",
")",
"{",
"range",
"=",
"shiftRange",
"(",
"range",
",",
"change",
",",
"source",
")",
";",
"}",
"else",
"if",
"(",
"shift",
"!==",
"0",
")",
"{",
"range",
"=",
"shiftRange",
"(",
"range",
",",
"index",
",",
"shift",
",",
"source",
")",
";",
"}",
"this",
".",
"setSelection",
"(",
"range",
",",
"Emitter",
".",
"sources",
".",
"SILENT",
")",
";",
"}",
"if",
"(",
"change",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"const",
"args",
"=",
"[",
"Emitter",
".",
"events",
".",
"TEXT_CHANGE",
",",
"change",
",",
"oldDelta",
",",
"source",
"]",
";",
"this",
".",
"emitter",
".",
"emit",
"(",
"Emitter",
".",
"events",
".",
"EDITOR_CHANGE",
",",
"...",
"args",
")",
";",
"if",
"(",
"source",
"!==",
"Emitter",
".",
"sources",
".",
"SILENT",
")",
"{",
"this",
".",
"emitter",
".",
"emit",
"(",
"...",
"args",
")",
";",
"}",
"}",
"return",
"change",
";",
"}"
] |
Handle selection preservation and TEXT_CHANGE emission common to modification APIs
|
[
"Handle",
"selection",
"preservation",
"and",
"TEXT_CHANGE",
"emission",
"common",
"to",
"modification",
"APIs"
] |
8ff5b872eb5fe2fc3653a55439acb6f59b12ab2e
|
https://github.com/quilljs/quill/blob/8ff5b872eb5fe2fc3653a55439acb6f59b12ab2e/core/quill.js#L544-L574
|
train
|
quilljs/quill
|
blots/block.js
|
blockDelta
|
function blockDelta(blot, filter = true) {
return blot
.descendants(LeafBlot)
.reduce((delta, leaf) => {
if (leaf.length() === 0) {
return delta;
}
return delta.insert(leaf.value(), bubbleFormats(leaf, {}, filter));
}, new Delta())
.insert('\n', bubbleFormats(blot));
}
|
javascript
|
function blockDelta(blot, filter = true) {
return blot
.descendants(LeafBlot)
.reduce((delta, leaf) => {
if (leaf.length() === 0) {
return delta;
}
return delta.insert(leaf.value(), bubbleFormats(leaf, {}, filter));
}, new Delta())
.insert('\n', bubbleFormats(blot));
}
|
[
"function",
"blockDelta",
"(",
"blot",
",",
"filter",
"=",
"true",
")",
"{",
"return",
"blot",
".",
"descendants",
"(",
"LeafBlot",
")",
".",
"reduce",
"(",
"(",
"delta",
",",
"leaf",
")",
"=>",
"{",
"if",
"(",
"leaf",
".",
"length",
"(",
")",
"===",
"0",
")",
"{",
"return",
"delta",
";",
"}",
"return",
"delta",
".",
"insert",
"(",
"leaf",
".",
"value",
"(",
")",
",",
"bubbleFormats",
"(",
"leaf",
",",
"{",
"}",
",",
"filter",
")",
")",
";",
"}",
",",
"new",
"Delta",
"(",
")",
")",
".",
"insert",
"(",
"'\\n'",
",",
"\\n",
")",
";",
"}"
] |
It is important for cursor behavior BlockEmbeds use tags that are block level elements
|
[
"It",
"is",
"important",
"for",
"cursor",
"behavior",
"BlockEmbeds",
"use",
"tags",
"that",
"are",
"block",
"level",
"elements"
] |
8ff5b872eb5fe2fc3653a55439acb6f59b12ab2e
|
https://github.com/quilljs/quill/blob/8ff5b872eb5fe2fc3653a55439acb6f59b12ab2e/blots/block.js#L168-L178
|
train
|
laurent22/joplin
|
Clipper/joplin-webclipper/content_scripts/JSDOMParser.js
|
function (quote) {
var str;
var n = this.html.indexOf(quote, this.currentChar);
if (n === -1) {
this.currentChar = this.html.length;
str = null;
} else {
str = this.html.substring(this.currentChar, n);
this.currentChar = n + 1;
}
return str;
}
|
javascript
|
function (quote) {
var str;
var n = this.html.indexOf(quote, this.currentChar);
if (n === -1) {
this.currentChar = this.html.length;
str = null;
} else {
str = this.html.substring(this.currentChar, n);
this.currentChar = n + 1;
}
return str;
}
|
[
"function",
"(",
"quote",
")",
"{",
"var",
"str",
";",
"var",
"n",
"=",
"this",
".",
"html",
".",
"indexOf",
"(",
"quote",
",",
"this",
".",
"currentChar",
")",
";",
"if",
"(",
"n",
"===",
"-",
"1",
")",
"{",
"this",
".",
"currentChar",
"=",
"this",
".",
"html",
".",
"length",
";",
"str",
"=",
"null",
";",
"}",
"else",
"{",
"str",
"=",
"this",
".",
"html",
".",
"substring",
"(",
"this",
".",
"currentChar",
",",
"n",
")",
";",
"this",
".",
"currentChar",
"=",
"n",
"+",
"1",
";",
"}",
"return",
"str",
";",
"}"
] |
Called after a quote character is read. This finds the next quote
character and returns the text string in between.
|
[
"Called",
"after",
"a",
"quote",
"character",
"is",
"read",
".",
"This",
"finds",
"the",
"next",
"quote",
"character",
"and",
"returns",
"the",
"text",
"string",
"in",
"between",
"."
] |
beb428b246cecba4630a3ca57b472f43c0933a43
|
https://github.com/laurent22/joplin/blob/beb428b246cecba4630a3ca57b472f43c0933a43/Clipper/joplin-webclipper/content_scripts/JSDOMParser.js#L885-L897
|
train
|
|
laurent22/joplin
|
Clipper/joplin-webclipper/content_scripts/JSDOMParser.js
|
function (retPair) {
var c = this.nextChar();
// Read the Element tag name
var strBuf = this.strBuf;
strBuf.length = 0;
while (whitespace.indexOf(c) == -1 && c !== ">" && c !== "/") {
if (c === undefined)
return false;
strBuf.push(c);
c = this.nextChar();
}
var tag = strBuf.join('');
if (!tag)
return false;
var node = new Element(tag);
// Read Element attributes
while (c !== "/" && c !== ">") {
if (c === undefined)
return false;
while (whitespace.indexOf(this.html[this.currentChar++]) != -1);
this.currentChar--;
c = this.nextChar();
if (c !== "/" && c !== ">") {
--this.currentChar;
this.readAttribute(node);
}
}
// If this is a self-closing tag, read '/>'
var closed = false;
if (c === "/") {
closed = true;
c = this.nextChar();
if (c !== ">") {
this.error("expected '>' to close " + tag);
return false;
}
}
retPair[0] = node;
retPair[1] = closed;
return true;
}
|
javascript
|
function (retPair) {
var c = this.nextChar();
// Read the Element tag name
var strBuf = this.strBuf;
strBuf.length = 0;
while (whitespace.indexOf(c) == -1 && c !== ">" && c !== "/") {
if (c === undefined)
return false;
strBuf.push(c);
c = this.nextChar();
}
var tag = strBuf.join('');
if (!tag)
return false;
var node = new Element(tag);
// Read Element attributes
while (c !== "/" && c !== ">") {
if (c === undefined)
return false;
while (whitespace.indexOf(this.html[this.currentChar++]) != -1);
this.currentChar--;
c = this.nextChar();
if (c !== "/" && c !== ">") {
--this.currentChar;
this.readAttribute(node);
}
}
// If this is a self-closing tag, read '/>'
var closed = false;
if (c === "/") {
closed = true;
c = this.nextChar();
if (c !== ">") {
this.error("expected '>' to close " + tag);
return false;
}
}
retPair[0] = node;
retPair[1] = closed;
return true;
}
|
[
"function",
"(",
"retPair",
")",
"{",
"var",
"c",
"=",
"this",
".",
"nextChar",
"(",
")",
";",
"var",
"strBuf",
"=",
"this",
".",
"strBuf",
";",
"strBuf",
".",
"length",
"=",
"0",
";",
"while",
"(",
"whitespace",
".",
"indexOf",
"(",
"c",
")",
"==",
"-",
"1",
"&&",
"c",
"!==",
"\">\"",
"&&",
"c",
"!==",
"\"/\"",
")",
"{",
"if",
"(",
"c",
"===",
"undefined",
")",
"return",
"false",
";",
"strBuf",
".",
"push",
"(",
"c",
")",
";",
"c",
"=",
"this",
".",
"nextChar",
"(",
")",
";",
"}",
"var",
"tag",
"=",
"strBuf",
".",
"join",
"(",
"''",
")",
";",
"if",
"(",
"!",
"tag",
")",
"return",
"false",
";",
"var",
"node",
"=",
"new",
"Element",
"(",
"tag",
")",
";",
"while",
"(",
"c",
"!==",
"\"/\"",
"&&",
"c",
"!==",
"\">\"",
")",
"{",
"if",
"(",
"c",
"===",
"undefined",
")",
"return",
"false",
";",
"while",
"(",
"whitespace",
".",
"indexOf",
"(",
"this",
".",
"html",
"[",
"this",
".",
"currentChar",
"++",
"]",
")",
"!=",
"-",
"1",
")",
";",
"this",
".",
"currentChar",
"--",
";",
"c",
"=",
"this",
".",
"nextChar",
"(",
")",
";",
"if",
"(",
"c",
"!==",
"\"/\"",
"&&",
"c",
"!==",
"\">\"",
")",
"{",
"--",
"this",
".",
"currentChar",
";",
"this",
".",
"readAttribute",
"(",
"node",
")",
";",
"}",
"}",
"var",
"closed",
"=",
"false",
";",
"if",
"(",
"c",
"===",
"\"/\"",
")",
"{",
"closed",
"=",
"true",
";",
"c",
"=",
"this",
".",
"nextChar",
"(",
")",
";",
"if",
"(",
"c",
"!==",
"\">\"",
")",
"{",
"this",
".",
"error",
"(",
"\"expected '>' to close \"",
"+",
"tag",
")",
";",
"return",
"false",
";",
"}",
"}",
"retPair",
"[",
"0",
"]",
"=",
"node",
";",
"retPair",
"[",
"1",
"]",
"=",
"closed",
";",
"return",
"true",
";",
"}"
] |
Parses and returns an Element node. This is called after a '<' has been
read.
@returns an array; the first index of the array is the parsed node;
the second index is a boolean indicating whether this is a void
Element
|
[
"Parses",
"and",
"returns",
"an",
"Element",
"node",
".",
"This",
"is",
"called",
"after",
"a",
"<",
"has",
"been",
"read",
"."
] |
beb428b246cecba4630a3ca57b472f43c0933a43
|
https://github.com/laurent22/joplin/blob/beb428b246cecba4630a3ca57b472f43c0933a43/Clipper/joplin-webclipper/content_scripts/JSDOMParser.js#L941-L987
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.