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 |
---|---|---|---|---|---|---|---|---|---|---|---|
GitbookIO/gitbook
|
lib/parse/parseLanguages.js
|
parseLanguages
|
function parseLanguages(book) {
var logger = book.getLogger();
return parseStructureFile(book, 'langs')
.spread(function(file, result) {
if (!file) {
return book;
}
var languages = Languages.createFromList(file, result);
logger.debug.ln('languages index file found at', file.getPath());
logger.info.ln('parsing multilingual book, with', languages.getList().size, 'languages');
return book.set('languages', languages);
});
}
|
javascript
|
function parseLanguages(book) {
var logger = book.getLogger();
return parseStructureFile(book, 'langs')
.spread(function(file, result) {
if (!file) {
return book;
}
var languages = Languages.createFromList(file, result);
logger.debug.ln('languages index file found at', file.getPath());
logger.info.ln('parsing multilingual book, with', languages.getList().size, 'languages');
return book.set('languages', languages);
});
}
|
[
"function",
"parseLanguages",
"(",
"book",
")",
"{",
"var",
"logger",
"=",
"book",
".",
"getLogger",
"(",
")",
";",
"return",
"parseStructureFile",
"(",
"book",
",",
"'langs'",
")",
".",
"spread",
"(",
"function",
"(",
"file",
",",
"result",
")",
"{",
"if",
"(",
"!",
"file",
")",
"{",
"return",
"book",
";",
"}",
"var",
"languages",
"=",
"Languages",
".",
"createFromList",
"(",
"file",
",",
"result",
")",
";",
"logger",
".",
"debug",
".",
"ln",
"(",
"'languages index file found at'",
",",
"file",
".",
"getPath",
"(",
")",
")",
";",
"logger",
".",
"info",
".",
"ln",
"(",
"'parsing multilingual book, with'",
",",
"languages",
".",
"getList",
"(",
")",
".",
"size",
",",
"'languages'",
")",
";",
"return",
"book",
".",
"set",
"(",
"'languages'",
",",
"languages",
")",
";",
"}",
")",
";",
"}"
] |
Parse languages list from book
@param {Book} book
@return {Promise<Book>}
|
[
"Parse",
"languages",
"list",
"from",
"book"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/parseLanguages.js#L10-L26
|
train
|
GitbookIO/gitbook
|
lib/output/website/onFinish.js
|
onFinish
|
function onFinish(output) {
var book = output.getBook();
var options = output.getOptions();
var prefix = options.get('prefix');
if (!book.isMultilingual()) {
return Promise(output);
}
var filePath = 'index.html';
var engine = createTemplateEngine(output, filePath);
var context = JSONUtils.encodeOutput(output);
// Render the theme
return Templating.renderFile(engine, prefix + '/languages.html', context)
// Write it to the disk
.then(function(tplOut) {
return writeFile(output, filePath, tplOut.getContent());
});
}
|
javascript
|
function onFinish(output) {
var book = output.getBook();
var options = output.getOptions();
var prefix = options.get('prefix');
if (!book.isMultilingual()) {
return Promise(output);
}
var filePath = 'index.html';
var engine = createTemplateEngine(output, filePath);
var context = JSONUtils.encodeOutput(output);
// Render the theme
return Templating.renderFile(engine, prefix + '/languages.html', context)
// Write it to the disk
.then(function(tplOut) {
return writeFile(output, filePath, tplOut.getContent());
});
}
|
[
"function",
"onFinish",
"(",
"output",
")",
"{",
"var",
"book",
"=",
"output",
".",
"getBook",
"(",
")",
";",
"var",
"options",
"=",
"output",
".",
"getOptions",
"(",
")",
";",
"var",
"prefix",
"=",
"options",
".",
"get",
"(",
"'prefix'",
")",
";",
"if",
"(",
"!",
"book",
".",
"isMultilingual",
"(",
")",
")",
"{",
"return",
"Promise",
"(",
"output",
")",
";",
"}",
"var",
"filePath",
"=",
"'index.html'",
";",
"var",
"engine",
"=",
"createTemplateEngine",
"(",
"output",
",",
"filePath",
")",
";",
"var",
"context",
"=",
"JSONUtils",
".",
"encodeOutput",
"(",
"output",
")",
";",
"return",
"Templating",
".",
"renderFile",
"(",
"engine",
",",
"prefix",
"+",
"'/languages.html'",
",",
"context",
")",
".",
"then",
"(",
"function",
"(",
"tplOut",
")",
"{",
"return",
"writeFile",
"(",
"output",
",",
"filePath",
",",
"tplOut",
".",
"getContent",
"(",
")",
")",
";",
"}",
")",
";",
"}"
] |
Finish the generation, write the languages index
@param {Output}
@return {Output}
|
[
"Finish",
"the",
"generation",
"write",
"the",
"languages",
"index"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/website/onFinish.js#L13-L33
|
train
|
GitbookIO/gitbook
|
lib/output/generatePages.js
|
generatePages
|
function generatePages(generator, output) {
var pages = output.getPages();
var logger = output.getLogger();
// Is generator ignoring assets?
if (!generator.onPage) {
return Promise(output);
}
return Promise.reduce(pages, function(out, page) {
var file = page.getFile();
logger.debug.ln('generate page "' + file.getPath() + '"');
return generatePage(out, page)
.then(function(resultPage) {
return generator.onPage(out, resultPage);
})
.fail(function(err) {
logger.error.ln('error while generating page "' + file.getPath() + '":');
throw err;
});
}, output);
}
|
javascript
|
function generatePages(generator, output) {
var pages = output.getPages();
var logger = output.getLogger();
// Is generator ignoring assets?
if (!generator.onPage) {
return Promise(output);
}
return Promise.reduce(pages, function(out, page) {
var file = page.getFile();
logger.debug.ln('generate page "' + file.getPath() + '"');
return generatePage(out, page)
.then(function(resultPage) {
return generator.onPage(out, resultPage);
})
.fail(function(err) {
logger.error.ln('error while generating page "' + file.getPath() + '":');
throw err;
});
}, output);
}
|
[
"function",
"generatePages",
"(",
"generator",
",",
"output",
")",
"{",
"var",
"pages",
"=",
"output",
".",
"getPages",
"(",
")",
";",
"var",
"logger",
"=",
"output",
".",
"getLogger",
"(",
")",
";",
"if",
"(",
"!",
"generator",
".",
"onPage",
")",
"{",
"return",
"Promise",
"(",
"output",
")",
";",
"}",
"return",
"Promise",
".",
"reduce",
"(",
"pages",
",",
"function",
"(",
"out",
",",
"page",
")",
"{",
"var",
"file",
"=",
"page",
".",
"getFile",
"(",
")",
";",
"logger",
".",
"debug",
".",
"ln",
"(",
"'generate page \"'",
"+",
"file",
".",
"getPath",
"(",
")",
"+",
"'\"'",
")",
";",
"return",
"generatePage",
"(",
"out",
",",
"page",
")",
".",
"then",
"(",
"function",
"(",
"resultPage",
")",
"{",
"return",
"generator",
".",
"onPage",
"(",
"out",
",",
"resultPage",
")",
";",
"}",
")",
".",
"fail",
"(",
"function",
"(",
"err",
")",
"{",
"logger",
".",
"error",
".",
"ln",
"(",
"'error while generating page \"'",
"+",
"file",
".",
"getPath",
"(",
")",
"+",
"'\":'",
")",
";",
"throw",
"err",
";",
"}",
")",
";",
"}",
",",
"output",
")",
";",
"}"
] |
Output all pages using a generator
@param {Generator} generator
@param {Output} output
@return {Promise<Output>}
|
[
"Output",
"all",
"pages",
"using",
"a",
"generator"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/generatePages.js#L11-L34
|
train
|
GitbookIO/gitbook
|
lib/modifiers/config/addPlugin.js
|
addPlugin
|
function addPlugin(config, pluginName, version) {
// For default plugin, we only ensure it is enabled
if (isDefaultPlugin(pluginName, version)) {
return togglePlugin(config, pluginName, true);
}
var deps = config.getPluginDependencies();
var dep = PluginDependency.create(pluginName, version);
deps = deps.push(dep);
return config.setPluginDependencies(deps);
}
|
javascript
|
function addPlugin(config, pluginName, version) {
// For default plugin, we only ensure it is enabled
if (isDefaultPlugin(pluginName, version)) {
return togglePlugin(config, pluginName, true);
}
var deps = config.getPluginDependencies();
var dep = PluginDependency.create(pluginName, version);
deps = deps.push(dep);
return config.setPluginDependencies(deps);
}
|
[
"function",
"addPlugin",
"(",
"config",
",",
"pluginName",
",",
"version",
")",
"{",
"if",
"(",
"isDefaultPlugin",
"(",
"pluginName",
",",
"version",
")",
")",
"{",
"return",
"togglePlugin",
"(",
"config",
",",
"pluginName",
",",
"true",
")",
";",
"}",
"var",
"deps",
"=",
"config",
".",
"getPluginDependencies",
"(",
")",
";",
"var",
"dep",
"=",
"PluginDependency",
".",
"create",
"(",
"pluginName",
",",
"version",
")",
";",
"deps",
"=",
"deps",
".",
"push",
"(",
"dep",
")",
";",
"return",
"config",
".",
"setPluginDependencies",
"(",
"deps",
")",
";",
"}"
] |
Add a plugin to a book's configuration
@param {Config} config
@param {String} pluginName
@param {String} version (optional)
@return {Config}
|
[
"Add",
"a",
"plugin",
"to",
"a",
"book",
"s",
"configuration"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/config/addPlugin.js#L12-L23
|
train
|
GitbookIO/gitbook
|
lib/output/prepareAssets.js
|
prepareAssets
|
function prepareAssets(output) {
var book = output.getBook();
var pages = output.getPages();
var logger = output.getLogger();
return Parse.listAssets(book, pages)
.then(function(assets) {
logger.info.ln('found', assets.size, 'asset files');
return output.set('assets', assets);
});
}
|
javascript
|
function prepareAssets(output) {
var book = output.getBook();
var pages = output.getPages();
var logger = output.getLogger();
return Parse.listAssets(book, pages)
.then(function(assets) {
logger.info.ln('found', assets.size, 'asset files');
return output.set('assets', assets);
});
}
|
[
"function",
"prepareAssets",
"(",
"output",
")",
"{",
"var",
"book",
"=",
"output",
".",
"getBook",
"(",
")",
";",
"var",
"pages",
"=",
"output",
".",
"getPages",
"(",
")",
";",
"var",
"logger",
"=",
"output",
".",
"getLogger",
"(",
")",
";",
"return",
"Parse",
".",
"listAssets",
"(",
"book",
",",
"pages",
")",
".",
"then",
"(",
"function",
"(",
"assets",
")",
"{",
"logger",
".",
"info",
".",
"ln",
"(",
"'found'",
",",
"assets",
".",
"size",
",",
"'asset files'",
")",
";",
"return",
"output",
".",
"set",
"(",
"'assets'",
",",
"assets",
")",
";",
"}",
")",
";",
"}"
] |
List all assets in the book
@param {Output}
@return {Promise<Output>}
|
[
"List",
"all",
"assets",
"in",
"the",
"book"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/prepareAssets.js#L9-L20
|
train
|
GitbookIO/gitbook
|
lib/json/encodeGlossary.js
|
encodeGlossary
|
function encodeGlossary(glossary) {
var file = glossary.getFile();
var entries = glossary.getEntries();
return {
file: encodeFile(file),
entries: entries
.map(encodeGlossaryEntry).toJS()
};
}
|
javascript
|
function encodeGlossary(glossary) {
var file = glossary.getFile();
var entries = glossary.getEntries();
return {
file: encodeFile(file),
entries: entries
.map(encodeGlossaryEntry).toJS()
};
}
|
[
"function",
"encodeGlossary",
"(",
"glossary",
")",
"{",
"var",
"file",
"=",
"glossary",
".",
"getFile",
"(",
")",
";",
"var",
"entries",
"=",
"glossary",
".",
"getEntries",
"(",
")",
";",
"return",
"{",
"file",
":",
"encodeFile",
"(",
"file",
")",
",",
"entries",
":",
"entries",
".",
"map",
"(",
"encodeGlossaryEntry",
")",
".",
"toJS",
"(",
")",
"}",
";",
"}"
] |
Encode a glossary to JSON
@param {Glossary}
@return {Object}
|
[
"Encode",
"a",
"glossary",
"to",
"JSON"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/json/encodeGlossary.js#L10-L19
|
train
|
GitbookIO/gitbook
|
lib/utils/timing.js
|
measure
|
function measure(type, p) {
timers[type] = timers[type] || {
type: type,
count: 0,
total: 0,
min: undefined,
max: 0
};
var start = Date.now();
return p
.fin(function() {
var end = Date.now();
var duration = (end - start);
timers[type].count ++;
timers[type].total += duration;
if (is.undefined(timers[type].min)) {
timers[type].min = duration;
} else {
timers[type].min = Math.min(timers[type].min, duration);
}
timers[type].max = Math.max(timers[type].max, duration);
});
}
|
javascript
|
function measure(type, p) {
timers[type] = timers[type] || {
type: type,
count: 0,
total: 0,
min: undefined,
max: 0
};
var start = Date.now();
return p
.fin(function() {
var end = Date.now();
var duration = (end - start);
timers[type].count ++;
timers[type].total += duration;
if (is.undefined(timers[type].min)) {
timers[type].min = duration;
} else {
timers[type].min = Math.min(timers[type].min, duration);
}
timers[type].max = Math.max(timers[type].max, duration);
});
}
|
[
"function",
"measure",
"(",
"type",
",",
"p",
")",
"{",
"timers",
"[",
"type",
"]",
"=",
"timers",
"[",
"type",
"]",
"||",
"{",
"type",
":",
"type",
",",
"count",
":",
"0",
",",
"total",
":",
"0",
",",
"min",
":",
"undefined",
",",
"max",
":",
"0",
"}",
";",
"var",
"start",
"=",
"Date",
".",
"now",
"(",
")",
";",
"return",
"p",
".",
"fin",
"(",
"function",
"(",
")",
"{",
"var",
"end",
"=",
"Date",
".",
"now",
"(",
")",
";",
"var",
"duration",
"=",
"(",
"end",
"-",
"start",
")",
";",
"timers",
"[",
"type",
"]",
".",
"count",
"++",
";",
"timers",
"[",
"type",
"]",
".",
"total",
"+=",
"duration",
";",
"if",
"(",
"is",
".",
"undefined",
"(",
"timers",
"[",
"type",
"]",
".",
"min",
")",
")",
"{",
"timers",
"[",
"type",
"]",
".",
"min",
"=",
"duration",
";",
"}",
"else",
"{",
"timers",
"[",
"type",
"]",
".",
"min",
"=",
"Math",
".",
"min",
"(",
"timers",
"[",
"type",
"]",
".",
"min",
",",
"duration",
")",
";",
"}",
"timers",
"[",
"type",
"]",
".",
"max",
"=",
"Math",
".",
"max",
"(",
"timers",
"[",
"type",
"]",
".",
"max",
",",
"duration",
")",
";",
"}",
")",
";",
"}"
] |
Mesure an operation
@parqm {String} type
@param {Promise} p
@return {Promise}
|
[
"Mesure",
"an",
"operation"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/timing.js#L14-L41
|
train
|
GitbookIO/gitbook
|
lib/utils/timing.js
|
dump
|
function dump(logger) {
var prefix = ' > ';
var measured = 0;
var totalDuration = Date.now() - startDate;
// Enable debug logging
var logLevel = logger.getLevel();
logger.setLevel('debug');
Immutable.Map(timers)
.valueSeq()
.sortBy(function(timer) {
measured += timer.total;
return timer.total;
})
.forEach(function(timer) {
var percent = (timer.total * 100) / totalDuration;
logger.debug.ln((percent.toFixed(1)) + '% of time spent in "' + timer.type + '" (' + timer.count + ' times) :');
logger.debug.ln(prefix + 'Total: ' + time(timer.total)+ ' | Average: ' + time(timer.total / timer.count));
logger.debug.ln(prefix + 'Min: ' + time(timer.min) + ' | Max: ' + time(timer.max));
logger.debug.ln('---------------------------');
});
logger.debug.ln(time(totalDuration - measured) + ' spent in non-mesured sections');
// Rollback to previous level
logger.setLevel(logLevel);
}
|
javascript
|
function dump(logger) {
var prefix = ' > ';
var measured = 0;
var totalDuration = Date.now() - startDate;
// Enable debug logging
var logLevel = logger.getLevel();
logger.setLevel('debug');
Immutable.Map(timers)
.valueSeq()
.sortBy(function(timer) {
measured += timer.total;
return timer.total;
})
.forEach(function(timer) {
var percent = (timer.total * 100) / totalDuration;
logger.debug.ln((percent.toFixed(1)) + '% of time spent in "' + timer.type + '" (' + timer.count + ' times) :');
logger.debug.ln(prefix + 'Total: ' + time(timer.total)+ ' | Average: ' + time(timer.total / timer.count));
logger.debug.ln(prefix + 'Min: ' + time(timer.min) + ' | Max: ' + time(timer.max));
logger.debug.ln('---------------------------');
});
logger.debug.ln(time(totalDuration - measured) + ' spent in non-mesured sections');
// Rollback to previous level
logger.setLevel(logLevel);
}
|
[
"function",
"dump",
"(",
"logger",
")",
"{",
"var",
"prefix",
"=",
"' > '",
";",
"var",
"measured",
"=",
"0",
";",
"var",
"totalDuration",
"=",
"Date",
".",
"now",
"(",
")",
"-",
"startDate",
";",
"var",
"logLevel",
"=",
"logger",
".",
"getLevel",
"(",
")",
";",
"logger",
".",
"setLevel",
"(",
"'debug'",
")",
";",
"Immutable",
".",
"Map",
"(",
"timers",
")",
".",
"valueSeq",
"(",
")",
".",
"sortBy",
"(",
"function",
"(",
"timer",
")",
"{",
"measured",
"+=",
"timer",
".",
"total",
";",
"return",
"timer",
".",
"total",
";",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"timer",
")",
"{",
"var",
"percent",
"=",
"(",
"timer",
".",
"total",
"*",
"100",
")",
"/",
"totalDuration",
";",
"logger",
".",
"debug",
".",
"ln",
"(",
"(",
"percent",
".",
"toFixed",
"(",
"1",
")",
")",
"+",
"'% of time spent in \"'",
"+",
"timer",
".",
"type",
"+",
"'\" ('",
"+",
"timer",
".",
"count",
"+",
"' times) :'",
")",
";",
"logger",
".",
"debug",
".",
"ln",
"(",
"prefix",
"+",
"'Total: '",
"+",
"time",
"(",
"timer",
".",
"total",
")",
"+",
"' | Average: '",
"+",
"time",
"(",
"timer",
".",
"total",
"/",
"timer",
".",
"count",
")",
")",
";",
"logger",
".",
"debug",
".",
"ln",
"(",
"prefix",
"+",
"'Min: '",
"+",
"time",
"(",
"timer",
".",
"min",
")",
"+",
"' | Max: '",
"+",
"time",
"(",
"timer",
".",
"max",
")",
")",
";",
"logger",
".",
"debug",
".",
"ln",
"(",
"'---------------------------'",
")",
";",
"}",
")",
";",
"logger",
".",
"debug",
".",
"ln",
"(",
"time",
"(",
"totalDuration",
"-",
"measured",
")",
"+",
"' spent in non-mesured sections'",
")",
";",
"logger",
".",
"setLevel",
"(",
"logLevel",
")",
";",
"}"
] |
Dump all timers to a logger
@param {Logger} logger
|
[
"Dump",
"all",
"timers",
"to",
"a",
"logger"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/timing.js#L62-L92
|
train
|
GitbookIO/gitbook
|
lib/plugins/loadPlugin.js
|
loadPlugin
|
function loadPlugin(book, plugin) {
var logger = book.getLogger();
var name = plugin.getName();
var pkgPath = plugin.getPath();
// Try loading plugins from different location
var p = Promise()
.then(function() {
var packageContent;
var packageMain;
var content;
// Locate plugin and load package.json
try {
var res = resolve.sync('./package.json', { basedir: pkgPath });
pkgPath = path.dirname(res);
packageContent = require(res);
} catch (err) {
if (!isModuleNotFound(err)) throw err;
packageContent = undefined;
content = undefined;
return;
}
// Locate the main package
try {
var indexJs = path.normalize(packageContent.main || 'index.js');
packageMain = resolve.sync('./' + indexJs, { basedir: pkgPath });
} catch (err) {
if (!isModuleNotFound(err)) throw err;
packageMain = undefined;
}
// Load plugin JS content
if (packageMain) {
try {
content = require(packageMain);
} catch(err) {
throw new error.PluginError(err, {
plugin: name
});
}
}
// Update plugin
return plugin.merge({
'package': Immutable.fromJS(packageContent),
'content': Immutable.fromJS(content || {})
});
})
.then(validatePlugin);
p = timing.measure('plugin.load', p);
logger.info('loading plugin "' + name + '"... ');
return logger.info.promise(p);
}
|
javascript
|
function loadPlugin(book, plugin) {
var logger = book.getLogger();
var name = plugin.getName();
var pkgPath = plugin.getPath();
// Try loading plugins from different location
var p = Promise()
.then(function() {
var packageContent;
var packageMain;
var content;
// Locate plugin and load package.json
try {
var res = resolve.sync('./package.json', { basedir: pkgPath });
pkgPath = path.dirname(res);
packageContent = require(res);
} catch (err) {
if (!isModuleNotFound(err)) throw err;
packageContent = undefined;
content = undefined;
return;
}
// Locate the main package
try {
var indexJs = path.normalize(packageContent.main || 'index.js');
packageMain = resolve.sync('./' + indexJs, { basedir: pkgPath });
} catch (err) {
if (!isModuleNotFound(err)) throw err;
packageMain = undefined;
}
// Load plugin JS content
if (packageMain) {
try {
content = require(packageMain);
} catch(err) {
throw new error.PluginError(err, {
plugin: name
});
}
}
// Update plugin
return plugin.merge({
'package': Immutable.fromJS(packageContent),
'content': Immutable.fromJS(content || {})
});
})
.then(validatePlugin);
p = timing.measure('plugin.load', p);
logger.info('loading plugin "' + name + '"... ');
return logger.info.promise(p);
}
|
[
"function",
"loadPlugin",
"(",
"book",
",",
"plugin",
")",
"{",
"var",
"logger",
"=",
"book",
".",
"getLogger",
"(",
")",
";",
"var",
"name",
"=",
"plugin",
".",
"getName",
"(",
")",
";",
"var",
"pkgPath",
"=",
"plugin",
".",
"getPath",
"(",
")",
";",
"var",
"p",
"=",
"Promise",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"packageContent",
";",
"var",
"packageMain",
";",
"var",
"content",
";",
"try",
"{",
"var",
"res",
"=",
"resolve",
".",
"sync",
"(",
"'./package.json'",
",",
"{",
"basedir",
":",
"pkgPath",
"}",
")",
";",
"pkgPath",
"=",
"path",
".",
"dirname",
"(",
"res",
")",
";",
"packageContent",
"=",
"require",
"(",
"res",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"isModuleNotFound",
"(",
"err",
")",
")",
"throw",
"err",
";",
"packageContent",
"=",
"undefined",
";",
"content",
"=",
"undefined",
";",
"return",
";",
"}",
"try",
"{",
"var",
"indexJs",
"=",
"path",
".",
"normalize",
"(",
"packageContent",
".",
"main",
"||",
"'index.js'",
")",
";",
"packageMain",
"=",
"resolve",
".",
"sync",
"(",
"'./'",
"+",
"indexJs",
",",
"{",
"basedir",
":",
"pkgPath",
"}",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"isModuleNotFound",
"(",
"err",
")",
")",
"throw",
"err",
";",
"packageMain",
"=",
"undefined",
";",
"}",
"if",
"(",
"packageMain",
")",
"{",
"try",
"{",
"content",
"=",
"require",
"(",
"packageMain",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"throw",
"new",
"error",
".",
"PluginError",
"(",
"err",
",",
"{",
"plugin",
":",
"name",
"}",
")",
";",
"}",
"}",
"return",
"plugin",
".",
"merge",
"(",
"{",
"'package'",
":",
"Immutable",
".",
"fromJS",
"(",
"packageContent",
")",
",",
"'content'",
":",
"Immutable",
".",
"fromJS",
"(",
"content",
"||",
"{",
"}",
")",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"validatePlugin",
")",
";",
"p",
"=",
"timing",
".",
"measure",
"(",
"'plugin.load'",
",",
"p",
")",
";",
"logger",
".",
"info",
"(",
"'loading plugin \"'",
"+",
"name",
"+",
"'\"... '",
")",
";",
"return",
"logger",
".",
"info",
".",
"promise",
"(",
"p",
")",
";",
"}"
] |
Load a plugin in a book
@param {Book} book
@param {Plugin} plugin
@param {String} pkgPath (optional)
@return {Promise<Plugin>}
|
[
"Load",
"a",
"plugin",
"in",
"a",
"book"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/loadPlugin.js#L25-L86
|
train
|
GitbookIO/gitbook
|
lib/plugins/installPlugin.js
|
installPlugin
|
function installPlugin(book, plugin) {
var logger = book.getLogger();
var installFolder = book.getRoot();
var name = plugin.getName();
var requirement = plugin.getVersion();
logger.info.ln('');
logger.info.ln('installing plugin "' + name + '"');
// Find a version to install
return resolveVersion(plugin)
.then(function(version) {
if (!version) {
throw new Error('Found no satisfactory version for plugin "' + name + '" with requirement "' + requirement + '"');
}
logger.info.ln('install plugin "' + name +'" (' + requirement + ') from NPM with version', version);
return Promise.nfcall(npmi, {
'name': plugin.getNpmID(),
'version': version,
'path': installFolder,
'npmLoad': {
'loglevel': 'silent',
'loaded': true,
'prefix': installFolder
}
});
})
.then(function() {
logger.info.ok('plugin "' + name + '" installed with success');
});
}
|
javascript
|
function installPlugin(book, plugin) {
var logger = book.getLogger();
var installFolder = book.getRoot();
var name = plugin.getName();
var requirement = plugin.getVersion();
logger.info.ln('');
logger.info.ln('installing plugin "' + name + '"');
// Find a version to install
return resolveVersion(plugin)
.then(function(version) {
if (!version) {
throw new Error('Found no satisfactory version for plugin "' + name + '" with requirement "' + requirement + '"');
}
logger.info.ln('install plugin "' + name +'" (' + requirement + ') from NPM with version', version);
return Promise.nfcall(npmi, {
'name': plugin.getNpmID(),
'version': version,
'path': installFolder,
'npmLoad': {
'loglevel': 'silent',
'loaded': true,
'prefix': installFolder
}
});
})
.then(function() {
logger.info.ok('plugin "' + name + '" installed with success');
});
}
|
[
"function",
"installPlugin",
"(",
"book",
",",
"plugin",
")",
"{",
"var",
"logger",
"=",
"book",
".",
"getLogger",
"(",
")",
";",
"var",
"installFolder",
"=",
"book",
".",
"getRoot",
"(",
")",
";",
"var",
"name",
"=",
"plugin",
".",
"getName",
"(",
")",
";",
"var",
"requirement",
"=",
"plugin",
".",
"getVersion",
"(",
")",
";",
"logger",
".",
"info",
".",
"ln",
"(",
"''",
")",
";",
"logger",
".",
"info",
".",
"ln",
"(",
"'installing plugin \"'",
"+",
"name",
"+",
"'\"'",
")",
";",
"return",
"resolveVersion",
"(",
"plugin",
")",
".",
"then",
"(",
"function",
"(",
"version",
")",
"{",
"if",
"(",
"!",
"version",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Found no satisfactory version for plugin \"'",
"+",
"name",
"+",
"'\" with requirement \"'",
"+",
"requirement",
"+",
"'\"'",
")",
";",
"}",
"logger",
".",
"info",
".",
"ln",
"(",
"'install plugin \"'",
"+",
"name",
"+",
"'\" ('",
"+",
"requirement",
"+",
"') from NPM with version'",
",",
"version",
")",
";",
"return",
"Promise",
".",
"nfcall",
"(",
"npmi",
",",
"{",
"'name'",
":",
"plugin",
".",
"getNpmID",
"(",
")",
",",
"'version'",
":",
"version",
",",
"'path'",
":",
"installFolder",
",",
"'npmLoad'",
":",
"{",
"'loglevel'",
":",
"'silent'",
",",
"'loaded'",
":",
"true",
",",
"'prefix'",
":",
"installFolder",
"}",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"logger",
".",
"info",
".",
"ok",
"(",
"'plugin \"'",
"+",
"name",
"+",
"'\" installed with success'",
")",
";",
"}",
")",
";",
"}"
] |
Install a plugin for a book
@param {Book}
@param {PluginDependency}
@return {Promise}
|
[
"Install",
"a",
"plugin",
"for",
"a",
"book"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/installPlugin.js#L13-L45
|
train
|
GitbookIO/gitbook
|
lib/api/encodeSummary.js
|
encodeSummary
|
function encodeSummary(output, summary) {
var result = {
/**
Iterate over the summary, it stops when the "iter" returns false
@param {Function} iter
*/
walk: function (iter) {
summary.getArticle(function(article) {
var jsonArticle = encodeSummaryArticle(article, false);
return iter(jsonArticle);
});
},
/**
Get an article by its level
@param {String} level
@return {Object}
*/
getArticleByLevel: function(level) {
var article = summary.getByLevel(level);
return (article? encodeSummaryArticle(article) : undefined);
},
/**
Get an article by its path
@param {String} level
@return {Object}
*/
getArticleByPath: function(level) {
var article = summary.getByPath(level);
return (article? encodeSummaryArticle(article) : undefined);
}
};
return result;
}
|
javascript
|
function encodeSummary(output, summary) {
var result = {
/**
Iterate over the summary, it stops when the "iter" returns false
@param {Function} iter
*/
walk: function (iter) {
summary.getArticle(function(article) {
var jsonArticle = encodeSummaryArticle(article, false);
return iter(jsonArticle);
});
},
/**
Get an article by its level
@param {String} level
@return {Object}
*/
getArticleByLevel: function(level) {
var article = summary.getByLevel(level);
return (article? encodeSummaryArticle(article) : undefined);
},
/**
Get an article by its path
@param {String} level
@return {Object}
*/
getArticleByPath: function(level) {
var article = summary.getByPath(level);
return (article? encodeSummaryArticle(article) : undefined);
}
};
return result;
}
|
[
"function",
"encodeSummary",
"(",
"output",
",",
"summary",
")",
"{",
"var",
"result",
"=",
"{",
"walk",
":",
"function",
"(",
"iter",
")",
"{",
"summary",
".",
"getArticle",
"(",
"function",
"(",
"article",
")",
"{",
"var",
"jsonArticle",
"=",
"encodeSummaryArticle",
"(",
"article",
",",
"false",
")",
";",
"return",
"iter",
"(",
"jsonArticle",
")",
";",
"}",
")",
";",
"}",
",",
"getArticleByLevel",
":",
"function",
"(",
"level",
")",
"{",
"var",
"article",
"=",
"summary",
".",
"getByLevel",
"(",
"level",
")",
";",
"return",
"(",
"article",
"?",
"encodeSummaryArticle",
"(",
"article",
")",
":",
"undefined",
")",
";",
"}",
",",
"getArticleByPath",
":",
"function",
"(",
"level",
")",
"{",
"var",
"article",
"=",
"summary",
".",
"getByPath",
"(",
"level",
")",
";",
"return",
"(",
"article",
"?",
"encodeSummaryArticle",
"(",
"article",
")",
":",
"undefined",
")",
";",
"}",
"}",
";",
"return",
"result",
";",
"}"
] |
Encode summary to provide an API to plugin
@param {Output} output
@param {Config} config
@return {Object}
|
[
"Encode",
"summary",
"to",
"provide",
"an",
"API",
"to",
"plugin"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/encodeSummary.js#L10-L49
|
train
|
GitbookIO/gitbook
|
lib/api/encodeSummary.js
|
function (iter) {
summary.getArticle(function(article) {
var jsonArticle = encodeSummaryArticle(article, false);
return iter(jsonArticle);
});
}
|
javascript
|
function (iter) {
summary.getArticle(function(article) {
var jsonArticle = encodeSummaryArticle(article, false);
return iter(jsonArticle);
});
}
|
[
"function",
"(",
"iter",
")",
"{",
"summary",
".",
"getArticle",
"(",
"function",
"(",
"article",
")",
"{",
"var",
"jsonArticle",
"=",
"encodeSummaryArticle",
"(",
"article",
",",
"false",
")",
";",
"return",
"iter",
"(",
"jsonArticle",
")",
";",
"}",
")",
";",
"}"
] |
Iterate over the summary, it stops when the "iter" returns false
@param {Function} iter
|
[
"Iterate",
"over",
"the",
"summary",
"it",
"stops",
"when",
"the",
"iter",
"returns",
"false"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/encodeSummary.js#L17-L23
|
train
|
|
GitbookIO/gitbook
|
lib/modifiers/summary/indexLevels.js
|
indexLevels
|
function indexLevels(summary) {
var parts = summary.getParts();
parts = parts.map(indexPartLevels);
return summary.set('parts', parts);
}
|
javascript
|
function indexLevels(summary) {
var parts = summary.getParts();
parts = parts.map(indexPartLevels);
return summary.set('parts', parts);
}
|
[
"function",
"indexLevels",
"(",
"summary",
")",
"{",
"var",
"parts",
"=",
"summary",
".",
"getParts",
"(",
")",
";",
"parts",
"=",
"parts",
".",
"map",
"(",
"indexPartLevels",
")",
";",
"return",
"summary",
".",
"set",
"(",
"'parts'",
",",
"parts",
")",
";",
"}"
] |
Index all levels in the summary
@param {Summary}
@return {Summary}
|
[
"Index",
"all",
"levels",
"in",
"the",
"summary"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/summary/indexLevels.js#L9-L14
|
train
|
GitbookIO/gitbook
|
lib/models/templateBlock.js
|
extractKwargs
|
function extractKwargs(args) {
var last = args[args.length - 1];
return (is.object(last) && last.__keywords)? args.pop() : {};
}
|
javascript
|
function extractKwargs(args) {
var last = args[args.length - 1];
return (is.object(last) && last.__keywords)? args.pop() : {};
}
|
[
"function",
"extractKwargs",
"(",
"args",
")",
"{",
"var",
"last",
"=",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
";",
"return",
"(",
"is",
".",
"object",
"(",
"last",
")",
"&&",
"last",
".",
"__keywords",
")",
"?",
"args",
".",
"pop",
"(",
")",
":",
"{",
"}",
";",
"}"
] |
Extract kwargs from an arguments array
@param {Array} args
@return {Object}
|
[
"Extract",
"kwargs",
"from",
"an",
"arguments",
"array"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/models/templateBlock.js#L276-L279
|
train
|
GitbookIO/gitbook
|
lib/json/encodePage.js
|
encodePage
|
function encodePage(page, summary) {
var file = page.getFile();
var attributes = page.getAttributes();
var article = summary.getByPath(file.getPath());
var result = attributes.toJS();
if (article) {
result.title = article.getTitle();
result.level = article.getLevel();
result.depth = article.getDepth();
var nextArticle = summary.getNextArticle(article);
if (nextArticle) {
result.next = encodeSummaryArticle(nextArticle);
}
var prevArticle = summary.getPrevArticle(article);
if (prevArticle) {
result.previous = encodeSummaryArticle(prevArticle);
}
}
result.content = page.getContent();
result.dir = page.getDir();
return result;
}
|
javascript
|
function encodePage(page, summary) {
var file = page.getFile();
var attributes = page.getAttributes();
var article = summary.getByPath(file.getPath());
var result = attributes.toJS();
if (article) {
result.title = article.getTitle();
result.level = article.getLevel();
result.depth = article.getDepth();
var nextArticle = summary.getNextArticle(article);
if (nextArticle) {
result.next = encodeSummaryArticle(nextArticle);
}
var prevArticle = summary.getPrevArticle(article);
if (prevArticle) {
result.previous = encodeSummaryArticle(prevArticle);
}
}
result.content = page.getContent();
result.dir = page.getDir();
return result;
}
|
[
"function",
"encodePage",
"(",
"page",
",",
"summary",
")",
"{",
"var",
"file",
"=",
"page",
".",
"getFile",
"(",
")",
";",
"var",
"attributes",
"=",
"page",
".",
"getAttributes",
"(",
")",
";",
"var",
"article",
"=",
"summary",
".",
"getByPath",
"(",
"file",
".",
"getPath",
"(",
")",
")",
";",
"var",
"result",
"=",
"attributes",
".",
"toJS",
"(",
")",
";",
"if",
"(",
"article",
")",
"{",
"result",
".",
"title",
"=",
"article",
".",
"getTitle",
"(",
")",
";",
"result",
".",
"level",
"=",
"article",
".",
"getLevel",
"(",
")",
";",
"result",
".",
"depth",
"=",
"article",
".",
"getDepth",
"(",
")",
";",
"var",
"nextArticle",
"=",
"summary",
".",
"getNextArticle",
"(",
"article",
")",
";",
"if",
"(",
"nextArticle",
")",
"{",
"result",
".",
"next",
"=",
"encodeSummaryArticle",
"(",
"nextArticle",
")",
";",
"}",
"var",
"prevArticle",
"=",
"summary",
".",
"getPrevArticle",
"(",
"article",
")",
";",
"if",
"(",
"prevArticle",
")",
"{",
"result",
".",
"previous",
"=",
"encodeSummaryArticle",
"(",
"prevArticle",
")",
";",
"}",
"}",
"result",
".",
"content",
"=",
"page",
".",
"getContent",
"(",
")",
";",
"result",
".",
"dir",
"=",
"page",
".",
"getDir",
"(",
")",
";",
"return",
"result",
";",
"}"
] |
Return a JSON representation of a page
@param {Page} page
@param {Summary} summary
@return {Object}
|
[
"Return",
"a",
"JSON",
"representation",
"of",
"a",
"page"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/json/encodePage.js#L10-L37
|
train
|
GitbookIO/gitbook
|
lib/plugins/findInstalled.js
|
findInstalled
|
function findInstalled(folder) {
var options = {
dev: false,
log: function() {},
depth: 4
};
var results = Immutable.OrderedMap();
function onPackage(pkg, parent) {
if (!pkg.name) return;
var name = pkg.name;
var version = pkg.version;
var pkgPath = pkg.realPath;
var depth = pkg.depth;
var dependencies = pkg.dependencies;
var pluginName = name.slice(PREFIX.length);
if (!validateId(name)){
if (parent) return;
} else {
results = results.set(pluginName, Plugin({
name: pluginName,
version: version,
path: pkgPath,
depth: depth,
parent: parent
}));
}
Immutable.Map(dependencies).forEach(function(dep) {
onPackage(dep, pluginName);
});
}
// Search for gitbook-plugins in node_modules folder
var node_modules = path.join(folder, 'node_modules');
// List all folders in node_modules
return fs.readdir(node_modules)
.fail(function() {
return Promise([]);
})
.then(function(modules) {
return Promise.serie(modules, function(module) {
// Not a gitbook-plugin
if (!validateId(module)) {
return Promise();
}
// Read gitbook-plugin package details
var module_folder = path.join(node_modules, module);
return Promise.nfcall(readInstalled, module_folder, options)
.then(function(data) {
onPackage(data);
});
});
})
.then(function() {
// Return installed plugins
return results;
});
}
|
javascript
|
function findInstalled(folder) {
var options = {
dev: false,
log: function() {},
depth: 4
};
var results = Immutable.OrderedMap();
function onPackage(pkg, parent) {
if (!pkg.name) return;
var name = pkg.name;
var version = pkg.version;
var pkgPath = pkg.realPath;
var depth = pkg.depth;
var dependencies = pkg.dependencies;
var pluginName = name.slice(PREFIX.length);
if (!validateId(name)){
if (parent) return;
} else {
results = results.set(pluginName, Plugin({
name: pluginName,
version: version,
path: pkgPath,
depth: depth,
parent: parent
}));
}
Immutable.Map(dependencies).forEach(function(dep) {
onPackage(dep, pluginName);
});
}
// Search for gitbook-plugins in node_modules folder
var node_modules = path.join(folder, 'node_modules');
// List all folders in node_modules
return fs.readdir(node_modules)
.fail(function() {
return Promise([]);
})
.then(function(modules) {
return Promise.serie(modules, function(module) {
// Not a gitbook-plugin
if (!validateId(module)) {
return Promise();
}
// Read gitbook-plugin package details
var module_folder = path.join(node_modules, module);
return Promise.nfcall(readInstalled, module_folder, options)
.then(function(data) {
onPackage(data);
});
});
})
.then(function() {
// Return installed plugins
return results;
});
}
|
[
"function",
"findInstalled",
"(",
"folder",
")",
"{",
"var",
"options",
"=",
"{",
"dev",
":",
"false",
",",
"log",
":",
"function",
"(",
")",
"{",
"}",
",",
"depth",
":",
"4",
"}",
";",
"var",
"results",
"=",
"Immutable",
".",
"OrderedMap",
"(",
")",
";",
"function",
"onPackage",
"(",
"pkg",
",",
"parent",
")",
"{",
"if",
"(",
"!",
"pkg",
".",
"name",
")",
"return",
";",
"var",
"name",
"=",
"pkg",
".",
"name",
";",
"var",
"version",
"=",
"pkg",
".",
"version",
";",
"var",
"pkgPath",
"=",
"pkg",
".",
"realPath",
";",
"var",
"depth",
"=",
"pkg",
".",
"depth",
";",
"var",
"dependencies",
"=",
"pkg",
".",
"dependencies",
";",
"var",
"pluginName",
"=",
"name",
".",
"slice",
"(",
"PREFIX",
".",
"length",
")",
";",
"if",
"(",
"!",
"validateId",
"(",
"name",
")",
")",
"{",
"if",
"(",
"parent",
")",
"return",
";",
"}",
"else",
"{",
"results",
"=",
"results",
".",
"set",
"(",
"pluginName",
",",
"Plugin",
"(",
"{",
"name",
":",
"pluginName",
",",
"version",
":",
"version",
",",
"path",
":",
"pkgPath",
",",
"depth",
":",
"depth",
",",
"parent",
":",
"parent",
"}",
")",
")",
";",
"}",
"Immutable",
".",
"Map",
"(",
"dependencies",
")",
".",
"forEach",
"(",
"function",
"(",
"dep",
")",
"{",
"onPackage",
"(",
"dep",
",",
"pluginName",
")",
";",
"}",
")",
";",
"}",
"var",
"node_modules",
"=",
"path",
".",
"join",
"(",
"folder",
",",
"'node_modules'",
")",
";",
"return",
"fs",
".",
"readdir",
"(",
"node_modules",
")",
".",
"fail",
"(",
"function",
"(",
")",
"{",
"return",
"Promise",
"(",
"[",
"]",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"modules",
")",
"{",
"return",
"Promise",
".",
"serie",
"(",
"modules",
",",
"function",
"(",
"module",
")",
"{",
"if",
"(",
"!",
"validateId",
"(",
"module",
")",
")",
"{",
"return",
"Promise",
"(",
")",
";",
"}",
"var",
"module_folder",
"=",
"path",
".",
"join",
"(",
"node_modules",
",",
"module",
")",
";",
"return",
"Promise",
".",
"nfcall",
"(",
"readInstalled",
",",
"module_folder",
",",
"options",
")",
".",
"then",
"(",
"function",
"(",
"data",
")",
"{",
"onPackage",
"(",
"data",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"results",
";",
"}",
")",
";",
"}"
] |
List all packages installed inside a folder
@param {String} folder
@return {OrderedMap<String:Plugin>}
|
[
"List",
"all",
"packages",
"installed",
"inside",
"a",
"folder"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/findInstalled.js#L26-L89
|
train
|
GitbookIO/gitbook
|
lib/api/encodePage.js
|
encodePage
|
function encodePage(output, page) {
var book = output.getBook();
var summary = book.getSummary();
var fs = book.getContentFS();
var file = page.getFile();
// JS Page is based on the JSON output
var result = JSONUtils.encodePage(page, summary);
result.type = file.getType();
result.path = file.getPath();
result.rawPath = fs.resolve(result.path);
deprecate.field(output, 'page.progress', result, 'progress', function() {
return encodeProgress(output, page);
}, '"page.progress" property is deprecated');
deprecate.field(output, 'page.sections', result, 'sections', [
{
content: result.content,
type: 'normal'
}
], '"sections" property is deprecated, use page.content instead');
return result;
}
|
javascript
|
function encodePage(output, page) {
var book = output.getBook();
var summary = book.getSummary();
var fs = book.getContentFS();
var file = page.getFile();
// JS Page is based on the JSON output
var result = JSONUtils.encodePage(page, summary);
result.type = file.getType();
result.path = file.getPath();
result.rawPath = fs.resolve(result.path);
deprecate.field(output, 'page.progress', result, 'progress', function() {
return encodeProgress(output, page);
}, '"page.progress" property is deprecated');
deprecate.field(output, 'page.sections', result, 'sections', [
{
content: result.content,
type: 'normal'
}
], '"sections" property is deprecated, use page.content instead');
return result;
}
|
[
"function",
"encodePage",
"(",
"output",
",",
"page",
")",
"{",
"var",
"book",
"=",
"output",
".",
"getBook",
"(",
")",
";",
"var",
"summary",
"=",
"book",
".",
"getSummary",
"(",
")",
";",
"var",
"fs",
"=",
"book",
".",
"getContentFS",
"(",
")",
";",
"var",
"file",
"=",
"page",
".",
"getFile",
"(",
")",
";",
"var",
"result",
"=",
"JSONUtils",
".",
"encodePage",
"(",
"page",
",",
"summary",
")",
";",
"result",
".",
"type",
"=",
"file",
".",
"getType",
"(",
")",
";",
"result",
".",
"path",
"=",
"file",
".",
"getPath",
"(",
")",
";",
"result",
".",
"rawPath",
"=",
"fs",
".",
"resolve",
"(",
"result",
".",
"path",
")",
";",
"deprecate",
".",
"field",
"(",
"output",
",",
"'page.progress'",
",",
"result",
",",
"'progress'",
",",
"function",
"(",
")",
"{",
"return",
"encodeProgress",
"(",
"output",
",",
"page",
")",
";",
"}",
",",
"'\"page.progress\" property is deprecated'",
")",
";",
"deprecate",
".",
"field",
"(",
"output",
",",
"'page.sections'",
",",
"result",
",",
"'sections'",
",",
"[",
"{",
"content",
":",
"result",
".",
"content",
",",
"type",
":",
"'normal'",
"}",
"]",
",",
"'\"sections\" property is deprecated, use page.content instead'",
")",
";",
"return",
"result",
";",
"}"
] |
Encode a page in a context to a JS API
@param {Output} output
@param {Page} page
@return {Object}
|
[
"Encode",
"a",
"page",
"in",
"a",
"context",
"to",
"a",
"JS",
"API"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/encodePage.js#L12-L37
|
train
|
GitbookIO/gitbook
|
lib/api/deprecate.js
|
logNotice
|
function logNotice(book, key, message) {
if (logged[key] || disabled[key]) return;
logged[key] = true;
var logger = book.getLogger();
logger.warn.ln(message);
}
|
javascript
|
function logNotice(book, key, message) {
if (logged[key] || disabled[key]) return;
logged[key] = true;
var logger = book.getLogger();
logger.warn.ln(message);
}
|
[
"function",
"logNotice",
"(",
"book",
",",
"key",
",",
"message",
")",
"{",
"if",
"(",
"logged",
"[",
"key",
"]",
"||",
"disabled",
"[",
"key",
"]",
")",
"return",
";",
"logged",
"[",
"key",
"]",
"=",
"true",
";",
"var",
"logger",
"=",
"book",
".",
"getLogger",
"(",
")",
";",
"logger",
".",
"warn",
".",
"ln",
"(",
"message",
")",
";",
"}"
] |
Log a deprecated notice
@param {Book|Output} book
@param {String} key
@param {String} message
|
[
"Log",
"a",
"deprecated",
"notice"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/deprecate.js#L14-L21
|
train
|
GitbookIO/gitbook
|
lib/api/deprecate.js
|
deprecateMethod
|
function deprecateMethod(book, key, fn, msg) {
return function() {
logNotice(book, key, msg);
return fn.apply(this, arguments);
};
}
|
javascript
|
function deprecateMethod(book, key, fn, msg) {
return function() {
logNotice(book, key, msg);
return fn.apply(this, arguments);
};
}
|
[
"function",
"deprecateMethod",
"(",
"book",
",",
"key",
",",
"fn",
",",
"msg",
")",
"{",
"return",
"function",
"(",
")",
"{",
"logNotice",
"(",
"book",
",",
"key",
",",
"msg",
")",
";",
"return",
"fn",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
";",
"}"
] |
Deprecate a function
@param {Book|Output} book
@param {String} key: unique identitifer for the deprecated
@param {Function} fn
@param {String} msg: message to print when called
@return {Function}
|
[
"Deprecate",
"a",
"function"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/deprecate.js#L32-L38
|
train
|
GitbookIO/gitbook
|
lib/api/deprecate.js
|
deprecateField
|
function deprecateField(book, key, instance, property, value, msg) {
var store = undefined;
var prepare = function() {
if (!is.undefined(store)) return;
if (is.fn(value)) store = value();
else store = value;
};
var getter = function(){
prepare();
logNotice(book, key, msg);
return store;
};
var setter = function(v) {
prepare();
logNotice(book, key, msg);
store = v;
return store;
};
Object.defineProperty(instance, property, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
|
javascript
|
function deprecateField(book, key, instance, property, value, msg) {
var store = undefined;
var prepare = function() {
if (!is.undefined(store)) return;
if (is.fn(value)) store = value();
else store = value;
};
var getter = function(){
prepare();
logNotice(book, key, msg);
return store;
};
var setter = function(v) {
prepare();
logNotice(book, key, msg);
store = v;
return store;
};
Object.defineProperty(instance, property, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
|
[
"function",
"deprecateField",
"(",
"book",
",",
"key",
",",
"instance",
",",
"property",
",",
"value",
",",
"msg",
")",
"{",
"var",
"store",
"=",
"undefined",
";",
"var",
"prepare",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"is",
".",
"undefined",
"(",
"store",
")",
")",
"return",
";",
"if",
"(",
"is",
".",
"fn",
"(",
"value",
")",
")",
"store",
"=",
"value",
"(",
")",
";",
"else",
"store",
"=",
"value",
";",
"}",
";",
"var",
"getter",
"=",
"function",
"(",
")",
"{",
"prepare",
"(",
")",
";",
"logNotice",
"(",
"book",
",",
"key",
",",
"msg",
")",
";",
"return",
"store",
";",
"}",
";",
"var",
"setter",
"=",
"function",
"(",
"v",
")",
"{",
"prepare",
"(",
")",
";",
"logNotice",
"(",
"book",
",",
"key",
",",
"msg",
")",
";",
"store",
"=",
"v",
";",
"return",
"store",
";",
"}",
";",
"Object",
".",
"defineProperty",
"(",
"instance",
",",
"property",
",",
"{",
"get",
":",
"getter",
",",
"set",
":",
"setter",
",",
"enumerable",
":",
"true",
",",
"configurable",
":",
"true",
"}",
")",
";",
"}"
] |
Deprecate a property of an object
@param {Book|Output} book
@param {String} key: unique identitifer for the deprecated
@param {Object} instance
@param {String|Function} property
@param {String} msg: message to print when called
@return {Function}
|
[
"Deprecate",
"a",
"property",
"of",
"an",
"object"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/deprecate.js#L50-L80
|
train
|
GitbookIO/gitbook
|
lib/api/deprecate.js
|
deprecateRenamedMethod
|
function deprecateRenamedMethod(book, key, instance, oldName, newName, msg) {
msg = msg || ('"' + oldName + '" is deprecated, use "' + newName + '()" instead');
var fn = objectPath.get(instance, newName);
instance[oldName] = deprecateMethod(book, key, fn, msg);
}
|
javascript
|
function deprecateRenamedMethod(book, key, instance, oldName, newName, msg) {
msg = msg || ('"' + oldName + '" is deprecated, use "' + newName + '()" instead');
var fn = objectPath.get(instance, newName);
instance[oldName] = deprecateMethod(book, key, fn, msg);
}
|
[
"function",
"deprecateRenamedMethod",
"(",
"book",
",",
"key",
",",
"instance",
",",
"oldName",
",",
"newName",
",",
"msg",
")",
"{",
"msg",
"=",
"msg",
"||",
"(",
"'\"'",
"+",
"oldName",
"+",
"'\" is deprecated, use \"'",
"+",
"newName",
"+",
"'()\" instead'",
")",
";",
"var",
"fn",
"=",
"objectPath",
".",
"get",
"(",
"instance",
",",
"newName",
")",
";",
"instance",
"[",
"oldName",
"]",
"=",
"deprecateMethod",
"(",
"book",
",",
"key",
",",
"fn",
",",
"msg",
")",
";",
"}"
] |
Deprecate a method in favor of another one
@param {Book} book
@param {String} key
@param {Object} instance
@param {String} oldName
@param {String} newName
|
[
"Deprecate",
"a",
"method",
"in",
"favor",
"of",
"another",
"one"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/deprecate.js#L109-L114
|
train
|
GitbookIO/gitbook
|
lib/output/modifiers/modifyHTML.js
|
modifyHTML
|
function modifyHTML(page, operations) {
var html = page.getContent();
var $ = cheerio.load(html);
return Promise.forEach(operations, function(op) {
return op($);
})
.then(function() {
var resultHTML = $.html();
return page.set('content', resultHTML);
});
}
|
javascript
|
function modifyHTML(page, operations) {
var html = page.getContent();
var $ = cheerio.load(html);
return Promise.forEach(operations, function(op) {
return op($);
})
.then(function() {
var resultHTML = $.html();
return page.set('content', resultHTML);
});
}
|
[
"function",
"modifyHTML",
"(",
"page",
",",
"operations",
")",
"{",
"var",
"html",
"=",
"page",
".",
"getContent",
"(",
")",
";",
"var",
"$",
"=",
"cheerio",
".",
"load",
"(",
"html",
")",
";",
"return",
"Promise",
".",
"forEach",
"(",
"operations",
",",
"function",
"(",
"op",
")",
"{",
"return",
"op",
"(",
"$",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"resultHTML",
"=",
"$",
".",
"html",
"(",
")",
";",
"return",
"page",
".",
"set",
"(",
"'content'",
",",
"resultHTML",
")",
";",
"}",
")",
";",
"}"
] |
Apply a list of operations to a page and
output the new page.
@param {Page}
@param {List|Array<Transformation>}
@return {Promise<Page>}
|
[
"Apply",
"a",
"list",
"of",
"operations",
"to",
"a",
"page",
"and",
"output",
"the",
"new",
"page",
"."
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/modifiers/modifyHTML.js#L12-L23
|
train
|
GitbookIO/gitbook
|
lib/parse/validateConfig.js
|
validateConfig
|
function validateConfig(bookJson) {
var v = new jsonschema.Validator();
var result = v.validate(bookJson, schema, {
propertyName: 'config'
});
// Throw error
if (result.errors.length > 0) {
throw new error.ConfigurationError(new Error(result.errors[0].stack));
}
// Insert default values
var defaults = jsonSchemaDefaults(schema);
return mergeDefaults(bookJson, defaults);
}
|
javascript
|
function validateConfig(bookJson) {
var v = new jsonschema.Validator();
var result = v.validate(bookJson, schema, {
propertyName: 'config'
});
// Throw error
if (result.errors.length > 0) {
throw new error.ConfigurationError(new Error(result.errors[0].stack));
}
// Insert default values
var defaults = jsonSchemaDefaults(schema);
return mergeDefaults(bookJson, defaults);
}
|
[
"function",
"validateConfig",
"(",
"bookJson",
")",
"{",
"var",
"v",
"=",
"new",
"jsonschema",
".",
"Validator",
"(",
")",
";",
"var",
"result",
"=",
"v",
".",
"validate",
"(",
"bookJson",
",",
"schema",
",",
"{",
"propertyName",
":",
"'config'",
"}",
")",
";",
"if",
"(",
"result",
".",
"errors",
".",
"length",
">",
"0",
")",
"{",
"throw",
"new",
"error",
".",
"ConfigurationError",
"(",
"new",
"Error",
"(",
"result",
".",
"errors",
"[",
"0",
"]",
".",
"stack",
")",
")",
";",
"}",
"var",
"defaults",
"=",
"jsonSchemaDefaults",
"(",
"schema",
")",
";",
"return",
"mergeDefaults",
"(",
"bookJson",
",",
"defaults",
")",
";",
"}"
] |
Validate a book.json content
And return a mix with the default value
@param {Object} bookJson
@return {Object}
|
[
"Validate",
"a",
"book",
".",
"json",
"content",
"And",
"return",
"a",
"mix",
"with",
"the",
"default",
"value"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/validateConfig.js#L15-L29
|
train
|
GitbookIO/gitbook
|
lib/plugins/locateRootFolder.js
|
locateRootFolder
|
function locateRootFolder() {
var firstDefaultPlugin = DEFAULT_PLUGINS.first();
var pluginPath = resolve.sync(firstDefaultPlugin.getNpmID() + '/package.json', {
basedir: __dirname
});
var nodeModules = path.resolve(pluginPath, '../../..');
return nodeModules;
}
|
javascript
|
function locateRootFolder() {
var firstDefaultPlugin = DEFAULT_PLUGINS.first();
var pluginPath = resolve.sync(firstDefaultPlugin.getNpmID() + '/package.json', {
basedir: __dirname
});
var nodeModules = path.resolve(pluginPath, '../../..');
return nodeModules;
}
|
[
"function",
"locateRootFolder",
"(",
")",
"{",
"var",
"firstDefaultPlugin",
"=",
"DEFAULT_PLUGINS",
".",
"first",
"(",
")",
";",
"var",
"pluginPath",
"=",
"resolve",
".",
"sync",
"(",
"firstDefaultPlugin",
".",
"getNpmID",
"(",
")",
"+",
"'/package.json'",
",",
"{",
"basedir",
":",
"__dirname",
"}",
")",
";",
"var",
"nodeModules",
"=",
"path",
".",
"resolve",
"(",
"pluginPath",
",",
"'../../..'",
")",
";",
"return",
"nodeModules",
";",
"}"
] |
Resolve the root folder containing for node_modules
since gitbook can be used as a library and dependency can be flattened.
@return {String} folderPath
|
[
"Resolve",
"the",
"root",
"folder",
"containing",
"for",
"node_modules",
"since",
"gitbook",
"can",
"be",
"used",
"as",
"a",
"library",
"and",
"dependency",
"can",
"be",
"flattened",
"."
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/locateRootFolder.js#L12-L20
|
train
|
GitbookIO/gitbook
|
lib/output/generateBook.js
|
generateBook
|
function generateBook(generator, book, options) {
options = generator.Options(options);
var state = generator.State? generator.State({}) : Immutable.Map();
var start = Date.now();
return Promise(
new Output({
book: book,
options: options,
state: state,
generator: generator.name
})
)
// Cleanup output folder
.then(function(output) {
var logger = output.getLogger();
var rootFolder = output.getRoot();
logger.debug.ln('cleanup folder "' + rootFolder + '"');
return fs.ensureFolder(rootFolder)
.thenResolve(output);
})
.then(processOutput.bind(null, generator))
// Log duration and end message
.then(function(output) {
var logger = output.getLogger();
var end = Date.now();
var duration = (end - start)/1000;
logger.info.ok('generation finished with success in ' + duration.toFixed(1) + 's !');
return output;
});
}
|
javascript
|
function generateBook(generator, book, options) {
options = generator.Options(options);
var state = generator.State? generator.State({}) : Immutable.Map();
var start = Date.now();
return Promise(
new Output({
book: book,
options: options,
state: state,
generator: generator.name
})
)
// Cleanup output folder
.then(function(output) {
var logger = output.getLogger();
var rootFolder = output.getRoot();
logger.debug.ln('cleanup folder "' + rootFolder + '"');
return fs.ensureFolder(rootFolder)
.thenResolve(output);
})
.then(processOutput.bind(null, generator))
// Log duration and end message
.then(function(output) {
var logger = output.getLogger();
var end = Date.now();
var duration = (end - start)/1000;
logger.info.ok('generation finished with success in ' + duration.toFixed(1) + 's !');
return output;
});
}
|
[
"function",
"generateBook",
"(",
"generator",
",",
"book",
",",
"options",
")",
"{",
"options",
"=",
"generator",
".",
"Options",
"(",
"options",
")",
";",
"var",
"state",
"=",
"generator",
".",
"State",
"?",
"generator",
".",
"State",
"(",
"{",
"}",
")",
":",
"Immutable",
".",
"Map",
"(",
")",
";",
"var",
"start",
"=",
"Date",
".",
"now",
"(",
")",
";",
"return",
"Promise",
"(",
"new",
"Output",
"(",
"{",
"book",
":",
"book",
",",
"options",
":",
"options",
",",
"state",
":",
"state",
",",
"generator",
":",
"generator",
".",
"name",
"}",
")",
")",
".",
"then",
"(",
"function",
"(",
"output",
")",
"{",
"var",
"logger",
"=",
"output",
".",
"getLogger",
"(",
")",
";",
"var",
"rootFolder",
"=",
"output",
".",
"getRoot",
"(",
")",
";",
"logger",
".",
"debug",
".",
"ln",
"(",
"'cleanup folder \"'",
"+",
"rootFolder",
"+",
"'\"'",
")",
";",
"return",
"fs",
".",
"ensureFolder",
"(",
"rootFolder",
")",
".",
"thenResolve",
"(",
"output",
")",
";",
"}",
")",
".",
"then",
"(",
"processOutput",
".",
"bind",
"(",
"null",
",",
"generator",
")",
")",
".",
"then",
"(",
"function",
"(",
"output",
")",
"{",
"var",
"logger",
"=",
"output",
".",
"getLogger",
"(",
")",
";",
"var",
"end",
"=",
"Date",
".",
"now",
"(",
")",
";",
"var",
"duration",
"=",
"(",
"end",
"-",
"start",
")",
"/",
"1000",
";",
"logger",
".",
"info",
".",
"ok",
"(",
"'generation finished with success in '",
"+",
"duration",
".",
"toFixed",
"(",
"1",
")",
"+",
"'s !'",
")",
";",
"return",
"output",
";",
"}",
")",
";",
"}"
] |
Generate a book using a generator.
The overall process is:
1. List and load plugins for this book
2. Call hook "config"
3. Call hook "init"
4. Initialize generator
5. List all assets and pages
6. Copy all assets to output
7. Generate all pages
8. Call hook "finish:before"
9. Finish generation
10. Call hook "finish"
@param {Generator} generator
@param {Book} book
@param {Object} options
@return {Promise<Output>}
|
[
"Generate",
"a",
"book",
"using",
"a",
"generator",
"."
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/generateBook.js#L155-L191
|
train
|
GitbookIO/gitbook
|
lib/api/encodeConfig.js
|
encodeConfig
|
function encodeConfig(output, config) {
var result = {
values: config.getValues().toJS(),
get: function(key, defaultValue) {
return objectPath.get(result.values, key, defaultValue);
},
set: function(key, value) {
return objectPath.set(result.values, key, value);
}
};
deprecate.field(output, 'config.options', result, 'options',
result.values, '"config.options" property is deprecated, use "config.get(key)" instead');
deprecate.field(output, 'config.options.generator', result.values, 'generator',
output.getGenerator(), '"options.generator" property is deprecated, use "output.name" instead');
deprecate.field(output, 'config.options.generator', result.values, 'output',
output.getRoot(), '"options.output" property is deprecated, use "output.root()" instead');
return result;
}
|
javascript
|
function encodeConfig(output, config) {
var result = {
values: config.getValues().toJS(),
get: function(key, defaultValue) {
return objectPath.get(result.values, key, defaultValue);
},
set: function(key, value) {
return objectPath.set(result.values, key, value);
}
};
deprecate.field(output, 'config.options', result, 'options',
result.values, '"config.options" property is deprecated, use "config.get(key)" instead');
deprecate.field(output, 'config.options.generator', result.values, 'generator',
output.getGenerator(), '"options.generator" property is deprecated, use "output.name" instead');
deprecate.field(output, 'config.options.generator', result.values, 'output',
output.getRoot(), '"options.output" property is deprecated, use "output.root()" instead');
return result;
}
|
[
"function",
"encodeConfig",
"(",
"output",
",",
"config",
")",
"{",
"var",
"result",
"=",
"{",
"values",
":",
"config",
".",
"getValues",
"(",
")",
".",
"toJS",
"(",
")",
",",
"get",
":",
"function",
"(",
"key",
",",
"defaultValue",
")",
"{",
"return",
"objectPath",
".",
"get",
"(",
"result",
".",
"values",
",",
"key",
",",
"defaultValue",
")",
";",
"}",
",",
"set",
":",
"function",
"(",
"key",
",",
"value",
")",
"{",
"return",
"objectPath",
".",
"set",
"(",
"result",
".",
"values",
",",
"key",
",",
"value",
")",
";",
"}",
"}",
";",
"deprecate",
".",
"field",
"(",
"output",
",",
"'config.options'",
",",
"result",
",",
"'options'",
",",
"result",
".",
"values",
",",
"'\"config.options\" property is deprecated, use \"config.get(key)\" instead'",
")",
";",
"deprecate",
".",
"field",
"(",
"output",
",",
"'config.options.generator'",
",",
"result",
".",
"values",
",",
"'generator'",
",",
"output",
".",
"getGenerator",
"(",
")",
",",
"'\"options.generator\" property is deprecated, use \"output.name\" instead'",
")",
";",
"deprecate",
".",
"field",
"(",
"output",
",",
"'config.options.generator'",
",",
"result",
".",
"values",
",",
"'output'",
",",
"output",
".",
"getRoot",
"(",
")",
",",
"'\"options.output\" property is deprecated, use \"output.root()\" instead'",
")",
";",
"return",
"result",
";",
"}"
] |
Encode a config object into a JS config api
@param {Output} output
@param {Config} config
@return {Object}
|
[
"Encode",
"a",
"config",
"object",
"into",
"a",
"JS",
"config",
"api"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/encodeConfig.js#L11-L34
|
train
|
GitbookIO/gitbook
|
lib/modifiers/config/getPluginConfig.js
|
getPluginConfig
|
function getPluginConfig(config, pluginName) {
var pluginsConfig = config.getValues().get('pluginsConfig');
if (pluginsConfig === undefined) {
return {};
}
var pluginConf = pluginsConfig.get(pluginName);
if (pluginConf === undefined) {
return {};
} else {
return pluginConf.toJS();
}
}
|
javascript
|
function getPluginConfig(config, pluginName) {
var pluginsConfig = config.getValues().get('pluginsConfig');
if (pluginsConfig === undefined) {
return {};
}
var pluginConf = pluginsConfig.get(pluginName);
if (pluginConf === undefined) {
return {};
} else {
return pluginConf.toJS();
}
}
|
[
"function",
"getPluginConfig",
"(",
"config",
",",
"pluginName",
")",
"{",
"var",
"pluginsConfig",
"=",
"config",
".",
"getValues",
"(",
")",
".",
"get",
"(",
"'pluginsConfig'",
")",
";",
"if",
"(",
"pluginsConfig",
"===",
"undefined",
")",
"{",
"return",
"{",
"}",
";",
"}",
"var",
"pluginConf",
"=",
"pluginsConfig",
".",
"get",
"(",
"pluginName",
")",
";",
"if",
"(",
"pluginConf",
"===",
"undefined",
")",
"{",
"return",
"{",
"}",
";",
"}",
"else",
"{",
"return",
"pluginConf",
".",
"toJS",
"(",
")",
";",
"}",
"}"
] |
Return the configuration for a plugin
@param {Config} config
@param {String} pluginName
@return {Object}
|
[
"Return",
"the",
"configuration",
"for",
"a",
"plugin"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/config/getPluginConfig.js#L7-L18
|
train
|
GitbookIO/gitbook
|
lib/json/encodeLanguages.js
|
encodeLanguages
|
function encodeLanguages(languages) {
var file = languages.getFile();
var list = languages.getList();
return {
file: encodeFile(file),
list: list
.valueSeq()
.map(function(lang) {
return {
id: lang.getID(),
title: lang.getTitle()
};
}).toJS()
};
}
|
javascript
|
function encodeLanguages(languages) {
var file = languages.getFile();
var list = languages.getList();
return {
file: encodeFile(file),
list: list
.valueSeq()
.map(function(lang) {
return {
id: lang.getID(),
title: lang.getTitle()
};
}).toJS()
};
}
|
[
"function",
"encodeLanguages",
"(",
"languages",
")",
"{",
"var",
"file",
"=",
"languages",
".",
"getFile",
"(",
")",
";",
"var",
"list",
"=",
"languages",
".",
"getList",
"(",
")",
";",
"return",
"{",
"file",
":",
"encodeFile",
"(",
"file",
")",
",",
"list",
":",
"list",
".",
"valueSeq",
"(",
")",
".",
"map",
"(",
"function",
"(",
"lang",
")",
"{",
"return",
"{",
"id",
":",
"lang",
".",
"getID",
"(",
")",
",",
"title",
":",
"lang",
".",
"getTitle",
"(",
")",
"}",
";",
"}",
")",
".",
"toJS",
"(",
")",
"}",
";",
"}"
] |
Encode a languages listing to JSON
@param {Languages}
@return {Object}
|
[
"Encode",
"a",
"languages",
"listing",
"to",
"JSON"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/json/encodeLanguages.js#L9-L24
|
train
|
GitbookIO/gitbook
|
lib/constants/defaultPlugins.js
|
createFromDependency
|
function createFromDependency(pluginName) {
var npmID = PluginDependency.nameToNpmID(pluginName);
var version = pkg.dependencies[npmID];
return PluginDependency.create(pluginName, version);
}
|
javascript
|
function createFromDependency(pluginName) {
var npmID = PluginDependency.nameToNpmID(pluginName);
var version = pkg.dependencies[npmID];
return PluginDependency.create(pluginName, version);
}
|
[
"function",
"createFromDependency",
"(",
"pluginName",
")",
"{",
"var",
"npmID",
"=",
"PluginDependency",
".",
"nameToNpmID",
"(",
"pluginName",
")",
";",
"var",
"version",
"=",
"pkg",
".",
"dependencies",
"[",
"npmID",
"]",
";",
"return",
"PluginDependency",
".",
"create",
"(",
"pluginName",
",",
"version",
")",
";",
"}"
] |
Create a PluginDependency from a dependency of gitbook
@param {String} pluginName
@return {PluginDependency}
|
[
"Create",
"a",
"PluginDependency",
"from",
"a",
"dependency",
"of",
"gitbook"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/constants/defaultPlugins.js#L11-L16
|
train
|
GitbookIO/gitbook
|
lib/parse/parseStructureFile.js
|
parseFile
|
function parseFile(fs, file, type) {
var filepath = file.getPath();
var parser = file.getParser();
if (!parser) {
return Promise.reject(
error.FileNotParsableError({
filename: filepath
})
);
}
return fs.readAsString(filepath)
.then(function(content) {
if (type === 'readme') {
return parser.parseReadme(content);
} else if (type === 'glossary') {
return parser.parseGlossary(content);
} else if (type === 'summary') {
return parser.parseSummary(content);
} else if (type === 'langs') {
return parser.parseLanguages(content);
} else {
throw new Error('Parsing invalid type "' + type + '"');
}
})
.then(function(result) {
return [
file,
result
];
});
}
|
javascript
|
function parseFile(fs, file, type) {
var filepath = file.getPath();
var parser = file.getParser();
if (!parser) {
return Promise.reject(
error.FileNotParsableError({
filename: filepath
})
);
}
return fs.readAsString(filepath)
.then(function(content) {
if (type === 'readme') {
return parser.parseReadme(content);
} else if (type === 'glossary') {
return parser.parseGlossary(content);
} else if (type === 'summary') {
return parser.parseSummary(content);
} else if (type === 'langs') {
return parser.parseLanguages(content);
} else {
throw new Error('Parsing invalid type "' + type + '"');
}
})
.then(function(result) {
return [
file,
result
];
});
}
|
[
"function",
"parseFile",
"(",
"fs",
",",
"file",
",",
"type",
")",
"{",
"var",
"filepath",
"=",
"file",
".",
"getPath",
"(",
")",
";",
"var",
"parser",
"=",
"file",
".",
"getParser",
"(",
")",
";",
"if",
"(",
"!",
"parser",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"error",
".",
"FileNotParsableError",
"(",
"{",
"filename",
":",
"filepath",
"}",
")",
")",
";",
"}",
"return",
"fs",
".",
"readAsString",
"(",
"filepath",
")",
".",
"then",
"(",
"function",
"(",
"content",
")",
"{",
"if",
"(",
"type",
"===",
"'readme'",
")",
"{",
"return",
"parser",
".",
"parseReadme",
"(",
"content",
")",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"'glossary'",
")",
"{",
"return",
"parser",
".",
"parseGlossary",
"(",
"content",
")",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"'summary'",
")",
"{",
"return",
"parser",
".",
"parseSummary",
"(",
"content",
")",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"'langs'",
")",
"{",
"return",
"parser",
".",
"parseLanguages",
"(",
"content",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Parsing invalid type \"'",
"+",
"type",
"+",
"'\"'",
")",
";",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"return",
"[",
"file",
",",
"result",
"]",
";",
"}",
")",
";",
"}"
] |
Parse a ParsableFile using a specific method
@param {FS} fs
@param {ParsableFile} file
@param {String} type
@return {Promise<Array<String, List|Map>>}
|
[
"Parse",
"a",
"ParsableFile",
"using",
"a",
"specific",
"method"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/parseStructureFile.js#L13-L45
|
train
|
GitbookIO/gitbook
|
lib/plugins/listFilters.js
|
listFilters
|
function listFilters(plugins) {
return plugins
.reverse()
.reduce(function(result, plugin) {
return result.merge(plugin.getFilters());
}, Immutable.Map());
}
|
javascript
|
function listFilters(plugins) {
return plugins
.reverse()
.reduce(function(result, plugin) {
return result.merge(plugin.getFilters());
}, Immutable.Map());
}
|
[
"function",
"listFilters",
"(",
"plugins",
")",
"{",
"return",
"plugins",
".",
"reverse",
"(",
")",
".",
"reduce",
"(",
"function",
"(",
"result",
",",
"plugin",
")",
"{",
"return",
"result",
".",
"merge",
"(",
"plugin",
".",
"getFilters",
"(",
")",
")",
";",
"}",
",",
"Immutable",
".",
"Map",
"(",
")",
")",
";",
"}"
] |
List filters from a list of plugins
@param {OrderedMap<String:Plugin>}
@return {Map<String:Function>}
|
[
"List",
"filters",
"from",
"a",
"list",
"of",
"plugins"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/listFilters.js#L9-L15
|
train
|
GitbookIO/gitbook
|
lib/output/preparePlugins.js
|
preparePlugins
|
function preparePlugins(output) {
var book = output.getBook();
return Promise()
// Only load plugins for main book
.then(function() {
if (book.isLanguageBook()) {
return output.getPlugins();
} else {
return Plugins.loadForBook(book);
}
})
// Update book's configuration using the plugins
.then(function(plugins) {
return Plugins.validateConfig(book, plugins)
.then(function(newBook) {
return output.merge({
book: newBook,
plugins: plugins
});
});
});
}
|
javascript
|
function preparePlugins(output) {
var book = output.getBook();
return Promise()
// Only load plugins for main book
.then(function() {
if (book.isLanguageBook()) {
return output.getPlugins();
} else {
return Plugins.loadForBook(book);
}
})
// Update book's configuration using the plugins
.then(function(plugins) {
return Plugins.validateConfig(book, plugins)
.then(function(newBook) {
return output.merge({
book: newBook,
plugins: plugins
});
});
});
}
|
[
"function",
"preparePlugins",
"(",
"output",
")",
"{",
"var",
"book",
"=",
"output",
".",
"getBook",
"(",
")",
";",
"return",
"Promise",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"book",
".",
"isLanguageBook",
"(",
")",
")",
"{",
"return",
"output",
".",
"getPlugins",
"(",
")",
";",
"}",
"else",
"{",
"return",
"Plugins",
".",
"loadForBook",
"(",
"book",
")",
";",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
"plugins",
")",
"{",
"return",
"Plugins",
".",
"validateConfig",
"(",
"book",
",",
"plugins",
")",
".",
"then",
"(",
"function",
"(",
"newBook",
")",
"{",
"return",
"output",
".",
"merge",
"(",
"{",
"book",
":",
"newBook",
",",
"plugins",
":",
"plugins",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Load and setup plugins
@param {Output}
@return {Promise<Output>}
|
[
"Load",
"and",
"setup",
"plugins"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/preparePlugins.js#L10-L34
|
train
|
GitbookIO/gitbook
|
lib/json/encodeSummary.js
|
encodeSummary
|
function encodeSummary(summary) {
var file = summary.getFile();
var parts = summary.getParts();
return {
file: encodeFile(file),
parts: parts.map(encodeSummaryPart).toJS()
};
}
|
javascript
|
function encodeSummary(summary) {
var file = summary.getFile();
var parts = summary.getParts();
return {
file: encodeFile(file),
parts: parts.map(encodeSummaryPart).toJS()
};
}
|
[
"function",
"encodeSummary",
"(",
"summary",
")",
"{",
"var",
"file",
"=",
"summary",
".",
"getFile",
"(",
")",
";",
"var",
"parts",
"=",
"summary",
".",
"getParts",
"(",
")",
";",
"return",
"{",
"file",
":",
"encodeFile",
"(",
"file",
")",
",",
"parts",
":",
"parts",
".",
"map",
"(",
"encodeSummaryPart",
")",
".",
"toJS",
"(",
")",
"}",
";",
"}"
] |
Encode a summary to JSON
@param {Summary}
@return {Object}
|
[
"Encode",
"a",
"summary",
"to",
"JSON"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/json/encodeSummary.js#L10-L18
|
train
|
GitbookIO/gitbook
|
lib/modifiers/summary/indexArticleLevels.js
|
indexArticleLevels
|
function indexArticleLevels(article, baseLevel) {
baseLevel = baseLevel || article.getLevel();
var articles = article.getArticles();
articles = articles.map(function(inner, i) {
return indexArticleLevels(inner, baseLevel + '.' + (i + 1));
});
return article.merge({
level: baseLevel,
articles: articles
});
}
|
javascript
|
function indexArticleLevels(article, baseLevel) {
baseLevel = baseLevel || article.getLevel();
var articles = article.getArticles();
articles = articles.map(function(inner, i) {
return indexArticleLevels(inner, baseLevel + '.' + (i + 1));
});
return article.merge({
level: baseLevel,
articles: articles
});
}
|
[
"function",
"indexArticleLevels",
"(",
"article",
",",
"baseLevel",
")",
"{",
"baseLevel",
"=",
"baseLevel",
"||",
"article",
".",
"getLevel",
"(",
")",
";",
"var",
"articles",
"=",
"article",
".",
"getArticles",
"(",
")",
";",
"articles",
"=",
"articles",
".",
"map",
"(",
"function",
"(",
"inner",
",",
"i",
")",
"{",
"return",
"indexArticleLevels",
"(",
"inner",
",",
"baseLevel",
"+",
"'.'",
"+",
"(",
"i",
"+",
"1",
")",
")",
";",
"}",
")",
";",
"return",
"article",
".",
"merge",
"(",
"{",
"level",
":",
"baseLevel",
",",
"articles",
":",
"articles",
"}",
")",
";",
"}"
] |
Index levels in an article tree
@param {Article}
@param {String} baseLevel
@return {Article}
|
[
"Index",
"levels",
"in",
"an",
"article",
"tree"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/summary/indexArticleLevels.js#L9-L21
|
train
|
GitbookIO/gitbook
|
lib/output/callHook.js
|
callHook
|
function callHook(name, getArgument, handleResult, output) {
getArgument = getArgument || defaultGetArgument;
handleResult = handleResult || defaultHandleResult;
var logger = output.getLogger();
var plugins = output.getPlugins();
logger.debug.ln('calling hook "' + name + '"');
// Create the JS context for plugins
var context = Api.encodeGlobal(output);
return timing.measure(
'call.hook.' + name,
// Get the arguments
Promise(getArgument(output))
// Call the hooks in serie
.then(function(arg) {
return Promise.reduce(plugins, function(prev, plugin) {
var hook = plugin.getHook(name);
if (!hook) {
return prev;
}
return hook.call(context, prev);
}, arg);
})
// Handle final result
.then(function(result) {
output = Api.decodeGlobal(output, context);
return handleResult(output, result);
})
);
}
|
javascript
|
function callHook(name, getArgument, handleResult, output) {
getArgument = getArgument || defaultGetArgument;
handleResult = handleResult || defaultHandleResult;
var logger = output.getLogger();
var plugins = output.getPlugins();
logger.debug.ln('calling hook "' + name + '"');
// Create the JS context for plugins
var context = Api.encodeGlobal(output);
return timing.measure(
'call.hook.' + name,
// Get the arguments
Promise(getArgument(output))
// Call the hooks in serie
.then(function(arg) {
return Promise.reduce(plugins, function(prev, plugin) {
var hook = plugin.getHook(name);
if (!hook) {
return prev;
}
return hook.call(context, prev);
}, arg);
})
// Handle final result
.then(function(result) {
output = Api.decodeGlobal(output, context);
return handleResult(output, result);
})
);
}
|
[
"function",
"callHook",
"(",
"name",
",",
"getArgument",
",",
"handleResult",
",",
"output",
")",
"{",
"getArgument",
"=",
"getArgument",
"||",
"defaultGetArgument",
";",
"handleResult",
"=",
"handleResult",
"||",
"defaultHandleResult",
";",
"var",
"logger",
"=",
"output",
".",
"getLogger",
"(",
")",
";",
"var",
"plugins",
"=",
"output",
".",
"getPlugins",
"(",
")",
";",
"logger",
".",
"debug",
".",
"ln",
"(",
"'calling hook \"'",
"+",
"name",
"+",
"'\"'",
")",
";",
"var",
"context",
"=",
"Api",
".",
"encodeGlobal",
"(",
"output",
")",
";",
"return",
"timing",
".",
"measure",
"(",
"'call.hook.'",
"+",
"name",
",",
"Promise",
"(",
"getArgument",
"(",
"output",
")",
")",
".",
"then",
"(",
"function",
"(",
"arg",
")",
"{",
"return",
"Promise",
".",
"reduce",
"(",
"plugins",
",",
"function",
"(",
"prev",
",",
"plugin",
")",
"{",
"var",
"hook",
"=",
"plugin",
".",
"getHook",
"(",
"name",
")",
";",
"if",
"(",
"!",
"hook",
")",
"{",
"return",
"prev",
";",
"}",
"return",
"hook",
".",
"call",
"(",
"context",
",",
"prev",
")",
";",
"}",
",",
"arg",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"output",
"=",
"Api",
".",
"decodeGlobal",
"(",
"output",
",",
"context",
")",
";",
"return",
"handleResult",
"(",
"output",
",",
"result",
")",
";",
"}",
")",
")",
";",
"}"
] |
Call a "global" hook for an output
@param {String} name
@param {Function(Output) -> Mixed} getArgument
@param {Function(Output, result) -> Output} handleResult
@param {Output} output
@return {Promise<Output>}
|
[
"Call",
"a",
"global",
"hook",
"for",
"an",
"output"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/callHook.js#L22-L58
|
train
|
GitbookIO/gitbook
|
lib/cli/server.js
|
redirect
|
function redirect() {
var resultURL = urlTransform(req.url, function(parsed) {
parsed.pathname += '/';
return parsed;
});
res.statusCode = 301;
res.setHeader('Location', resultURL);
res.end('Redirecting to ' + resultURL);
}
|
javascript
|
function redirect() {
var resultURL = urlTransform(req.url, function(parsed) {
parsed.pathname += '/';
return parsed;
});
res.statusCode = 301;
res.setHeader('Location', resultURL);
res.end('Redirecting to ' + resultURL);
}
|
[
"function",
"redirect",
"(",
")",
"{",
"var",
"resultURL",
"=",
"urlTransform",
"(",
"req",
".",
"url",
",",
"function",
"(",
"parsed",
")",
"{",
"parsed",
".",
"pathname",
"+=",
"'/'",
";",
"return",
"parsed",
";",
"}",
")",
";",
"res",
".",
"statusCode",
"=",
"301",
";",
"res",
".",
"setHeader",
"(",
"'Location'",
",",
"resultURL",
")",
";",
"res",
".",
"end",
"(",
"'Redirecting to '",
"+",
"resultURL",
")",
";",
"}"
] |
Redirect to directory's index.html
|
[
"Redirect",
"to",
"directory",
"s",
"index",
".",
"html"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/cli/server.js#L73-L82
|
train
|
GitbookIO/gitbook
|
lib/modifiers/summary/mergeAtLevel.js
|
editArticleInList
|
function editArticleInList(articles, level, newArticle) {
return articles.map(function(article) {
var articleLevel = article.getLevel();
if (articleLevel === level) {
// it is the article to edit
return article.merge(newArticle);
} else if (level.indexOf(articleLevel) === 0) {
// it is a parent
var articles = editArticleInList(article.getArticles(), level, newArticle);
return article.set('articles', articles);
} else {
// This is not the article you are looking for
return article;
}
});
}
|
javascript
|
function editArticleInList(articles, level, newArticle) {
return articles.map(function(article) {
var articleLevel = article.getLevel();
if (articleLevel === level) {
// it is the article to edit
return article.merge(newArticle);
} else if (level.indexOf(articleLevel) === 0) {
// it is a parent
var articles = editArticleInList(article.getArticles(), level, newArticle);
return article.set('articles', articles);
} else {
// This is not the article you are looking for
return article;
}
});
}
|
[
"function",
"editArticleInList",
"(",
"articles",
",",
"level",
",",
"newArticle",
")",
"{",
"return",
"articles",
".",
"map",
"(",
"function",
"(",
"article",
")",
"{",
"var",
"articleLevel",
"=",
"article",
".",
"getLevel",
"(",
")",
";",
"if",
"(",
"articleLevel",
"===",
"level",
")",
"{",
"return",
"article",
".",
"merge",
"(",
"newArticle",
")",
";",
"}",
"else",
"if",
"(",
"level",
".",
"indexOf",
"(",
"articleLevel",
")",
"===",
"0",
")",
"{",
"var",
"articles",
"=",
"editArticleInList",
"(",
"article",
".",
"getArticles",
"(",
")",
",",
"level",
",",
"newArticle",
")",
";",
"return",
"article",
".",
"set",
"(",
"'articles'",
",",
"articles",
")",
";",
"}",
"else",
"{",
"return",
"article",
";",
"}",
"}",
")",
";",
"}"
] |
Edit a list of articles
@param {List<Article>} articles
@param {String} level
@param {Article} newArticle
@return {List<Article>}
|
[
"Edit",
"a",
"list",
"of",
"articles"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/summary/mergeAtLevel.js#L10-L26
|
train
|
GitbookIO/gitbook
|
lib/modifiers/summary/mergeAtLevel.js
|
editArticleInPart
|
function editArticleInPart(part, level, newArticle) {
var articles = part.getArticles();
articles = editArticleInList(articles, level, newArticle);
return part.set('articles', articles);
}
|
javascript
|
function editArticleInPart(part, level, newArticle) {
var articles = part.getArticles();
articles = editArticleInList(articles, level, newArticle);
return part.set('articles', articles);
}
|
[
"function",
"editArticleInPart",
"(",
"part",
",",
"level",
",",
"newArticle",
")",
"{",
"var",
"articles",
"=",
"part",
".",
"getArticles",
"(",
")",
";",
"articles",
"=",
"editArticleInList",
"(",
"articles",
",",
"level",
",",
"newArticle",
")",
";",
"return",
"part",
".",
"set",
"(",
"'articles'",
",",
"articles",
")",
";",
"}"
] |
Edit an article in a part
@param {Part} part
@param {String} level
@param {Article} newArticle
@return {Part}
|
[
"Edit",
"an",
"article",
"in",
"a",
"part"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/summary/mergeAtLevel.js#L37-L42
|
train
|
GitbookIO/gitbook
|
lib/modifiers/summary/mergeAtLevel.js
|
mergeAtLevel
|
function mergeAtLevel(summary, level, newValue) {
var levelParts = level.split('.');
var partIndex = Number(levelParts[0]) -1;
var parts = summary.getParts();
var part = parts.get(partIndex);
if (!part) {
return summary;
}
var isEditingPart = levelParts.length < 2;
if (isEditingPart) {
part = part.merge(newValue);
} else {
part = editArticleInPart(part, level, newValue);
}
parts = parts.set(partIndex, part);
return summary.set('parts', parts);
}
|
javascript
|
function mergeAtLevel(summary, level, newValue) {
var levelParts = level.split('.');
var partIndex = Number(levelParts[0]) -1;
var parts = summary.getParts();
var part = parts.get(partIndex);
if (!part) {
return summary;
}
var isEditingPart = levelParts.length < 2;
if (isEditingPart) {
part = part.merge(newValue);
} else {
part = editArticleInPart(part, level, newValue);
}
parts = parts.set(partIndex, part);
return summary.set('parts', parts);
}
|
[
"function",
"mergeAtLevel",
"(",
"summary",
",",
"level",
",",
"newValue",
")",
"{",
"var",
"levelParts",
"=",
"level",
".",
"split",
"(",
"'.'",
")",
";",
"var",
"partIndex",
"=",
"Number",
"(",
"levelParts",
"[",
"0",
"]",
")",
"-",
"1",
";",
"var",
"parts",
"=",
"summary",
".",
"getParts",
"(",
")",
";",
"var",
"part",
"=",
"parts",
".",
"get",
"(",
"partIndex",
")",
";",
"if",
"(",
"!",
"part",
")",
"{",
"return",
"summary",
";",
"}",
"var",
"isEditingPart",
"=",
"levelParts",
".",
"length",
"<",
"2",
";",
"if",
"(",
"isEditingPart",
")",
"{",
"part",
"=",
"part",
".",
"merge",
"(",
"newValue",
")",
";",
"}",
"else",
"{",
"part",
"=",
"editArticleInPart",
"(",
"part",
",",
"level",
",",
"newValue",
")",
";",
"}",
"parts",
"=",
"parts",
".",
"set",
"(",
"partIndex",
",",
"part",
")",
";",
"return",
"summary",
".",
"set",
"(",
"'parts'",
",",
"parts",
")",
";",
"}"
] |
Edit an article, or a part, in a summary. Does a shallow merge.
@param {Summary} summary
@param {String} level
@param {Article|Part} newValue
@return {Summary}
|
[
"Edit",
"an",
"article",
"or",
"a",
"part",
"in",
"a",
"summary",
".",
"Does",
"a",
"shallow",
"merge",
"."
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/summary/mergeAtLevel.js#L53-L72
|
train
|
GitbookIO/gitbook
|
lib/utils/location.js
|
isExternal
|
function isExternal(href) {
try {
return Boolean(url.parse(href).protocol) && !isDataURI(href);
} catch(err) {
return false;
}
}
|
javascript
|
function isExternal(href) {
try {
return Boolean(url.parse(href).protocol) && !isDataURI(href);
} catch(err) {
return false;
}
}
|
[
"function",
"isExternal",
"(",
"href",
")",
"{",
"try",
"{",
"return",
"Boolean",
"(",
"url",
".",
"parse",
"(",
"href",
")",
".",
"protocol",
")",
"&&",
"!",
"isDataURI",
"(",
"href",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"false",
";",
"}",
"}"
] |
Is the url an external url
|
[
"Is",
"the",
"url",
"an",
"external",
"url"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/location.js#L5-L11
|
train
|
GitbookIO/gitbook
|
lib/utils/location.js
|
isAnchor
|
function isAnchor(href) {
try {
var parsed = url.parse(href);
return !!(!parsed.protocol && !parsed.path && parsed.hash);
} catch(err) {
return false;
}
}
|
javascript
|
function isAnchor(href) {
try {
var parsed = url.parse(href);
return !!(!parsed.protocol && !parsed.path && parsed.hash);
} catch(err) {
return false;
}
}
|
[
"function",
"isAnchor",
"(",
"href",
")",
"{",
"try",
"{",
"var",
"parsed",
"=",
"url",
".",
"parse",
"(",
"href",
")",
";",
"return",
"!",
"!",
"(",
"!",
"parsed",
".",
"protocol",
"&&",
"!",
"parsed",
".",
"path",
"&&",
"parsed",
".",
"hash",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"false",
";",
"}",
"}"
] |
Return true if the link is an achor
|
[
"Return",
"true",
"if",
"the",
"link",
"is",
"an",
"achor"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/location.js#L28-L35
|
train
|
GitbookIO/gitbook
|
lib/utils/location.js
|
toAbsolute
|
function toAbsolute(_href, dir, outdir) {
if (isExternal(_href) || isDataURI(_href)) {
return _href;
}
outdir = outdir == undefined? dir : outdir;
_href = normalize(_href);
dir = normalize(dir);
outdir = normalize(outdir);
// Path "_href" inside the base folder
var hrefInRoot = normalize(path.join(dir, _href));
if (_href[0] == '/') {
hrefInRoot = normalize(_href.slice(1));
}
// Make it relative to output
_href = path.relative(outdir, hrefInRoot);
// Normalize windows paths
_href = normalize(_href);
return _href;
}
|
javascript
|
function toAbsolute(_href, dir, outdir) {
if (isExternal(_href) || isDataURI(_href)) {
return _href;
}
outdir = outdir == undefined? dir : outdir;
_href = normalize(_href);
dir = normalize(dir);
outdir = normalize(outdir);
// Path "_href" inside the base folder
var hrefInRoot = normalize(path.join(dir, _href));
if (_href[0] == '/') {
hrefInRoot = normalize(_href.slice(1));
}
// Make it relative to output
_href = path.relative(outdir, hrefInRoot);
// Normalize windows paths
_href = normalize(_href);
return _href;
}
|
[
"function",
"toAbsolute",
"(",
"_href",
",",
"dir",
",",
"outdir",
")",
"{",
"if",
"(",
"isExternal",
"(",
"_href",
")",
"||",
"isDataURI",
"(",
"_href",
")",
")",
"{",
"return",
"_href",
";",
"}",
"outdir",
"=",
"outdir",
"==",
"undefined",
"?",
"dir",
":",
"outdir",
";",
"_href",
"=",
"normalize",
"(",
"_href",
")",
";",
"dir",
"=",
"normalize",
"(",
"dir",
")",
";",
"outdir",
"=",
"normalize",
"(",
"outdir",
")",
";",
"var",
"hrefInRoot",
"=",
"normalize",
"(",
"path",
".",
"join",
"(",
"dir",
",",
"_href",
")",
")",
";",
"if",
"(",
"_href",
"[",
"0",
"]",
"==",
"'/'",
")",
"{",
"hrefInRoot",
"=",
"normalize",
"(",
"_href",
".",
"slice",
"(",
"1",
")",
")",
";",
"}",
"_href",
"=",
"path",
".",
"relative",
"(",
"outdir",
",",
"hrefInRoot",
")",
";",
"_href",
"=",
"normalize",
"(",
"_href",
")",
";",
"return",
"_href",
";",
"}"
] |
Convert a relative path to absolute
@param {String} href
@param {String} dir: directory parent of the file currently in rendering process
@param {String} outdir: directory parent from the html output
@return {String}
|
[
"Convert",
"a",
"relative",
"path",
"to",
"absolute"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/location.js#L65-L89
|
train
|
GitbookIO/gitbook
|
lib/parse/parsePageFromString.js
|
parsePageFromString
|
function parsePageFromString(page, content) {
// Parse page YAML
var parsed = fm(content);
return page.merge({
content: parsed.body,
attributes: Immutable.fromJS(parsed.attributes),
dir: direction(parsed.body)
});
}
|
javascript
|
function parsePageFromString(page, content) {
// Parse page YAML
var parsed = fm(content);
return page.merge({
content: parsed.body,
attributes: Immutable.fromJS(parsed.attributes),
dir: direction(parsed.body)
});
}
|
[
"function",
"parsePageFromString",
"(",
"page",
",",
"content",
")",
"{",
"var",
"parsed",
"=",
"fm",
"(",
"content",
")",
";",
"return",
"page",
".",
"merge",
"(",
"{",
"content",
":",
"parsed",
".",
"body",
",",
"attributes",
":",
"Immutable",
".",
"fromJS",
"(",
"parsed",
".",
"attributes",
")",
",",
"dir",
":",
"direction",
"(",
"parsed",
".",
"body",
")",
"}",
")",
";",
"}"
] |
Parse a page, its content and the YAMl header
@param {Page} page
@return {Page}
|
[
"Parse",
"a",
"page",
"its",
"content",
"and",
"the",
"YAMl",
"header"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/parsePageFromString.js#L11-L20
|
train
|
GitbookIO/gitbook
|
lib/output/json/onFinish.js
|
onFinish
|
function onFinish(output) {
var book = output.getBook();
var outputRoot = output.getRoot();
if (!book.isMultilingual()) {
return Promise(output);
}
// Get main language
var languages = book.getLanguages();
var mainLanguage = languages.getDefaultLanguage();
// Read the main JSON
return fs.readFile(path.resolve(outputRoot, mainLanguage.getID(), 'README.json'), 'utf8')
// Extend the JSON
.then(function(content) {
var json = JSON.parse(content);
json.languages = JSONUtils.encodeLanguages(languages);
return json;
})
.then(function(json) {
return fs.writeFile(
path.resolve(outputRoot, 'README.json'),
JSON.stringify(json, null, 4)
);
})
.thenResolve(output);
}
|
javascript
|
function onFinish(output) {
var book = output.getBook();
var outputRoot = output.getRoot();
if (!book.isMultilingual()) {
return Promise(output);
}
// Get main language
var languages = book.getLanguages();
var mainLanguage = languages.getDefaultLanguage();
// Read the main JSON
return fs.readFile(path.resolve(outputRoot, mainLanguage.getID(), 'README.json'), 'utf8')
// Extend the JSON
.then(function(content) {
var json = JSON.parse(content);
json.languages = JSONUtils.encodeLanguages(languages);
return json;
})
.then(function(json) {
return fs.writeFile(
path.resolve(outputRoot, 'README.json'),
JSON.stringify(json, null, 4)
);
})
.thenResolve(output);
}
|
[
"function",
"onFinish",
"(",
"output",
")",
"{",
"var",
"book",
"=",
"output",
".",
"getBook",
"(",
")",
";",
"var",
"outputRoot",
"=",
"output",
".",
"getRoot",
"(",
")",
";",
"if",
"(",
"!",
"book",
".",
"isMultilingual",
"(",
")",
")",
"{",
"return",
"Promise",
"(",
"output",
")",
";",
"}",
"var",
"languages",
"=",
"book",
".",
"getLanguages",
"(",
")",
";",
"var",
"mainLanguage",
"=",
"languages",
".",
"getDefaultLanguage",
"(",
")",
";",
"return",
"fs",
".",
"readFile",
"(",
"path",
".",
"resolve",
"(",
"outputRoot",
",",
"mainLanguage",
".",
"getID",
"(",
")",
",",
"'README.json'",
")",
",",
"'utf8'",
")",
".",
"then",
"(",
"function",
"(",
"content",
")",
"{",
"var",
"json",
"=",
"JSON",
".",
"parse",
"(",
"content",
")",
";",
"json",
".",
"languages",
"=",
"JSONUtils",
".",
"encodeLanguages",
"(",
"languages",
")",
";",
"return",
"json",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"json",
")",
"{",
"return",
"fs",
".",
"writeFile",
"(",
"path",
".",
"resolve",
"(",
"outputRoot",
",",
"'README.json'",
")",
",",
"JSON",
".",
"stringify",
"(",
"json",
",",
"null",
",",
"4",
")",
")",
";",
"}",
")",
".",
"thenResolve",
"(",
"output",
")",
";",
"}"
] |
Finish the generation
@param {Output}
@return {Output}
|
[
"Finish",
"the",
"generation"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/json/onFinish.js#L13-L45
|
train
|
GitbookIO/gitbook
|
lib/modifiers/summary/removeArticle.js
|
removeArticle
|
function removeArticle(summary, level) {
// Coerce to level
level = is.string(level)? level : level.getLevel();
var parent = summary.getParent(level);
var articles = parent.getArticles();
// Find the index to remove
var index = articles.findIndex(function(art) {
return art.getLevel() === level;
});
if (index === -1) {
return summary;
}
// Remove from children
articles = articles.remove(index);
parent = parent.set('articles', articles);
// Reindex the level from here
parent = indexArticleLevels(parent);
return mergeAtLevel(summary, parent.getLevel(), parent);
}
|
javascript
|
function removeArticle(summary, level) {
// Coerce to level
level = is.string(level)? level : level.getLevel();
var parent = summary.getParent(level);
var articles = parent.getArticles();
// Find the index to remove
var index = articles.findIndex(function(art) {
return art.getLevel() === level;
});
if (index === -1) {
return summary;
}
// Remove from children
articles = articles.remove(index);
parent = parent.set('articles', articles);
// Reindex the level from here
parent = indexArticleLevels(parent);
return mergeAtLevel(summary, parent.getLevel(), parent);
}
|
[
"function",
"removeArticle",
"(",
"summary",
",",
"level",
")",
"{",
"level",
"=",
"is",
".",
"string",
"(",
"level",
")",
"?",
"level",
":",
"level",
".",
"getLevel",
"(",
")",
";",
"var",
"parent",
"=",
"summary",
".",
"getParent",
"(",
"level",
")",
";",
"var",
"articles",
"=",
"parent",
".",
"getArticles",
"(",
")",
";",
"var",
"index",
"=",
"articles",
".",
"findIndex",
"(",
"function",
"(",
"art",
")",
"{",
"return",
"art",
".",
"getLevel",
"(",
")",
"===",
"level",
";",
"}",
")",
";",
"if",
"(",
"index",
"===",
"-",
"1",
")",
"{",
"return",
"summary",
";",
"}",
"articles",
"=",
"articles",
".",
"remove",
"(",
"index",
")",
";",
"parent",
"=",
"parent",
".",
"set",
"(",
"'articles'",
",",
"articles",
")",
";",
"parent",
"=",
"indexArticleLevels",
"(",
"parent",
")",
";",
"return",
"mergeAtLevel",
"(",
"summary",
",",
"parent",
".",
"getLevel",
"(",
")",
",",
"parent",
")",
";",
"}"
] |
Remove an article from a level.
@param {Summary} summary
@param {String|SummaryArticle} level: level to remove
@return {Summary}
|
[
"Remove",
"an",
"article",
"from",
"a",
"level",
"."
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/summary/removeArticle.js#L12-L35
|
train
|
GitbookIO/gitbook
|
lib/modifiers/summary/editPartTitle.js
|
editPartTitle
|
function editPartTitle(summary, index, newTitle) {
var parts = summary.getParts();
var part = parts.get(index);
if (!part) {
return summary;
}
part = part.set('title', newTitle);
parts = parts.set(index, part);
return summary.set('parts', parts);
}
|
javascript
|
function editPartTitle(summary, index, newTitle) {
var parts = summary.getParts();
var part = parts.get(index);
if (!part) {
return summary;
}
part = part.set('title', newTitle);
parts = parts.set(index, part);
return summary.set('parts', parts);
}
|
[
"function",
"editPartTitle",
"(",
"summary",
",",
"index",
",",
"newTitle",
")",
"{",
"var",
"parts",
"=",
"summary",
".",
"getParts",
"(",
")",
";",
"var",
"part",
"=",
"parts",
".",
"get",
"(",
"index",
")",
";",
"if",
"(",
"!",
"part",
")",
"{",
"return",
"summary",
";",
"}",
"part",
"=",
"part",
".",
"set",
"(",
"'title'",
",",
"newTitle",
")",
";",
"parts",
"=",
"parts",
".",
"set",
"(",
"index",
",",
"part",
")",
";",
"return",
"summary",
".",
"set",
"(",
"'parts'",
",",
"parts",
")",
";",
"}"
] |
Edit title of a part in the summary
@param {Summary} summary
@param {Number} index
@param {String} newTitle
@return {Summary}
|
[
"Edit",
"title",
"of",
"a",
"part",
"in",
"the",
"summary"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/summary/editPartTitle.js#L9-L21
|
train
|
GitbookIO/gitbook
|
lib/output/preparePages.js
|
preparePages
|
function preparePages(output) {
var book = output.getBook();
var logger = book.getLogger();
if (book.isMultilingual()) {
return Promise(output);
}
return Parse.parsePagesList(book)
.then(function(pages) {
logger.info.ln('found', pages.size, 'pages');
return output.set('pages', pages);
});
}
|
javascript
|
function preparePages(output) {
var book = output.getBook();
var logger = book.getLogger();
if (book.isMultilingual()) {
return Promise(output);
}
return Parse.parsePagesList(book)
.then(function(pages) {
logger.info.ln('found', pages.size, 'pages');
return output.set('pages', pages);
});
}
|
[
"function",
"preparePages",
"(",
"output",
")",
"{",
"var",
"book",
"=",
"output",
".",
"getBook",
"(",
")",
";",
"var",
"logger",
"=",
"book",
".",
"getLogger",
"(",
")",
";",
"if",
"(",
"book",
".",
"isMultilingual",
"(",
")",
")",
"{",
"return",
"Promise",
"(",
"output",
")",
";",
"}",
"return",
"Parse",
".",
"parsePagesList",
"(",
"book",
")",
".",
"then",
"(",
"function",
"(",
"pages",
")",
"{",
"logger",
".",
"info",
".",
"ln",
"(",
"'found'",
",",
"pages",
".",
"size",
",",
"'pages'",
")",
";",
"return",
"output",
".",
"set",
"(",
"'pages'",
",",
"pages",
")",
";",
"}",
")",
";",
"}"
] |
List and prepare all pages
@param {Output}
@return {Promise<Output>}
|
[
"List",
"and",
"prepare",
"all",
"pages"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/preparePages.js#L10-L24
|
train
|
GitbookIO/gitbook
|
lib/output/modifiers/svgToPng.js
|
svgToPng
|
function svgToPng(rootFolder, currentFile, $) {
var currentDirectory = path.dirname(currentFile);
return editHTMLElement($, 'img', function($img) {
var src = $img.attr('src');
if (path.extname(src) !== '.svg') {
return;
}
// Calcul absolute path for this
src = LocationUtils.toAbsolute(src, currentDirectory, '.');
// We avoid generating twice the same PNG
var hash = crc.crc32(src).toString(16);
var fileName = hash + '.png';
// Input file path
var inputPath = path.join(rootFolder, src);
// Result file path
var filePath = path.join(rootFolder, fileName);
return fs.assertFile(filePath, function() {
return imagesUtil.convertSVGToPNG(inputPath, filePath);
})
.then(function() {
// Convert filename to a relative filename
fileName = LocationUtils.relative(currentDirectory, fileName);
// Replace src
$img.attr('src', fileName);
});
});
}
|
javascript
|
function svgToPng(rootFolder, currentFile, $) {
var currentDirectory = path.dirname(currentFile);
return editHTMLElement($, 'img', function($img) {
var src = $img.attr('src');
if (path.extname(src) !== '.svg') {
return;
}
// Calcul absolute path for this
src = LocationUtils.toAbsolute(src, currentDirectory, '.');
// We avoid generating twice the same PNG
var hash = crc.crc32(src).toString(16);
var fileName = hash + '.png';
// Input file path
var inputPath = path.join(rootFolder, src);
// Result file path
var filePath = path.join(rootFolder, fileName);
return fs.assertFile(filePath, function() {
return imagesUtil.convertSVGToPNG(inputPath, filePath);
})
.then(function() {
// Convert filename to a relative filename
fileName = LocationUtils.relative(currentDirectory, fileName);
// Replace src
$img.attr('src', fileName);
});
});
}
|
[
"function",
"svgToPng",
"(",
"rootFolder",
",",
"currentFile",
",",
"$",
")",
"{",
"var",
"currentDirectory",
"=",
"path",
".",
"dirname",
"(",
"currentFile",
")",
";",
"return",
"editHTMLElement",
"(",
"$",
",",
"'img'",
",",
"function",
"(",
"$img",
")",
"{",
"var",
"src",
"=",
"$img",
".",
"attr",
"(",
"'src'",
")",
";",
"if",
"(",
"path",
".",
"extname",
"(",
"src",
")",
"!==",
"'.svg'",
")",
"{",
"return",
";",
"}",
"src",
"=",
"LocationUtils",
".",
"toAbsolute",
"(",
"src",
",",
"currentDirectory",
",",
"'.'",
")",
";",
"var",
"hash",
"=",
"crc",
".",
"crc32",
"(",
"src",
")",
".",
"toString",
"(",
"16",
")",
";",
"var",
"fileName",
"=",
"hash",
"+",
"'.png'",
";",
"var",
"inputPath",
"=",
"path",
".",
"join",
"(",
"rootFolder",
",",
"src",
")",
";",
"var",
"filePath",
"=",
"path",
".",
"join",
"(",
"rootFolder",
",",
"fileName",
")",
";",
"return",
"fs",
".",
"assertFile",
"(",
"filePath",
",",
"function",
"(",
")",
"{",
"return",
"imagesUtil",
".",
"convertSVGToPNG",
"(",
"inputPath",
",",
"filePath",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"fileName",
"=",
"LocationUtils",
".",
"relative",
"(",
"currentDirectory",
",",
"fileName",
")",
";",
"$img",
".",
"attr",
"(",
"'src'",
",",
"fileName",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Convert all SVG images to PNG
@param {String} rootFolder
@param {HTMLDom} $
@return {Promise}
|
[
"Convert",
"all",
"SVG",
"images",
"to",
"PNG"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/modifiers/svgToPng.js#L17-L50
|
train
|
GitbookIO/gitbook
|
lib/plugins/installPlugins.js
|
installPlugins
|
function installPlugins(book) {
var logger = book.getLogger();
var config = book.getConfig();
var plugins = config.getPluginDependencies();
// Remove default plugins
// (only if version is same as installed)
plugins = plugins.filterNot(function(plugin) {
var dependency = DEFAULT_PLUGINS.find(function(dep) {
return dep.getName() === plugin.getName();
});
return (
// Disabled plugin
!plugin.isEnabled() ||
// Or default one installed in GitBook itself
(dependency &&
plugin.getVersion() === dependency.getVersion())
);
});
if (plugins.size == 0) {
logger.info.ln('nothing to install!');
return Promise();
}
logger.info.ln('installing', plugins.size, 'plugins using npm@' + npmi.NPM_VERSION);
return Promise.forEach(plugins, function(plugin) {
return installPlugin(book, plugin);
})
.thenResolve(plugins.size);
}
|
javascript
|
function installPlugins(book) {
var logger = book.getLogger();
var config = book.getConfig();
var plugins = config.getPluginDependencies();
// Remove default plugins
// (only if version is same as installed)
plugins = plugins.filterNot(function(plugin) {
var dependency = DEFAULT_PLUGINS.find(function(dep) {
return dep.getName() === plugin.getName();
});
return (
// Disabled plugin
!plugin.isEnabled() ||
// Or default one installed in GitBook itself
(dependency &&
plugin.getVersion() === dependency.getVersion())
);
});
if (plugins.size == 0) {
logger.info.ln('nothing to install!');
return Promise();
}
logger.info.ln('installing', plugins.size, 'plugins using npm@' + npmi.NPM_VERSION);
return Promise.forEach(plugins, function(plugin) {
return installPlugin(book, plugin);
})
.thenResolve(plugins.size);
}
|
[
"function",
"installPlugins",
"(",
"book",
")",
"{",
"var",
"logger",
"=",
"book",
".",
"getLogger",
"(",
")",
";",
"var",
"config",
"=",
"book",
".",
"getConfig",
"(",
")",
";",
"var",
"plugins",
"=",
"config",
".",
"getPluginDependencies",
"(",
")",
";",
"plugins",
"=",
"plugins",
".",
"filterNot",
"(",
"function",
"(",
"plugin",
")",
"{",
"var",
"dependency",
"=",
"DEFAULT_PLUGINS",
".",
"find",
"(",
"function",
"(",
"dep",
")",
"{",
"return",
"dep",
".",
"getName",
"(",
")",
"===",
"plugin",
".",
"getName",
"(",
")",
";",
"}",
")",
";",
"return",
"(",
"!",
"plugin",
".",
"isEnabled",
"(",
")",
"||",
"(",
"dependency",
"&&",
"plugin",
".",
"getVersion",
"(",
")",
"===",
"dependency",
".",
"getVersion",
"(",
")",
")",
")",
";",
"}",
")",
";",
"if",
"(",
"plugins",
".",
"size",
"==",
"0",
")",
"{",
"logger",
".",
"info",
".",
"ln",
"(",
"'nothing to install!'",
")",
";",
"return",
"Promise",
"(",
")",
";",
"}",
"logger",
".",
"info",
".",
"ln",
"(",
"'installing'",
",",
"plugins",
".",
"size",
",",
"'plugins using npm@'",
"+",
"npmi",
".",
"NPM_VERSION",
")",
";",
"return",
"Promise",
".",
"forEach",
"(",
"plugins",
",",
"function",
"(",
"plugin",
")",
"{",
"return",
"installPlugin",
"(",
"book",
",",
"plugin",
")",
";",
"}",
")",
".",
"thenResolve",
"(",
"plugins",
".",
"size",
")",
";",
"}"
] |
Install plugin requirements for a book
@param {Book}
@return {Promise<Number>}
|
[
"Install",
"plugin",
"requirements",
"for",
"a",
"book"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/installPlugins.js#L13-L46
|
train
|
GitbookIO/gitbook
|
lib/modifiers/config/removePlugin.js
|
removePlugin
|
function removePlugin(config, pluginName) {
var deps = config.getPluginDependencies();
// For default plugin, we have to disable it instead of removing from the list
if (isDefaultPlugin(pluginName)) {
return togglePlugin(config, pluginName, false);
}
// Remove the dependency from the list
deps = deps.filterNot(function(dep) {
return dep.getName() === pluginName;
});
return config.setPluginDependencies(deps);
}
|
javascript
|
function removePlugin(config, pluginName) {
var deps = config.getPluginDependencies();
// For default plugin, we have to disable it instead of removing from the list
if (isDefaultPlugin(pluginName)) {
return togglePlugin(config, pluginName, false);
}
// Remove the dependency from the list
deps = deps.filterNot(function(dep) {
return dep.getName() === pluginName;
});
return config.setPluginDependencies(deps);
}
|
[
"function",
"removePlugin",
"(",
"config",
",",
"pluginName",
")",
"{",
"var",
"deps",
"=",
"config",
".",
"getPluginDependencies",
"(",
")",
";",
"if",
"(",
"isDefaultPlugin",
"(",
"pluginName",
")",
")",
"{",
"return",
"togglePlugin",
"(",
"config",
",",
"pluginName",
",",
"false",
")",
";",
"}",
"deps",
"=",
"deps",
".",
"filterNot",
"(",
"function",
"(",
"dep",
")",
"{",
"return",
"dep",
".",
"getName",
"(",
")",
"===",
"pluginName",
";",
"}",
")",
";",
"return",
"config",
".",
"setPluginDependencies",
"(",
"deps",
")",
";",
"}"
] |
Remove a plugin from a book's configuration
@param {Config} config
@param {String} plugin
@return {Config}
|
[
"Remove",
"a",
"plugin",
"from",
"a",
"book",
"s",
"configuration"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/config/removePlugin.js#L10-L23
|
train
|
GitbookIO/gitbook
|
lib/api/decodePage.js
|
decodePage
|
function decodePage(output, page, result) {
var originalContent = page.getContent();
// No returned value
// Existing content will be used
if (!result) {
return page;
}
deprecate.disable('page.sections');
// GitBook 3
// Use returned page.content if different from original content
if (result.content != originalContent) {
page = page.set('content', result.content);
}
// GitBook 2 compatibility
// Finally, use page.sections
else if (result.sections) {
page = page.set('content',
result.sections.map(function(section) {
return section.content;
}).join('\n')
);
}
deprecate.enable('page.sections');
return page;
}
|
javascript
|
function decodePage(output, page, result) {
var originalContent = page.getContent();
// No returned value
// Existing content will be used
if (!result) {
return page;
}
deprecate.disable('page.sections');
// GitBook 3
// Use returned page.content if different from original content
if (result.content != originalContent) {
page = page.set('content', result.content);
}
// GitBook 2 compatibility
// Finally, use page.sections
else if (result.sections) {
page = page.set('content',
result.sections.map(function(section) {
return section.content;
}).join('\n')
);
}
deprecate.enable('page.sections');
return page;
}
|
[
"function",
"decodePage",
"(",
"output",
",",
"page",
",",
"result",
")",
"{",
"var",
"originalContent",
"=",
"page",
".",
"getContent",
"(",
")",
";",
"if",
"(",
"!",
"result",
")",
"{",
"return",
"page",
";",
"}",
"deprecate",
".",
"disable",
"(",
"'page.sections'",
")",
";",
"if",
"(",
"result",
".",
"content",
"!=",
"originalContent",
")",
"{",
"page",
"=",
"page",
".",
"set",
"(",
"'content'",
",",
"result",
".",
"content",
")",
";",
"}",
"else",
"if",
"(",
"result",
".",
"sections",
")",
"{",
"page",
"=",
"page",
".",
"set",
"(",
"'content'",
",",
"result",
".",
"sections",
".",
"map",
"(",
"function",
"(",
"section",
")",
"{",
"return",
"section",
".",
"content",
";",
"}",
")",
".",
"join",
"(",
"'\\n'",
")",
")",
";",
"}",
"\\n",
"deprecate",
".",
"enable",
"(",
"'page.sections'",
")",
";",
"}"
] |
Decode changes from a JS API to a page object.
Only the content can be edited by plugin's hooks.
@param {Output} output
@param {Page} page: page instance to edit
@param {Object} result: result from API
@return {Page}
|
[
"Decode",
"changes",
"from",
"a",
"JS",
"API",
"to",
"a",
"page",
"object",
".",
"Only",
"the",
"content",
"can",
"be",
"edited",
"by",
"plugin",
"s",
"hooks",
"."
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/decodePage.js#L12-L42
|
train
|
GitbookIO/gitbook
|
lib/utils/command.js
|
spawnCmd
|
function spawnCmd(command, args, options) {
var d = Promise.defer();
var child = spawn(command, args, options);
child.on('error', function(error) {
return d.reject(error);
});
child.stdout.on('data', function (data) {
d.notify(data);
});
child.stderr.on('data', function (data) {
d.notify(data);
});
child.on('close', function(code) {
if (code === 0) {
d.resolve();
} else {
d.reject(new Error('Error with command "'+command+'"'));
}
});
return d.promise;
}
|
javascript
|
function spawnCmd(command, args, options) {
var d = Promise.defer();
var child = spawn(command, args, options);
child.on('error', function(error) {
return d.reject(error);
});
child.stdout.on('data', function (data) {
d.notify(data);
});
child.stderr.on('data', function (data) {
d.notify(data);
});
child.on('close', function(code) {
if (code === 0) {
d.resolve();
} else {
d.reject(new Error('Error with command "'+command+'"'));
}
});
return d.promise;
}
|
[
"function",
"spawnCmd",
"(",
"command",
",",
"args",
",",
"options",
")",
"{",
"var",
"d",
"=",
"Promise",
".",
"defer",
"(",
")",
";",
"var",
"child",
"=",
"spawn",
"(",
"command",
",",
"args",
",",
"options",
")",
";",
"child",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"error",
")",
"{",
"return",
"d",
".",
"reject",
"(",
"error",
")",
";",
"}",
")",
";",
"child",
".",
"stdout",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"d",
".",
"notify",
"(",
"data",
")",
";",
"}",
")",
";",
"child",
".",
"stderr",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"d",
".",
"notify",
"(",
"data",
")",
";",
"}",
")",
";",
"child",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
"code",
")",
"{",
"if",
"(",
"code",
"===",
"0",
")",
"{",
"d",
".",
"resolve",
"(",
")",
";",
"}",
"else",
"{",
"d",
".",
"reject",
"(",
"new",
"Error",
"(",
"'Error with command \"'",
"+",
"command",
"+",
"'\"'",
")",
")",
";",
"}",
"}",
")",
";",
"return",
"d",
".",
"promise",
";",
"}"
] |
Spawn an executable
@param {String} command
@param {Array} args
@param {Object} options
@return {Promise}
|
[
"Spawn",
"an",
"executable"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/command.js#L44-L69
|
train
|
GitbookIO/gitbook
|
lib/utils/command.js
|
escapeShellArg
|
function escapeShellArg(value) {
if (is.number(value)) {
return value;
}
value = String(value);
value = value.replace(/"/g, '\\"');
return '"' + value + '"';
}
|
javascript
|
function escapeShellArg(value) {
if (is.number(value)) {
return value;
}
value = String(value);
value = value.replace(/"/g, '\\"');
return '"' + value + '"';
}
|
[
"function",
"escapeShellArg",
"(",
"value",
")",
"{",
"if",
"(",
"is",
".",
"number",
"(",
"value",
")",
")",
"{",
"return",
"value",
";",
"}",
"value",
"=",
"String",
"(",
"value",
")",
";",
"value",
"=",
"value",
".",
"replace",
"(",
"/",
"\"",
"/",
"g",
",",
"'\\\\\"'",
")",
";",
"\\\\",
"}"
] |
Transform an option object to a command line string
@param {String|number} value
@param {String}
|
[
"Transform",
"an",
"option",
"object",
"to",
"a",
"command",
"line",
"string"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/command.js#L77-L86
|
train
|
GitbookIO/gitbook
|
lib/utils/command.js
|
optionsToShellArgs
|
function optionsToShellArgs(options) {
var result = [];
for (var key in options) {
var value = options[key];
if (value === null || value === undefined || value === false) {
continue;
}
if (is.bool(value)) {
result.push(key);
} else {
result.push(key + '=' + escapeShellArg(value));
}
}
return result.join(' ');
}
|
javascript
|
function optionsToShellArgs(options) {
var result = [];
for (var key in options) {
var value = options[key];
if (value === null || value === undefined || value === false) {
continue;
}
if (is.bool(value)) {
result.push(key);
} else {
result.push(key + '=' + escapeShellArg(value));
}
}
return result.join(' ');
}
|
[
"function",
"optionsToShellArgs",
"(",
"options",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"key",
"in",
"options",
")",
"{",
"var",
"value",
"=",
"options",
"[",
"key",
"]",
";",
"if",
"(",
"value",
"===",
"null",
"||",
"value",
"===",
"undefined",
"||",
"value",
"===",
"false",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"is",
".",
"bool",
"(",
"value",
")",
")",
"{",
"result",
".",
"push",
"(",
"key",
")",
";",
"}",
"else",
"{",
"result",
".",
"push",
"(",
"key",
"+",
"'='",
"+",
"escapeShellArg",
"(",
"value",
")",
")",
";",
"}",
"}",
"return",
"result",
".",
"join",
"(",
"' '",
")",
";",
"}"
] |
Transform a map of options into a command line arguments string
@param {Object} options
@return {String}
|
[
"Transform",
"a",
"map",
"of",
"options",
"into",
"a",
"command",
"line",
"arguments",
"string"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/command.js#L94-L112
|
train
|
GitbookIO/gitbook
|
lib/output/website/onInit.js
|
onInit
|
function onInit(output) {
return Promise(output)
.then(prepareI18n)
.then(prepareResources)
.then(copyPluginAssets);
}
|
javascript
|
function onInit(output) {
return Promise(output)
.then(prepareI18n)
.then(prepareResources)
.then(copyPluginAssets);
}
|
[
"function",
"onInit",
"(",
"output",
")",
"{",
"return",
"Promise",
"(",
"output",
")",
".",
"then",
"(",
"prepareI18n",
")",
".",
"then",
"(",
"prepareResources",
")",
".",
"then",
"(",
"copyPluginAssets",
")",
";",
"}"
] |
Initialize the generator
@param {Output}
@return {Output}
|
[
"Initialize",
"the",
"generator"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/website/onInit.js#L13-L18
|
train
|
GitbookIO/gitbook
|
lib/output/callPageHook.js
|
callPageHook
|
function callPageHook(name, output, page) {
return callHook(
name,
function(out) {
return Api.encodePage(out, page);
},
function(out, result) {
return Api.decodePage(out, page, result);
},
output
);
}
|
javascript
|
function callPageHook(name, output, page) {
return callHook(
name,
function(out) {
return Api.encodePage(out, page);
},
function(out, result) {
return Api.decodePage(out, page, result);
},
output
);
}
|
[
"function",
"callPageHook",
"(",
"name",
",",
"output",
",",
"page",
")",
"{",
"return",
"callHook",
"(",
"name",
",",
"function",
"(",
"out",
")",
"{",
"return",
"Api",
".",
"encodePage",
"(",
"out",
",",
"page",
")",
";",
"}",
",",
"function",
"(",
"out",
",",
"result",
")",
"{",
"return",
"Api",
".",
"decodePage",
"(",
"out",
",",
"page",
",",
"result",
")",
";",
"}",
",",
"output",
")",
";",
"}"
] |
Call a hook for a specific page
@param {String} name
@param {Output} output
@param {Page} page
@return {Promise<Page>}
|
[
"Call",
"a",
"hook",
"for",
"a",
"specific",
"page"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/callPageHook.js#L12-L26
|
train
|
GitbookIO/gitbook
|
lib/utils/reducedObject.js
|
reducedObject
|
function reducedObject(defaultVersion, currentVersion) {
if(defaultVersion === undefined) {
return currentVersion;
}
return currentVersion.reduce(function(result, value, key) {
var defaultValue = defaultVersion.get(key);
if (Immutable.Map.isMap(value)) {
var diffs = reducedObject(defaultValue, value);
if (diffs.size > 0) {
return result.set(key, diffs);
}
}
if (Immutable.is(defaultValue, value)) {
return result;
}
return result.set(key, value);
}, Immutable.Map());
}
|
javascript
|
function reducedObject(defaultVersion, currentVersion) {
if(defaultVersion === undefined) {
return currentVersion;
}
return currentVersion.reduce(function(result, value, key) {
var defaultValue = defaultVersion.get(key);
if (Immutable.Map.isMap(value)) {
var diffs = reducedObject(defaultValue, value);
if (diffs.size > 0) {
return result.set(key, diffs);
}
}
if (Immutable.is(defaultValue, value)) {
return result;
}
return result.set(key, value);
}, Immutable.Map());
}
|
[
"function",
"reducedObject",
"(",
"defaultVersion",
",",
"currentVersion",
")",
"{",
"if",
"(",
"defaultVersion",
"===",
"undefined",
")",
"{",
"return",
"currentVersion",
";",
"}",
"return",
"currentVersion",
".",
"reduce",
"(",
"function",
"(",
"result",
",",
"value",
",",
"key",
")",
"{",
"var",
"defaultValue",
"=",
"defaultVersion",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"Immutable",
".",
"Map",
".",
"isMap",
"(",
"value",
")",
")",
"{",
"var",
"diffs",
"=",
"reducedObject",
"(",
"defaultValue",
",",
"value",
")",
";",
"if",
"(",
"diffs",
".",
"size",
">",
"0",
")",
"{",
"return",
"result",
".",
"set",
"(",
"key",
",",
"diffs",
")",
";",
"}",
"}",
"if",
"(",
"Immutable",
".",
"is",
"(",
"defaultValue",
",",
"value",
")",
")",
"{",
"return",
"result",
";",
"}",
"return",
"result",
".",
"set",
"(",
"key",
",",
"value",
")",
";",
"}",
",",
"Immutable",
".",
"Map",
"(",
")",
")",
";",
"}"
] |
Reduce the difference between a map and its default version
@param {Map} defaultVersion
@param {Map} currentVersion
@return {Map} The properties of currentVersion that differs from defaultVersion
|
[
"Reduce",
"the",
"difference",
"between",
"a",
"map",
"and",
"its",
"default",
"version"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/reducedObject.js#L9-L31
|
train
|
ksky521/nodeppt
|
packages/nodeppt-serve/config/app.js
|
ensureRelative
|
function ensureRelative(outputDir, p) {
if (path.isAbsolute(p)) {
return path.relative(outputDir, p);
} else {
return p;
}
}
|
javascript
|
function ensureRelative(outputDir, p) {
if (path.isAbsolute(p)) {
return path.relative(outputDir, p);
} else {
return p;
}
}
|
[
"function",
"ensureRelative",
"(",
"outputDir",
",",
"p",
")",
"{",
"if",
"(",
"path",
".",
"isAbsolute",
"(",
"p",
")",
")",
"{",
"return",
"path",
".",
"relative",
"(",
"outputDir",
",",
"p",
")",
";",
"}",
"else",
"{",
"return",
"p",
";",
"}",
"}"
] |
ensure the filename passed to html-webpack-plugin is a relative path because it cannot correctly handle absolute paths
|
[
"ensure",
"the",
"filename",
"passed",
"to",
"html",
"-",
"webpack",
"-",
"plugin",
"is",
"a",
"relative",
"path",
"because",
"it",
"cannot",
"correctly",
"handle",
"absolute",
"paths"
] |
ca77e29ef818c08b0522b31e3925b073cf159b9c
|
https://github.com/ksky521/nodeppt/blob/ca77e29ef818c08b0522b31e3925b073cf159b9c/packages/nodeppt-serve/config/app.js#L9-L15
|
train
|
ksky521/nodeppt
|
packages/nodeppt-parser/lib/markdown/attrs/index.js
|
get
|
function get(arr, n) {
return n >= 0 ? arr[n] : arr[arr.length + n];
}
|
javascript
|
function get(arr, n) {
return n >= 0 ? arr[n] : arr[arr.length + n];
}
|
[
"function",
"get",
"(",
"arr",
",",
"n",
")",
"{",
"return",
"n",
">=",
"0",
"?",
"arr",
"[",
"n",
"]",
":",
"arr",
"[",
"arr",
".",
"length",
"+",
"n",
"]",
";",
"}"
] |
Get n item of array. Supports negative n, where -1 is last
element in array.
@param {array} arr
@param {number} n
|
[
"Get",
"n",
"item",
"of",
"array",
".",
"Supports",
"negative",
"n",
"where",
"-",
"1",
"is",
"last",
"element",
"in",
"array",
"."
] |
ca77e29ef818c08b0522b31e3925b073cf159b9c
|
https://github.com/ksky521/nodeppt/blob/ca77e29ef818c08b0522b31e3925b073cf159b9c/packages/nodeppt-parser/lib/markdown/attrs/index.js#L158-L160
|
train
|
ksky521/nodeppt
|
packages/nodeppt-parser/lib/markdown/prism.js
|
selectLanguage
|
function selectLanguage(options, lang) {
let langToUse = lang;
if (langToUse === '' && options.defaultLanguageForUnspecified !== undefined) {
langToUse = options.defaultLanguageForUnspecified;
}
let prismLang = loadPrismLang(langToUse);
if (prismLang === undefined && options.defaultLanguageForUnknown !== undefined) {
langToUse = options.defaultLanguageForUnknown;
prismLang = loadPrismLang(langToUse);
}
return [langToUse, prismLang];
}
|
javascript
|
function selectLanguage(options, lang) {
let langToUse = lang;
if (langToUse === '' && options.defaultLanguageForUnspecified !== undefined) {
langToUse = options.defaultLanguageForUnspecified;
}
let prismLang = loadPrismLang(langToUse);
if (prismLang === undefined && options.defaultLanguageForUnknown !== undefined) {
langToUse = options.defaultLanguageForUnknown;
prismLang = loadPrismLang(langToUse);
}
return [langToUse, prismLang];
}
|
[
"function",
"selectLanguage",
"(",
"options",
",",
"lang",
")",
"{",
"let",
"langToUse",
"=",
"lang",
";",
"if",
"(",
"langToUse",
"===",
"''",
"&&",
"options",
".",
"defaultLanguageForUnspecified",
"!==",
"undefined",
")",
"{",
"langToUse",
"=",
"options",
".",
"defaultLanguageForUnspecified",
";",
"}",
"let",
"prismLang",
"=",
"loadPrismLang",
"(",
"langToUse",
")",
";",
"if",
"(",
"prismLang",
"===",
"undefined",
"&&",
"options",
".",
"defaultLanguageForUnknown",
"!==",
"undefined",
")",
"{",
"langToUse",
"=",
"options",
".",
"defaultLanguageForUnknown",
";",
"prismLang",
"=",
"loadPrismLang",
"(",
"langToUse",
")",
";",
"}",
"return",
"[",
"langToUse",
",",
"prismLang",
"]",
";",
"}"
] |
Select the language to use for highlighting, based on the provided options and the specified language.
@param {Object} options
The options that were used to initialise the plugin.
@param {String} lang
Code of the language to highlight the text in.
@return {Array} An array where the first element is the name of the language to use, and the second element is the PRISM language object for that language.
|
[
"Select",
"the",
"language",
"to",
"use",
"for",
"highlighting",
"based",
"on",
"the",
"provided",
"options",
"and",
"the",
"specified",
"language",
"."
] |
ca77e29ef818c08b0522b31e3925b073cf159b9c
|
https://github.com/ksky521/nodeppt/blob/ca77e29ef818c08b0522b31e3925b073cf159b9c/packages/nodeppt-parser/lib/markdown/prism.js#L80-L91
|
train
|
ksky521/nodeppt
|
packages/nodeppt-parser/lib/markdown/prism.js
|
checkLanguageOption
|
function checkLanguageOption(options, optionName) {
const language = options[optionName];
if (language !== undefined && loadPrismLang(language) === undefined) {
throw new Error(`Bad option ${optionName}: There is no Prism language '${language}'.`);
}
}
|
javascript
|
function checkLanguageOption(options, optionName) {
const language = options[optionName];
if (language !== undefined && loadPrismLang(language) === undefined) {
throw new Error(`Bad option ${optionName}: There is no Prism language '${language}'.`);
}
}
|
[
"function",
"checkLanguageOption",
"(",
"options",
",",
"optionName",
")",
"{",
"const",
"language",
"=",
"options",
"[",
"optionName",
"]",
";",
"if",
"(",
"language",
"!==",
"undefined",
"&&",
"loadPrismLang",
"(",
"language",
")",
"===",
"undefined",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"optionName",
"}",
"${",
"language",
"}",
"`",
")",
";",
"}",
"}"
] |
Checks whether an option represents a valid Prism language
@param {MarkdownItPrismOptions} options
The options that have been used to initialise the plugin.
@param optionName
The key of the option insides {@code options} that shall be checked.
@throws {Error} If the option is not set to a valid Prism language.
|
[
"Checks",
"whether",
"an",
"option",
"represents",
"a",
"valid",
"Prism",
"language"
] |
ca77e29ef818c08b0522b31e3925b073cf159b9c
|
https://github.com/ksky521/nodeppt/blob/ca77e29ef818c08b0522b31e3925b073cf159b9c/packages/nodeppt-parser/lib/markdown/prism.js#L152-L157
|
train
|
ksky521/nodeppt
|
packages/nodeppt-parser/lib/markdown/plus-list.js
|
applyClass
|
function applyClass(token) {
// init attributes
token.attrs = token.attrs || [];
// get index of class attribute
let keys = token.attrs.map(arr => arr[0]);
let idx = keys.indexOf('class');
if (idx === -1) {
// Add class attribute if not defined
token.attrs.push(['class', className]);
} else {
// Get the current class list to append.
// Watch out for duplicates
let classStr = token.attrs[idx][1] || '';
let classList = classStr.split(' ');
// Add the class if we don't already have it
if (classList.indexOf(className) === -1) {
token.attrs[idx][1] = classStr += ' ' + className;
}
}
}
|
javascript
|
function applyClass(token) {
// init attributes
token.attrs = token.attrs || [];
// get index of class attribute
let keys = token.attrs.map(arr => arr[0]);
let idx = keys.indexOf('class');
if (idx === -1) {
// Add class attribute if not defined
token.attrs.push(['class', className]);
} else {
// Get the current class list to append.
// Watch out for duplicates
let classStr = token.attrs[idx][1] || '';
let classList = classStr.split(' ');
// Add the class if we don't already have it
if (classList.indexOf(className) === -1) {
token.attrs[idx][1] = classStr += ' ' + className;
}
}
}
|
[
"function",
"applyClass",
"(",
"token",
")",
"{",
"token",
".",
"attrs",
"=",
"token",
".",
"attrs",
"||",
"[",
"]",
";",
"let",
"keys",
"=",
"token",
".",
"attrs",
".",
"map",
"(",
"arr",
"=>",
"arr",
"[",
"0",
"]",
")",
";",
"let",
"idx",
"=",
"keys",
".",
"indexOf",
"(",
"'class'",
")",
";",
"if",
"(",
"idx",
"===",
"-",
"1",
")",
"{",
"token",
".",
"attrs",
".",
"push",
"(",
"[",
"'class'",
",",
"className",
"]",
")",
";",
"}",
"else",
"{",
"let",
"classStr",
"=",
"token",
".",
"attrs",
"[",
"idx",
"]",
"[",
"1",
"]",
"||",
"''",
";",
"let",
"classList",
"=",
"classStr",
".",
"split",
"(",
"' '",
")",
";",
"if",
"(",
"classList",
".",
"indexOf",
"(",
"className",
")",
"===",
"-",
"1",
")",
"{",
"token",
".",
"attrs",
"[",
"idx",
"]",
"[",
"1",
"]",
"=",
"classStr",
"+=",
"' '",
"+",
"className",
";",
"}",
"}",
"}"
] |
Adds class to token
@param {any} token
@param {string} className
|
[
"Adds",
"class",
"to",
"token"
] |
ca77e29ef818c08b0522b31e3925b073cf159b9c
|
https://github.com/ksky521/nodeppt/blob/ca77e29ef818c08b0522b31e3925b073cf159b9c/packages/nodeppt-parser/lib/markdown/plus-list.js#L17-L39
|
train
|
react-bootstrap/react-bootstrap
|
www/src/components/SideNav.js
|
attachSearch
|
function attachSearch(ref) {
if (ref && window)
import('docsearch.js').then(({ default: docsearch }) => {
docsearch({
apiKey: '00f98b765b687b91399288e7c4c68ce1',
indexName: 'react_bootstrap_v4',
inputSelector: `#${ref.id}`,
debug: process.env.NODE_ENV !== 'production', // Set debug to true if you want to inspect the dropdown
});
});
}
|
javascript
|
function attachSearch(ref) {
if (ref && window)
import('docsearch.js').then(({ default: docsearch }) => {
docsearch({
apiKey: '00f98b765b687b91399288e7c4c68ce1',
indexName: 'react_bootstrap_v4',
inputSelector: `#${ref.id}`,
debug: process.env.NODE_ENV !== 'production', // Set debug to true if you want to inspect the dropdown
});
});
}
|
[
"function",
"attachSearch",
"(",
"ref",
")",
"{",
"if",
"(",
"ref",
"&&",
"window",
")",
"import",
"(",
"'docsearch.js'",
")",
".",
"then",
"(",
"(",
"{",
"default",
":",
"docsearch",
"}",
")",
"=>",
"{",
"docsearch",
"(",
"{",
"apiKey",
":",
"'00f98b765b687b91399288e7c4c68ce1'",
",",
"indexName",
":",
"'react_bootstrap_v4'",
",",
"inputSelector",
":",
"`",
"${",
"ref",
".",
"id",
"}",
"`",
",",
"debug",
":",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
",",
"}",
")",
";",
"}",
")",
";",
"}"
] |
We need to configure this
|
[
"We",
"need",
"to",
"configure",
"this"
] |
f0dc81f91ae90eb54bd1e4c04fa9419872d347dc
|
https://github.com/react-bootstrap/react-bootstrap/blob/f0dc81f91ae90eb54bd1e4c04fa9419872d347dc/www/src/components/SideNav.js#L141-L151
|
train
|
react-bootstrap/react-bootstrap
|
src/utils/ElementChildren.js
|
map
|
function map(children, func) {
let index = 0;
return React.Children.map(children, child =>
React.isValidElement(child) ? func(child, index++) : child,
);
}
|
javascript
|
function map(children, func) {
let index = 0;
return React.Children.map(children, child =>
React.isValidElement(child) ? func(child, index++) : child,
);
}
|
[
"function",
"map",
"(",
"children",
",",
"func",
")",
"{",
"let",
"index",
"=",
"0",
";",
"return",
"React",
".",
"Children",
".",
"map",
"(",
"children",
",",
"child",
"=>",
"React",
".",
"isValidElement",
"(",
"child",
")",
"?",
"func",
"(",
"child",
",",
"index",
"++",
")",
":",
"child",
",",
")",
";",
"}"
] |
Iterates through children that are typically specified as `props.children`,
but only maps over children that are "valid elements".
The mapFunction provided index will be normalised to the components mapped,
so an invalid component would not increase the index.
|
[
"Iterates",
"through",
"children",
"that",
"are",
"typically",
"specified",
"as",
"props",
".",
"children",
"but",
"only",
"maps",
"over",
"children",
"that",
"are",
"valid",
"elements",
"."
] |
f0dc81f91ae90eb54bd1e4c04fa9419872d347dc
|
https://github.com/react-bootstrap/react-bootstrap/blob/f0dc81f91ae90eb54bd1e4c04fa9419872d347dc/src/utils/ElementChildren.js#L11-L17
|
train
|
react-bootstrap/react-bootstrap
|
src/utils/ElementChildren.js
|
forEach
|
function forEach(children, func) {
let index = 0;
React.Children.forEach(children, child => {
if (React.isValidElement(child)) func(child, index++);
});
}
|
javascript
|
function forEach(children, func) {
let index = 0;
React.Children.forEach(children, child => {
if (React.isValidElement(child)) func(child, index++);
});
}
|
[
"function",
"forEach",
"(",
"children",
",",
"func",
")",
"{",
"let",
"index",
"=",
"0",
";",
"React",
".",
"Children",
".",
"forEach",
"(",
"children",
",",
"child",
"=>",
"{",
"if",
"(",
"React",
".",
"isValidElement",
"(",
"child",
")",
")",
"func",
"(",
"child",
",",
"index",
"++",
")",
";",
"}",
")",
";",
"}"
] |
Iterates through children that are "valid elements".
The provided forEachFunc(child, index) will be called for each
leaf child with the index reflecting the position relative to "valid components".
|
[
"Iterates",
"through",
"children",
"that",
"are",
"valid",
"elements",
"."
] |
f0dc81f91ae90eb54bd1e4c04fa9419872d347dc
|
https://github.com/react-bootstrap/react-bootstrap/blob/f0dc81f91ae90eb54bd1e4c04fa9419872d347dc/src/utils/ElementChildren.js#L25-L30
|
train
|
openlayers/openlayers
|
examples/image-filter.js
|
convolve
|
function convolve(context, kernel) {
const canvas = context.canvas;
const width = canvas.width;
const height = canvas.height;
const size = Math.sqrt(kernel.length);
const half = Math.floor(size / 2);
const inputData = context.getImageData(0, 0, width, height).data;
const output = context.createImageData(width, height);
const outputData = output.data;
for (let pixelY = 0; pixelY < height; ++pixelY) {
const pixelsAbove = pixelY * width;
for (let pixelX = 0; pixelX < width; ++pixelX) {
let r = 0, g = 0, b = 0, a = 0;
for (let kernelY = 0; kernelY < size; ++kernelY) {
for (let kernelX = 0; kernelX < size; ++kernelX) {
const weight = kernel[kernelY * size + kernelX];
const neighborY = Math.min(
height - 1, Math.max(0, pixelY + kernelY - half));
const neighborX = Math.min(
width - 1, Math.max(0, pixelX + kernelX - half));
const inputIndex = (neighborY * width + neighborX) * 4;
r += inputData[inputIndex] * weight;
g += inputData[inputIndex + 1] * weight;
b += inputData[inputIndex + 2] * weight;
a += inputData[inputIndex + 3] * weight;
}
}
const outputIndex = (pixelsAbove + pixelX) * 4;
outputData[outputIndex] = r;
outputData[outputIndex + 1] = g;
outputData[outputIndex + 2] = b;
outputData[outputIndex + 3] = kernel.normalized ? a : 255;
}
}
context.putImageData(output, 0, 0);
}
|
javascript
|
function convolve(context, kernel) {
const canvas = context.canvas;
const width = canvas.width;
const height = canvas.height;
const size = Math.sqrt(kernel.length);
const half = Math.floor(size / 2);
const inputData = context.getImageData(0, 0, width, height).data;
const output = context.createImageData(width, height);
const outputData = output.data;
for (let pixelY = 0; pixelY < height; ++pixelY) {
const pixelsAbove = pixelY * width;
for (let pixelX = 0; pixelX < width; ++pixelX) {
let r = 0, g = 0, b = 0, a = 0;
for (let kernelY = 0; kernelY < size; ++kernelY) {
for (let kernelX = 0; kernelX < size; ++kernelX) {
const weight = kernel[kernelY * size + kernelX];
const neighborY = Math.min(
height - 1, Math.max(0, pixelY + kernelY - half));
const neighborX = Math.min(
width - 1, Math.max(0, pixelX + kernelX - half));
const inputIndex = (neighborY * width + neighborX) * 4;
r += inputData[inputIndex] * weight;
g += inputData[inputIndex + 1] * weight;
b += inputData[inputIndex + 2] * weight;
a += inputData[inputIndex + 3] * weight;
}
}
const outputIndex = (pixelsAbove + pixelX) * 4;
outputData[outputIndex] = r;
outputData[outputIndex + 1] = g;
outputData[outputIndex + 2] = b;
outputData[outputIndex + 3] = kernel.normalized ? a : 255;
}
}
context.putImageData(output, 0, 0);
}
|
[
"function",
"convolve",
"(",
"context",
",",
"kernel",
")",
"{",
"const",
"canvas",
"=",
"context",
".",
"canvas",
";",
"const",
"width",
"=",
"canvas",
".",
"width",
";",
"const",
"height",
"=",
"canvas",
".",
"height",
";",
"const",
"size",
"=",
"Math",
".",
"sqrt",
"(",
"kernel",
".",
"length",
")",
";",
"const",
"half",
"=",
"Math",
".",
"floor",
"(",
"size",
"/",
"2",
")",
";",
"const",
"inputData",
"=",
"context",
".",
"getImageData",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
".",
"data",
";",
"const",
"output",
"=",
"context",
".",
"createImageData",
"(",
"width",
",",
"height",
")",
";",
"const",
"outputData",
"=",
"output",
".",
"data",
";",
"for",
"(",
"let",
"pixelY",
"=",
"0",
";",
"pixelY",
"<",
"height",
";",
"++",
"pixelY",
")",
"{",
"const",
"pixelsAbove",
"=",
"pixelY",
"*",
"width",
";",
"for",
"(",
"let",
"pixelX",
"=",
"0",
";",
"pixelX",
"<",
"width",
";",
"++",
"pixelX",
")",
"{",
"let",
"r",
"=",
"0",
",",
"g",
"=",
"0",
",",
"b",
"=",
"0",
",",
"a",
"=",
"0",
";",
"for",
"(",
"let",
"kernelY",
"=",
"0",
";",
"kernelY",
"<",
"size",
";",
"++",
"kernelY",
")",
"{",
"for",
"(",
"let",
"kernelX",
"=",
"0",
";",
"kernelX",
"<",
"size",
";",
"++",
"kernelX",
")",
"{",
"const",
"weight",
"=",
"kernel",
"[",
"kernelY",
"*",
"size",
"+",
"kernelX",
"]",
";",
"const",
"neighborY",
"=",
"Math",
".",
"min",
"(",
"height",
"-",
"1",
",",
"Math",
".",
"max",
"(",
"0",
",",
"pixelY",
"+",
"kernelY",
"-",
"half",
")",
")",
";",
"const",
"neighborX",
"=",
"Math",
".",
"min",
"(",
"width",
"-",
"1",
",",
"Math",
".",
"max",
"(",
"0",
",",
"pixelX",
"+",
"kernelX",
"-",
"half",
")",
")",
";",
"const",
"inputIndex",
"=",
"(",
"neighborY",
"*",
"width",
"+",
"neighborX",
")",
"*",
"4",
";",
"r",
"+=",
"inputData",
"[",
"inputIndex",
"]",
"*",
"weight",
";",
"g",
"+=",
"inputData",
"[",
"inputIndex",
"+",
"1",
"]",
"*",
"weight",
";",
"b",
"+=",
"inputData",
"[",
"inputIndex",
"+",
"2",
"]",
"*",
"weight",
";",
"a",
"+=",
"inputData",
"[",
"inputIndex",
"+",
"3",
"]",
"*",
"weight",
";",
"}",
"}",
"const",
"outputIndex",
"=",
"(",
"pixelsAbove",
"+",
"pixelX",
")",
"*",
"4",
";",
"outputData",
"[",
"outputIndex",
"]",
"=",
"r",
";",
"outputData",
"[",
"outputIndex",
"+",
"1",
"]",
"=",
"g",
";",
"outputData",
"[",
"outputIndex",
"+",
"2",
"]",
"=",
"b",
";",
"outputData",
"[",
"outputIndex",
"+",
"3",
"]",
"=",
"kernel",
".",
"normalized",
"?",
"a",
":",
"255",
";",
"}",
"}",
"context",
".",
"putImageData",
"(",
"output",
",",
"0",
",",
"0",
")",
";",
"}"
] |
Apply a convolution kernel to canvas. This works for any size kernel, but
performance starts degrading above 3 x 3.
@param {CanvasRenderingContext2D} context Canvas 2d context.
@param {Array<number>} kernel Kernel.
|
[
"Apply",
"a",
"convolution",
"kernel",
"to",
"canvas",
".",
"This",
"works",
"for",
"any",
"size",
"kernel",
"but",
"performance",
"starts",
"degrading",
"above",
"3",
"x",
"3",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/image-filter.js#L106-L145
|
train
|
openlayers/openlayers
|
examples/color-manipulation.js
|
rgb2hcl
|
function rgb2hcl(pixel) {
const red = rgb2xyz(pixel[0]);
const green = rgb2xyz(pixel[1]);
const blue = rgb2xyz(pixel[2]);
const x = xyz2lab(
(0.4124564 * red + 0.3575761 * green + 0.1804375 * blue) / Xn);
const y = xyz2lab(
(0.2126729 * red + 0.7151522 * green + 0.0721750 * blue) / Yn);
const z = xyz2lab(
(0.0193339 * red + 0.1191920 * green + 0.9503041 * blue) / Zn);
const l = 116 * y - 16;
const a = 500 * (x - y);
const b = 200 * (y - z);
const c = Math.sqrt(a * a + b * b);
let h = Math.atan2(b, a);
if (h < 0) {
h += twoPi;
}
pixel[0] = h;
pixel[1] = c;
pixel[2] = l;
return pixel;
}
|
javascript
|
function rgb2hcl(pixel) {
const red = rgb2xyz(pixel[0]);
const green = rgb2xyz(pixel[1]);
const blue = rgb2xyz(pixel[2]);
const x = xyz2lab(
(0.4124564 * red + 0.3575761 * green + 0.1804375 * blue) / Xn);
const y = xyz2lab(
(0.2126729 * red + 0.7151522 * green + 0.0721750 * blue) / Yn);
const z = xyz2lab(
(0.0193339 * red + 0.1191920 * green + 0.9503041 * blue) / Zn);
const l = 116 * y - 16;
const a = 500 * (x - y);
const b = 200 * (y - z);
const c = Math.sqrt(a * a + b * b);
let h = Math.atan2(b, a);
if (h < 0) {
h += twoPi;
}
pixel[0] = h;
pixel[1] = c;
pixel[2] = l;
return pixel;
}
|
[
"function",
"rgb2hcl",
"(",
"pixel",
")",
"{",
"const",
"red",
"=",
"rgb2xyz",
"(",
"pixel",
"[",
"0",
"]",
")",
";",
"const",
"green",
"=",
"rgb2xyz",
"(",
"pixel",
"[",
"1",
"]",
")",
";",
"const",
"blue",
"=",
"rgb2xyz",
"(",
"pixel",
"[",
"2",
"]",
")",
";",
"const",
"x",
"=",
"xyz2lab",
"(",
"(",
"0.4124564",
"*",
"red",
"+",
"0.3575761",
"*",
"green",
"+",
"0.1804375",
"*",
"blue",
")",
"/",
"Xn",
")",
";",
"const",
"y",
"=",
"xyz2lab",
"(",
"(",
"0.2126729",
"*",
"red",
"+",
"0.7151522",
"*",
"green",
"+",
"0.0721750",
"*",
"blue",
")",
"/",
"Yn",
")",
";",
"const",
"z",
"=",
"xyz2lab",
"(",
"(",
"0.0193339",
"*",
"red",
"+",
"0.1191920",
"*",
"green",
"+",
"0.9503041",
"*",
"blue",
")",
"/",
"Zn",
")",
";",
"const",
"l",
"=",
"116",
"*",
"y",
"-",
"16",
";",
"const",
"a",
"=",
"500",
"*",
"(",
"x",
"-",
"y",
")",
";",
"const",
"b",
"=",
"200",
"*",
"(",
"y",
"-",
"z",
")",
";",
"const",
"c",
"=",
"Math",
".",
"sqrt",
"(",
"a",
"*",
"a",
"+",
"b",
"*",
"b",
")",
";",
"let",
"h",
"=",
"Math",
".",
"atan2",
"(",
"b",
",",
"a",
")",
";",
"if",
"(",
"h",
"<",
"0",
")",
"{",
"h",
"+=",
"twoPi",
";",
"}",
"pixel",
"[",
"0",
"]",
"=",
"h",
";",
"pixel",
"[",
"1",
"]",
"=",
"c",
";",
"pixel",
"[",
"2",
"]",
"=",
"l",
";",
"return",
"pixel",
";",
"}"
] |
Convert an RGB pixel into an HCL pixel.
@param {Array<number>} pixel A pixel in RGB space.
@return {Array<number>} A pixel in HCL space.
|
[
"Convert",
"an",
"RGB",
"pixel",
"into",
"an",
"HCL",
"pixel",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/color-manipulation.js#L26-L53
|
train
|
openlayers/openlayers
|
examples/color-manipulation.js
|
hcl2rgb
|
function hcl2rgb(pixel) {
const h = pixel[0];
const c = pixel[1];
const l = pixel[2];
const a = Math.cos(h) * c;
const b = Math.sin(h) * c;
let y = (l + 16) / 116;
let x = isNaN(a) ? y : y + a / 500;
let z = isNaN(b) ? y : y - b / 200;
y = Yn * lab2xyz(y);
x = Xn * lab2xyz(x);
z = Zn * lab2xyz(z);
pixel[0] = xyz2rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z);
pixel[1] = xyz2rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z);
pixel[2] = xyz2rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z);
return pixel;
}
|
javascript
|
function hcl2rgb(pixel) {
const h = pixel[0];
const c = pixel[1];
const l = pixel[2];
const a = Math.cos(h) * c;
const b = Math.sin(h) * c;
let y = (l + 16) / 116;
let x = isNaN(a) ? y : y + a / 500;
let z = isNaN(b) ? y : y - b / 200;
y = Yn * lab2xyz(y);
x = Xn * lab2xyz(x);
z = Zn * lab2xyz(z);
pixel[0] = xyz2rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z);
pixel[1] = xyz2rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z);
pixel[2] = xyz2rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z);
return pixel;
}
|
[
"function",
"hcl2rgb",
"(",
"pixel",
")",
"{",
"const",
"h",
"=",
"pixel",
"[",
"0",
"]",
";",
"const",
"c",
"=",
"pixel",
"[",
"1",
"]",
";",
"const",
"l",
"=",
"pixel",
"[",
"2",
"]",
";",
"const",
"a",
"=",
"Math",
".",
"cos",
"(",
"h",
")",
"*",
"c",
";",
"const",
"b",
"=",
"Math",
".",
"sin",
"(",
"h",
")",
"*",
"c",
";",
"let",
"y",
"=",
"(",
"l",
"+",
"16",
")",
"/",
"116",
";",
"let",
"x",
"=",
"isNaN",
"(",
"a",
")",
"?",
"y",
":",
"y",
"+",
"a",
"/",
"500",
";",
"let",
"z",
"=",
"isNaN",
"(",
"b",
")",
"?",
"y",
":",
"y",
"-",
"b",
"/",
"200",
";",
"y",
"=",
"Yn",
"*",
"lab2xyz",
"(",
"y",
")",
";",
"x",
"=",
"Xn",
"*",
"lab2xyz",
"(",
"x",
")",
";",
"z",
"=",
"Zn",
"*",
"lab2xyz",
"(",
"z",
")",
";",
"pixel",
"[",
"0",
"]",
"=",
"xyz2rgb",
"(",
"3.2404542",
"*",
"x",
"-",
"1.5371385",
"*",
"y",
"-",
"0.4985314",
"*",
"z",
")",
";",
"pixel",
"[",
"1",
"]",
"=",
"xyz2rgb",
"(",
"-",
"0.9692660",
"*",
"x",
"+",
"1.8760108",
"*",
"y",
"+",
"0.0415560",
"*",
"z",
")",
";",
"pixel",
"[",
"2",
"]",
"=",
"xyz2rgb",
"(",
"0.0556434",
"*",
"x",
"-",
"0.2040259",
"*",
"y",
"+",
"1.0572252",
"*",
"z",
")",
";",
"return",
"pixel",
";",
"}"
] |
Convert an HCL pixel into an RGB pixel.
@param {Array<number>} pixel A pixel in HCL space.
@return {Array<number>} A pixel in RGB space.
|
[
"Convert",
"an",
"HCL",
"pixel",
"into",
"an",
"RGB",
"pixel",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/color-manipulation.js#L61-L82
|
train
|
openlayers/openlayers
|
examples/webpack/example-builder.js
|
createWordIndex
|
function createWordIndex(exampleData) {
const index = {};
const keys = ['shortdesc', 'title', 'tags'];
exampleData.forEach((data, i) => {
keys.forEach(key => {
let text = data[key];
if (Array.isArray(text)) {
text = text.join(' ');
}
const words = text ? text.split(/\W+/) : [];
words.forEach(word => {
if (word) {
word = word.toLowerCase();
let counts = index[word];
if (counts) {
if (index in counts) {
counts[i] += 1;
} else {
counts[i] = 1;
}
} else {
counts = {};
counts[i] = 1;
index[word] = counts;
}
}
});
});
});
return index;
}
|
javascript
|
function createWordIndex(exampleData) {
const index = {};
const keys = ['shortdesc', 'title', 'tags'];
exampleData.forEach((data, i) => {
keys.forEach(key => {
let text = data[key];
if (Array.isArray(text)) {
text = text.join(' ');
}
const words = text ? text.split(/\W+/) : [];
words.forEach(word => {
if (word) {
word = word.toLowerCase();
let counts = index[word];
if (counts) {
if (index in counts) {
counts[i] += 1;
} else {
counts[i] = 1;
}
} else {
counts = {};
counts[i] = 1;
index[word] = counts;
}
}
});
});
});
return index;
}
|
[
"function",
"createWordIndex",
"(",
"exampleData",
")",
"{",
"const",
"index",
"=",
"{",
"}",
";",
"const",
"keys",
"=",
"[",
"'shortdesc'",
",",
"'title'",
",",
"'tags'",
"]",
";",
"exampleData",
".",
"forEach",
"(",
"(",
"data",
",",
"i",
")",
"=>",
"{",
"keys",
".",
"forEach",
"(",
"key",
"=>",
"{",
"let",
"text",
"=",
"data",
"[",
"key",
"]",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"text",
")",
")",
"{",
"text",
"=",
"text",
".",
"join",
"(",
"' '",
")",
";",
"}",
"const",
"words",
"=",
"text",
"?",
"text",
".",
"split",
"(",
"/",
"\\W+",
"/",
")",
":",
"[",
"]",
";",
"words",
".",
"forEach",
"(",
"word",
"=>",
"{",
"if",
"(",
"word",
")",
"{",
"word",
"=",
"word",
".",
"toLowerCase",
"(",
")",
";",
"let",
"counts",
"=",
"index",
"[",
"word",
"]",
";",
"if",
"(",
"counts",
")",
"{",
"if",
"(",
"index",
"in",
"counts",
")",
"{",
"counts",
"[",
"i",
"]",
"+=",
"1",
";",
"}",
"else",
"{",
"counts",
"[",
"i",
"]",
"=",
"1",
";",
"}",
"}",
"else",
"{",
"counts",
"=",
"{",
"}",
";",
"counts",
"[",
"i",
"]",
"=",
"1",
";",
"index",
"[",
"word",
"]",
"=",
"counts",
";",
"}",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"index",
";",
"}"
] |
Create an inverted index of keywords from examples. Property names are
lowercased words. Property values are objects mapping example index to word
count.
@param {Array<Object>} exampleData Array of example data objects.
@return {Object} Word index.
|
[
"Create",
"an",
"inverted",
"index",
"of",
"keywords",
"from",
"examples",
".",
"Property",
"names",
"are",
"lowercased",
"words",
".",
"Property",
"values",
"are",
"objects",
"mapping",
"example",
"index",
"to",
"word",
"count",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/webpack/example-builder.js#L33-L63
|
train
|
openlayers/openlayers
|
examples/webpack/example-builder.js
|
getJsSource
|
function getJsSource(chunk, jsName) {
let jsSource;
for (let i = 0, ii = chunk.modules.length; i < ii; ++i) {
const module = chunk.modules[i];
if (module.modules) {
jsSource = getJsSource(module, jsName);
if (jsSource) {
return jsSource;
}
}
if (module.identifier.endsWith(jsName) && module.source) {
return module.source;
}
}
}
|
javascript
|
function getJsSource(chunk, jsName) {
let jsSource;
for (let i = 0, ii = chunk.modules.length; i < ii; ++i) {
const module = chunk.modules[i];
if (module.modules) {
jsSource = getJsSource(module, jsName);
if (jsSource) {
return jsSource;
}
}
if (module.identifier.endsWith(jsName) && module.source) {
return module.source;
}
}
}
|
[
"function",
"getJsSource",
"(",
"chunk",
",",
"jsName",
")",
"{",
"let",
"jsSource",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"ii",
"=",
"chunk",
".",
"modules",
".",
"length",
";",
"i",
"<",
"ii",
";",
"++",
"i",
")",
"{",
"const",
"module",
"=",
"chunk",
".",
"modules",
"[",
"i",
"]",
";",
"if",
"(",
"module",
".",
"modules",
")",
"{",
"jsSource",
"=",
"getJsSource",
"(",
"module",
",",
"jsName",
")",
";",
"if",
"(",
"jsSource",
")",
"{",
"return",
"jsSource",
";",
"}",
"}",
"if",
"(",
"module",
".",
"identifier",
".",
"endsWith",
"(",
"jsName",
")",
"&&",
"module",
".",
"source",
")",
"{",
"return",
"module",
".",
"source",
";",
"}",
"}",
"}"
] |
Gets the source for the chunk that matches the jsPath
@param {Object} chunk Chunk.
@param {string} jsName Name of the file.
@return {string} The source.
|
[
"Gets",
"the",
"source",
"for",
"the",
"chunk",
"that",
"matches",
"the",
"jsPath"
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/webpack/example-builder.js#L71-L85
|
train
|
openlayers/openlayers
|
examples/webpack/example-builder.js
|
getDependencies
|
function getDependencies(jsSource) {
const lines = jsSource.split('\n');
const dependencies = {
ol: pkg.version
};
for (let i = 0, ii = lines.length; i < ii; ++i) {
const line = lines[i];
const importMatch = line.match(importRegEx);
if (importMatch) {
const imp = importMatch[1];
if (!imp.startsWith('ol/') && imp != 'ol') {
const parts = imp.split('/');
let dep;
if (imp.startsWith('@')) {
dep = parts.slice(0, 2).join('/');
} else {
dep = parts[0];
}
if (dep in pkg.devDependencies) {
dependencies[dep] = pkg.devDependencies[dep];
}
}
}
}
return dependencies;
}
|
javascript
|
function getDependencies(jsSource) {
const lines = jsSource.split('\n');
const dependencies = {
ol: pkg.version
};
for (let i = 0, ii = lines.length; i < ii; ++i) {
const line = lines[i];
const importMatch = line.match(importRegEx);
if (importMatch) {
const imp = importMatch[1];
if (!imp.startsWith('ol/') && imp != 'ol') {
const parts = imp.split('/');
let dep;
if (imp.startsWith('@')) {
dep = parts.slice(0, 2).join('/');
} else {
dep = parts[0];
}
if (dep in pkg.devDependencies) {
dependencies[dep] = pkg.devDependencies[dep];
}
}
}
}
return dependencies;
}
|
[
"function",
"getDependencies",
"(",
"jsSource",
")",
"{",
"const",
"lines",
"=",
"jsSource",
".",
"split",
"(",
"'\\n'",
")",
";",
"\\n",
"const",
"dependencies",
"=",
"{",
"ol",
":",
"pkg",
".",
"version",
"}",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"ii",
"=",
"lines",
".",
"length",
";",
"i",
"<",
"ii",
";",
"++",
"i",
")",
"{",
"const",
"line",
"=",
"lines",
"[",
"i",
"]",
";",
"const",
"importMatch",
"=",
"line",
".",
"match",
"(",
"importRegEx",
")",
";",
"if",
"(",
"importMatch",
")",
"{",
"const",
"imp",
"=",
"importMatch",
"[",
"1",
"]",
";",
"if",
"(",
"!",
"imp",
".",
"startsWith",
"(",
"'ol/'",
")",
"&&",
"imp",
"!=",
"'ol'",
")",
"{",
"const",
"parts",
"=",
"imp",
".",
"split",
"(",
"'/'",
")",
";",
"let",
"dep",
";",
"if",
"(",
"imp",
".",
"startsWith",
"(",
"'@'",
")",
")",
"{",
"dep",
"=",
"parts",
".",
"slice",
"(",
"0",
",",
"2",
")",
".",
"join",
"(",
"'/'",
")",
";",
"}",
"else",
"{",
"dep",
"=",
"parts",
"[",
"0",
"]",
";",
"}",
"if",
"(",
"dep",
"in",
"pkg",
".",
"devDependencies",
")",
"{",
"dependencies",
"[",
"dep",
"]",
"=",
"pkg",
".",
"devDependencies",
"[",
"dep",
"]",
";",
"}",
"}",
"}",
"}",
"}"
] |
Gets dependencies from the js source.
@param {string} jsSource Source.
@return {Object<string, string>} dependencies
|
[
"Gets",
"dependencies",
"from",
"the",
"js",
"source",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/webpack/example-builder.js#L92-L117
|
train
|
openlayers/openlayers
|
src/ol/format/KML.js
|
setCommonGeometryProperties
|
function setCommonGeometryProperties(multiGeometry, geometries) {
const ii = geometries.length;
const extrudes = new Array(geometries.length);
const tessellates = new Array(geometries.length);
const altitudeModes = new Array(geometries.length);
let hasExtrude, hasTessellate, hasAltitudeMode;
hasExtrude = hasTessellate = hasAltitudeMode = false;
for (let i = 0; i < ii; ++i) {
const geometry = geometries[i];
extrudes[i] = geometry.get('extrude');
tessellates[i] = geometry.get('tessellate');
altitudeModes[i] = geometry.get('altitudeMode');
hasExtrude = hasExtrude || extrudes[i] !== undefined;
hasTessellate = hasTessellate || tessellates[i] !== undefined;
hasAltitudeMode = hasAltitudeMode || altitudeModes[i];
}
if (hasExtrude) {
multiGeometry.set('extrude', extrudes);
}
if (hasTessellate) {
multiGeometry.set('tessellate', tessellates);
}
if (hasAltitudeMode) {
multiGeometry.set('altitudeMode', altitudeModes);
}
}
|
javascript
|
function setCommonGeometryProperties(multiGeometry, geometries) {
const ii = geometries.length;
const extrudes = new Array(geometries.length);
const tessellates = new Array(geometries.length);
const altitudeModes = new Array(geometries.length);
let hasExtrude, hasTessellate, hasAltitudeMode;
hasExtrude = hasTessellate = hasAltitudeMode = false;
for (let i = 0; i < ii; ++i) {
const geometry = geometries[i];
extrudes[i] = geometry.get('extrude');
tessellates[i] = geometry.get('tessellate');
altitudeModes[i] = geometry.get('altitudeMode');
hasExtrude = hasExtrude || extrudes[i] !== undefined;
hasTessellate = hasTessellate || tessellates[i] !== undefined;
hasAltitudeMode = hasAltitudeMode || altitudeModes[i];
}
if (hasExtrude) {
multiGeometry.set('extrude', extrudes);
}
if (hasTessellate) {
multiGeometry.set('tessellate', tessellates);
}
if (hasAltitudeMode) {
multiGeometry.set('altitudeMode', altitudeModes);
}
}
|
[
"function",
"setCommonGeometryProperties",
"(",
"multiGeometry",
",",
"geometries",
")",
"{",
"const",
"ii",
"=",
"geometries",
".",
"length",
";",
"const",
"extrudes",
"=",
"new",
"Array",
"(",
"geometries",
".",
"length",
")",
";",
"const",
"tessellates",
"=",
"new",
"Array",
"(",
"geometries",
".",
"length",
")",
";",
"const",
"altitudeModes",
"=",
"new",
"Array",
"(",
"geometries",
".",
"length",
")",
";",
"let",
"hasExtrude",
",",
"hasTessellate",
",",
"hasAltitudeMode",
";",
"hasExtrude",
"=",
"hasTessellate",
"=",
"hasAltitudeMode",
"=",
"false",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"ii",
";",
"++",
"i",
")",
"{",
"const",
"geometry",
"=",
"geometries",
"[",
"i",
"]",
";",
"extrudes",
"[",
"i",
"]",
"=",
"geometry",
".",
"get",
"(",
"'extrude'",
")",
";",
"tessellates",
"[",
"i",
"]",
"=",
"geometry",
".",
"get",
"(",
"'tessellate'",
")",
";",
"altitudeModes",
"[",
"i",
"]",
"=",
"geometry",
".",
"get",
"(",
"'altitudeMode'",
")",
";",
"hasExtrude",
"=",
"hasExtrude",
"||",
"extrudes",
"[",
"i",
"]",
"!==",
"undefined",
";",
"hasTessellate",
"=",
"hasTessellate",
"||",
"tessellates",
"[",
"i",
"]",
"!==",
"undefined",
";",
"hasAltitudeMode",
"=",
"hasAltitudeMode",
"||",
"altitudeModes",
"[",
"i",
"]",
";",
"}",
"if",
"(",
"hasExtrude",
")",
"{",
"multiGeometry",
".",
"set",
"(",
"'extrude'",
",",
"extrudes",
")",
";",
"}",
"if",
"(",
"hasTessellate",
")",
"{",
"multiGeometry",
".",
"set",
"(",
"'tessellate'",
",",
"tessellates",
")",
";",
"}",
"if",
"(",
"hasAltitudeMode",
")",
"{",
"multiGeometry",
".",
"set",
"(",
"'altitudeMode'",
",",
"altitudeModes",
")",
";",
"}",
"}"
] |
Reads an array of geometries and creates arrays for common geometry
properties. Then sets them to the multi geometry.
@param {MultiPoint|MultiLineString|MultiPolygon} multiGeometry A multi-geometry.
@param {Array<import("../geom/Geometry.js").default>} geometries List of geometries.
|
[
"Reads",
"an",
"array",
"of",
"geometries",
"and",
"creates",
"arrays",
"for",
"common",
"geometry",
"properties",
".",
"Then",
"sets",
"them",
"to",
"the",
"multi",
"geometry",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/KML.js#L1753-L1778
|
train
|
openlayers/openlayers
|
src/ol/pointer/MsSource.js
|
msPointerDown
|
function msPointerDown(inEvent) {
this.pointerMap[inEvent.pointerId.toString()] = inEvent;
const e = this.prepareEvent_(inEvent);
this.dispatcher.down(e, inEvent);
}
|
javascript
|
function msPointerDown(inEvent) {
this.pointerMap[inEvent.pointerId.toString()] = inEvent;
const e = this.prepareEvent_(inEvent);
this.dispatcher.down(e, inEvent);
}
|
[
"function",
"msPointerDown",
"(",
"inEvent",
")",
"{",
"this",
".",
"pointerMap",
"[",
"inEvent",
".",
"pointerId",
".",
"toString",
"(",
")",
"]",
"=",
"inEvent",
";",
"const",
"e",
"=",
"this",
".",
"prepareEvent_",
"(",
"inEvent",
")",
";",
"this",
".",
"dispatcher",
".",
"down",
"(",
"e",
",",
"inEvent",
")",
";",
"}"
] |
Handler for `msPointerDown`.
@this {MsSource}
@param {MSPointerEvent} inEvent The in event.
|
[
"Handler",
"for",
"msPointerDown",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/pointer/MsSource.js#L55-L59
|
train
|
openlayers/openlayers
|
src/ol/pointer/MsSource.js
|
msPointerUp
|
function msPointerUp(inEvent) {
const e = this.prepareEvent_(inEvent);
this.dispatcher.up(e, inEvent);
this.cleanup(inEvent.pointerId);
}
|
javascript
|
function msPointerUp(inEvent) {
const e = this.prepareEvent_(inEvent);
this.dispatcher.up(e, inEvent);
this.cleanup(inEvent.pointerId);
}
|
[
"function",
"msPointerUp",
"(",
"inEvent",
")",
"{",
"const",
"e",
"=",
"this",
".",
"prepareEvent_",
"(",
"inEvent",
")",
";",
"this",
".",
"dispatcher",
".",
"up",
"(",
"e",
",",
"inEvent",
")",
";",
"this",
".",
"cleanup",
"(",
"inEvent",
".",
"pointerId",
")",
";",
"}"
] |
Handler for `msPointerUp`.
@this {MsSource}
@param {MSPointerEvent} inEvent The in event.
|
[
"Handler",
"for",
"msPointerUp",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/pointer/MsSource.js#L78-L82
|
train
|
openlayers/openlayers
|
src/ol/pointer/MsSource.js
|
msPointerCancel
|
function msPointerCancel(inEvent) {
const e = this.prepareEvent_(inEvent);
this.dispatcher.cancel(e, inEvent);
this.cleanup(inEvent.pointerId);
}
|
javascript
|
function msPointerCancel(inEvent) {
const e = this.prepareEvent_(inEvent);
this.dispatcher.cancel(e, inEvent);
this.cleanup(inEvent.pointerId);
}
|
[
"function",
"msPointerCancel",
"(",
"inEvent",
")",
"{",
"const",
"e",
"=",
"this",
".",
"prepareEvent_",
"(",
"inEvent",
")",
";",
"this",
".",
"dispatcher",
".",
"cancel",
"(",
"e",
",",
"inEvent",
")",
";",
"this",
".",
"cleanup",
"(",
"inEvent",
".",
"pointerId",
")",
";",
"}"
] |
Handler for `msPointerCancel`.
@this {MsSource}
@param {MSPointerEvent} inEvent The in event.
|
[
"Handler",
"for",
"msPointerCancel",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/pointer/MsSource.js#L112-L116
|
train
|
openlayers/openlayers
|
src/ol/pointer/MsSource.js
|
msLostPointerCapture
|
function msLostPointerCapture(inEvent) {
const e = this.dispatcher.makeEvent('lostpointercapture', inEvent, inEvent);
this.dispatcher.dispatchEvent(e);
}
|
javascript
|
function msLostPointerCapture(inEvent) {
const e = this.dispatcher.makeEvent('lostpointercapture', inEvent, inEvent);
this.dispatcher.dispatchEvent(e);
}
|
[
"function",
"msLostPointerCapture",
"(",
"inEvent",
")",
"{",
"const",
"e",
"=",
"this",
".",
"dispatcher",
".",
"makeEvent",
"(",
"'lostpointercapture'",
",",
"inEvent",
",",
"inEvent",
")",
";",
"this",
".",
"dispatcher",
".",
"dispatchEvent",
"(",
"e",
")",
";",
"}"
] |
Handler for `msLostPointerCapture`.
@this {MsSource}
@param {MSPointerEvent} inEvent The in event.
|
[
"Handler",
"for",
"msLostPointerCapture",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/pointer/MsSource.js#L124-L127
|
train
|
openlayers/openlayers
|
src/ol/pointer/MsSource.js
|
msGotPointerCapture
|
function msGotPointerCapture(inEvent) {
const e = this.dispatcher.makeEvent('gotpointercapture', inEvent, inEvent);
this.dispatcher.dispatchEvent(e);
}
|
javascript
|
function msGotPointerCapture(inEvent) {
const e = this.dispatcher.makeEvent('gotpointercapture', inEvent, inEvent);
this.dispatcher.dispatchEvent(e);
}
|
[
"function",
"msGotPointerCapture",
"(",
"inEvent",
")",
"{",
"const",
"e",
"=",
"this",
".",
"dispatcher",
".",
"makeEvent",
"(",
"'gotpointercapture'",
",",
"inEvent",
",",
"inEvent",
")",
";",
"this",
".",
"dispatcher",
".",
"dispatchEvent",
"(",
"e",
")",
";",
"}"
] |
Handler for `msGotPointerCapture`.
@this {MsSource}
@param {MSPointerEvent} inEvent The in event.
|
[
"Handler",
"for",
"msGotPointerCapture",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/pointer/MsSource.js#L135-L138
|
train
|
openlayers/openlayers
|
src/ol/source/Source.js
|
adaptAttributions
|
function adaptAttributions(attributionLike) {
if (!attributionLike) {
return null;
}
if (Array.isArray(attributionLike)) {
return function(frameState) {
return attributionLike;
};
}
if (typeof attributionLike === 'function') {
return attributionLike;
}
return function(frameState) {
return [attributionLike];
};
}
|
javascript
|
function adaptAttributions(attributionLike) {
if (!attributionLike) {
return null;
}
if (Array.isArray(attributionLike)) {
return function(frameState) {
return attributionLike;
};
}
if (typeof attributionLike === 'function') {
return attributionLike;
}
return function(frameState) {
return [attributionLike];
};
}
|
[
"function",
"adaptAttributions",
"(",
"attributionLike",
")",
"{",
"if",
"(",
"!",
"attributionLike",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"attributionLike",
")",
")",
"{",
"return",
"function",
"(",
"frameState",
")",
"{",
"return",
"attributionLike",
";",
"}",
";",
"}",
"if",
"(",
"typeof",
"attributionLike",
"===",
"'function'",
")",
"{",
"return",
"attributionLike",
";",
"}",
"return",
"function",
"(",
"frameState",
")",
"{",
"return",
"[",
"attributionLike",
"]",
";",
"}",
";",
"}"
] |
Turns the attributions option into an attributions function.
@param {AttributionLike|undefined} attributionLike The attribution option.
@return {?Attribution} An attribution function (or null).
|
[
"Turns",
"the",
"attributions",
"option",
"into",
"an",
"attributions",
"function",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/source/Source.js#L184-L201
|
train
|
openlayers/openlayers
|
examples/measure.js
|
function(evt) {
if (evt.dragging) {
return;
}
/** @type {string} */
let helpMsg = 'Click to start drawing';
if (sketch) {
const geom = sketch.getGeometry();
if (geom instanceof Polygon) {
helpMsg = continuePolygonMsg;
} else if (geom instanceof LineString) {
helpMsg = continueLineMsg;
}
}
helpTooltipElement.innerHTML = helpMsg;
helpTooltip.setPosition(evt.coordinate);
helpTooltipElement.classList.remove('hidden');
}
|
javascript
|
function(evt) {
if (evt.dragging) {
return;
}
/** @type {string} */
let helpMsg = 'Click to start drawing';
if (sketch) {
const geom = sketch.getGeometry();
if (geom instanceof Polygon) {
helpMsg = continuePolygonMsg;
} else if (geom instanceof LineString) {
helpMsg = continueLineMsg;
}
}
helpTooltipElement.innerHTML = helpMsg;
helpTooltip.setPosition(evt.coordinate);
helpTooltipElement.classList.remove('hidden');
}
|
[
"function",
"(",
"evt",
")",
"{",
"if",
"(",
"evt",
".",
"dragging",
")",
"{",
"return",
";",
"}",
"let",
"helpMsg",
"=",
"'Click to start drawing'",
";",
"if",
"(",
"sketch",
")",
"{",
"const",
"geom",
"=",
"sketch",
".",
"getGeometry",
"(",
")",
";",
"if",
"(",
"geom",
"instanceof",
"Polygon",
")",
"{",
"helpMsg",
"=",
"continuePolygonMsg",
";",
"}",
"else",
"if",
"(",
"geom",
"instanceof",
"LineString",
")",
"{",
"helpMsg",
"=",
"continueLineMsg",
";",
"}",
"}",
"helpTooltipElement",
".",
"innerHTML",
"=",
"helpMsg",
";",
"helpTooltip",
".",
"setPosition",
"(",
"evt",
".",
"coordinate",
")",
";",
"helpTooltipElement",
".",
"classList",
".",
"remove",
"(",
"'hidden'",
")",
";",
"}"
] |
Handle pointer move.
@param {import("../src/ol/MapBrowserEvent").default} evt The event.
|
[
"Handle",
"pointer",
"move",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/measure.js#L92-L112
|
train
|
|
openlayers/openlayers
|
examples/measure.js
|
function(line) {
const length = getLength(line);
let output;
if (length > 100) {
output = (Math.round(length / 1000 * 100) / 100) +
' ' + 'km';
} else {
output = (Math.round(length * 100) / 100) +
' ' + 'm';
}
return output;
}
|
javascript
|
function(line) {
const length = getLength(line);
let output;
if (length > 100) {
output = (Math.round(length / 1000 * 100) / 100) +
' ' + 'km';
} else {
output = (Math.round(length * 100) / 100) +
' ' + 'm';
}
return output;
}
|
[
"function",
"(",
"line",
")",
"{",
"const",
"length",
"=",
"getLength",
"(",
"line",
")",
";",
"let",
"output",
";",
"if",
"(",
"length",
">",
"100",
")",
"{",
"output",
"=",
"(",
"Math",
".",
"round",
"(",
"length",
"/",
"1000",
"*",
"100",
")",
"/",
"100",
")",
"+",
"' '",
"+",
"'km'",
";",
"}",
"else",
"{",
"output",
"=",
"(",
"Math",
".",
"round",
"(",
"length",
"*",
"100",
")",
"/",
"100",
")",
"+",
"' '",
"+",
"'m'",
";",
"}",
"return",
"output",
";",
"}"
] |
global so we can remove it later
Format length output.
@param {LineString} line The line.
@return {string} The formatted length.
|
[
"global",
"so",
"we",
"can",
"remove",
"it",
"later",
"Format",
"length",
"output",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/measure.js#L140-L151
|
train
|
|
openlayers/openlayers
|
examples/measure.js
|
function(polygon) {
const area = getArea(polygon);
let output;
if (area > 10000) {
output = (Math.round(area / 1000000 * 100) / 100) +
' ' + 'km<sup>2</sup>';
} else {
output = (Math.round(area * 100) / 100) +
' ' + 'm<sup>2</sup>';
}
return output;
}
|
javascript
|
function(polygon) {
const area = getArea(polygon);
let output;
if (area > 10000) {
output = (Math.round(area / 1000000 * 100) / 100) +
' ' + 'km<sup>2</sup>';
} else {
output = (Math.round(area * 100) / 100) +
' ' + 'm<sup>2</sup>';
}
return output;
}
|
[
"function",
"(",
"polygon",
")",
"{",
"const",
"area",
"=",
"getArea",
"(",
"polygon",
")",
";",
"let",
"output",
";",
"if",
"(",
"area",
">",
"10000",
")",
"{",
"output",
"=",
"(",
"Math",
".",
"round",
"(",
"area",
"/",
"1000000",
"*",
"100",
")",
"/",
"100",
")",
"+",
"' '",
"+",
"'km<sup>2</sup>'",
";",
"}",
"else",
"{",
"output",
"=",
"(",
"Math",
".",
"round",
"(",
"area",
"*",
"100",
")",
"/",
"100",
")",
"+",
"' '",
"+",
"'m<sup>2</sup>'",
";",
"}",
"return",
"output",
";",
"}"
] |
Format area output.
@param {Polygon} polygon The polygon.
@return {string} Formatted area.
|
[
"Format",
"area",
"output",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/measure.js#L159-L170
|
train
|
|
openlayers/openlayers
|
examples/measure.js
|
createHelpTooltip
|
function createHelpTooltip() {
if (helpTooltipElement) {
helpTooltipElement.parentNode.removeChild(helpTooltipElement);
}
helpTooltipElement = document.createElement('div');
helpTooltipElement.className = 'ol-tooltip hidden';
helpTooltip = new Overlay({
element: helpTooltipElement,
offset: [15, 0],
positioning: 'center-left'
});
map.addOverlay(helpTooltip);
}
|
javascript
|
function createHelpTooltip() {
if (helpTooltipElement) {
helpTooltipElement.parentNode.removeChild(helpTooltipElement);
}
helpTooltipElement = document.createElement('div');
helpTooltipElement.className = 'ol-tooltip hidden';
helpTooltip = new Overlay({
element: helpTooltipElement,
offset: [15, 0],
positioning: 'center-left'
});
map.addOverlay(helpTooltip);
}
|
[
"function",
"createHelpTooltip",
"(",
")",
"{",
"if",
"(",
"helpTooltipElement",
")",
"{",
"helpTooltipElement",
".",
"parentNode",
".",
"removeChild",
"(",
"helpTooltipElement",
")",
";",
"}",
"helpTooltipElement",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"helpTooltipElement",
".",
"className",
"=",
"'ol-tooltip hidden'",
";",
"helpTooltip",
"=",
"new",
"Overlay",
"(",
"{",
"element",
":",
"helpTooltipElement",
",",
"offset",
":",
"[",
"15",
",",
"0",
"]",
",",
"positioning",
":",
"'center-left'",
"}",
")",
";",
"map",
".",
"addOverlay",
"(",
"helpTooltip",
")",
";",
"}"
] |
Creates a new help tooltip
|
[
"Creates",
"a",
"new",
"help",
"tooltip"
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/measure.js#L243-L255
|
train
|
openlayers/openlayers
|
examples/measure.js
|
createMeasureTooltip
|
function createMeasureTooltip() {
if (measureTooltipElement) {
measureTooltipElement.parentNode.removeChild(measureTooltipElement);
}
measureTooltipElement = document.createElement('div');
measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure';
measureTooltip = new Overlay({
element: measureTooltipElement,
offset: [0, -15],
positioning: 'bottom-center'
});
map.addOverlay(measureTooltip);
}
|
javascript
|
function createMeasureTooltip() {
if (measureTooltipElement) {
measureTooltipElement.parentNode.removeChild(measureTooltipElement);
}
measureTooltipElement = document.createElement('div');
measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure';
measureTooltip = new Overlay({
element: measureTooltipElement,
offset: [0, -15],
positioning: 'bottom-center'
});
map.addOverlay(measureTooltip);
}
|
[
"function",
"createMeasureTooltip",
"(",
")",
"{",
"if",
"(",
"measureTooltipElement",
")",
"{",
"measureTooltipElement",
".",
"parentNode",
".",
"removeChild",
"(",
"measureTooltipElement",
")",
";",
"}",
"measureTooltipElement",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"measureTooltipElement",
".",
"className",
"=",
"'ol-tooltip ol-tooltip-measure'",
";",
"measureTooltip",
"=",
"new",
"Overlay",
"(",
"{",
"element",
":",
"measureTooltipElement",
",",
"offset",
":",
"[",
"0",
",",
"-",
"15",
"]",
",",
"positioning",
":",
"'bottom-center'",
"}",
")",
";",
"map",
".",
"addOverlay",
"(",
"measureTooltip",
")",
";",
"}"
] |
Creates a new measure tooltip
|
[
"Creates",
"a",
"new",
"measure",
"tooltip"
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/measure.js#L261-L273
|
train
|
openlayers/openlayers
|
src/ol/sphere.js
|
getAreaInternal
|
function getAreaInternal(coordinates, radius) {
let area = 0;
const len = coordinates.length;
let x1 = coordinates[len - 1][0];
let y1 = coordinates[len - 1][1];
for (let i = 0; i < len; i++) {
const x2 = coordinates[i][0];
const y2 = coordinates[i][1];
area += toRadians(x2 - x1) *
(2 + Math.sin(toRadians(y1)) +
Math.sin(toRadians(y2)));
x1 = x2;
y1 = y2;
}
return area * radius * radius / 2.0;
}
|
javascript
|
function getAreaInternal(coordinates, radius) {
let area = 0;
const len = coordinates.length;
let x1 = coordinates[len - 1][0];
let y1 = coordinates[len - 1][1];
for (let i = 0; i < len; i++) {
const x2 = coordinates[i][0];
const y2 = coordinates[i][1];
area += toRadians(x2 - x1) *
(2 + Math.sin(toRadians(y1)) +
Math.sin(toRadians(y2)));
x1 = x2;
y1 = y2;
}
return area * radius * radius / 2.0;
}
|
[
"function",
"getAreaInternal",
"(",
"coordinates",
",",
"radius",
")",
"{",
"let",
"area",
"=",
"0",
";",
"const",
"len",
"=",
"coordinates",
".",
"length",
";",
"let",
"x1",
"=",
"coordinates",
"[",
"len",
"-",
"1",
"]",
"[",
"0",
"]",
";",
"let",
"y1",
"=",
"coordinates",
"[",
"len",
"-",
"1",
"]",
"[",
"1",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"const",
"x2",
"=",
"coordinates",
"[",
"i",
"]",
"[",
"0",
"]",
";",
"const",
"y2",
"=",
"coordinates",
"[",
"i",
"]",
"[",
"1",
"]",
";",
"area",
"+=",
"toRadians",
"(",
"x2",
"-",
"x1",
")",
"*",
"(",
"2",
"+",
"Math",
".",
"sin",
"(",
"toRadians",
"(",
"y1",
")",
")",
"+",
"Math",
".",
"sin",
"(",
"toRadians",
"(",
"y2",
")",
")",
")",
";",
"x1",
"=",
"x2",
";",
"y1",
"=",
"y2",
";",
"}",
"return",
"area",
"*",
"radius",
"*",
"radius",
"/",
"2.0",
";",
"}"
] |
Returns the spherical area for a list of coordinates.
[Reference](https://trs-new.jpl.nasa.gov/handle/2014/40409)
Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for
Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion
Laboratory, Pasadena, CA, June 2007
@param {Array<import("./coordinate.js").Coordinate>} coordinates List of coordinates of a linear
ring. If the ring is oriented clockwise, the area will be positive,
otherwise it will be negative.
@param {number} radius The sphere radius.
@return {number} Area (in square meters).
|
[
"Returns",
"the",
"spherical",
"area",
"for",
"a",
"list",
"of",
"coordinates",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/sphere.js#L153-L168
|
train
|
openlayers/openlayers
|
examples/wms-custom-proj.js
|
DECtoSEX
|
function DECtoSEX(angle) {
// Extract DMS
const deg = parseInt(angle, 10);
const min = parseInt((angle - deg) * 60, 10);
const sec = (((angle - deg) * 60) - min) * 60;
// Result in degrees sex (dd.mmss)
return deg + min / 100 + sec / 10000;
}
|
javascript
|
function DECtoSEX(angle) {
// Extract DMS
const deg = parseInt(angle, 10);
const min = parseInt((angle - deg) * 60, 10);
const sec = (((angle - deg) * 60) - min) * 60;
// Result in degrees sex (dd.mmss)
return deg + min / 100 + sec / 10000;
}
|
[
"function",
"DECtoSEX",
"(",
"angle",
")",
"{",
"const",
"deg",
"=",
"parseInt",
"(",
"angle",
",",
"10",
")",
";",
"const",
"min",
"=",
"parseInt",
"(",
"(",
"angle",
"-",
"deg",
")",
"*",
"60",
",",
"10",
")",
";",
"const",
"sec",
"=",
"(",
"(",
"(",
"angle",
"-",
"deg",
")",
"*",
"60",
")",
"-",
"min",
")",
"*",
"60",
";",
"return",
"deg",
"+",
"min",
"/",
"100",
"+",
"sec",
"/",
"10000",
";",
"}"
] |
Convert DEC angle to SEX DMS
|
[
"Convert",
"DEC",
"angle",
"to",
"SEX",
"DMS"
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/wms-custom-proj.js#L193-L203
|
train
|
openlayers/openlayers
|
examples/wms-custom-proj.js
|
DEGtoSEC
|
function DEGtoSEC(angle) {
// Extract DMS
const deg = parseInt(angle, 10);
let min = parseInt((angle - deg) * 100, 10);
let sec = (((angle - deg) * 100) - min) * 100;
// Avoid rounding problems with seconds=0
const parts = String(angle).split('.');
if (parts.length == 2 && parts[1].length == 2) {
min = Number(parts[1]);
sec = 0;
}
// Result in degrees sex (dd.mmss)
return sec + min * 60 + deg * 3600;
}
|
javascript
|
function DEGtoSEC(angle) {
// Extract DMS
const deg = parseInt(angle, 10);
let min = parseInt((angle - deg) * 100, 10);
let sec = (((angle - deg) * 100) - min) * 100;
// Avoid rounding problems with seconds=0
const parts = String(angle).split('.');
if (parts.length == 2 && parts[1].length == 2) {
min = Number(parts[1]);
sec = 0;
}
// Result in degrees sex (dd.mmss)
return sec + min * 60 + deg * 3600;
}
|
[
"function",
"DEGtoSEC",
"(",
"angle",
")",
"{",
"const",
"deg",
"=",
"parseInt",
"(",
"angle",
",",
"10",
")",
";",
"let",
"min",
"=",
"parseInt",
"(",
"(",
"angle",
"-",
"deg",
")",
"*",
"100",
",",
"10",
")",
";",
"let",
"sec",
"=",
"(",
"(",
"(",
"angle",
"-",
"deg",
")",
"*",
"100",
")",
"-",
"min",
")",
"*",
"100",
";",
"const",
"parts",
"=",
"String",
"(",
"angle",
")",
".",
"split",
"(",
"'.'",
")",
";",
"if",
"(",
"parts",
".",
"length",
"==",
"2",
"&&",
"parts",
"[",
"1",
"]",
".",
"length",
"==",
"2",
")",
"{",
"min",
"=",
"Number",
"(",
"parts",
"[",
"1",
"]",
")",
";",
"sec",
"=",
"0",
";",
"}",
"return",
"sec",
"+",
"min",
"*",
"60",
"+",
"deg",
"*",
"3600",
";",
"}"
] |
Convert Degrees angle to seconds
|
[
"Convert",
"Degrees",
"angle",
"to",
"seconds"
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/wms-custom-proj.js#L206-L223
|
train
|
openlayers/openlayers
|
src/ol/events.js
|
getListenerMap
|
function getListenerMap(target, opt_create) {
let listenerMap = target.ol_lm;
if (!listenerMap && opt_create) {
listenerMap = target.ol_lm = {};
}
return listenerMap;
}
|
javascript
|
function getListenerMap(target, opt_create) {
let listenerMap = target.ol_lm;
if (!listenerMap && opt_create) {
listenerMap = target.ol_lm = {};
}
return listenerMap;
}
|
[
"function",
"getListenerMap",
"(",
"target",
",",
"opt_create",
")",
"{",
"let",
"listenerMap",
"=",
"target",
".",
"ol_lm",
";",
"if",
"(",
"!",
"listenerMap",
"&&",
"opt_create",
")",
"{",
"listenerMap",
"=",
"target",
".",
"ol_lm",
"=",
"{",
"}",
";",
"}",
"return",
"listenerMap",
";",
"}"
] |
Get the lookup of listeners.
@param {Object} target Target.
@param {boolean=} opt_create If a map should be created if it doesn't exist.
@return {!Object<string, Array<EventsKey>>} Map of
listeners by event type.
|
[
"Get",
"the",
"lookup",
"of",
"listeners",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/events.js#L93-L99
|
train
|
openlayers/openlayers
|
src/ol/events.js
|
removeListeners
|
function removeListeners(target, type) {
const listeners = getListeners(target, type);
if (listeners) {
for (let i = 0, ii = listeners.length; i < ii; ++i) {
/** @type {import("./events/Target.js").default} */ (target).
removeEventListener(type, listeners[i].boundListener);
clear(listeners[i]);
}
listeners.length = 0;
const listenerMap = getListenerMap(target);
if (listenerMap) {
delete listenerMap[type];
if (Object.keys(listenerMap).length === 0) {
removeListenerMap(target);
}
}
}
}
|
javascript
|
function removeListeners(target, type) {
const listeners = getListeners(target, type);
if (listeners) {
for (let i = 0, ii = listeners.length; i < ii; ++i) {
/** @type {import("./events/Target.js").default} */ (target).
removeEventListener(type, listeners[i].boundListener);
clear(listeners[i]);
}
listeners.length = 0;
const listenerMap = getListenerMap(target);
if (listenerMap) {
delete listenerMap[type];
if (Object.keys(listenerMap).length === 0) {
removeListenerMap(target);
}
}
}
}
|
[
"function",
"removeListeners",
"(",
"target",
",",
"type",
")",
"{",
"const",
"listeners",
"=",
"getListeners",
"(",
"target",
",",
"type",
")",
";",
"if",
"(",
"listeners",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"ii",
"=",
"listeners",
".",
"length",
";",
"i",
"<",
"ii",
";",
"++",
"i",
")",
"{",
"(",
"target",
")",
".",
"removeEventListener",
"(",
"type",
",",
"listeners",
"[",
"i",
"]",
".",
"boundListener",
")",
";",
"clear",
"(",
"listeners",
"[",
"i",
"]",
")",
";",
"}",
"listeners",
".",
"length",
"=",
"0",
";",
"const",
"listenerMap",
"=",
"getListenerMap",
"(",
"target",
")",
";",
"if",
"(",
"listenerMap",
")",
"{",
"delete",
"listenerMap",
"[",
"type",
"]",
";",
"if",
"(",
"Object",
".",
"keys",
"(",
"listenerMap",
")",
".",
"length",
"===",
"0",
")",
"{",
"removeListenerMap",
"(",
"target",
")",
";",
"}",
"}",
"}",
"}"
] |
Clean up all listener objects of the given type. All properties on the
listener objects will be removed, and if no listeners remain in the listener
map, it will be removed from the target.
@param {import("./events/Target.js").EventTargetLike} target Target.
@param {string} type Type.
|
[
"Clean",
"up",
"all",
"listener",
"objects",
"of",
"the",
"given",
"type",
".",
"All",
"properties",
"on",
"the",
"listener",
"objects",
"will",
"be",
"removed",
"and",
"if",
"no",
"listeners",
"remain",
"in",
"the",
"listener",
"map",
"it",
"will",
"be",
"removed",
"from",
"the",
"target",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/events.js#L118-L135
|
train
|
openlayers/openlayers
|
src/ol/source/Raster.js
|
getImageData
|
function getImageData(layer, frameState, layerState) {
const renderer = layer.getRenderer();
if (!renderer) {
throw new Error('Unsupported layer type: ' + layer);
}
if (!renderer.prepareFrame(frameState, layerState)) {
return null;
}
const width = frameState.size[0];
const height = frameState.size[1];
const element = renderer.renderFrame(frameState, layerState);
if (!(element instanceof HTMLCanvasElement)) {
throw new Error('Unsupported rendered element: ' + element);
}
if (element.width === width && element.height === height) {
const context = element.getContext('2d');
return context.getImageData(0, 0, width, height);
}
if (!sharedContext) {
sharedContext = createCanvasContext2D(width, height);
} else {
const canvas = sharedContext.canvas;
if (canvas.width !== width || canvas.height !== height) {
sharedContext = createCanvasContext2D(width, height);
} else {
sharedContext.clearRect(0, 0, width, height);
}
}
sharedContext.drawImage(element, 0, 0, width, height);
return sharedContext.getImageData(0, 0, width, height);
}
|
javascript
|
function getImageData(layer, frameState, layerState) {
const renderer = layer.getRenderer();
if (!renderer) {
throw new Error('Unsupported layer type: ' + layer);
}
if (!renderer.prepareFrame(frameState, layerState)) {
return null;
}
const width = frameState.size[0];
const height = frameState.size[1];
const element = renderer.renderFrame(frameState, layerState);
if (!(element instanceof HTMLCanvasElement)) {
throw new Error('Unsupported rendered element: ' + element);
}
if (element.width === width && element.height === height) {
const context = element.getContext('2d');
return context.getImageData(0, 0, width, height);
}
if (!sharedContext) {
sharedContext = createCanvasContext2D(width, height);
} else {
const canvas = sharedContext.canvas;
if (canvas.width !== width || canvas.height !== height) {
sharedContext = createCanvasContext2D(width, height);
} else {
sharedContext.clearRect(0, 0, width, height);
}
}
sharedContext.drawImage(element, 0, 0, width, height);
return sharedContext.getImageData(0, 0, width, height);
}
|
[
"function",
"getImageData",
"(",
"layer",
",",
"frameState",
",",
"layerState",
")",
"{",
"const",
"renderer",
"=",
"layer",
".",
"getRenderer",
"(",
")",
";",
"if",
"(",
"!",
"renderer",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unsupported layer type: '",
"+",
"layer",
")",
";",
"}",
"if",
"(",
"!",
"renderer",
".",
"prepareFrame",
"(",
"frameState",
",",
"layerState",
")",
")",
"{",
"return",
"null",
";",
"}",
"const",
"width",
"=",
"frameState",
".",
"size",
"[",
"0",
"]",
";",
"const",
"height",
"=",
"frameState",
".",
"size",
"[",
"1",
"]",
";",
"const",
"element",
"=",
"renderer",
".",
"renderFrame",
"(",
"frameState",
",",
"layerState",
")",
";",
"if",
"(",
"!",
"(",
"element",
"instanceof",
"HTMLCanvasElement",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unsupported rendered element: '",
"+",
"element",
")",
";",
"}",
"if",
"(",
"element",
".",
"width",
"===",
"width",
"&&",
"element",
".",
"height",
"===",
"height",
")",
"{",
"const",
"context",
"=",
"element",
".",
"getContext",
"(",
"'2d'",
")",
";",
"return",
"context",
".",
"getImageData",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
";",
"}",
"if",
"(",
"!",
"sharedContext",
")",
"{",
"sharedContext",
"=",
"createCanvasContext2D",
"(",
"width",
",",
"height",
")",
";",
"}",
"else",
"{",
"const",
"canvas",
"=",
"sharedContext",
".",
"canvas",
";",
"if",
"(",
"canvas",
".",
"width",
"!==",
"width",
"||",
"canvas",
".",
"height",
"!==",
"height",
")",
"{",
"sharedContext",
"=",
"createCanvasContext2D",
"(",
"width",
",",
"height",
")",
";",
"}",
"else",
"{",
"sharedContext",
".",
"clearRect",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
";",
"}",
"}",
"sharedContext",
".",
"drawImage",
"(",
"element",
",",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
";",
"return",
"sharedContext",
".",
"getImageData",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
";",
"}"
] |
Get image data from a layer.
@param {import("../layer/Layer.js").default} layer Layer to render.
@param {import("../PluggableMap.js").FrameState} frameState The frame state.
@param {import("../layer/Layer.js").State} layerState The layer state.
@return {ImageData} The image data.
|
[
"Get",
"image",
"data",
"from",
"a",
"layer",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/source/Raster.js#L436-L468
|
train
|
openlayers/openlayers
|
src/ol/source/Raster.js
|
createLayers
|
function createLayers(sources) {
const len = sources.length;
const layers = new Array(len);
for (let i = 0; i < len; ++i) {
layers[i] = createLayer(sources[i]);
}
return layers;
}
|
javascript
|
function createLayers(sources) {
const len = sources.length;
const layers = new Array(len);
for (let i = 0; i < len; ++i) {
layers[i] = createLayer(sources[i]);
}
return layers;
}
|
[
"function",
"createLayers",
"(",
"sources",
")",
"{",
"const",
"len",
"=",
"sources",
".",
"length",
";",
"const",
"layers",
"=",
"new",
"Array",
"(",
"len",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"{",
"layers",
"[",
"i",
"]",
"=",
"createLayer",
"(",
"sources",
"[",
"i",
"]",
")",
";",
"}",
"return",
"layers",
";",
"}"
] |
Create layers for all sources.
@param {Array<import("./Source.js").default|import("../layer/Layer.js").default>} sources The sources.
@return {Array<import("../layer/Layer.js").default>} Array of layers.
|
[
"Create",
"layers",
"for",
"all",
"sources",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/source/Raster.js#L488-L495
|
train
|
openlayers/openlayers
|
src/ol/source/Raster.js
|
createLayer
|
function createLayer(layerOrSource) {
// @type {import("../layer/Layer.js").default}
let layer;
if (layerOrSource instanceof Source) {
if (layerOrSource instanceof TileSource) {
layer = new TileLayer({source: layerOrSource});
} else if (layerOrSource instanceof ImageSource) {
layer = new ImageLayer({source: layerOrSource});
}
} else {
layer = layerOrSource;
}
return layer;
}
|
javascript
|
function createLayer(layerOrSource) {
// @type {import("../layer/Layer.js").default}
let layer;
if (layerOrSource instanceof Source) {
if (layerOrSource instanceof TileSource) {
layer = new TileLayer({source: layerOrSource});
} else if (layerOrSource instanceof ImageSource) {
layer = new ImageLayer({source: layerOrSource});
}
} else {
layer = layerOrSource;
}
return layer;
}
|
[
"function",
"createLayer",
"(",
"layerOrSource",
")",
"{",
"let",
"layer",
";",
"if",
"(",
"layerOrSource",
"instanceof",
"Source",
")",
"{",
"if",
"(",
"layerOrSource",
"instanceof",
"TileSource",
")",
"{",
"layer",
"=",
"new",
"TileLayer",
"(",
"{",
"source",
":",
"layerOrSource",
"}",
")",
";",
"}",
"else",
"if",
"(",
"layerOrSource",
"instanceof",
"ImageSource",
")",
"{",
"layer",
"=",
"new",
"ImageLayer",
"(",
"{",
"source",
":",
"layerOrSource",
"}",
")",
";",
"}",
"}",
"else",
"{",
"layer",
"=",
"layerOrSource",
";",
"}",
"return",
"layer",
";",
"}"
] |
Create a layer for the provided source.
@param {import("./Source.js").default|import("../layer/Layer.js").default} layerOrSource The layer or source.
@return {import("../layer/Layer.js").default} The layer.
|
[
"Create",
"a",
"layer",
"for",
"the",
"provided",
"source",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/source/Raster.js#L503-L516
|
train
|
openlayers/openlayers
|
src/ol/render/canvas/ExecutorGroup.js
|
fillCircleArrayRowToMiddle
|
function fillCircleArrayRowToMiddle(array, x, y) {
let i;
const radius = Math.floor(array.length / 2);
if (x >= radius) {
for (i = radius; i < x; i++) {
array[i][y] = true;
}
} else if (x < radius) {
for (i = x + 1; i < radius; i++) {
array[i][y] = true;
}
}
}
|
javascript
|
function fillCircleArrayRowToMiddle(array, x, y) {
let i;
const radius = Math.floor(array.length / 2);
if (x >= radius) {
for (i = radius; i < x; i++) {
array[i][y] = true;
}
} else if (x < radius) {
for (i = x + 1; i < radius; i++) {
array[i][y] = true;
}
}
}
|
[
"function",
"fillCircleArrayRowToMiddle",
"(",
"array",
",",
"x",
",",
"y",
")",
"{",
"let",
"i",
";",
"const",
"radius",
"=",
"Math",
".",
"floor",
"(",
"array",
".",
"length",
"/",
"2",
")",
";",
"if",
"(",
"x",
">=",
"radius",
")",
"{",
"for",
"(",
"i",
"=",
"radius",
";",
"i",
"<",
"x",
";",
"i",
"++",
")",
"{",
"array",
"[",
"i",
"]",
"[",
"y",
"]",
"=",
"true",
";",
"}",
"}",
"else",
"if",
"(",
"x",
"<",
"radius",
")",
"{",
"for",
"(",
"i",
"=",
"x",
"+",
"1",
";",
"i",
"<",
"radius",
";",
"i",
"++",
")",
"{",
"array",
"[",
"i",
"]",
"[",
"y",
"]",
"=",
"true",
";",
"}",
"}",
"}"
] |
This method fills a row in the array from the given coordinate to the
middle with `true`.
@param {Array<Array<(boolean|undefined)>>} array The array that will be altered.
@param {number} x X coordinate.
@param {number} y Y coordinate.
|
[
"This",
"method",
"fills",
"a",
"row",
"in",
"the",
"array",
"from",
"the",
"given",
"coordinate",
"to",
"the",
"middle",
"with",
"true",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/render/canvas/ExecutorGroup.js#L361-L373
|
train
|
openlayers/openlayers
|
src/ol/format/TopoJSON.js
|
concatenateArcs
|
function concatenateArcs(indices, arcs) {
/** @type {Array<import("../coordinate.js").Coordinate>} */
const coordinates = [];
let index, arc;
for (let i = 0, ii = indices.length; i < ii; ++i) {
index = indices[i];
if (i > 0) {
// splicing together arcs, discard last point
coordinates.pop();
}
if (index >= 0) {
// forward arc
arc = arcs[index];
} else {
// reverse arc
arc = arcs[~index].slice().reverse();
}
coordinates.push.apply(coordinates, arc);
}
// provide fresh copies of coordinate arrays
for (let j = 0, jj = coordinates.length; j < jj; ++j) {
coordinates[j] = coordinates[j].slice();
}
return coordinates;
}
|
javascript
|
function concatenateArcs(indices, arcs) {
/** @type {Array<import("../coordinate.js").Coordinate>} */
const coordinates = [];
let index, arc;
for (let i = 0, ii = indices.length; i < ii; ++i) {
index = indices[i];
if (i > 0) {
// splicing together arcs, discard last point
coordinates.pop();
}
if (index >= 0) {
// forward arc
arc = arcs[index];
} else {
// reverse arc
arc = arcs[~index].slice().reverse();
}
coordinates.push.apply(coordinates, arc);
}
// provide fresh copies of coordinate arrays
for (let j = 0, jj = coordinates.length; j < jj; ++j) {
coordinates[j] = coordinates[j].slice();
}
return coordinates;
}
|
[
"function",
"concatenateArcs",
"(",
"indices",
",",
"arcs",
")",
"{",
"const",
"coordinates",
"=",
"[",
"]",
";",
"let",
"index",
",",
"arc",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"ii",
"=",
"indices",
".",
"length",
";",
"i",
"<",
"ii",
";",
"++",
"i",
")",
"{",
"index",
"=",
"indices",
"[",
"i",
"]",
";",
"if",
"(",
"i",
">",
"0",
")",
"{",
"coordinates",
".",
"pop",
"(",
")",
";",
"}",
"if",
"(",
"index",
">=",
"0",
")",
"{",
"arc",
"=",
"arcs",
"[",
"index",
"]",
";",
"}",
"else",
"{",
"arc",
"=",
"arcs",
"[",
"~",
"index",
"]",
".",
"slice",
"(",
")",
".",
"reverse",
"(",
")",
";",
"}",
"coordinates",
".",
"push",
".",
"apply",
"(",
"coordinates",
",",
"arc",
")",
";",
"}",
"for",
"(",
"let",
"j",
"=",
"0",
",",
"jj",
"=",
"coordinates",
".",
"length",
";",
"j",
"<",
"jj",
";",
"++",
"j",
")",
"{",
"coordinates",
"[",
"j",
"]",
"=",
"coordinates",
"[",
"j",
"]",
".",
"slice",
"(",
")",
";",
"}",
"return",
"coordinates",
";",
"}"
] |
Concatenate arcs into a coordinate array.
@param {Array<number>} indices Indices of arcs to concatenate. Negative
values indicate arcs need to be reversed.
@param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs (already
transformed).
@return {Array<import("../coordinate.js").Coordinate>} Coordinates array.
|
[
"Concatenate",
"arcs",
"into",
"a",
"coordinate",
"array",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L162-L186
|
train
|
openlayers/openlayers
|
src/ol/format/TopoJSON.js
|
readPointGeometry
|
function readPointGeometry(object, scale, translate) {
const coordinates = object['coordinates'];
if (scale && translate) {
transformVertex(coordinates, scale, translate);
}
return new Point(coordinates);
}
|
javascript
|
function readPointGeometry(object, scale, translate) {
const coordinates = object['coordinates'];
if (scale && translate) {
transformVertex(coordinates, scale, translate);
}
return new Point(coordinates);
}
|
[
"function",
"readPointGeometry",
"(",
"object",
",",
"scale",
",",
"translate",
")",
"{",
"const",
"coordinates",
"=",
"object",
"[",
"'coordinates'",
"]",
";",
"if",
"(",
"scale",
"&&",
"translate",
")",
"{",
"transformVertex",
"(",
"coordinates",
",",
"scale",
",",
"translate",
")",
";",
"}",
"return",
"new",
"Point",
"(",
"coordinates",
")",
";",
"}"
] |
Create a point from a TopoJSON geometry object.
@param {TopoJSONPoint} object TopoJSON object.
@param {Array<number>} scale Scale for each dimension.
@param {Array<number>} translate Translation for each dimension.
@return {Point} Geometry.
|
[
"Create",
"a",
"point",
"from",
"a",
"TopoJSON",
"geometry",
"object",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L197-L203
|
train
|
openlayers/openlayers
|
src/ol/format/TopoJSON.js
|
readMultiPointGeometry
|
function readMultiPointGeometry(object, scale, translate) {
const coordinates = object['coordinates'];
if (scale && translate) {
for (let i = 0, ii = coordinates.length; i < ii; ++i) {
transformVertex(coordinates[i], scale, translate);
}
}
return new MultiPoint(coordinates);
}
|
javascript
|
function readMultiPointGeometry(object, scale, translate) {
const coordinates = object['coordinates'];
if (scale && translate) {
for (let i = 0, ii = coordinates.length; i < ii; ++i) {
transformVertex(coordinates[i], scale, translate);
}
}
return new MultiPoint(coordinates);
}
|
[
"function",
"readMultiPointGeometry",
"(",
"object",
",",
"scale",
",",
"translate",
")",
"{",
"const",
"coordinates",
"=",
"object",
"[",
"'coordinates'",
"]",
";",
"if",
"(",
"scale",
"&&",
"translate",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"ii",
"=",
"coordinates",
".",
"length",
";",
"i",
"<",
"ii",
";",
"++",
"i",
")",
"{",
"transformVertex",
"(",
"coordinates",
"[",
"i",
"]",
",",
"scale",
",",
"translate",
")",
";",
"}",
"}",
"return",
"new",
"MultiPoint",
"(",
"coordinates",
")",
";",
"}"
] |
Create a multi-point from a TopoJSON geometry object.
@param {TopoJSONMultiPoint} object TopoJSON object.
@param {Array<number>} scale Scale for each dimension.
@param {Array<number>} translate Translation for each dimension.
@return {MultiPoint} Geometry.
|
[
"Create",
"a",
"multi",
"-",
"point",
"from",
"a",
"TopoJSON",
"geometry",
"object",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L214-L222
|
train
|
openlayers/openlayers
|
src/ol/format/TopoJSON.js
|
readMultiLineStringGeometry
|
function readMultiLineStringGeometry(object, arcs) {
const coordinates = [];
for (let i = 0, ii = object['arcs'].length; i < ii; ++i) {
coordinates[i] = concatenateArcs(object['arcs'][i], arcs);
}
return new MultiLineString(coordinates);
}
|
javascript
|
function readMultiLineStringGeometry(object, arcs) {
const coordinates = [];
for (let i = 0, ii = object['arcs'].length; i < ii; ++i) {
coordinates[i] = concatenateArcs(object['arcs'][i], arcs);
}
return new MultiLineString(coordinates);
}
|
[
"function",
"readMultiLineStringGeometry",
"(",
"object",
",",
"arcs",
")",
"{",
"const",
"coordinates",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"ii",
"=",
"object",
"[",
"'arcs'",
"]",
".",
"length",
";",
"i",
"<",
"ii",
";",
"++",
"i",
")",
"{",
"coordinates",
"[",
"i",
"]",
"=",
"concatenateArcs",
"(",
"object",
"[",
"'arcs'",
"]",
"[",
"i",
"]",
",",
"arcs",
")",
";",
"}",
"return",
"new",
"MultiLineString",
"(",
"coordinates",
")",
";",
"}"
] |
Create a multi-linestring from a TopoJSON geometry object.
@param {TopoJSONMultiLineString} object TopoJSON object.
@param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs.
@return {MultiLineString} Geometry.
|
[
"Create",
"a",
"multi",
"-",
"linestring",
"from",
"a",
"TopoJSON",
"geometry",
"object",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L245-L251
|
train
|
openlayers/openlayers
|
src/ol/format/TopoJSON.js
|
readPolygonGeometry
|
function readPolygonGeometry(object, arcs) {
const coordinates = [];
for (let i = 0, ii = object['arcs'].length; i < ii; ++i) {
coordinates[i] = concatenateArcs(object['arcs'][i], arcs);
}
return new Polygon(coordinates);
}
|
javascript
|
function readPolygonGeometry(object, arcs) {
const coordinates = [];
for (let i = 0, ii = object['arcs'].length; i < ii; ++i) {
coordinates[i] = concatenateArcs(object['arcs'][i], arcs);
}
return new Polygon(coordinates);
}
|
[
"function",
"readPolygonGeometry",
"(",
"object",
",",
"arcs",
")",
"{",
"const",
"coordinates",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"ii",
"=",
"object",
"[",
"'arcs'",
"]",
".",
"length",
";",
"i",
"<",
"ii",
";",
"++",
"i",
")",
"{",
"coordinates",
"[",
"i",
"]",
"=",
"concatenateArcs",
"(",
"object",
"[",
"'arcs'",
"]",
"[",
"i",
"]",
",",
"arcs",
")",
";",
"}",
"return",
"new",
"Polygon",
"(",
"coordinates",
")",
";",
"}"
] |
Create a polygon from a TopoJSON geometry object.
@param {TopoJSONPolygon} object TopoJSON object.
@param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs.
@return {Polygon} Geometry.
|
[
"Create",
"a",
"polygon",
"from",
"a",
"TopoJSON",
"geometry",
"object",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L261-L267
|
train
|
openlayers/openlayers
|
src/ol/format/TopoJSON.js
|
readMultiPolygonGeometry
|
function readMultiPolygonGeometry(object, arcs) {
const coordinates = [];
for (let i = 0, ii = object['arcs'].length; i < ii; ++i) {
// for each polygon
const polyArray = object['arcs'][i];
const ringCoords = [];
for (let j = 0, jj = polyArray.length; j < jj; ++j) {
// for each ring
ringCoords[j] = concatenateArcs(polyArray[j], arcs);
}
coordinates[i] = ringCoords;
}
return new MultiPolygon(coordinates);
}
|
javascript
|
function readMultiPolygonGeometry(object, arcs) {
const coordinates = [];
for (let i = 0, ii = object['arcs'].length; i < ii; ++i) {
// for each polygon
const polyArray = object['arcs'][i];
const ringCoords = [];
for (let j = 0, jj = polyArray.length; j < jj; ++j) {
// for each ring
ringCoords[j] = concatenateArcs(polyArray[j], arcs);
}
coordinates[i] = ringCoords;
}
return new MultiPolygon(coordinates);
}
|
[
"function",
"readMultiPolygonGeometry",
"(",
"object",
",",
"arcs",
")",
"{",
"const",
"coordinates",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"ii",
"=",
"object",
"[",
"'arcs'",
"]",
".",
"length",
";",
"i",
"<",
"ii",
";",
"++",
"i",
")",
"{",
"const",
"polyArray",
"=",
"object",
"[",
"'arcs'",
"]",
"[",
"i",
"]",
";",
"const",
"ringCoords",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"j",
"=",
"0",
",",
"jj",
"=",
"polyArray",
".",
"length",
";",
"j",
"<",
"jj",
";",
"++",
"j",
")",
"{",
"ringCoords",
"[",
"j",
"]",
"=",
"concatenateArcs",
"(",
"polyArray",
"[",
"j",
"]",
",",
"arcs",
")",
";",
"}",
"coordinates",
"[",
"i",
"]",
"=",
"ringCoords",
";",
"}",
"return",
"new",
"MultiPolygon",
"(",
"coordinates",
")",
";",
"}"
] |
Create a multi-polygon from a TopoJSON geometry object.
@param {TopoJSONMultiPolygon} object TopoJSON object.
@param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs.
@return {MultiPolygon} Geometry.
|
[
"Create",
"a",
"multi",
"-",
"polygon",
"from",
"a",
"TopoJSON",
"geometry",
"object",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L277-L290
|
train
|
openlayers/openlayers
|
src/ol/format/TopoJSON.js
|
readFeaturesFromGeometryCollection
|
function readFeaturesFromGeometryCollection(collection, arcs, scale, translate, property, name, opt_options) {
const geometries = collection['geometries'];
const features = [];
for (let i = 0, ii = geometries.length; i < ii; ++i) {
features[i] = readFeatureFromGeometry(
geometries[i], arcs, scale, translate, property, name, opt_options);
}
return features;
}
|
javascript
|
function readFeaturesFromGeometryCollection(collection, arcs, scale, translate, property, name, opt_options) {
const geometries = collection['geometries'];
const features = [];
for (let i = 0, ii = geometries.length; i < ii; ++i) {
features[i] = readFeatureFromGeometry(
geometries[i], arcs, scale, translate, property, name, opt_options);
}
return features;
}
|
[
"function",
"readFeaturesFromGeometryCollection",
"(",
"collection",
",",
"arcs",
",",
"scale",
",",
"translate",
",",
"property",
",",
"name",
",",
"opt_options",
")",
"{",
"const",
"geometries",
"=",
"collection",
"[",
"'geometries'",
"]",
";",
"const",
"features",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"ii",
"=",
"geometries",
".",
"length",
";",
"i",
"<",
"ii",
";",
"++",
"i",
")",
"{",
"features",
"[",
"i",
"]",
"=",
"readFeatureFromGeometry",
"(",
"geometries",
"[",
"i",
"]",
",",
"arcs",
",",
"scale",
",",
"translate",
",",
"property",
",",
"name",
",",
"opt_options",
")",
";",
"}",
"return",
"features",
";",
"}"
] |
Create features from a TopoJSON GeometryCollection object.
@param {TopoJSONGeometryCollection} collection TopoJSON Geometry
object.
@param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs.
@param {Array<number>} scale Scale for each dimension.
@param {Array<number>} translate Translation for each dimension.
@param {string|undefined} property Property to set the `GeometryCollection`'s parent
object to.
@param {string} name Name of the `Topology`'s child object.
@param {import("./Feature.js").ReadOptions=} opt_options Read options.
@return {Array<Feature>} Array of features.
|
[
"Create",
"features",
"from",
"a",
"TopoJSON",
"GeometryCollection",
"object",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L307-L315
|
train
|
openlayers/openlayers
|
src/ol/format/TopoJSON.js
|
readFeatureFromGeometry
|
function readFeatureFromGeometry(object, arcs, scale, translate, property, name, opt_options) {
let geometry;
const type = object.type;
const geometryReader = GEOMETRY_READERS[type];
if ((type === 'Point') || (type === 'MultiPoint')) {
geometry = geometryReader(object, scale, translate);
} else {
geometry = geometryReader(object, arcs);
}
const feature = new Feature();
feature.setGeometry(transformGeometryWithOptions(geometry, false, opt_options));
if (object.id !== undefined) {
feature.setId(object.id);
}
let properties = object.properties;
if (property) {
if (!properties) {
properties = {};
}
properties[property] = name;
}
if (properties) {
feature.setProperties(properties, true);
}
return feature;
}
|
javascript
|
function readFeatureFromGeometry(object, arcs, scale, translate, property, name, opt_options) {
let geometry;
const type = object.type;
const geometryReader = GEOMETRY_READERS[type];
if ((type === 'Point') || (type === 'MultiPoint')) {
geometry = geometryReader(object, scale, translate);
} else {
geometry = geometryReader(object, arcs);
}
const feature = new Feature();
feature.setGeometry(transformGeometryWithOptions(geometry, false, opt_options));
if (object.id !== undefined) {
feature.setId(object.id);
}
let properties = object.properties;
if (property) {
if (!properties) {
properties = {};
}
properties[property] = name;
}
if (properties) {
feature.setProperties(properties, true);
}
return feature;
}
|
[
"function",
"readFeatureFromGeometry",
"(",
"object",
",",
"arcs",
",",
"scale",
",",
"translate",
",",
"property",
",",
"name",
",",
"opt_options",
")",
"{",
"let",
"geometry",
";",
"const",
"type",
"=",
"object",
".",
"type",
";",
"const",
"geometryReader",
"=",
"GEOMETRY_READERS",
"[",
"type",
"]",
";",
"if",
"(",
"(",
"type",
"===",
"'Point'",
")",
"||",
"(",
"type",
"===",
"'MultiPoint'",
")",
")",
"{",
"geometry",
"=",
"geometryReader",
"(",
"object",
",",
"scale",
",",
"translate",
")",
";",
"}",
"else",
"{",
"geometry",
"=",
"geometryReader",
"(",
"object",
",",
"arcs",
")",
";",
"}",
"const",
"feature",
"=",
"new",
"Feature",
"(",
")",
";",
"feature",
".",
"setGeometry",
"(",
"transformGeometryWithOptions",
"(",
"geometry",
",",
"false",
",",
"opt_options",
")",
")",
";",
"if",
"(",
"object",
".",
"id",
"!==",
"undefined",
")",
"{",
"feature",
".",
"setId",
"(",
"object",
".",
"id",
")",
";",
"}",
"let",
"properties",
"=",
"object",
".",
"properties",
";",
"if",
"(",
"property",
")",
"{",
"if",
"(",
"!",
"properties",
")",
"{",
"properties",
"=",
"{",
"}",
";",
"}",
"properties",
"[",
"property",
"]",
"=",
"name",
";",
"}",
"if",
"(",
"properties",
")",
"{",
"feature",
".",
"setProperties",
"(",
"properties",
",",
"true",
")",
";",
"}",
"return",
"feature",
";",
"}"
] |
Create a feature from a TopoJSON geometry object.
@param {TopoJSONGeometry} object TopoJSON geometry object.
@param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs.
@param {Array<number>} scale Scale for each dimension.
@param {Array<number>} translate Translation for each dimension.
@param {string|undefined} property Property to set the `GeometryCollection`'s parent
object to.
@param {string} name Name of the `Topology`'s child object.
@param {import("./Feature.js").ReadOptions=} opt_options Read options.
@return {Feature} Feature.
|
[
"Create",
"a",
"feature",
"from",
"a",
"TopoJSON",
"geometry",
"object",
"."
] |
f366eaea522388fb575b11010e69d309164baca7
|
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L331-L356
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.