id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
800
jhipster/generator-jhipster
generators/utils.js
buildEnumInfo
function buildEnumInfo(field, angularAppName, packageName, clientRootFolder) { const fieldType = field.fieldType; field.enumInstance = _.lowerFirst(fieldType); const enumInfo = { enumName: fieldType, enumValues: field.fieldValues.split(',').join(', '), enumInstance: field.enumInstance, enums: field.fieldValues.replace(/\s/g, '').split(','), angularAppName, packageName, clientRootFolder: clientRootFolder ? `${clientRootFolder}-` : '' }; return enumInfo; }
javascript
function buildEnumInfo(field, angularAppName, packageName, clientRootFolder) { const fieldType = field.fieldType; field.enumInstance = _.lowerFirst(fieldType); const enumInfo = { enumName: fieldType, enumValues: field.fieldValues.split(',').join(', '), enumInstance: field.enumInstance, enums: field.fieldValues.replace(/\s/g, '').split(','), angularAppName, packageName, clientRootFolder: clientRootFolder ? `${clientRootFolder}-` : '' }; return enumInfo; }
[ "function", "buildEnumInfo", "(", "field", ",", "angularAppName", ",", "packageName", ",", "clientRootFolder", ")", "{", "const", "fieldType", "=", "field", ".", "fieldType", ";", "field", ".", "enumInstance", "=", "_", ".", "lowerFirst", "(", "fieldType", ")", ";", "const", "enumInfo", "=", "{", "enumName", ":", "fieldType", ",", "enumValues", ":", "field", ".", "fieldValues", ".", "split", "(", "','", ")", ".", "join", "(", "', '", ")", ",", "enumInstance", ":", "field", ".", "enumInstance", ",", "enums", ":", "field", ".", "fieldValues", ".", "replace", "(", "/", "\\s", "/", "g", ",", "''", ")", ".", "split", "(", "','", ")", ",", "angularAppName", ",", "packageName", ",", "clientRootFolder", ":", "clientRootFolder", "?", "`", "${", "clientRootFolder", "}", "`", ":", "''", "}", ";", "return", "enumInfo", ";", "}" ]
Build an enum object @param {any} field : entity field @param {string} angularAppName @param {string} packageName
[ "Build", "an", "enum", "object" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/utils.js#L378-L391
801
jhipster/generator-jhipster
generators/utils.js
getAllJhipsterConfig
function getAllJhipsterConfig(generator, force) { let configuration = generator && generator.config ? generator.config.getAll() || {} : {}; if ((force || !configuration.baseName) && jhiCore.FileUtils.doesFileExist('.yo-rc.json')) { const yoRc = JSON.parse(fs.readFileSync('.yo-rc.json', { encoding: 'utf-8' })); configuration = yoRc['generator-jhipster']; // merge the blueprint config if available if (configuration.blueprint) { configuration = { ...configuration, ...yoRc[configuration.blueprint] }; } } if (!configuration.get || typeof configuration.get !== 'function') { configuration = { ...configuration, getAll: () => configuration, get: key => configuration[key], set: (key, value) => { configuration[key] = value; } }; } return configuration; }
javascript
function getAllJhipsterConfig(generator, force) { let configuration = generator && generator.config ? generator.config.getAll() || {} : {}; if ((force || !configuration.baseName) && jhiCore.FileUtils.doesFileExist('.yo-rc.json')) { const yoRc = JSON.parse(fs.readFileSync('.yo-rc.json', { encoding: 'utf-8' })); configuration = yoRc['generator-jhipster']; // merge the blueprint config if available if (configuration.blueprint) { configuration = { ...configuration, ...yoRc[configuration.blueprint] }; } } if (!configuration.get || typeof configuration.get !== 'function') { configuration = { ...configuration, getAll: () => configuration, get: key => configuration[key], set: (key, value) => { configuration[key] = value; } }; } return configuration; }
[ "function", "getAllJhipsterConfig", "(", "generator", ",", "force", ")", "{", "let", "configuration", "=", "generator", "&&", "generator", ".", "config", "?", "generator", ".", "config", ".", "getAll", "(", ")", "||", "{", "}", ":", "{", "}", ";", "if", "(", "(", "force", "||", "!", "configuration", ".", "baseName", ")", "&&", "jhiCore", ".", "FileUtils", ".", "doesFileExist", "(", "'.yo-rc.json'", ")", ")", "{", "const", "yoRc", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "'.yo-rc.json'", ",", "{", "encoding", ":", "'utf-8'", "}", ")", ")", ";", "configuration", "=", "yoRc", "[", "'generator-jhipster'", "]", ";", "// merge the blueprint config if available", "if", "(", "configuration", ".", "blueprint", ")", "{", "configuration", "=", "{", "...", "configuration", ",", "...", "yoRc", "[", "configuration", ".", "blueprint", "]", "}", ";", "}", "}", "if", "(", "!", "configuration", ".", "get", "||", "typeof", "configuration", ".", "get", "!==", "'function'", ")", "{", "configuration", "=", "{", "...", "configuration", ",", "getAll", ":", "(", ")", "=>", "configuration", ",", "get", ":", "key", "=>", "configuration", "[", "key", "]", ",", "set", ":", "(", "key", ",", "value", ")", "=>", "{", "configuration", "[", "key", "]", "=", "value", ";", "}", "}", ";", "}", "return", "configuration", ";", "}" ]
Get all the generator configuration from the .yo-rc.json file @param {Generator} generator the generator instance to use @param {boolean} force force getting direct from file
[ "Get", "all", "the", "generator", "configuration", "from", "the", ".", "yo", "-", "rc", ".", "json", "file" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/utils.js#L417-L438
802
jhipster/generator-jhipster
generators/utils.js
getDBTypeFromDBValue
function getDBTypeFromDBValue(db) { if (constants.SQL_DB_OPTIONS.map(db => db.value).includes(db)) { return 'sql'; } return db; }
javascript
function getDBTypeFromDBValue(db) { if (constants.SQL_DB_OPTIONS.map(db => db.value).includes(db)) { return 'sql'; } return db; }
[ "function", "getDBTypeFromDBValue", "(", "db", ")", "{", "if", "(", "constants", ".", "SQL_DB_OPTIONS", ".", "map", "(", "db", "=>", "db", ".", "value", ")", ".", "includes", "(", "db", ")", ")", "{", "return", "'sql'", ";", "}", "return", "db", ";", "}" ]
Get DB type from DB value @param {string} db - db
[ "Get", "DB", "type", "from", "DB", "value" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/utils.js#L444-L449
803
jhipster/generator-jhipster
generators/entity/prompts.js
askForRelationship
function askForRelationship(done) { const context = this.context; const name = context.name; this.log(chalk.green('\nGenerating relationships to other entities\n')); const fieldNamesUnderscored = context.fieldNamesUnderscored; const prompts = [ { type: 'confirm', name: 'relationshipAdd', message: 'Do you want to add a relationship to another entity?', default: true }, { when: response => response.relationshipAdd === true, type: 'input', name: 'otherEntityName', validate: input => { if (!/^([a-zA-Z0-9_]*)$/.test(input)) { return 'Your other entity name cannot contain special characters'; } if (input === '') { return 'Your other entity name cannot be empty'; } if (jhiCore.isReservedKeyword(input, 'JAVA')) { return 'Your other entity name cannot contain a Java reserved keyword'; } if (input.toLowerCase() === 'user' && context.applicationType === 'microservice') { return "Your entity cannot have a relationship with User because it's a gateway entity"; } return true; }, message: 'What is the name of the other entity?' }, { when: response => response.relationshipAdd === true, type: 'input', name: 'relationshipName', validate: input => { if (!/^([a-zA-Z0-9_]*)$/.test(input)) { return 'Your relationship cannot contain special characters'; } if (input === '') { return 'Your relationship cannot be empty'; } if (input.charAt(0) === input.charAt(0).toUpperCase()) { return 'Your relationship cannot start with an upper case letter'; } if (input === 'id' || fieldNamesUnderscored.includes(_.snakeCase(input))) { return 'Your relationship cannot use an already existing field name'; } if (jhiCore.isReservedKeyword(input, 'JAVA')) { return 'Your relationship cannot contain a Java reserved keyword'; } return true; }, message: 'What is the name of the relationship?', default: response => _.lowerFirst(response.otherEntityName) }, { when: response => response.relationshipAdd === true, type: 'list', name: 'relationshipType', message: 'What is the type of the relationship?', choices: response => { const opts = [ { value: 'many-to-one', name: 'many-to-one' }, { value: 'many-to-many', name: 'many-to-many' }, { value: 'one-to-one', name: 'one-to-one' } ]; if (response.otherEntityName.toLowerCase() !== 'user') { opts.unshift({ value: 'one-to-many', name: 'one-to-many' }); } return opts; }, default: 0 }, { when: response => response.relationshipAdd === true && response.otherEntityName.toLowerCase() !== 'user' && (response.relationshipType === 'many-to-many' || response.relationshipType === 'one-to-one'), type: 'confirm', name: 'ownerSide', message: 'Is this entity the owner of the relationship?', default: false }, { when: response => context.databaseType === 'sql' && response.relationshipAdd === true && response.relationshipType === 'one-to-one' && (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user'), type: 'confirm', name: 'useJPADerivedIdentifier', message: 'Do you want to use JPA Derived Identifier - @MapsId?', default: false }, { when: response => response.relationshipAdd === true && (response.relationshipType === 'one-to-many' || ((response.relationshipType === 'many-to-many' || response.relationshipType === 'one-to-one') && response.otherEntityName.toLowerCase() !== 'user')), type: 'input', name: 'otherEntityRelationshipName', message: 'What is the name of this relationship in the other entity?', default: response => _.lowerFirst(name) }, { when: response => response.relationshipAdd === true && (response.relationshipType === 'many-to-one' || (response.relationshipType === 'many-to-many' && response.ownerSide === true) || (response.relationshipType === 'one-to-one' && response.ownerSide === true)), type: 'input', name: 'otherEntityField', message: response => `When you display this relationship on client-side, which field from '${ response.otherEntityName }' do you want to use? This field will be displayed as a String, so it cannot be a Blob`, default: 'id' }, { when: response => response.relationshipAdd === true && response.otherEntityName.toLowerCase() !== context.name.toLowerCase() && (response.relationshipType === 'many-to-one' || (response.relationshipType === 'many-to-many' && (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user')) || (response.relationshipType === 'one-to-one' && (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user'))), type: 'confirm', name: 'relationshipValidate', message: 'Do you want to add any validation rules to this relationship?', default: false }, { when: response => response.relationshipValidate === true, type: 'checkbox', name: 'relationshipValidateRules', message: 'Which validation rules do you want to add?', choices: [ { name: 'Required', value: 'required' } ], default: 0 } ]; this.prompt(prompts).then(props => { if (props.relationshipAdd) { const relationship = { relationshipName: props.relationshipName, otherEntityName: _.lowerFirst(props.otherEntityName), relationshipType: props.relationshipType, relationshipValidateRules: props.relationshipValidateRules, otherEntityField: props.otherEntityField, ownerSide: props.ownerSide, useJPADerivedIdentifier: props.useJPADerivedIdentifier, otherEntityRelationshipName: props.otherEntityRelationshipName }; if (props.otherEntityName.toLowerCase() === 'user') { relationship.ownerSide = true; relationship.otherEntityField = 'login'; relationship.otherEntityRelationshipName = _.lowerFirst(name); } fieldNamesUnderscored.push(_.snakeCase(props.relationshipName)); context.relationships.push(relationship); } logFieldsAndRelationships.call(this); if (props.relationshipAdd) { askForRelationship.call(this, done); } else { this.log('\n'); done(); } }); }
javascript
function askForRelationship(done) { const context = this.context; const name = context.name; this.log(chalk.green('\nGenerating relationships to other entities\n')); const fieldNamesUnderscored = context.fieldNamesUnderscored; const prompts = [ { type: 'confirm', name: 'relationshipAdd', message: 'Do you want to add a relationship to another entity?', default: true }, { when: response => response.relationshipAdd === true, type: 'input', name: 'otherEntityName', validate: input => { if (!/^([a-zA-Z0-9_]*)$/.test(input)) { return 'Your other entity name cannot contain special characters'; } if (input === '') { return 'Your other entity name cannot be empty'; } if (jhiCore.isReservedKeyword(input, 'JAVA')) { return 'Your other entity name cannot contain a Java reserved keyword'; } if (input.toLowerCase() === 'user' && context.applicationType === 'microservice') { return "Your entity cannot have a relationship with User because it's a gateway entity"; } return true; }, message: 'What is the name of the other entity?' }, { when: response => response.relationshipAdd === true, type: 'input', name: 'relationshipName', validate: input => { if (!/^([a-zA-Z0-9_]*)$/.test(input)) { return 'Your relationship cannot contain special characters'; } if (input === '') { return 'Your relationship cannot be empty'; } if (input.charAt(0) === input.charAt(0).toUpperCase()) { return 'Your relationship cannot start with an upper case letter'; } if (input === 'id' || fieldNamesUnderscored.includes(_.snakeCase(input))) { return 'Your relationship cannot use an already existing field name'; } if (jhiCore.isReservedKeyword(input, 'JAVA')) { return 'Your relationship cannot contain a Java reserved keyword'; } return true; }, message: 'What is the name of the relationship?', default: response => _.lowerFirst(response.otherEntityName) }, { when: response => response.relationshipAdd === true, type: 'list', name: 'relationshipType', message: 'What is the type of the relationship?', choices: response => { const opts = [ { value: 'many-to-one', name: 'many-to-one' }, { value: 'many-to-many', name: 'many-to-many' }, { value: 'one-to-one', name: 'one-to-one' } ]; if (response.otherEntityName.toLowerCase() !== 'user') { opts.unshift({ value: 'one-to-many', name: 'one-to-many' }); } return opts; }, default: 0 }, { when: response => response.relationshipAdd === true && response.otherEntityName.toLowerCase() !== 'user' && (response.relationshipType === 'many-to-many' || response.relationshipType === 'one-to-one'), type: 'confirm', name: 'ownerSide', message: 'Is this entity the owner of the relationship?', default: false }, { when: response => context.databaseType === 'sql' && response.relationshipAdd === true && response.relationshipType === 'one-to-one' && (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user'), type: 'confirm', name: 'useJPADerivedIdentifier', message: 'Do you want to use JPA Derived Identifier - @MapsId?', default: false }, { when: response => response.relationshipAdd === true && (response.relationshipType === 'one-to-many' || ((response.relationshipType === 'many-to-many' || response.relationshipType === 'one-to-one') && response.otherEntityName.toLowerCase() !== 'user')), type: 'input', name: 'otherEntityRelationshipName', message: 'What is the name of this relationship in the other entity?', default: response => _.lowerFirst(name) }, { when: response => response.relationshipAdd === true && (response.relationshipType === 'many-to-one' || (response.relationshipType === 'many-to-many' && response.ownerSide === true) || (response.relationshipType === 'one-to-one' && response.ownerSide === true)), type: 'input', name: 'otherEntityField', message: response => `When you display this relationship on client-side, which field from '${ response.otherEntityName }' do you want to use? This field will be displayed as a String, so it cannot be a Blob`, default: 'id' }, { when: response => response.relationshipAdd === true && response.otherEntityName.toLowerCase() !== context.name.toLowerCase() && (response.relationshipType === 'many-to-one' || (response.relationshipType === 'many-to-many' && (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user')) || (response.relationshipType === 'one-to-one' && (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user'))), type: 'confirm', name: 'relationshipValidate', message: 'Do you want to add any validation rules to this relationship?', default: false }, { when: response => response.relationshipValidate === true, type: 'checkbox', name: 'relationshipValidateRules', message: 'Which validation rules do you want to add?', choices: [ { name: 'Required', value: 'required' } ], default: 0 } ]; this.prompt(prompts).then(props => { if (props.relationshipAdd) { const relationship = { relationshipName: props.relationshipName, otherEntityName: _.lowerFirst(props.otherEntityName), relationshipType: props.relationshipType, relationshipValidateRules: props.relationshipValidateRules, otherEntityField: props.otherEntityField, ownerSide: props.ownerSide, useJPADerivedIdentifier: props.useJPADerivedIdentifier, otherEntityRelationshipName: props.otherEntityRelationshipName }; if (props.otherEntityName.toLowerCase() === 'user') { relationship.ownerSide = true; relationship.otherEntityField = 'login'; relationship.otherEntityRelationshipName = _.lowerFirst(name); } fieldNamesUnderscored.push(_.snakeCase(props.relationshipName)); context.relationships.push(relationship); } logFieldsAndRelationships.call(this); if (props.relationshipAdd) { askForRelationship.call(this, done); } else { this.log('\n'); done(); } }); }
[ "function", "askForRelationship", "(", "done", ")", "{", "const", "context", "=", "this", ".", "context", ";", "const", "name", "=", "context", ".", "name", ";", "this", ".", "log", "(", "chalk", ".", "green", "(", "'\\nGenerating relationships to other entities\\n'", ")", ")", ";", "const", "fieldNamesUnderscored", "=", "context", ".", "fieldNamesUnderscored", ";", "const", "prompts", "=", "[", "{", "type", ":", "'confirm'", ",", "name", ":", "'relationshipAdd'", ",", "message", ":", "'Do you want to add a relationship to another entity?'", ",", "default", ":", "true", "}", ",", "{", "when", ":", "response", "=>", "response", ".", "relationshipAdd", "===", "true", ",", "type", ":", "'input'", ",", "name", ":", "'otherEntityName'", ",", "validate", ":", "input", "=>", "{", "if", "(", "!", "/", "^([a-zA-Z0-9_]*)$", "/", ".", "test", "(", "input", ")", ")", "{", "return", "'Your other entity name cannot contain special characters'", ";", "}", "if", "(", "input", "===", "''", ")", "{", "return", "'Your other entity name cannot be empty'", ";", "}", "if", "(", "jhiCore", ".", "isReservedKeyword", "(", "input", ",", "'JAVA'", ")", ")", "{", "return", "'Your other entity name cannot contain a Java reserved keyword'", ";", "}", "if", "(", "input", ".", "toLowerCase", "(", ")", "===", "'user'", "&&", "context", ".", "applicationType", "===", "'microservice'", ")", "{", "return", "\"Your entity cannot have a relationship with User because it's a gateway entity\"", ";", "}", "return", "true", ";", "}", ",", "message", ":", "'What is the name of the other entity?'", "}", ",", "{", "when", ":", "response", "=>", "response", ".", "relationshipAdd", "===", "true", ",", "type", ":", "'input'", ",", "name", ":", "'relationshipName'", ",", "validate", ":", "input", "=>", "{", "if", "(", "!", "/", "^([a-zA-Z0-9_]*)$", "/", ".", "test", "(", "input", ")", ")", "{", "return", "'Your relationship cannot contain special characters'", ";", "}", "if", "(", "input", "===", "''", ")", "{", "return", "'Your relationship cannot be empty'", ";", "}", "if", "(", "input", ".", "charAt", "(", "0", ")", "===", "input", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", ")", "{", "return", "'Your relationship cannot start with an upper case letter'", ";", "}", "if", "(", "input", "===", "'id'", "||", "fieldNamesUnderscored", ".", "includes", "(", "_", ".", "snakeCase", "(", "input", ")", ")", ")", "{", "return", "'Your relationship cannot use an already existing field name'", ";", "}", "if", "(", "jhiCore", ".", "isReservedKeyword", "(", "input", ",", "'JAVA'", ")", ")", "{", "return", "'Your relationship cannot contain a Java reserved keyword'", ";", "}", "return", "true", ";", "}", ",", "message", ":", "'What is the name of the relationship?'", ",", "default", ":", "response", "=>", "_", ".", "lowerFirst", "(", "response", ".", "otherEntityName", ")", "}", ",", "{", "when", ":", "response", "=>", "response", ".", "relationshipAdd", "===", "true", ",", "type", ":", "'list'", ",", "name", ":", "'relationshipType'", ",", "message", ":", "'What is the type of the relationship?'", ",", "choices", ":", "response", "=>", "{", "const", "opts", "=", "[", "{", "value", ":", "'many-to-one'", ",", "name", ":", "'many-to-one'", "}", ",", "{", "value", ":", "'many-to-many'", ",", "name", ":", "'many-to-many'", "}", ",", "{", "value", ":", "'one-to-one'", ",", "name", ":", "'one-to-one'", "}", "]", ";", "if", "(", "response", ".", "otherEntityName", ".", "toLowerCase", "(", ")", "!==", "'user'", ")", "{", "opts", ".", "unshift", "(", "{", "value", ":", "'one-to-many'", ",", "name", ":", "'one-to-many'", "}", ")", ";", "}", "return", "opts", ";", "}", ",", "default", ":", "0", "}", ",", "{", "when", ":", "response", "=>", "response", ".", "relationshipAdd", "===", "true", "&&", "response", ".", "otherEntityName", ".", "toLowerCase", "(", ")", "!==", "'user'", "&&", "(", "response", ".", "relationshipType", "===", "'many-to-many'", "||", "response", ".", "relationshipType", "===", "'one-to-one'", ")", ",", "type", ":", "'confirm'", ",", "name", ":", "'ownerSide'", ",", "message", ":", "'Is this entity the owner of the relationship?'", ",", "default", ":", "false", "}", ",", "{", "when", ":", "response", "=>", "context", ".", "databaseType", "===", "'sql'", "&&", "response", ".", "relationshipAdd", "===", "true", "&&", "response", ".", "relationshipType", "===", "'one-to-one'", "&&", "(", "response", ".", "ownerSide", "===", "true", "||", "response", ".", "otherEntityName", ".", "toLowerCase", "(", ")", "===", "'user'", ")", ",", "type", ":", "'confirm'", ",", "name", ":", "'useJPADerivedIdentifier'", ",", "message", ":", "'Do you want to use JPA Derived Identifier - @MapsId?'", ",", "default", ":", "false", "}", ",", "{", "when", ":", "response", "=>", "response", ".", "relationshipAdd", "===", "true", "&&", "(", "response", ".", "relationshipType", "===", "'one-to-many'", "||", "(", "(", "response", ".", "relationshipType", "===", "'many-to-many'", "||", "response", ".", "relationshipType", "===", "'one-to-one'", ")", "&&", "response", ".", "otherEntityName", ".", "toLowerCase", "(", ")", "!==", "'user'", ")", ")", ",", "type", ":", "'input'", ",", "name", ":", "'otherEntityRelationshipName'", ",", "message", ":", "'What is the name of this relationship in the other entity?'", ",", "default", ":", "response", "=>", "_", ".", "lowerFirst", "(", "name", ")", "}", ",", "{", "when", ":", "response", "=>", "response", ".", "relationshipAdd", "===", "true", "&&", "(", "response", ".", "relationshipType", "===", "'many-to-one'", "||", "(", "response", ".", "relationshipType", "===", "'many-to-many'", "&&", "response", ".", "ownerSide", "===", "true", ")", "||", "(", "response", ".", "relationshipType", "===", "'one-to-one'", "&&", "response", ".", "ownerSide", "===", "true", ")", ")", ",", "type", ":", "'input'", ",", "name", ":", "'otherEntityField'", ",", "message", ":", "response", "=>", "`", "${", "response", ".", "otherEntityName", "}", "`", ",", "default", ":", "'id'", "}", ",", "{", "when", ":", "response", "=>", "response", ".", "relationshipAdd", "===", "true", "&&", "response", ".", "otherEntityName", ".", "toLowerCase", "(", ")", "!==", "context", ".", "name", ".", "toLowerCase", "(", ")", "&&", "(", "response", ".", "relationshipType", "===", "'many-to-one'", "||", "(", "response", ".", "relationshipType", "===", "'many-to-many'", "&&", "(", "response", ".", "ownerSide", "===", "true", "||", "response", ".", "otherEntityName", ".", "toLowerCase", "(", ")", "===", "'user'", ")", ")", "||", "(", "response", ".", "relationshipType", "===", "'one-to-one'", "&&", "(", "response", ".", "ownerSide", "===", "true", "||", "response", ".", "otherEntityName", ".", "toLowerCase", "(", ")", "===", "'user'", ")", ")", ")", ",", "type", ":", "'confirm'", ",", "name", ":", "'relationshipValidate'", ",", "message", ":", "'Do you want to add any validation rules to this relationship?'", ",", "default", ":", "false", "}", ",", "{", "when", ":", "response", "=>", "response", ".", "relationshipValidate", "===", "true", ",", "type", ":", "'checkbox'", ",", "name", ":", "'relationshipValidateRules'", ",", "message", ":", "'Which validation rules do you want to add?'", ",", "choices", ":", "[", "{", "name", ":", "'Required'", ",", "value", ":", "'required'", "}", "]", ",", "default", ":", "0", "}", "]", ";", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "if", "(", "props", ".", "relationshipAdd", ")", "{", "const", "relationship", "=", "{", "relationshipName", ":", "props", ".", "relationshipName", ",", "otherEntityName", ":", "_", ".", "lowerFirst", "(", "props", ".", "otherEntityName", ")", ",", "relationshipType", ":", "props", ".", "relationshipType", ",", "relationshipValidateRules", ":", "props", ".", "relationshipValidateRules", ",", "otherEntityField", ":", "props", ".", "otherEntityField", ",", "ownerSide", ":", "props", ".", "ownerSide", ",", "useJPADerivedIdentifier", ":", "props", ".", "useJPADerivedIdentifier", ",", "otherEntityRelationshipName", ":", "props", ".", "otherEntityRelationshipName", "}", ";", "if", "(", "props", ".", "otherEntityName", ".", "toLowerCase", "(", ")", "===", "'user'", ")", "{", "relationship", ".", "ownerSide", "=", "true", ";", "relationship", ".", "otherEntityField", "=", "'login'", ";", "relationship", ".", "otherEntityRelationshipName", "=", "_", ".", "lowerFirst", "(", "name", ")", ";", "}", "fieldNamesUnderscored", ".", "push", "(", "_", ".", "snakeCase", "(", "props", ".", "relationshipName", ")", ")", ";", "context", ".", "relationships", ".", "push", "(", "relationship", ")", ";", "}", "logFieldsAndRelationships", ".", "call", "(", "this", ")", ";", "if", "(", "props", ".", "relationshipAdd", ")", "{", "askForRelationship", ".", "call", "(", "this", ",", "done", ")", ";", "}", "else", "{", "this", ".", "log", "(", "'\\n'", ")", ";", "done", "(", ")", ";", "}", "}", ")", ";", "}" ]
ask question for a relationship creation
[ "ask", "question", "for", "a", "relationship", "creation" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/entity/prompts.js#L878-L1070
804
jhipster/generator-jhipster
generators/entity/prompts.js
logFieldsAndRelationships
function logFieldsAndRelationships() { const context = this.context; if (context.fields.length > 0 || context.relationships.length > 0) { this.log(chalk.red(chalk.white('\n================= ') + context.entityNameCapitalized + chalk.white(' ================='))); } if (context.fields.length > 0) { this.log(chalk.white('Fields')); context.fields.forEach(field => { const validationDetails = []; const fieldValidate = _.isArray(field.fieldValidateRules) && field.fieldValidateRules.length >= 1; if (fieldValidate === true) { if (field.fieldValidateRules.includes('required')) { validationDetails.push('required'); } if (field.fieldValidateRules.includes('unique')) { validationDetails.push('unique'); } if (field.fieldValidateRules.includes('minlength')) { validationDetails.push(`minlength='${field.fieldValidateRulesMinlength}'`); } if (field.fieldValidateRules.includes('maxlength')) { validationDetails.push(`maxlength='${field.fieldValidateRulesMaxlength}'`); } if (field.fieldValidateRules.includes('pattern')) { validationDetails.push(`pattern='${field.fieldValidateRulesPattern}'`); } if (field.fieldValidateRules.includes('min')) { validationDetails.push(`min='${field.fieldValidateRulesMin}'`); } if (field.fieldValidateRules.includes('max')) { validationDetails.push(`max='${field.fieldValidateRulesMax}'`); } if (field.fieldValidateRules.includes('minbytes')) { validationDetails.push(`minbytes='${field.fieldValidateRulesMinbytes}'`); } if (field.fieldValidateRules.includes('maxbytes')) { validationDetails.push(`maxbytes='${field.fieldValidateRulesMaxbytes}'`); } } this.log( chalk.red(field.fieldName) + chalk.white(` (${field.fieldType}${field.fieldTypeBlobContent ? ` ${field.fieldTypeBlobContent}` : ''}) `) + chalk.cyan(validationDetails.join(' ')) ); }); this.log(); } if (context.relationships.length > 0) { this.log(chalk.white('Relationships')); context.relationships.forEach(relationship => { const validationDetails = []; if (relationship.relationshipValidateRules && relationship.relationshipValidateRules.includes('required')) { validationDetails.push('required'); } this.log( `${chalk.red(relationship.relationshipName)} ${chalk.white(`(${_.upperFirst(relationship.otherEntityName)})`)} ${chalk.cyan( relationship.relationshipType )} ${chalk.cyan(validationDetails.join(' '))}` ); }); this.log(); } }
javascript
function logFieldsAndRelationships() { const context = this.context; if (context.fields.length > 0 || context.relationships.length > 0) { this.log(chalk.red(chalk.white('\n================= ') + context.entityNameCapitalized + chalk.white(' ================='))); } if (context.fields.length > 0) { this.log(chalk.white('Fields')); context.fields.forEach(field => { const validationDetails = []; const fieldValidate = _.isArray(field.fieldValidateRules) && field.fieldValidateRules.length >= 1; if (fieldValidate === true) { if (field.fieldValidateRules.includes('required')) { validationDetails.push('required'); } if (field.fieldValidateRules.includes('unique')) { validationDetails.push('unique'); } if (field.fieldValidateRules.includes('minlength')) { validationDetails.push(`minlength='${field.fieldValidateRulesMinlength}'`); } if (field.fieldValidateRules.includes('maxlength')) { validationDetails.push(`maxlength='${field.fieldValidateRulesMaxlength}'`); } if (field.fieldValidateRules.includes('pattern')) { validationDetails.push(`pattern='${field.fieldValidateRulesPattern}'`); } if (field.fieldValidateRules.includes('min')) { validationDetails.push(`min='${field.fieldValidateRulesMin}'`); } if (field.fieldValidateRules.includes('max')) { validationDetails.push(`max='${field.fieldValidateRulesMax}'`); } if (field.fieldValidateRules.includes('minbytes')) { validationDetails.push(`minbytes='${field.fieldValidateRulesMinbytes}'`); } if (field.fieldValidateRules.includes('maxbytes')) { validationDetails.push(`maxbytes='${field.fieldValidateRulesMaxbytes}'`); } } this.log( chalk.red(field.fieldName) + chalk.white(` (${field.fieldType}${field.fieldTypeBlobContent ? ` ${field.fieldTypeBlobContent}` : ''}) `) + chalk.cyan(validationDetails.join(' ')) ); }); this.log(); } if (context.relationships.length > 0) { this.log(chalk.white('Relationships')); context.relationships.forEach(relationship => { const validationDetails = []; if (relationship.relationshipValidateRules && relationship.relationshipValidateRules.includes('required')) { validationDetails.push('required'); } this.log( `${chalk.red(relationship.relationshipName)} ${chalk.white(`(${_.upperFirst(relationship.otherEntityName)})`)} ${chalk.cyan( relationship.relationshipType )} ${chalk.cyan(validationDetails.join(' '))}` ); }); this.log(); } }
[ "function", "logFieldsAndRelationships", "(", ")", "{", "const", "context", "=", "this", ".", "context", ";", "if", "(", "context", ".", "fields", ".", "length", ">", "0", "||", "context", ".", "relationships", ".", "length", ">", "0", ")", "{", "this", ".", "log", "(", "chalk", ".", "red", "(", "chalk", ".", "white", "(", "'\\n================= '", ")", "+", "context", ".", "entityNameCapitalized", "+", "chalk", ".", "white", "(", "' ================='", ")", ")", ")", ";", "}", "if", "(", "context", ".", "fields", ".", "length", ">", "0", ")", "{", "this", ".", "log", "(", "chalk", ".", "white", "(", "'Fields'", ")", ")", ";", "context", ".", "fields", ".", "forEach", "(", "field", "=>", "{", "const", "validationDetails", "=", "[", "]", ";", "const", "fieldValidate", "=", "_", ".", "isArray", "(", "field", ".", "fieldValidateRules", ")", "&&", "field", ".", "fieldValidateRules", ".", "length", ">=", "1", ";", "if", "(", "fieldValidate", "===", "true", ")", "{", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'required'", ")", ")", "{", "validationDetails", ".", "push", "(", "'required'", ")", ";", "}", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'unique'", ")", ")", "{", "validationDetails", ".", "push", "(", "'unique'", ")", ";", "}", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'minlength'", ")", ")", "{", "validationDetails", ".", "push", "(", "`", "${", "field", ".", "fieldValidateRulesMinlength", "}", "`", ")", ";", "}", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'maxlength'", ")", ")", "{", "validationDetails", ".", "push", "(", "`", "${", "field", ".", "fieldValidateRulesMaxlength", "}", "`", ")", ";", "}", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'pattern'", ")", ")", "{", "validationDetails", ".", "push", "(", "`", "${", "field", ".", "fieldValidateRulesPattern", "}", "`", ")", ";", "}", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'min'", ")", ")", "{", "validationDetails", ".", "push", "(", "`", "${", "field", ".", "fieldValidateRulesMin", "}", "`", ")", ";", "}", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'max'", ")", ")", "{", "validationDetails", ".", "push", "(", "`", "${", "field", ".", "fieldValidateRulesMax", "}", "`", ")", ";", "}", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'minbytes'", ")", ")", "{", "validationDetails", ".", "push", "(", "`", "${", "field", ".", "fieldValidateRulesMinbytes", "}", "`", ")", ";", "}", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'maxbytes'", ")", ")", "{", "validationDetails", ".", "push", "(", "`", "${", "field", ".", "fieldValidateRulesMaxbytes", "}", "`", ")", ";", "}", "}", "this", ".", "log", "(", "chalk", ".", "red", "(", "field", ".", "fieldName", ")", "+", "chalk", ".", "white", "(", "`", "${", "field", ".", "fieldType", "}", "${", "field", ".", "fieldTypeBlobContent", "?", "`", "${", "field", ".", "fieldTypeBlobContent", "}", "`", ":", "''", "}", "`", ")", "+", "chalk", ".", "cyan", "(", "validationDetails", ".", "join", "(", "' '", ")", ")", ")", ";", "}", ")", ";", "this", ".", "log", "(", ")", ";", "}", "if", "(", "context", ".", "relationships", ".", "length", ">", "0", ")", "{", "this", ".", "log", "(", "chalk", ".", "white", "(", "'Relationships'", ")", ")", ";", "context", ".", "relationships", ".", "forEach", "(", "relationship", "=>", "{", "const", "validationDetails", "=", "[", "]", ";", "if", "(", "relationship", ".", "relationshipValidateRules", "&&", "relationship", ".", "relationshipValidateRules", ".", "includes", "(", "'required'", ")", ")", "{", "validationDetails", ".", "push", "(", "'required'", ")", ";", "}", "this", ".", "log", "(", "`", "${", "chalk", ".", "red", "(", "relationship", ".", "relationshipName", ")", "}", "${", "chalk", ".", "white", "(", "`", "${", "_", ".", "upperFirst", "(", "relationship", ".", "otherEntityName", ")", "}", "`", ")", "}", "${", "chalk", ".", "cyan", "(", "relationship", ".", "relationshipType", ")", "}", "${", "chalk", ".", "cyan", "(", "validationDetails", ".", "join", "(", "' '", ")", ")", "}", "`", ")", ";", "}", ")", ";", "this", ".", "log", "(", ")", ";", "}", "}" ]
Show the entity and it's fields and relationships in console
[ "Show", "the", "entity", "and", "it", "s", "fields", "and", "relationships", "in", "console" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/entity/prompts.js#L1075-L1137
805
jhipster/generator-jhipster
generators/aws-containers/aws-client.js
loadAWS
function loadAWS(generator) { return new Promise((resolve, reject) => { try { AWS = require('aws-sdk'); // eslint-disable-line ProgressBar = require('progress'); // eslint-disable-line ora = require('ora'); // eslint-disable-line } catch (e) { generator.log('Installing AWS dependencies'); let installCommand = 'yarn add aws-sdk@2.167.0 progress@2.0.0 ora@1.3.0'; if (generator.config.get('clientPackageManager') === 'npm') { installCommand = 'npm install aws-sdk@2.167.0 progress@2.0.0 ora@1.3.0--save'; } shelljs.exec(installCommand, { silent: false }, code => { if (code !== 0) { generator.error('Something went wrong while installing the dependencies\n'); reject(); } AWS = require('aws-sdk'); // eslint-disable-line ProgressBar = require('progress'); // eslint-disable-line ora = require('ora'); // eslint-disable-line }); } resolve(); }); }
javascript
function loadAWS(generator) { return new Promise((resolve, reject) => { try { AWS = require('aws-sdk'); // eslint-disable-line ProgressBar = require('progress'); // eslint-disable-line ora = require('ora'); // eslint-disable-line } catch (e) { generator.log('Installing AWS dependencies'); let installCommand = 'yarn add aws-sdk@2.167.0 progress@2.0.0 ora@1.3.0'; if (generator.config.get('clientPackageManager') === 'npm') { installCommand = 'npm install aws-sdk@2.167.0 progress@2.0.0 ora@1.3.0--save'; } shelljs.exec(installCommand, { silent: false }, code => { if (code !== 0) { generator.error('Something went wrong while installing the dependencies\n'); reject(); } AWS = require('aws-sdk'); // eslint-disable-line ProgressBar = require('progress'); // eslint-disable-line ora = require('ora'); // eslint-disable-line }); } resolve(); }); }
[ "function", "loadAWS", "(", "generator", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "AWS", "=", "require", "(", "'aws-sdk'", ")", ";", "// eslint-disable-line", "ProgressBar", "=", "require", "(", "'progress'", ")", ";", "// eslint-disable-line", "ora", "=", "require", "(", "'ora'", ")", ";", "// eslint-disable-line", "}", "catch", "(", "e", ")", "{", "generator", ".", "log", "(", "'Installing AWS dependencies'", ")", ";", "let", "installCommand", "=", "'yarn add aws-sdk@2.167.0 progress@2.0.0 ora@1.3.0'", ";", "if", "(", "generator", ".", "config", ".", "get", "(", "'clientPackageManager'", ")", "===", "'npm'", ")", "{", "installCommand", "=", "'npm install aws-sdk@2.167.0 progress@2.0.0 ora@1.3.0--save'", ";", "}", "shelljs", ".", "exec", "(", "installCommand", ",", "{", "silent", ":", "false", "}", ",", "code", "=>", "{", "if", "(", "code", "!==", "0", ")", "{", "generator", ".", "error", "(", "'Something went wrong while installing the dependencies\\n'", ")", ";", "reject", "(", ")", ";", "}", "AWS", "=", "require", "(", "'aws-sdk'", ")", ";", "// eslint-disable-line", "ProgressBar", "=", "require", "(", "'progress'", ")", ";", "// eslint-disable-line", "ora", "=", "require", "(", "'ora'", ")", ";", "// eslint-disable-line", "}", ")", ";", "}", "resolve", "(", ")", ";", "}", ")", ";", "}" ]
Will load the aws-sdk npm dependency if it's not already loaded. @param generator the yeoman generator it'll be loaded in. @returns {Promise} The promise will succeed if the aws-sdk has been loaded and fails if it couldn't be installed.
[ "Will", "load", "the", "aws", "-", "sdk", "npm", "dependency", "if", "it", "s", "not", "already", "loaded", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/aws-client.js#L73-L97
806
jhipster/generator-jhipster
generators/aws-containers/aws-client.js
initAwsStuff
function initAwsStuff(region = DEFAULT_REGION) { ec2 = new AWS.EC2({ region }); // ecr = new AWS.ECR({ region }); s3 = new AWS.S3(); sts = new AWS.STS(); SSM = new AwsSSM(region); ECR = new AwsECR(region); CF = new AwsCF(region); }
javascript
function initAwsStuff(region = DEFAULT_REGION) { ec2 = new AWS.EC2({ region }); // ecr = new AWS.ECR({ region }); s3 = new AWS.S3(); sts = new AWS.STS(); SSM = new AwsSSM(region); ECR = new AwsECR(region); CF = new AwsCF(region); }
[ "function", "initAwsStuff", "(", "region", "=", "DEFAULT_REGION", ")", "{", "ec2", "=", "new", "AWS", ".", "EC2", "(", "{", "region", "}", ")", ";", "// ecr = new AWS.ECR({ region });", "s3", "=", "new", "AWS", ".", "S3", "(", ")", ";", "sts", "=", "new", "AWS", ".", "STS", "(", ")", ";", "SSM", "=", "new", "AwsSSM", "(", "region", ")", ";", "ECR", "=", "new", "AwsECR", "(", "region", ")", ";", "CF", "=", "new", "AwsCF", "(", "region", ")", ";", "}" ]
Init AWS stuff like ECR and whatnot. @param ecrConfig The config used to instanciate ECR
[ "Init", "AWS", "stuff", "like", "ECR", "and", "whatnot", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/aws-client.js#L104-L113
807
jhipster/generator-jhipster
generators/aws-containers/aws-client.js
getDockerLogin
function getDockerLogin() { return spinner( new Promise((resolve, reject) => _getAuthorizationToken().then(authToken => sts .getCallerIdentity({}) .promise() .then(data => { const decoded = utils.decodeBase64(authToken.authorizationToken); const splitResult = decoded.split(':'); resolve({ username: splitResult[0], password: splitResult[1], accountId: data.Account }); }) .catch(() => reject(new Error("Couldn't retrieve the user informations"))) ) ) ); }
javascript
function getDockerLogin() { return spinner( new Promise((resolve, reject) => _getAuthorizationToken().then(authToken => sts .getCallerIdentity({}) .promise() .then(data => { const decoded = utils.decodeBase64(authToken.authorizationToken); const splitResult = decoded.split(':'); resolve({ username: splitResult[0], password: splitResult[1], accountId: data.Account }); }) .catch(() => reject(new Error("Couldn't retrieve the user informations"))) ) ) ); }
[ "function", "getDockerLogin", "(", ")", "{", "return", "spinner", "(", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "_getAuthorizationToken", "(", ")", ".", "then", "(", "authToken", "=>", "sts", ".", "getCallerIdentity", "(", "{", "}", ")", ".", "promise", "(", ")", ".", "then", "(", "data", "=>", "{", "const", "decoded", "=", "utils", ".", "decodeBase64", "(", "authToken", ".", "authorizationToken", ")", ";", "const", "splitResult", "=", "decoded", ".", "split", "(", "':'", ")", ";", "resolve", "(", "{", "username", ":", "splitResult", "[", "0", "]", ",", "password", ":", "splitResult", "[", "1", "]", ",", "accountId", ":", "data", ".", "Account", "}", ")", ";", "}", ")", ".", "catch", "(", "(", ")", "=>", "reject", "(", "new", "Error", "(", "\"Couldn't retrieve the user informations\"", ")", ")", ")", ")", ")", ")", ";", "}" ]
Retrieve decoded information to authenticate to Docker with AWS credentials. @returns {Promise} Returns a promise that resolves when the informations are retrieved.
[ "Retrieve", "decoded", "information", "to", "authenticate", "to", "Docker", "with", "AWS", "credentials", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/aws-client.js#L213-L233
808
jhipster/generator-jhipster
generators/aws-containers/aws-client.js
_getAuthorizationToken
function _getAuthorizationToken() { return spinner( new Promise((resolve, reject) => ECR.sdk .getAuthorizationToken({}) .promise() .then(data => { if (!_.has(data, 'authorizationData.0')) { reject(new Error('No authorization data found.')); return; } resolve(data.authorizationData[0]); }) ) ); }
javascript
function _getAuthorizationToken() { return spinner( new Promise((resolve, reject) => ECR.sdk .getAuthorizationToken({}) .promise() .then(data => { if (!_.has(data, 'authorizationData.0')) { reject(new Error('No authorization data found.')); return; } resolve(data.authorizationData[0]); }) ) ); }
[ "function", "_getAuthorizationToken", "(", ")", "{", "return", "spinner", "(", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "ECR", ".", "sdk", ".", "getAuthorizationToken", "(", "{", "}", ")", ".", "promise", "(", ")", ".", "then", "(", "data", "=>", "{", "if", "(", "!", "_", ".", "has", "(", "data", ",", "'authorizationData.0'", ")", ")", "{", "reject", "(", "new", "Error", "(", "'No authorization data found.'", ")", ")", ";", "return", ";", "}", "resolve", "(", "data", ".", "authorizationData", "[", "0", "]", ")", ";", "}", ")", ")", ")", ";", "}" ]
Fetch Authentication token from AWS to authenticate with Docker @returns {Promise} Returns a promise that resolves when the informations are retrieved. @private
[ "Fetch", "Authentication", "token", "from", "AWS", "to", "authenticate", "with", "Docker" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/aws-client.js#L240-L255
809
jhipster/generator-jhipster
generators/aws-containers/aws-client.js
createS3Bucket
function createS3Bucket(bucketName, region = DEFAULT_REGION) { const createBuckerParams = { Bucket: bucketName }; return spinner( new Promise((resolve, reject) => s3 .headBucket({ Bucket: bucketName }) .promise() .catch(error => { if (error.code !== 'NotFound') { reject( new Error( `The S3 Bucket ${chalk.bold(bucketName)} in region ${chalk.bold( region )} already exists and you don't have access to it. Error code: ${chalk.bold(error.code)}` ) ); } }) .then(() => s3 .createBucket(createBuckerParams) .promise() .then(resolve) .catch(error => reject( new Error( `There was an error during the creation of the S3 Bucket ${chalk.bold( bucketName )} in region ${chalk.bold(region)}` ) ) ) ) ) ); }
javascript
function createS3Bucket(bucketName, region = DEFAULT_REGION) { const createBuckerParams = { Bucket: bucketName }; return spinner( new Promise((resolve, reject) => s3 .headBucket({ Bucket: bucketName }) .promise() .catch(error => { if (error.code !== 'NotFound') { reject( new Error( `The S3 Bucket ${chalk.bold(bucketName)} in region ${chalk.bold( region )} already exists and you don't have access to it. Error code: ${chalk.bold(error.code)}` ) ); } }) .then(() => s3 .createBucket(createBuckerParams) .promise() .then(resolve) .catch(error => reject( new Error( `There was an error during the creation of the S3 Bucket ${chalk.bold( bucketName )} in region ${chalk.bold(region)}` ) ) ) ) ) ); }
[ "function", "createS3Bucket", "(", "bucketName", ",", "region", "=", "DEFAULT_REGION", ")", "{", "const", "createBuckerParams", "=", "{", "Bucket", ":", "bucketName", "}", ";", "return", "spinner", "(", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "s3", ".", "headBucket", "(", "{", "Bucket", ":", "bucketName", "}", ")", ".", "promise", "(", ")", ".", "catch", "(", "error", "=>", "{", "if", "(", "error", ".", "code", "!==", "'NotFound'", ")", "{", "reject", "(", "new", "Error", "(", "`", "${", "chalk", ".", "bold", "(", "bucketName", ")", "}", "${", "chalk", ".", "bold", "(", "region", ")", "}", "${", "chalk", ".", "bold", "(", "error", ".", "code", ")", "}", "`", ")", ")", ";", "}", "}", ")", ".", "then", "(", "(", ")", "=>", "s3", ".", "createBucket", "(", "createBuckerParams", ")", ".", "promise", "(", ")", ".", "then", "(", "resolve", ")", ".", "catch", "(", "error", "=>", "reject", "(", "new", "Error", "(", "`", "${", "chalk", ".", "bold", "(", "bucketName", ")", "}", "${", "chalk", ".", "bold", "(", "region", ")", "}", "`", ")", ")", ")", ")", ")", ")", ";", "}" ]
Create a S3 Bucket in said region with said bucketBaseName. the bucketBaseName will be used to create a @param bucketName the name of the bucket to create. @param region the region to create the bucket in. @returns {Promise}
[ "Create", "a", "S3", "Bucket", "in", "said", "region", "with", "said", "bucketBaseName", ".", "the", "bucketBaseName", "will", "be", "used", "to", "create", "a" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/aws-client.js#L264-L303
810
jhipster/generator-jhipster
generators/aws-containers/aws-client.js
uploadTemplate
function uploadTemplate(bucketName, filename, path) { return spinner( new Promise((resolve, reject) => fs.stat(path, (error, stats) => { if (!stats) { reject(new Error(`File ${chalk.bold(path)} not found`)); } const upload = s3.upload( { Bucket: bucketName, Key: filename, Body: fs.createReadStream(path) }, { partSize: Math.max(stats.size, S3_MIN_PART_SIZE), queueSize: 1 } ); let bar; upload.on('httpUploadProgress', evt => { if (!bar && evt.total) { const total = evt.total / 1000000; bar = new ProgressBar('uploading [:bar] :percent :etas', { complete: '=', incomplete: ' ', width: 20, total, clear: true }); } const curr = evt.loaded / 1000000; bar.tick(curr - bar.curr); }); return upload .promise() .then(resolve) .catch(reject); }) ) ); }
javascript
function uploadTemplate(bucketName, filename, path) { return spinner( new Promise((resolve, reject) => fs.stat(path, (error, stats) => { if (!stats) { reject(new Error(`File ${chalk.bold(path)} not found`)); } const upload = s3.upload( { Bucket: bucketName, Key: filename, Body: fs.createReadStream(path) }, { partSize: Math.max(stats.size, S3_MIN_PART_SIZE), queueSize: 1 } ); let bar; upload.on('httpUploadProgress', evt => { if (!bar && evt.total) { const total = evt.total / 1000000; bar = new ProgressBar('uploading [:bar] :percent :etas', { complete: '=', incomplete: ' ', width: 20, total, clear: true }); } const curr = evt.loaded / 1000000; bar.tick(curr - bar.curr); }); return upload .promise() .then(resolve) .catch(reject); }) ) ); }
[ "function", "uploadTemplate", "(", "bucketName", ",", "filename", ",", "path", ")", "{", "return", "spinner", "(", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "fs", ".", "stat", "(", "path", ",", "(", "error", ",", "stats", ")", "=>", "{", "if", "(", "!", "stats", ")", "{", "reject", "(", "new", "Error", "(", "`", "${", "chalk", ".", "bold", "(", "path", ")", "}", "`", ")", ")", ";", "}", "const", "upload", "=", "s3", ".", "upload", "(", "{", "Bucket", ":", "bucketName", ",", "Key", ":", "filename", ",", "Body", ":", "fs", ".", "createReadStream", "(", "path", ")", "}", ",", "{", "partSize", ":", "Math", ".", "max", "(", "stats", ".", "size", ",", "S3_MIN_PART_SIZE", ")", ",", "queueSize", ":", "1", "}", ")", ";", "let", "bar", ";", "upload", ".", "on", "(", "'httpUploadProgress'", ",", "evt", "=>", "{", "if", "(", "!", "bar", "&&", "evt", ".", "total", ")", "{", "const", "total", "=", "evt", ".", "total", "/", "1000000", ";", "bar", "=", "new", "ProgressBar", "(", "'uploading [:bar] :percent :etas'", ",", "{", "complete", ":", "'='", ",", "incomplete", ":", "' '", ",", "width", ":", "20", ",", "total", ",", "clear", ":", "true", "}", ")", ";", "}", "const", "curr", "=", "evt", ".", "loaded", "/", "1000000", ";", "bar", ".", "tick", "(", "curr", "-", "bar", ".", "curr", ")", ";", "}", ")", ";", "return", "upload", ".", "promise", "(", ")", ".", "then", "(", "resolve", ")", ".", "catch", "(", "reject", ")", ";", "}", ")", ")", ")", ";", "}" ]
Upload the template in the S3Bucket @param bucketName S3 Bucket name to upload the template into @param filename Name to give to the file in the Bucket @param path Path to the file @returns {Promise}
[ "Upload", "the", "template", "in", "the", "S3Bucket" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/aws-client.js#L312-L353
811
jhipster/generator-jhipster
generators/docker-prompts.js
askForApplicationType
function askForApplicationType() { if (this.regenerate) return; const done = this.async(); const prompts = [ { type: 'list', name: 'deploymentApplicationType', message: 'Which *type* of application would you like to deploy?', choices: [ { value: 'monolith', name: 'Monolithic application' }, { value: 'microservice', name: 'Microservice application' } ], default: 'monolith' } ]; this.prompt(prompts).then(props => { this.deploymentApplicationType = props.deploymentApplicationType; done(); }); }
javascript
function askForApplicationType() { if (this.regenerate) return; const done = this.async(); const prompts = [ { type: 'list', name: 'deploymentApplicationType', message: 'Which *type* of application would you like to deploy?', choices: [ { value: 'monolith', name: 'Monolithic application' }, { value: 'microservice', name: 'Microservice application' } ], default: 'monolith' } ]; this.prompt(prompts).then(props => { this.deploymentApplicationType = props.deploymentApplicationType; done(); }); }
[ "function", "askForApplicationType", "(", ")", "{", "if", "(", "this", ".", "regenerate", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'list'", ",", "name", ":", "'deploymentApplicationType'", ",", "message", ":", "'Which *type* of application would you like to deploy?'", ",", "choices", ":", "[", "{", "value", ":", "'monolith'", ",", "name", ":", "'Monolithic application'", "}", ",", "{", "value", ":", "'microservice'", ",", "name", ":", "'Microservice application'", "}", "]", ",", "default", ":", "'monolith'", "}", "]", ";", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "deploymentApplicationType", "=", "props", ".", "deploymentApplicationType", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Ask For Application Type
[ "Ask", "For", "Application", "Type" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L42-L70
812
jhipster/generator-jhipster
generators/docker-prompts.js
askForPath
function askForPath() { if (this.regenerate) return; const done = this.async(); const deploymentApplicationType = this.deploymentApplicationType; let messageAskForPath; if (deploymentApplicationType === 'monolith') { messageAskForPath = 'Enter the root directory where your applications are located'; } else { messageAskForPath = 'Enter the root directory where your gateway(s) and microservices are located'; } const prompts = [ { type: 'input', name: 'directoryPath', message: messageAskForPath, default: this.directoryPath || '../', validate: input => { const path = this.destinationPath(input); if (shelljs.test('-d', path)) { const appsFolders = getAppFolders.call(this, input, deploymentApplicationType); if (appsFolders.length === 0) { return deploymentApplicationType === 'monolith' ? `No monolith found in ${path}` : `No microservice or gateway found in ${path}`; } return true; } return `${path} is not a directory or doesn't exist`; } } ]; this.prompt(prompts).then(props => { this.directoryPath = props.directoryPath; // Patch the path if there is no trailing "/" if (!this.directoryPath.endsWith('/')) { this.log(chalk.yellow(`The path "${this.directoryPath}" does not end with a trailing "/", adding it anyway.`)); this.directoryPath += '/'; } this.appsFolders = getAppFolders.call(this, this.directoryPath, deploymentApplicationType); // Removing registry from appsFolders, using reverse for loop for (let i = this.appsFolders.length - 1; i >= 0; i--) { if (this.appsFolders[i] === 'jhipster-registry' || this.appsFolders[i] === 'registry') { this.appsFolders.splice(i, 1); } } this.log(chalk.green(`${this.appsFolders.length} applications found at ${this.destinationPath(this.directoryPath)}\n`)); done(); }); }
javascript
function askForPath() { if (this.regenerate) return; const done = this.async(); const deploymentApplicationType = this.deploymentApplicationType; let messageAskForPath; if (deploymentApplicationType === 'monolith') { messageAskForPath = 'Enter the root directory where your applications are located'; } else { messageAskForPath = 'Enter the root directory where your gateway(s) and microservices are located'; } const prompts = [ { type: 'input', name: 'directoryPath', message: messageAskForPath, default: this.directoryPath || '../', validate: input => { const path = this.destinationPath(input); if (shelljs.test('-d', path)) { const appsFolders = getAppFolders.call(this, input, deploymentApplicationType); if (appsFolders.length === 0) { return deploymentApplicationType === 'monolith' ? `No monolith found in ${path}` : `No microservice or gateway found in ${path}`; } return true; } return `${path} is not a directory or doesn't exist`; } } ]; this.prompt(prompts).then(props => { this.directoryPath = props.directoryPath; // Patch the path if there is no trailing "/" if (!this.directoryPath.endsWith('/')) { this.log(chalk.yellow(`The path "${this.directoryPath}" does not end with a trailing "/", adding it anyway.`)); this.directoryPath += '/'; } this.appsFolders = getAppFolders.call(this, this.directoryPath, deploymentApplicationType); // Removing registry from appsFolders, using reverse for loop for (let i = this.appsFolders.length - 1; i >= 0; i--) { if (this.appsFolders[i] === 'jhipster-registry' || this.appsFolders[i] === 'registry') { this.appsFolders.splice(i, 1); } } this.log(chalk.green(`${this.appsFolders.length} applications found at ${this.destinationPath(this.directoryPath)}\n`)); done(); }); }
[ "function", "askForPath", "(", ")", "{", "if", "(", "this", ".", "regenerate", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "deploymentApplicationType", "=", "this", ".", "deploymentApplicationType", ";", "let", "messageAskForPath", ";", "if", "(", "deploymentApplicationType", "===", "'monolith'", ")", "{", "messageAskForPath", "=", "'Enter the root directory where your applications are located'", ";", "}", "else", "{", "messageAskForPath", "=", "'Enter the root directory where your gateway(s) and microservices are located'", ";", "}", "const", "prompts", "=", "[", "{", "type", ":", "'input'", ",", "name", ":", "'directoryPath'", ",", "message", ":", "messageAskForPath", ",", "default", ":", "this", ".", "directoryPath", "||", "'../'", ",", "validate", ":", "input", "=>", "{", "const", "path", "=", "this", ".", "destinationPath", "(", "input", ")", ";", "if", "(", "shelljs", ".", "test", "(", "'-d'", ",", "path", ")", ")", "{", "const", "appsFolders", "=", "getAppFolders", ".", "call", "(", "this", ",", "input", ",", "deploymentApplicationType", ")", ";", "if", "(", "appsFolders", ".", "length", "===", "0", ")", "{", "return", "deploymentApplicationType", "===", "'monolith'", "?", "`", "${", "path", "}", "`", ":", "`", "${", "path", "}", "`", ";", "}", "return", "true", ";", "}", "return", "`", "${", "path", "}", "`", ";", "}", "}", "]", ";", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "directoryPath", "=", "props", ".", "directoryPath", ";", "// Patch the path if there is no trailing \"/\"", "if", "(", "!", "this", ".", "directoryPath", ".", "endsWith", "(", "'/'", ")", ")", "{", "this", ".", "log", "(", "chalk", ".", "yellow", "(", "`", "${", "this", ".", "directoryPath", "}", "`", ")", ")", ";", "this", ".", "directoryPath", "+=", "'/'", ";", "}", "this", ".", "appsFolders", "=", "getAppFolders", ".", "call", "(", "this", ",", "this", ".", "directoryPath", ",", "deploymentApplicationType", ")", ";", "// Removing registry from appsFolders, using reverse for loop", "for", "(", "let", "i", "=", "this", ".", "appsFolders", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "this", ".", "appsFolders", "[", "i", "]", "===", "'jhipster-registry'", "||", "this", ".", "appsFolders", "[", "i", "]", "===", "'registry'", ")", "{", "this", ".", "appsFolders", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "}", "this", ".", "log", "(", "chalk", ".", "green", "(", "`", "${", "this", ".", "appsFolders", ".", "length", "}", "${", "this", ".", "destinationPath", "(", "this", ".", "directoryPath", ")", "}", "\\n", "`", ")", ")", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Ask For Path
[ "Ask", "For", "Path" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L108-L163
813
jhipster/generator-jhipster
generators/docker-prompts.js
askForApps
function askForApps() { if (this.regenerate) return; const done = this.async(); const messageAskForApps = 'Which applications do you want to include in your configuration?'; const prompts = [ { type: 'checkbox', name: 'chosenApps', message: messageAskForApps, choices: this.appsFolders, default: this.defaultAppsFolders, validate: input => (input.length === 0 ? 'Please choose at least one application' : true) } ]; this.prompt(prompts).then(props => { this.appsFolders = props.chosenApps; loadConfigs.call(this); done(); }); }
javascript
function askForApps() { if (this.regenerate) return; const done = this.async(); const messageAskForApps = 'Which applications do you want to include in your configuration?'; const prompts = [ { type: 'checkbox', name: 'chosenApps', message: messageAskForApps, choices: this.appsFolders, default: this.defaultAppsFolders, validate: input => (input.length === 0 ? 'Please choose at least one application' : true) } ]; this.prompt(prompts).then(props => { this.appsFolders = props.chosenApps; loadConfigs.call(this); done(); }); }
[ "function", "askForApps", "(", ")", "{", "if", "(", "this", ".", "regenerate", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "messageAskForApps", "=", "'Which applications do you want to include in your configuration?'", ";", "const", "prompts", "=", "[", "{", "type", ":", "'checkbox'", ",", "name", ":", "'chosenApps'", ",", "message", ":", "messageAskForApps", ",", "choices", ":", "this", ".", "appsFolders", ",", "default", ":", "this", ".", "defaultAppsFolders", ",", "validate", ":", "input", "=>", "(", "input", ".", "length", "===", "0", "?", "'Please choose at least one application'", ":", "true", ")", "}", "]", ";", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "appsFolders", "=", "props", ".", "chosenApps", ";", "loadConfigs", ".", "call", "(", "this", ")", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Ask For Apps
[ "Ask", "For", "Apps" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L168-L191
814
jhipster/generator-jhipster
generators/docker-prompts.js
askForClustersMode
function askForClustersMode() { if (this.regenerate) return; const clusteredDbApps = []; this.appConfigs.forEach((appConfig, index) => { if (appConfig.prodDatabaseType === 'mongodb' || appConfig.prodDatabaseType === 'couchbase') { clusteredDbApps.push(this.appsFolders[index]); } }); if (clusteredDbApps.length === 0) return; const done = this.async(); const prompts = [ { type: 'checkbox', name: 'clusteredDbApps', message: 'Which applications do you want to use with clustered databases (only available with MongoDB and Couchbase)?', choices: clusteredDbApps, default: this.clusteredDbApps } ]; this.prompt(prompts).then(props => { this.clusteredDbApps = props.clusteredDbApps; setClusteredApps.call(this); done(); }); }
javascript
function askForClustersMode() { if (this.regenerate) return; const clusteredDbApps = []; this.appConfigs.forEach((appConfig, index) => { if (appConfig.prodDatabaseType === 'mongodb' || appConfig.prodDatabaseType === 'couchbase') { clusteredDbApps.push(this.appsFolders[index]); } }); if (clusteredDbApps.length === 0) return; const done = this.async(); const prompts = [ { type: 'checkbox', name: 'clusteredDbApps', message: 'Which applications do you want to use with clustered databases (only available with MongoDB and Couchbase)?', choices: clusteredDbApps, default: this.clusteredDbApps } ]; this.prompt(prompts).then(props => { this.clusteredDbApps = props.clusteredDbApps; setClusteredApps.call(this); done(); }); }
[ "function", "askForClustersMode", "(", ")", "{", "if", "(", "this", ".", "regenerate", ")", "return", ";", "const", "clusteredDbApps", "=", "[", "]", ";", "this", ".", "appConfigs", ".", "forEach", "(", "(", "appConfig", ",", "index", ")", "=>", "{", "if", "(", "appConfig", ".", "prodDatabaseType", "===", "'mongodb'", "||", "appConfig", ".", "prodDatabaseType", "===", "'couchbase'", ")", "{", "clusteredDbApps", ".", "push", "(", "this", ".", "appsFolders", "[", "index", "]", ")", ";", "}", "}", ")", ";", "if", "(", "clusteredDbApps", ".", "length", "===", "0", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'checkbox'", ",", "name", ":", "'clusteredDbApps'", ",", "message", ":", "'Which applications do you want to use with clustered databases (only available with MongoDB and Couchbase)?'", ",", "choices", ":", "clusteredDbApps", ",", "default", ":", "this", ".", "clusteredDbApps", "}", "]", ";", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "clusteredDbApps", "=", "props", ".", "clusteredDbApps", ";", "setClusteredApps", ".", "call", "(", "this", ")", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Ask For Clusters Mode
[ "Ask", "For", "Clusters", "Mode" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L196-L225
815
jhipster/generator-jhipster
generators/docker-prompts.js
askForMonitoring
function askForMonitoring() { if (this.regenerate) return; const done = this.async(); const prompts = [ { type: 'list', name: 'monitoring', message: 'Do you want to setup monitoring for your applications ?', choices: [ { value: 'no', name: 'No' }, { value: 'elk', name: this.deploymentApplicationType === 'monolith' ? 'Yes, for logs and metrics with the JHipster Console (based on ELK)' : 'Yes, for logs and metrics with the JHipster Console (based on ELK and Zipkin)' }, { value: 'prometheus', name: 'Yes, for metrics only with Prometheus' } ], default: this.monitoring ? this.monitoring : 'no' } ]; this.prompt(prompts).then(props => { this.monitoring = props.monitoring; done(); }); }
javascript
function askForMonitoring() { if (this.regenerate) return; const done = this.async(); const prompts = [ { type: 'list', name: 'monitoring', message: 'Do you want to setup monitoring for your applications ?', choices: [ { value: 'no', name: 'No' }, { value: 'elk', name: this.deploymentApplicationType === 'monolith' ? 'Yes, for logs and metrics with the JHipster Console (based on ELK)' : 'Yes, for logs and metrics with the JHipster Console (based on ELK and Zipkin)' }, { value: 'prometheus', name: 'Yes, for metrics only with Prometheus' } ], default: this.monitoring ? this.monitoring : 'no' } ]; this.prompt(prompts).then(props => { this.monitoring = props.monitoring; done(); }); }
[ "function", "askForMonitoring", "(", ")", "{", "if", "(", "this", ".", "regenerate", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'list'", ",", "name", ":", "'monitoring'", ",", "message", ":", "'Do you want to setup monitoring for your applications ?'", ",", "choices", ":", "[", "{", "value", ":", "'no'", ",", "name", ":", "'No'", "}", ",", "{", "value", ":", "'elk'", ",", "name", ":", "this", ".", "deploymentApplicationType", "===", "'monolith'", "?", "'Yes, for logs and metrics with the JHipster Console (based on ELK)'", ":", "'Yes, for logs and metrics with the JHipster Console (based on ELK and Zipkin)'", "}", ",", "{", "value", ":", "'prometheus'", ",", "name", ":", "'Yes, for metrics only with Prometheus'", "}", "]", ",", "default", ":", "this", ".", "monitoring", "?", "this", ".", "monitoring", ":", "'no'", "}", "]", ";", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "monitoring", "=", "props", ".", "monitoring", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Ask For Monitoring
[ "Ask", "For", "Monitoring" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L230-L265
816
jhipster/generator-jhipster
generators/docker-prompts.js
askForConsoleOptions
function askForConsoleOptions() { if (this.regenerate) return; if (this.monitoring !== 'elk') return; const done = this.async(); const prompts = [ { type: 'checkbox', name: 'consoleOptions', message: 'You have selected the JHipster Console which is based on the ELK stack and additional technologies, which one do you want to use ?', choices: [ { value: 'curator', name: 'Curator, to help you curate and manage your Elasticsearch indices' } ], default: this.monitoring } ]; if (this.deploymentApplicationType === 'microservice') { prompts[0].choices.push({ value: 'zipkin', name: 'Zipkin, for distributed tracing (only compatible with JHipster >= v4.2.0)' }); } this.prompt(prompts).then(props => { this.consoleOptions = props.consoleOptions; done(); }); }
javascript
function askForConsoleOptions() { if (this.regenerate) return; if (this.monitoring !== 'elk') return; const done = this.async(); const prompts = [ { type: 'checkbox', name: 'consoleOptions', message: 'You have selected the JHipster Console which is based on the ELK stack and additional technologies, which one do you want to use ?', choices: [ { value: 'curator', name: 'Curator, to help you curate and manage your Elasticsearch indices' } ], default: this.monitoring } ]; if (this.deploymentApplicationType === 'microservice') { prompts[0].choices.push({ value: 'zipkin', name: 'Zipkin, for distributed tracing (only compatible with JHipster >= v4.2.0)' }); } this.prompt(prompts).then(props => { this.consoleOptions = props.consoleOptions; done(); }); }
[ "function", "askForConsoleOptions", "(", ")", "{", "if", "(", "this", ".", "regenerate", ")", "return", ";", "if", "(", "this", ".", "monitoring", "!==", "'elk'", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'checkbox'", ",", "name", ":", "'consoleOptions'", ",", "message", ":", "'You have selected the JHipster Console which is based on the ELK stack and additional technologies, which one do you want to use ?'", ",", "choices", ":", "[", "{", "value", ":", "'curator'", ",", "name", ":", "'Curator, to help you curate and manage your Elasticsearch indices'", "}", "]", ",", "default", ":", "this", ".", "monitoring", "}", "]", ";", "if", "(", "this", ".", "deploymentApplicationType", "===", "'microservice'", ")", "{", "prompts", "[", "0", "]", ".", "choices", ".", "push", "(", "{", "value", ":", "'zipkin'", ",", "name", ":", "'Zipkin, for distributed tracing (only compatible with JHipster >= v4.2.0)'", "}", ")", ";", "}", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "consoleOptions", "=", "props", ".", "consoleOptions", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Ask For Console Options
[ "Ask", "For", "Console", "Options" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L270-L302
817
jhipster/generator-jhipster
generators/docker-prompts.js
askForServiceDiscovery
function askForServiceDiscovery() { if (this.regenerate) return; const done = this.async(); const serviceDiscoveryEnabledApps = []; this.appConfigs.forEach((appConfig, index) => { if (appConfig.serviceDiscoveryType) { serviceDiscoveryEnabledApps.push({ baseName: appConfig.baseName, serviceDiscoveryType: appConfig.serviceDiscoveryType }); } }); if (serviceDiscoveryEnabledApps.length === 0) { this.serviceDiscoveryType = false; done(); return; } if (serviceDiscoveryEnabledApps.every(app => app.serviceDiscoveryType === 'consul')) { this.serviceDiscoveryType = 'consul'; this.log(chalk.green('Consul detected as the service discovery and configuration provider used by your apps')); done(); } else if (serviceDiscoveryEnabledApps.every(app => app.serviceDiscoveryType === 'eureka')) { this.serviceDiscoveryType = 'eureka'; this.log(chalk.green('JHipster registry detected as the service discovery and configuration provider used by your apps')); done(); } else { this.log(chalk.yellow('Unable to determine the service discovery and configuration provider to use from your apps configuration.')); this.log('Your service discovery enabled apps:'); serviceDiscoveryEnabledApps.forEach(app => { this.log(` -${app.baseName} (${app.serviceDiscoveryType})`); }); const prompts = [ { type: 'list', name: 'serviceDiscoveryType', message: 'Which Service Discovery registry and Configuration server would you like to use ?', choices: [ { value: 'eureka', name: 'JHipster Registry' }, { value: 'consul', name: 'Consul' }, { value: false, name: 'No Service Discovery and Configuration' } ], default: 'eureka' } ]; this.prompt(prompts).then(props => { this.serviceDiscoveryType = props.serviceDiscoveryType; done(); }); } }
javascript
function askForServiceDiscovery() { if (this.regenerate) return; const done = this.async(); const serviceDiscoveryEnabledApps = []; this.appConfigs.forEach((appConfig, index) => { if (appConfig.serviceDiscoveryType) { serviceDiscoveryEnabledApps.push({ baseName: appConfig.baseName, serviceDiscoveryType: appConfig.serviceDiscoveryType }); } }); if (serviceDiscoveryEnabledApps.length === 0) { this.serviceDiscoveryType = false; done(); return; } if (serviceDiscoveryEnabledApps.every(app => app.serviceDiscoveryType === 'consul')) { this.serviceDiscoveryType = 'consul'; this.log(chalk.green('Consul detected as the service discovery and configuration provider used by your apps')); done(); } else if (serviceDiscoveryEnabledApps.every(app => app.serviceDiscoveryType === 'eureka')) { this.serviceDiscoveryType = 'eureka'; this.log(chalk.green('JHipster registry detected as the service discovery and configuration provider used by your apps')); done(); } else { this.log(chalk.yellow('Unable to determine the service discovery and configuration provider to use from your apps configuration.')); this.log('Your service discovery enabled apps:'); serviceDiscoveryEnabledApps.forEach(app => { this.log(` -${app.baseName} (${app.serviceDiscoveryType})`); }); const prompts = [ { type: 'list', name: 'serviceDiscoveryType', message: 'Which Service Discovery registry and Configuration server would you like to use ?', choices: [ { value: 'eureka', name: 'JHipster Registry' }, { value: 'consul', name: 'Consul' }, { value: false, name: 'No Service Discovery and Configuration' } ], default: 'eureka' } ]; this.prompt(prompts).then(props => { this.serviceDiscoveryType = props.serviceDiscoveryType; done(); }); } }
[ "function", "askForServiceDiscovery", "(", ")", "{", "if", "(", "this", ".", "regenerate", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "serviceDiscoveryEnabledApps", "=", "[", "]", ";", "this", ".", "appConfigs", ".", "forEach", "(", "(", "appConfig", ",", "index", ")", "=>", "{", "if", "(", "appConfig", ".", "serviceDiscoveryType", ")", "{", "serviceDiscoveryEnabledApps", ".", "push", "(", "{", "baseName", ":", "appConfig", ".", "baseName", ",", "serviceDiscoveryType", ":", "appConfig", ".", "serviceDiscoveryType", "}", ")", ";", "}", "}", ")", ";", "if", "(", "serviceDiscoveryEnabledApps", ".", "length", "===", "0", ")", "{", "this", ".", "serviceDiscoveryType", "=", "false", ";", "done", "(", ")", ";", "return", ";", "}", "if", "(", "serviceDiscoveryEnabledApps", ".", "every", "(", "app", "=>", "app", ".", "serviceDiscoveryType", "===", "'consul'", ")", ")", "{", "this", ".", "serviceDiscoveryType", "=", "'consul'", ";", "this", ".", "log", "(", "chalk", ".", "green", "(", "'Consul detected as the service discovery and configuration provider used by your apps'", ")", ")", ";", "done", "(", ")", ";", "}", "else", "if", "(", "serviceDiscoveryEnabledApps", ".", "every", "(", "app", "=>", "app", ".", "serviceDiscoveryType", "===", "'eureka'", ")", ")", "{", "this", ".", "serviceDiscoveryType", "=", "'eureka'", ";", "this", ".", "log", "(", "chalk", ".", "green", "(", "'JHipster registry detected as the service discovery and configuration provider used by your apps'", ")", ")", ";", "done", "(", ")", ";", "}", "else", "{", "this", ".", "log", "(", "chalk", ".", "yellow", "(", "'Unable to determine the service discovery and configuration provider to use from your apps configuration.'", ")", ")", ";", "this", ".", "log", "(", "'Your service discovery enabled apps:'", ")", ";", "serviceDiscoveryEnabledApps", ".", "forEach", "(", "app", "=>", "{", "this", ".", "log", "(", "`", "${", "app", ".", "baseName", "}", "${", "app", ".", "serviceDiscoveryType", "}", "`", ")", ";", "}", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'list'", ",", "name", ":", "'serviceDiscoveryType'", ",", "message", ":", "'Which Service Discovery registry and Configuration server would you like to use ?'", ",", "choices", ":", "[", "{", "value", ":", "'eureka'", ",", "name", ":", "'JHipster Registry'", "}", ",", "{", "value", ":", "'consul'", ",", "name", ":", "'Consul'", "}", ",", "{", "value", ":", "false", ",", "name", ":", "'No Service Discovery and Configuration'", "}", "]", ",", "default", ":", "'eureka'", "}", "]", ";", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "serviceDiscoveryType", "=", "props", ".", "serviceDiscoveryType", ";", "done", "(", ")", ";", "}", ")", ";", "}", "}" ]
Ask For Service Discovery
[ "Ask", "For", "Service", "Discovery" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L307-L371
818
jhipster/generator-jhipster
generators/docker-prompts.js
askForAdminPassword
function askForAdminPassword() { if (this.regenerate || this.serviceDiscoveryType !== 'eureka') return; const done = this.async(); const prompts = [ { type: 'input', name: 'adminPassword', message: 'Enter the admin password used to secure the JHipster Registry', default: 'admin', validate: input => (input.length < 5 ? 'The password must have at least 5 characters' : true) } ]; this.prompt(prompts).then(props => { this.adminPassword = props.adminPassword; this.adminPasswordBase64 = getBase64Secret(this.adminPassword); done(); }); }
javascript
function askForAdminPassword() { if (this.regenerate || this.serviceDiscoveryType !== 'eureka') return; const done = this.async(); const prompts = [ { type: 'input', name: 'adminPassword', message: 'Enter the admin password used to secure the JHipster Registry', default: 'admin', validate: input => (input.length < 5 ? 'The password must have at least 5 characters' : true) } ]; this.prompt(prompts).then(props => { this.adminPassword = props.adminPassword; this.adminPasswordBase64 = getBase64Secret(this.adminPassword); done(); }); }
[ "function", "askForAdminPassword", "(", ")", "{", "if", "(", "this", ".", "regenerate", "||", "this", ".", "serviceDiscoveryType", "!==", "'eureka'", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'input'", ",", "name", ":", "'adminPassword'", ",", "message", ":", "'Enter the admin password used to secure the JHipster Registry'", ",", "default", ":", "'admin'", ",", "validate", ":", "input", "=>", "(", "input", ".", "length", "<", "5", "?", "'The password must have at least 5 characters'", ":", "true", ")", "}", "]", ";", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "adminPassword", "=", "props", ".", "adminPassword", ";", "this", ".", "adminPasswordBase64", "=", "getBase64Secret", "(", "this", ".", "adminPassword", ")", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Ask For Admin Password
[ "Ask", "For", "Admin", "Password" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L376-L396
819
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
820
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
821
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
822
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
823
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
824
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", ";", "// Loading configs", "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
825
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'", ")", "||", "// feature commit", "parsedCommit", ".", "notes", ".", "find", "(", "(", "note", ")", "=>", "note", ".", "title", "===", "'BREAKING CHANGE'", ")", "||", "// breaking change commit", "(", "parsedCommit", ".", "type", "===", "'chore'", "&&", "parsedCommit", ".", "subject", "===", "'Publish'", ")", ";", "// Publish (version-rev) commit", "}" ]
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
826
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", ")", "{", "// 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", "=", "`", "\\`", "${", "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
827
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
828
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", ")", "{", "// 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", ";", "}", "}", "}" ]
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
829
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", ")", "{", "// 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", "}" ]
Get time format
[ "Get", "time", "format" ]
484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6
https://github.com/airyland/vux/blob/484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6/src/components/video/zy.media.js#L138-L159
830
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
831
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 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", "}", "}", "}" ]
Get media type
[ "Get", "media", "type" ]
484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6
https://github.com/airyland/vux/blob/484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6/src/components/video/zy.media.js#L195-L209
832
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", ";", "// 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", "}" ]
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
833
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
834
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", ")", "{", "// 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.'", ")", "}", "}" ]
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
835
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", "// 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", "}", "}" ]
Time string formatter
[ "Time", "string", "formatter" ]
484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6
https://github.com/airyland/vux/blob/484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6/src/components/clocker/clocker.js#L59-L114
836
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", "// 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", ")", "}" ]
The Final Countdown
[ "The", "Final", "Countdown" ]
484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6
https://github.com/airyland/vux/blob/484fc3c18bdca99b0c08efbb678c0ee0f5ceedd6/src/components/clocker/clocker.js#L143-L153
837
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", "}", "`", ")", "// https://github.com/webpack/webpack/issues/1643\r", "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
838
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
839
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
840
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
841
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", ">", "\n ", "{", "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", "}", "/", ">", ")", ";", "}", "}", "\n ", "<", "/", "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
842
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%\"", ">", "\n ", "<", "Block", "className", "=", "\"api-doc\"", ">", "\n ", "<", "ScrollToDoc", "doc", "=", "{", "doc", "}", "header", "=", "{", "header", "}", "/", ">", "\n ", "<", "MarkdownViewer", "html", "=", "{", "doc", ".", "markup", "}", "/", ">", "\n ", "<", "/", "Block", ">", "\n ", "<", "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", "}", "`", "}", "/", ">", ")", ";", "}", "}", "/", ">", "\n ", "<", "/", "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
843
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
844
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", ">", "\n ", "{", "context", "=>", "{", "invariant", "(", "context", ",", "`", "${", "displayName", "}", "`", ")", ";", "return", "(", "<", "Component", "{", "...", "remainingProps", "}", "{", "...", "context", "}", "ref", "=", "{", "wrappedComponentRef", "}", "/", ">", ")", ";", "}", "}", "\n ", "<", "/", "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
845
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
846
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
847
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", ")", ";", "// 0: fps, 1: ms, 2: mb, 3+: custom", "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
848
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'", ")", ";", "// 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", "(", ")", ";", "}" ]
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
849
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
850
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
851
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", ";", "// displacements not used for single pose decoding", "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
852
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
853
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", "]", ";", "// 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", ";", "}", "}" ]
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
854
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
855
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
856
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'", ")", ";", "// 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", "(", ")", ";", "}" ]
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
857
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
858
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
859
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", "(", ")", "{", "// 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", ")", ";", "}", "}" ]
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
860
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", "(", ")", ";", "// 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", "]", "}", "${", "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
861
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
862
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
863
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", "(", ")", ";", "// 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", ")", ";", "}" ]
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
864
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", "=", "[", "/* [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", ")", ";", "}", "}" ]
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
865
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
866
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
867
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", "]", ")", ")", ";", "// [::::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", "]", ")", ")", ";", "}", "}" ]
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
868
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", ")", "{", "// 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", ")", ";", "}" ]
Initialize a single slider.
[ "Initialize", "a", "single", "slider", "." ]
1122efadad8f1433d404696f7613e3cc13fb83a4
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L960-L978
869
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", "(", ")", "{", "// 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>'", ";", "}", ")", ";", "}" ]
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
870
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
871
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", ")", "{", "// 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", ";", "}" ]
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
872
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", ";", "}", "// 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", ")", ";", "}" ]
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
873
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", ")", "{", "// 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", ";", "}" ]
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
874
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
875
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", ")", "{", "// 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", ";", "}" ]
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
876
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", "(", "// 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", "(", ")", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
External event handling
[ "External", "event", "handling" ]
1122efadad8f1433d404696f7613e3cc13fb83a4
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1447-L1473
877
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
878
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", ")", "{", "// 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", ")", ";", "}" ]
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
879
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", ")", "{", "// 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", ")", ";", "}", ")", ";", "}" ]
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
880
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", "]", "]", ";", "// 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", ")", ";", "}", ")", ";", "}" ]
Bind move events on document.
[ "Bind", "move", "events", "on", "document", "." ]
1122efadad8f1433d404696f7613e3cc13fb83a4
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1537-L1604
881
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", ")", "{", "// 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", "]", "}", ")", ";", "}", "}" ]
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
882
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", ")", "{", "// 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", "]", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", "}" ]
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
883
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", ")", "{", "// 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", ";", "}" ]
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
884
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", ")", "{", "// 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", "(", ")", ";", "}", "}" ]
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
885
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
886
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
887
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", ")", "{", "// 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", ")", ";", "}" ]
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
888
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", ";", "// 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", ")", ";", "}", "}", ")", ";", "}" ]
Set the slider value.
[ "Set", "the", "slider", "value", "." ]
1122efadad8f1433d404696f7613e3cc13fb83a4
https://github.com/Dogfalo/materialize/blob/1122efadad8f1433d404696f7613e3cc13fb83a4/extras/noUiSlider/nouislider.js#L1878-L1910
889
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 only one handle is used, return a single value.", "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
890
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
891
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", "(", ")", "{", "// 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", "]", ";", "}", ")", ";", "}" ]
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
892
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 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", ")", ";", "}", ")", ";", "}", "}" ]
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
893
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
894
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", ";", "}", "// Test the options and create the slider environment;", "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
895
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
896
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
897
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", ")", ";", "// 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", ")", ";", "}" ]
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
898
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", ";", "/**\n * Options for the modal\n * @member Modal#options\n * @prop {Number} [opacity=0.5] - Opacity of the modal overlay\n * @prop {Number} [inDuration=250] - Length in ms of enter transition\n * @prop {Number} [outDuration=250] - Length in ms of exit transition\n * @prop {Function} onOpenStart - Callback function called before modal is opened\n * @prop {Function} onOpenEnd - Callback function called after modal is opened\n * @prop {Function} onCloseStart - Callback function called before modal is closed\n * @prop {Function} onCloseEnd - Callback function called after modal is closed\n * @prop {Boolean} [dismissible=true] - Allow modal to be dismissed by keyboard or overlay click\n * @prop {String} [startingTop='4%'] - startingTop\n * @prop {String} [endingTop='10%'] - endingTop\n */", "_this13", ".", "options", "=", "$", ".", "extend", "(", "{", "}", ",", "Modal", ".", "defaults", ",", "options", ")", ";", "/**\n * Describes open/close state of modal\n * @type {Boolean}\n */", "_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
899
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