repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
angular/angular
tools/gulp-tasks/cldr/extract.js
getDayPeriodRules
function getDayPeriodRules(localeData) { const dayPeriodRules = localeData.get(`supplemental/dayPeriodRuleSet/${localeData.attributes.language}`); const rules = {}; if (dayPeriodRules) { Object.keys(dayPeriodRules).forEach(key => { if (dayPeriodRules[key]._at) { rules[key] = dayPeriodRules[key]._at; } else { rules[key] = [dayPeriodRules[key]._from, dayPeriodRules[key]._before]; } }); } return rules; }
javascript
function getDayPeriodRules(localeData) { const dayPeriodRules = localeData.get(`supplemental/dayPeriodRuleSet/${localeData.attributes.language}`); const rules = {}; if (dayPeriodRules) { Object.keys(dayPeriodRules).forEach(key => { if (dayPeriodRules[key]._at) { rules[key] = dayPeriodRules[key]._at; } else { rules[key] = [dayPeriodRules[key]._from, dayPeriodRules[key]._before]; } }); } return rules; }
[ "function", "getDayPeriodRules", "(", "localeData", ")", "{", "const", "dayPeriodRules", "=", "localeData", ".", "get", "(", "`", "${", "localeData", ".", "attributes", ".", "language", "}", "`", ")", ";", "const", "rules", "=", "{", "}", ";", "if", "(", "dayPeriodRules", ")", "{", "Object", ".", "keys", "(", "dayPeriodRules", ")", ".", "forEach", "(", "key", "=>", "{", "if", "(", "dayPeriodRules", "[", "key", "]", ".", "_at", ")", "{", "rules", "[", "key", "]", "=", "dayPeriodRules", "[", "key", "]", ".", "_at", ";", "}", "else", "{", "rules", "[", "key", "]", "=", "[", "dayPeriodRules", "[", "key", "]", ".", "_from", ",", "dayPeriodRules", "[", "key", "]", ".", "_before", "]", ";", "}", "}", ")", ";", "}", "return", "rules", ";", "}" ]
Returns day period rules for a locale @returns string[]
[ "Returns", "day", "period", "rules", "for", "a", "locale" ]
c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c
https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L374-L388
train
angular/angular
tools/gulp-tasks/cldr/extract.js
getWeekendRange
function getWeekendRange(localeData) { const startDay = localeData.get(`supplemental/weekData/weekendStart/${localeData.attributes.territory}`) || localeData.get('supplemental/weekData/weekendStart/001'); const endDay = localeData.get(`supplemental/weekData/weekendEnd/${localeData.attributes.territory}`) || localeData.get('supplemental/weekData/weekendEnd/001'); return [WEEK_DAYS.indexOf(startDay), WEEK_DAYS.indexOf(endDay)]; }
javascript
function getWeekendRange(localeData) { const startDay = localeData.get(`supplemental/weekData/weekendStart/${localeData.attributes.territory}`) || localeData.get('supplemental/weekData/weekendStart/001'); const endDay = localeData.get(`supplemental/weekData/weekendEnd/${localeData.attributes.territory}`) || localeData.get('supplemental/weekData/weekendEnd/001'); return [WEEK_DAYS.indexOf(startDay), WEEK_DAYS.indexOf(endDay)]; }
[ "function", "getWeekendRange", "(", "localeData", ")", "{", "const", "startDay", "=", "localeData", ".", "get", "(", "`", "${", "localeData", ".", "attributes", ".", "territory", "}", "`", ")", "||", "localeData", ".", "get", "(", "'supplemental/weekData/weekendStart/001'", ")", ";", "const", "endDay", "=", "localeData", ".", "get", "(", "`", "${", "localeData", ".", "attributes", ".", "territory", "}", "`", ")", "||", "localeData", ".", "get", "(", "'supplemental/weekData/weekendEnd/001'", ")", ";", "return", "[", "WEEK_DAYS", ".", "indexOf", "(", "startDay", ")", ",", "WEEK_DAYS", ".", "indexOf", "(", "endDay", ")", "]", ";", "}" ]
Returns week-end range for a locale, based on US week days @returns [number, number]
[ "Returns", "week", "-", "end", "range", "for", "a", "locale", "based", "on", "US", "week", "days" ]
c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c
https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L402-L410
train
angular/angular
tools/gulp-tasks/cldr/extract.js
getNumberSettings
function getNumberSettings(localeData) { const decimalFormat = localeData.main('numbers/decimalFormats-numberSystem-latn/standard'); const percentFormat = localeData.main('numbers/percentFormats-numberSystem-latn/standard'); const scientificFormat = localeData.main('numbers/scientificFormats-numberSystem-latn/standard'); const currencyFormat = localeData.main('numbers/currencyFormats-numberSystem-latn/standard'); const symbols = localeData.main('numbers/symbols-numberSystem-latn'); const symbolValues = [ symbols.decimal, symbols.group, symbols.list, symbols.percentSign, symbols.plusSign, symbols.minusSign, symbols.exponential, symbols.superscriptingExponent, symbols.perMille, symbols.infinity, symbols.nan, symbols.timeSeparator, ]; if (symbols.currencyDecimal || symbols.currencyGroup) { symbolValues.push(symbols.currencyDecimal); } if (symbols.currencyGroup) { symbolValues.push(symbols.currencyGroup); } return [ symbolValues, [decimalFormat, percentFormat, currencyFormat, scientificFormat] ]; }
javascript
function getNumberSettings(localeData) { const decimalFormat = localeData.main('numbers/decimalFormats-numberSystem-latn/standard'); const percentFormat = localeData.main('numbers/percentFormats-numberSystem-latn/standard'); const scientificFormat = localeData.main('numbers/scientificFormats-numberSystem-latn/standard'); const currencyFormat = localeData.main('numbers/currencyFormats-numberSystem-latn/standard'); const symbols = localeData.main('numbers/symbols-numberSystem-latn'); const symbolValues = [ symbols.decimal, symbols.group, symbols.list, symbols.percentSign, symbols.plusSign, symbols.minusSign, symbols.exponential, symbols.superscriptingExponent, symbols.perMille, symbols.infinity, symbols.nan, symbols.timeSeparator, ]; if (symbols.currencyDecimal || symbols.currencyGroup) { symbolValues.push(symbols.currencyDecimal); } if (symbols.currencyGroup) { symbolValues.push(symbols.currencyGroup); } return [ symbolValues, [decimalFormat, percentFormat, currencyFormat, scientificFormat] ]; }
[ "function", "getNumberSettings", "(", "localeData", ")", "{", "const", "decimalFormat", "=", "localeData", ".", "main", "(", "'numbers/decimalFormats-numberSystem-latn/standard'", ")", ";", "const", "percentFormat", "=", "localeData", ".", "main", "(", "'numbers/percentFormats-numberSystem-latn/standard'", ")", ";", "const", "scientificFormat", "=", "localeData", ".", "main", "(", "'numbers/scientificFormats-numberSystem-latn/standard'", ")", ";", "const", "currencyFormat", "=", "localeData", ".", "main", "(", "'numbers/currencyFormats-numberSystem-latn/standard'", ")", ";", "const", "symbols", "=", "localeData", ".", "main", "(", "'numbers/symbols-numberSystem-latn'", ")", ";", "const", "symbolValues", "=", "[", "symbols", ".", "decimal", ",", "symbols", ".", "group", ",", "symbols", ".", "list", ",", "symbols", ".", "percentSign", ",", "symbols", ".", "plusSign", ",", "symbols", ".", "minusSign", ",", "symbols", ".", "exponential", ",", "symbols", ".", "superscriptingExponent", ",", "symbols", ".", "perMille", ",", "symbols", ".", "infinity", ",", "symbols", ".", "nan", ",", "symbols", ".", "timeSeparator", ",", "]", ";", "if", "(", "symbols", ".", "currencyDecimal", "||", "symbols", ".", "currencyGroup", ")", "{", "symbolValues", ".", "push", "(", "symbols", ".", "currencyDecimal", ")", ";", "}", "if", "(", "symbols", ".", "currencyGroup", ")", "{", "symbolValues", ".", "push", "(", "symbols", ".", "currencyGroup", ")", ";", "}", "return", "[", "symbolValues", ",", "[", "decimalFormat", ",", "percentFormat", ",", "currencyFormat", ",", "scientificFormat", "]", "]", ";", "}" ]
Returns the number symbols and formats for a locale @returns [ symbols, formats ] symbols: [ decimal, group, list, percentSign, plusSign, minusSign, exponential, superscriptingExponent, perMille, infinity, nan, timeSeparator, currencyDecimal?, currencyGroup? ] formats: [ currency, decimal, percent, scientific ]
[ "Returns", "the", "number", "symbols", "and", "formats", "for", "a", "locale" ]
c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c
https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L426-L459
train
angular/angular
tools/gulp-tasks/cldr/extract.js
getCurrencySettings
function getCurrencySettings(locale, localeData) { const currencyInfo = localeData.main(`numbers/currencies`); let currentCurrency = ''; // find the currency currently used in this country const currencies = localeData.get(`supplemental/currencyData/region/${localeData.attributes.territory}`) || localeData.get(`supplemental/currencyData/region/${localeData.attributes.language.toUpperCase()}`); if (currencies) { currencies.some(currency => { const keys = Object.keys(currency); return keys.some(key => { if (currency[key]._from && !currency[key]._to) { return currentCurrency = key; } }); }); if (!currentCurrency) { throw new Error(`Unable to find currency for locale "${locale}"`); } } let currencySettings = [undefined, undefined]; if (currentCurrency) { currencySettings = [currencyInfo[currentCurrency].symbol, currencyInfo[currentCurrency].displayName]; } return currencySettings; }
javascript
function getCurrencySettings(locale, localeData) { const currencyInfo = localeData.main(`numbers/currencies`); let currentCurrency = ''; // find the currency currently used in this country const currencies = localeData.get(`supplemental/currencyData/region/${localeData.attributes.territory}`) || localeData.get(`supplemental/currencyData/region/${localeData.attributes.language.toUpperCase()}`); if (currencies) { currencies.some(currency => { const keys = Object.keys(currency); return keys.some(key => { if (currency[key]._from && !currency[key]._to) { return currentCurrency = key; } }); }); if (!currentCurrency) { throw new Error(`Unable to find currency for locale "${locale}"`); } } let currencySettings = [undefined, undefined]; if (currentCurrency) { currencySettings = [currencyInfo[currentCurrency].symbol, currencyInfo[currentCurrency].displayName]; } return currencySettings; }
[ "function", "getCurrencySettings", "(", "locale", ",", "localeData", ")", "{", "const", "currencyInfo", "=", "localeData", ".", "main", "(", "`", "`", ")", ";", "let", "currentCurrency", "=", "''", ";", "const", "currencies", "=", "localeData", ".", "get", "(", "`", "${", "localeData", ".", "attributes", ".", "territory", "}", "`", ")", "||", "localeData", ".", "get", "(", "`", "${", "localeData", ".", "attributes", ".", "language", ".", "toUpperCase", "(", ")", "}", "`", ")", ";", "if", "(", "currencies", ")", "{", "currencies", ".", "some", "(", "currency", "=>", "{", "const", "keys", "=", "Object", ".", "keys", "(", "currency", ")", ";", "return", "keys", ".", "some", "(", "key", "=>", "{", "if", "(", "currency", "[", "key", "]", ".", "_from", "&&", "!", "currency", "[", "key", "]", ".", "_to", ")", "{", "return", "currentCurrency", "=", "key", ";", "}", "}", ")", ";", "}", ")", ";", "if", "(", "!", "currentCurrency", ")", "{", "throw", "new", "Error", "(", "`", "${", "locale", "}", "`", ")", ";", "}", "}", "let", "currencySettings", "=", "[", "undefined", ",", "undefined", "]", ";", "if", "(", "currentCurrency", ")", "{", "currencySettings", "=", "[", "currencyInfo", "[", "currentCurrency", "]", ".", "symbol", ",", "currencyInfo", "[", "currentCurrency", "]", ".", "displayName", "]", ";", "}", "return", "currencySettings", ";", "}" ]
Returns the currency symbol and name for a locale @returns [ symbol, name ]
[ "Returns", "the", "currency", "symbol", "and", "name", "for", "a", "locale" ]
c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c
https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L465-L496
train
angular/angular
tools/npm/check-node-modules.js
_deleteDir
function _deleteDir(path) { if (fs.existsSync(path)) { var subpaths = fs.readdirSync(path); subpaths.forEach(function(subpath) { var curPath = path + '/' + subpath; if (fs.lstatSync(curPath).isDirectory()) { _deleteDir(curPath); } else { fs.unlinkSync(curPath); } }); fs.rmdirSync(path); } }
javascript
function _deleteDir(path) { if (fs.existsSync(path)) { var subpaths = fs.readdirSync(path); subpaths.forEach(function(subpath) { var curPath = path + '/' + subpath; if (fs.lstatSync(curPath).isDirectory()) { _deleteDir(curPath); } else { fs.unlinkSync(curPath); } }); fs.rmdirSync(path); } }
[ "function", "_deleteDir", "(", "path", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "path", ")", ")", "{", "var", "subpaths", "=", "fs", ".", "readdirSync", "(", "path", ")", ";", "subpaths", ".", "forEach", "(", "function", "(", "subpath", ")", "{", "var", "curPath", "=", "path", "+", "'/'", "+", "subpath", ";", "if", "(", "fs", ".", "lstatSync", "(", "curPath", ")", ".", "isDirectory", "(", ")", ")", "{", "_deleteDir", "(", "curPath", ")", ";", "}", "else", "{", "fs", ".", "unlinkSync", "(", "curPath", ")", ";", "}", "}", ")", ";", "fs", ".", "rmdirSync", "(", "path", ")", ";", "}", "}" ]
Custom implementation of recursive `rm` because we can't rely on the state of node_modules to pull in existing module.
[ "Custom", "implementation", "of", "recursive", "rm", "because", "we", "can", "t", "rely", "on", "the", "state", "of", "node_modules", "to", "pull", "in", "existing", "module", "." ]
c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c
https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/npm/check-node-modules.js#L41-L54
train
angular/angular
tools/gulp-tasks/cldr/closure.js
generateAllLocalesFile
function generateAllLocalesFile(LOCALES, ALIASES) { const existingLocalesAliases = {}; const existingLocalesData = {}; // for each locale, get the data and the list of equivalent locales LOCALES.forEach(locale => { const eqLocales = new Set(); eqLocales.add(locale); if (locale.match(/-/)) { eqLocales.add(locale.replace(/-/g, '_')); } // check for aliases const alias = ALIASES[locale]; if (alias) { eqLocales.add(alias); if (alias.match(/-/)) { eqLocales.add(alias.replace(/-/g, '_')); } // to avoid duplicated "case" we regroup all locales in the same "case" // the simplest way to do that is to have alias aliases // e.g. 'no' --> 'nb', 'nb' --> 'no-NO' // which means that we'll have 'no', 'nb' and 'no-NO' in the same "case" const aliasKeys = Object.keys(ALIASES); for (let i = 0; i < aliasKeys.length; i++) { const aliasValue = ALIASES[alias]; if (aliasKeys.indexOf(alias) !== -1 && !eqLocales.has(aliasValue)) { eqLocales.add(aliasValue); if (aliasValue.match(/-/)) { eqLocales.add(aliasValue.replace(/-/g, '_')); } } } } for (let l of eqLocales) { // find the existing content file const path = `${RELATIVE_I18N_DATA_FOLDER}/${l}.ts`; if (fs.existsSync(`${RELATIVE_I18N_DATA_FOLDER}/${l}.ts`)) { const localeName = formatLocale(locale); existingLocalesData[locale] = fs.readFileSync(path, 'utf8') .replace(`${HEADER}\n`, '') .replace('export default ', `export const locale_${localeName} = `) .replace('function plural', `function plural_${localeName}`) .replace(/,(\n | )plural/, `, plural_${localeName}`) .replace('const u = undefined;\n\n', ''); } } existingLocalesAliases[locale] = eqLocales; }); function generateCases(locale) { let str = ''; let locales = []; const eqLocales = existingLocalesAliases[locale]; for (let l of eqLocales) { str += `case '${l}':\n`; locales.push(`'${l}'`); } let localesStr = '[' + locales.join(',') + ']'; str += ` l = locale_${formatLocale(locale)}; locales = ${localesStr}; break;\n`; return str; } function formatLocale(locale) { return locale.replace(/-/g, '_'); } // clang-format off return `${HEADER} import {registerLocaleData} from '../src/i18n/locale_data'; const u = undefined; ${LOCALES.map(locale => `${existingLocalesData[locale]}`).join('\n')} let l: any; let locales: string[] = []; switch (goog.LOCALE) { ${LOCALES.map(locale => generateCases(locale)).join('')}} if(l) { locales.forEach(locale => registerLocaleData(l, locale)); } `; // clang-format on }
javascript
function generateAllLocalesFile(LOCALES, ALIASES) { const existingLocalesAliases = {}; const existingLocalesData = {}; // for each locale, get the data and the list of equivalent locales LOCALES.forEach(locale => { const eqLocales = new Set(); eqLocales.add(locale); if (locale.match(/-/)) { eqLocales.add(locale.replace(/-/g, '_')); } // check for aliases const alias = ALIASES[locale]; if (alias) { eqLocales.add(alias); if (alias.match(/-/)) { eqLocales.add(alias.replace(/-/g, '_')); } // to avoid duplicated "case" we regroup all locales in the same "case" // the simplest way to do that is to have alias aliases // e.g. 'no' --> 'nb', 'nb' --> 'no-NO' // which means that we'll have 'no', 'nb' and 'no-NO' in the same "case" const aliasKeys = Object.keys(ALIASES); for (let i = 0; i < aliasKeys.length; i++) { const aliasValue = ALIASES[alias]; if (aliasKeys.indexOf(alias) !== -1 && !eqLocales.has(aliasValue)) { eqLocales.add(aliasValue); if (aliasValue.match(/-/)) { eqLocales.add(aliasValue.replace(/-/g, '_')); } } } } for (let l of eqLocales) { // find the existing content file const path = `${RELATIVE_I18N_DATA_FOLDER}/${l}.ts`; if (fs.existsSync(`${RELATIVE_I18N_DATA_FOLDER}/${l}.ts`)) { const localeName = formatLocale(locale); existingLocalesData[locale] = fs.readFileSync(path, 'utf8') .replace(`${HEADER}\n`, '') .replace('export default ', `export const locale_${localeName} = `) .replace('function plural', `function plural_${localeName}`) .replace(/,(\n | )plural/, `, plural_${localeName}`) .replace('const u = undefined;\n\n', ''); } } existingLocalesAliases[locale] = eqLocales; }); function generateCases(locale) { let str = ''; let locales = []; const eqLocales = existingLocalesAliases[locale]; for (let l of eqLocales) { str += `case '${l}':\n`; locales.push(`'${l}'`); } let localesStr = '[' + locales.join(',') + ']'; str += ` l = locale_${formatLocale(locale)}; locales = ${localesStr}; break;\n`; return str; } function formatLocale(locale) { return locale.replace(/-/g, '_'); } // clang-format off return `${HEADER} import {registerLocaleData} from '../src/i18n/locale_data'; const u = undefined; ${LOCALES.map(locale => `${existingLocalesData[locale]}`).join('\n')} let l: any; let locales: string[] = []; switch (goog.LOCALE) { ${LOCALES.map(locale => generateCases(locale)).join('')}} if(l) { locales.forEach(locale => registerLocaleData(l, locale)); } `; // clang-format on }
[ "function", "generateAllLocalesFile", "(", "LOCALES", ",", "ALIASES", ")", "{", "const", "existingLocalesAliases", "=", "{", "}", ";", "const", "existingLocalesData", "=", "{", "}", ";", "LOCALES", ".", "forEach", "(", "locale", "=>", "{", "const", "eqLocales", "=", "new", "Set", "(", ")", ";", "eqLocales", ".", "add", "(", "locale", ")", ";", "if", "(", "locale", ".", "match", "(", "/", "-", "/", ")", ")", "{", "eqLocales", ".", "add", "(", "locale", ".", "replace", "(", "/", "-", "/", "g", ",", "'_'", ")", ")", ";", "}", "const", "alias", "=", "ALIASES", "[", "locale", "]", ";", "if", "(", "alias", ")", "{", "eqLocales", ".", "add", "(", "alias", ")", ";", "if", "(", "alias", ".", "match", "(", "/", "-", "/", ")", ")", "{", "eqLocales", ".", "add", "(", "alias", ".", "replace", "(", "/", "-", "/", "g", ",", "'_'", ")", ")", ";", "}", "const", "aliasKeys", "=", "Object", ".", "keys", "(", "ALIASES", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "aliasKeys", ".", "length", ";", "i", "++", ")", "{", "const", "aliasValue", "=", "ALIASES", "[", "alias", "]", ";", "if", "(", "aliasKeys", ".", "indexOf", "(", "alias", ")", "!==", "-", "1", "&&", "!", "eqLocales", ".", "has", "(", "aliasValue", ")", ")", "{", "eqLocales", ".", "add", "(", "aliasValue", ")", ";", "if", "(", "aliasValue", ".", "match", "(", "/", "-", "/", ")", ")", "{", "eqLocales", ".", "add", "(", "aliasValue", ".", "replace", "(", "/", "-", "/", "g", ",", "'_'", ")", ")", ";", "}", "}", "}", "}", "for", "(", "let", "l", "of", "eqLocales", ")", "{", "const", "path", "=", "`", "${", "RELATIVE_I18N_DATA_FOLDER", "}", "${", "l", "}", "`", ";", "if", "(", "fs", ".", "existsSync", "(", "`", "${", "RELATIVE_I18N_DATA_FOLDER", "}", "${", "l", "}", "`", ")", ")", "{", "const", "localeName", "=", "formatLocale", "(", "locale", ")", ";", "existingLocalesData", "[", "locale", "]", "=", "fs", ".", "readFileSync", "(", "path", ",", "'utf8'", ")", ".", "replace", "(", "`", "${", "HEADER", "}", "\\n", "`", ",", "''", ")", ".", "replace", "(", "'export default '", ",", "`", "${", "localeName", "}", "`", ")", ".", "replace", "(", "'function plural'", ",", "`", "${", "localeName", "}", "`", ")", ".", "replace", "(", "/", ",(\\n | )plural", "/", ",", "`", "${", "localeName", "}", "`", ")", ".", "replace", "(", "'const u = undefined;\\n\\n'", ",", "\\n", ")", ";", "}", "}", "\\n", "}", ")", ";", "''", "existingLocalesAliases", "[", "locale", "]", "=", "eqLocales", ";", "function", "generateCases", "(", "locale", ")", "{", "let", "str", "=", "''", ";", "let", "locales", "=", "[", "]", ";", "const", "eqLocales", "=", "existingLocalesAliases", "[", "locale", "]", ";", "for", "(", "let", "l", "of", "eqLocales", ")", "{", "str", "+=", "`", "${", "l", "}", "\\n", "`", ";", "locales", ".", "push", "(", "`", "${", "l", "}", "`", ")", ";", "}", "let", "localesStr", "=", "'['", "+", "locales", ".", "join", "(", "','", ")", "+", "']'", ";", "str", "+=", "`", "${", "formatLocale", "(", "locale", ")", "}", "${", "localesStr", "}", "\\n", "`", ";", "return", "str", ";", "}", "}" ]
Generate a file that contains all locale to import for closure. Tree shaking will only keep the data for the `goog.LOCALE` locale.
[ "Generate", "a", "file", "that", "contains", "all", "locale", "to", "import", "for", "closure", ".", "Tree", "shaking", "will", "only", "keep", "the", "data", "for", "the", "goog", ".", "LOCALE", "locale", "." ]
c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c
https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/closure.js#L71-L163
train
angular/angular
aio/tools/transforms/remark-package/services/renderMarkdown.js
inlineTagDefs
function inlineTagDefs() { const Parser = this.Parser; const inlineTokenizers = Parser.prototype.inlineTokenizers; const inlineMethods = Parser.prototype.inlineMethods; const blockTokenizers = Parser.prototype.blockTokenizers; const blockMethods = Parser.prototype.blockMethods; blockTokenizers.inlineTag = tokenizeInlineTag; blockMethods.splice(blockMethods.indexOf('paragraph'), 0, 'inlineTag'); inlineTokenizers.inlineTag = tokenizeInlineTag; inlineMethods.splice(blockMethods.indexOf('text'), 0, 'inlineTag'); tokenizeInlineTag.notInLink = true; tokenizeInlineTag.locator = inlineTagLocator; function tokenizeInlineTag(eat, value, silent) { const match = /^\{@[^\s\}]+[^\}]*\}/.exec(value); if (match) { if (silent) { return true; } return eat(match[0])({ 'type': 'inlineTag', 'value': match[0] }); } } function inlineTagLocator(value, fromIndex) { return value.indexOf('{@', fromIndex); } }
javascript
function inlineTagDefs() { const Parser = this.Parser; const inlineTokenizers = Parser.prototype.inlineTokenizers; const inlineMethods = Parser.prototype.inlineMethods; const blockTokenizers = Parser.prototype.blockTokenizers; const blockMethods = Parser.prototype.blockMethods; blockTokenizers.inlineTag = tokenizeInlineTag; blockMethods.splice(blockMethods.indexOf('paragraph'), 0, 'inlineTag'); inlineTokenizers.inlineTag = tokenizeInlineTag; inlineMethods.splice(blockMethods.indexOf('text'), 0, 'inlineTag'); tokenizeInlineTag.notInLink = true; tokenizeInlineTag.locator = inlineTagLocator; function tokenizeInlineTag(eat, value, silent) { const match = /^\{@[^\s\}]+[^\}]*\}/.exec(value); if (match) { if (silent) { return true; } return eat(match[0])({ 'type': 'inlineTag', 'value': match[0] }); } } function inlineTagLocator(value, fromIndex) { return value.indexOf('{@', fromIndex); } }
[ "function", "inlineTagDefs", "(", ")", "{", "const", "Parser", "=", "this", ".", "Parser", ";", "const", "inlineTokenizers", "=", "Parser", ".", "prototype", ".", "inlineTokenizers", ";", "const", "inlineMethods", "=", "Parser", ".", "prototype", ".", "inlineMethods", ";", "const", "blockTokenizers", "=", "Parser", ".", "prototype", ".", "blockTokenizers", ";", "const", "blockMethods", "=", "Parser", ".", "prototype", ".", "blockMethods", ";", "blockTokenizers", ".", "inlineTag", "=", "tokenizeInlineTag", ";", "blockMethods", ".", "splice", "(", "blockMethods", ".", "indexOf", "(", "'paragraph'", ")", ",", "0", ",", "'inlineTag'", ")", ";", "inlineTokenizers", ".", "inlineTag", "=", "tokenizeInlineTag", ";", "inlineMethods", ".", "splice", "(", "blockMethods", ".", "indexOf", "(", "'text'", ")", ",", "0", ",", "'inlineTag'", ")", ";", "tokenizeInlineTag", ".", "notInLink", "=", "true", ";", "tokenizeInlineTag", ".", "locator", "=", "inlineTagLocator", ";", "function", "tokenizeInlineTag", "(", "eat", ",", "value", ",", "silent", ")", "{", "const", "match", "=", "/", "^\\{@[^\\s\\}]+[^\\}]*\\}", "/", ".", "exec", "(", "value", ")", ";", "if", "(", "match", ")", "{", "if", "(", "silent", ")", "{", "return", "true", ";", "}", "return", "eat", "(", "match", "[", "0", "]", ")", "(", "{", "'type'", ":", "'inlineTag'", ",", "'value'", ":", "match", "[", "0", "]", "}", ")", ";", "}", "}", "function", "inlineTagLocator", "(", "value", ",", "fromIndex", ")", "{", "return", "value", ".", "indexOf", "(", "'{@'", ",", "fromIndex", ")", ";", "}", "}" ]
Teach remark about inline tags, so that it neither wraps block level tags in paragraphs nor processes the text within the tag.
[ "Teach", "remark", "about", "inline", "tags", "so", "that", "it", "neither", "wraps", "block", "level", "tags", "in", "paragraphs", "nor", "processes", "the", "text", "within", "the", "tag", "." ]
c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c
https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/aio/tools/transforms/remark-package/services/renderMarkdown.js#L43-L75
train
angular/angular
aio/tools/transforms/remark-package/services/renderMarkdown.js
plainHTMLBlocks
function plainHTMLBlocks() { const plainBlocks = ['code-example', 'code-tabs']; // Create matchers for each block const anyBlockMatcher = new RegExp('^' + createOpenMatcher(`(${plainBlocks.join('|')})`)); const Parser = this.Parser; const blockTokenizers = Parser.prototype.blockTokenizers; const blockMethods = Parser.prototype.blockMethods; blockTokenizers.plainHTMLBlocks = tokenizePlainHTMLBlocks; blockMethods.splice(blockMethods.indexOf('html'), 0, 'plainHTMLBlocks'); function tokenizePlainHTMLBlocks(eat, value, silent) { const openMatch = anyBlockMatcher.exec(value); if (openMatch) { const blockName = openMatch[1]; try { const fullMatch = matchRecursiveRegExp(value, createOpenMatcher(blockName), createCloseMatcher(blockName))[0]; if (silent || !fullMatch) { // either we are not eating (silent) or the match failed return !!fullMatch; } return eat(fullMatch[0])({ type: 'html', value: fullMatch[0] }); } catch(e) { this.file.fail('Unmatched plain HTML block tag ' + e.message); } } } }
javascript
function plainHTMLBlocks() { const plainBlocks = ['code-example', 'code-tabs']; // Create matchers for each block const anyBlockMatcher = new RegExp('^' + createOpenMatcher(`(${plainBlocks.join('|')})`)); const Parser = this.Parser; const blockTokenizers = Parser.prototype.blockTokenizers; const blockMethods = Parser.prototype.blockMethods; blockTokenizers.plainHTMLBlocks = tokenizePlainHTMLBlocks; blockMethods.splice(blockMethods.indexOf('html'), 0, 'plainHTMLBlocks'); function tokenizePlainHTMLBlocks(eat, value, silent) { const openMatch = anyBlockMatcher.exec(value); if (openMatch) { const blockName = openMatch[1]; try { const fullMatch = matchRecursiveRegExp(value, createOpenMatcher(blockName), createCloseMatcher(blockName))[0]; if (silent || !fullMatch) { // either we are not eating (silent) or the match failed return !!fullMatch; } return eat(fullMatch[0])({ type: 'html', value: fullMatch[0] }); } catch(e) { this.file.fail('Unmatched plain HTML block tag ' + e.message); } } } }
[ "function", "plainHTMLBlocks", "(", ")", "{", "const", "plainBlocks", "=", "[", "'code-example'", ",", "'code-tabs'", "]", ";", "const", "anyBlockMatcher", "=", "new", "RegExp", "(", "'^'", "+", "createOpenMatcher", "(", "`", "${", "plainBlocks", ".", "join", "(", "'|'", ")", "}", "`", ")", ")", ";", "const", "Parser", "=", "this", ".", "Parser", ";", "const", "blockTokenizers", "=", "Parser", ".", "prototype", ".", "blockTokenizers", ";", "const", "blockMethods", "=", "Parser", ".", "prototype", ".", "blockMethods", ";", "blockTokenizers", ".", "plainHTMLBlocks", "=", "tokenizePlainHTMLBlocks", ";", "blockMethods", ".", "splice", "(", "blockMethods", ".", "indexOf", "(", "'html'", ")", ",", "0", ",", "'plainHTMLBlocks'", ")", ";", "function", "tokenizePlainHTMLBlocks", "(", "eat", ",", "value", ",", "silent", ")", "{", "const", "openMatch", "=", "anyBlockMatcher", ".", "exec", "(", "value", ")", ";", "if", "(", "openMatch", ")", "{", "const", "blockName", "=", "openMatch", "[", "1", "]", ";", "try", "{", "const", "fullMatch", "=", "matchRecursiveRegExp", "(", "value", ",", "createOpenMatcher", "(", "blockName", ")", ",", "createCloseMatcher", "(", "blockName", ")", ")", "[", "0", "]", ";", "if", "(", "silent", "||", "!", "fullMatch", ")", "{", "return", "!", "!", "fullMatch", ";", "}", "return", "eat", "(", "fullMatch", "[", "0", "]", ")", "(", "{", "type", ":", "'html'", ",", "value", ":", "fullMatch", "[", "0", "]", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "this", ".", "file", ".", "fail", "(", "'Unmatched plain HTML block tag '", "+", "e", ".", "message", ")", ";", "}", "}", "}", "}" ]
Teach remark that some HTML blocks never include markdown
[ "Teach", "remark", "that", "some", "HTML", "blocks", "never", "include", "markdown" ]
c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c
https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/aio/tools/transforms/remark-package/services/renderMarkdown.js#L80-L113
train
angular/angular
packages/bazel/src/protractor/protractor.conf.js
setConf
function setConf(conf, name, value, msg) { if (conf[name] && conf[name] !== value) { console.warn( `Your protractor configuration specifies an option which is overwritten by Bazel: '${name}' ${msg}`); } conf[name] = value; }
javascript
function setConf(conf, name, value, msg) { if (conf[name] && conf[name] !== value) { console.warn( `Your protractor configuration specifies an option which is overwritten by Bazel: '${name}' ${msg}`); } conf[name] = value; }
[ "function", "setConf", "(", "conf", ",", "name", ",", "value", ",", "msg", ")", "{", "if", "(", "conf", "[", "name", "]", "&&", "conf", "[", "name", "]", "!==", "value", ")", "{", "console", ".", "warn", "(", "`", "${", "name", "}", "${", "msg", "}", "`", ")", ";", "}", "conf", "[", "name", "]", "=", "value", ";", "}" ]
Helper function to warn when a user specified value is being overwritten
[ "Helper", "function", "to", "warn", "when", "a", "user", "specified", "value", "is", "being", "overwritten" ]
c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c
https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/packages/bazel/src/protractor/protractor.conf.js#L24-L30
train
angular/angular
aio/tools/examples/run-example-e2e.js
runProtractorAoT
function runProtractorAoT(appDir, outputFile) { fs.appendFileSync(outputFile, '++ AoT version ++\n'); const aotBuildSpawnInfo = spawnExt('yarn', ['build:aot'], {cwd: appDir}); let promise = aotBuildSpawnInfo.promise; const copyFileCmd = 'copy-dist-files.js'; if (fs.existsSync(appDir + '/' + copyFileCmd)) { promise = promise.then(() => spawnExt('node', [copyFileCmd], {cwd: appDir}).promise); } const aotRunSpawnInfo = spawnExt('yarn', ['serve:aot'], {cwd: appDir}, true); return runProtractorSystemJS(promise, appDir, aotRunSpawnInfo, outputFile); }
javascript
function runProtractorAoT(appDir, outputFile) { fs.appendFileSync(outputFile, '++ AoT version ++\n'); const aotBuildSpawnInfo = spawnExt('yarn', ['build:aot'], {cwd: appDir}); let promise = aotBuildSpawnInfo.promise; const copyFileCmd = 'copy-dist-files.js'; if (fs.existsSync(appDir + '/' + copyFileCmd)) { promise = promise.then(() => spawnExt('node', [copyFileCmd], {cwd: appDir}).promise); } const aotRunSpawnInfo = spawnExt('yarn', ['serve:aot'], {cwd: appDir}, true); return runProtractorSystemJS(promise, appDir, aotRunSpawnInfo, outputFile); }
[ "function", "runProtractorAoT", "(", "appDir", ",", "outputFile", ")", "{", "fs", ".", "appendFileSync", "(", "outputFile", ",", "'++ AoT version ++\\n'", ")", ";", "\\n", "const", "aotBuildSpawnInfo", "=", "spawnExt", "(", "'yarn'", ",", "[", "'build:aot'", "]", ",", "{", "cwd", ":", "appDir", "}", ")", ";", "let", "promise", "=", "aotBuildSpawnInfo", ".", "promise", ";", "const", "copyFileCmd", "=", "'copy-dist-files.js'", ";", "if", "(", "fs", ".", "existsSync", "(", "appDir", "+", "'/'", "+", "copyFileCmd", ")", ")", "{", "promise", "=", "promise", ".", "then", "(", "(", ")", "=>", "spawnExt", "(", "'node'", ",", "[", "copyFileCmd", "]", ",", "{", "cwd", ":", "appDir", "}", ")", ".", "promise", ")", ";", "}", "const", "aotRunSpawnInfo", "=", "spawnExt", "(", "'yarn'", ",", "[", "'serve:aot'", "]", ",", "{", "cwd", ":", "appDir", "}", ",", "true", ")", ";", "}" ]
Run e2e tests over the AOT build for projects that examples it.
[ "Run", "e2e", "tests", "over", "the", "AOT", "build", "for", "projects", "that", "examples", "it", "." ]
c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c
https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/aio/tools/examples/run-example-e2e.js#L223-L234
train
angular/angular
aio/tools/examples/run-example-e2e.js
loadExampleConfig
function loadExampleConfig(exampleFolder) { // Default config. let config = {build: 'build', run: 'serve:e2e'}; try { const exampleConfig = fs.readJsonSync(`${exampleFolder}/${EXAMPLE_CONFIG_FILENAME}`); Object.assign(config, exampleConfig); } catch (e) { } return config; }
javascript
function loadExampleConfig(exampleFolder) { // Default config. let config = {build: 'build', run: 'serve:e2e'}; try { const exampleConfig = fs.readJsonSync(`${exampleFolder}/${EXAMPLE_CONFIG_FILENAME}`); Object.assign(config, exampleConfig); } catch (e) { } return config; }
[ "function", "loadExampleConfig", "(", "exampleFolder", ")", "{", "let", "config", "=", "{", "build", ":", "'build'", ",", "run", ":", "'serve:e2e'", "}", ";", "try", "{", "const", "exampleConfig", "=", "fs", ".", "readJsonSync", "(", "`", "${", "exampleFolder", "}", "${", "EXAMPLE_CONFIG_FILENAME", "}", "`", ")", ";", "Object", ".", "assign", "(", "config", ",", "exampleConfig", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "return", "config", ";", "}" ]
Load configuration for an example. Used for SystemJS
[ "Load", "configuration", "for", "an", "example", ".", "Used", "for", "SystemJS" ]
c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c
https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/aio/tools/examples/run-example-e2e.js#L373-L384
train
angular/angular
aio/tools/examples/shared/protractor.config.js
formatOutput
function formatOutput(output) { var indent = ' '; var pad = ' '; var results = []; results.push('AppDir:' + output.appDir); output.suites.forEach(function(suite) { results.push(pad + 'Suite: ' + suite.description + ' -- ' + suite.status); pad+=indent; suite.specs.forEach(function(spec) { results.push(pad + spec.status + ' - ' + spec.description); if (spec.failedExpectations) { pad+=indent; spec.failedExpectations.forEach(function (fe) { results.push(pad + 'message: ' + fe.message); }); pad=pad.substr(2); } }); pad = pad.substr(2); results.push(''); }); results.push(''); return results.join('\n'); }
javascript
function formatOutput(output) { var indent = ' '; var pad = ' '; var results = []; results.push('AppDir:' + output.appDir); output.suites.forEach(function(suite) { results.push(pad + 'Suite: ' + suite.description + ' -- ' + suite.status); pad+=indent; suite.specs.forEach(function(spec) { results.push(pad + spec.status + ' - ' + spec.description); if (spec.failedExpectations) { pad+=indent; spec.failedExpectations.forEach(function (fe) { results.push(pad + 'message: ' + fe.message); }); pad=pad.substr(2); } }); pad = pad.substr(2); results.push(''); }); results.push(''); return results.join('\n'); }
[ "function", "formatOutput", "(", "output", ")", "{", "var", "indent", "=", "' '", ";", "var", "pad", "=", "' '", ";", "var", "results", "=", "[", "]", ";", "results", ".", "push", "(", "'AppDir:'", "+", "output", ".", "appDir", ")", ";", "output", ".", "suites", ".", "forEach", "(", "function", "(", "suite", ")", "{", "results", ".", "push", "(", "pad", "+", "'Suite: '", "+", "suite", ".", "description", "+", "' -- '", "+", "suite", ".", "status", ")", ";", "pad", "+=", "indent", ";", "suite", ".", "specs", ".", "forEach", "(", "function", "(", "spec", ")", "{", "results", ".", "push", "(", "pad", "+", "spec", ".", "status", "+", "' - '", "+", "spec", ".", "description", ")", ";", "if", "(", "spec", ".", "failedExpectations", ")", "{", "pad", "+=", "indent", ";", "spec", ".", "failedExpectations", ".", "forEach", "(", "function", "(", "fe", ")", "{", "results", ".", "push", "(", "pad", "+", "'message: '", "+", "fe", ".", "message", ")", ";", "}", ")", ";", "pad", "=", "pad", ".", "substr", "(", "2", ")", ";", "}", "}", ")", ";", "pad", "=", "pad", ".", "substr", "(", "2", ")", ";", "results", ".", "push", "(", "''", ")", ";", "}", ")", ";", "results", ".", "push", "(", "''", ")", ";", "return", "results", ".", "join", "(", "'\\n'", ")", ";", "}" ]
for output file output
[ "for", "output", "file", "output" ]
c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c
https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/aio/tools/examples/shared/protractor.config.js#L122-L145
train
angular/angular
tools/gulp-tasks/format.js
gulpStatus
function gulpStatus() { const Vinyl = require('vinyl'); const path = require('path'); const gulpGit = require('gulp-git'); const through = require('through2'); const srcStream = through.obj(); const opt = {cwd: process.cwd()}; // https://git-scm.com/docs/git-status#_short_format const RE_STATUS = /((\s\w)|(\w+)|\?{0,2})\s([\w\+\-\/\\\.]+)(\s->\s)?([\w\+\-\/\\\.]+)*\n{0,1}/gm; gulpGit.status({args: '--porcelain', quiet: true}, function(err, stdout) { if (err) return srcStream.emit('error', err); const data = stdout.toString(); let currentMatch; while ((currentMatch = RE_STATUS.exec(data)) !== null) { // status const status = currentMatch[1].trim().toLowerCase(); // We only care about untracked files and renamed files if (!new RegExp(/r|\?/i).test(status)) { continue; } // file path const currentFilePath = currentMatch[4]; // new file path in case its been moved const newFilePath = currentMatch[6]; const filePath = newFilePath || currentFilePath; srcStream.write(new Vinyl({ path: path.resolve(opt.cwd, filePath), cwd: opt.cwd, })); RE_STATUS.lastIndex++; } srcStream.end(); }); return srcStream; }
javascript
function gulpStatus() { const Vinyl = require('vinyl'); const path = require('path'); const gulpGit = require('gulp-git'); const through = require('through2'); const srcStream = through.obj(); const opt = {cwd: process.cwd()}; // https://git-scm.com/docs/git-status#_short_format const RE_STATUS = /((\s\w)|(\w+)|\?{0,2})\s([\w\+\-\/\\\.]+)(\s->\s)?([\w\+\-\/\\\.]+)*\n{0,1}/gm; gulpGit.status({args: '--porcelain', quiet: true}, function(err, stdout) { if (err) return srcStream.emit('error', err); const data = stdout.toString(); let currentMatch; while ((currentMatch = RE_STATUS.exec(data)) !== null) { // status const status = currentMatch[1].trim().toLowerCase(); // We only care about untracked files and renamed files if (!new RegExp(/r|\?/i).test(status)) { continue; } // file path const currentFilePath = currentMatch[4]; // new file path in case its been moved const newFilePath = currentMatch[6]; const filePath = newFilePath || currentFilePath; srcStream.write(new Vinyl({ path: path.resolve(opt.cwd, filePath), cwd: opt.cwd, })); RE_STATUS.lastIndex++; } srcStream.end(); }); return srcStream; }
[ "function", "gulpStatus", "(", ")", "{", "const", "Vinyl", "=", "require", "(", "'vinyl'", ")", ";", "const", "path", "=", "require", "(", "'path'", ")", ";", "const", "gulpGit", "=", "require", "(", "'gulp-git'", ")", ";", "const", "through", "=", "require", "(", "'through2'", ")", ";", "const", "srcStream", "=", "through", ".", "obj", "(", ")", ";", "const", "opt", "=", "{", "cwd", ":", "process", ".", "cwd", "(", ")", "}", ";", "const", "RE_STATUS", "=", "/", "((\\s\\w)|(\\w+)|\\?{0,2})\\s([\\w\\+\\-\\/\\\\\\.]+)(\\s->\\s)?([\\w\\+\\-\\/\\\\\\.]+)*\\n{0,1}", "/", "gm", ";", "gulpGit", ".", "status", "(", "{", "args", ":", "'--porcelain'", ",", "quiet", ":", "true", "}", ",", "function", "(", "err", ",", "stdout", ")", "{", "if", "(", "err", ")", "return", "srcStream", ".", "emit", "(", "'error'", ",", "err", ")", ";", "const", "data", "=", "stdout", ".", "toString", "(", ")", ";", "let", "currentMatch", ";", "while", "(", "(", "currentMatch", "=", "RE_STATUS", ".", "exec", "(", "data", ")", ")", "!==", "null", ")", "{", "const", "status", "=", "currentMatch", "[", "1", "]", ".", "trim", "(", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "!", "new", "RegExp", "(", "/", "r|\\?", "/", "i", ")", ".", "test", "(", "status", ")", ")", "{", "continue", ";", "}", "const", "currentFilePath", "=", "currentMatch", "[", "4", "]", ";", "const", "newFilePath", "=", "currentMatch", "[", "6", "]", ";", "const", "filePath", "=", "newFilePath", "||", "currentFilePath", ";", "srcStream", ".", "write", "(", "new", "Vinyl", "(", "{", "path", ":", "path", ".", "resolve", "(", "opt", ".", "cwd", ",", "filePath", ")", ",", "cwd", ":", "opt", ".", "cwd", ",", "}", ")", ")", ";", "RE_STATUS", ".", "lastIndex", "++", ";", "}", "srcStream", ".", "end", "(", ")", ";", "}", ")", ";", "return", "srcStream", ";", "}" ]
Gulp stream that wraps the gulp-git status, only returns untracked files, and converts the stdout into a stream of files.
[ "Gulp", "stream", "that", "wraps", "the", "gulp", "-", "git", "status", "only", "returns", "untracked", "files", "and", "converts", "the", "stdout", "into", "a", "stream", "of", "files", "." ]
c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c
https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/format.js#L37-L83
train
facebook/create-react-app
packages/react-scripts/config/modules.js
getAdditionalModulePaths
function getAdditionalModulePaths(options = {}) { const baseUrl = options.baseUrl; // We need to explicitly check for null and undefined (and not a falsy value) because // TypeScript treats an empty string as `.`. if (baseUrl == null) { // If there's no baseUrl set we respect NODE_PATH // Note that NODE_PATH is deprecated and will be removed // in the next major release of create-react-app. const nodePath = process.env.NODE_PATH || ''; return nodePath.split(path.delimiter).filter(Boolean); } const baseUrlResolved = path.resolve(paths.appPath, baseUrl); // We don't need to do anything if `baseUrl` is set to `node_modules`. This is // the default behavior. if (path.relative(paths.appNodeModules, baseUrlResolved) === '') { return null; } // Allow the user set the `baseUrl` to `appSrc`. if (path.relative(paths.appSrc, baseUrlResolved) === '') { return [paths.appSrc]; } // Otherwise, throw an error. throw new Error( chalk.red.bold( "Your project's `baseUrl` can only be set to `src` or `node_modules`." + ' Create React App does not support other values at this time.' ) ); }
javascript
function getAdditionalModulePaths(options = {}) { const baseUrl = options.baseUrl; // We need to explicitly check for null and undefined (and not a falsy value) because // TypeScript treats an empty string as `.`. if (baseUrl == null) { // If there's no baseUrl set we respect NODE_PATH // Note that NODE_PATH is deprecated and will be removed // in the next major release of create-react-app. const nodePath = process.env.NODE_PATH || ''; return nodePath.split(path.delimiter).filter(Boolean); } const baseUrlResolved = path.resolve(paths.appPath, baseUrl); // We don't need to do anything if `baseUrl` is set to `node_modules`. This is // the default behavior. if (path.relative(paths.appNodeModules, baseUrlResolved) === '') { return null; } // Allow the user set the `baseUrl` to `appSrc`. if (path.relative(paths.appSrc, baseUrlResolved) === '') { return [paths.appSrc]; } // Otherwise, throw an error. throw new Error( chalk.red.bold( "Your project's `baseUrl` can only be set to `src` or `node_modules`." + ' Create React App does not support other values at this time.' ) ); }
[ "function", "getAdditionalModulePaths", "(", "options", "=", "{", "}", ")", "{", "const", "baseUrl", "=", "options", ".", "baseUrl", ";", "if", "(", "baseUrl", "==", "null", ")", "{", "const", "nodePath", "=", "process", ".", "env", ".", "NODE_PATH", "||", "''", ";", "return", "nodePath", ".", "split", "(", "path", ".", "delimiter", ")", ".", "filter", "(", "Boolean", ")", ";", "}", "const", "baseUrlResolved", "=", "path", ".", "resolve", "(", "paths", ".", "appPath", ",", "baseUrl", ")", ";", "if", "(", "path", ".", "relative", "(", "paths", ".", "appNodeModules", ",", "baseUrlResolved", ")", "===", "''", ")", "{", "return", "null", ";", "}", "if", "(", "path", ".", "relative", "(", "paths", ".", "appSrc", ",", "baseUrlResolved", ")", "===", "''", ")", "{", "return", "[", "paths", ".", "appSrc", "]", ";", "}", "throw", "new", "Error", "(", "chalk", ".", "red", ".", "bold", "(", "\"Your project's `baseUrl` can only be set to `src` or `node_modules`.\"", "+", "' Create React App does not support other values at this time.'", ")", ")", ";", "}" ]
Get the baseUrl of a compilerOptions object. @param {Object} options
[ "Get", "the", "baseUrl", "of", "a", "compilerOptions", "object", "." ]
57ef103440c24e41b0d7dc82b7ad7fc1dc817eca
https://github.com/facebook/create-react-app/blob/57ef103440c24e41b0d7dc82b7ad7fc1dc817eca/packages/react-scripts/config/modules.js#L21-L55
train
facebook/create-react-app
packages/react-dev-utils/webpackHotDevClient.js
handleSuccess
function handleSuccess() { clearOutdatedErrors(); var isHotUpdate = !isFirstCompilation; isFirstCompilation = false; hasCompileErrors = false; // Attempt to apply hot updates or reload. if (isHotUpdate) { tryApplyUpdates(function onHotUpdateSuccess() { // Only dismiss it when we're sure it's a hot update. // Otherwise it would flicker right before the reload. tryDismissErrorOverlay(); }); } }
javascript
function handleSuccess() { clearOutdatedErrors(); var isHotUpdate = !isFirstCompilation; isFirstCompilation = false; hasCompileErrors = false; // Attempt to apply hot updates or reload. if (isHotUpdate) { tryApplyUpdates(function onHotUpdateSuccess() { // Only dismiss it when we're sure it's a hot update. // Otherwise it would flicker right before the reload. tryDismissErrorOverlay(); }); } }
[ "function", "handleSuccess", "(", ")", "{", "clearOutdatedErrors", "(", ")", ";", "var", "isHotUpdate", "=", "!", "isFirstCompilation", ";", "isFirstCompilation", "=", "false", ";", "hasCompileErrors", "=", "false", ";", "if", "(", "isHotUpdate", ")", "{", "tryApplyUpdates", "(", "function", "onHotUpdateSuccess", "(", ")", "{", "tryDismissErrorOverlay", "(", ")", ";", "}", ")", ";", "}", "}" ]
Successful compilation.
[ "Successful", "compilation", "." ]
57ef103440c24e41b0d7dc82b7ad7fc1dc817eca
https://github.com/facebook/create-react-app/blob/57ef103440c24e41b0d7dc82b7ad7fc1dc817eca/packages/react-dev-utils/webpackHotDevClient.js#L97-L112
train
facebook/create-react-app
packages/react-dev-utils/FileSizeReporter.js
printFileSizesAfterBuild
function printFileSizesAfterBuild( webpackStats, previousSizeMap, buildFolder, maxBundleGzipSize, maxChunkGzipSize ) { var root = previousSizeMap.root; var sizes = previousSizeMap.sizes; var assets = (webpackStats.stats || [webpackStats]) .map(stats => stats .toJson({ all: false, assets: true }) .assets.filter(asset => canReadAsset(asset.name)) .map(asset => { var fileContents = fs.readFileSync(path.join(root, asset.name)); var size = gzipSize(fileContents); var previousSize = sizes[removeFileNameHash(root, asset.name)]; var difference = getDifferenceLabel(size, previousSize); return { folder: path.join( path.basename(buildFolder), path.dirname(asset.name) ), name: path.basename(asset.name), size: size, sizeLabel: filesize(size) + (difference ? ' (' + difference + ')' : ''), }; }) ) .reduce((single, all) => all.concat(single), []); assets.sort((a, b) => b.size - a.size); var longestSizeLabelLength = Math.max.apply( null, assets.map(a => stripAnsi(a.sizeLabel).length) ); var suggestBundleSplitting = false; assets.forEach(asset => { var sizeLabel = asset.sizeLabel; var sizeLength = stripAnsi(sizeLabel).length; if (sizeLength < longestSizeLabelLength) { var rightPadding = ' '.repeat(longestSizeLabelLength - sizeLength); sizeLabel += rightPadding; } var isMainBundle = asset.name.indexOf('main.') === 0; var maxRecommendedSize = isMainBundle ? maxBundleGzipSize : maxChunkGzipSize; var isLarge = maxRecommendedSize && asset.size > maxRecommendedSize; if (isLarge && path.extname(asset.name) === '.js') { suggestBundleSplitting = true; } console.log( ' ' + (isLarge ? chalk.yellow(sizeLabel) : sizeLabel) + ' ' + chalk.dim(asset.folder + path.sep) + chalk.cyan(asset.name) ); }); if (suggestBundleSplitting) { console.log(); console.log( chalk.yellow('The bundle size is significantly larger than recommended.') ); console.log( chalk.yellow( 'Consider reducing it with code splitting: https://goo.gl/9VhYWB' ) ); console.log( chalk.yellow( 'You can also analyze the project dependencies: https://goo.gl/LeUzfb' ) ); } }
javascript
function printFileSizesAfterBuild( webpackStats, previousSizeMap, buildFolder, maxBundleGzipSize, maxChunkGzipSize ) { var root = previousSizeMap.root; var sizes = previousSizeMap.sizes; var assets = (webpackStats.stats || [webpackStats]) .map(stats => stats .toJson({ all: false, assets: true }) .assets.filter(asset => canReadAsset(asset.name)) .map(asset => { var fileContents = fs.readFileSync(path.join(root, asset.name)); var size = gzipSize(fileContents); var previousSize = sizes[removeFileNameHash(root, asset.name)]; var difference = getDifferenceLabel(size, previousSize); return { folder: path.join( path.basename(buildFolder), path.dirname(asset.name) ), name: path.basename(asset.name), size: size, sizeLabel: filesize(size) + (difference ? ' (' + difference + ')' : ''), }; }) ) .reduce((single, all) => all.concat(single), []); assets.sort((a, b) => b.size - a.size); var longestSizeLabelLength = Math.max.apply( null, assets.map(a => stripAnsi(a.sizeLabel).length) ); var suggestBundleSplitting = false; assets.forEach(asset => { var sizeLabel = asset.sizeLabel; var sizeLength = stripAnsi(sizeLabel).length; if (sizeLength < longestSizeLabelLength) { var rightPadding = ' '.repeat(longestSizeLabelLength - sizeLength); sizeLabel += rightPadding; } var isMainBundle = asset.name.indexOf('main.') === 0; var maxRecommendedSize = isMainBundle ? maxBundleGzipSize : maxChunkGzipSize; var isLarge = maxRecommendedSize && asset.size > maxRecommendedSize; if (isLarge && path.extname(asset.name) === '.js') { suggestBundleSplitting = true; } console.log( ' ' + (isLarge ? chalk.yellow(sizeLabel) : sizeLabel) + ' ' + chalk.dim(asset.folder + path.sep) + chalk.cyan(asset.name) ); }); if (suggestBundleSplitting) { console.log(); console.log( chalk.yellow('The bundle size is significantly larger than recommended.') ); console.log( chalk.yellow( 'Consider reducing it with code splitting: https://goo.gl/9VhYWB' ) ); console.log( chalk.yellow( 'You can also analyze the project dependencies: https://goo.gl/LeUzfb' ) ); } }
[ "function", "printFileSizesAfterBuild", "(", "webpackStats", ",", "previousSizeMap", ",", "buildFolder", ",", "maxBundleGzipSize", ",", "maxChunkGzipSize", ")", "{", "var", "root", "=", "previousSizeMap", ".", "root", ";", "var", "sizes", "=", "previousSizeMap", ".", "sizes", ";", "var", "assets", "=", "(", "webpackStats", ".", "stats", "||", "[", "webpackStats", "]", ")", ".", "map", "(", "stats", "=>", "stats", ".", "toJson", "(", "{", "all", ":", "false", ",", "assets", ":", "true", "}", ")", ".", "assets", ".", "filter", "(", "asset", "=>", "canReadAsset", "(", "asset", ".", "name", ")", ")", ".", "map", "(", "asset", "=>", "{", "var", "fileContents", "=", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "root", ",", "asset", ".", "name", ")", ")", ";", "var", "size", "=", "gzipSize", "(", "fileContents", ")", ";", "var", "previousSize", "=", "sizes", "[", "removeFileNameHash", "(", "root", ",", "asset", ".", "name", ")", "]", ";", "var", "difference", "=", "getDifferenceLabel", "(", "size", ",", "previousSize", ")", ";", "return", "{", "folder", ":", "path", ".", "join", "(", "path", ".", "basename", "(", "buildFolder", ")", ",", "path", ".", "dirname", "(", "asset", ".", "name", ")", ")", ",", "name", ":", "path", ".", "basename", "(", "asset", ".", "name", ")", ",", "size", ":", "size", ",", "sizeLabel", ":", "filesize", "(", "size", ")", "+", "(", "difference", "?", "' ('", "+", "difference", "+", "')'", ":", "''", ")", ",", "}", ";", "}", ")", ")", ".", "reduce", "(", "(", "single", ",", "all", ")", "=>", "all", ".", "concat", "(", "single", ")", ",", "[", "]", ")", ";", "assets", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "b", ".", "size", "-", "a", ".", "size", ")", ";", "var", "longestSizeLabelLength", "=", "Math", ".", "max", ".", "apply", "(", "null", ",", "assets", ".", "map", "(", "a", "=>", "stripAnsi", "(", "a", ".", "sizeLabel", ")", ".", "length", ")", ")", ";", "var", "suggestBundleSplitting", "=", "false", ";", "assets", ".", "forEach", "(", "asset", "=>", "{", "var", "sizeLabel", "=", "asset", ".", "sizeLabel", ";", "var", "sizeLength", "=", "stripAnsi", "(", "sizeLabel", ")", ".", "length", ";", "if", "(", "sizeLength", "<", "longestSizeLabelLength", ")", "{", "var", "rightPadding", "=", "' '", ".", "repeat", "(", "longestSizeLabelLength", "-", "sizeLength", ")", ";", "sizeLabel", "+=", "rightPadding", ";", "}", "var", "isMainBundle", "=", "asset", ".", "name", ".", "indexOf", "(", "'main.'", ")", "===", "0", ";", "var", "maxRecommendedSize", "=", "isMainBundle", "?", "maxBundleGzipSize", ":", "maxChunkGzipSize", ";", "var", "isLarge", "=", "maxRecommendedSize", "&&", "asset", ".", "size", ">", "maxRecommendedSize", ";", "if", "(", "isLarge", "&&", "path", ".", "extname", "(", "asset", ".", "name", ")", "===", "'.js'", ")", "{", "suggestBundleSplitting", "=", "true", ";", "}", "console", ".", "log", "(", "' '", "+", "(", "isLarge", "?", "chalk", ".", "yellow", "(", "sizeLabel", ")", ":", "sizeLabel", ")", "+", "' '", "+", "chalk", ".", "dim", "(", "asset", ".", "folder", "+", "path", ".", "sep", ")", "+", "chalk", ".", "cyan", "(", "asset", ".", "name", ")", ")", ";", "}", ")", ";", "if", "(", "suggestBundleSplitting", ")", "{", "console", ".", "log", "(", ")", ";", "console", ".", "log", "(", "chalk", ".", "yellow", "(", "'The bundle size is significantly larger than recommended.'", ")", ")", ";", "console", ".", "log", "(", "chalk", ".", "yellow", "(", "'Consider reducing it with code splitting: https://goo.gl/9VhYWB'", ")", ")", ";", "console", ".", "log", "(", "chalk", ".", "yellow", "(", "'You can also analyze the project dependencies: https://goo.gl/LeUzfb'", ")", ")", ";", "}", "}" ]
Prints a detailed summary of build files.
[ "Prints", "a", "detailed", "summary", "of", "build", "files", "." ]
57ef103440c24e41b0d7dc82b7ad7fc1dc817eca
https://github.com/facebook/create-react-app/blob/57ef103440c24e41b0d7dc82b7ad7fc1dc817eca/packages/react-dev-utils/FileSizeReporter.js#L27-L104
train
facebook/create-react-app
packages/react-dev-utils/openBrowser.js
openBrowser
function openBrowser(url) { const { action, value } = getBrowserEnv(); switch (action) { case Actions.NONE: // Special case: BROWSER="none" will prevent opening completely. return false; case Actions.SCRIPT: return executeNodeScript(value, url); case Actions.BROWSER: return startBrowserProcess(value, url); default: throw new Error('Not implemented.'); } }
javascript
function openBrowser(url) { const { action, value } = getBrowserEnv(); switch (action) { case Actions.NONE: // Special case: BROWSER="none" will prevent opening completely. return false; case Actions.SCRIPT: return executeNodeScript(value, url); case Actions.BROWSER: return startBrowserProcess(value, url); default: throw new Error('Not implemented.'); } }
[ "function", "openBrowser", "(", "url", ")", "{", "const", "{", "action", ",", "value", "}", "=", "getBrowserEnv", "(", ")", ";", "switch", "(", "action", ")", "{", "case", "Actions", ".", "NONE", ":", "return", "false", ";", "case", "Actions", ".", "SCRIPT", ":", "return", "executeNodeScript", "(", "value", ",", "url", ")", ";", "case", "Actions", ".", "BROWSER", ":", "return", "startBrowserProcess", "(", "value", ",", "url", ")", ";", "default", ":", "throw", "new", "Error", "(", "'Not implemented.'", ")", ";", "}", "}" ]
Reads the BROWSER environment variable and decides what to do with it. Returns true if it opened a browser or ran a node.js script, otherwise false.
[ "Reads", "the", "BROWSER", "environment", "variable", "and", "decides", "what", "to", "do", "with", "it", ".", "Returns", "true", "if", "it", "opened", "a", "browser", "or", "ran", "a", "node", ".", "js", "script", "otherwise", "false", "." ]
57ef103440c24e41b0d7dc82b7ad7fc1dc817eca
https://github.com/facebook/create-react-app/blob/57ef103440c24e41b0d7dc82b7ad7fc1dc817eca/packages/react-dev-utils/openBrowser.js#L111-L124
train
facebook/create-react-app
packages/react-dev-utils/WebpackDevServerUtils.js
onProxyError
function onProxyError(proxy) { return (err, req, res) => { const host = req.headers && req.headers.host; console.log( chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) + ' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.' ); console.log( 'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' + chalk.cyan(err.code) + ').' ); console.log(); // And immediately send the proper error response to the client. // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side. if (res.writeHead && !res.headersSent) { res.writeHead(500); } res.end( 'Proxy error: Could not proxy request ' + req.url + ' from ' + host + ' to ' + proxy + ' (' + err.code + ').' ); }; }
javascript
function onProxyError(proxy) { return (err, req, res) => { const host = req.headers && req.headers.host; console.log( chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) + ' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.' ); console.log( 'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' + chalk.cyan(err.code) + ').' ); console.log(); // And immediately send the proper error response to the client. // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side. if (res.writeHead && !res.headersSent) { res.writeHead(500); } res.end( 'Proxy error: Could not proxy request ' + req.url + ' from ' + host + ' to ' + proxy + ' (' + err.code + ').' ); }; }
[ "function", "onProxyError", "(", "proxy", ")", "{", "return", "(", "err", ",", "req", ",", "res", ")", "=>", "{", "const", "host", "=", "req", ".", "headers", "&&", "req", ".", "headers", ".", "host", ";", "console", ".", "log", "(", "chalk", ".", "red", "(", "'Proxy error:'", ")", "+", "' Could not proxy request '", "+", "chalk", ".", "cyan", "(", "req", ".", "url", ")", "+", "' from '", "+", "chalk", ".", "cyan", "(", "host", ")", "+", "' to '", "+", "chalk", ".", "cyan", "(", "proxy", ")", "+", "'.'", ")", ";", "console", ".", "log", "(", "'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information ('", "+", "chalk", ".", "cyan", "(", "err", ".", "code", ")", "+", "').'", ")", ";", "console", ".", "log", "(", ")", ";", "if", "(", "res", ".", "writeHead", "&&", "!", "res", ".", "headersSent", ")", "{", "res", ".", "writeHead", "(", "500", ")", ";", "}", "res", ".", "end", "(", "'Proxy error: Could not proxy request '", "+", "req", ".", "url", "+", "' from '", "+", "host", "+", "' to '", "+", "proxy", "+", "' ('", "+", "err", ".", "code", "+", "').'", ")", ";", "}", ";", "}" ]
We need to provide a custom onError function for httpProxyMiddleware. It allows us to log custom error messages on the console.
[ "We", "need", "to", "provide", "a", "custom", "onError", "function", "for", "httpProxyMiddleware", ".", "It", "allows", "us", "to", "log", "custom", "error", "messages", "on", "the", "console", "." ]
57ef103440c24e41b0d7dc82b7ad7fc1dc817eca
https://github.com/facebook/create-react-app/blob/57ef103440c24e41b0d7dc82b7ad7fc1dc817eca/packages/react-dev-utils/WebpackDevServerUtils.js#L307-L344
train
ant-design/ant-design
.antd-tools.config.js
finalizeCompile
function finalizeCompile() { if (fs.existsSync(path.join(__dirname, './lib'))) { // Build package.json version to lib/version/index.js // prevent json-loader needing in user-side const versionFilePath = path.join(process.cwd(), 'lib', 'version', 'index.js'); const versionFileContent = fs.readFileSync(versionFilePath).toString(); fs.writeFileSync( versionFilePath, versionFileContent.replace( /require\(('|")\.\.\/\.\.\/package\.json('|")\)/, `{ version: '${packageInfo.version}' }`, ), ); // eslint-disable-next-line console.log('Wrote version into lib/version/index.js'); // Build package.json version to lib/version/index.d.ts // prevent https://github.com/ant-design/ant-design/issues/4935 const versionDefPath = path.join(process.cwd(), 'lib', 'version', 'index.d.ts'); fs.writeFileSync( versionDefPath, `declare var _default: "${packageInfo.version}";\nexport default _default;\n`, ); // eslint-disable-next-line console.log('Wrote version into lib/version/index.d.ts'); // Build a entry less file to dist/antd.less const componentsPath = path.join(process.cwd(), 'components'); let componentsLessContent = ''; // Build components in one file: lib/style/components.less fs.readdir(componentsPath, (err, files) => { files.forEach(file => { if (fs.existsSync(path.join(componentsPath, file, 'style', 'index.less'))) { componentsLessContent += `@import "../${path.join(file, 'style', 'index.less')}";\n`; } }); fs.writeFileSync( path.join(process.cwd(), 'lib', 'style', 'components.less'), componentsLessContent, ); }); } }
javascript
function finalizeCompile() { if (fs.existsSync(path.join(__dirname, './lib'))) { // Build package.json version to lib/version/index.js // prevent json-loader needing in user-side const versionFilePath = path.join(process.cwd(), 'lib', 'version', 'index.js'); const versionFileContent = fs.readFileSync(versionFilePath).toString(); fs.writeFileSync( versionFilePath, versionFileContent.replace( /require\(('|")\.\.\/\.\.\/package\.json('|")\)/, `{ version: '${packageInfo.version}' }`, ), ); // eslint-disable-next-line console.log('Wrote version into lib/version/index.js'); // Build package.json version to lib/version/index.d.ts // prevent https://github.com/ant-design/ant-design/issues/4935 const versionDefPath = path.join(process.cwd(), 'lib', 'version', 'index.d.ts'); fs.writeFileSync( versionDefPath, `declare var _default: "${packageInfo.version}";\nexport default _default;\n`, ); // eslint-disable-next-line console.log('Wrote version into lib/version/index.d.ts'); // Build a entry less file to dist/antd.less const componentsPath = path.join(process.cwd(), 'components'); let componentsLessContent = ''; // Build components in one file: lib/style/components.less fs.readdir(componentsPath, (err, files) => { files.forEach(file => { if (fs.existsSync(path.join(componentsPath, file, 'style', 'index.less'))) { componentsLessContent += `@import "../${path.join(file, 'style', 'index.less')}";\n`; } }); fs.writeFileSync( path.join(process.cwd(), 'lib', 'style', 'components.less'), componentsLessContent, ); }); } }
[ "function", "finalizeCompile", "(", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "path", ".", "join", "(", "__dirname", ",", "'./lib'", ")", ")", ")", "{", "const", "versionFilePath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'lib'", ",", "'version'", ",", "'index.js'", ")", ";", "const", "versionFileContent", "=", "fs", ".", "readFileSync", "(", "versionFilePath", ")", ".", "toString", "(", ")", ";", "fs", ".", "writeFileSync", "(", "versionFilePath", ",", "versionFileContent", ".", "replace", "(", "/", "require\\(('|\")\\.\\.\\/\\.\\.\\/package\\.json('|\")\\)", "/", ",", "`", "${", "packageInfo", ".", "version", "}", "`", ",", ")", ",", ")", ";", "console", ".", "log", "(", "'Wrote version into lib/version/index.js'", ")", ";", "const", "versionDefPath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'lib'", ",", "'version'", ",", "'index.d.ts'", ")", ";", "fs", ".", "writeFileSync", "(", "versionDefPath", ",", "`", "${", "packageInfo", ".", "version", "}", "\\n", "\\n", "`", ",", ")", ";", "console", ".", "log", "(", "'Wrote version into lib/version/index.d.ts'", ")", ";", "const", "componentsPath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'components'", ")", ";", "let", "componentsLessContent", "=", "''", ";", "fs", ".", "readdir", "(", "componentsPath", ",", "(", "err", ",", "files", ")", "=>", "{", "files", ".", "forEach", "(", "file", "=>", "{", "if", "(", "fs", ".", "existsSync", "(", "path", ".", "join", "(", "componentsPath", ",", "file", ",", "'style'", ",", "'index.less'", ")", ")", ")", "{", "componentsLessContent", "+=", "`", "${", "path", ".", "join", "(", "file", ",", "'style'", ",", "'index.less'", ")", "}", "\\n", "`", ";", "}", "}", ")", ";", "fs", ".", "writeFileSync", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'lib'", ",", "'style'", ",", "'components.less'", ")", ",", "componentsLessContent", ",", ")", ";", "}", ")", ";", "}", "}" ]
We need compile additional content for antd user
[ "We", "need", "compile", "additional", "content", "for", "antd", "user" ]
6d845f60efe9bd50a25c0ce29eb1fee895b9c7b7
https://github.com/ant-design/ant-design/blob/6d845f60efe9bd50a25c0ce29eb1fee895b9c7b7/.antd-tools.config.js#L6-L48
train
30-seconds/30-seconds-of-code
scripts/module.js
build
async function build() { console.time('Packager'); let requires = []; let esmExportString = ''; let cjsExportString = ''; try { if (!fs.existsSync(DIST_PATH)) fs.mkdirSync(DIST_PATH); fs.writeFileSync(ROLLUP_INPUT_FILE, ''); fs.writeFileSync(TEST_MODULE_FILE, ''); // All the snippets that are Node.js-based and will break in a browser // environment const nodeSnippets = fs .readFileSync('tag_database', 'utf8') .split('\n') .filter(v => v.search(/:.*node/g) !== -1) .map(v => v.slice(0, v.indexOf(':'))); const snippets = fs.readdirSync(SNIPPETS_PATH); const archivedSnippets = fs .readdirSync(SNIPPETS_ARCHIVE_PATH) .filter(v => v !== 'README.md'); snippets.forEach(snippet => { const rawSnippetString = getRawSnippetString(SNIPPETS_PATH, snippet); const snippetName = snippet.replace('.md', ''); let code = getCode(rawSnippetString); if (nodeSnippets.includes(snippetName)) { requires.push(code.match(/const.*=.*require\(([^\)]*)\);/g)); code = code.replace(/const.*=.*require\(([^\)]*)\);/g, ''); } esmExportString += `export ${code}`; cjsExportString += code; }); archivedSnippets.forEach(snippet => { const rawSnippetString = getRawSnippetString( SNIPPETS_ARCHIVE_PATH, snippet ); cjsExportString += getCode(rawSnippetString); }); requires = [ ...new Set( requires .filter(Boolean) .map(v => v[0].replace( 'require(', 'typeof require !== "undefined" && require(' ) ) ) ].join('\n'); fs.writeFileSync(ROLLUP_INPUT_FILE, `${requires}\n\n${esmExportString}`); const testExports = `module.exports = {${[...snippets, ...archivedSnippets] .map(v => v.replace('.md', '')) .join(',')}}`; fs.writeFileSync( TEST_MODULE_FILE, `${requires}\n\n${cjsExportString}\n\n${testExports}` ); // Check Travis builds - Will skip builds on Travis if not CRON/API if (util.isTravisCI() && util.isNotTravisCronOrAPI()) { fs.unlink(ROLLUP_INPUT_FILE); console.log( `${chalk.green( 'NOBUILD' )} Module build terminated, not a cron job or a custom build!` ); console.timeEnd('Packager'); process.exit(0); } await doRollup(); // Clean up the temporary input file Rollup used for building the module fs.unlink(ROLLUP_INPUT_FILE); console.log(`${chalk.green('SUCCESS!')} Snippet module built!`); console.timeEnd('Packager'); } catch (err) { console.log(`${chalk.red('ERROR!')} During module creation: ${err}`); process.exit(1); } }
javascript
async function build() { console.time('Packager'); let requires = []; let esmExportString = ''; let cjsExportString = ''; try { if (!fs.existsSync(DIST_PATH)) fs.mkdirSync(DIST_PATH); fs.writeFileSync(ROLLUP_INPUT_FILE, ''); fs.writeFileSync(TEST_MODULE_FILE, ''); // All the snippets that are Node.js-based and will break in a browser // environment const nodeSnippets = fs .readFileSync('tag_database', 'utf8') .split('\n') .filter(v => v.search(/:.*node/g) !== -1) .map(v => v.slice(0, v.indexOf(':'))); const snippets = fs.readdirSync(SNIPPETS_PATH); const archivedSnippets = fs .readdirSync(SNIPPETS_ARCHIVE_PATH) .filter(v => v !== 'README.md'); snippets.forEach(snippet => { const rawSnippetString = getRawSnippetString(SNIPPETS_PATH, snippet); const snippetName = snippet.replace('.md', ''); let code = getCode(rawSnippetString); if (nodeSnippets.includes(snippetName)) { requires.push(code.match(/const.*=.*require\(([^\)]*)\);/g)); code = code.replace(/const.*=.*require\(([^\)]*)\);/g, ''); } esmExportString += `export ${code}`; cjsExportString += code; }); archivedSnippets.forEach(snippet => { const rawSnippetString = getRawSnippetString( SNIPPETS_ARCHIVE_PATH, snippet ); cjsExportString += getCode(rawSnippetString); }); requires = [ ...new Set( requires .filter(Boolean) .map(v => v[0].replace( 'require(', 'typeof require !== "undefined" && require(' ) ) ) ].join('\n'); fs.writeFileSync(ROLLUP_INPUT_FILE, `${requires}\n\n${esmExportString}`); const testExports = `module.exports = {${[...snippets, ...archivedSnippets] .map(v => v.replace('.md', '')) .join(',')}}`; fs.writeFileSync( TEST_MODULE_FILE, `${requires}\n\n${cjsExportString}\n\n${testExports}` ); // Check Travis builds - Will skip builds on Travis if not CRON/API if (util.isTravisCI() && util.isNotTravisCronOrAPI()) { fs.unlink(ROLLUP_INPUT_FILE); console.log( `${chalk.green( 'NOBUILD' )} Module build terminated, not a cron job or a custom build!` ); console.timeEnd('Packager'); process.exit(0); } await doRollup(); // Clean up the temporary input file Rollup used for building the module fs.unlink(ROLLUP_INPUT_FILE); console.log(`${chalk.green('SUCCESS!')} Snippet module built!`); console.timeEnd('Packager'); } catch (err) { console.log(`${chalk.red('ERROR!')} During module creation: ${err}`); process.exit(1); } }
[ "async", "function", "build", "(", ")", "{", "console", ".", "time", "(", "'Packager'", ")", ";", "let", "requires", "=", "[", "]", ";", "let", "esmExportString", "=", "''", ";", "let", "cjsExportString", "=", "''", ";", "try", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "DIST_PATH", ")", ")", "fs", ".", "mkdirSync", "(", "DIST_PATH", ")", ";", "fs", ".", "writeFileSync", "(", "ROLLUP_INPUT_FILE", ",", "''", ")", ";", "fs", ".", "writeFileSync", "(", "TEST_MODULE_FILE", ",", "''", ")", ";", "const", "nodeSnippets", "=", "fs", ".", "readFileSync", "(", "'tag_database'", ",", "'utf8'", ")", ".", "split", "(", "'\\n'", ")", ".", "\\n", "filter", ".", "(", "v", "=>", "v", ".", "search", "(", "/", ":.*node", "/", "g", ")", "!==", "-", "1", ")", "map", ";", "(", "v", "=>", "v", ".", "slice", "(", "0", ",", "v", ".", "indexOf", "(", "':'", ")", ")", ")", "const", "snippets", "=", "fs", ".", "readdirSync", "(", "SNIPPETS_PATH", ")", ";", "const", "archivedSnippets", "=", "fs", ".", "readdirSync", "(", "SNIPPETS_ARCHIVE_PATH", ")", ".", "filter", "(", "v", "=>", "v", "!==", "'README.md'", ")", ";", "snippets", ".", "forEach", "(", "snippet", "=>", "{", "const", "rawSnippetString", "=", "getRawSnippetString", "(", "SNIPPETS_PATH", ",", "snippet", ")", ";", "const", "snippetName", "=", "snippet", ".", "replace", "(", "'.md'", ",", "''", ")", ";", "let", "code", "=", "getCode", "(", "rawSnippetString", ")", ";", "if", "(", "nodeSnippets", ".", "includes", "(", "snippetName", ")", ")", "{", "requires", ".", "push", "(", "code", ".", "match", "(", "/", "const.*=.*require\\(([^\\)]*)\\);", "/", "g", ")", ")", ";", "code", "=", "code", ".", "replace", "(", "/", "const.*=.*require\\(([^\\)]*)\\);", "/", "g", ",", "''", ")", ";", "}", "esmExportString", "+=", "`", "${", "code", "}", "`", ";", "cjsExportString", "+=", "code", ";", "}", ")", ";", "archivedSnippets", ".", "forEach", "(", "snippet", "=>", "{", "const", "rawSnippetString", "=", "getRawSnippetString", "(", "SNIPPETS_ARCHIVE_PATH", ",", "snippet", ")", ";", "cjsExportString", "+=", "getCode", "(", "rawSnippetString", ")", ";", "}", ")", ";", "requires", "=", "[", "...", "new", "Set", "(", "requires", ".", "filter", "(", "Boolean", ")", ".", "map", "(", "v", "=>", "v", "[", "0", "]", ".", "replace", "(", "'require('", ",", "'typeof require !== \"undefined\" && require('", ")", ")", ")", "]", ".", "join", "(", "'\\n'", ")", ";", "\\n", "fs", ".", "writeFileSync", "(", "ROLLUP_INPUT_FILE", ",", "`", "${", "requires", "}", "\\n", "\\n", "${", "esmExportString", "}", "`", ")", ";", "const", "testExports", "=", "`", "${", "[", "...", "snippets", ",", "...", "archivedSnippets", "]", ".", "map", "(", "v", "=>", "v", ".", "replace", "(", "'.md'", ",", "''", ")", ")", ".", "join", "(", "','", ")", "}", "`", ";", "fs", ".", "writeFileSync", "(", "TEST_MODULE_FILE", ",", "`", "${", "requires", "}", "\\n", "\\n", "${", "cjsExportString", "}", "\\n", "\\n", "${", "testExports", "}", "`", ")", ";", "if", "(", "util", ".", "isTravisCI", "(", ")", "&&", "util", ".", "isNotTravisCronOrAPI", "(", ")", ")", "{", "fs", ".", "unlink", "(", "ROLLUP_INPUT_FILE", ")", ";", "console", ".", "log", "(", "`", "${", "chalk", ".", "green", "(", "'NOBUILD'", ")", "}", "`", ")", ";", "console", ".", "timeEnd", "(", "'Packager'", ")", ";", "process", ".", "exit", "(", "0", ")", ";", "}", "await", "doRollup", "(", ")", ";", "fs", ".", "unlink", "(", "ROLLUP_INPUT_FILE", ")", ";", "}", "console", ".", "log", "(", "`", "${", "chalk", ".", "green", "(", "'SUCCESS!'", ")", "}", "`", ")", ";", "}" ]
Starts the build process.
[ "Starts", "the", "build", "process", "." ]
5ef18713903aaaa5ff5409ef3a6de31dbd878d0c
https://github.com/30-seconds/30-seconds-of-code/blob/5ef18713903aaaa5ff5409ef3a6de31dbd878d0c/scripts/module.js#L74-L165
train
electron/electron
lib/browser/guest-view-manager.js
function (embedder, params) { if (webViewManager == null) { webViewManager = process.electronBinding('web_view_manager') } const guest = webContents.create({ isGuest: true, partition: params.partition, embedder: embedder }) const guestInstanceId = guest.id guestInstances[guestInstanceId] = { guest: guest, embedder: embedder } // Clear the guest from map when it is destroyed. // // The guest WebContents is usually destroyed in 2 cases: // 1. The embedder frame is closed (reloaded or destroyed), and it // automatically closes the guest frame. // 2. The guest frame is detached dynamically via JS, and it is manually // destroyed when the renderer sends the GUEST_VIEW_MANAGER_DESTROY_GUEST // message. // The second case relies on the libcc patch: // https://github.com/electron/libchromiumcontent/pull/676 // The patch was introduced to work around a bug in Chromium: // https://github.com/electron/electron/issues/14211 // We should revisit the bug to see if we can remove our libcc patch, the // patch was introduced in Chrome 66. guest.once('destroyed', () => { if (guestInstanceId in guestInstances) { detachGuest(embedder, guestInstanceId) } }) // Init guest web view after attached. guest.once('did-attach', function (event) { params = this.attachParams delete this.attachParams const previouslyAttached = this.viewInstanceId != null this.viewInstanceId = params.instanceId // Only load URL and set size on first attach if (previouslyAttached) { return } if (params.src) { const opts = {} if (params.httpreferrer) { opts.httpReferrer = params.httpreferrer } if (params.useragent) { opts.userAgent = params.useragent } this.loadURL(params.src, opts) } guest.allowPopups = params.allowpopups embedder.emit('did-attach-webview', event, guest) }) const sendToEmbedder = (channel, ...args) => { if (!embedder.isDestroyed()) { embedder._sendInternal(`${channel}-${guest.viewInstanceId}`, ...args) } } // Dispatch events to embedder. const fn = function (event) { guest.on(event, function (_, ...args) { sendToEmbedder('ELECTRON_GUEST_VIEW_INTERNAL_DISPATCH_EVENT', event, ...args) }) } for (const event of supportedWebViewEvents) { fn(event) } // Dispatch guest's IPC messages to embedder. guest.on('ipc-message-host', function (_, channel, args) { sendToEmbedder('ELECTRON_GUEST_VIEW_INTERNAL_IPC_MESSAGE', channel, ...args) }) // Notify guest of embedder window visibility when it is ready // FIXME Remove once https://github.com/electron/electron/issues/6828 is fixed guest.on('dom-ready', function () { const guestInstance = guestInstances[guestInstanceId] if (guestInstance != null && guestInstance.visibilityState != null) { guest._sendInternal('ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE', guestInstance.visibilityState) } }) // Forward internal web contents event to embedder to handle // native window.open setup guest.on('-add-new-contents', (...args) => { if (guest.getLastWebPreferences().nativeWindowOpen === true) { const embedder = getEmbedder(guestInstanceId) if (embedder != null) { embedder.emit('-add-new-contents', ...args) } } }) return guestInstanceId }
javascript
function (embedder, params) { if (webViewManager == null) { webViewManager = process.electronBinding('web_view_manager') } const guest = webContents.create({ isGuest: true, partition: params.partition, embedder: embedder }) const guestInstanceId = guest.id guestInstances[guestInstanceId] = { guest: guest, embedder: embedder } // Clear the guest from map when it is destroyed. // // The guest WebContents is usually destroyed in 2 cases: // 1. The embedder frame is closed (reloaded or destroyed), and it // automatically closes the guest frame. // 2. The guest frame is detached dynamically via JS, and it is manually // destroyed when the renderer sends the GUEST_VIEW_MANAGER_DESTROY_GUEST // message. // The second case relies on the libcc patch: // https://github.com/electron/libchromiumcontent/pull/676 // The patch was introduced to work around a bug in Chromium: // https://github.com/electron/electron/issues/14211 // We should revisit the bug to see if we can remove our libcc patch, the // patch was introduced in Chrome 66. guest.once('destroyed', () => { if (guestInstanceId in guestInstances) { detachGuest(embedder, guestInstanceId) } }) // Init guest web view after attached. guest.once('did-attach', function (event) { params = this.attachParams delete this.attachParams const previouslyAttached = this.viewInstanceId != null this.viewInstanceId = params.instanceId // Only load URL and set size on first attach if (previouslyAttached) { return } if (params.src) { const opts = {} if (params.httpreferrer) { opts.httpReferrer = params.httpreferrer } if (params.useragent) { opts.userAgent = params.useragent } this.loadURL(params.src, opts) } guest.allowPopups = params.allowpopups embedder.emit('did-attach-webview', event, guest) }) const sendToEmbedder = (channel, ...args) => { if (!embedder.isDestroyed()) { embedder._sendInternal(`${channel}-${guest.viewInstanceId}`, ...args) } } // Dispatch events to embedder. const fn = function (event) { guest.on(event, function (_, ...args) { sendToEmbedder('ELECTRON_GUEST_VIEW_INTERNAL_DISPATCH_EVENT', event, ...args) }) } for (const event of supportedWebViewEvents) { fn(event) } // Dispatch guest's IPC messages to embedder. guest.on('ipc-message-host', function (_, channel, args) { sendToEmbedder('ELECTRON_GUEST_VIEW_INTERNAL_IPC_MESSAGE', channel, ...args) }) // Notify guest of embedder window visibility when it is ready // FIXME Remove once https://github.com/electron/electron/issues/6828 is fixed guest.on('dom-ready', function () { const guestInstance = guestInstances[guestInstanceId] if (guestInstance != null && guestInstance.visibilityState != null) { guest._sendInternal('ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE', guestInstance.visibilityState) } }) // Forward internal web contents event to embedder to handle // native window.open setup guest.on('-add-new-contents', (...args) => { if (guest.getLastWebPreferences().nativeWindowOpen === true) { const embedder = getEmbedder(guestInstanceId) if (embedder != null) { embedder.emit('-add-new-contents', ...args) } } }) return guestInstanceId }
[ "function", "(", "embedder", ",", "params", ")", "{", "if", "(", "webViewManager", "==", "null", ")", "{", "webViewManager", "=", "process", ".", "electronBinding", "(", "'web_view_manager'", ")", "}", "const", "guest", "=", "webContents", ".", "create", "(", "{", "isGuest", ":", "true", ",", "partition", ":", "params", ".", "partition", ",", "embedder", ":", "embedder", "}", ")", "const", "guestInstanceId", "=", "guest", ".", "id", "guestInstances", "[", "guestInstanceId", "]", "=", "{", "guest", ":", "guest", ",", "embedder", ":", "embedder", "}", "guest", ".", "once", "(", "'destroyed'", ",", "(", ")", "=>", "{", "if", "(", "guestInstanceId", "in", "guestInstances", ")", "{", "detachGuest", "(", "embedder", ",", "guestInstanceId", ")", "}", "}", ")", "guest", ".", "once", "(", "'did-attach'", ",", "function", "(", "event", ")", "{", "params", "=", "this", ".", "attachParams", "delete", "this", ".", "attachParams", "const", "previouslyAttached", "=", "this", ".", "viewInstanceId", "!=", "null", "this", ".", "viewInstanceId", "=", "params", ".", "instanceId", "if", "(", "previouslyAttached", ")", "{", "return", "}", "if", "(", "params", ".", "src", ")", "{", "const", "opts", "=", "{", "}", "if", "(", "params", ".", "httpreferrer", ")", "{", "opts", ".", "httpReferrer", "=", "params", ".", "httpreferrer", "}", "if", "(", "params", ".", "useragent", ")", "{", "opts", ".", "userAgent", "=", "params", ".", "useragent", "}", "this", ".", "loadURL", "(", "params", ".", "src", ",", "opts", ")", "}", "guest", ".", "allowPopups", "=", "params", ".", "allowpopups", "embedder", ".", "emit", "(", "'did-attach-webview'", ",", "event", ",", "guest", ")", "}", ")", "const", "sendToEmbedder", "=", "(", "channel", ",", "...", "args", ")", "=>", "{", "if", "(", "!", "embedder", ".", "isDestroyed", "(", ")", ")", "{", "embedder", ".", "_sendInternal", "(", "`", "${", "channel", "}", "${", "guest", ".", "viewInstanceId", "}", "`", ",", "...", "args", ")", "}", "}", "const", "fn", "=", "function", "(", "event", ")", "{", "guest", ".", "on", "(", "event", ",", "function", "(", "_", ",", "...", "args", ")", "{", "sendToEmbedder", "(", "'ELECTRON_GUEST_VIEW_INTERNAL_DISPATCH_EVENT'", ",", "event", ",", "...", "args", ")", "}", ")", "}", "for", "(", "const", "event", "of", "supportedWebViewEvents", ")", "{", "fn", "(", "event", ")", "}", "guest", ".", "on", "(", "'ipc-message-host'", ",", "function", "(", "_", ",", "channel", ",", "args", ")", "{", "sendToEmbedder", "(", "'ELECTRON_GUEST_VIEW_INTERNAL_IPC_MESSAGE'", ",", "channel", ",", "...", "args", ")", "}", ")", "guest", ".", "on", "(", "'dom-ready'", ",", "function", "(", ")", "{", "const", "guestInstance", "=", "guestInstances", "[", "guestInstanceId", "]", "if", "(", "guestInstance", "!=", "null", "&&", "guestInstance", ".", "visibilityState", "!=", "null", ")", "{", "guest", ".", "_sendInternal", "(", "'ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE'", ",", "guestInstance", ".", "visibilityState", ")", "}", "}", ")", "guest", ".", "on", "(", "'-add-new-contents'", ",", "(", "...", "args", ")", "=>", "{", "if", "(", "guest", ".", "getLastWebPreferences", "(", ")", ".", "nativeWindowOpen", "===", "true", ")", "{", "const", "embedder", "=", "getEmbedder", "(", "guestInstanceId", ")", "if", "(", "embedder", "!=", "null", ")", "{", "embedder", ".", "emit", "(", "'-add-new-contents'", ",", "...", "args", ")", "}", "}", "}", ")", "return", "guestInstanceId", "}" ]
Create a new guest instance.
[ "Create", "a", "new", "guest", "instance", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/guest-view-manager.js#L56-L161
train
electron/electron
lib/browser/guest-view-manager.js
function (embedder, guestInstanceId) { const guestInstance = guestInstances[guestInstanceId] if (embedder !== guestInstance.embedder) { return } webViewManager.removeGuest(embedder, guestInstanceId) delete guestInstances[guestInstanceId] const key = `${embedder.id}-${guestInstance.elementInstanceId}` delete embedderElementsMap[key] }
javascript
function (embedder, guestInstanceId) { const guestInstance = guestInstances[guestInstanceId] if (embedder !== guestInstance.embedder) { return } webViewManager.removeGuest(embedder, guestInstanceId) delete guestInstances[guestInstanceId] const key = `${embedder.id}-${guestInstance.elementInstanceId}` delete embedderElementsMap[key] }
[ "function", "(", "embedder", ",", "guestInstanceId", ")", "{", "const", "guestInstance", "=", "guestInstances", "[", "guestInstanceId", "]", "if", "(", "embedder", "!==", "guestInstance", ".", "embedder", ")", "{", "return", "}", "webViewManager", ".", "removeGuest", "(", "embedder", ",", "guestInstanceId", ")", "delete", "guestInstances", "[", "guestInstanceId", "]", "const", "key", "=", "`", "${", "embedder", ".", "id", "}", "${", "guestInstance", ".", "elementInstanceId", "}", "`", "delete", "embedderElementsMap", "[", "key", "]", "}" ]
Remove an guest-embedder relationship.
[ "Remove", "an", "guest", "-", "embedder", "relationship", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/guest-view-manager.js#L276-L287
train
electron/electron
lib/browser/guest-view-manager.js
function (visibilityState) { for (const guestInstanceId in guestInstances) { const guestInstance = guestInstances[guestInstanceId] guestInstance.visibilityState = visibilityState if (guestInstance.embedder === embedder) { guestInstance.guest._sendInternal('ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE', visibilityState) } } }
javascript
function (visibilityState) { for (const guestInstanceId in guestInstances) { const guestInstance = guestInstances[guestInstanceId] guestInstance.visibilityState = visibilityState if (guestInstance.embedder === embedder) { guestInstance.guest._sendInternal('ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE', visibilityState) } } }
[ "function", "(", "visibilityState", ")", "{", "for", "(", "const", "guestInstanceId", "in", "guestInstances", ")", "{", "const", "guestInstance", "=", "guestInstances", "[", "guestInstanceId", "]", "guestInstance", ".", "visibilityState", "=", "visibilityState", "if", "(", "guestInstance", ".", "embedder", "===", "embedder", ")", "{", "guestInstance", ".", "guest", ".", "_sendInternal", "(", "'ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE'", ",", "visibilityState", ")", "}", "}", "}" ]
Forward embedder window visiblity change events to guest
[ "Forward", "embedder", "window", "visiblity", "change", "events", "to", "guest" ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/guest-view-manager.js#L299-L307
train
electron/electron
lib/browser/guest-view-manager.js
function (guestInstanceId, contents) { const guest = getGuest(guestInstanceId) if (!guest) { throw new Error(`Invalid guestInstanceId: ${guestInstanceId}`) } if (guest.hostWebContents !== contents) { throw new Error(`Access denied to guestInstanceId: ${guestInstanceId}`) } return guest }
javascript
function (guestInstanceId, contents) { const guest = getGuest(guestInstanceId) if (!guest) { throw new Error(`Invalid guestInstanceId: ${guestInstanceId}`) } if (guest.hostWebContents !== contents) { throw new Error(`Access denied to guestInstanceId: ${guestInstanceId}`) } return guest }
[ "function", "(", "guestInstanceId", ",", "contents", ")", "{", "const", "guest", "=", "getGuest", "(", "guestInstanceId", ")", "if", "(", "!", "guest", ")", "{", "throw", "new", "Error", "(", "`", "${", "guestInstanceId", "}", "`", ")", "}", "if", "(", "guest", ".", "hostWebContents", "!==", "contents", ")", "{", "throw", "new", "Error", "(", "`", "${", "guestInstanceId", "}", "`", ")", "}", "return", "guest", "}" ]
Returns WebContents from its guest id hosted in given webContents.
[ "Returns", "WebContents", "from", "its", "guest", "id", "hosted", "in", "given", "webContents", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/guest-view-manager.js#L395-L404
train
electron/electron
script/prepare-release.js
changesToRelease
async function changesToRelease () { const lastCommitWasRelease = new RegExp(`^Bump v[0-9.]*(-beta[0-9.]*)?(-nightly[0-9.]*)?$`, 'g') const lastCommit = await GitProcess.exec(['log', '-n', '1', `--pretty=format:'%s'`], gitDir) return !lastCommitWasRelease.test(lastCommit.stdout) }
javascript
async function changesToRelease () { const lastCommitWasRelease = new RegExp(`^Bump v[0-9.]*(-beta[0-9.]*)?(-nightly[0-9.]*)?$`, 'g') const lastCommit = await GitProcess.exec(['log', '-n', '1', `--pretty=format:'%s'`], gitDir) return !lastCommitWasRelease.test(lastCommit.stdout) }
[ "async", "function", "changesToRelease", "(", ")", "{", "const", "lastCommitWasRelease", "=", "new", "RegExp", "(", "`", "`", ",", "'g'", ")", "const", "lastCommit", "=", "await", "GitProcess", ".", "exec", "(", "[", "'log'", ",", "'-n'", ",", "'1'", ",", "`", "`", "]", ",", "gitDir", ")", "return", "!", "lastCommitWasRelease", ".", "test", "(", "lastCommit", ".", "stdout", ")", "}" ]
function to determine if there have been commits to master since the last release
[ "function", "to", "determine", "if", "there", "have", "been", "commits", "to", "master", "since", "the", "last", "release" ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/script/prepare-release.js#L184-L188
train
electron/electron
script/release-notes/notes.js
runRetryable
async function runRetryable (fn, maxRetries) { let lastError for (let i = 0; i < maxRetries; i++) { try { return await fn() } catch (error) { await new Promise((resolve, reject) => setTimeout(resolve, CHECK_INTERVAL)) lastError = error } } // Silently eat 404s. if (lastError.status !== 404) throw lastError }
javascript
async function runRetryable (fn, maxRetries) { let lastError for (let i = 0; i < maxRetries; i++) { try { return await fn() } catch (error) { await new Promise((resolve, reject) => setTimeout(resolve, CHECK_INTERVAL)) lastError = error } } // Silently eat 404s. if (lastError.status !== 404) throw lastError }
[ "async", "function", "runRetryable", "(", "fn", ",", "maxRetries", ")", "{", "let", "lastError", "for", "(", "let", "i", "=", "0", ";", "i", "<", "maxRetries", ";", "i", "++", ")", "{", "try", "{", "return", "await", "fn", "(", ")", "}", "catch", "(", "error", ")", "{", "await", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "setTimeout", "(", "resolve", ",", "CHECK_INTERVAL", ")", ")", "lastError", "=", "error", "}", "}", "if", "(", "lastError", ".", "status", "!==", "404", ")", "throw", "lastError", "}" ]
helper function to add some resiliency to volatile GH api endpoints
[ "helper", "function", "to", "add", "some", "resiliency", "to", "volatile", "GH", "api", "endpoints" ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/script/release-notes/notes.js#L305-L317
train
electron/electron
lib/renderer/api/remote.js
wrapArgs
function wrapArgs (args, visited = new Set()) { const valueToMeta = (value) => { // Check for circular reference. if (visited.has(value)) { return { type: 'value', value: null } } if (Array.isArray(value)) { visited.add(value) const meta = { type: 'array', value: wrapArgs(value, visited) } visited.delete(value) return meta } else if (bufferUtils.isBuffer(value)) { return { type: 'buffer', value: bufferUtils.bufferToMeta(value) } } else if (value instanceof Date) { return { type: 'date', value: value.getTime() } } else if ((value != null) && typeof value === 'object') { if (isPromise(value)) { return { type: 'promise', then: valueToMeta(function (onFulfilled, onRejected) { value.then(onFulfilled, onRejected) }) } } else if (v8Util.getHiddenValue(value, 'atomId')) { return { type: 'remote-object', id: v8Util.getHiddenValue(value, 'atomId') } } const meta = { type: 'object', name: value.constructor ? value.constructor.name : '', members: [] } visited.add(value) for (const prop in value) { meta.members.push({ name: prop, value: valueToMeta(value[prop]) }) } visited.delete(value) return meta } else if (typeof value === 'function' && v8Util.getHiddenValue(value, 'returnValue')) { return { type: 'function-with-return-value', value: valueToMeta(value()) } } else if (typeof value === 'function') { return { type: 'function', id: callbacksRegistry.add(value), location: v8Util.getHiddenValue(value, 'location'), length: value.length } } else { return { type: 'value', value: value } } } return args.map(valueToMeta) }
javascript
function wrapArgs (args, visited = new Set()) { const valueToMeta = (value) => { // Check for circular reference. if (visited.has(value)) { return { type: 'value', value: null } } if (Array.isArray(value)) { visited.add(value) const meta = { type: 'array', value: wrapArgs(value, visited) } visited.delete(value) return meta } else if (bufferUtils.isBuffer(value)) { return { type: 'buffer', value: bufferUtils.bufferToMeta(value) } } else if (value instanceof Date) { return { type: 'date', value: value.getTime() } } else if ((value != null) && typeof value === 'object') { if (isPromise(value)) { return { type: 'promise', then: valueToMeta(function (onFulfilled, onRejected) { value.then(onFulfilled, onRejected) }) } } else if (v8Util.getHiddenValue(value, 'atomId')) { return { type: 'remote-object', id: v8Util.getHiddenValue(value, 'atomId') } } const meta = { type: 'object', name: value.constructor ? value.constructor.name : '', members: [] } visited.add(value) for (const prop in value) { meta.members.push({ name: prop, value: valueToMeta(value[prop]) }) } visited.delete(value) return meta } else if (typeof value === 'function' && v8Util.getHiddenValue(value, 'returnValue')) { return { type: 'function-with-return-value', value: valueToMeta(value()) } } else if (typeof value === 'function') { return { type: 'function', id: callbacksRegistry.add(value), location: v8Util.getHiddenValue(value, 'location'), length: value.length } } else { return { type: 'value', value: value } } } return args.map(valueToMeta) }
[ "function", "wrapArgs", "(", "args", ",", "visited", "=", "new", "Set", "(", ")", ")", "{", "const", "valueToMeta", "=", "(", "value", ")", "=>", "{", "if", "(", "visited", ".", "has", "(", "value", ")", ")", "{", "return", "{", "type", ":", "'value'", ",", "value", ":", "null", "}", "}", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "visited", ".", "add", "(", "value", ")", "const", "meta", "=", "{", "type", ":", "'array'", ",", "value", ":", "wrapArgs", "(", "value", ",", "visited", ")", "}", "visited", ".", "delete", "(", "value", ")", "return", "meta", "}", "else", "if", "(", "bufferUtils", ".", "isBuffer", "(", "value", ")", ")", "{", "return", "{", "type", ":", "'buffer'", ",", "value", ":", "bufferUtils", ".", "bufferToMeta", "(", "value", ")", "}", "}", "else", "if", "(", "value", "instanceof", "Date", ")", "{", "return", "{", "type", ":", "'date'", ",", "value", ":", "value", ".", "getTime", "(", ")", "}", "}", "else", "if", "(", "(", "value", "!=", "null", ")", "&&", "typeof", "value", "===", "'object'", ")", "{", "if", "(", "isPromise", "(", "value", ")", ")", "{", "return", "{", "type", ":", "'promise'", ",", "then", ":", "valueToMeta", "(", "function", "(", "onFulfilled", ",", "onRejected", ")", "{", "value", ".", "then", "(", "onFulfilled", ",", "onRejected", ")", "}", ")", "}", "}", "else", "if", "(", "v8Util", ".", "getHiddenValue", "(", "value", ",", "'atomId'", ")", ")", "{", "return", "{", "type", ":", "'remote-object'", ",", "id", ":", "v8Util", ".", "getHiddenValue", "(", "value", ",", "'atomId'", ")", "}", "}", "const", "meta", "=", "{", "type", ":", "'object'", ",", "name", ":", "value", ".", "constructor", "?", "value", ".", "constructor", ".", "name", ":", "''", ",", "members", ":", "[", "]", "}", "visited", ".", "add", "(", "value", ")", "for", "(", "const", "prop", "in", "value", ")", "{", "meta", ".", "members", ".", "push", "(", "{", "name", ":", "prop", ",", "value", ":", "valueToMeta", "(", "value", "[", "prop", "]", ")", "}", ")", "}", "visited", ".", "delete", "(", "value", ")", "return", "meta", "}", "else", "if", "(", "typeof", "value", "===", "'function'", "&&", "v8Util", ".", "getHiddenValue", "(", "value", ",", "'returnValue'", ")", ")", "{", "return", "{", "type", ":", "'function-with-return-value'", ",", "value", ":", "valueToMeta", "(", "value", "(", ")", ")", "}", "}", "else", "if", "(", "typeof", "value", "===", "'function'", ")", "{", "return", "{", "type", ":", "'function'", ",", "id", ":", "callbacksRegistry", ".", "add", "(", "value", ")", ",", "location", ":", "v8Util", ".", "getHiddenValue", "(", "value", ",", "'location'", ")", ",", "length", ":", "value", ".", "length", "}", "}", "else", "{", "return", "{", "type", ":", "'value'", ",", "value", ":", "value", "}", "}", "}", "return", "args", ".", "map", "(", "valueToMeta", ")", "}" ]
Convert the arguments object into an array of meta data.
[ "Convert", "the", "arguments", "object", "into", "an", "array", "of", "meta", "data", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/renderer/api/remote.js#L28-L105
train
electron/electron
lib/renderer/api/remote.js
setObjectMembers
function setObjectMembers (ref, object, metaId, members) { if (!Array.isArray(members)) return for (const member of members) { if (object.hasOwnProperty(member.name)) continue const descriptor = { enumerable: member.enumerable } if (member.type === 'method') { const remoteMemberFunction = function (...args) { let command if (this && this.constructor === remoteMemberFunction) { command = 'ELECTRON_BROWSER_MEMBER_CONSTRUCTOR' } else { command = 'ELECTRON_BROWSER_MEMBER_CALL' } const ret = ipcRendererInternal.sendSync(command, contextId, metaId, member.name, wrapArgs(args)) return metaToValue(ret) } let descriptorFunction = proxyFunctionProperties(remoteMemberFunction, metaId, member.name) descriptor.get = () => { descriptorFunction.ref = ref // The member should reference its object. return descriptorFunction } // Enable monkey-patch the method descriptor.set = (value) => { descriptorFunction = value return value } descriptor.configurable = true } else if (member.type === 'get') { descriptor.get = () => { const command = 'ELECTRON_BROWSER_MEMBER_GET' const meta = ipcRendererInternal.sendSync(command, contextId, metaId, member.name) return metaToValue(meta) } if (member.writable) { descriptor.set = (value) => { const args = wrapArgs([value]) const command = 'ELECTRON_BROWSER_MEMBER_SET' const meta = ipcRendererInternal.sendSync(command, contextId, metaId, member.name, args) if (meta != null) metaToValue(meta) return value } } } Object.defineProperty(object, member.name, descriptor) } }
javascript
function setObjectMembers (ref, object, metaId, members) { if (!Array.isArray(members)) return for (const member of members) { if (object.hasOwnProperty(member.name)) continue const descriptor = { enumerable: member.enumerable } if (member.type === 'method') { const remoteMemberFunction = function (...args) { let command if (this && this.constructor === remoteMemberFunction) { command = 'ELECTRON_BROWSER_MEMBER_CONSTRUCTOR' } else { command = 'ELECTRON_BROWSER_MEMBER_CALL' } const ret = ipcRendererInternal.sendSync(command, contextId, metaId, member.name, wrapArgs(args)) return metaToValue(ret) } let descriptorFunction = proxyFunctionProperties(remoteMemberFunction, metaId, member.name) descriptor.get = () => { descriptorFunction.ref = ref // The member should reference its object. return descriptorFunction } // Enable monkey-patch the method descriptor.set = (value) => { descriptorFunction = value return value } descriptor.configurable = true } else if (member.type === 'get') { descriptor.get = () => { const command = 'ELECTRON_BROWSER_MEMBER_GET' const meta = ipcRendererInternal.sendSync(command, contextId, metaId, member.name) return metaToValue(meta) } if (member.writable) { descriptor.set = (value) => { const args = wrapArgs([value]) const command = 'ELECTRON_BROWSER_MEMBER_SET' const meta = ipcRendererInternal.sendSync(command, contextId, metaId, member.name, args) if (meta != null) metaToValue(meta) return value } } } Object.defineProperty(object, member.name, descriptor) } }
[ "function", "setObjectMembers", "(", "ref", ",", "object", ",", "metaId", ",", "members", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "members", ")", ")", "return", "for", "(", "const", "member", "of", "members", ")", "{", "if", "(", "object", ".", "hasOwnProperty", "(", "member", ".", "name", ")", ")", "continue", "const", "descriptor", "=", "{", "enumerable", ":", "member", ".", "enumerable", "}", "if", "(", "member", ".", "type", "===", "'method'", ")", "{", "const", "remoteMemberFunction", "=", "function", "(", "...", "args", ")", "{", "let", "command", "if", "(", "this", "&&", "this", ".", "constructor", "===", "remoteMemberFunction", ")", "{", "command", "=", "'ELECTRON_BROWSER_MEMBER_CONSTRUCTOR'", "}", "else", "{", "command", "=", "'ELECTRON_BROWSER_MEMBER_CALL'", "}", "const", "ret", "=", "ipcRendererInternal", ".", "sendSync", "(", "command", ",", "contextId", ",", "metaId", ",", "member", ".", "name", ",", "wrapArgs", "(", "args", ")", ")", "return", "metaToValue", "(", "ret", ")", "}", "let", "descriptorFunction", "=", "proxyFunctionProperties", "(", "remoteMemberFunction", ",", "metaId", ",", "member", ".", "name", ")", "descriptor", ".", "get", "=", "(", ")", "=>", "{", "descriptorFunction", ".", "ref", "=", "ref", "return", "descriptorFunction", "}", "descriptor", ".", "set", "=", "(", "value", ")", "=>", "{", "descriptorFunction", "=", "value", "return", "value", "}", "descriptor", ".", "configurable", "=", "true", "}", "else", "if", "(", "member", ".", "type", "===", "'get'", ")", "{", "descriptor", ".", "get", "=", "(", ")", "=>", "{", "const", "command", "=", "'ELECTRON_BROWSER_MEMBER_GET'", "const", "meta", "=", "ipcRendererInternal", ".", "sendSync", "(", "command", ",", "contextId", ",", "metaId", ",", "member", ".", "name", ")", "return", "metaToValue", "(", "meta", ")", "}", "if", "(", "member", ".", "writable", ")", "{", "descriptor", ".", "set", "=", "(", "value", ")", "=>", "{", "const", "args", "=", "wrapArgs", "(", "[", "value", "]", ")", "const", "command", "=", "'ELECTRON_BROWSER_MEMBER_SET'", "const", "meta", "=", "ipcRendererInternal", ".", "sendSync", "(", "command", ",", "contextId", ",", "metaId", ",", "member", ".", "name", ",", "args", ")", "if", "(", "meta", "!=", "null", ")", "metaToValue", "(", "meta", ")", "return", "value", "}", "}", "}", "Object", ".", "defineProperty", "(", "object", ",", "member", ".", "name", ",", "descriptor", ")", "}", "}" ]
Populate object's members from descriptors. The |ref| will be kept referenced by |members|. This matches |getObjectMemebers| in rpc-server.
[ "Populate", "object", "s", "members", "from", "descriptors", ".", "The", "|ref|", "will", "be", "kept", "referenced", "by", "|members|", ".", "This", "matches", "|getObjectMemebers|", "in", "rpc", "-", "server", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/renderer/api/remote.js#L110-L161
train
electron/electron
lib/renderer/api/remote.js
setObjectPrototype
function setObjectPrototype (ref, object, metaId, descriptor) { if (descriptor === null) return const proto = {} setObjectMembers(ref, proto, metaId, descriptor.members) setObjectPrototype(ref, proto, metaId, descriptor.proto) Object.setPrototypeOf(object, proto) }
javascript
function setObjectPrototype (ref, object, metaId, descriptor) { if (descriptor === null) return const proto = {} setObjectMembers(ref, proto, metaId, descriptor.members) setObjectPrototype(ref, proto, metaId, descriptor.proto) Object.setPrototypeOf(object, proto) }
[ "function", "setObjectPrototype", "(", "ref", ",", "object", ",", "metaId", ",", "descriptor", ")", "{", "if", "(", "descriptor", "===", "null", ")", "return", "const", "proto", "=", "{", "}", "setObjectMembers", "(", "ref", ",", "proto", ",", "metaId", ",", "descriptor", ".", "members", ")", "setObjectPrototype", "(", "ref", ",", "proto", ",", "metaId", ",", "descriptor", ".", "proto", ")", "Object", ".", "setPrototypeOf", "(", "object", ",", "proto", ")", "}" ]
Populate object's prototype from descriptor. This matches |getObjectPrototype| in rpc-server.
[ "Populate", "object", "s", "prototype", "from", "descriptor", ".", "This", "matches", "|getObjectPrototype|", "in", "rpc", "-", "server", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/renderer/api/remote.js#L165-L171
train
electron/electron
lib/renderer/api/remote.js
proxyFunctionProperties
function proxyFunctionProperties (remoteMemberFunction, metaId, name) { let loaded = false // Lazily load function properties const loadRemoteProperties = () => { if (loaded) return loaded = true const command = 'ELECTRON_BROWSER_MEMBER_GET' const meta = ipcRendererInternal.sendSync(command, contextId, metaId, name) setObjectMembers(remoteMemberFunction, remoteMemberFunction, meta.id, meta.members) } return new Proxy(remoteMemberFunction, { set: (target, property, value, receiver) => { if (property !== 'ref') loadRemoteProperties() target[property] = value return true }, get: (target, property, receiver) => { if (!target.hasOwnProperty(property)) loadRemoteProperties() const value = target[property] if (property === 'toString' && typeof value === 'function') { return value.bind(target) } return value }, ownKeys: (target) => { loadRemoteProperties() return Object.getOwnPropertyNames(target) }, getOwnPropertyDescriptor: (target, property) => { const descriptor = Object.getOwnPropertyDescriptor(target, property) if (descriptor) return descriptor loadRemoteProperties() return Object.getOwnPropertyDescriptor(target, property) } }) }
javascript
function proxyFunctionProperties (remoteMemberFunction, metaId, name) { let loaded = false // Lazily load function properties const loadRemoteProperties = () => { if (loaded) return loaded = true const command = 'ELECTRON_BROWSER_MEMBER_GET' const meta = ipcRendererInternal.sendSync(command, contextId, metaId, name) setObjectMembers(remoteMemberFunction, remoteMemberFunction, meta.id, meta.members) } return new Proxy(remoteMemberFunction, { set: (target, property, value, receiver) => { if (property !== 'ref') loadRemoteProperties() target[property] = value return true }, get: (target, property, receiver) => { if (!target.hasOwnProperty(property)) loadRemoteProperties() const value = target[property] if (property === 'toString' && typeof value === 'function') { return value.bind(target) } return value }, ownKeys: (target) => { loadRemoteProperties() return Object.getOwnPropertyNames(target) }, getOwnPropertyDescriptor: (target, property) => { const descriptor = Object.getOwnPropertyDescriptor(target, property) if (descriptor) return descriptor loadRemoteProperties() return Object.getOwnPropertyDescriptor(target, property) } }) }
[ "function", "proxyFunctionProperties", "(", "remoteMemberFunction", ",", "metaId", ",", "name", ")", "{", "let", "loaded", "=", "false", "const", "loadRemoteProperties", "=", "(", ")", "=>", "{", "if", "(", "loaded", ")", "return", "loaded", "=", "true", "const", "command", "=", "'ELECTRON_BROWSER_MEMBER_GET'", "const", "meta", "=", "ipcRendererInternal", ".", "sendSync", "(", "command", ",", "contextId", ",", "metaId", ",", "name", ")", "setObjectMembers", "(", "remoteMemberFunction", ",", "remoteMemberFunction", ",", "meta", ".", "id", ",", "meta", ".", "members", ")", "}", "return", "new", "Proxy", "(", "remoteMemberFunction", ",", "{", "set", ":", "(", "target", ",", "property", ",", "value", ",", "receiver", ")", "=>", "{", "if", "(", "property", "!==", "'ref'", ")", "loadRemoteProperties", "(", ")", "target", "[", "property", "]", "=", "value", "return", "true", "}", ",", "get", ":", "(", "target", ",", "property", ",", "receiver", ")", "=>", "{", "if", "(", "!", "target", ".", "hasOwnProperty", "(", "property", ")", ")", "loadRemoteProperties", "(", ")", "const", "value", "=", "target", "[", "property", "]", "if", "(", "property", "===", "'toString'", "&&", "typeof", "value", "===", "'function'", ")", "{", "return", "value", ".", "bind", "(", "target", ")", "}", "return", "value", "}", ",", "ownKeys", ":", "(", "target", ")", "=>", "{", "loadRemoteProperties", "(", ")", "return", "Object", ".", "getOwnPropertyNames", "(", "target", ")", "}", ",", "getOwnPropertyDescriptor", ":", "(", "target", ",", "property", ")", "=>", "{", "const", "descriptor", "=", "Object", ".", "getOwnPropertyDescriptor", "(", "target", ",", "property", ")", "if", "(", "descriptor", ")", "return", "descriptor", "loadRemoteProperties", "(", ")", "return", "Object", ".", "getOwnPropertyDescriptor", "(", "target", ",", "property", ")", "}", "}", ")", "}" ]
Wrap function in Proxy for accessing remote properties
[ "Wrap", "function", "in", "Proxy", "for", "accessing", "remote", "properties" ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/renderer/api/remote.js#L174-L211
train
electron/electron
lib/renderer/api/remote.js
metaToValue
function metaToValue (meta) { const types = { value: () => meta.value, array: () => meta.members.map((member) => metaToValue(member)), buffer: () => bufferUtils.metaToBuffer(meta.value), promise: () => resolvePromise({ then: metaToValue(meta.then) }), error: () => metaToPlainObject(meta), date: () => new Date(meta.value), exception: () => { throw errorUtils.deserialize(meta.value) } } if (meta.type in types) { return types[meta.type]() } else { let ret if (remoteObjectCache.has(meta.id)) { v8Util.addRemoteObjectRef(contextId, meta.id) return remoteObjectCache.get(meta.id) } // A shadow class to represent the remote function object. if (meta.type === 'function') { const remoteFunction = function (...args) { let command if (this && this.constructor === remoteFunction) { command = 'ELECTRON_BROWSER_CONSTRUCTOR' } else { command = 'ELECTRON_BROWSER_FUNCTION_CALL' } const obj = ipcRendererInternal.sendSync(command, contextId, meta.id, wrapArgs(args)) return metaToValue(obj) } ret = remoteFunction } else { ret = {} } setObjectMembers(ret, ret, meta.id, meta.members) setObjectPrototype(ret, ret, meta.id, meta.proto) Object.defineProperty(ret.constructor, 'name', { value: meta.name }) // Track delegate obj's lifetime & tell browser to clean up when object is GCed. v8Util.setRemoteObjectFreer(ret, contextId, meta.id) v8Util.setHiddenValue(ret, 'atomId', meta.id) v8Util.addRemoteObjectRef(contextId, meta.id) remoteObjectCache.set(meta.id, ret) return ret } }
javascript
function metaToValue (meta) { const types = { value: () => meta.value, array: () => meta.members.map((member) => metaToValue(member)), buffer: () => bufferUtils.metaToBuffer(meta.value), promise: () => resolvePromise({ then: metaToValue(meta.then) }), error: () => metaToPlainObject(meta), date: () => new Date(meta.value), exception: () => { throw errorUtils.deserialize(meta.value) } } if (meta.type in types) { return types[meta.type]() } else { let ret if (remoteObjectCache.has(meta.id)) { v8Util.addRemoteObjectRef(contextId, meta.id) return remoteObjectCache.get(meta.id) } // A shadow class to represent the remote function object. if (meta.type === 'function') { const remoteFunction = function (...args) { let command if (this && this.constructor === remoteFunction) { command = 'ELECTRON_BROWSER_CONSTRUCTOR' } else { command = 'ELECTRON_BROWSER_FUNCTION_CALL' } const obj = ipcRendererInternal.sendSync(command, contextId, meta.id, wrapArgs(args)) return metaToValue(obj) } ret = remoteFunction } else { ret = {} } setObjectMembers(ret, ret, meta.id, meta.members) setObjectPrototype(ret, ret, meta.id, meta.proto) Object.defineProperty(ret.constructor, 'name', { value: meta.name }) // Track delegate obj's lifetime & tell browser to clean up when object is GCed. v8Util.setRemoteObjectFreer(ret, contextId, meta.id) v8Util.setHiddenValue(ret, 'atomId', meta.id) v8Util.addRemoteObjectRef(contextId, meta.id) remoteObjectCache.set(meta.id, ret) return ret } }
[ "function", "metaToValue", "(", "meta", ")", "{", "const", "types", "=", "{", "value", ":", "(", ")", "=>", "meta", ".", "value", ",", "array", ":", "(", ")", "=>", "meta", ".", "members", ".", "map", "(", "(", "member", ")", "=>", "metaToValue", "(", "member", ")", ")", ",", "buffer", ":", "(", ")", "=>", "bufferUtils", ".", "metaToBuffer", "(", "meta", ".", "value", ")", ",", "promise", ":", "(", ")", "=>", "resolvePromise", "(", "{", "then", ":", "metaToValue", "(", "meta", ".", "then", ")", "}", ")", ",", "error", ":", "(", ")", "=>", "metaToPlainObject", "(", "meta", ")", ",", "date", ":", "(", ")", "=>", "new", "Date", "(", "meta", ".", "value", ")", ",", "exception", ":", "(", ")", "=>", "{", "throw", "errorUtils", ".", "deserialize", "(", "meta", ".", "value", ")", "}", "}", "if", "(", "meta", ".", "type", "in", "types", ")", "{", "return", "types", "[", "meta", ".", "type", "]", "(", ")", "}", "else", "{", "let", "ret", "if", "(", "remoteObjectCache", ".", "has", "(", "meta", ".", "id", ")", ")", "{", "v8Util", ".", "addRemoteObjectRef", "(", "contextId", ",", "meta", ".", "id", ")", "return", "remoteObjectCache", ".", "get", "(", "meta", ".", "id", ")", "}", "if", "(", "meta", ".", "type", "===", "'function'", ")", "{", "const", "remoteFunction", "=", "function", "(", "...", "args", ")", "{", "let", "command", "if", "(", "this", "&&", "this", ".", "constructor", "===", "remoteFunction", ")", "{", "command", "=", "'ELECTRON_BROWSER_CONSTRUCTOR'", "}", "else", "{", "command", "=", "'ELECTRON_BROWSER_FUNCTION_CALL'", "}", "const", "obj", "=", "ipcRendererInternal", ".", "sendSync", "(", "command", ",", "contextId", ",", "meta", ".", "id", ",", "wrapArgs", "(", "args", ")", ")", "return", "metaToValue", "(", "obj", ")", "}", "ret", "=", "remoteFunction", "}", "else", "{", "ret", "=", "{", "}", "}", "setObjectMembers", "(", "ret", ",", "ret", ",", "meta", ".", "id", ",", "meta", ".", "members", ")", "setObjectPrototype", "(", "ret", ",", "ret", ",", "meta", ".", "id", ",", "meta", ".", "proto", ")", "Object", ".", "defineProperty", "(", "ret", ".", "constructor", ",", "'name'", ",", "{", "value", ":", "meta", ".", "name", "}", ")", "v8Util", ".", "setRemoteObjectFreer", "(", "ret", ",", "contextId", ",", "meta", ".", "id", ")", "v8Util", ".", "setHiddenValue", "(", "ret", ",", "'atomId'", ",", "meta", ".", "id", ")", "v8Util", ".", "addRemoteObjectRef", "(", "contextId", ",", "meta", ".", "id", ")", "remoteObjectCache", ".", "set", "(", "meta", ".", "id", ",", "ret", ")", "return", "ret", "}", "}" ]
Convert meta data from browser into real value.
[ "Convert", "meta", "data", "from", "browser", "into", "real", "value", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/renderer/api/remote.js#L214-L262
train
electron/electron
lib/renderer/api/remote.js
metaToPlainObject
function metaToPlainObject (meta) { const obj = (() => meta.type === 'error' ? new Error() : {})() for (let i = 0; i < meta.members.length; i++) { const { name, value } = meta.members[i] obj[name] = value } return obj }
javascript
function metaToPlainObject (meta) { const obj = (() => meta.type === 'error' ? new Error() : {})() for (let i = 0; i < meta.members.length; i++) { const { name, value } = meta.members[i] obj[name] = value } return obj }
[ "function", "metaToPlainObject", "(", "meta", ")", "{", "const", "obj", "=", "(", "(", ")", "=>", "meta", ".", "type", "===", "'error'", "?", "new", "Error", "(", ")", ":", "{", "}", ")", "(", ")", "for", "(", "let", "i", "=", "0", ";", "i", "<", "meta", ".", "members", ".", "length", ";", "i", "++", ")", "{", "const", "{", "name", ",", "value", "}", "=", "meta", ".", "members", "[", "i", "]", "obj", "[", "name", "]", "=", "value", "}", "return", "obj", "}" ]
Construct a plain object from the meta.
[ "Construct", "a", "plain", "object", "from", "the", "meta", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/renderer/api/remote.js#L265-L272
train
electron/electron
lib/browser/chrome-extension.js
function (srcDirectory) { let manifest let manifestContent try { manifestContent = fs.readFileSync(path.join(srcDirectory, 'manifest.json')) } catch (readError) { console.warn(`Reading ${path.join(srcDirectory, 'manifest.json')} failed.`) console.warn(readError.stack || readError) throw readError } try { manifest = JSON.parse(manifestContent) } catch (parseError) { console.warn(`Parsing ${path.join(srcDirectory, 'manifest.json')} failed.`) console.warn(parseError.stack || parseError) throw parseError } if (!manifestNameMap[manifest.name]) { const extensionId = generateExtensionIdFromName(manifest.name) manifestMap[extensionId] = manifestNameMap[manifest.name] = manifest Object.assign(manifest, { srcDirectory: srcDirectory, extensionId: extensionId, // We can not use 'file://' directly because all resources in the extension // will be treated as relative to the root in Chrome. startPage: url.format({ protocol: 'chrome-extension', slashes: true, hostname: extensionId, pathname: manifest.devtools_page }) }) return manifest } else if (manifest && manifest.name) { console.warn(`Attempted to load extension "${manifest.name}" that has already been loaded.`) return manifest } }
javascript
function (srcDirectory) { let manifest let manifestContent try { manifestContent = fs.readFileSync(path.join(srcDirectory, 'manifest.json')) } catch (readError) { console.warn(`Reading ${path.join(srcDirectory, 'manifest.json')} failed.`) console.warn(readError.stack || readError) throw readError } try { manifest = JSON.parse(manifestContent) } catch (parseError) { console.warn(`Parsing ${path.join(srcDirectory, 'manifest.json')} failed.`) console.warn(parseError.stack || parseError) throw parseError } if (!manifestNameMap[manifest.name]) { const extensionId = generateExtensionIdFromName(manifest.name) manifestMap[extensionId] = manifestNameMap[manifest.name] = manifest Object.assign(manifest, { srcDirectory: srcDirectory, extensionId: extensionId, // We can not use 'file://' directly because all resources in the extension // will be treated as relative to the root in Chrome. startPage: url.format({ protocol: 'chrome-extension', slashes: true, hostname: extensionId, pathname: manifest.devtools_page }) }) return manifest } else if (manifest && manifest.name) { console.warn(`Attempted to load extension "${manifest.name}" that has already been loaded.`) return manifest } }
[ "function", "(", "srcDirectory", ")", "{", "let", "manifest", "let", "manifestContent", "try", "{", "manifestContent", "=", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "srcDirectory", ",", "'manifest.json'", ")", ")", "}", "catch", "(", "readError", ")", "{", "console", ".", "warn", "(", "`", "${", "path", ".", "join", "(", "srcDirectory", ",", "'manifest.json'", ")", "}", "`", ")", "console", ".", "warn", "(", "readError", ".", "stack", "||", "readError", ")", "throw", "readError", "}", "try", "{", "manifest", "=", "JSON", ".", "parse", "(", "manifestContent", ")", "}", "catch", "(", "parseError", ")", "{", "console", ".", "warn", "(", "`", "${", "path", ".", "join", "(", "srcDirectory", ",", "'manifest.json'", ")", "}", "`", ")", "console", ".", "warn", "(", "parseError", ".", "stack", "||", "parseError", ")", "throw", "parseError", "}", "if", "(", "!", "manifestNameMap", "[", "manifest", ".", "name", "]", ")", "{", "const", "extensionId", "=", "generateExtensionIdFromName", "(", "manifest", ".", "name", ")", "manifestMap", "[", "extensionId", "]", "=", "manifestNameMap", "[", "manifest", ".", "name", "]", "=", "manifest", "Object", ".", "assign", "(", "manifest", ",", "{", "srcDirectory", ":", "srcDirectory", ",", "extensionId", ":", "extensionId", ",", "startPage", ":", "url", ".", "format", "(", "{", "protocol", ":", "'chrome-extension'", ",", "slashes", ":", "true", ",", "hostname", ":", "extensionId", ",", "pathname", ":", "manifest", ".", "devtools_page", "}", ")", "}", ")", "return", "manifest", "}", "else", "if", "(", "manifest", "&&", "manifest", ".", "name", ")", "{", "console", ".", "warn", "(", "`", "${", "manifest", ".", "name", "}", "`", ")", "return", "manifest", "}", "}" ]
Create or get manifest object from |srcDirectory|.
[ "Create", "or", "get", "manifest", "object", "from", "|srcDirectory|", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/chrome-extension.js#L33-L73
train
electron/electron
lib/browser/chrome-extension.js
function (webContents) { const tabId = webContents.id sendToBackgroundPages('CHROME_TABS_ONCREATED') webContents.on('will-navigate', (event, url) => { sendToBackgroundPages('CHROME_WEBNAVIGATION_ONBEFORENAVIGATE', { frameId: 0, parentFrameId: -1, processId: webContents.getProcessId(), tabId: tabId, timeStamp: Date.now(), url: url }) }) webContents.on('did-navigate', (event, url) => { sendToBackgroundPages('CHROME_WEBNAVIGATION_ONCOMPLETED', { frameId: 0, parentFrameId: -1, processId: webContents.getProcessId(), tabId: tabId, timeStamp: Date.now(), url: url }) }) webContents.once('destroyed', () => { sendToBackgroundPages('CHROME_TABS_ONREMOVED', tabId) }) }
javascript
function (webContents) { const tabId = webContents.id sendToBackgroundPages('CHROME_TABS_ONCREATED') webContents.on('will-navigate', (event, url) => { sendToBackgroundPages('CHROME_WEBNAVIGATION_ONBEFORENAVIGATE', { frameId: 0, parentFrameId: -1, processId: webContents.getProcessId(), tabId: tabId, timeStamp: Date.now(), url: url }) }) webContents.on('did-navigate', (event, url) => { sendToBackgroundPages('CHROME_WEBNAVIGATION_ONCOMPLETED', { frameId: 0, parentFrameId: -1, processId: webContents.getProcessId(), tabId: tabId, timeStamp: Date.now(), url: url }) }) webContents.once('destroyed', () => { sendToBackgroundPages('CHROME_TABS_ONREMOVED', tabId) }) }
[ "function", "(", "webContents", ")", "{", "const", "tabId", "=", "webContents", ".", "id", "sendToBackgroundPages", "(", "'CHROME_TABS_ONCREATED'", ")", "webContents", ".", "on", "(", "'will-navigate'", ",", "(", "event", ",", "url", ")", "=>", "{", "sendToBackgroundPages", "(", "'CHROME_WEBNAVIGATION_ONBEFORENAVIGATE'", ",", "{", "frameId", ":", "0", ",", "parentFrameId", ":", "-", "1", ",", "processId", ":", "webContents", ".", "getProcessId", "(", ")", ",", "tabId", ":", "tabId", ",", "timeStamp", ":", "Date", ".", "now", "(", ")", ",", "url", ":", "url", "}", ")", "}", ")", "webContents", ".", "on", "(", "'did-navigate'", ",", "(", "event", ",", "url", ")", "=>", "{", "sendToBackgroundPages", "(", "'CHROME_WEBNAVIGATION_ONCOMPLETED'", ",", "{", "frameId", ":", "0", ",", "parentFrameId", ":", "-", "1", ",", "processId", ":", "webContents", ".", "getProcessId", "(", ")", ",", "tabId", ":", "tabId", ",", "timeStamp", ":", "Date", ".", "now", "(", ")", ",", "url", ":", "url", "}", ")", "}", ")", "webContents", ".", "once", "(", "'destroyed'", ",", "(", ")", "=>", "{", "sendToBackgroundPages", "(", "'CHROME_TABS_ONREMOVED'", ",", "tabId", ")", "}", ")", "}" ]
Dispatch web contents events to Chrome APIs
[ "Dispatch", "web", "contents", "events", "to", "Chrome", "APIs" ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/chrome-extension.js#L123-L153
train
electron/electron
lib/browser/chrome-extension.js
function (manifest) { return { startPage: manifest.startPage, srcDirectory: manifest.srcDirectory, name: manifest.name, exposeExperimentalAPIs: true } }
javascript
function (manifest) { return { startPage: manifest.startPage, srcDirectory: manifest.srcDirectory, name: manifest.name, exposeExperimentalAPIs: true } }
[ "function", "(", "manifest", ")", "{", "return", "{", "startPage", ":", "manifest", ".", "startPage", ",", "srcDirectory", ":", "manifest", ".", "srcDirectory", ",", "name", ":", "manifest", ".", "name", ",", "exposeExperimentalAPIs", ":", "true", "}", "}" ]
Transfer the |manifest| to a format that can be recognized by the |DevToolsAPI.addExtensions|.
[ "Transfer", "the", "|manifest|", "to", "a", "format", "that", "can", "be", "recognized", "by", "the", "|DevToolsAPI", ".", "addExtensions|", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/chrome-extension.js#L357-L364
train
electron/electron
lib/sandboxed_renderer/init.js
preloadRequire
function preloadRequire (module) { if (loadedModules.has(module)) { return loadedModules.get(module) } throw new Error(`module not found: ${module}`) }
javascript
function preloadRequire (module) { if (loadedModules.has(module)) { return loadedModules.get(module) } throw new Error(`module not found: ${module}`) }
[ "function", "preloadRequire", "(", "module", ")", "{", "if", "(", "loadedModules", ".", "has", "(", "module", ")", ")", "{", "return", "loadedModules", ".", "get", "(", "module", ")", "}", "throw", "new", "Error", "(", "`", "${", "module", "}", "`", ")", "}" ]
This is the `require` function that will be visible to the preload script
[ "This", "is", "the", "require", "function", "that", "will", "be", "visible", "to", "the", "preload", "script" ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/sandboxed_renderer/init.js#L99-L104
train
electron/electron
lib/browser/api/menu.js
generateGroupId
function generateGroupId (items, pos) { if (pos > 0) { for (let idx = pos - 1; idx >= 0; idx--) { if (items[idx].type === 'radio') return items[idx].groupId if (items[idx].type === 'separator') break } } else if (pos < items.length) { for (let idx = pos; idx <= items.length - 1; idx++) { if (items[idx].type === 'radio') return items[idx].groupId if (items[idx].type === 'separator') break } } groupIdIndex += 1 return groupIdIndex }
javascript
function generateGroupId (items, pos) { if (pos > 0) { for (let idx = pos - 1; idx >= 0; idx--) { if (items[idx].type === 'radio') return items[idx].groupId if (items[idx].type === 'separator') break } } else if (pos < items.length) { for (let idx = pos; idx <= items.length - 1; idx++) { if (items[idx].type === 'radio') return items[idx].groupId if (items[idx].type === 'separator') break } } groupIdIndex += 1 return groupIdIndex }
[ "function", "generateGroupId", "(", "items", ",", "pos", ")", "{", "if", "(", "pos", ">", "0", ")", "{", "for", "(", "let", "idx", "=", "pos", "-", "1", ";", "idx", ">=", "0", ";", "idx", "--", ")", "{", "if", "(", "items", "[", "idx", "]", ".", "type", "===", "'radio'", ")", "return", "items", "[", "idx", "]", ".", "groupId", "if", "(", "items", "[", "idx", "]", ".", "type", "===", "'separator'", ")", "break", "}", "}", "else", "if", "(", "pos", "<", "items", ".", "length", ")", "{", "for", "(", "let", "idx", "=", "pos", ";", "idx", "<=", "items", ".", "length", "-", "1", ";", "idx", "++", ")", "{", "if", "(", "items", "[", "idx", "]", ".", "type", "===", "'radio'", ")", "return", "items", "[", "idx", "]", ".", "groupId", "if", "(", "items", "[", "idx", "]", ".", "type", "===", "'separator'", ")", "break", "}", "}", "groupIdIndex", "+=", "1", "return", "groupIdIndex", "}" ]
Search between separators to find a radio menu item and return its group id
[ "Search", "between", "separators", "to", "find", "a", "radio", "menu", "item", "and", "return", "its", "group", "id" ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/api/menu.js#L213-L227
train
electron/electron
lib/browser/api/auto-updater/squirrel-update-win.js
function (args, detached, callback) { let error, errorEmitted, stderr, stdout try { // Ensure we don't spawn multiple squirrel processes // Process spawned, same args: Attach events to alread running process // Process spawned, different args: Return with error // No process spawned: Spawn new process if (spawnedProcess && !isSameArgs(args)) { // Disabled for backwards compatibility: // eslint-disable-next-line standard/no-callback-literal return callback(`AutoUpdater process with arguments ${args} is already running`) } else if (!spawnedProcess) { spawnedProcess = spawn(updateExe, args, { detached: detached, windowsHide: true }) spawnedArgs = args || [] } } catch (error1) { error = error1 // Shouldn't happen, but still guard it. process.nextTick(function () { return callback(error) }) return } stdout = '' stderr = '' spawnedProcess.stdout.on('data', (data) => { stdout += data }) spawnedProcess.stderr.on('data', (data) => { stderr += data }) errorEmitted = false spawnedProcess.on('error', (error) => { errorEmitted = true callback(error) }) return spawnedProcess.on('exit', function (code, signal) { spawnedProcess = undefined spawnedArgs = [] // We may have already emitted an error. if (errorEmitted) { return } // Process terminated with error. if (code !== 0) { // Disabled for backwards compatibility: // eslint-disable-next-line standard/no-callback-literal return callback(`Command failed: ${signal != null ? signal : code}\n${stderr}`) } // Success. callback(null, stdout) }) }
javascript
function (args, detached, callback) { let error, errorEmitted, stderr, stdout try { // Ensure we don't spawn multiple squirrel processes // Process spawned, same args: Attach events to alread running process // Process spawned, different args: Return with error // No process spawned: Spawn new process if (spawnedProcess && !isSameArgs(args)) { // Disabled for backwards compatibility: // eslint-disable-next-line standard/no-callback-literal return callback(`AutoUpdater process with arguments ${args} is already running`) } else if (!spawnedProcess) { spawnedProcess = spawn(updateExe, args, { detached: detached, windowsHide: true }) spawnedArgs = args || [] } } catch (error1) { error = error1 // Shouldn't happen, but still guard it. process.nextTick(function () { return callback(error) }) return } stdout = '' stderr = '' spawnedProcess.stdout.on('data', (data) => { stdout += data }) spawnedProcess.stderr.on('data', (data) => { stderr += data }) errorEmitted = false spawnedProcess.on('error', (error) => { errorEmitted = true callback(error) }) return spawnedProcess.on('exit', function (code, signal) { spawnedProcess = undefined spawnedArgs = [] // We may have already emitted an error. if (errorEmitted) { return } // Process terminated with error. if (code !== 0) { // Disabled for backwards compatibility: // eslint-disable-next-line standard/no-callback-literal return callback(`Command failed: ${signal != null ? signal : code}\n${stderr}`) } // Success. callback(null, stdout) }) }
[ "function", "(", "args", ",", "detached", ",", "callback", ")", "{", "let", "error", ",", "errorEmitted", ",", "stderr", ",", "stdout", "try", "{", "if", "(", "spawnedProcess", "&&", "!", "isSameArgs", "(", "args", ")", ")", "{", "return", "callback", "(", "`", "${", "args", "}", "`", ")", "}", "else", "if", "(", "!", "spawnedProcess", ")", "{", "spawnedProcess", "=", "spawn", "(", "updateExe", ",", "args", ",", "{", "detached", ":", "detached", ",", "windowsHide", ":", "true", "}", ")", "spawnedArgs", "=", "args", "||", "[", "]", "}", "}", "catch", "(", "error1", ")", "{", "error", "=", "error1", "process", ".", "nextTick", "(", "function", "(", ")", "{", "return", "callback", "(", "error", ")", "}", ")", "return", "}", "stdout", "=", "''", "stderr", "=", "''", "spawnedProcess", ".", "stdout", ".", "on", "(", "'data'", ",", "(", "data", ")", "=>", "{", "stdout", "+=", "data", "}", ")", "spawnedProcess", ".", "stderr", ".", "on", "(", "'data'", ",", "(", "data", ")", "=>", "{", "stderr", "+=", "data", "}", ")", "errorEmitted", "=", "false", "spawnedProcess", ".", "on", "(", "'error'", ",", "(", "error", ")", "=>", "{", "errorEmitted", "=", "true", "callback", "(", "error", ")", "}", ")", "return", "spawnedProcess", ".", "on", "(", "'exit'", ",", "function", "(", "code", ",", "signal", ")", "{", "spawnedProcess", "=", "undefined", "spawnedArgs", "=", "[", "]", "if", "(", "errorEmitted", ")", "{", "return", "}", "if", "(", "code", "!==", "0", ")", "{", "return", "callback", "(", "`", "${", "signal", "!=", "null", "?", "signal", ":", "code", "}", "\\n", "${", "stderr", "}", "`", ")", "}", "callback", "(", "null", ",", "stdout", ")", "}", ")", "}" ]
Spawn a command and invoke the callback when it completes with an error and the output from standard out.
[ "Spawn", "a", "command", "and", "invoke", "the", "callback", "when", "it", "completes", "with", "an", "error", "and", "the", "output", "from", "standard", "out", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/api/auto-updater/squirrel-update-win.js#L20-L79
train
electron/electron
lib/browser/api/menu-utils.js
sortTopologically
function sortTopologically (originalOrder, edgesById) { const sorted = [] const marked = new Set() const visit = (mark) => { if (marked.has(mark)) return marked.add(mark) const edges = edgesById.get(mark) if (edges != null) { edges.forEach(visit) } sorted.push(mark) } originalOrder.forEach(visit) return sorted }
javascript
function sortTopologically (originalOrder, edgesById) { const sorted = [] const marked = new Set() const visit = (mark) => { if (marked.has(mark)) return marked.add(mark) const edges = edgesById.get(mark) if (edges != null) { edges.forEach(visit) } sorted.push(mark) } originalOrder.forEach(visit) return sorted }
[ "function", "sortTopologically", "(", "originalOrder", ",", "edgesById", ")", "{", "const", "sorted", "=", "[", "]", "const", "marked", "=", "new", "Set", "(", ")", "const", "visit", "=", "(", "mark", ")", "=>", "{", "if", "(", "marked", ".", "has", "(", "mark", ")", ")", "return", "marked", ".", "add", "(", "mark", ")", "const", "edges", "=", "edgesById", ".", "get", "(", "mark", ")", "if", "(", "edges", "!=", "null", ")", "{", "edges", ".", "forEach", "(", "visit", ")", "}", "sorted", ".", "push", "(", "mark", ")", "}", "originalOrder", ".", "forEach", "(", "visit", ")", "return", "sorted", "}" ]
Sort nodes topologically using a depth-first approach. Encountered cycles are broken.
[ "Sort", "nodes", "topologically", "using", "a", "depth", "-", "first", "approach", ".", "Encountered", "cycles", "are", "broken", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/api/menu-utils.js#L53-L69
train
electron/electron
lib/browser/rpc-server.js
function (object) { const proto = Object.getPrototypeOf(object) if (proto === null || proto === Object.prototype) return null return { members: getObjectMembers(proto), proto: getObjectPrototype(proto) } }
javascript
function (object) { const proto = Object.getPrototypeOf(object) if (proto === null || proto === Object.prototype) return null return { members: getObjectMembers(proto), proto: getObjectPrototype(proto) } }
[ "function", "(", "object", ")", "{", "const", "proto", "=", "Object", ".", "getPrototypeOf", "(", "object", ")", "if", "(", "proto", "===", "null", "||", "proto", "===", "Object", ".", "prototype", ")", "return", "null", "return", "{", "members", ":", "getObjectMembers", "(", "proto", ")", ",", "proto", ":", "getObjectPrototype", "(", "proto", ")", "}", "}" ]
Return the description of object's prototype.
[ "Return", "the", "description", "of", "object", "s", "prototype", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/rpc-server.js#L61-L68
train
electron/electron
lib/browser/rpc-server.js
function (sender, contextId, value, optimizeSimpleObject = false) { // Determine the type of value. const meta = { type: typeof value } if (meta.type === 'object') { // Recognize certain types of objects. if (value === null) { meta.type = 'value' } else if (bufferUtils.isBuffer(value)) { meta.type = 'buffer' } else if (Array.isArray(value)) { meta.type = 'array' } else if (value instanceof Error) { meta.type = 'error' } else if (value instanceof Date) { meta.type = 'date' } else if (isPromise(value)) { meta.type = 'promise' } else if (hasProp.call(value, 'callee') && value.length != null) { // Treat the arguments object as array. meta.type = 'array' } else if (optimizeSimpleObject && v8Util.getHiddenValue(value, 'simple')) { // Treat simple objects as value. meta.type = 'value' } } // Fill the meta object according to value's type. if (meta.type === 'array') { meta.members = value.map((el) => valueToMeta(sender, contextId, el, optimizeSimpleObject)) } else if (meta.type === 'object' || meta.type === 'function') { meta.name = value.constructor ? value.constructor.name : '' // Reference the original value if it's an object, because when it's // passed to renderer we would assume the renderer keeps a reference of // it. meta.id = objectsRegistry.add(sender, contextId, value) meta.members = getObjectMembers(value) meta.proto = getObjectPrototype(value) } else if (meta.type === 'buffer') { meta.value = bufferUtils.bufferToMeta(value) } else if (meta.type === 'promise') { // Add default handler to prevent unhandled rejections in main process // Instead they should appear in the renderer process value.then(function () {}, function () {}) meta.then = valueToMeta(sender, contextId, function (onFulfilled, onRejected) { value.then(onFulfilled, onRejected) }) } else if (meta.type === 'error') { meta.members = plainObjectToMeta(value) // Error.name is not part of own properties. meta.members.push({ name: 'name', value: value.name }) } else if (meta.type === 'date') { meta.value = value.getTime() } else { meta.type = 'value' meta.value = value } return meta }
javascript
function (sender, contextId, value, optimizeSimpleObject = false) { // Determine the type of value. const meta = { type: typeof value } if (meta.type === 'object') { // Recognize certain types of objects. if (value === null) { meta.type = 'value' } else if (bufferUtils.isBuffer(value)) { meta.type = 'buffer' } else if (Array.isArray(value)) { meta.type = 'array' } else if (value instanceof Error) { meta.type = 'error' } else if (value instanceof Date) { meta.type = 'date' } else if (isPromise(value)) { meta.type = 'promise' } else if (hasProp.call(value, 'callee') && value.length != null) { // Treat the arguments object as array. meta.type = 'array' } else if (optimizeSimpleObject && v8Util.getHiddenValue(value, 'simple')) { // Treat simple objects as value. meta.type = 'value' } } // Fill the meta object according to value's type. if (meta.type === 'array') { meta.members = value.map((el) => valueToMeta(sender, contextId, el, optimizeSimpleObject)) } else if (meta.type === 'object' || meta.type === 'function') { meta.name = value.constructor ? value.constructor.name : '' // Reference the original value if it's an object, because when it's // passed to renderer we would assume the renderer keeps a reference of // it. meta.id = objectsRegistry.add(sender, contextId, value) meta.members = getObjectMembers(value) meta.proto = getObjectPrototype(value) } else if (meta.type === 'buffer') { meta.value = bufferUtils.bufferToMeta(value) } else if (meta.type === 'promise') { // Add default handler to prevent unhandled rejections in main process // Instead they should appear in the renderer process value.then(function () {}, function () {}) meta.then = valueToMeta(sender, contextId, function (onFulfilled, onRejected) { value.then(onFulfilled, onRejected) }) } else if (meta.type === 'error') { meta.members = plainObjectToMeta(value) // Error.name is not part of own properties. meta.members.push({ name: 'name', value: value.name }) } else if (meta.type === 'date') { meta.value = value.getTime() } else { meta.type = 'value' meta.value = value } return meta }
[ "function", "(", "sender", ",", "contextId", ",", "value", ",", "optimizeSimpleObject", "=", "false", ")", "{", "const", "meta", "=", "{", "type", ":", "typeof", "value", "}", "if", "(", "meta", ".", "type", "===", "'object'", ")", "{", "if", "(", "value", "===", "null", ")", "{", "meta", ".", "type", "=", "'value'", "}", "else", "if", "(", "bufferUtils", ".", "isBuffer", "(", "value", ")", ")", "{", "meta", ".", "type", "=", "'buffer'", "}", "else", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "meta", ".", "type", "=", "'array'", "}", "else", "if", "(", "value", "instanceof", "Error", ")", "{", "meta", ".", "type", "=", "'error'", "}", "else", "if", "(", "value", "instanceof", "Date", ")", "{", "meta", ".", "type", "=", "'date'", "}", "else", "if", "(", "isPromise", "(", "value", ")", ")", "{", "meta", ".", "type", "=", "'promise'", "}", "else", "if", "(", "hasProp", ".", "call", "(", "value", ",", "'callee'", ")", "&&", "value", ".", "length", "!=", "null", ")", "{", "meta", ".", "type", "=", "'array'", "}", "else", "if", "(", "optimizeSimpleObject", "&&", "v8Util", ".", "getHiddenValue", "(", "value", ",", "'simple'", ")", ")", "{", "meta", ".", "type", "=", "'value'", "}", "}", "if", "(", "meta", ".", "type", "===", "'array'", ")", "{", "meta", ".", "members", "=", "value", ".", "map", "(", "(", "el", ")", "=>", "valueToMeta", "(", "sender", ",", "contextId", ",", "el", ",", "optimizeSimpleObject", ")", ")", "}", "else", "if", "(", "meta", ".", "type", "===", "'object'", "||", "meta", ".", "type", "===", "'function'", ")", "{", "meta", ".", "name", "=", "value", ".", "constructor", "?", "value", ".", "constructor", ".", "name", ":", "''", "meta", ".", "id", "=", "objectsRegistry", ".", "add", "(", "sender", ",", "contextId", ",", "value", ")", "meta", ".", "members", "=", "getObjectMembers", "(", "value", ")", "meta", ".", "proto", "=", "getObjectPrototype", "(", "value", ")", "}", "else", "if", "(", "meta", ".", "type", "===", "'buffer'", ")", "{", "meta", ".", "value", "=", "bufferUtils", ".", "bufferToMeta", "(", "value", ")", "}", "else", "if", "(", "meta", ".", "type", "===", "'promise'", ")", "{", "value", ".", "then", "(", "function", "(", ")", "{", "}", ",", "function", "(", ")", "{", "}", ")", "meta", ".", "then", "=", "valueToMeta", "(", "sender", ",", "contextId", ",", "function", "(", "onFulfilled", ",", "onRejected", ")", "{", "value", ".", "then", "(", "onFulfilled", ",", "onRejected", ")", "}", ")", "}", "else", "if", "(", "meta", ".", "type", "===", "'error'", ")", "{", "meta", ".", "members", "=", "plainObjectToMeta", "(", "value", ")", "meta", ".", "members", ".", "push", "(", "{", "name", ":", "'name'", ",", "value", ":", "value", ".", "name", "}", ")", "}", "else", "if", "(", "meta", ".", "type", "===", "'date'", ")", "{", "meta", ".", "value", "=", "value", ".", "getTime", "(", ")", "}", "else", "{", "meta", ".", "type", "=", "'value'", "meta", ".", "value", "=", "value", "}", "return", "meta", "}" ]
Convert a real value into meta data.
[ "Convert", "a", "real", "value", "into", "meta", "data", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/rpc-server.js#L71-L134
train
electron/electron
lib/browser/rpc-server.js
function (obj) { return Object.getOwnPropertyNames(obj).map(function (name) { return { name: name, value: obj[name] } }) }
javascript
function (obj) { return Object.getOwnPropertyNames(obj).map(function (name) { return { name: name, value: obj[name] } }) }
[ "function", "(", "obj", ")", "{", "return", "Object", ".", "getOwnPropertyNames", "(", "obj", ")", ".", "map", "(", "function", "(", "name", ")", "{", "return", "{", "name", ":", "name", ",", "value", ":", "obj", "[", "name", "]", "}", "}", ")", "}" ]
Convert object to meta by value.
[ "Convert", "object", "to", "meta", "by", "value", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/rpc-server.js#L137-L144
train
electron/electron
lib/browser/rpc-server.js
function (sender, frameId, contextId, args) { const metaToValue = function (meta) { switch (meta.type) { case 'value': return meta.value case 'remote-object': return objectsRegistry.get(meta.id) case 'array': return unwrapArgs(sender, frameId, contextId, meta.value) case 'buffer': return bufferUtils.metaToBuffer(meta.value) case 'date': return new Date(meta.value) case 'promise': return Promise.resolve({ then: metaToValue(meta.then) }) case 'object': { const ret = {} Object.defineProperty(ret.constructor, 'name', { value: meta.name }) for (const { name, value } of meta.members) { ret[name] = metaToValue(value) } return ret } case 'function-with-return-value': const returnValue = metaToValue(meta.value) return function () { return returnValue } case 'function': { // Merge contextId and meta.id, since meta.id can be the same in // different webContents. const objectId = [contextId, meta.id] // Cache the callbacks in renderer. if (rendererFunctions.has(objectId)) { return rendererFunctions.get(objectId) } const callIntoRenderer = function (...args) { let succeed = false if (!sender.isDestroyed()) { succeed = sender._sendToFrameInternal(frameId, 'ELECTRON_RENDERER_CALLBACK', contextId, meta.id, valueToMeta(sender, contextId, args)) } if (!succeed) { removeRemoteListenersAndLogWarning(this, callIntoRenderer) } } v8Util.setHiddenValue(callIntoRenderer, 'location', meta.location) Object.defineProperty(callIntoRenderer, 'length', { value: meta.length }) v8Util.setRemoteCallbackFreer(callIntoRenderer, contextId, meta.id, sender) rendererFunctions.set(objectId, callIntoRenderer) return callIntoRenderer } default: throw new TypeError(`Unknown type: ${meta.type}`) } } return args.map(metaToValue) }
javascript
function (sender, frameId, contextId, args) { const metaToValue = function (meta) { switch (meta.type) { case 'value': return meta.value case 'remote-object': return objectsRegistry.get(meta.id) case 'array': return unwrapArgs(sender, frameId, contextId, meta.value) case 'buffer': return bufferUtils.metaToBuffer(meta.value) case 'date': return new Date(meta.value) case 'promise': return Promise.resolve({ then: metaToValue(meta.then) }) case 'object': { const ret = {} Object.defineProperty(ret.constructor, 'name', { value: meta.name }) for (const { name, value } of meta.members) { ret[name] = metaToValue(value) } return ret } case 'function-with-return-value': const returnValue = metaToValue(meta.value) return function () { return returnValue } case 'function': { // Merge contextId and meta.id, since meta.id can be the same in // different webContents. const objectId = [contextId, meta.id] // Cache the callbacks in renderer. if (rendererFunctions.has(objectId)) { return rendererFunctions.get(objectId) } const callIntoRenderer = function (...args) { let succeed = false if (!sender.isDestroyed()) { succeed = sender._sendToFrameInternal(frameId, 'ELECTRON_RENDERER_CALLBACK', contextId, meta.id, valueToMeta(sender, contextId, args)) } if (!succeed) { removeRemoteListenersAndLogWarning(this, callIntoRenderer) } } v8Util.setHiddenValue(callIntoRenderer, 'location', meta.location) Object.defineProperty(callIntoRenderer, 'length', { value: meta.length }) v8Util.setRemoteCallbackFreer(callIntoRenderer, contextId, meta.id, sender) rendererFunctions.set(objectId, callIntoRenderer) return callIntoRenderer } default: throw new TypeError(`Unknown type: ${meta.type}`) } } return args.map(metaToValue) }
[ "function", "(", "sender", ",", "frameId", ",", "contextId", ",", "args", ")", "{", "const", "metaToValue", "=", "function", "(", "meta", ")", "{", "switch", "(", "meta", ".", "type", ")", "{", "case", "'value'", ":", "return", "meta", ".", "value", "case", "'remote-object'", ":", "return", "objectsRegistry", ".", "get", "(", "meta", ".", "id", ")", "case", "'array'", ":", "return", "unwrapArgs", "(", "sender", ",", "frameId", ",", "contextId", ",", "meta", ".", "value", ")", "case", "'buffer'", ":", "return", "bufferUtils", ".", "metaToBuffer", "(", "meta", ".", "value", ")", "case", "'date'", ":", "return", "new", "Date", "(", "meta", ".", "value", ")", "case", "'promise'", ":", "return", "Promise", ".", "resolve", "(", "{", "then", ":", "metaToValue", "(", "meta", ".", "then", ")", "}", ")", "case", "'object'", ":", "{", "const", "ret", "=", "{", "}", "Object", ".", "defineProperty", "(", "ret", ".", "constructor", ",", "'name'", ",", "{", "value", ":", "meta", ".", "name", "}", ")", "for", "(", "const", "{", "name", ",", "value", "}", "of", "meta", ".", "members", ")", "{", "ret", "[", "name", "]", "=", "metaToValue", "(", "value", ")", "}", "return", "ret", "}", "case", "'function-with-return-value'", ":", "const", "returnValue", "=", "metaToValue", "(", "meta", ".", "value", ")", "return", "function", "(", ")", "{", "return", "returnValue", "}", "case", "'function'", ":", "{", "const", "objectId", "=", "[", "contextId", ",", "meta", ".", "id", "]", "if", "(", "rendererFunctions", ".", "has", "(", "objectId", ")", ")", "{", "return", "rendererFunctions", ".", "get", "(", "objectId", ")", "}", "const", "callIntoRenderer", "=", "function", "(", "...", "args", ")", "{", "let", "succeed", "=", "false", "if", "(", "!", "sender", ".", "isDestroyed", "(", ")", ")", "{", "succeed", "=", "sender", ".", "_sendToFrameInternal", "(", "frameId", ",", "'ELECTRON_RENDERER_CALLBACK'", ",", "contextId", ",", "meta", ".", "id", ",", "valueToMeta", "(", "sender", ",", "contextId", ",", "args", ")", ")", "}", "if", "(", "!", "succeed", ")", "{", "removeRemoteListenersAndLogWarning", "(", "this", ",", "callIntoRenderer", ")", "}", "}", "v8Util", ".", "setHiddenValue", "(", "callIntoRenderer", ",", "'location'", ",", "meta", ".", "location", ")", "Object", ".", "defineProperty", "(", "callIntoRenderer", ",", "'length'", ",", "{", "value", ":", "meta", ".", "length", "}", ")", "v8Util", ".", "setRemoteCallbackFreer", "(", "callIntoRenderer", ",", "contextId", ",", "meta", ".", "id", ",", "sender", ")", "rendererFunctions", ".", "set", "(", "objectId", ",", "callIntoRenderer", ")", "return", "callIntoRenderer", "}", "default", ":", "throw", "new", "TypeError", "(", "`", "${", "meta", ".", "type", "}", "`", ")", "}", "}", "return", "args", ".", "map", "(", "metaToValue", ")", "}" ]
Convert array of meta data from renderer into array of real values.
[ "Convert", "array", "of", "meta", "data", "from", "renderer", "into", "array", "of", "real", "values", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/rpc-server.js#L183-L245
train
electron/electron
lib/renderer/api/desktop-capturer.js
isValid
function isValid (options) { const types = options ? options.types : undefined return Array.isArray(types) }
javascript
function isValid (options) { const types = options ? options.types : undefined return Array.isArray(types) }
[ "function", "isValid", "(", "options", ")", "{", "const", "types", "=", "options", "?", "options", ".", "types", ":", "undefined", "return", "Array", ".", "isArray", "(", "types", ")", "}" ]
|options.types| can't be empty and must be an array
[ "|options", ".", "types|", "can", "t", "be", "empty", "and", "must", "be", "an", "array" ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/renderer/api/desktop-capturer.js#L7-L10
train
electron/electron
script/bump-version.js
updateVersion
async function updateVersion (version) { const versionPath = path.resolve(__dirname, '..', 'ELECTRON_VERSION') await writeFile(versionPath, version, 'utf8') }
javascript
async function updateVersion (version) { const versionPath = path.resolve(__dirname, '..', 'ELECTRON_VERSION') await writeFile(versionPath, version, 'utf8') }
[ "async", "function", "updateVersion", "(", "version", ")", "{", "const", "versionPath", "=", "path", ".", "resolve", "(", "__dirname", ",", "'..'", ",", "'ELECTRON_VERSION'", ")", "await", "writeFile", "(", "versionPath", ",", "version", ",", "'utf8'", ")", "}" ]
update VERSION file with latest release info
[ "update", "VERSION", "file", "with", "latest", "release", "info" ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/script/bump-version.js#L107-L110
train
electron/electron
script/bump-version.js
updatePackageJSON
async function updatePackageJSON (version) { ['package.json'].forEach(async fileName => { const filePath = path.resolve(__dirname, '..', fileName) const file = require(filePath) file.version = version await writeFile(filePath, JSON.stringify(file, null, 2)) }) }
javascript
async function updatePackageJSON (version) { ['package.json'].forEach(async fileName => { const filePath = path.resolve(__dirname, '..', fileName) const file = require(filePath) file.version = version await writeFile(filePath, JSON.stringify(file, null, 2)) }) }
[ "async", "function", "updatePackageJSON", "(", "version", ")", "{", "[", "'package.json'", "]", ".", "forEach", "(", "async", "fileName", "=>", "{", "const", "filePath", "=", "path", ".", "resolve", "(", "__dirname", ",", "'..'", ",", "fileName", ")", "const", "file", "=", "require", "(", "filePath", ")", "file", ".", "version", "=", "version", "await", "writeFile", "(", "filePath", ",", "JSON", ".", "stringify", "(", "file", ",", "null", ",", "2", ")", ")", "}", ")", "}" ]
update package metadata files with new version
[ "update", "package", "metadata", "files", "with", "new", "version" ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/script/bump-version.js#L113-L120
train
electron/electron
script/bump-version.js
commitVersionBump
async function commitVersionBump (version) { const gitDir = path.resolve(__dirname, '..') const gitArgs = ['commit', '-a', '-m', `Bump v${version}`, '-n'] await GitProcess.exec(gitArgs, gitDir) }
javascript
async function commitVersionBump (version) { const gitDir = path.resolve(__dirname, '..') const gitArgs = ['commit', '-a', '-m', `Bump v${version}`, '-n'] await GitProcess.exec(gitArgs, gitDir) }
[ "async", "function", "commitVersionBump", "(", "version", ")", "{", "const", "gitDir", "=", "path", ".", "resolve", "(", "__dirname", ",", "'..'", ")", "const", "gitArgs", "=", "[", "'commit'", ",", "'-a'", ",", "'-m'", ",", "`", "${", "version", "}", "`", ",", "'-n'", "]", "await", "GitProcess", ".", "exec", "(", "gitArgs", ",", "gitDir", ")", "}" ]
push bump commit to release branch
[ "push", "bump", "commit", "to", "release", "branch" ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/script/bump-version.js#L135-L139
train
electron/electron
script/bump-version.js
updateWinRC
async function updateWinRC (components) { const filePath = path.resolve(__dirname, '..', 'atom', 'browser', 'resources', 'win', 'atom.rc') const data = await readFile(filePath, 'utf8') const arr = data.split('\n') arr.forEach((line, idx) => { if (line.includes('FILEVERSION')) { arr[idx] = ` FILEVERSION ${utils.makeVersion(components, ',', utils.preType.PARTIAL)}` arr[idx + 1] = ` PRODUCTVERSION ${utils.makeVersion(components, ',', utils.preType.PARTIAL)}` } else if (line.includes('FileVersion')) { arr[idx] = ` VALUE "FileVersion", "${utils.makeVersion(components, '.')}"` arr[idx + 5] = ` VALUE "ProductVersion", "${utils.makeVersion(components, '.')}"` } }) await writeFile(filePath, arr.join('\n')) }
javascript
async function updateWinRC (components) { const filePath = path.resolve(__dirname, '..', 'atom', 'browser', 'resources', 'win', 'atom.rc') const data = await readFile(filePath, 'utf8') const arr = data.split('\n') arr.forEach((line, idx) => { if (line.includes('FILEVERSION')) { arr[idx] = ` FILEVERSION ${utils.makeVersion(components, ',', utils.preType.PARTIAL)}` arr[idx + 1] = ` PRODUCTVERSION ${utils.makeVersion(components, ',', utils.preType.PARTIAL)}` } else if (line.includes('FileVersion')) { arr[idx] = ` VALUE "FileVersion", "${utils.makeVersion(components, '.')}"` arr[idx + 5] = ` VALUE "ProductVersion", "${utils.makeVersion(components, '.')}"` } }) await writeFile(filePath, arr.join('\n')) }
[ "async", "function", "updateWinRC", "(", "components", ")", "{", "const", "filePath", "=", "path", ".", "resolve", "(", "__dirname", ",", "'..'", ",", "'atom'", ",", "'browser'", ",", "'resources'", ",", "'win'", ",", "'atom.rc'", ")", "const", "data", "=", "await", "readFile", "(", "filePath", ",", "'utf8'", ")", "const", "arr", "=", "data", ".", "split", "(", "'\\n'", ")", "\\n", "arr", ".", "forEach", "(", "(", "line", ",", "idx", ")", "=>", "{", "if", "(", "line", ".", "includes", "(", "'FILEVERSION'", ")", ")", "{", "arr", "[", "idx", "]", "=", "`", "${", "utils", ".", "makeVersion", "(", "components", ",", "','", ",", "utils", ".", "preType", ".", "PARTIAL", ")", "}", "`", "arr", "[", "idx", "+", "1", "]", "=", "`", "${", "utils", ".", "makeVersion", "(", "components", ",", "','", ",", "utils", ".", "preType", ".", "PARTIAL", ")", "}", "`", "}", "else", "if", "(", "line", ".", "includes", "(", "'FileVersion'", ")", ")", "{", "arr", "[", "idx", "]", "=", "`", "${", "utils", ".", "makeVersion", "(", "components", ",", "'.'", ")", "}", "`", "arr", "[", "idx", "+", "5", "]", "=", "`", "${", "utils", ".", "makeVersion", "(", "components", ",", "'.'", ")", "}", "`", "}", "}", ")", "}" ]
updates atom.rc file with new semver values
[ "updates", "atom", ".", "rc", "file", "with", "new", "semver", "values" ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/script/bump-version.js#L161-L175
train
electron/electron
lib/browser/guest-window-manager.js
function (child, parent, visited) { // Check for circular reference. if (visited == null) visited = new Set() if (visited.has(parent)) return visited.add(parent) for (const key in parent) { if (key === 'isBrowserView') continue if (!hasProp.call(parent, key)) continue if (key in child && key !== 'webPreferences') continue const value = parent[key] if (typeof value === 'object') { child[key] = mergeOptions(child[key] || {}, value, visited) } else { child[key] = value } } visited.delete(parent) return child }
javascript
function (child, parent, visited) { // Check for circular reference. if (visited == null) visited = new Set() if (visited.has(parent)) return visited.add(parent) for (const key in parent) { if (key === 'isBrowserView') continue if (!hasProp.call(parent, key)) continue if (key in child && key !== 'webPreferences') continue const value = parent[key] if (typeof value === 'object') { child[key] = mergeOptions(child[key] || {}, value, visited) } else { child[key] = value } } visited.delete(parent) return child }
[ "function", "(", "child", ",", "parent", ",", "visited", ")", "{", "if", "(", "visited", "==", "null", ")", "visited", "=", "new", "Set", "(", ")", "if", "(", "visited", ".", "has", "(", "parent", ")", ")", "return", "visited", ".", "add", "(", "parent", ")", "for", "(", "const", "key", "in", "parent", ")", "{", "if", "(", "key", "===", "'isBrowserView'", ")", "continue", "if", "(", "!", "hasProp", ".", "call", "(", "parent", ",", "key", ")", ")", "continue", "if", "(", "key", "in", "child", "&&", "key", "!==", "'webPreferences'", ")", "continue", "const", "value", "=", "parent", "[", "key", "]", "if", "(", "typeof", "value", "===", "'object'", ")", "{", "child", "[", "key", "]", "=", "mergeOptions", "(", "child", "[", "key", "]", "||", "{", "}", ",", "value", ",", "visited", ")", "}", "else", "{", "child", "[", "key", "]", "=", "value", "}", "}", "visited", ".", "delete", "(", "parent", ")", "return", "child", "}" ]
Copy attribute of |parent| to |child| if it is not defined in |child|.
[ "Copy", "attribute", "of", "|parent|", "to", "|child|", "if", "it", "is", "not", "defined", "in", "|child|", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/guest-window-manager.js#L24-L45
train
electron/electron
lib/browser/guest-window-manager.js
function (embedder, options) { if (options.webPreferences == null) { options.webPreferences = {} } if (embedder.browserWindowOptions != null) { let parentOptions = embedder.browserWindowOptions // if parent's visibility is available, that overrides 'show' flag (#12125) const win = BrowserWindow.fromWebContents(embedder.webContents) if (win != null) { parentOptions = { ...embedder.browserWindowOptions, show: win.isVisible() } } // Inherit the original options if it is a BrowserWindow. mergeOptions(options, parentOptions) } else { // Or only inherit webPreferences if it is a webview. mergeOptions(options.webPreferences, embedder.getLastWebPreferences()) } // Inherit certain option values from parent window const webPreferences = embedder.getLastWebPreferences() for (const [name, value] of inheritedWebPreferences) { if (webPreferences[name] === value) { options.webPreferences[name] = value } } // Sets correct openerId here to give correct options to 'new-window' event handler options.webPreferences.openerId = embedder.id return options }
javascript
function (embedder, options) { if (options.webPreferences == null) { options.webPreferences = {} } if (embedder.browserWindowOptions != null) { let parentOptions = embedder.browserWindowOptions // if parent's visibility is available, that overrides 'show' flag (#12125) const win = BrowserWindow.fromWebContents(embedder.webContents) if (win != null) { parentOptions = { ...embedder.browserWindowOptions, show: win.isVisible() } } // Inherit the original options if it is a BrowserWindow. mergeOptions(options, parentOptions) } else { // Or only inherit webPreferences if it is a webview. mergeOptions(options.webPreferences, embedder.getLastWebPreferences()) } // Inherit certain option values from parent window const webPreferences = embedder.getLastWebPreferences() for (const [name, value] of inheritedWebPreferences) { if (webPreferences[name] === value) { options.webPreferences[name] = value } } // Sets correct openerId here to give correct options to 'new-window' event handler options.webPreferences.openerId = embedder.id return options }
[ "function", "(", "embedder", ",", "options", ")", "{", "if", "(", "options", ".", "webPreferences", "==", "null", ")", "{", "options", ".", "webPreferences", "=", "{", "}", "}", "if", "(", "embedder", ".", "browserWindowOptions", "!=", "null", ")", "{", "let", "parentOptions", "=", "embedder", ".", "browserWindowOptions", "const", "win", "=", "BrowserWindow", ".", "fromWebContents", "(", "embedder", ".", "webContents", ")", "if", "(", "win", "!=", "null", ")", "{", "parentOptions", "=", "{", "...", "embedder", ".", "browserWindowOptions", ",", "show", ":", "win", ".", "isVisible", "(", ")", "}", "}", "mergeOptions", "(", "options", ",", "parentOptions", ")", "}", "else", "{", "mergeOptions", "(", "options", ".", "webPreferences", ",", "embedder", ".", "getLastWebPreferences", "(", ")", ")", "}", "const", "webPreferences", "=", "embedder", ".", "getLastWebPreferences", "(", ")", "for", "(", "const", "[", "name", ",", "value", "]", "of", "inheritedWebPreferences", ")", "{", "if", "(", "webPreferences", "[", "name", "]", "===", "value", ")", "{", "options", ".", "webPreferences", "[", "name", "]", "=", "value", "}", "}", "options", ".", "webPreferences", ".", "openerId", "=", "embedder", ".", "id", "return", "options", "}" ]
Merge |options| with the |embedder|'s window's options.
[ "Merge", "|options|", "with", "the", "|embedder|", "s", "window", "s", "options", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/guest-window-manager.js#L48-L80
train
electron/electron
lib/browser/guest-window-manager.js
function (embedder, frameName, guest, options) { // When |embedder| is destroyed we should also destroy attached guest, and if // guest is closed by user then we should prevent |embedder| from double // closing guest. const guestId = guest.webContents.id const closedByEmbedder = function () { guest.removeListener('closed', closedByUser) guest.destroy() } const closedByUser = function () { embedder._sendInternal('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_' + guestId) embedder.removeListener('current-render-view-deleted', closedByEmbedder) } embedder.once('current-render-view-deleted', closedByEmbedder) guest.once('closed', closedByUser) if (frameName) { frameToGuest.set(frameName, guest) guest.frameName = frameName guest.once('closed', function () { frameToGuest.delete(frameName) }) } return guestId }
javascript
function (embedder, frameName, guest, options) { // When |embedder| is destroyed we should also destroy attached guest, and if // guest is closed by user then we should prevent |embedder| from double // closing guest. const guestId = guest.webContents.id const closedByEmbedder = function () { guest.removeListener('closed', closedByUser) guest.destroy() } const closedByUser = function () { embedder._sendInternal('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_' + guestId) embedder.removeListener('current-render-view-deleted', closedByEmbedder) } embedder.once('current-render-view-deleted', closedByEmbedder) guest.once('closed', closedByUser) if (frameName) { frameToGuest.set(frameName, guest) guest.frameName = frameName guest.once('closed', function () { frameToGuest.delete(frameName) }) } return guestId }
[ "function", "(", "embedder", ",", "frameName", ",", "guest", ",", "options", ")", "{", "const", "guestId", "=", "guest", ".", "webContents", ".", "id", "const", "closedByEmbedder", "=", "function", "(", ")", "{", "guest", ".", "removeListener", "(", "'closed'", ",", "closedByUser", ")", "guest", ".", "destroy", "(", ")", "}", "const", "closedByUser", "=", "function", "(", ")", "{", "embedder", ".", "_sendInternal", "(", "'ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_'", "+", "guestId", ")", "embedder", ".", "removeListener", "(", "'current-render-view-deleted'", ",", "closedByEmbedder", ")", "}", "embedder", ".", "once", "(", "'current-render-view-deleted'", ",", "closedByEmbedder", ")", "guest", ".", "once", "(", "'closed'", ",", "closedByUser", ")", "if", "(", "frameName", ")", "{", "frameToGuest", ".", "set", "(", "frameName", ",", "guest", ")", "guest", ".", "frameName", "=", "frameName", "guest", ".", "once", "(", "'closed'", ",", "function", "(", ")", "{", "frameToGuest", ".", "delete", "(", "frameName", ")", "}", ")", "}", "return", "guestId", "}" ]
Setup a new guest with |embedder|
[ "Setup", "a", "new", "guest", "with", "|embedder|" ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/guest-window-manager.js#L83-L106
train
electron/electron
lib/browser/guest-window-manager.js
function (embedder, url, referrer, frameName, options, postData) { let guest = frameToGuest.get(frameName) if (frameName && (guest != null)) { guest.loadURL(url) return guest.webContents.id } // Remember the embedder window's id. if (options.webPreferences == null) { options.webPreferences = {} } guest = new BrowserWindow(options) if (!options.webContents) { // We should not call `loadURL` if the window was constructed from an // existing webContents (window.open in a sandboxed renderer). // // Navigating to the url when creating the window from an existing // webContents is not necessary (it will navigate there anyway). const loadOptions = { httpReferrer: referrer } if (postData != null) { loadOptions.postData = postData loadOptions.extraHeaders = 'content-type: application/x-www-form-urlencoded' if (postData.length > 0) { const postDataFront = postData[0].bytes.toString() const boundary = /^--.*[^-\r\n]/.exec(postDataFront) if (boundary != null) { loadOptions.extraHeaders = `content-type: multipart/form-data; boundary=${boundary[0].substr(2)}` } } } guest.loadURL(url, loadOptions) } return setupGuest(embedder, frameName, guest, options) }
javascript
function (embedder, url, referrer, frameName, options, postData) { let guest = frameToGuest.get(frameName) if (frameName && (guest != null)) { guest.loadURL(url) return guest.webContents.id } // Remember the embedder window's id. if (options.webPreferences == null) { options.webPreferences = {} } guest = new BrowserWindow(options) if (!options.webContents) { // We should not call `loadURL` if the window was constructed from an // existing webContents (window.open in a sandboxed renderer). // // Navigating to the url when creating the window from an existing // webContents is not necessary (it will navigate there anyway). const loadOptions = { httpReferrer: referrer } if (postData != null) { loadOptions.postData = postData loadOptions.extraHeaders = 'content-type: application/x-www-form-urlencoded' if (postData.length > 0) { const postDataFront = postData[0].bytes.toString() const boundary = /^--.*[^-\r\n]/.exec(postDataFront) if (boundary != null) { loadOptions.extraHeaders = `content-type: multipart/form-data; boundary=${boundary[0].substr(2)}` } } } guest.loadURL(url, loadOptions) } return setupGuest(embedder, frameName, guest, options) }
[ "function", "(", "embedder", ",", "url", ",", "referrer", ",", "frameName", ",", "options", ",", "postData", ")", "{", "let", "guest", "=", "frameToGuest", ".", "get", "(", "frameName", ")", "if", "(", "frameName", "&&", "(", "guest", "!=", "null", ")", ")", "{", "guest", ".", "loadURL", "(", "url", ")", "return", "guest", ".", "webContents", ".", "id", "}", "if", "(", "options", ".", "webPreferences", "==", "null", ")", "{", "options", ".", "webPreferences", "=", "{", "}", "}", "guest", "=", "new", "BrowserWindow", "(", "options", ")", "if", "(", "!", "options", ".", "webContents", ")", "{", "const", "loadOptions", "=", "{", "httpReferrer", ":", "referrer", "}", "if", "(", "postData", "!=", "null", ")", "{", "loadOptions", ".", "postData", "=", "postData", "loadOptions", ".", "extraHeaders", "=", "'content-type: application/x-www-form-urlencoded'", "if", "(", "postData", ".", "length", ">", "0", ")", "{", "const", "postDataFront", "=", "postData", "[", "0", "]", ".", "bytes", ".", "toString", "(", ")", "const", "boundary", "=", "/", "^--.*[^-\\r\\n]", "/", ".", "exec", "(", "postDataFront", ")", "if", "(", "boundary", "!=", "null", ")", "{", "loadOptions", ".", "extraHeaders", "=", "`", "${", "boundary", "[", "0", "]", ".", "substr", "(", "2", ")", "}", "`", "}", "}", "}", "guest", ".", "loadURL", "(", "url", ",", "loadOptions", ")", "}", "return", "setupGuest", "(", "embedder", ",", "frameName", ",", "guest", ",", "options", ")", "}" ]
Create a new guest created by |embedder| with |options|.
[ "Create", "a", "new", "guest", "created", "by", "|embedder|", "with", "|options|", "." ]
6e29611788277729647acf465f10db1ea6f15788
https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/guest-window-manager.js#L109-L146
train
storybooks/storybook
addons/storyshots/storyshots-core/src/frameworks/svelte/renderTree.js
getRenderedTree
function getRenderedTree(story) { const { Component, props } = story.render(); const DefaultCompatComponent = Component.default || Component; // We need to create a target to mount onto. const target = document.createElement('section'); new DefaultCompatComponent({ target, props }); // eslint-disable-line // Classify the target so that it is clear where the markup // originates from, and that it is specific for snapshot tests. target.className = 'storybook-snapshot-container'; return target; }
javascript
function getRenderedTree(story) { const { Component, props } = story.render(); const DefaultCompatComponent = Component.default || Component; // We need to create a target to mount onto. const target = document.createElement('section'); new DefaultCompatComponent({ target, props }); // eslint-disable-line // Classify the target so that it is clear where the markup // originates from, and that it is specific for snapshot tests. target.className = 'storybook-snapshot-container'; return target; }
[ "function", "getRenderedTree", "(", "story", ")", "{", "const", "{", "Component", ",", "props", "}", "=", "story", ".", "render", "(", ")", ";", "const", "DefaultCompatComponent", "=", "Component", ".", "default", "||", "Component", ";", "const", "target", "=", "document", ".", "createElement", "(", "'section'", ")", ";", "new", "DefaultCompatComponent", "(", "{", "target", ",", "props", "}", ")", ";", "target", ".", "className", "=", "'storybook-snapshot-container'", ";", "return", "target", ";", "}" ]
Provides functionality to convert your raw story to the resulting markup. Storybook snapshots need the rendered markup that svelte outputs, but since we only have the story config data ({ Component, data }) in the Svelte stories, we need to mount the component, and then return the resulting HTML. If we don't render to HTML, we will get a snapshot of the raw story i.e. ({ Component, data }).
[ "Provides", "functionality", "to", "convert", "your", "raw", "story", "to", "the", "resulting", "markup", "." ]
9bff9271b7e163fb12b9ee0cf697c56f9d727b7b
https://github.com/storybooks/storybook/blob/9bff9271b7e163fb12b9ee0cf697c56f9d727b7b/addons/storyshots/storyshots-core/src/frameworks/svelte/renderTree.js#L14-L29
train
storybooks/storybook
lib/core/src/client/preview/start.js
showException
function showException(exception) { addons.getChannel().emit(Events.STORY_THREW_EXCEPTION, exception); showErrorDisplay(exception); // Log the stack to the console. So, user could check the source code. logger.error(exception.stack); }
javascript
function showException(exception) { addons.getChannel().emit(Events.STORY_THREW_EXCEPTION, exception); showErrorDisplay(exception); // Log the stack to the console. So, user could check the source code. logger.error(exception.stack); }
[ "function", "showException", "(", "exception", ")", "{", "addons", ".", "getChannel", "(", ")", ".", "emit", "(", "Events", ".", "STORY_THREW_EXCEPTION", ",", "exception", ")", ";", "showErrorDisplay", "(", "exception", ")", ";", "logger", ".", "error", "(", "exception", ".", "stack", ")", ";", "}" ]
showException is used if we fail to render the story and it is uncaught by the app layer
[ "showException", "is", "used", "if", "we", "fail", "to", "render", "the", "story", "and", "it", "is", "uncaught", "by", "the", "app", "layer" ]
9bff9271b7e163fb12b9ee0cf697c56f9d727b7b
https://github.com/storybooks/storybook/blob/9bff9271b7e163fb12b9ee0cf697c56f9d727b7b/lib/core/src/client/preview/start.js#L50-L56
train
storybooks/storybook
lib/core/src/server/utils/load-custom-babel-config.js
loadFromPath
function loadFromPath(babelConfigPath) { let config; if (fs.existsSync(babelConfigPath)) { const content = fs.readFileSync(babelConfigPath, 'utf-8'); try { config = JSON5.parse(content); config.babelrc = false; logger.info('=> Loading custom .babelrc'); } catch (e) { logger.error(`=> Error parsing .babelrc file: ${e.message}`); throw e; } } if (!config) return null; // Remove react-hmre preset. // It causes issues with react-storybook. // We don't really need it. // Earlier, we fix this by running storybook in the production mode. // But, that hide some useful debug messages. if (config.presets) { removeReactHmre(config.presets); } if (config.env && config.env.development && config.env.development.presets) { removeReactHmre(config.env.development.presets); } return config; }
javascript
function loadFromPath(babelConfigPath) { let config; if (fs.existsSync(babelConfigPath)) { const content = fs.readFileSync(babelConfigPath, 'utf-8'); try { config = JSON5.parse(content); config.babelrc = false; logger.info('=> Loading custom .babelrc'); } catch (e) { logger.error(`=> Error parsing .babelrc file: ${e.message}`); throw e; } } if (!config) return null; // Remove react-hmre preset. // It causes issues with react-storybook. // We don't really need it. // Earlier, we fix this by running storybook in the production mode. // But, that hide some useful debug messages. if (config.presets) { removeReactHmre(config.presets); } if (config.env && config.env.development && config.env.development.presets) { removeReactHmre(config.env.development.presets); } return config; }
[ "function", "loadFromPath", "(", "babelConfigPath", ")", "{", "let", "config", ";", "if", "(", "fs", ".", "existsSync", "(", "babelConfigPath", ")", ")", "{", "const", "content", "=", "fs", ".", "readFileSync", "(", "babelConfigPath", ",", "'utf-8'", ")", ";", "try", "{", "config", "=", "JSON5", ".", "parse", "(", "content", ")", ";", "config", ".", "babelrc", "=", "false", ";", "logger", ".", "info", "(", "'=> Loading custom .babelrc'", ")", ";", "}", "catch", "(", "e", ")", "{", "logger", ".", "error", "(", "`", "${", "e", ".", "message", "}", "`", ")", ";", "throw", "e", ";", "}", "}", "if", "(", "!", "config", ")", "return", "null", ";", "if", "(", "config", ".", "presets", ")", "{", "removeReactHmre", "(", "config", ".", "presets", ")", ";", "}", "if", "(", "config", ".", "env", "&&", "config", ".", "env", ".", "development", "&&", "config", ".", "env", ".", "development", ".", "presets", ")", "{", "removeReactHmre", "(", "config", ".", "env", ".", "development", ".", "presets", ")", ";", "}", "return", "config", ";", "}" ]
Tries to load a .babelrc and returns the parsed object if successful
[ "Tries", "to", "load", "a", ".", "babelrc", "and", "returns", "the", "parsed", "object", "if", "successful" ]
9bff9271b7e163fb12b9ee0cf697c56f9d727b7b
https://github.com/storybooks/storybook/blob/9bff9271b7e163fb12b9ee0cf697c56f9d727b7b/lib/core/src/server/utils/load-custom-babel-config.js#L17-L47
train
storybooks/storybook
examples/official-storybook/config.js
importAll
function importAll(context) { const storyStore = window.__STORYBOOK_CLIENT_API__._storyStore; // eslint-disable-line no-undef, no-underscore-dangle context.keys().forEach(filename => { const fileExports = context(filename); // A old-style story file if (!fileExports.default) { return; } const { default: component, ...examples } = fileExports; let componentOptions = component; if (component.prototype && component.prototype.isReactComponent) { componentOptions = { component }; } const kindName = componentOptions.title || componentOptions.component.displayName; if (previousExports[filename]) { if (previousExports[filename] === fileExports) { return; } // Otherwise clear this kind storyStore.removeStoryKind(kindName); storyStore.incrementRevision(); } // We pass true here to avoid the warning about HMR. It's cool clientApi, we got this const kind = storiesOf(kindName, true); (componentOptions.decorators || []).forEach(decorator => { kind.addDecorator(decorator); }); if (componentOptions.parameters) { kind.addParameters(componentOptions.parameters); } Object.keys(examples).forEach(key => { const example = examples[key]; const { title = key, parameters } = example; kind.add(title, example, parameters); }); previousExports[filename] = fileExports; }); }
javascript
function importAll(context) { const storyStore = window.__STORYBOOK_CLIENT_API__._storyStore; // eslint-disable-line no-undef, no-underscore-dangle context.keys().forEach(filename => { const fileExports = context(filename); // A old-style story file if (!fileExports.default) { return; } const { default: component, ...examples } = fileExports; let componentOptions = component; if (component.prototype && component.prototype.isReactComponent) { componentOptions = { component }; } const kindName = componentOptions.title || componentOptions.component.displayName; if (previousExports[filename]) { if (previousExports[filename] === fileExports) { return; } // Otherwise clear this kind storyStore.removeStoryKind(kindName); storyStore.incrementRevision(); } // We pass true here to avoid the warning about HMR. It's cool clientApi, we got this const kind = storiesOf(kindName, true); (componentOptions.decorators || []).forEach(decorator => { kind.addDecorator(decorator); }); if (componentOptions.parameters) { kind.addParameters(componentOptions.parameters); } Object.keys(examples).forEach(key => { const example = examples[key]; const { title = key, parameters } = example; kind.add(title, example, parameters); }); previousExports[filename] = fileExports; }); }
[ "function", "importAll", "(", "context", ")", "{", "const", "storyStore", "=", "window", ".", "__STORYBOOK_CLIENT_API__", ".", "_storyStore", ";", "context", ".", "keys", "(", ")", ".", "forEach", "(", "filename", "=>", "{", "const", "fileExports", "=", "context", "(", "filename", ")", ";", "if", "(", "!", "fileExports", ".", "default", ")", "{", "return", ";", "}", "const", "{", "default", ":", "component", ",", "...", "examples", "}", "=", "fileExports", ";", "let", "componentOptions", "=", "component", ";", "if", "(", "component", ".", "prototype", "&&", "component", ".", "prototype", ".", "isReactComponent", ")", "{", "componentOptions", "=", "{", "component", "}", ";", "}", "const", "kindName", "=", "componentOptions", ".", "title", "||", "componentOptions", ".", "component", ".", "displayName", ";", "if", "(", "previousExports", "[", "filename", "]", ")", "{", "if", "(", "previousExports", "[", "filename", "]", "===", "fileExports", ")", "{", "return", ";", "}", "storyStore", ".", "removeStoryKind", "(", "kindName", ")", ";", "storyStore", ".", "incrementRevision", "(", ")", ";", "}", "const", "kind", "=", "storiesOf", "(", "kindName", ",", "true", ")", ";", "(", "componentOptions", ".", "decorators", "||", "[", "]", ")", ".", "forEach", "(", "decorator", "=>", "{", "kind", ".", "addDecorator", "(", "decorator", ")", ";", "}", ")", ";", "if", "(", "componentOptions", ".", "parameters", ")", "{", "kind", ".", "addParameters", "(", "componentOptions", ".", "parameters", ")", ";", "}", "Object", ".", "keys", "(", "examples", ")", ".", "forEach", "(", "key", "=>", "{", "const", "example", "=", "examples", "[", "key", "]", ";", "const", "{", "title", "=", "key", ",", "parameters", "}", "=", "example", ";", "kind", ".", "add", "(", "title", ",", "example", ",", "parameters", ")", ";", "}", ")", ";", "previousExports", "[", "filename", "]", "=", "fileExports", ";", "}", ")", ";", "}" ]
The simplest version of examples would just export this function for users to use
[ "The", "simplest", "version", "of", "examples", "would", "just", "export", "this", "function", "for", "users", "to", "use" ]
9bff9271b7e163fb12b9ee0cf697c56f9d727b7b
https://github.com/storybooks/storybook/blob/9bff9271b7e163fb12b9ee0cf697c56f9d727b7b/examples/official-storybook/config.js#L72-L118
train
ColorlibHQ/AdminLTE
bower_components/Flot/jquery.flot.selection.js
extractRange
function extractRange(ranges, coord) { var axis, from, to, key, axes = plot.getAxes(); for (var k in axes) { axis = axes[k]; if (axis.direction == coord) { key = coord + axis.n + "axis"; if (!ranges[key] && axis.n == 1) key = coord + "axis"; // support x1axis as xaxis if (ranges[key]) { from = ranges[key].from; to = ranges[key].to; break; } } } // backwards-compat stuff - to be removed in future if (!ranges[key]) { axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0]; from = ranges[coord + "1"]; to = ranges[coord + "2"]; } // auto-reverse as an added bonus if (from != null && to != null && from > to) { var tmp = from; from = to; to = tmp; } return { from: from, to: to, axis: axis }; }
javascript
function extractRange(ranges, coord) { var axis, from, to, key, axes = plot.getAxes(); for (var k in axes) { axis = axes[k]; if (axis.direction == coord) { key = coord + axis.n + "axis"; if (!ranges[key] && axis.n == 1) key = coord + "axis"; // support x1axis as xaxis if (ranges[key]) { from = ranges[key].from; to = ranges[key].to; break; } } } // backwards-compat stuff - to be removed in future if (!ranges[key]) { axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0]; from = ranges[coord + "1"]; to = ranges[coord + "2"]; } // auto-reverse as an added bonus if (from != null && to != null && from > to) { var tmp = from; from = to; to = tmp; } return { from: from, to: to, axis: axis }; }
[ "function", "extractRange", "(", "ranges", ",", "coord", ")", "{", "var", "axis", ",", "from", ",", "to", ",", "key", ",", "axes", "=", "plot", ".", "getAxes", "(", ")", ";", "for", "(", "var", "k", "in", "axes", ")", "{", "axis", "=", "axes", "[", "k", "]", ";", "if", "(", "axis", ".", "direction", "==", "coord", ")", "{", "key", "=", "coord", "+", "axis", ".", "n", "+", "\"axis\"", ";", "if", "(", "!", "ranges", "[", "key", "]", "&&", "axis", ".", "n", "==", "1", ")", "key", "=", "coord", "+", "\"axis\"", ";", "if", "(", "ranges", "[", "key", "]", ")", "{", "from", "=", "ranges", "[", "key", "]", ".", "from", ";", "to", "=", "ranges", "[", "key", "]", ".", "to", ";", "break", ";", "}", "}", "}", "if", "(", "!", "ranges", "[", "key", "]", ")", "{", "axis", "=", "coord", "==", "\"x\"", "?", "plot", ".", "getXAxes", "(", ")", "[", "0", "]", ":", "plot", ".", "getYAxes", "(", ")", "[", "0", "]", ";", "from", "=", "ranges", "[", "coord", "+", "\"1\"", "]", ";", "to", "=", "ranges", "[", "coord", "+", "\"2\"", "]", ";", "}", "if", "(", "from", "!=", "null", "&&", "to", "!=", "null", "&&", "from", ">", "to", ")", "{", "var", "tmp", "=", "from", ";", "from", "=", "to", ";", "to", "=", "tmp", ";", "}", "return", "{", "from", ":", "from", ",", "to", ":", "to", ",", "axis", ":", "axis", "}", ";", "}" ]
function taken from markings support in Flot
[ "function", "taken", "from", "markings", "support", "in", "Flot" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/bower_components/Flot/jquery.flot.selection.js#L225-L257
train
ColorlibHQ/AdminLTE
bower_components/jvectormap/lib/data-series.js
function(values) { var max = Number.MIN_VALUE, min = Number.MAX_VALUE, val, cc, attrs = {}; if (!(this.scale instanceof jvm.OrdinalScale) && !(this.scale instanceof jvm.SimpleScale)) { if (!this.params.min || !this.params.max) { for (cc in values) { val = parseFloat(values[cc]); if (val > max) max = values[cc]; if (val < min) min = val; } if (!this.params.min) { this.scale.setMin(min); } if (!this.params.max) { this.scale.setMax(max); } this.params.min = min; this.params.max = max; } for (cc in values) { val = parseFloat(values[cc]); if (!isNaN(val)) { attrs[cc] = this.scale.getValue(val); } else { attrs[cc] = this.elements[cc].element.style.initial[this.params.attribute]; } } } else { for (cc in values) { if (values[cc]) { attrs[cc] = this.scale.getValue(values[cc]); } else { attrs[cc] = this.elements[cc].element.style.initial[this.params.attribute]; } } } this.setAttributes(attrs); jvm.$.extend(this.values, values); }
javascript
function(values) { var max = Number.MIN_VALUE, min = Number.MAX_VALUE, val, cc, attrs = {}; if (!(this.scale instanceof jvm.OrdinalScale) && !(this.scale instanceof jvm.SimpleScale)) { if (!this.params.min || !this.params.max) { for (cc in values) { val = parseFloat(values[cc]); if (val > max) max = values[cc]; if (val < min) min = val; } if (!this.params.min) { this.scale.setMin(min); } if (!this.params.max) { this.scale.setMax(max); } this.params.min = min; this.params.max = max; } for (cc in values) { val = parseFloat(values[cc]); if (!isNaN(val)) { attrs[cc] = this.scale.getValue(val); } else { attrs[cc] = this.elements[cc].element.style.initial[this.params.attribute]; } } } else { for (cc in values) { if (values[cc]) { attrs[cc] = this.scale.getValue(values[cc]); } else { attrs[cc] = this.elements[cc].element.style.initial[this.params.attribute]; } } } this.setAttributes(attrs); jvm.$.extend(this.values, values); }
[ "function", "(", "values", ")", "{", "var", "max", "=", "Number", ".", "MIN_VALUE", ",", "min", "=", "Number", ".", "MAX_VALUE", ",", "val", ",", "cc", ",", "attrs", "=", "{", "}", ";", "if", "(", "!", "(", "this", ".", "scale", "instanceof", "jvm", ".", "OrdinalScale", ")", "&&", "!", "(", "this", ".", "scale", "instanceof", "jvm", ".", "SimpleScale", ")", ")", "{", "if", "(", "!", "this", ".", "params", ".", "min", "||", "!", "this", ".", "params", ".", "max", ")", "{", "for", "(", "cc", "in", "values", ")", "{", "val", "=", "parseFloat", "(", "values", "[", "cc", "]", ")", ";", "if", "(", "val", ">", "max", ")", "max", "=", "values", "[", "cc", "]", ";", "if", "(", "val", "<", "min", ")", "min", "=", "val", ";", "}", "if", "(", "!", "this", ".", "params", ".", "min", ")", "{", "this", ".", "scale", ".", "setMin", "(", "min", ")", ";", "}", "if", "(", "!", "this", ".", "params", ".", "max", ")", "{", "this", ".", "scale", ".", "setMax", "(", "max", ")", ";", "}", "this", ".", "params", ".", "min", "=", "min", ";", "this", ".", "params", ".", "max", "=", "max", ";", "}", "for", "(", "cc", "in", "values", ")", "{", "val", "=", "parseFloat", "(", "values", "[", "cc", "]", ")", ";", "if", "(", "!", "isNaN", "(", "val", ")", ")", "{", "attrs", "[", "cc", "]", "=", "this", ".", "scale", ".", "getValue", "(", "val", ")", ";", "}", "else", "{", "attrs", "[", "cc", "]", "=", "this", ".", "elements", "[", "cc", "]", ".", "element", ".", "style", ".", "initial", "[", "this", ".", "params", ".", "attribute", "]", ";", "}", "}", "}", "else", "{", "for", "(", "cc", "in", "values", ")", "{", "if", "(", "values", "[", "cc", "]", ")", "{", "attrs", "[", "cc", "]", "=", "this", ".", "scale", ".", "getValue", "(", "values", "[", "cc", "]", ")", ";", "}", "else", "{", "attrs", "[", "cc", "]", "=", "this", ".", "elements", "[", "cc", "]", ".", "element", ".", "style", ".", "initial", "[", "this", ".", "params", ".", "attribute", "]", ";", "}", "}", "}", "this", ".", "setAttributes", "(", "attrs", ")", ";", "jvm", ".", "$", ".", "extend", "(", "this", ".", "values", ",", "values", ")", ";", "}" ]
Set values for the data set. @param {Object} values Object which maps codes of regions or markers to values.
[ "Set", "values", "for", "the", "data", "set", "." ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/bower_components/jvectormap/lib/data-series.js#L60-L103
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(node) { assertRangeValid(this); var parent = node.parentNode; var nodeIndex = getNodeIndex(node); if (!parent) { throw new DOMException("NOT_FOUND_ERR"); } var startComparison = this.comparePoint(parent, nodeIndex), endComparison = this.comparePoint(parent, nodeIndex + 1); if (startComparison < 0) { // Node starts before return (endComparison > 0) ? n_b_a : n_b; } else { return (endComparison > 0) ? n_a : n_i; } }
javascript
function(node) { assertRangeValid(this); var parent = node.parentNode; var nodeIndex = getNodeIndex(node); if (!parent) { throw new DOMException("NOT_FOUND_ERR"); } var startComparison = this.comparePoint(parent, nodeIndex), endComparison = this.comparePoint(parent, nodeIndex + 1); if (startComparison < 0) { // Node starts before return (endComparison > 0) ? n_b_a : n_b; } else { return (endComparison > 0) ? n_a : n_i; } }
[ "function", "(", "node", ")", "{", "assertRangeValid", "(", "this", ")", ";", "var", "parent", "=", "node", ".", "parentNode", ";", "var", "nodeIndex", "=", "getNodeIndex", "(", "node", ")", ";", "if", "(", "!", "parent", ")", "{", "throw", "new", "DOMException", "(", "\"NOT_FOUND_ERR\"", ")", ";", "}", "var", "startComparison", "=", "this", ".", "comparePoint", "(", "parent", ",", "nodeIndex", ")", ",", "endComparison", "=", "this", ".", "comparePoint", "(", "parent", ",", "nodeIndex", "+", "1", ")", ";", "if", "(", "startComparison", "<", "0", ")", "{", "return", "(", "endComparison", ">", "0", ")", "?", "n_b_a", ":", "n_b", ";", "}", "else", "{", "return", "(", "endComparison", ">", "0", ")", "?", "n_a", ":", "n_i", ";", "}", "}" ]
The methods below are all non-standard. The following batch were introduced by Mozilla but have since been removed from Mozilla.
[ "The", "methods", "below", "are", "all", "non", "-", "standard", ".", "The", "following", "batch", "were", "introduced", "by", "Mozilla", "but", "have", "since", "been", "removed", "from", "Mozilla", "." ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L1622-L1640
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(sel, range) { var ranges = sel.getAllRanges(); sel.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { if (!rangesEqual(range, ranges[i])) { sel.addRange(ranges[i]); } } if (!sel.rangeCount) { updateEmptySelection(sel); } }
javascript
function(sel, range) { var ranges = sel.getAllRanges(); sel.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { if (!rangesEqual(range, ranges[i])) { sel.addRange(ranges[i]); } } if (!sel.rangeCount) { updateEmptySelection(sel); } }
[ "function", "(", "sel", ",", "range", ")", "{", "var", "ranges", "=", "sel", ".", "getAllRanges", "(", ")", ";", "sel", ".", "removeAllRanges", "(", ")", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "ranges", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "if", "(", "!", "rangesEqual", "(", "range", ",", "ranges", "[", "i", "]", ")", ")", "{", "sel", ".", "addRange", "(", "ranges", "[", "i", "]", ")", ";", "}", "}", "if", "(", "!", "sel", ".", "rangeCount", ")", "{", "updateEmptySelection", "(", "sel", ")", ";", "}", "}" ]
Removal of a single range
[ "Removal", "of", "a", "single", "range" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L3480-L3491
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(context) { var element = context.createElement("div"), html5 = "<article>foo</article>"; element.innerHTML = html5; return element.innerHTML.toLowerCase() === html5; }
javascript
function(context) { var element = context.createElement("div"), html5 = "<article>foo</article>"; element.innerHTML = html5; return element.innerHTML.toLowerCase() === html5; }
[ "function", "(", "context", ")", "{", "var", "element", "=", "context", ".", "createElement", "(", "\"div\"", ")", ",", "html5", "=", "\"<article>foo</article>\"", ";", "element", ".", "innerHTML", "=", "html5", ";", "return", "element", ".", "innerHTML", ".", "toLowerCase", "(", ")", "===", "html5", ";", "}" ]
Everything below IE9 doesn't know how to treat HTML5 tags @param {Object} context The document object on which to check HTML5 support @example wysihtml5.browser.supportsHTML5Tags(document);
[ "Everything", "below", "IE9", "doesn", "t", "know", "how", "to", "treat", "HTML5", "tags" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L4345-L4350
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function() { var clonedTestElement = testElement.cloneNode(false), returnValue, innerHTML; clonedTestElement.innerHTML = "<p><div></div>"; innerHTML = clonedTestElement.innerHTML.toLowerCase(); returnValue = innerHTML === "<p></p><div></div>" || innerHTML === "<p><div></div></p>"; // Cache result by overwriting current function this.autoClosesUnclosedTags = function() { return returnValue; }; return returnValue; }
javascript
function() { var clonedTestElement = testElement.cloneNode(false), returnValue, innerHTML; clonedTestElement.innerHTML = "<p><div></div>"; innerHTML = clonedTestElement.innerHTML.toLowerCase(); returnValue = innerHTML === "<p></p><div></div>" || innerHTML === "<p><div></div></p>"; // Cache result by overwriting current function this.autoClosesUnclosedTags = function() { return returnValue; }; return returnValue; }
[ "function", "(", ")", "{", "var", "clonedTestElement", "=", "testElement", ".", "cloneNode", "(", "false", ")", ",", "returnValue", ",", "innerHTML", ";", "clonedTestElement", ".", "innerHTML", "=", "\"<p><div></div>\"", ";", "innerHTML", "=", "clonedTestElement", ".", "innerHTML", ".", "toLowerCase", "(", ")", ";", "returnValue", "=", "innerHTML", "===", "\"<p></p><div></div>\"", "||", "innerHTML", "===", "\"<p><div></div></p>\"", ";", "this", ".", "autoClosesUnclosedTags", "=", "function", "(", ")", "{", "return", "returnValue", ";", "}", ";", "return", "returnValue", ";", "}" ]
Check whether the browser automatically closes tags that don't need to be opened
[ "Check", "whether", "the", "browser", "automatically", "closes", "tags", "that", "don", "t", "need", "to", "be", "opened" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L4455-L4468
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(needle) { if (Array.isArray(needle)) { for (var i = needle.length; i--;) { if (wysihtml5.lang.array(arr).indexOf(needle[i]) !== -1) { return true; } } return false; } else { return wysihtml5.lang.array(arr).indexOf(needle) !== -1; } }
javascript
function(needle) { if (Array.isArray(needle)) { for (var i = needle.length; i--;) { if (wysihtml5.lang.array(arr).indexOf(needle[i]) !== -1) { return true; } } return false; } else { return wysihtml5.lang.array(arr).indexOf(needle) !== -1; } }
[ "function", "(", "needle", ")", "{", "if", "(", "Array", ".", "isArray", "(", "needle", ")", ")", "{", "for", "(", "var", "i", "=", "needle", ".", "length", ";", "i", "--", ";", ")", "{", "if", "(", "wysihtml5", ".", "lang", ".", "array", "(", "arr", ")", ".", "indexOf", "(", "needle", "[", "i", "]", ")", "!==", "-", "1", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", "else", "{", "return", "wysihtml5", ".", "lang", ".", "array", "(", "arr", ")", ".", "indexOf", "(", "needle", ")", "!==", "-", "1", ";", "}", "}" ]
Check whether a given object exists in an array @example wysihtml5.lang.array([1, 2]).contains(1); // => true Can be used to match array with array. If intersection is found true is returned
[ "Check", "whether", "a", "given", "object", "exists", "in", "an", "array" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L4588-L4599
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(needle) { if (arr.indexOf) { return arr.indexOf(needle); } else { for (var i=0, length=arr.length; i<length; i++) { if (arr[i] === needle) { return i; } } return -1; } }
javascript
function(needle) { if (arr.indexOf) { return arr.indexOf(needle); } else { for (var i=0, length=arr.length; i<length; i++) { if (arr[i] === needle) { return i; } } return -1; } }
[ "function", "(", "needle", ")", "{", "if", "(", "arr", ".", "indexOf", ")", "{", "return", "arr", ".", "indexOf", "(", "needle", ")", ";", "}", "else", "{", "for", "(", "var", "i", "=", "0", ",", "length", "=", "arr", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "arr", "[", "i", "]", "===", "needle", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}", "}" ]
Check whether a given object exists in an array and return index If no elelemt found returns -1 @example wysihtml5.lang.array([1, 2]).indexOf(2); // => 1
[ "Check", "whether", "a", "given", "object", "exists", "in", "an", "array", "and", "return", "index", "If", "no", "elelemt", "found", "returns", "-", "1" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L4609-L4618
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(arrayToSubstract) { arrayToSubstract = wysihtml5.lang.array(arrayToSubstract); var newArr = [], i = 0, length = arr.length; for (; i<length; i++) { if (!arrayToSubstract.contains(arr[i])) { newArr.push(arr[i]); } } return newArr; }
javascript
function(arrayToSubstract) { arrayToSubstract = wysihtml5.lang.array(arrayToSubstract); var newArr = [], i = 0, length = arr.length; for (; i<length; i++) { if (!arrayToSubstract.contains(arr[i])) { newArr.push(arr[i]); } } return newArr; }
[ "function", "(", "arrayToSubstract", ")", "{", "arrayToSubstract", "=", "wysihtml5", ".", "lang", ".", "array", "(", "arrayToSubstract", ")", ";", "var", "newArr", "=", "[", "]", ",", "i", "=", "0", ",", "length", "=", "arr", ".", "length", ";", "for", "(", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "!", "arrayToSubstract", ".", "contains", "(", "arr", "[", "i", "]", ")", ")", "{", "newArr", ".", "push", "(", "arr", "[", "i", "]", ")", ";", "}", "}", "return", "newArr", ";", "}" ]
Substract one array from another @example wysihtml5.lang.array([1, 2, 3, 4]).without([3, 4]); // => [1, 2]
[ "Substract", "one", "array", "from", "another" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L4627-L4638
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function() { var i = 0, length = arr.length, newArray = []; for (; i<length; i++) { newArray.push(arr[i]); } return newArray; }
javascript
function() { var i = 0, length = arr.length, newArray = []; for (; i<length; i++) { newArray.push(arr[i]); } return newArray; }
[ "function", "(", ")", "{", "var", "i", "=", "0", ",", "length", "=", "arr", ".", "length", ",", "newArray", "=", "[", "]", ";", "for", "(", ";", "i", "<", "length", ";", "i", "++", ")", "{", "newArray", ".", "push", "(", "arr", "[", "i", "]", ")", ";", "}", "return", "newArray", ";", "}" ]
Return a clean native array Following will convert a Live NodeList to a proper Array @example var childNodes = wysihtml5.lang.array(document.body.childNodes).get();
[ "Return", "a", "clean", "native", "array" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L4647-L4655
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(callback, thisArg) { if (Array.prototype.map) { return arr.map(callback, thisArg); } else { var len = arr.length >>> 0, A = new Array(len), i = 0; for (; i < len; i++) { A[i] = callback.call(thisArg, arr[i], i, arr); } return A; } }
javascript
function(callback, thisArg) { if (Array.prototype.map) { return arr.map(callback, thisArg); } else { var len = arr.length >>> 0, A = new Array(len), i = 0; for (; i < len; i++) { A[i] = callback.call(thisArg, arr[i], i, arr); } return A; } }
[ "function", "(", "callback", ",", "thisArg", ")", "{", "if", "(", "Array", ".", "prototype", ".", "map", ")", "{", "return", "arr", ".", "map", "(", "callback", ",", "thisArg", ")", ";", "}", "else", "{", "var", "len", "=", "arr", ".", "length", ">>>", "0", ",", "A", "=", "new", "Array", "(", "len", ")", ",", "i", "=", "0", ";", "for", "(", ";", "i", "<", "len", ";", "i", "++", ")", "{", "A", "[", "i", "]", "=", "callback", ".", "call", "(", "thisArg", ",", "arr", "[", "i", "]", ",", "i", ",", "arr", ")", ";", "}", "return", "A", ";", "}", "}" ]
Creates a new array with the results of calling a provided function on every element in this array. optionally this can be provided as second argument @example var childNodes = wysihtml5.lang.array([1,2,3,4]).map(function (value, index, array) { return value * 2; }); // => [2,4,6,8]
[ "Creates", "a", "new", "array", "with", "the", "results", "of", "calling", "a", "provided", "function", "on", "every", "element", "in", "this", "array", ".", "optionally", "this", "can", "be", "provided", "as", "second", "argument" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L4667-L4679
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
_convertUrlsToLinks
function _convertUrlsToLinks(str) { return str.replace(URL_REG_EXP, function(match, url) { var punctuation = (url.match(TRAILING_CHAR_REG_EXP) || [])[1] || "", opening = BRACKETS[punctuation]; url = url.replace(TRAILING_CHAR_REG_EXP, ""); if (url.split(opening).length > url.split(punctuation).length) { url = url + punctuation; punctuation = ""; } var realUrl = url, displayUrl = url; if (url.length > MAX_DISPLAY_LENGTH) { displayUrl = displayUrl.substr(0, MAX_DISPLAY_LENGTH) + "..."; } // Add http prefix if necessary if (realUrl.substr(0, 4) === "www.") { realUrl = "http://" + realUrl; } return '<a href="' + realUrl + '">' + displayUrl + '</a>' + punctuation; }); }
javascript
function _convertUrlsToLinks(str) { return str.replace(URL_REG_EXP, function(match, url) { var punctuation = (url.match(TRAILING_CHAR_REG_EXP) || [])[1] || "", opening = BRACKETS[punctuation]; url = url.replace(TRAILING_CHAR_REG_EXP, ""); if (url.split(opening).length > url.split(punctuation).length) { url = url + punctuation; punctuation = ""; } var realUrl = url, displayUrl = url; if (url.length > MAX_DISPLAY_LENGTH) { displayUrl = displayUrl.substr(0, MAX_DISPLAY_LENGTH) + "..."; } // Add http prefix if necessary if (realUrl.substr(0, 4) === "www.") { realUrl = "http://" + realUrl; } return '<a href="' + realUrl + '">' + displayUrl + '</a>' + punctuation; }); }
[ "function", "_convertUrlsToLinks", "(", "str", ")", "{", "return", "str", ".", "replace", "(", "URL_REG_EXP", ",", "function", "(", "match", ",", "url", ")", "{", "var", "punctuation", "=", "(", "url", ".", "match", "(", "TRAILING_CHAR_REG_EXP", ")", "||", "[", "]", ")", "[", "1", "]", "||", "\"\"", ",", "opening", "=", "BRACKETS", "[", "punctuation", "]", ";", "url", "=", "url", ".", "replace", "(", "TRAILING_CHAR_REG_EXP", ",", "\"\"", ")", ";", "if", "(", "url", ".", "split", "(", "opening", ")", ".", "length", ">", "url", ".", "split", "(", "punctuation", ")", ".", "length", ")", "{", "url", "=", "url", "+", "punctuation", ";", "punctuation", "=", "\"\"", ";", "}", "var", "realUrl", "=", "url", ",", "displayUrl", "=", "url", ";", "if", "(", "url", ".", "length", ">", "MAX_DISPLAY_LENGTH", ")", "{", "displayUrl", "=", "displayUrl", ".", "substr", "(", "0", ",", "MAX_DISPLAY_LENGTH", ")", "+", "\"...\"", ";", "}", "if", "(", "realUrl", ".", "substr", "(", "0", ",", "4", ")", "===", "\"www.\"", ")", "{", "realUrl", "=", "\"http://\"", "+", "realUrl", ";", "}", "return", "'<a href=\"'", "+", "realUrl", "+", "'\">'", "+", "displayUrl", "+", "'</a>'", "+", "punctuation", ";", "}", ")", ";", "}" ]
This is basically a rebuild of the rails auto_link_urls text helper
[ "This", "is", "basically", "a", "rebuild", "of", "the", "rails", "auto_link_urls", "text", "helper" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L4933-L4955
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
_wrapMatchesInNode
function _wrapMatchesInNode(textNode) { var parentNode = textNode.parentNode, nodeValue = wysihtml5.lang.string(textNode.data).escapeHTML(), tempElement = _getTempElement(parentNode.ownerDocument); // We need to insert an empty/temporary <span /> to fix IE quirks // Elsewise IE would strip white space in the beginning tempElement.innerHTML = "<span></span>" + _convertUrlsToLinks(nodeValue); tempElement.removeChild(tempElement.firstChild); while (tempElement.firstChild) { // inserts tempElement.firstChild before textNode parentNode.insertBefore(tempElement.firstChild, textNode); } parentNode.removeChild(textNode); }
javascript
function _wrapMatchesInNode(textNode) { var parentNode = textNode.parentNode, nodeValue = wysihtml5.lang.string(textNode.data).escapeHTML(), tempElement = _getTempElement(parentNode.ownerDocument); // We need to insert an empty/temporary <span /> to fix IE quirks // Elsewise IE would strip white space in the beginning tempElement.innerHTML = "<span></span>" + _convertUrlsToLinks(nodeValue); tempElement.removeChild(tempElement.firstChild); while (tempElement.firstChild) { // inserts tempElement.firstChild before textNode parentNode.insertBefore(tempElement.firstChild, textNode); } parentNode.removeChild(textNode); }
[ "function", "_wrapMatchesInNode", "(", "textNode", ")", "{", "var", "parentNode", "=", "textNode", ".", "parentNode", ",", "nodeValue", "=", "wysihtml5", ".", "lang", ".", "string", "(", "textNode", ".", "data", ")", ".", "escapeHTML", "(", ")", ",", "tempElement", "=", "_getTempElement", "(", "parentNode", ".", "ownerDocument", ")", ";", "tempElement", ".", "innerHTML", "=", "\"<span></span>\"", "+", "_convertUrlsToLinks", "(", "nodeValue", ")", ";", "tempElement", ".", "removeChild", "(", "tempElement", ".", "firstChild", ")", ";", "while", "(", "tempElement", ".", "firstChild", ")", "{", "parentNode", ".", "insertBefore", "(", "tempElement", ".", "firstChild", ",", "textNode", ")", ";", "}", "parentNode", ".", "removeChild", "(", "textNode", ")", ";", "}" ]
Replaces the original text nodes with the newly auto-linked dom tree
[ "Replaces", "the", "original", "text", "nodes", "with", "the", "newly", "auto", "-", "linked", "dom", "tree" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L4972-L4987
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(context) { if (context._wysihtml5_supportsHTML5Tags) { return; } for (var i=0, length=HTML5_ELEMENTS.length; i<length; i++) { context.createElement(HTML5_ELEMENTS[i]); } context._wysihtml5_supportsHTML5Tags = true; }
javascript
function(context) { if (context._wysihtml5_supportsHTML5Tags) { return; } for (var i=0, length=HTML5_ELEMENTS.length; i<length; i++) { context.createElement(HTML5_ELEMENTS[i]); } context._wysihtml5_supportsHTML5Tags = true; }
[ "function", "(", "context", ")", "{", "if", "(", "context", ".", "_wysihtml5_supportsHTML5Tags", ")", "{", "return", ";", "}", "for", "(", "var", "i", "=", "0", ",", "length", "=", "HTML5_ELEMENTS", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "context", ".", "createElement", "(", "HTML5_ELEMENTS", "[", "i", "]", ")", ";", "}", "context", ".", "_wysihtml5_supportsHTML5Tags", "=", "true", ";", "}" ]
Make sure IE supports HTML5 tags, which is accomplished by simply creating one instance of each element
[ "Make", "sure", "IE", "supports", "HTML5", "tags", "which", "is", "accomplished", "by", "simply", "creating", "one", "instance", "of", "each", "element" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L5405-L5413
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
parse
function parse(elementOrHtml, config) { wysihtml5.lang.object(currentRules).merge(defaultRules).merge(config.rules).get(); var context = config.context || elementOrHtml.ownerDocument || document, fragment = context.createDocumentFragment(), isString = typeof(elementOrHtml) === "string", clearInternals = false, element, newNode, firstChild; if (config.clearInternals === true) { clearInternals = true; } if (isString) { element = wysihtml5.dom.getAsDom(elementOrHtml, context); } else { element = elementOrHtml; } if (currentRules.selectors) { _applySelectorRules(element, currentRules.selectors); } while (element.firstChild) { firstChild = element.firstChild; newNode = _convert(firstChild, config.cleanUp, clearInternals, config.uneditableClass); if (newNode) { fragment.appendChild(newNode); } if (firstChild !== newNode) { element.removeChild(firstChild); } } if (config.unjoinNbsps) { // replace joined non-breakable spaces with unjoined var txtnodes = wysihtml5.dom.getTextNodes(fragment); for (var n = txtnodes.length; n--;) { txtnodes[n].nodeValue = txtnodes[n].nodeValue.replace(/([\S\u00A0])\u00A0/gi, "$1 "); } } // Clear element contents element.innerHTML = ""; // Insert new DOM tree element.appendChild(fragment); return isString ? wysihtml5.quirks.getCorrectInnerHTML(element) : element; }
javascript
function parse(elementOrHtml, config) { wysihtml5.lang.object(currentRules).merge(defaultRules).merge(config.rules).get(); var context = config.context || elementOrHtml.ownerDocument || document, fragment = context.createDocumentFragment(), isString = typeof(elementOrHtml) === "string", clearInternals = false, element, newNode, firstChild; if (config.clearInternals === true) { clearInternals = true; } if (isString) { element = wysihtml5.dom.getAsDom(elementOrHtml, context); } else { element = elementOrHtml; } if (currentRules.selectors) { _applySelectorRules(element, currentRules.selectors); } while (element.firstChild) { firstChild = element.firstChild; newNode = _convert(firstChild, config.cleanUp, clearInternals, config.uneditableClass); if (newNode) { fragment.appendChild(newNode); } if (firstChild !== newNode) { element.removeChild(firstChild); } } if (config.unjoinNbsps) { // replace joined non-breakable spaces with unjoined var txtnodes = wysihtml5.dom.getTextNodes(fragment); for (var n = txtnodes.length; n--;) { txtnodes[n].nodeValue = txtnodes[n].nodeValue.replace(/([\S\u00A0])\u00A0/gi, "$1 "); } } // Clear element contents element.innerHTML = ""; // Insert new DOM tree element.appendChild(fragment); return isString ? wysihtml5.quirks.getCorrectInnerHTML(element) : element; }
[ "function", "parse", "(", "elementOrHtml", ",", "config", ")", "{", "wysihtml5", ".", "lang", ".", "object", "(", "currentRules", ")", ".", "merge", "(", "defaultRules", ")", ".", "merge", "(", "config", ".", "rules", ")", ".", "get", "(", ")", ";", "var", "context", "=", "config", ".", "context", "||", "elementOrHtml", ".", "ownerDocument", "||", "document", ",", "fragment", "=", "context", ".", "createDocumentFragment", "(", ")", ",", "isString", "=", "typeof", "(", "elementOrHtml", ")", "===", "\"string\"", ",", "clearInternals", "=", "false", ",", "element", ",", "newNode", ",", "firstChild", ";", "if", "(", "config", ".", "clearInternals", "===", "true", ")", "{", "clearInternals", "=", "true", ";", "}", "if", "(", "isString", ")", "{", "element", "=", "wysihtml5", ".", "dom", ".", "getAsDom", "(", "elementOrHtml", ",", "context", ")", ";", "}", "else", "{", "element", "=", "elementOrHtml", ";", "}", "if", "(", "currentRules", ".", "selectors", ")", "{", "_applySelectorRules", "(", "element", ",", "currentRules", ".", "selectors", ")", ";", "}", "while", "(", "element", ".", "firstChild", ")", "{", "firstChild", "=", "element", ".", "firstChild", ";", "newNode", "=", "_convert", "(", "firstChild", ",", "config", ".", "cleanUp", ",", "clearInternals", ",", "config", ".", "uneditableClass", ")", ";", "if", "(", "newNode", ")", "{", "fragment", ".", "appendChild", "(", "newNode", ")", ";", "}", "if", "(", "firstChild", "!==", "newNode", ")", "{", "element", ".", "removeChild", "(", "firstChild", ")", ";", "}", "}", "if", "(", "config", ".", "unjoinNbsps", ")", "{", "var", "txtnodes", "=", "wysihtml5", ".", "dom", ".", "getTextNodes", "(", "fragment", ")", ";", "for", "(", "var", "n", "=", "txtnodes", ".", "length", ";", "n", "--", ";", ")", "{", "txtnodes", "[", "n", "]", ".", "nodeValue", "=", "txtnodes", "[", "n", "]", ".", "nodeValue", ".", "replace", "(", "/", "([\\S\\u00A0])\\u00A0", "/", "gi", ",", "\"$1 \"", ")", ";", "}", "}", "element", ".", "innerHTML", "=", "\"\"", ";", "element", ".", "appendChild", "(", "fragment", ")", ";", "return", "isString", "?", "wysihtml5", ".", "quirks", ".", "getCorrectInnerHTML", "(", "element", ")", ":", "element", ";", "}" ]
Iterates over all childs of the element, recreates them, appends them into a document fragment which later replaces the entire body content
[ "Iterates", "over", "all", "childs", "of", "the", "element", "recreates", "them", "appends", "them", "into", "a", "document", "fragment", "which", "later", "replaces", "the", "entire", "body", "content" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L5888-L5939
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function() { var that = this, iframe = doc.createElement("iframe"); iframe.className = "wysihtml5-sandbox"; wysihtml5.dom.setAttributes({ "security": "restricted", "allowtransparency": "true", "frameborder": 0, "width": 0, "height": 0, "marginwidth": 0, "marginheight": 0 }).on(iframe); // Setting the src like this prevents ssl warnings in IE6 if (wysihtml5.browser.throwsMixedContentWarningWhenIframeSrcIsEmpty()) { iframe.src = "javascript:'<html></html>'"; } iframe.onload = function() { iframe.onreadystatechange = iframe.onload = null; that._onLoadIframe(iframe); }; iframe.onreadystatechange = function() { if (/loaded|complete/.test(iframe.readyState)) { iframe.onreadystatechange = iframe.onload = null; that._onLoadIframe(iframe); } }; return iframe; }
javascript
function() { var that = this, iframe = doc.createElement("iframe"); iframe.className = "wysihtml5-sandbox"; wysihtml5.dom.setAttributes({ "security": "restricted", "allowtransparency": "true", "frameborder": 0, "width": 0, "height": 0, "marginwidth": 0, "marginheight": 0 }).on(iframe); // Setting the src like this prevents ssl warnings in IE6 if (wysihtml5.browser.throwsMixedContentWarningWhenIframeSrcIsEmpty()) { iframe.src = "javascript:'<html></html>'"; } iframe.onload = function() { iframe.onreadystatechange = iframe.onload = null; that._onLoadIframe(iframe); }; iframe.onreadystatechange = function() { if (/loaded|complete/.test(iframe.readyState)) { iframe.onreadystatechange = iframe.onload = null; that._onLoadIframe(iframe); } }; return iframe; }
[ "function", "(", ")", "{", "var", "that", "=", "this", ",", "iframe", "=", "doc", ".", "createElement", "(", "\"iframe\"", ")", ";", "iframe", ".", "className", "=", "\"wysihtml5-sandbox\"", ";", "wysihtml5", ".", "dom", ".", "setAttributes", "(", "{", "\"security\"", ":", "\"restricted\"", ",", "\"allowtransparency\"", ":", "\"true\"", ",", "\"frameborder\"", ":", "0", ",", "\"width\"", ":", "0", ",", "\"height\"", ":", "0", ",", "\"marginwidth\"", ":", "0", ",", "\"marginheight\"", ":", "0", "}", ")", ".", "on", "(", "iframe", ")", ";", "if", "(", "wysihtml5", ".", "browser", ".", "throwsMixedContentWarningWhenIframeSrcIsEmpty", "(", ")", ")", "{", "iframe", ".", "src", "=", "\"javascript:'<html></html>'\"", ";", "}", "iframe", ".", "onload", "=", "function", "(", ")", "{", "iframe", ".", "onreadystatechange", "=", "iframe", ".", "onload", "=", "null", ";", "that", ".", "_onLoadIframe", "(", "iframe", ")", ";", "}", ";", "iframe", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "/", "loaded|complete", "/", ".", "test", "(", "iframe", ".", "readyState", ")", ")", "{", "iframe", ".", "onreadystatechange", "=", "iframe", ".", "onload", "=", "null", ";", "that", ".", "_onLoadIframe", "(", "iframe", ")", ";", "}", "}", ";", "return", "iframe", ";", "}" ]
Creates the sandbox iframe Some important notes: - We can't use HTML5 sandbox for now: setting it causes that the iframe's dom can't be accessed from the outside Therefore we need to set the "allow-same-origin" flag which enables accessing the iframe's dom But then there's another problem, DOM events (focus, blur, change, keypress, ...) aren't fired. In order to make this happen we need to set the "allow-scripts" flag. A combination of allow-scripts and allow-same-origin is almost the same as setting no sandbox attribute at all. - Chrome & Safari, doesn't seem to support sandboxing correctly when the iframe's html is inlined (no physical document) - IE needs to have the security="restricted" attribute set before the iframe is inserted into the dom tree - Believe it or not but in IE "security" in document.createElement("iframe") is false, even though it supports it - When an iframe has security="restricted", in IE eval() & execScript() don't work anymore - IE doesn't fire the onload event when the content is inlined in the src attribute, therefore we rely on the onreadystatechange event
[ "Creates", "the", "sandbox", "iframe" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L6933-L6965
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(contentEditable) { contentEditable.className = (contentEditable.className && contentEditable.className != '') ? contentEditable.className + " wysihtml5-sandbox" : "wysihtml5-sandbox"; this._loadElement(contentEditable, true); return contentEditable; }
javascript
function(contentEditable) { contentEditable.className = (contentEditable.className && contentEditable.className != '') ? contentEditable.className + " wysihtml5-sandbox" : "wysihtml5-sandbox"; this._loadElement(contentEditable, true); return contentEditable; }
[ "function", "(", "contentEditable", ")", "{", "contentEditable", ".", "className", "=", "(", "contentEditable", ".", "className", "&&", "contentEditable", ".", "className", "!=", "''", ")", "?", "contentEditable", ".", "className", "+", "\" wysihtml5-sandbox\"", ":", "\"wysihtml5-sandbox\"", ";", "this", ".", "_loadElement", "(", "contentEditable", ",", "true", ")", ";", "return", "contentEditable", ";", "}" ]
initiates an allready existent contenteditable
[ "initiates", "an", "allready", "existent", "contenteditable" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L7111-L7115
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(cell) { if (cell.isColspan) { var colspan = parseInt(api.getAttribute(cell.el, 'colspan') || 1, 10), cType = cell.el.tagName.toLowerCase(); if (colspan > 1) { var newCells = this.createCells(cType, colspan -1); insertAfter(cell.el, newCells); } cell.el.removeAttribute('colspan'); } }
javascript
function(cell) { if (cell.isColspan) { var colspan = parseInt(api.getAttribute(cell.el, 'colspan') || 1, 10), cType = cell.el.tagName.toLowerCase(); if (colspan > 1) { var newCells = this.createCells(cType, colspan -1); insertAfter(cell.el, newCells); } cell.el.removeAttribute('colspan'); } }
[ "function", "(", "cell", ")", "{", "if", "(", "cell", ".", "isColspan", ")", "{", "var", "colspan", "=", "parseInt", "(", "api", ".", "getAttribute", "(", "cell", ".", "el", ",", "'colspan'", ")", "||", "1", ",", "10", ")", ",", "cType", "=", "cell", ".", "el", ".", "tagName", ".", "toLowerCase", "(", ")", ";", "if", "(", "colspan", ">", "1", ")", "{", "var", "newCells", "=", "this", ".", "createCells", "(", "cType", ",", "colspan", "-", "1", ")", ";", "insertAfter", "(", "cell", ".", "el", ",", "newCells", ")", ";", "}", "cell", ".", "el", ".", "removeAttribute", "(", "'colspan'", ")", ";", "}", "}" ]
Splits merged cell on row to unique cells
[ "Splits", "merged", "cell", "on", "row", "to", "unique", "cells" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L7615-L7625
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function() { var oldRow = api.getParentElement(this.cell, { nodeName: ["TR"] }); if (oldRow) { this.setTableMap(); this.idx = this.getMapIndex(this.cell); if (this.idx !== false) { var modRow = this.map[this.idx.row]; for (var cidx = 0, cmax = modRow.length; cidx < cmax; cidx++) { if (!modRow[cidx].modified) { this.setCellAsModified(modRow[cidx]); this.removeRowCell(modRow[cidx]); } } } removeElement(oldRow); } }
javascript
function() { var oldRow = api.getParentElement(this.cell, { nodeName: ["TR"] }); if (oldRow) { this.setTableMap(); this.idx = this.getMapIndex(this.cell); if (this.idx !== false) { var modRow = this.map[this.idx.row]; for (var cidx = 0, cmax = modRow.length; cidx < cmax; cidx++) { if (!modRow[cidx].modified) { this.setCellAsModified(modRow[cidx]); this.removeRowCell(modRow[cidx]); } } } removeElement(oldRow); } }
[ "function", "(", ")", "{", "var", "oldRow", "=", "api", ".", "getParentElement", "(", "this", ".", "cell", ",", "{", "nodeName", ":", "[", "\"TR\"", "]", "}", ")", ";", "if", "(", "oldRow", ")", "{", "this", ".", "setTableMap", "(", ")", ";", "this", ".", "idx", "=", "this", ".", "getMapIndex", "(", "this", ".", "cell", ")", ";", "if", "(", "this", ".", "idx", "!==", "false", ")", "{", "var", "modRow", "=", "this", ".", "map", "[", "this", ".", "idx", ".", "row", "]", ";", "for", "(", "var", "cidx", "=", "0", ",", "cmax", "=", "modRow", ".", "length", ";", "cidx", "<", "cmax", ";", "cidx", "++", ")", "{", "if", "(", "!", "modRow", "[", "cidx", "]", ".", "modified", ")", "{", "this", ".", "setCellAsModified", "(", "modRow", "[", "cidx", "]", ")", ";", "this", ".", "removeRowCell", "(", "modRow", "[", "cidx", "]", ")", ";", "}", "}", "}", "removeElement", "(", "oldRow", ")", ";", "}", "}" ]
Removes the row of selected cell
[ "Removes", "the", "row", "of", "selected", "cell" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L7935-L7951
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
removeCellSelections
function removeCellSelections () { if (editable) { var selectedCells = editable.querySelectorAll('.' + selection_class); if (selectedCells.length > 0) { for (var i = 0; i < selectedCells.length; i++) { dom.removeClass(selectedCells[i], selection_class); } } } }
javascript
function removeCellSelections () { if (editable) { var selectedCells = editable.querySelectorAll('.' + selection_class); if (selectedCells.length > 0) { for (var i = 0; i < selectedCells.length; i++) { dom.removeClass(selectedCells[i], selection_class); } } } }
[ "function", "removeCellSelections", "(", ")", "{", "if", "(", "editable", ")", "{", "var", "selectedCells", "=", "editable", ".", "querySelectorAll", "(", "'.'", "+", "selection_class", ")", ";", "if", "(", "selectedCells", ".", "length", ">", "0", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "selectedCells", ".", "length", ";", "i", "++", ")", "{", "dom", ".", "removeClass", "(", "selectedCells", "[", "i", "]", ",", "selection_class", ")", ";", "}", "}", "}", "}" ]
remove all selection classes
[ "remove", "all", "selection", "classes" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L8538-L8547
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
getDepth
function getDepth(ancestor, descendant) { var ret = 0; while (descendant !== ancestor) { ret++; descendant = descendant.parentNode; if (!descendant) throw new Error("not a descendant of ancestor!"); } return ret; }
javascript
function getDepth(ancestor, descendant) { var ret = 0; while (descendant !== ancestor) { ret++; descendant = descendant.parentNode; if (!descendant) throw new Error("not a descendant of ancestor!"); } return ret; }
[ "function", "getDepth", "(", "ancestor", ",", "descendant", ")", "{", "var", "ret", "=", "0", ";", "while", "(", "descendant", "!==", "ancestor", ")", "{", "ret", "++", ";", "descendant", "=", "descendant", ".", "parentNode", ";", "if", "(", "!", "descendant", ")", "throw", "new", "Error", "(", "\"not a descendant of ancestor!\"", ")", ";", "}", "return", "ret", ";", "}" ]
Provides the depth of ``descendant`` relative to ``ancestor``
[ "Provides", "the", "depth", "of", "descendant", "relative", "to", "ancestor" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L8719-L8728
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
expandRangeToSurround
function expandRangeToSurround(range) { if (range.canSurroundContents()) return; var common = range.commonAncestorContainer, start_depth = getDepth(common, range.startContainer), end_depth = getDepth(common, range.endContainer); while(!range.canSurroundContents()) { // In the following branches, we cannot just decrement the depth variables because the setStartBefore/setEndAfter may move the start or end of the range more than one level relative to ``common``. So we need to recompute the depth. if (start_depth > end_depth) { range.setStartBefore(range.startContainer); start_depth = getDepth(common, range.startContainer); } else { range.setEndAfter(range.endContainer); end_depth = getDepth(common, range.endContainer); } } }
javascript
function expandRangeToSurround(range) { if (range.canSurroundContents()) return; var common = range.commonAncestorContainer, start_depth = getDepth(common, range.startContainer), end_depth = getDepth(common, range.endContainer); while(!range.canSurroundContents()) { // In the following branches, we cannot just decrement the depth variables because the setStartBefore/setEndAfter may move the start or end of the range more than one level relative to ``common``. So we need to recompute the depth. if (start_depth > end_depth) { range.setStartBefore(range.startContainer); start_depth = getDepth(common, range.startContainer); } else { range.setEndAfter(range.endContainer); end_depth = getDepth(common, range.endContainer); } } }
[ "function", "expandRangeToSurround", "(", "range", ")", "{", "if", "(", "range", ".", "canSurroundContents", "(", ")", ")", "return", ";", "var", "common", "=", "range", ".", "commonAncestorContainer", ",", "start_depth", "=", "getDepth", "(", "common", ",", "range", ".", "startContainer", ")", ",", "end_depth", "=", "getDepth", "(", "common", ",", "range", ".", "endContainer", ")", ";", "while", "(", "!", "range", ".", "canSurroundContents", "(", ")", ")", "{", "if", "(", "start_depth", ">", "end_depth", ")", "{", "range", ".", "setStartBefore", "(", "range", ".", "startContainer", ")", ";", "start_depth", "=", "getDepth", "(", "common", ",", "range", ".", "startContainer", ")", ";", "}", "else", "{", "range", ".", "setEndAfter", "(", "range", ".", "endContainer", ")", ";", "end_depth", "=", "getDepth", "(", "common", ",", "range", ".", "endContainer", ")", ";", "}", "}", "}" ]
Should fix the obtained ranges that cannot surrond contents normally to apply changes upon Being considerate to firefox that sets range start start out of span and end inside on doubleclick initiated selection
[ "Should", "fix", "the", "obtained", "ranges", "that", "cannot", "surrond", "contents", "normally", "to", "apply", "changes", "upon", "Being", "considerate", "to", "firefox", "that", "sets", "range", "start", "start", "out", "of", "span", "and", "end", "inside", "on", "doubleclick", "initiated", "selection" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L8732-L8750
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(node) { var range = rangy.createRange(this.doc); range.setStartBefore(node); range.setEndBefore(node); return this.setSelection(range); }
javascript
function(node) { var range = rangy.createRange(this.doc); range.setStartBefore(node); range.setEndBefore(node); return this.setSelection(range); }
[ "function", "(", "node", ")", "{", "var", "range", "=", "rangy", ".", "createRange", "(", "this", ".", "doc", ")", ";", "range", ".", "setStartBefore", "(", "node", ")", ";", "range", ".", "setEndBefore", "(", "node", ")", ";", "return", "this", ".", "setSelection", "(", "range", ")", ";", "}" ]
Set the caret in front of the given node @param {Object} node The element or text node where to position the caret in front of @example selection.setBefore(myElement);
[ "Set", "the", "caret", "in", "front", "of", "the", "given", "node" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L8796-L8801
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(node) { var range = rangy.createRange(this.doc); range.setStartAfter(node); range.setEndAfter(node); return this.setSelection(range); }
javascript
function(node) { var range = rangy.createRange(this.doc); range.setStartAfter(node); range.setEndAfter(node); return this.setSelection(range); }
[ "function", "(", "node", ")", "{", "var", "range", "=", "rangy", ".", "createRange", "(", "this", ".", "doc", ")", ";", "range", ".", "setStartAfter", "(", "node", ")", ";", "range", ".", "setEndAfter", "(", "node", ")", ";", "return", "this", ".", "setSelection", "(", "range", ")", ";", "}" ]
Set the caret after the given node @param {Object} node The element or text node where to position the caret in front of @example selection.setBefore(myElement);
[ "Set", "the", "caret", "after", "the", "given", "node" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L8810-L8816
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(controlRange) { var selection, range; if (controlRange && this.doc.selection && this.doc.selection.type === "Control") { range = this.doc.selection.createRange(); if (range && range.length) { return range.item(0); } } selection = this.getSelection(this.doc); if (selection.focusNode === selection.anchorNode) { return selection.focusNode; } else { range = this.getRange(this.doc); return range ? range.commonAncestorContainer : this.doc.body; } }
javascript
function(controlRange) { var selection, range; if (controlRange && this.doc.selection && this.doc.selection.type === "Control") { range = this.doc.selection.createRange(); if (range && range.length) { return range.item(0); } } selection = this.getSelection(this.doc); if (selection.focusNode === selection.anchorNode) { return selection.focusNode; } else { range = this.getRange(this.doc); return range ? range.commonAncestorContainer : this.doc.body; } }
[ "function", "(", "controlRange", ")", "{", "var", "selection", ",", "range", ";", "if", "(", "controlRange", "&&", "this", ".", "doc", ".", "selection", "&&", "this", ".", "doc", ".", "selection", ".", "type", "===", "\"Control\"", ")", "{", "range", "=", "this", ".", "doc", ".", "selection", ".", "createRange", "(", ")", ";", "if", "(", "range", "&&", "range", ".", "length", ")", "{", "return", "range", ".", "item", "(", "0", ")", ";", "}", "}", "selection", "=", "this", ".", "getSelection", "(", "this", ".", "doc", ")", ";", "if", "(", "selection", ".", "focusNode", "===", "selection", ".", "anchorNode", ")", "{", "return", "selection", ".", "focusNode", ";", "}", "else", "{", "range", "=", "this", ".", "getRange", "(", "this", ".", "doc", ")", ";", "return", "range", "?", "range", ".", "commonAncestorContainer", ":", "this", ".", "doc", ".", "body", ";", "}", "}" ]
Get the node which contains the selection @param {Boolean} [controlRange] (only IE) Whether it should return the selected ControlRange element when the selection type is a "ControlRange" @return {Object} The node that contains the caret @example var nodeThatContainsCaret = selection.getSelectedNode();
[ "Get", "the", "node", "which", "contains", "the", "selection" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L8863-L8881
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(html) { var range = rangy.createRange(this.doc), node = this.doc.createElement('DIV'), fragment = this.doc.createDocumentFragment(), lastChild; node.innerHTML = html; lastChild = node.lastChild; while (node.firstChild) { fragment.appendChild(node.firstChild); } this.insertNode(fragment); if (lastChild) { this.setAfter(lastChild); } }
javascript
function(html) { var range = rangy.createRange(this.doc), node = this.doc.createElement('DIV'), fragment = this.doc.createDocumentFragment(), lastChild; node.innerHTML = html; lastChild = node.lastChild; while (node.firstChild) { fragment.appendChild(node.firstChild); } this.insertNode(fragment); if (lastChild) { this.setAfter(lastChild); } }
[ "function", "(", "html", ")", "{", "var", "range", "=", "rangy", ".", "createRange", "(", "this", ".", "doc", ")", ",", "node", "=", "this", ".", "doc", ".", "createElement", "(", "'DIV'", ")", ",", "fragment", "=", "this", ".", "doc", ".", "createDocumentFragment", "(", ")", ",", "lastChild", ";", "node", ".", "innerHTML", "=", "html", ";", "lastChild", "=", "node", ".", "lastChild", ";", "while", "(", "node", ".", "firstChild", ")", "{", "fragment", ".", "appendChild", "(", "node", ".", "firstChild", ")", ";", "}", "this", ".", "insertNode", "(", "fragment", ")", ";", "if", "(", "lastChild", ")", "{", "this", ".", "setAfter", "(", "lastChild", ")", ";", "}", "}" ]
Insert html at the caret position and move the cursor after the inserted html @param {String} html HTML string to insert @example selection.insertHTML("<p>foobar</p>");
[ "Insert", "html", "at", "the", "caret", "position", "and", "move", "the", "cursor", "after", "the", "inserted", "html" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L9161-L9178
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(nodeOptions) { var ranges = this.getOwnRanges(), node, nodes = []; if (ranges.length == 0) { return nodes; } for (var i = ranges.length; i--;) { node = this.doc.createElement(nodeOptions.nodeName); nodes.push(node); if (nodeOptions.className) { node.className = nodeOptions.className; } if (nodeOptions.cssStyle) { node.setAttribute('style', nodeOptions.cssStyle); } try { // This only works when the range boundaries are not overlapping other elements ranges[i].surroundContents(node); this.selectNode(node); } catch(e) { // fallback node.appendChild(ranges[i].extractContents()); ranges[i].insertNode(node); } } return nodes; }
javascript
function(nodeOptions) { var ranges = this.getOwnRanges(), node, nodes = []; if (ranges.length == 0) { return nodes; } for (var i = ranges.length; i--;) { node = this.doc.createElement(nodeOptions.nodeName); nodes.push(node); if (nodeOptions.className) { node.className = nodeOptions.className; } if (nodeOptions.cssStyle) { node.setAttribute('style', nodeOptions.cssStyle); } try { // This only works when the range boundaries are not overlapping other elements ranges[i].surroundContents(node); this.selectNode(node); } catch(e) { // fallback node.appendChild(ranges[i].extractContents()); ranges[i].insertNode(node); } } return nodes; }
[ "function", "(", "nodeOptions", ")", "{", "var", "ranges", "=", "this", ".", "getOwnRanges", "(", ")", ",", "node", ",", "nodes", "=", "[", "]", ";", "if", "(", "ranges", ".", "length", "==", "0", ")", "{", "return", "nodes", ";", "}", "for", "(", "var", "i", "=", "ranges", ".", "length", ";", "i", "--", ";", ")", "{", "node", "=", "this", ".", "doc", ".", "createElement", "(", "nodeOptions", ".", "nodeName", ")", ";", "nodes", ".", "push", "(", "node", ")", ";", "if", "(", "nodeOptions", ".", "className", ")", "{", "node", ".", "className", "=", "nodeOptions", ".", "className", ";", "}", "if", "(", "nodeOptions", ".", "cssStyle", ")", "{", "node", ".", "setAttribute", "(", "'style'", ",", "nodeOptions", ".", "cssStyle", ")", ";", "}", "try", "{", "ranges", "[", "i", "]", ".", "surroundContents", "(", "node", ")", ";", "this", ".", "selectNode", "(", "node", ")", ";", "}", "catch", "(", "e", ")", "{", "node", ".", "appendChild", "(", "ranges", "[", "i", "]", ".", "extractContents", "(", ")", ")", ";", "ranges", "[", "i", "]", ".", "insertNode", "(", "node", ")", ";", "}", "}", "return", "nodes", ";", "}" ]
Wraps current selection with the given node @param {Object} node The node to surround the selected elements with
[ "Wraps", "current", "selection", "with", "the", "given", "node" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L9199-L9226
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function() { var ranges = [], r = this.getRange(), tmpRanges; if (r) { ranges.push(r); } if (this.unselectableClass && this.contain && r) { var uneditables = this.getOwnUneditables(), tmpRange; if (uneditables.length > 0) { for (var i = 0, imax = uneditables.length; i < imax; i++) { tmpRanges = []; for (var j = 0, jmax = ranges.length; j < jmax; j++) { if (ranges[j]) { switch (ranges[j].compareNode(uneditables[i])) { case 2: // all selection inside uneditable. remove break; case 3: //section begins before and ends after uneditable. spilt tmpRange = ranges[j].cloneRange(); tmpRange.setEndBefore(uneditables[i]); tmpRanges.push(tmpRange); tmpRange = ranges[j].cloneRange(); tmpRange.setStartAfter(uneditables[i]); tmpRanges.push(tmpRange); break; default: // in all other cases uneditable does not touch selection. dont modify tmpRanges.push(ranges[j]); } } ranges = tmpRanges; } } } } return ranges; }
javascript
function() { var ranges = [], r = this.getRange(), tmpRanges; if (r) { ranges.push(r); } if (this.unselectableClass && this.contain && r) { var uneditables = this.getOwnUneditables(), tmpRange; if (uneditables.length > 0) { for (var i = 0, imax = uneditables.length; i < imax; i++) { tmpRanges = []; for (var j = 0, jmax = ranges.length; j < jmax; j++) { if (ranges[j]) { switch (ranges[j].compareNode(uneditables[i])) { case 2: // all selection inside uneditable. remove break; case 3: //section begins before and ends after uneditable. spilt tmpRange = ranges[j].cloneRange(); tmpRange.setEndBefore(uneditables[i]); tmpRanges.push(tmpRange); tmpRange = ranges[j].cloneRange(); tmpRange.setStartAfter(uneditables[i]); tmpRanges.push(tmpRange); break; default: // in all other cases uneditable does not touch selection. dont modify tmpRanges.push(ranges[j]); } } ranges = tmpRanges; } } } } return ranges; }
[ "function", "(", ")", "{", "var", "ranges", "=", "[", "]", ",", "r", "=", "this", ".", "getRange", "(", ")", ",", "tmpRanges", ";", "if", "(", "r", ")", "{", "ranges", ".", "push", "(", "r", ")", ";", "}", "if", "(", "this", ".", "unselectableClass", "&&", "this", ".", "contain", "&&", "r", ")", "{", "var", "uneditables", "=", "this", ".", "getOwnUneditables", "(", ")", ",", "tmpRange", ";", "if", "(", "uneditables", ".", "length", ">", "0", ")", "{", "for", "(", "var", "i", "=", "0", ",", "imax", "=", "uneditables", ".", "length", ";", "i", "<", "imax", ";", "i", "++", ")", "{", "tmpRanges", "=", "[", "]", ";", "for", "(", "var", "j", "=", "0", ",", "jmax", "=", "ranges", ".", "length", ";", "j", "<", "jmax", ";", "j", "++", ")", "{", "if", "(", "ranges", "[", "j", "]", ")", "{", "switch", "(", "ranges", "[", "j", "]", ".", "compareNode", "(", "uneditables", "[", "i", "]", ")", ")", "{", "case", "2", ":", "break", ";", "case", "3", ":", "tmpRange", "=", "ranges", "[", "j", "]", ".", "cloneRange", "(", ")", ";", "tmpRange", ".", "setEndBefore", "(", "uneditables", "[", "i", "]", ")", ";", "tmpRanges", ".", "push", "(", "tmpRange", ")", ";", "tmpRange", "=", "ranges", "[", "j", "]", ".", "cloneRange", "(", ")", ";", "tmpRange", ".", "setStartAfter", "(", "uneditables", "[", "i", "]", ")", ";", "tmpRanges", ".", "push", "(", "tmpRange", ")", ";", "break", ";", "default", ":", "tmpRanges", ".", "push", "(", "ranges", "[", "j", "]", ")", ";", "}", "}", "ranges", "=", "tmpRanges", ";", "}", "}", "}", "}", "return", "ranges", ";", "}" ]
Returns an array of ranges that belong only to this editable Needed as uneditable block in contenteditabel can split range into pieces If manipulating content reverse loop is usually needed as manipulation can shift subsequent ranges
[ "Returns", "an", "array", "of", "ranges", "that", "belong", "only", "to", "this", "editable", "Needed", "as", "uneditable", "block", "in", "contenteditabel", "can", "split", "range", "into", "pieces", "If", "manipulating", "content", "reverse", "loop", "is", "usually", "needed", "as", "manipulation", "can", "shift", "subsequent", "ranges" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L9434-L9474
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(node) { var cssStyleMatch; while (node) { cssStyleMatch = this.cssStyle ? hasStyleAttr(node, this.similarStyleRegExp) : false; if (node.nodeType == wysihtml5.ELEMENT_NODE && node.getAttribute("contenteditable") != "false" && rangy.dom.arrayContains(this.tagNames, node.tagName.toLowerCase()) && cssStyleMatch) { return node; } node = node.parentNode; } return false; }
javascript
function(node) { var cssStyleMatch; while (node) { cssStyleMatch = this.cssStyle ? hasStyleAttr(node, this.similarStyleRegExp) : false; if (node.nodeType == wysihtml5.ELEMENT_NODE && node.getAttribute("contenteditable") != "false" && rangy.dom.arrayContains(this.tagNames, node.tagName.toLowerCase()) && cssStyleMatch) { return node; } node = node.parentNode; } return false; }
[ "function", "(", "node", ")", "{", "var", "cssStyleMatch", ";", "while", "(", "node", ")", "{", "cssStyleMatch", "=", "this", ".", "cssStyle", "?", "hasStyleAttr", "(", "node", ",", "this", ".", "similarStyleRegExp", ")", ":", "false", ";", "if", "(", "node", ".", "nodeType", "==", "wysihtml5", ".", "ELEMENT_NODE", "&&", "node", ".", "getAttribute", "(", "\"contenteditable\"", ")", "!=", "\"false\"", "&&", "rangy", ".", "dom", ".", "arrayContains", "(", "this", ".", "tagNames", ",", "node", ".", "tagName", ".", "toLowerCase", "(", ")", ")", "&&", "cssStyleMatch", ")", "{", "return", "node", ";", "}", "node", "=", "node", ".", "parentNode", ";", "}", "return", "false", ";", "}" ]
returns parents of node with given style attribute
[ "returns", "parents", "of", "node", "with", "given", "style", "attribute" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L9823-L9834
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(command, value) { var obj = wysihtml5.commands[command], args = wysihtml5.lang.array(arguments).get(), method = obj && obj.exec, result = null; this.editor.fire("beforecommand:composer"); if (method) { args.unshift(this.composer); result = method.apply(obj, args); } else { try { // try/catch for buggy firefox result = this.doc.execCommand(command, false, value); } catch(e) {} } this.editor.fire("aftercommand:composer"); return result; }
javascript
function(command, value) { var obj = wysihtml5.commands[command], args = wysihtml5.lang.array(arguments).get(), method = obj && obj.exec, result = null; this.editor.fire("beforecommand:composer"); if (method) { args.unshift(this.composer); result = method.apply(obj, args); } else { try { // try/catch for buggy firefox result = this.doc.execCommand(command, false, value); } catch(e) {} } this.editor.fire("aftercommand:composer"); return result; }
[ "function", "(", "command", ",", "value", ")", "{", "var", "obj", "=", "wysihtml5", ".", "commands", "[", "command", "]", ",", "args", "=", "wysihtml5", ".", "lang", ".", "array", "(", "arguments", ")", ".", "get", "(", ")", ",", "method", "=", "obj", "&&", "obj", ".", "exec", ",", "result", "=", "null", ";", "this", ".", "editor", ".", "fire", "(", "\"beforecommand:composer\"", ")", ";", "if", "(", "method", ")", "{", "args", ".", "unshift", "(", "this", ".", "composer", ")", ";", "result", "=", "method", ".", "apply", "(", "obj", ",", "args", ")", ";", "}", "else", "{", "try", "{", "result", "=", "this", ".", "doc", ".", "execCommand", "(", "command", ",", "false", ",", "value", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "}", "this", ".", "editor", ".", "fire", "(", "\"aftercommand:composer\"", ")", ";", "return", "result", ";", "}" ]
Check whether the browser supports the given command @param {String} command The command string which to execute (eg. "bold", "italic", "insertUnorderedList") @param {String} [value] The command value parameter, needed for some commands ("createLink", "insertImage", ...), optional for commands that don't require one ("bold", "underline", ...) @example commands.exec("insertImage", "http://a1.twimg.com/profile_images/113868655/schrei_twitter_reasonably_small.jpg");
[ "Check", "whether", "the", "browser", "supports", "the", "given", "command" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L10224-L10244
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(command, commandValue) { var obj = wysihtml5.commands[command], args = wysihtml5.lang.array(arguments).get(), method = obj && obj.state; if (method) { args.unshift(this.composer); return method.apply(obj, args); } else { try { // try/catch for buggy firefox return this.doc.queryCommandState(command); } catch(e) { return false; } } }
javascript
function(command, commandValue) { var obj = wysihtml5.commands[command], args = wysihtml5.lang.array(arguments).get(), method = obj && obj.state; if (method) { args.unshift(this.composer); return method.apply(obj, args); } else { try { // try/catch for buggy firefox return this.doc.queryCommandState(command); } catch(e) { return false; } } }
[ "function", "(", "command", ",", "commandValue", ")", "{", "var", "obj", "=", "wysihtml5", ".", "commands", "[", "command", "]", ",", "args", "=", "wysihtml5", ".", "lang", ".", "array", "(", "arguments", ")", ".", "get", "(", ")", ",", "method", "=", "obj", "&&", "obj", ".", "state", ";", "if", "(", "method", ")", "{", "args", ".", "unshift", "(", "this", ".", "composer", ")", ";", "return", "method", ".", "apply", "(", "obj", ",", "args", ")", ";", "}", "else", "{", "try", "{", "return", "this", ".", "doc", ".", "queryCommandState", "(", "command", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}", "}" ]
Check whether the current command is active If the caret is within a bold text, then calling this with command "bold" should return true @param {String} command The command string which to check (eg. "bold", "italic", "insertUnorderedList") @param {String} [commandValue] The command value parameter (eg. for "insertImage" the image src) @return {Boolean} Whether the command is active @example var isCurrentSelectionBold = commands.state("bold");
[ "Check", "whether", "the", "current", "command", "is", "active", "If", "the", "caret", "is", "within", "a", "bold", "text", "then", "calling", "this", "with", "command", "bold", "should", "return", "true" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L10256-L10271
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
_changeLinks
function _changeLinks(composer, anchors, attributes) { var oldAttrs; for (var a = anchors.length; a--;) { // Remove all old attributes oldAttrs = anchors[a].attributes; for (var oa = oldAttrs.length; oa--;) { anchors[a].removeAttribute(oldAttrs.item(oa).name); } // Set new attributes for (var j in attributes) { if (attributes.hasOwnProperty(j)) { anchors[a].setAttribute(j, attributes[j]); } } } }
javascript
function _changeLinks(composer, anchors, attributes) { var oldAttrs; for (var a = anchors.length; a--;) { // Remove all old attributes oldAttrs = anchors[a].attributes; for (var oa = oldAttrs.length; oa--;) { anchors[a].removeAttribute(oldAttrs.item(oa).name); } // Set new attributes for (var j in attributes) { if (attributes.hasOwnProperty(j)) { anchors[a].setAttribute(j, attributes[j]); } } } }
[ "function", "_changeLinks", "(", "composer", ",", "anchors", ",", "attributes", ")", "{", "var", "oldAttrs", ";", "for", "(", "var", "a", "=", "anchors", ".", "length", ";", "a", "--", ";", ")", "{", "oldAttrs", "=", "anchors", "[", "a", "]", ".", "attributes", ";", "for", "(", "var", "oa", "=", "oldAttrs", ".", "length", ";", "oa", "--", ";", ")", "{", "anchors", "[", "a", "]", ".", "removeAttribute", "(", "oldAttrs", ".", "item", "(", "oa", ")", ".", "name", ")", ";", "}", "for", "(", "var", "j", "in", "attributes", ")", "{", "if", "(", "attributes", ".", "hasOwnProperty", "(", "j", ")", ")", "{", "anchors", "[", "a", "]", ".", "setAttribute", "(", "j", ",", "attributes", "[", "j", "]", ")", ";", "}", "}", "}", "}" ]
Changes attributes of links
[ "Changes", "attributes", "of", "links" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L10351-L10369
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
_execCommand
function _execCommand(doc, composer, command, nodeName, className) { var ranges = composer.selection.getOwnRanges(); for (var i = ranges.length; i--;){ composer.selection.getSelection().removeAllRanges(); composer.selection.setSelection(ranges[i]); if (className) { var eventListener = dom.observe(doc, "DOMNodeInserted", function(event) { var target = event.target, displayStyle; if (target.nodeType !== wysihtml5.ELEMENT_NODE) { return; } displayStyle = dom.getStyle("display").from(target); if (displayStyle.substr(0, 6) !== "inline") { // Make sure that only block elements receive the given class target.className += " " + className; } }); } doc.execCommand(command, false, nodeName); if (eventListener) { eventListener.stop(); } } }
javascript
function _execCommand(doc, composer, command, nodeName, className) { var ranges = composer.selection.getOwnRanges(); for (var i = ranges.length; i--;){ composer.selection.getSelection().removeAllRanges(); composer.selection.setSelection(ranges[i]); if (className) { var eventListener = dom.observe(doc, "DOMNodeInserted", function(event) { var target = event.target, displayStyle; if (target.nodeType !== wysihtml5.ELEMENT_NODE) { return; } displayStyle = dom.getStyle("display").from(target); if (displayStyle.substr(0, 6) !== "inline") { // Make sure that only block elements receive the given class target.className += " " + className; } }); } doc.execCommand(command, false, nodeName); if (eventListener) { eventListener.stop(); } } }
[ "function", "_execCommand", "(", "doc", ",", "composer", ",", "command", ",", "nodeName", ",", "className", ")", "{", "var", "ranges", "=", "composer", ".", "selection", ".", "getOwnRanges", "(", ")", ";", "for", "(", "var", "i", "=", "ranges", ".", "length", ";", "i", "--", ";", ")", "{", "composer", ".", "selection", ".", "getSelection", "(", ")", ".", "removeAllRanges", "(", ")", ";", "composer", ".", "selection", ".", "setSelection", "(", "ranges", "[", "i", "]", ")", ";", "if", "(", "className", ")", "{", "var", "eventListener", "=", "dom", ".", "observe", "(", "doc", ",", "\"DOMNodeInserted\"", ",", "function", "(", "event", ")", "{", "var", "target", "=", "event", ".", "target", ",", "displayStyle", ";", "if", "(", "target", ".", "nodeType", "!==", "wysihtml5", ".", "ELEMENT_NODE", ")", "{", "return", ";", "}", "displayStyle", "=", "dom", ".", "getStyle", "(", "\"display\"", ")", ".", "from", "(", "target", ")", ";", "if", "(", "displayStyle", ".", "substr", "(", "0", ",", "6", ")", "!==", "\"inline\"", ")", "{", "target", ".", "className", "+=", "\" \"", "+", "className", ";", "}", "}", ")", ";", "}", "doc", ".", "execCommand", "(", "command", ",", "false", ",", "nodeName", ")", ";", "if", "(", "eventListener", ")", "{", "eventListener", ".", "stop", "(", ")", ";", "}", "}", "}" ]
Execute native query command and if necessary modify the inserted node's className
[ "Execute", "native", "query", "command", "and", "if", "necessary", "modify", "the", "inserted", "node", "s", "className" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L10674-L10699
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp) { var that = this; if (this.state(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp) && composer.selection.isCollapsed() && !composer.selection.caretIsLastInSelection() && !composer.selection.caretIsFirstInSelection() ) { var state_element = that.state(composer, command, tagName, className, classRegExp)[0]; composer.selection.executeAndRestoreRangy(function() { var parent = state_element.parentNode; composer.selection.selectNode(state_element, true); wysihtml5.commands.formatInline.exec(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp, true, true); }); } else { if (this.state(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp) && !composer.selection.isCollapsed()) { composer.selection.executeAndRestoreRangy(function() { wysihtml5.commands.formatInline.exec(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp, true, true); }); } else { wysihtml5.commands.formatInline.exec(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp); } } }
javascript
function(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp) { var that = this; if (this.state(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp) && composer.selection.isCollapsed() && !composer.selection.caretIsLastInSelection() && !composer.selection.caretIsFirstInSelection() ) { var state_element = that.state(composer, command, tagName, className, classRegExp)[0]; composer.selection.executeAndRestoreRangy(function() { var parent = state_element.parentNode; composer.selection.selectNode(state_element, true); wysihtml5.commands.formatInline.exec(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp, true, true); }); } else { if (this.state(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp) && !composer.selection.isCollapsed()) { composer.selection.executeAndRestoreRangy(function() { wysihtml5.commands.formatInline.exec(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp, true, true); }); } else { wysihtml5.commands.formatInline.exec(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp); } } }
[ "function", "(", "composer", ",", "command", ",", "tagName", ",", "className", ",", "classRegExp", ",", "cssStyle", ",", "styleRegExp", ")", "{", "var", "that", "=", "this", ";", "if", "(", "this", ".", "state", "(", "composer", ",", "command", ",", "tagName", ",", "className", ",", "classRegExp", ",", "cssStyle", ",", "styleRegExp", ")", "&&", "composer", ".", "selection", ".", "isCollapsed", "(", ")", "&&", "!", "composer", ".", "selection", ".", "caretIsLastInSelection", "(", ")", "&&", "!", "composer", ".", "selection", ".", "caretIsFirstInSelection", "(", ")", ")", "{", "var", "state_element", "=", "that", ".", "state", "(", "composer", ",", "command", ",", "tagName", ",", "className", ",", "classRegExp", ")", "[", "0", "]", ";", "composer", ".", "selection", ".", "executeAndRestoreRangy", "(", "function", "(", ")", "{", "var", "parent", "=", "state_element", ".", "parentNode", ";", "composer", ".", "selection", ".", "selectNode", "(", "state_element", ",", "true", ")", ";", "wysihtml5", ".", "commands", ".", "formatInline", ".", "exec", "(", "composer", ",", "command", ",", "tagName", ",", "className", ",", "classRegExp", ",", "cssStyle", ",", "styleRegExp", ",", "true", ",", "true", ")", ";", "}", ")", ";", "}", "else", "{", "if", "(", "this", ".", "state", "(", "composer", ",", "command", ",", "tagName", ",", "className", ",", "classRegExp", ",", "cssStyle", ",", "styleRegExp", ")", "&&", "!", "composer", ".", "selection", ".", "isCollapsed", "(", ")", ")", "{", "composer", ".", "selection", ".", "executeAndRestoreRangy", "(", "function", "(", ")", "{", "wysihtml5", ".", "commands", ".", "formatInline", ".", "exec", "(", "composer", ",", "command", ",", "tagName", ",", "className", ",", "classRegExp", ",", "cssStyle", ",", "styleRegExp", ",", "true", ",", "true", ")", ";", "}", ")", ";", "}", "else", "{", "wysihtml5", ".", "commands", ".", "formatInline", ".", "exec", "(", "composer", ",", "command", ",", "tagName", ",", "className", ",", "classRegExp", ",", "cssStyle", ",", "styleRegExp", ")", ";", "}", "}", "}" ]
Executes so that if collapsed caret is in a state and executing that state it should unformat that state It is achieved by selecting the entire state element before executing. This works on built in contenteditable inline format commands
[ "Executes", "so", "that", "if", "collapsed", "caret", "is", "in", "a", "state", "and", "executing", "that", "state", "it", "should", "unformat", "that", "state", "It", "is", "achieved", "by", "selecting", "the", "entire", "state", "element", "before", "executing", ".", "This", "works", "on", "built", "in", "contenteditable", "inline", "format", "commands" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L10981-L11004
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function() { if (this.textarea.element.form) { var hiddenField = document.createElement("input"); hiddenField.type = "hidden"; hiddenField.name = "_wysihtml5_mode"; hiddenField.value = 1; dom.insert(hiddenField).after(this.textarea.element); } }
javascript
function() { if (this.textarea.element.form) { var hiddenField = document.createElement("input"); hiddenField.type = "hidden"; hiddenField.name = "_wysihtml5_mode"; hiddenField.value = 1; dom.insert(hiddenField).after(this.textarea.element); } }
[ "function", "(", ")", "{", "if", "(", "this", ".", "textarea", ".", "element", ".", "form", ")", "{", "var", "hiddenField", "=", "document", ".", "createElement", "(", "\"input\"", ")", ";", "hiddenField", ".", "type", "=", "\"hidden\"", ";", "hiddenField", ".", "name", "=", "\"_wysihtml5_mode\"", ";", "hiddenField", ".", "value", "=", "1", ";", "dom", ".", "insert", "(", "hiddenField", ")", ".", "after", "(", "this", ".", "textarea", ".", "element", ")", ";", "}", "}" ]
Creates hidden field which tells the server after submit, that the user used an wysiwyg editor
[ "Creates", "hidden", "field", "which", "tells", "the", "server", "after", "submit", "that", "the", "user", "used", "an", "wysiwyg", "editor" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L12178-L12186
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(shouldParseHtml) { this.textarea.setValue(wysihtml5.lang.string(this.composer.getValue(false, false)).trim(), shouldParseHtml); }
javascript
function(shouldParseHtml) { this.textarea.setValue(wysihtml5.lang.string(this.composer.getValue(false, false)).trim(), shouldParseHtml); }
[ "function", "(", "shouldParseHtml", ")", "{", "this", ".", "textarea", ".", "setValue", "(", "wysihtml5", ".", "lang", ".", "string", "(", "this", ".", "composer", ".", "getValue", "(", "false", ",", "false", ")", ")", ".", "trim", "(", ")", ",", "shouldParseHtml", ")", ";", "}" ]
Sync html from composer to textarea Takes care of placeholders @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the textarea
[ "Sync", "html", "from", "composer", "to", "textarea", "Takes", "care", "of", "placeholders" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L13045-L13047
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function(shouldParseHtml) { var textareaValue = this.textarea.getValue(false, false); if (textareaValue) { this.composer.setValue(textareaValue, shouldParseHtml); } else { this.composer.clear(); this.editor.fire("set_placeholder"); } }
javascript
function(shouldParseHtml) { var textareaValue = this.textarea.getValue(false, false); if (textareaValue) { this.composer.setValue(textareaValue, shouldParseHtml); } else { this.composer.clear(); this.editor.fire("set_placeholder"); } }
[ "function", "(", "shouldParseHtml", ")", "{", "var", "textareaValue", "=", "this", ".", "textarea", ".", "getValue", "(", "false", ",", "false", ")", ";", "if", "(", "textareaValue", ")", "{", "this", ".", "composer", ".", "setValue", "(", "textareaValue", ",", "shouldParseHtml", ")", ";", "}", "else", "{", "this", ".", "composer", ".", "clear", "(", ")", ";", "this", ".", "editor", ".", "fire", "(", "\"set_placeholder\"", ")", ";", "}", "}" ]
Sync value of textarea to composer Takes care of placeholders @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the composer
[ "Sync", "value", "of", "textarea", "to", "composer", "Takes", "care", "of", "placeholders" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L13054-L13062
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function() { var interval, that = this, form = this.textarea.element.form, startInterval = function() { interval = setInterval(function() { that.fromComposerToTextarea(); }, INTERVAL); }, stopInterval = function() { clearInterval(interval); interval = null; }; startInterval(); if (form) { // If the textarea is in a form make sure that after onreset and onsubmit the composer // has the correct state wysihtml5.dom.observe(form, "submit", function() { that.sync(true); }); wysihtml5.dom.observe(form, "reset", function() { setTimeout(function() { that.fromTextareaToComposer(); }, 0); }); } this.editor.on("change_view", function(view) { if (view === "composer" && !interval) { that.fromTextareaToComposer(true); startInterval(); } else if (view === "textarea") { that.fromComposerToTextarea(true); stopInterval(); } }); this.editor.on("destroy:composer", stopInterval); }
javascript
function() { var interval, that = this, form = this.textarea.element.form, startInterval = function() { interval = setInterval(function() { that.fromComposerToTextarea(); }, INTERVAL); }, stopInterval = function() { clearInterval(interval); interval = null; }; startInterval(); if (form) { // If the textarea is in a form make sure that after onreset and onsubmit the composer // has the correct state wysihtml5.dom.observe(form, "submit", function() { that.sync(true); }); wysihtml5.dom.observe(form, "reset", function() { setTimeout(function() { that.fromTextareaToComposer(); }, 0); }); } this.editor.on("change_view", function(view) { if (view === "composer" && !interval) { that.fromTextareaToComposer(true); startInterval(); } else if (view === "textarea") { that.fromComposerToTextarea(true); stopInterval(); } }); this.editor.on("destroy:composer", stopInterval); }
[ "function", "(", ")", "{", "var", "interval", ",", "that", "=", "this", ",", "form", "=", "this", ".", "textarea", ".", "element", ".", "form", ",", "startInterval", "=", "function", "(", ")", "{", "interval", "=", "setInterval", "(", "function", "(", ")", "{", "that", ".", "fromComposerToTextarea", "(", ")", ";", "}", ",", "INTERVAL", ")", ";", "}", ",", "stopInterval", "=", "function", "(", ")", "{", "clearInterval", "(", "interval", ")", ";", "interval", "=", "null", ";", "}", ";", "startInterval", "(", ")", ";", "if", "(", "form", ")", "{", "wysihtml5", ".", "dom", ".", "observe", "(", "form", ",", "\"submit\"", ",", "function", "(", ")", "{", "that", ".", "sync", "(", "true", ")", ";", "}", ")", ";", "wysihtml5", ".", "dom", ".", "observe", "(", "form", ",", "\"reset\"", ",", "function", "(", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "that", ".", "fromTextareaToComposer", "(", ")", ";", "}", ",", "0", ")", ";", "}", ")", ";", "}", "this", ".", "editor", ".", "on", "(", "\"change_view\"", ",", "function", "(", "view", ")", "{", "if", "(", "view", "===", "\"composer\"", "&&", "!", "interval", ")", "{", "that", ".", "fromTextareaToComposer", "(", "true", ")", ";", "startInterval", "(", ")", ";", "}", "else", "if", "(", "view", "===", "\"textarea\"", ")", "{", "that", ".", "fromComposerToTextarea", "(", "true", ")", ";", "stopInterval", "(", ")", ";", "}", "}", ")", ";", "this", ".", "editor", ".", "on", "(", "\"destroy:composer\"", ",", "stopInterval", ")", ";", "}" ]
Initializes interval-based syncing also makes sure that on-submit the composer's content is synced with the textarea immediately when the form gets submitted
[ "Initializes", "interval", "-", "based", "syncing", "also", "makes", "sure", "that", "on", "-", "submit", "the", "composer", "s", "content", "is", "synced", "with", "the", "textarea", "immediately", "when", "the", "form", "gets", "submitted" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L13081-L13117
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function() { var that = this, oldHtml, cleanHtml; if (wysihtml5.browser.supportsModenPaste()) { this.on("paste:composer", function(event) { event.preventDefault(); oldHtml = wysihtml5.dom.getPastedHtml(event); if (oldHtml) { that._cleanAndPaste(oldHtml); } }); } else { this.on("beforepaste:composer", function(event) { event.preventDefault(); wysihtml5.dom.getPastedHtmlWithDiv(that.composer, function(pastedHTML) { if (pastedHTML) { that._cleanAndPaste(pastedHTML); } }); }); } }
javascript
function() { var that = this, oldHtml, cleanHtml; if (wysihtml5.browser.supportsModenPaste()) { this.on("paste:composer", function(event) { event.preventDefault(); oldHtml = wysihtml5.dom.getPastedHtml(event); if (oldHtml) { that._cleanAndPaste(oldHtml); } }); } else { this.on("beforepaste:composer", function(event) { event.preventDefault(); wysihtml5.dom.getPastedHtmlWithDiv(that.composer, function(pastedHTML) { if (pastedHTML) { that._cleanAndPaste(pastedHTML); } }); }); } }
[ "function", "(", ")", "{", "var", "that", "=", "this", ",", "oldHtml", ",", "cleanHtml", ";", "if", "(", "wysihtml5", ".", "browser", ".", "supportsModenPaste", "(", ")", ")", "{", "this", ".", "on", "(", "\"paste:composer\"", ",", "function", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "oldHtml", "=", "wysihtml5", ".", "dom", ".", "getPastedHtml", "(", "event", ")", ";", "if", "(", "oldHtml", ")", "{", "that", ".", "_cleanAndPaste", "(", "oldHtml", ")", ";", "}", "}", ")", ";", "}", "else", "{", "this", ".", "on", "(", "\"beforepaste:composer\"", ",", "function", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "wysihtml5", ".", "dom", ".", "getPastedHtmlWithDiv", "(", "that", ".", "composer", ",", "function", "(", "pastedHTML", ")", "{", "if", "(", "pastedHTML", ")", "{", "that", ".", "_cleanAndPaste", "(", "pastedHTML", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", "}" ]
Prepare html parser logic - Observes for paste and drop
[ "Prepare", "html", "parser", "logic", "-", "Observes", "for", "paste", "and", "drop" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L13395-L13420
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function() { var data = this.elementToChange || {}, fields = this.container.querySelectorAll(SELECTOR_FIELDS), length = fields.length, i = 0; for (; i<length; i++) { data[fields[i].getAttribute(ATTRIBUTE_FIELDS)] = fields[i].value; } return data; }
javascript
function() { var data = this.elementToChange || {}, fields = this.container.querySelectorAll(SELECTOR_FIELDS), length = fields.length, i = 0; for (; i<length; i++) { data[fields[i].getAttribute(ATTRIBUTE_FIELDS)] = fields[i].value; } return data; }
[ "function", "(", ")", "{", "var", "data", "=", "this", ".", "elementToChange", "||", "{", "}", ",", "fields", "=", "this", ".", "container", ".", "querySelectorAll", "(", "SELECTOR_FIELDS", ")", ",", "length", "=", "fields", ".", "length", ",", "i", "=", "0", ";", "for", "(", ";", "i", "<", "length", ";", "i", "++", ")", "{", "data", "[", "fields", "[", "i", "]", ".", "getAttribute", "(", "ATTRIBUTE_FIELDS", ")", "]", "=", "fields", "[", "i", "]", ".", "value", ";", "}", "return", "data", ";", "}" ]
Grabs all fields in the dialog and puts them in key=>value style in an object which then gets returned
[ "Grabs", "all", "fields", "in", "the", "dialog", "and", "puts", "them", "in", "key", "=", ">", "value", "style", "in", "an", "object", "which", "then", "gets", "returned" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L13537-L13547
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function() { clearInterval(this.interval); this.elementToChange = null; dom.removeClass(this.link, CLASS_NAME_OPENED); this.container.style.display = "none"; this.fire("hide"); }
javascript
function() { clearInterval(this.interval); this.elementToChange = null; dom.removeClass(this.link, CLASS_NAME_OPENED); this.container.style.display = "none"; this.fire("hide"); }
[ "function", "(", ")", "{", "clearInterval", "(", "this", ".", "interval", ")", ";", "this", ".", "elementToChange", "=", "null", ";", "dom", ".", "removeClass", "(", "this", ".", "link", ",", "CLASS_NAME_OPENED", ")", ";", "this", ".", "container", ".", "style", ".", "display", "=", "\"none\"", ";", "this", ".", "fire", "(", "\"hide\"", ")", ";", "}" ]
Hide the dialog element
[ "Hide", "the", "dialog", "element" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L13624-L13630
train
ColorlibHQ/AdminLTE
plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js
function() { var editor = this; $.map(this.toolbar.commandMapping, function(value) { return [value]; }).filter(function(commandObj) { return commandObj.dialog; }).map(function(commandObj) { return commandObj.dialog; }).forEach(function(dialog) { dialog.on('show', function() { $(this.container).modal('show'); }); dialog.on('hide', function() { $(this.container).modal('hide'); setTimeout(editor.composer.focus, 0); }); $(dialog.container).on('shown.bs.modal', function () { $(this).find('input, select, textarea').first().focus(); }); }); this.on('change_view', function() { $(this.toolbar.container.children).find('a.btn').not('[data-wysihtml5-action="change_view"]').toggleClass('disabled'); }); }
javascript
function() { var editor = this; $.map(this.toolbar.commandMapping, function(value) { return [value]; }).filter(function(commandObj) { return commandObj.dialog; }).map(function(commandObj) { return commandObj.dialog; }).forEach(function(dialog) { dialog.on('show', function() { $(this.container).modal('show'); }); dialog.on('hide', function() { $(this.container).modal('hide'); setTimeout(editor.composer.focus, 0); }); $(dialog.container).on('shown.bs.modal', function () { $(this).find('input, select, textarea').first().focus(); }); }); this.on('change_view', function() { $(this.toolbar.container.children).find('a.btn').not('[data-wysihtml5-action="change_view"]').toggleClass('disabled'); }); }
[ "function", "(", ")", "{", "var", "editor", "=", "this", ";", "$", ".", "map", "(", "this", ".", "toolbar", ".", "commandMapping", ",", "function", "(", "value", ")", "{", "return", "[", "value", "]", ";", "}", ")", ".", "filter", "(", "function", "(", "commandObj", ")", "{", "return", "commandObj", ".", "dialog", ";", "}", ")", ".", "map", "(", "function", "(", "commandObj", ")", "{", "return", "commandObj", ".", "dialog", ";", "}", ")", ".", "forEach", "(", "function", "(", "dialog", ")", "{", "dialog", ".", "on", "(", "'show'", ",", "function", "(", ")", "{", "$", "(", "this", ".", "container", ")", ".", "modal", "(", "'show'", ")", ";", "}", ")", ";", "dialog", ".", "on", "(", "'hide'", ",", "function", "(", ")", "{", "$", "(", "this", ".", "container", ")", ".", "modal", "(", "'hide'", ")", ";", "setTimeout", "(", "editor", ".", "composer", ".", "focus", ",", "0", ")", ";", "}", ")", ";", "$", "(", "dialog", ".", "container", ")", ".", "on", "(", "'shown.bs.modal'", ",", "function", "(", ")", "{", "$", "(", "this", ")", ".", "find", "(", "'input, select, textarea'", ")", ".", "first", "(", ")", ".", "focus", "(", ")", ";", "}", ")", ";", "}", ")", ";", "this", ".", "on", "(", "'change_view'", ",", "function", "(", ")", "{", "$", "(", "this", ".", "toolbar", ".", "container", ".", "children", ")", ".", "find", "(", "'a.btn'", ")", ".", "not", "(", "'[data-wysihtml5-action=\"change_view\"]'", ")", ".", "toggleClass", "(", "'disabled'", ")", ";", "}", ")", ";", "}" ]
sync wysihtml5 events for dialogs with bootstrap events
[ "sync", "wysihtml5", "events", "for", "dialogs", "with", "bootstrap", "events" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.js#L14691-L14714
train
ColorlibHQ/AdminLTE
dist/js/demo.js
store
function store(name, val) { if (typeof (Storage) !== 'undefined') { localStorage.setItem(name, val) } else { window.alert('Please use a modern browser to properly view this template!') } }
javascript
function store(name, val) { if (typeof (Storage) !== 'undefined') { localStorage.setItem(name, val) } else { window.alert('Please use a modern browser to properly view this template!') } }
[ "function", "store", "(", "name", ",", "val", ")", "{", "if", "(", "typeof", "(", "Storage", ")", "!==", "'undefined'", ")", "{", "localStorage", ".", "setItem", "(", "name", ",", "val", ")", "}", "else", "{", "window", ".", "alert", "(", "'Please use a modern browser to properly view this template!'", ")", "}", "}" ]
Store a new settings in the browser @param String name Name of the setting @param String val Value of the setting @returns void
[ "Store", "a", "new", "settings", "in", "the", "browser" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/dist/js/demo.js#L67-L73
train
ColorlibHQ/AdminLTE
bower_components/bootstrap-colorpicker/dist/js/bootstrap-colorpicker.js
function( val, predefinedColors, fallbackColor, fallbackFormat, hexNumberSignPrefix) { this.fallbackValue = fallbackColor ? ( (typeof fallbackColor === 'string') ? this.parse(fallbackColor) : fallbackColor ) : null; this.fallbackFormat = fallbackFormat ? fallbackFormat : 'rgba'; this.hexNumberSignPrefix = hexNumberSignPrefix === true; this.value = this.fallbackValue; this.origFormat = null; // original string format this.predefinedColors = predefinedColors ? predefinedColors : {}; // We don't want to share aliases across instances so we extend new object this.colors = $.extend({}, Color.webColors, this.predefinedColors); if (val) { if (typeof val.h !== 'undefined') { this.value = val; } else { this.setColor(String(val)); } } if (!this.value) { // Initial value is always black if no arguments are passed or val is empty this.value = { h: 0, s: 0, b: 0, a: 1 }; } }
javascript
function( val, predefinedColors, fallbackColor, fallbackFormat, hexNumberSignPrefix) { this.fallbackValue = fallbackColor ? ( (typeof fallbackColor === 'string') ? this.parse(fallbackColor) : fallbackColor ) : null; this.fallbackFormat = fallbackFormat ? fallbackFormat : 'rgba'; this.hexNumberSignPrefix = hexNumberSignPrefix === true; this.value = this.fallbackValue; this.origFormat = null; // original string format this.predefinedColors = predefinedColors ? predefinedColors : {}; // We don't want to share aliases across instances so we extend new object this.colors = $.extend({}, Color.webColors, this.predefinedColors); if (val) { if (typeof val.h !== 'undefined') { this.value = val; } else { this.setColor(String(val)); } } if (!this.value) { // Initial value is always black if no arguments are passed or val is empty this.value = { h: 0, s: 0, b: 0, a: 1 }; } }
[ "function", "(", "val", ",", "predefinedColors", ",", "fallbackColor", ",", "fallbackFormat", ",", "hexNumberSignPrefix", ")", "{", "this", ".", "fallbackValue", "=", "fallbackColor", "?", "(", "(", "typeof", "fallbackColor", "===", "'string'", ")", "?", "this", ".", "parse", "(", "fallbackColor", ")", ":", "fallbackColor", ")", ":", "null", ";", "this", ".", "fallbackFormat", "=", "fallbackFormat", "?", "fallbackFormat", ":", "'rgba'", ";", "this", ".", "hexNumberSignPrefix", "=", "hexNumberSignPrefix", "===", "true", ";", "this", ".", "value", "=", "this", ".", "fallbackValue", ";", "this", ".", "origFormat", "=", "null", ";", "this", ".", "predefinedColors", "=", "predefinedColors", "?", "predefinedColors", ":", "{", "}", ";", "this", ".", "colors", "=", "$", ".", "extend", "(", "{", "}", ",", "Color", ".", "webColors", ",", "this", ".", "predefinedColors", ")", ";", "if", "(", "val", ")", "{", "if", "(", "typeof", "val", ".", "h", "!==", "'undefined'", ")", "{", "this", ".", "value", "=", "val", ";", "}", "else", "{", "this", ".", "setColor", "(", "String", "(", "val", ")", ")", ";", "}", "}", "if", "(", "!", "this", ".", "value", ")", "{", "this", ".", "value", "=", "{", "h", ":", "0", ",", "s", ":", "0", ",", "b", ":", "0", ",", "a", ":", "1", "}", ";", "}", "}" ]
Color manipulation helper class @param {Object|String} [val] @param {Object} [predefinedColors] @param {String|null} [fallbackColor] @param {String|null} [fallbackFormat] @param {Boolean} [hexNumberSignPrefix] @constructor
[ "Color", "manipulation", "helper", "class" ]
19113c3cbc19a7afe0cfd3158d647064d2d30661
https://github.com/ColorlibHQ/AdminLTE/blob/19113c3cbc19a7afe0cfd3158d647064d2d30661/bower_components/bootstrap-colorpicker/dist/js/bootstrap-colorpicker.js#L37-L77
train