code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
nodist.prototype.setGlobal = function setGlobal(versionSpec, cb){
var globalFile = this.getPathToGlobalVersion();
fs.writeFile(globalFile, versionSpec, function(er) {
if(er){
return cb(new Error(
'Could not set version ' + versionSpec + ' (' + er.message + ')'
));
}
cb();
});
}; | Sets the global node version
@param {string} version
@param {function} cb accepting (err) | setGlobal ( versionSpec , cb ) | javascript | nodists/nodist | lib/nodist.js | https://github.com/nodists/nodist/blob/master/lib/nodist.js | MIT |
nodist.prototype.getGlobal = function getGlobal(cb){
var globalFile = this.getPathToGlobalVersion();
fs.readFile(globalFile, function(er, version){
if(er) return cb(er);
cb(null, version.toString().trim(), cb);
});
}; | Gets the global node version
@param {function} cb a callback accepting (err) | getGlobal ( cb ) | javascript | nodists/nodist | lib/nodist.js | https://github.com/nodists/nodist/blob/master/lib/nodist.js | MIT |
nodist.prototype.setLocal = function setLocal(versionSpec, cb) {
fs.writeFile('./.node-version', versionSpec, function(er){
if(er){
return cb(new Error(
'Could not set version ' + versionSpec + ' (' + er.message + ')'
));
}
cb(null, process.cwd() + '\\.node-version');
});
}; | Sets the local node version
@param {string} version
@param {function} cb function accepting (err) | setLocal ( versionSpec , cb ) | javascript | nodists/nodist | lib/nodist.js | https://github.com/nodists/nodist/blob/master/lib/nodist.js | MIT |
nodist.prototype.getLocal = function getLocal(cb){
var dir = process.cwd();
var dirArray = dir.split('\\');
//NOTE: this function is recursive and could loop!!
function search(){
if(dirArray.length === 0) return cb();
dir = dirArray.join('\\');
var file = dir + '\\.node-version';
fs.readFile(file, function(er, version){
if(er){
dirArray.pop();
return search();
}
cb(null, version.toString().trim(), file);
});
}
search();
}; | Gets the local node version
@param {function} cb callback accepting (err, version) | getLocal ( cb ) | javascript | nodists/nodist | lib/nodist.js | https://github.com/nodists/nodist/blob/master/lib/nodist.js | MIT |
nodist.prototype.getEnv = function getEnv(cb) {
if(!this.envVersion) return cb();
cb(null, this.envVersion);
}; | Gets the environmental node version
@param {function} cb a callback accepting (err, env)
@return {*} nothing | getEnv ( cb ) | javascript | nodists/nodist | lib/nodist.js | https://github.com/nodists/nodist/blob/master/lib/nodist.js | MIT |
nodist.prototype.emulate = function emulate(version, args, cb) {
var that = this;
this.install(version, function(err) {
if(err) return cb(err);
var node = child_process.spawn(that.getPathToExe(version), args, {
stdio: 'inherit',
cwd: path.resolve('.')
});
node.on('exit', cb.bind(that, null));// onexit: cb(err=null, code)
});
}; | Emulates the passed node version with args
@param {string} version
@param {object} args
@param {function} cb A callback with (error) Will be called on error or exit. | emulate ( version , args , cb ) | javascript | nodists/nodist | lib/nodist.js | https://github.com/nodists/nodist/blob/master/lib/nodist.js | MIT |
function npmist(nodist, envVersion) {
this.nodist = nodist
this.envVersion = envVersion
//define where we store our npms
this.repoPath = path.resolve(path.join(this.nodist.nodistDir,'npmv'));
} | npmist /nopmist/
This poorly named module manages npm versions | npmist ( nodist , envVersion ) | javascript | nodists/nodist | lib/npm.js | https://github.com/nodists/nodist/blob/master/lib/npm.js | MIT |
NPMIST.listAvailable = function(){
return Promise.all([
octokit.paginate(octokit.rest.repos.listReleases, {
owner: 'npm',
repo: 'npm',
per_page: 100
}, function(response) {
return response.data.map(function(release) { return release.tag_name; });
}),
octokit.paginate(octokit.rest.repos.listReleases, {
owner: 'npm',
repo: 'cli',
per_page: 100
}, function(response) {
return response.data.map(function(release) { return release.tag_name; });
})
])
.then(([npm, cli]) => {
// The npm project has two kinds of releases: releases of npm,
// and releases of other utility libraries.
// Ignore the releases of libraries. They are named "library-version",
// while core npm releases are named just "version".
cli = cli.filter(release => versionRegex.test(release));
return npm.concat(cli);
});
}; | List available NPM versions
@return {string} | NPMIST.listAvailable ( ) | javascript | nodists/nodist | lib/npm.js | https://github.com/nodists/nodist/blob/master/lib/npm.js | MIT |
NPMIST.listInstalled = function listInstalled(cb) {
//return from cache if we can
if(this.installedCache){
return process.nextTick(() => {
cb(null, this.installedCache);
});
}
fs.readdir(this.repoPath, (err, ls) => {
if(err){
return cb({
message: 'Reading the version directory ' +
this.repoPath + ' failed: ' + err.message
});
}
ls = ls.filter(semver.valid)
ls.sort(function(v1, v2){
if(vermanager.compareable(v1) > vermanager.compareable(v2)){
return 1;
}
else{
return -1;
}
});
//set cache for later
this.installedCache = ls;
return cb(null, ls);
});
}; | List all npm versions installed in this.repoPath
@param {function} cb A callback with (error, arrayOfVersions)
@return {*} nothing | listInstalled ( cb ) | javascript | nodists/nodist | lib/npm.js | https://github.com/nodists/nodist/blob/master/lib/npm.js | MIT |
NPMIST.latestVersion = async function(){
// use list instead of getLatestRelease because there are non npm releases in the cli repo
let releases = [];
let page = 1;
while (releases.length === 0) {
releases = await getNpmReleases(page);
page += 1;
}
return releases.pop();
}; | Get latest NPM version
@return {string} | NPMIST.latestVersion ( ) | javascript | nodists/nodist | lib/npm.js | https://github.com/nodists/nodist/blob/master/lib/npm.js | MIT |
NPMIST.downloadUrl = function(version){
return 'https://codeload.github.com/npm/cli/tar.gz/vVERSION'
.replace('VERSION',version.replace('v',''));
}; | Get a download URL for the version
@param {string} version
@return {string} | NPMIST.downloadUrl ( version ) | javascript | nodists/nodist | lib/npm.js | https://github.com/nodists/nodist/blob/master/lib/npm.js | MIT |
NPMIST.resolveVersion = function(v,done){
if ('latest' === v || !v) {
this.latestVersion()
.then((latest) => {
done(null, latest)
})
return
}
if ('match' === v) {
this.matchingVersion()
.then((version) => {
done(null, version)
})
return
}
this.listAvailable()
.then(function(available){
//try to get a version if its explicit
var version = semver.clean(v);
//support version ranges
if(semver.validRange(v)){
version = semver.maxSatisfying(available,v);
}
if (!version) {
done(new Error('Version spec, "' + v + '", didn\'t match any version'));
return;
}
done(null,version);
})
.catch(function(err){
done(err);
});
}; | Resolve a version from a string
@param {string} v
@param {function} done | NPMIST.resolveVersion ( v , done ) | javascript | nodists/nodist | lib/npm.js | https://github.com/nodists/nodist/blob/master/lib/npm.js | MIT |
NPMIST.remove = function(v, done){
var version = semver.clean(v);
if(!semver.valid(version)) return done(new Error('Invalid version'));
var archivePath = path.resolve(path.join(this.repoPath,version));
//check if this version is already not installed, if so just bail
if(!fs.existsSync(archivePath)){
return done(null,version);
}
//nuke everything for this version
P.all([rimraf(archivePath)])
.then(function(){
done(null,version);
})
.catch(function(err){
done(err);
});
}; | Remove a version of NPM
@param {string} v
@param {function} done
@return {*} | NPMIST.remove ( v , done ) | javascript | nodists/nodist | lib/npm.js | https://github.com/nodists/nodist/blob/master/lib/npm.js | MIT |
NPMIST.install = function(v,done){
debug('install', v)
var version = semver.clean(v);
if(!semver.valid(version)) return done(new Error('Invalid version'));
var zipFile = path.resolve(path.join(this.repoPath,version + '.zip'));
var archivePath = path.resolve(path.join(this.repoPath,version));
//check if this version is already installed, if so just bail
if(fs.existsSync(archivePath)){
debug('install', 'this version is already installed')
return done(null, version)
}
//otherwise install the new version
Promise.resolve()
.then(() => mkdirp(archivePath))
.then(() => {
var downloadLink = NPMIST.downloadUrl(version);
debug('Downloading and extracting NPM from ' + downloadLink);
return new Promise((resolve, reject) => {
buildHelper.downloadFileStream(downloadLink)
.pipe(zlib.createUnzip())
.pipe(tar.x({
cwd: archivePath
, strip: 1
}))
.on('error', reject)
.on('end', resolve)
})
})
.then(() => {
if (semver.gte(version, '8.0.0')) {
debug('Fix symlinks for npm version >= 8');
return buildHelper.resolveLinkedWorkspaces(path.join(archivePath))
.then(fixedLinks => {
debug(`Fixed ${fixedLinks} symlinks for npm node_modules`);
});
}
})
.then(() => {
done(null, version)
})
.catch((err) => {
done(err);
});
}; | Install NPM version
@param {string} v
@param {function} done
@return {*} | NPMIST.install ( v , done ) | javascript | nodists/nodist | lib/npm.js | https://github.com/nodists/nodist/blob/master/lib/npm.js | MIT |
NPMIST.setGlobal = function setGlobal(versionSpec, cb){
var globalFile = this.nodist.nodistDir+'/.npm-version-global';
fs.writeFile(globalFile, versionSpec, function(er) {
if(er){
return cb(new Error(
'Could not set npm version ' + versionSpec + ' (' + er.message + ')'
));
}
cb();
});
}; | Sets the global npm version
@param {string} version
@param {function} cb accepting (err) | setGlobal ( versionSpec , cb ) | javascript | nodists/nodist | lib/npm.js | https://github.com/nodists/nodist/blob/master/lib/npm.js | MIT |
NPMIST.getGlobal = function getGlobal(cb){
var globalFile = this.nodist.nodistDir+'/.npm-version-global';
fs.readFile(globalFile, function(er, version){
if(er) return cb(er);
cb(null, version.toString().trim(), cb);
});
}; | Gets the global npm version
@param {function} cb a callback accepting (err) | getGlobal ( cb ) | javascript | nodists/nodist | lib/npm.js | https://github.com/nodists/nodist/blob/master/lib/npm.js | MIT |
NPMIST.setLocal = function setLocal(versionSpec, cb) {
fs.writeFile('./.npm-version', versionSpec, function(er){
if(er){
return cb(new Error(
'Could not set npm version ' + versionSpec + ' (' + er.message + ')'
));
}
cb(null, process.cwd() + '\\.npm-version');
});
}; | Sets the local npm version
@param {string} version
@param {function} cb function accepting (err) | setLocal ( versionSpec , cb ) | javascript | nodists/nodist | lib/npm.js | https://github.com/nodists/nodist/blob/master/lib/npm.js | MIT |
NPMIST.getLocal = function getLocal(cb){
var dir = process.cwd();
var dirArray = dir.split('\\');
//NOTE: this function is recursive and could loop!!
function search(){
if(dirArray.length === 0) return cb();
dir = dirArray.join('\\');
var file = dir + '\\.npm-version';
fs.readFile(file, function(er, version){
if(er){
dirArray.pop();
return search();
}
cb(null, version.toString().trim(), file);
});
}
search();
}; | Gets the local npm version
@param {function} cb callback accepting (err, version) | getLocal ( cb ) | javascript | nodists/nodist | lib/npm.js | https://github.com/nodists/nodist/blob/master/lib/npm.js | MIT |
NPMIST.getEnv = function getEnv(cb) {
if(!this.envVersion) return cb();
cb(null, this.envVersion);
}; | Gets the environmental npm version
@param {function} cb a callback accepting (err, env)
@return {*} nothing | getEnv ( cb ) | javascript | nodists/nodist | lib/npm.js | https://github.com/nodists/nodist/blob/master/lib/npm.js | MIT |
exports.copyFile = function copyFile(source, target, cb){
var cbCalled = false;
var rd = fs.createReadStream(path.resolve(source));
rd.on('error', function(err){
done(err);
});
var wr = fs.createWriteStream(path.resolve(target));
wr.on('error', function(err){
done(err);
});
wr.on('close', function(){
done();
});
rd.pipe(wr);
function done(err) {
if (!cbCalled) {
cb(err);
cbCalled = true;
}
}
}; | Copy File
@param {string} source
@param {string} target
@param {function} cb | copyFile ( source , target , cb ) | javascript | nodists/nodist | lib/build.js | https://github.com/nodists/nodist/blob/master/lib/build.js | MIT |
exports.downloadFile = function downloadFile(url, dest, cb, loopCount){
dest = path.resolve(dest);
var file = fs.createWriteStream(dest);
var progress = {};
var fileSize = 1;
var req = request({url: url});
req.on('response',function(res){
if(res.statusCode !== 200){
cb(new Error('Failed to read response from ' + url));
} else if(!res.headers['content-length']){
if(!loopCount) loopCount = 0;
if(loopCount < 5){
loopCount++;
debug('build.downloadFile',
'Failed to find content length on ' + url + ' retry ' + loopCount);
return downloadFile(url,dest,cb);
} else {
cb(new Error('Too many redirects looking for content length'));
}
} else {
var fileSize = Math.round(
((+res.headers['content-length']) || 3145728) / 1024
);
progress = new ProgressBar(
path.basename(dest) +
' [:bar] :current/:total KiB :rate/Kbps :percent :etas',
{
complete: '=',
incomplete: ' ',
width: 15,
total: fileSize,
clear: true
}
);
}
});
req.on('data',function(chunk){
if(progress && 'function' === typeof progress.tick)
progress.tick(Math.round(chunk.length / 1024));
});
promisePipe(req,file).then(function(){
progress.update(1,fileSize);
cb();
});
}; | Download file with progress bar
@param {string} url
@param {string} dest
@param {function} cb
@param {number} loopCount only used to prevent redirect loops looking for
content length | downloadFile ( url , dest , cb , loopCount ) | javascript | nodists/nodist | lib/build.js | https://github.com/nodists/nodist/blob/master/lib/build.js | MIT |
exports.resolveLinkedWorkspaces = async function resolveLinkedWorkspaces(dirPath, preferSymlink = true) {
let fixedLinks = 0;
const packageLockJson = JSON.parse(fs.readFileSync(path.join(dirPath, 'package-lock.json')).toString());
await Promise.all(Object.entries(packageLockJson.packages)
.filter(([pkgPath, pkg]) => pkg.link === true)
.map(async ([pkgPath, pkg]) => {
const linkPath = path.join(dirPath, pkgPath);
if (await fs.accessAsync(linkPath, fs.constants.F_OK).then(() => true).catch(() => false)) {
await fs.unlinkAsync(linkPath);
}
let linkCreated = false;
if (preferSymlink) {
const linkTarget = path.join(
...pkgPath.split('/').slice(0, -1).map(() => '..'),
pkg.resolved
);
debug('Create symlink for ', linkPath, 'with target', linkTarget);
try {
await fs.symlinkAsync(linkTarget, linkPath, 'junction');
linkCreated = true;
} catch (e) {
debug('Link ', linkPath, 'could not be created');
}
}
if (!linkCreated) {
const from = path.join(dirPath, pkg.resolved);
debug('Move', from, 'to', linkPath);
await fs.renameAsync(from, linkPath);
}
fixedLinks++;
}));
return fixedLinks;
}; | Npm version >= 18 using symlinks that do not work in windows and have to be fixed
this function replace the broken symlinks with NTFS junction or move the directory if junctions are not supported
@param {string} dirPath
@param {boolean} preferSymlink
@returns {Promise<number>} number of changed links | resolveLinkedWorkspaces ( dirPath , preferSymlink = true ) | javascript | nodists/nodist | lib/build.js | https://github.com/nodists/nodist/blob/master/lib/build.js | MIT |
var execNodist = function execNodist(args, cb){
var stdout = '';
var stderr = '';
var nodistCmd = path.resolve(__dirname + '/../bin/nodist.cmd');
debug('execNodist','executing',nodistCmd,args.join(' '));
var cp = spawn(
nodistCmd,
args,
{
env: {
NODIST_PREFIX: testPath,
NODIST_NODE_MIRROR: n.sourceUrl,
NODIST_IOJS_MIRROR: n.iojsSourceUrl,
HTTP_PROXY: proxy,
DEBUG: process.env.DEBUG
}
}
);
if(process.env.TEST){
cp.stdout.pipe(process.stdout);
cp.stderr.pipe(process.stderr);
}
cp.stdout.on('data',function(chunk){
stdout = stdout + chunk.toString();
});
cp.stderr.on('data',function(chunk){
stderr = stderr + chunk.toString();
});
cp.on('error', function(err){
debug('execNodist', 'exec failed with error', err);
cb(err);
});
cp.on('close', function(code){
var err = null;
debug('execNodist', 'exec completed with', { err, stdout, stderr, code });
cb(err, stdout, stderr, code);
});
}; | Exec Nodist for Testing
@param {Array} args
@param {function} cb | execNodist ( args , cb ) | javascript | nodists/nodist | test/cli-test.js | https://github.com/nodists/nodist/blob/master/test/cli-test.js | MIT |
THREE.Quaternion = function ( x, y, z, w ) {
this._x = x || 0;
this._y = y || 0;
this._z = z || 0;
this._w = ( w !== undefined ) ? w : 1;
}; | @author mikael emtinger / http://gomo.se/
@author alteredq / http://alteredqualia.com/
@author WestLangley / http://github.com/WestLangley
@author bhouston / http://exocortex.com | THREE.Quaternion ( x , y , z , w ) | javascript | brianchirls/Seriously.js | lib/three.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/three.js | MIT |
THREE.Vector2 = function ( x, y ) {
this.x = x || 0;
this.y = y || 0;
}; | @author mrdoob / http://mrdoob.com/
@author philogb / http://blog.thejit.org/
@author egraether / http://egraether.com/
@author zz85 / http://www.lab4games.net/zz85/blog | THREE.Vector2 ( x , y ) | javascript | brianchirls/Seriously.js | lib/three.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/three.js | MIT |
THREE.Vector3 = function ( x, y, z ) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
}; | @author mrdoob / http://mrdoob.com/
@author *kile / http://kile.stravaganza.org/
@author philogb / http://blog.thejit.org/
@author mikael emtinger / http://gomo.se/
@author egraether / http://egraether.com/
@author WestLangley / http://github.com/WestLangley | THREE.Vector3 ( x , y , z ) | javascript | brianchirls/Seriously.js | lib/three.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/three.js | MIT |
THREE.Vector4 = function ( x, y, z, w ) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
this.w = ( w !== undefined ) ? w : 1;
}; | @author supereggbert / http://www.paulbrunt.co.uk/
@author philogb / http://blog.thejit.org/
@author mikael emtinger / http://gomo.se/
@author egraether / http://egraether.com/
@author WestLangley / http://github.com/WestLangley | THREE.Vector4 ( x , y , z , w ) | javascript | brianchirls/Seriously.js | lib/three.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/three.js | MIT |
THREE.Euler = function ( x, y, z, order ) {
this._x = x || 0;
this._y = y || 0;
this._z = z || 0;
this._order = order || THREE.Euler.DefaultOrder;
}; | @author mrdoob / http://mrdoob.com/
@author WestLangley / http://github.com/WestLangley
@author bhouston / http://exocortex.com | THREE.Euler ( x , y , z , order ) | javascript | brianchirls/Seriously.js | lib/three.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/three.js | MIT |
THREE.Line3 = function ( start, end ) {
this.start = ( start !== undefined ) ? start : new THREE.Vector3();
this.end = ( end !== undefined ) ? end : new THREE.Vector3();
}; | @author bhouston / http://exocortex.com | THREE.Line3 ( start , end ) | javascript | brianchirls/Seriously.js | lib/three.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/three.js | MIT |
THREE.Box3 = function ( min, max ) {
this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity );
}; | @author bhouston / http://exocortex.com
@author WestLangley / http://github.com/WestLangley | THREE.Box3 ( min , max ) | javascript | brianchirls/Seriously.js | lib/three.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/three.js | MIT |
THREE.Sphere = function ( center, radius ) {
this.center = ( center !== undefined ) ? center : new THREE.Vector3();
this.radius = ( radius !== undefined ) ? radius : 0;
}; | @author bhouston / http://exocortex.com
@author mrdoob / http://mrdoob.com/ | THREE.Sphere ( center , radius ) | javascript | brianchirls/Seriously.js | lib/three.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/three.js | MIT |
THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
this.planes = [
( p0 !== undefined ) ? p0 : new THREE.Plane(),
( p1 !== undefined ) ? p1 : new THREE.Plane(),
( p2 !== undefined ) ? p2 : new THREE.Plane(),
( p3 !== undefined ) ? p3 : new THREE.Plane(),
( p4 !== undefined ) ? p4 : new THREE.Plane(),
( p5 !== undefined ) ? p5 : new THREE.Plane()
];
}; | @author mrdoob / http://mrdoob.com/
@author alteredq / http://alteredqualia.com/
@author bhouston / http://exocortex.com | THREE.Frustum ( p0 , p1 , p2 , p3 , p4 , p5 ) | javascript | brianchirls/Seriously.js | lib/three.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/three.js | MIT |
THREE.Clock = function ( autoStart ) {
this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
this.startTime = 0;
this.oldTime = 0;
this.elapsedTime = 0;
this.running = false;
}; | @author alteredq / http://alteredqualia.com/ | THREE.Clock ( autoStart ) | javascript | brianchirls/Seriously.js | lib/three.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/three.js | MIT |
THREE.EventDispatcher = function () {} | https://github.com/mrdoob/eventdispatcher.js/ | THREE.EventDispatcher ( ) | javascript | brianchirls/Seriously.js | lib/three.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/three.js | MIT |
THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
this.a = a;
this.b = b;
this.c = c;
this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
this.vertexNormals = normal instanceof Array ? normal : [];
this.color = color instanceof THREE.Color ? color : new THREE.Color();
this.vertexColors = color instanceof Array ? color : [];
this.vertexTangents = [];
this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
}; | @author mrdoob / http://mrdoob.com/
@author alteredq / http://alteredqualia.com/ | THREE.Face3 ( a , b , c , normal , color , materialIndex ) | javascript | brianchirls/Seriously.js | lib/three.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/three.js | MIT |
var log = function(msg) {
if (window.console && window.console.log) {
window.console.log(msg);
}
}; | Wrapped logging function.
@param {string} msg Message to log. | log ( msg ) | javascript | brianchirls/Seriously.js | lib/webgl-debug.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/webgl-debug.js | MIT |
var error = function(msg) {
if (window.console && window.console.error) {
window.console.error(msg);
} else {
log(msg);
}
}; | Wrapped error logging function.
@param {string} msg Message to log. | error ( msg ) | javascript | brianchirls/Seriously.js | lib/webgl-debug.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/webgl-debug.js | MIT |
function init(ctx) {
if (glEnums == null) {
glEnums = { };
for (var propertyName in ctx) {
if (typeof ctx[propertyName] == 'number') {
glEnums[ctx[propertyName]] = propertyName;
}
}
}
} | Initializes this module. Safe to call more than once.
@param {!WebGLRenderingContext} ctx A WebGL context. If
you have more than one context it doesn't matter which one
you pass in, it is only used to pull out constants. | init ( ctx ) | javascript | brianchirls/Seriously.js | lib/webgl-debug.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/webgl-debug.js | MIT |
function checkInit() {
if (glEnums == null) {
throw 'WebGLDebugUtils.init(ctx) not called';
}
} | Checks the utils have been initialized. | checkInit ( ) | javascript | brianchirls/Seriously.js | lib/webgl-debug.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/webgl-debug.js | MIT |
function mightBeEnum(value) {
checkInit();
return (glEnums[value] !== undefined);
} | Returns true or false if value matches any WebGL enum
@param {*} value Value to check if it might be an enum.
@return {boolean} True if value matches one of the WebGL defined enums | mightBeEnum ( value ) | javascript | brianchirls/Seriously.js | lib/webgl-debug.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/webgl-debug.js | MIT |
function glEnumToString(value) {
checkInit();
var name = glEnums[value];
return (name !== undefined) ? ("gl." + name) :
("/*UNKNOWN WebGL ENUM*/ 0x" + value.toString(16) + "");
} | Gets an string version of an WebGL enum.
Example:
var str = WebGLDebugUtil.glEnumToString(ctx.getError());
@param {number} value Value to return an enum for
@return {string} The string version of the enum. | glEnumToString ( value ) | javascript | brianchirls/Seriously.js | lib/webgl-debug.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/webgl-debug.js | MIT |
function glFunctionArgToString(functionName, numArgs, argumentIndex, value) {
var funcInfo = glValidEnumContexts[functionName];
if (funcInfo !== undefined) {
var funcInfo = funcInfo[numArgs];
if (funcInfo !== undefined) {
if (funcInfo[argumentIndex]) {
return glEnumToString(value);
}
}
}
if (value === null) {
return "null";
} else if (value === undefined) {
return "undefined";
} else {
return value.toString();
}
} | Returns the string version of a WebGL argument.
Attempts to convert enum arguments to strings.
@param {string} functionName the name of the WebGL function.
@param {number} numArgs the number of arguments passed to the function.
@param {number} argumentIndx the index of the argument.
@param {*} value The value of the argument.
@return {string} The value as a string. | glFunctionArgToString ( functionName , numArgs , argumentIndex , value ) | javascript | brianchirls/Seriously.js | lib/webgl-debug.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/webgl-debug.js | MIT |
function makeDebugContext(ctx, opt_onErrorFunc, opt_onFunc, opt_err_ctx) {
opt_err_ctx = opt_err_ctx || ctx;
init(ctx);
opt_onErrorFunc = opt_onErrorFunc || function(err, functionName, args) {
// apparently we can't do args.join(",");
var argStr = "";
var numArgs = args.length;
for (var ii = 0; ii < numArgs; ++ii) {
argStr += ((ii == 0) ? '' : ', ') +
glFunctionArgToString(functionName, numArgs, ii, args[ii]);
}
error("WebGL error "+ glEnumToString(err) + " in "+ functionName +
"(" + argStr + ")");
};
// Holds booleans for each GL error so after we get the error ourselves
// we can still return it to the client app.
var glErrorShadow = { };
// Makes a function that calls a WebGL function and then calls getError.
function makeErrorWrapper(ctx, functionName) {
return function() {
if (opt_onFunc) {
opt_onFunc(functionName, arguments);
}
var result = ctx[functionName].apply(ctx, arguments);
var err = opt_err_ctx.getError();
if (err != 0) {
glErrorShadow[err] = true;
opt_onErrorFunc(err, functionName, arguments);
}
return result;
};
}
// Make a an object that has a copy of every property of the WebGL context
// but wraps all functions.
var wrapper = {};
for (var propertyName in ctx) {
if (typeof ctx[propertyName] == 'function') {
if (propertyName != 'getExtension') {
wrapper[propertyName] = makeErrorWrapper(ctx, propertyName);
} else {
var wrapped = makeErrorWrapper(ctx, propertyName);
wrapper[propertyName] = function () {
var result = wrapped.apply(ctx, arguments);
return makeDebugContext(result, opt_onErrorFunc, opt_onFunc, opt_err_ctx);
};
}
} else {
makePropertyWrapper(wrapper, ctx, propertyName);
}
}
// Override the getError function with one that returns our saved results.
wrapper.getError = function() {
for (var err in glErrorShadow) {
if (glErrorShadow.hasOwnProperty(err)) {
if (glErrorShadow[err]) {
glErrorShadow[err] = false;
return err;
}
}
}
return ctx.NO_ERROR;
};
return wrapper;
}
function resetToInitialState(ctx) {
var numAttribs = ctx.getParameter(ctx.MAX_VERTEX_ATTRIBS);
var tmp = ctx.createBuffer();
ctx.bindBuffer(ctx.ARRAY_BUFFER, tmp);
for (var ii = 0; ii < numAttribs; ++ii) {
ctx.disableVertexAttribArray(ii);
ctx.vertexAttribPointer(ii, 4, ctx.FLOAT, false, 0, 0);
ctx.vertexAttrib1f(ii, 0);
}
ctx.deleteBuffer(tmp);
var numTextureUnits = ctx.getParameter(ctx.MAX_TEXTURE_IMAGE_UNITS);
for (var ii = 0; ii < numTextureUnits; ++ii) {
ctx.activeTexture(ctx.TEXTURE0 + ii);
ctx.bindTexture(ctx.TEXTURE_CUBE_MAP, null);
ctx.bindTexture(ctx.TEXTURE_2D, null);
}
ctx.activeTexture(ctx.TEXTURE0);
ctx.useProgram(null);
ctx.bindBuffer(ctx.ARRAY_BUFFER, null);
ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, null);
ctx.bindFramebuffer(ctx.FRAMEBUFFER, null);
ctx.bindRenderbuffer(ctx.RENDERBUFFER, null);
ctx.disable(ctx.BLEND);
ctx.disable(ctx.CULL_FACE);
ctx.disable(ctx.DEPTH_TEST);
ctx.disable(ctx.DITHER);
ctx.disable(ctx.SCISSOR_TEST);
ctx.blendColor(0, 0, 0, 0);
ctx.blendEquation(ctx.FUNC_ADD);
ctx.blendFunc(ctx.ONE, ctx.ZERO);
ctx.clearColor(0, 0, 0, 0);
ctx.clearDepth(1);
ctx.clearStencil(-1);
ctx.colorMask(true, true, true, true);
ctx.cullFace(ctx.BACK);
ctx.depthFunc(ctx.LESS);
ctx.depthMask(true);
ctx.depthRange(0, 1);
ctx.frontFace(ctx.CCW);
ctx.hint(ctx.GENERATE_MIPMAP_HINT, ctx.DONT_CARE);
ctx.lineWidth(1);
ctx.pixelStorei(ctx.PACK_ALIGNMENT, 4);
ctx.pixelStorei(ctx.UNPACK_ALIGNMENT, 4);
ctx.pixelStorei(ctx.UNPACK_FLIP_Y_WEBGL, false);
ctx.pixelStorei(ctx.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
// TODO: Delete this IF.
if (ctx.UNPACK_COLORSPACE_CONVERSION_WEBGL) {
ctx.pixelStorei(ctx.UNPACK_COLORSPACE_CONVERSION_WEBGL, ctx.BROWSER_DEFAULT_WEBGL);
}
ctx.polygonOffset(0, 0);
ctx.sampleCoverage(1, false);
ctx.scissor(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.stencilFunc(ctx.ALWAYS, 0, 0xFFFFFFFF);
ctx.stencilMask(0xFFFFFFFF);
ctx.stencilOp(ctx.KEEP, ctx.KEEP, ctx.KEEP);
ctx.viewport(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.clear(ctx.COLOR_BUFFER_BIT | ctx.DEPTH_BUFFER_BIT | ctx.STENCIL_BUFFER_BIT);
// TODO: This should NOT be needed but Firefox fails with 'hint'
while(ctx.getError());
}
function makeLostContextSimulatingCanvas(canvas) {
var unwrappedContext_;
var wrappedContext_;
var onLost_ = [];
var onRestored_ = [];
var wrappedContext_ = {};
var contextId_ = 1;
var contextLost_ = false;
var resourceId_ = 0;
var resourceDb_ = [];
var numCallsToLoseContext_ = 0;
var numCalls_ = 0;
var canRestore_ = false;
var restoreTimeout_ = 0;
// Holds booleans for each GL error so can simulate errors.
var glErrorShadow_ = { };
canvas.getContext = function(f) {
return function() {
var ctx = f.apply(canvas, arguments);
// Did we get a context and is it a WebGL context?
if (ctx instanceof WebGLRenderingContext) {
if (ctx != unwrappedContext_) {
if (unwrappedContext_) {
throw "got different context"
}
unwrappedContext_ = ctx;
wrappedContext_ = makeLostContextSimulatingContext(unwrappedContext_);
}
return wrappedContext_;
}
return ctx;
}
}(canvas.getContext);
function wrapEvent(listener) {
if (typeof(listener) == "function") {
return listener;
} else {
return function(info) {
listener.handleEvent(info);
}
}
}
var addOnContextLostListener = function(listener) {
onLost_.push(wrapEvent(listener));
};
var addOnContextRestoredListener = function(listener) {
onRestored_.push(wrapEvent(listener));
};
function wrapAddEventListener(canvas) {
var f = canvas.addEventListener;
canvas.addEventListener = function(type, listener, bubble) {
switch (type) {
case 'webglcontextlost':
addOnContextLostListener(listener);
break;
case 'webglcontextrestored':
addOnContextRestoredListener(listener);
break;
default:
f.apply(canvas, arguments);
}
};
}
wrapAddEventListener(canvas);
canvas.loseContext = function() {
if (!contextLost_) {
contextLost_ = true;
numCallsToLoseContext_ = 0;
++contextId_;
while (unwrappedContext_.getError());
clearErrors();
glErrorShadow_[unwrappedContext_.CONTEXT_LOST_WEBGL] = true;
var event = makeWebGLContextEvent("context lost");
var callbacks = onLost_.slice();
setTimeout(function() {
//log("numCallbacks:" + callbacks.length);
for (var ii = 0; ii < callbacks.length; ++ii) {
//log("calling callback:" + ii);
callbacks[ii](event);
}
if (restoreTimeout_ >= 0) {
setTimeout(function() {
canvas.restoreContext();
}, restoreTimeout_);
}
}, 0);
}
};
canvas.restoreContext = function() {
if (contextLost_) {
if (onRestored_.length) {
setTimeout(function() {
if (!canRestore_) {
throw "can not restore. webglcontestlost listener did not call event.preventDefault";
}
freeResources();
resetToInitialState(unwrappedContext_);
contextLost_ = false;
numCalls_ = 0;
canRestore_ = false;
var callbacks = onRestored_.slice();
var event = makeWebGLContextEvent("context restored");
for (var ii = 0; ii < callbacks.length; ++ii) {
callbacks[ii](event);
}
}, 0);
}
}
};
canvas.loseContextInNCalls = function(numCalls) {
if (contextLost_) {
throw "You can not ask a lost contet to be lost";
}
numCallsToLoseContext_ = numCalls_ + numCalls;
};
canvas.getNumCalls = function() {
return numCalls_;
};
canvas.setRestoreTimeout = function(timeout) {
restoreTimeout_ = timeout;
};
function isWebGLObject(obj) {
//return false;
return (obj instanceof WebGLBuffer ||
obj instanceof WebGLFramebuffer ||
obj instanceof WebGLProgram ||
obj instanceof WebGLRenderbuffer ||
obj instanceof WebGLShader ||
obj instanceof WebGLTexture);
}
function checkResources(args) {
for (var ii = 0; ii < args.length; ++ii) {
var arg = args[ii];
if (isWebGLObject(arg)) {
return arg.__webglDebugContextLostId__ == contextId_;
}
}
return true;
}
function clearErrors() {
var k = Object.keys(glErrorShadow_);
for (var ii = 0; ii < k.length; ++ii) {
delete glErrorShadow_[k];
}
}
function loseContextIfTime() {
++numCalls_;
if (!contextLost_) {
if (numCallsToLoseContext_ == numCalls_) {
canvas.loseContext();
}
}
}
// Makes a function that simulates WebGL when out of context.
function makeLostContextFunctionWrapper(ctx, functionName) {
var f = ctx[functionName];
return function() {
// log("calling:" + functionName);
// Only call the functions if the context is not lost.
loseContextIfTime();
if (!contextLost_) {
//if (!checkResources(arguments)) {
// glErrorShadow_[wrappedContext_.INVALID_OPERATION] = true;
// return;
//}
var result = f.apply(ctx, arguments);
return result;
}
};
}
function freeResources() {
for (var ii = 0; ii < resourceDb_.length; ++ii) {
var resource = resourceDb_[ii];
if (resource instanceof WebGLBuffer) {
unwrappedContext_.deleteBuffer(resource);
} else if (resource instanceof WebGLFramebuffer) {
unwrappedContext_.deleteFramebuffer(resource);
} else if (resource instanceof WebGLProgram) {
unwrappedContext_.deleteProgram(resource);
} else if (resource instanceof WebGLRenderbuffer) {
unwrappedContext_.deleteRenderbuffer(resource);
} else if (resource instanceof WebGLShader) {
unwrappedContext_.deleteShader(resource);
} else if (resource instanceof WebGLTexture) {
unwrappedContext_.deleteTexture(resource);
}
}
}
function makeWebGLContextEvent(statusMessage) {
return {
statusMessage: statusMessage,
preventDefault: function() {
canRestore_ = true;
}
};
}
return canvas;
function makeLostContextSimulatingContext(ctx) {
// copy all functions and properties to wrapper
for (var propertyName in ctx) {
if (typeof ctx[propertyName] == 'function') {
wrappedContext_[propertyName] = makeLostContextFunctionWrapper(
ctx, propertyName);
} else {
makePropertyWrapper(wrappedContext_, ctx, propertyName);
}
}
// Wrap a few functions specially.
wrappedContext_.getError = function() {
loseContextIfTime();
if (!contextLost_) {
var err;
while (err = unwrappedContext_.getError()) {
glErrorShadow_[err] = true;
}
}
for (var err in glErrorShadow_) {
if (glErrorShadow_[err]) {
delete glErrorShadow_[err];
return err;
}
}
return wrappedContext_.NO_ERROR;
};
var creationFunctions = [
"createBuffer",
"createFramebuffer",
"createProgram",
"createRenderbuffer",
"createShader",
"createTexture"
];
for (var ii = 0; ii < creationFunctions.length; ++ii) {
var functionName = creationFunctions[ii];
wrappedContext_[functionName] = function(f) {
return function() {
loseContextIfTime();
if (contextLost_) {
return null;
}
var obj = f.apply(ctx, arguments);
obj.__webglDebugContextLostId__ = contextId_;
resourceDb_.push(obj);
return obj;
};
}(ctx[functionName]);
}
var functionsThatShouldReturnNull = [
"getActiveAttrib",
"getActiveUniform",
"getBufferParameter",
"getContextAttributes",
"getAttachedShaders",
"getFramebufferAttachmentParameter",
"getParameter",
"getProgramParameter",
"getProgramInfoLog",
"getRenderbufferParameter",
"getShaderParameter",
"getShaderInfoLog",
"getShaderSource",
"getTexParameter",
"getUniform",
"getUniformLocation",
"getVertexAttrib"
];
for (var ii = 0; ii < functionsThatShouldReturnNull.length; ++ii) {
var functionName = functionsThatShouldReturnNull[ii];
wrappedContext_[functionName] = function(f) {
return function() {
loseContextIfTime();
if (contextLost_) {
return null;
}
return f.apply(ctx, arguments);
}
}(wrappedContext_[functionName]);
}
var isFunctions = [
"isBuffer",
"isEnabled",
"isFramebuffer",
"isProgram",
"isRenderbuffer",
"isShader",
"isTexture"
];
for (var ii = 0; ii < isFunctions.length; ++ii) {
var functionName = isFunctions[ii];
wrappedContext_[functionName] = function(f) {
return function() {
loseContextIfTime();
if (contextLost_) {
return false;
}
return f.apply(ctx, arguments);
}
}(wrappedContext_[functionName]);
}
wrappedContext_.checkFramebufferStatus = function(f) {
return function() {
loseContextIfTime();
if (contextLost_) {
return wrappedContext_.FRAMEBUFFER_UNSUPPORTED;
}
return f.apply(ctx, arguments);
};
}(wrappedContext_.checkFramebufferStatus);
wrappedContext_.getAttribLocation = function(f) {
return function() {
loseContextIfTime();
if (contextLost_) {
return -1;
}
return f.apply(ctx, arguments);
};
}(wrappedContext_.getAttribLocation);
wrappedContext_.getVertexAttribOffset = function(f) {
return function() {
loseContextIfTime();
if (contextLost_) {
return 0;
}
return f.apply(ctx, arguments);
};
}(wrappedContext_.getVertexAttribOffset);
wrappedContext_.isContextLost = function() {
return contextLost_;
};
return wrappedContext_;
}
}
return {
/**
* Initializes this module. Safe to call more than once.
* @param {!WebGLRenderingContext} ctx A WebGL context. If
* you have more than one context it doesn't matter which one
* you pass in, it is only used to pull out constants.
*/
'init': init,
/**
* Returns true or false if value matches any WebGL enum
* @param {*} value Value to check if it might be an enum.
* @return {boolean} True if value matches one of the WebGL defined enums
*/
'mightBeEnum': mightBeEnum,
/**
* Gets an string version of an WebGL enum.
*
* Example:
* WebGLDebugUtil.init(ctx);
* var str = WebGLDebugUtil.glEnumToString(ctx.getError());
*
* @param {number} value Value to return an enum for
* @return {string} The string version of the enum.
*/
'glEnumToString': glEnumToString,
/**
* Converts the argument of a WebGL function to a string.
* Attempts to convert enum arguments to strings.
*
* Example:
* WebGLDebugUtil.init(ctx);
* var str = WebGLDebugUtil.glFunctionArgToString('bindTexture', 2, 0, gl.TEXTURE_2D);
*
* would return 'TEXTURE_2D'
*
* @param {string} functionName the name of the WebGL function.
* @param {number} numArgs The number of arguments
* @param {number} argumentIndx the index of the argument.
* @param {*} value The value of the argument.
* @return {string} The value as a string.
*/
'glFunctionArgToString': glFunctionArgToString,
/**
* Converts the arguments of a WebGL function to a string.
* Attempts to convert enum arguments to strings.
*
* @param {string} functionName the name of the WebGL function.
* @param {number} args The arguments.
* @return {string} The arguments as a string.
*/
'glFunctionArgsToString': glFunctionArgsToString,
/**
* Given a WebGL context returns a wrapped context that calls
* gl.getError after every command and calls a function if the
* result is not NO_ERROR.
*
* You can supply your own function if you want. For example, if you'd like
* an exception thrown on any GL error you could do this
*
* function throwOnGLError(err, funcName, args) {
* throw WebGLDebugUtils.glEnumToString(err) +
* " was caused by call to " + funcName;
* };
*
* ctx = WebGLDebugUtils.makeDebugContext(
* canvas.getContext("webgl"), throwOnGLError);
*
* @param {!WebGLRenderingContext} ctx The webgl context to wrap.
* @param {!function(err, funcName, args): void} opt_onErrorFunc The function
* to call when gl.getError returns an error. If not specified the default
* function calls console.log with a message.
* @param {!function(funcName, args): void} opt_onFunc The
* function to call when each webgl function is called. You
* can use this to log all calls for example.
*/
'makeDebugContext': makeDebugContext,
/**
* Given a canvas element returns a wrapped canvas element that will
* simulate lost context. The canvas returned adds the following functions.
*
* loseContext:
* simulates a lost context event.
*
* restoreContext:
* simulates the context being restored.
*
* lostContextInNCalls:
* loses the context after N gl calls.
*
* getNumCalls:
* tells you how many gl calls there have been so far.
*
* setRestoreTimeout:
* sets the number of milliseconds until the context is restored
* after it has been lost. Defaults to 0. Pass -1 to prevent
* automatic restoring.
*
* @param {!Canvas} canvas The canvas element to wrap.
*/
'makeLostContextSimulatingCanvas': makeLostContextSimulatingCanvas,
/**
* Resets a context to the initial state.
* @param {!WebGLRenderingContext} ctx The webgl context to
* reset.
*/
'resetToInitialState': resetToInitialState
};
}(); | Given a WebGL context returns a wrapped context that calls
gl.getError after every command and calls a function if the
result is not gl.NO_ERROR.
@param {!WebGLRenderingContext} ctx The webgl context to
wrap.
@param {!function(err, funcName, args): void} opt_onErrorFunc
The function to call when gl.getError returns an
error. If not specified the default function calls
console.log with a message.
@param {!function(funcName, args): void} opt_onFunc The
function to call when each webgl function is called.
You can use this to log all calls for example.
@param {!WebGLRenderingContext} opt_err_ctx The webgl context
to call getError on if different than ctx. | makeDebugContext ( ctx , opt_onErrorFunc , opt_onFunc , opt_err_ctx ) | javascript | brianchirls/Seriously.js | lib/webgl-debug.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/webgl-debug.js | MIT |
function glFunctionArgsToString(functionName, args) {
// apparently we can't do args.join(",");
var argStr = "";
var numArgs = args.length;
for (var ii = 0; ii < numArgs; ++ii) {
argStr += ((ii == 0) ? '' : ', ') +
glFunctionArgToString(functionName, numArgs, ii, args[ii]);
}
return argStr;
};
function makePropertyWrapper(wrapper, original, propertyName) {
//log("wrap prop: " + propertyName);
wrapper.__defineGetter__(propertyName, function() {
return original[propertyName];
});
// TODO(gmane): this needs to handle properties that take more than
// one value?
wrapper.__defineSetter__(propertyName, function(value) {
//log("set: " + propertyName);
original[propertyName] = value;
});
}
// Makes a function that calls a function on another object.
function makeFunctionWrapper(original, functionName) {
//log("wrap fn: " + functionName);
var f = original[functionName];
return function() {
//log("call: " + functionName);
var result = f.apply(original, arguments);
return result;
};
}
/**
* Given a WebGL context returns a wrapped context that calls
* gl.getError after every command and calls a function if the
* result is not gl.NO_ERROR.
*
* @param {!WebGLRenderingContext} ctx The webgl context to
* wrap.
* @param {!function(err, funcName, args): void} opt_onErrorFunc
* The function to call when gl.getError returns an
* error. If not specified the default function calls
* console.log with a message.
* @param {!function(funcName, args): void} opt_onFunc The
* function to call when each webgl function is called.
* You can use this to log all calls for example.
* @param {!WebGLRenderingContext} opt_err_ctx The webgl context
* to call getError on if different than ctx.
*/
function makeDebugContext(ctx, opt_onErrorFunc, opt_onFunc, opt_err_ctx) {
opt_err_ctx = opt_err_ctx || ctx;
init(ctx);
opt_onErrorFunc = opt_onErrorFunc || function(err, functionName, args) {
// apparently we can't do args.join(",");
var argStr = "";
var numArgs = args.length;
for (var ii = 0; ii < numArgs; ++ii) {
argStr += ((ii == 0) ? '' : ', ') +
glFunctionArgToString(functionName, numArgs, ii, args[ii]);
}
error("WebGL error "+ glEnumToString(err) + " in "+ functionName +
"(" + argStr + ")");
};
// Holds booleans for each GL error so after we get the error ourselves
// we can still return it to the client app.
var glErrorShadow = { };
// Makes a function that calls a WebGL function and then calls getError.
function makeErrorWrapper(ctx, functionName) {
return function() {
if (opt_onFunc) {
opt_onFunc(functionName, arguments);
}
var result = ctx[functionName].apply(ctx, arguments);
var err = opt_err_ctx.getError();
if (err != 0) {
glErrorShadow[err] = true;
opt_onErrorFunc(err, functionName, arguments);
}
return result;
};
}
// Make a an object that has a copy of every property of the WebGL context
// but wraps all functions.
var wrapper = {};
for (var propertyName in ctx) {
if (typeof ctx[propertyName] == 'function') {
if (propertyName != 'getExtension') {
wrapper[propertyName] = makeErrorWrapper(ctx, propertyName);
} else {
var wrapped = makeErrorWrapper(ctx, propertyName);
wrapper[propertyName] = function () {
var result = wrapped.apply(ctx, arguments);
return makeDebugContext(result, opt_onErrorFunc, opt_onFunc, opt_err_ctx);
};
}
} else {
makePropertyWrapper(wrapper, ctx, propertyName);
}
}
// Override the getError function with one that returns our saved results.
wrapper.getError = function() {
for (var err in glErrorShadow) {
if (glErrorShadow.hasOwnProperty(err)) {
if (glErrorShadow[err]) {
glErrorShadow[err] = false;
return err;
}
}
}
return ctx.NO_ERROR;
};
return wrapper;
}
function resetToInitialState(ctx) {
var numAttribs = ctx.getParameter(ctx.MAX_VERTEX_ATTRIBS);
var tmp = ctx.createBuffer();
ctx.bindBuffer(ctx.ARRAY_BUFFER, tmp);
for (var ii = 0; ii < numAttribs; ++ii) {
ctx.disableVertexAttribArray(ii);
ctx.vertexAttribPointer(ii, 4, ctx.FLOAT, false, 0, 0);
ctx.vertexAttrib1f(ii, 0);
}
ctx.deleteBuffer(tmp);
var numTextureUnits = ctx.getParameter(ctx.MAX_TEXTURE_IMAGE_UNITS);
for (var ii = 0; ii < numTextureUnits; ++ii) {
ctx.activeTexture(ctx.TEXTURE0 + ii);
ctx.bindTexture(ctx.TEXTURE_CUBE_MAP, null);
ctx.bindTexture(ctx.TEXTURE_2D, null);
}
ctx.activeTexture(ctx.TEXTURE0);
ctx.useProgram(null);
ctx.bindBuffer(ctx.ARRAY_BUFFER, null);
ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, null);
ctx.bindFramebuffer(ctx.FRAMEBUFFER, null);
ctx.bindRenderbuffer(ctx.RENDERBUFFER, null);
ctx.disable(ctx.BLEND);
ctx.disable(ctx.CULL_FACE);
ctx.disable(ctx.DEPTH_TEST);
ctx.disable(ctx.DITHER);
ctx.disable(ctx.SCISSOR_TEST);
ctx.blendColor(0, 0, 0, 0);
ctx.blendEquation(ctx.FUNC_ADD);
ctx.blendFunc(ctx.ONE, ctx.ZERO);
ctx.clearColor(0, 0, 0, 0);
ctx.clearDepth(1);
ctx.clearStencil(-1);
ctx.colorMask(true, true, true, true);
ctx.cullFace(ctx.BACK);
ctx.depthFunc(ctx.LESS);
ctx.depthMask(true);
ctx.depthRange(0, 1);
ctx.frontFace(ctx.CCW);
ctx.hint(ctx.GENERATE_MIPMAP_HINT, ctx.DONT_CARE);
ctx.lineWidth(1);
ctx.pixelStorei(ctx.PACK_ALIGNMENT, 4);
ctx.pixelStorei(ctx.UNPACK_ALIGNMENT, 4);
ctx.pixelStorei(ctx.UNPACK_FLIP_Y_WEBGL, false);
ctx.pixelStorei(ctx.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
// TODO: Delete this IF.
if (ctx.UNPACK_COLORSPACE_CONVERSION_WEBGL) {
ctx.pixelStorei(ctx.UNPACK_COLORSPACE_CONVERSION_WEBGL, ctx.BROWSER_DEFAULT_WEBGL);
}
ctx.polygonOffset(0, 0);
ctx.sampleCoverage(1, false);
ctx.scissor(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.stencilFunc(ctx.ALWAYS, 0, 0xFFFFFFFF);
ctx.stencilMask(0xFFFFFFFF);
ctx.stencilOp(ctx.KEEP, ctx.KEEP, ctx.KEEP);
ctx.viewport(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.clear(ctx.COLOR_BUFFER_BIT | ctx.DEPTH_BUFFER_BIT | ctx.STENCIL_BUFFER_BIT);
// TODO: This should NOT be needed but Firefox fails with 'hint'
while(ctx.getError());
}
function makeLostContextSimulatingCanvas(canvas) {
var unwrappedContext_;
var wrappedContext_;
var onLost_ = [];
var onRestored_ = [];
var wrappedContext_ = {};
var contextId_ = 1;
var contextLost_ = false;
var resourceId_ = 0;
var resourceDb_ = [];
var numCallsToLoseContext_ = 0;
var numCalls_ = 0;
var canRestore_ = false;
var restoreTimeout_ = 0;
// Holds booleans for each GL error so can simulate errors.
var glErrorShadow_ = { };
canvas.getContext = function(f) {
return function() {
var ctx = f.apply(canvas, arguments);
// Did we get a context and is it a WebGL context?
if (ctx instanceof WebGLRenderingContext) {
if (ctx != unwrappedContext_) {
if (unwrappedContext_) {
throw "got different context"
}
unwrappedContext_ = ctx;
wrappedContext_ = makeLostContextSimulatingContext(unwrappedContext_);
}
return wrappedContext_;
}
return ctx;
}
}(canvas.getContext);
function wrapEvent(listener) {
if (typeof(listener) == "function") {
return listener;
} else {
return function(info) {
listener.handleEvent(info);
}
}
}
var addOnContextLostListener = function(listener) {
onLost_.push(wrapEvent(listener));
};
var addOnContextRestoredListener = function(listener) {
onRestored_.push(wrapEvent(listener));
};
function wrapAddEventListener(canvas) {
var f = canvas.addEventListener;
canvas.addEventListener = function(type, listener, bubble) {
switch (type) {
case 'webglcontextlost':
addOnContextLostListener(listener);
break;
case 'webglcontextrestored':
addOnContextRestoredListener(listener);
break;
default:
f.apply(canvas, arguments);
}
};
}
wrapAddEventListener(canvas);
canvas.loseContext = function() {
if (!contextLost_) {
contextLost_ = true;
numCallsToLoseContext_ = 0;
++contextId_;
while (unwrappedContext_.getError());
clearErrors();
glErrorShadow_[unwrappedContext_.CONTEXT_LOST_WEBGL] = true;
var event = makeWebGLContextEvent("context lost");
var callbacks = onLost_.slice();
setTimeout(function() {
//log("numCallbacks:" + callbacks.length);
for (var ii = 0; ii < callbacks.length; ++ii) {
//log("calling callback:" + ii);
callbacks[ii](event);
}
if (restoreTimeout_ >= 0) {
setTimeout(function() {
canvas.restoreContext();
}, restoreTimeout_);
}
}, 0);
}
};
canvas.restoreContext = function() {
if (contextLost_) {
if (onRestored_.length) {
setTimeout(function() {
if (!canRestore_) {
throw "can not restore. webglcontestlost listener did not call event.preventDefault";
}
freeResources();
resetToInitialState(unwrappedContext_);
contextLost_ = false;
numCalls_ = 0;
canRestore_ = false;
var callbacks = onRestored_.slice();
var event = makeWebGLContextEvent("context restored");
for (var ii = 0; ii < callbacks.length; ++ii) {
callbacks[ii](event);
}
}, 0);
}
}
};
canvas.loseContextInNCalls = function(numCalls) {
if (contextLost_) {
throw "You can not ask a lost contet to be lost";
}
numCallsToLoseContext_ = numCalls_ + numCalls;
};
canvas.getNumCalls = function() {
return numCalls_;
};
canvas.setRestoreTimeout = function(timeout) {
restoreTimeout_ = timeout;
};
function isWebGLObject(obj) {
//return false;
return (obj instanceof WebGLBuffer ||
obj instanceof WebGLFramebuffer ||
obj instanceof WebGLProgram ||
obj instanceof WebGLRenderbuffer ||
obj instanceof WebGLShader ||
obj instanceof WebGLTexture);
}
function checkResources(args) {
for (var ii = 0; ii < args.length; ++ii) {
var arg = args[ii];
if (isWebGLObject(arg)) {
return arg.__webglDebugContextLostId__ == contextId_;
}
}
return true;
}
function clearErrors() {
var k = Object.keys(glErrorShadow_);
for (var ii = 0; ii < k.length; ++ii) {
delete glErrorShadow_[k];
}
}
function loseContextIfTime() {
++numCalls_;
if (!contextLost_) {
if (numCallsToLoseContext_ == numCalls_) {
canvas.loseContext();
}
}
}
// Makes a function that simulates WebGL when out of context.
function makeLostContextFunctionWrapper(ctx, functionName) {
var f = ctx[functionName];
return function() {
// log("calling:" + functionName);
// Only call the functions if the context is not lost.
loseContextIfTime();
if (!contextLost_) {
//if (!checkResources(arguments)) {
// glErrorShadow_[wrappedContext_.INVALID_OPERATION] = true;
// return;
//}
var result = f.apply(ctx, arguments);
return result;
}
};
}
function freeResources() {
for (var ii = 0; ii < resourceDb_.length; ++ii) {
var resource = resourceDb_[ii];
if (resource instanceof WebGLBuffer) {
unwrappedContext_.deleteBuffer(resource);
} else if (resource instanceof WebGLFramebuffer) {
unwrappedContext_.deleteFramebuffer(resource);
} else if (resource instanceof WebGLProgram) {
unwrappedContext_.deleteProgram(resource);
} else if (resource instanceof WebGLRenderbuffer) {
unwrappedContext_.deleteRenderbuffer(resource);
} else if (resource instanceof WebGLShader) {
unwrappedContext_.deleteShader(resource);
} else if (resource instanceof WebGLTexture) {
unwrappedContext_.deleteTexture(resource);
}
}
}
function makeWebGLContextEvent(statusMessage) {
return {
statusMessage: statusMessage,
preventDefault: function() {
canRestore_ = true;
}
};
}
return canvas;
function makeLostContextSimulatingContext(ctx) {
// copy all functions and properties to wrapper
for (var propertyName in ctx) {
if (typeof ctx[propertyName] == 'function') {
wrappedContext_[propertyName] = makeLostContextFunctionWrapper(
ctx, propertyName);
} else {
makePropertyWrapper(wrappedContext_, ctx, propertyName);
}
}
// Wrap a few functions specially.
wrappedContext_.getError = function() {
loseContextIfTime();
if (!contextLost_) {
var err;
while (err = unwrappedContext_.getError()) {
glErrorShadow_[err] = true;
}
}
for (var err in glErrorShadow_) {
if (glErrorShadow_[err]) {
delete glErrorShadow_[err];
return err;
}
}
return wrappedContext_.NO_ERROR;
};
var creationFunctions = [
"createBuffer",
"createFramebuffer",
"createProgram",
"createRenderbuffer",
"createShader",
"createTexture"
];
for (var ii = 0; ii < creationFunctions.length; ++ii) {
var functionName = creationFunctions[ii];
wrappedContext_[functionName] = function(f) {
return function() {
loseContextIfTime();
if (contextLost_) {
return null;
}
var obj = f.apply(ctx, arguments);
obj.__webglDebugContextLostId__ = contextId_;
resourceDb_.push(obj);
return obj;
};
}(ctx[functionName]);
}
var functionsThatShouldReturnNull = [
"getActiveAttrib",
"getActiveUniform",
"getBufferParameter",
"getContextAttributes",
"getAttachedShaders",
"getFramebufferAttachmentParameter",
"getParameter",
"getProgramParameter",
"getProgramInfoLog",
"getRenderbufferParameter",
"getShaderParameter",
"getShaderInfoLog",
"getShaderSource",
"getTexParameter",
"getUniform",
"getUniformLocation",
"getVertexAttrib"
];
for (var ii = 0; ii < functionsThatShouldReturnNull.length; ++ii) {
var functionName = functionsThatShouldReturnNull[ii];
wrappedContext_[functionName] = function(f) {
return function() {
loseContextIfTime();
if (contextLost_) {
return null;
}
return f.apply(ctx, arguments);
}
}(wrappedContext_[functionName]);
}
var isFunctions = [
"isBuffer",
"isEnabled",
"isFramebuffer",
"isProgram",
"isRenderbuffer",
"isShader",
"isTexture"
];
for (var ii = 0; ii < isFunctions.length; ++ii) {
var functionName = isFunctions[ii];
wrappedContext_[functionName] = function(f) {
return function() {
loseContextIfTime();
if (contextLost_) {
return false;
}
return f.apply(ctx, arguments);
}
}(wrappedContext_[functionName]);
}
wrappedContext_.checkFramebufferStatus = function(f) {
return function() {
loseContextIfTime();
if (contextLost_) {
return wrappedContext_.FRAMEBUFFER_UNSUPPORTED;
}
return f.apply(ctx, arguments);
};
}(wrappedContext_.checkFramebufferStatus);
wrappedContext_.getAttribLocation = function(f) {
return function() {
loseContextIfTime();
if (contextLost_) {
return -1;
}
return f.apply(ctx, arguments);
};
}(wrappedContext_.getAttribLocation);
wrappedContext_.getVertexAttribOffset = function(f) {
return function() {
loseContextIfTime();
if (contextLost_) {
return 0;
}
return f.apply(ctx, arguments);
};
}(wrappedContext_.getVertexAttribOffset);
wrappedContext_.isContextLost = function() {
return contextLost_;
};
return wrappedContext_;
}
}
return {
/**
* Initializes this module. Safe to call more than once.
* @param {!WebGLRenderingContext} ctx A WebGL context. If
* you have more than one context it doesn't matter which one
* you pass in, it is only used to pull out constants.
*/
'init': init,
/**
* Returns true or false if value matches any WebGL enum
* @param {*} value Value to check if it might be an enum.
* @return {boolean} True if value matches one of the WebGL defined enums
*/
'mightBeEnum': mightBeEnum,
/**
* Gets an string version of an WebGL enum.
*
* Example:
* WebGLDebugUtil.init(ctx);
* var str = WebGLDebugUtil.glEnumToString(ctx.getError());
*
* @param {number} value Value to return an enum for
* @return {string} The string version of the enum.
*/
'glEnumToString': glEnumToString,
/**
* Converts the argument of a WebGL function to a string.
* Attempts to convert enum arguments to strings.
*
* Example:
* WebGLDebugUtil.init(ctx);
* var str = WebGLDebugUtil.glFunctionArgToString('bindTexture', 2, 0, gl.TEXTURE_2D);
*
* would return 'TEXTURE_2D'
*
* @param {string} functionName the name of the WebGL function.
* @param {number} numArgs The number of arguments
* @param {number} argumentIndx the index of the argument.
* @param {*} value The value of the argument.
* @return {string} The value as a string.
*/
'glFunctionArgToString': glFunctionArgToString,
/**
* Converts the arguments of a WebGL function to a string.
* Attempts to convert enum arguments to strings.
*
* @param {string} functionName the name of the WebGL function.
* @param {number} args The arguments.
* @return {string} The arguments as a string.
*/
'glFunctionArgsToString': glFunctionArgsToString,
/**
* Given a WebGL context returns a wrapped context that calls
* gl.getError after every command and calls a function if the
* result is not NO_ERROR.
*
* You can supply your own function if you want. For example, if you'd like
* an exception thrown on any GL error you could do this
*
* function throwOnGLError(err, funcName, args) {
* throw WebGLDebugUtils.glEnumToString(err) +
* " was caused by call to " + funcName;
* };
*
* ctx = WebGLDebugUtils.makeDebugContext(
* canvas.getContext("webgl"), throwOnGLError);
*
* @param {!WebGLRenderingContext} ctx The webgl context to wrap.
* @param {!function(err, funcName, args): void} opt_onErrorFunc The function
* to call when gl.getError returns an error. If not specified the default
* function calls console.log with a message.
* @param {!function(funcName, args): void} opt_onFunc The
* function to call when each webgl function is called. You
* can use this to log all calls for example.
*/
'makeDebugContext': makeDebugContext,
/**
* Given a canvas element returns a wrapped canvas element that will
* simulate lost context. The canvas returned adds the following functions.
*
* loseContext:
* simulates a lost context event.
*
* restoreContext:
* simulates the context being restored.
*
* lostContextInNCalls:
* loses the context after N gl calls.
*
* getNumCalls:
* tells you how many gl calls there have been so far.
*
* setRestoreTimeout:
* sets the number of milliseconds until the context is restored
* after it has been lost. Defaults to 0. Pass -1 to prevent
* automatic restoring.
*
* @param {!Canvas} canvas The canvas element to wrap.
*/
'makeLostContextSimulatingCanvas': makeLostContextSimulatingCanvas,
/**
* Resets a context to the initial state.
* @param {!WebGLRenderingContext} ctx The webgl context to
* reset.
*/
'resetToInitialState': resetToInitialState
};
}(); | Converts the arguments of a WebGL function to a string.
Attempts to convert enum arguments to strings.
@param {string} functionName the name of the WebGL function.
@param {number} args The arguments.
@return {string} The arguments as a string. | glFunctionArgsToString ( functionName , args ) | javascript | brianchirls/Seriously.js | lib/webgl-debug.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/webgl-debug.js | MIT |
req.exec = function (text) {
/*jslint evil: true */
return eval(text);
};
//Set up with config info.
req(cfg);
}(this)); | Executes the text. Normally just uses eval, but can be modified
to use a better, environment-specific call. Only used for transpiling
loader plugins, not for plain JS modules.
@param {String} text the text to execute/evaluate. | req.exec ( text ) | javascript | brianchirls/Seriously.js | lib/require.js | https://github.com/brianchirls/Seriously.js/blob/master/lib/require.js | MIT |
var sanitizeHTML = function (str) {
return str.replace(/[^\w. ]/gi, function (c) {
return '&#' + c.charCodeAt(0) + ';';
});
}; | Sanitize and encode all HTML in a user-submitted string
https://portswigger.net/web-security/cross-site-scripting/preventing
@param {String} str The user-submitted string
@return {String} str The sanitized string | sanitizeHTML ( str ) | javascript | colinwilson/lotusdocs | assets/docs/js/app.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/app.js | MIT |
/******/ !function() {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = function(exports, definition) {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ }(); | ****/ var __webpack_require__ = {};
****/
**********************************************************************/
****/ /* webpack/runtime/define property getters */ | (anonymous) ( ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
/******/ !function() {
/******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
/******/ }(); | ****/ }();
****/
****/ /* webpack/runtime/hasOwnProperty shorthand */ | (anonymous) ( ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var contains = function contains(list, elem) {
return list.indexOf(elem) !== -1;
}; | Return whether an element is contained in a list | contains ( list , elem ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var deflt = function deflt(setting, defaultIfUndefined) {
return setting === undefined ? defaultIfUndefined : setting;
}; // hyphenate and escape adapted from Facebook's React under Apache 2 license | Provide a default value if a setting is undefined
NOTE: Couldn't use `T` as the output type due to facebook/flow#5022. | deflt ( setting , defaultIfUndefined ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var Span = /*#__PURE__*/function () {
function Span(classes, children, options, style) {
this.children = void 0;
this.attributes = void 0;
this.classes = void 0;
this.height = void 0;
this.depth = void 0;
this.width = void 0;
this.maxFontSize = void 0;
this.style = void 0;
initNode.call(this, classes, options, style);
this.children = children || [];
}
/**
* Sets an arbitrary attribute on the span. Warning: use this wisely. Not
* all browsers support attributes the same, and having too many custom
* attributes is probably bad.
*/
var _proto = Span.prototype;
_proto.setAttribute = function setAttribute(attribute, value) {
this.attributes[attribute] = value;
};
_proto.hasClass = function hasClass(className) {
return utils.contains(this.classes, className);
};
_proto.toNode = function toNode() {
return _toNode.call(this, "span");
};
_proto.toMarkup = function toMarkup() {
return _toMarkup.call(this, "span");
};
return Span;
}(); | This node represents a span node, with a className, a list of children, and
an inline style. It also contains information about its height, depth, and
maxFontSize.
Represents two types with different uses: SvgSpan to wrap an SVG and DomSpan
otherwise. This typesafety is important when HTML builders access a span's
children. | Span ( ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var Anchor = /*#__PURE__*/function () {
function Anchor(href, classes, children, options) {
this.children = void 0;
this.attributes = void 0;
this.classes = void 0;
this.height = void 0;
this.depth = void 0;
this.maxFontSize = void 0;
this.style = void 0;
initNode.call(this, classes, options);
this.children = children || [];
this.setAttribute('href', href);
}
var _proto2 = Anchor.prototype;
_proto2.setAttribute = function setAttribute(attribute, value) {
this.attributes[attribute] = value;
};
_proto2.hasClass = function hasClass(className) {
return utils.contains(this.classes, className);
};
_proto2.toNode = function toNode() {
return _toNode.call(this, "a");
};
_proto2.toMarkup = function toMarkup() {
return _toMarkup.call(this, "a");
};
return Anchor;
}(); | This node represents an anchor (<a>) element with a hyperlink. See `span`
for further details. | Anchor ( ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var Img = /*#__PURE__*/function () {
function Img(src, alt, style) {
this.src = void 0;
this.alt = void 0;
this.classes = void 0;
this.height = void 0;
this.depth = void 0;
this.maxFontSize = void 0;
this.style = void 0;
this.alt = alt;
this.src = src;
this.classes = ["mord"];
this.style = style;
}
var _proto3 = Img.prototype;
_proto3.hasClass = function hasClass(className) {
return utils.contains(this.classes, className);
};
_proto3.toNode = function toNode() {
var node = document.createElement("img");
node.src = this.src;
node.alt = this.alt;
node.className = "mord"; // Apply inline styles
for (var style in this.style) {
if (this.style.hasOwnProperty(style)) {
// $FlowFixMe
node.style[style] = this.style[style];
}
}
return node;
};
_proto3.toMarkup = function toMarkup() {
var markup = "<img src='" + this.src + " 'alt='" + this.alt + "' "; // Add the styles, after hyphenation
var styles = "";
for (var style in this.style) {
if (this.style.hasOwnProperty(style)) {
styles += utils.hyphenate(style) + ":" + this.style[style] + ";";
}
}
if (styles) {
markup += " style=\"" + utils.escape(styles) + "\"";
}
markup += "'/>";
return markup;
};
return Img;
}(); | This node represents an image embed (<img>) element. | Img ( ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var SymbolNode = /*#__PURE__*/function () {
function SymbolNode(text, height, depth, italic, skew, width, classes, style) {
this.text = void 0;
this.height = void 0;
this.depth = void 0;
this.italic = void 0;
this.skew = void 0;
this.width = void 0;
this.maxFontSize = void 0;
this.classes = void 0;
this.style = void 0;
this.text = text;
this.height = height || 0;
this.depth = depth || 0;
this.italic = italic || 0;
this.skew = skew || 0;
this.width = width || 0;
this.classes = classes || [];
this.style = style || {};
this.maxFontSize = 0; // Mark text from non-Latin scripts with specific classes so that we
// can specify which fonts to use. This allows us to render these
// characters with a serif font in situations where the browser would
// either default to a sans serif or render a placeholder character.
// We use CSS class names like cjk_fallback, hangul_fallback and
// brahmic_fallback. See ./unicodeScripts.js for the set of possible
// script names
var script = scriptFromCodepoint(this.text.charCodeAt(0));
if (script) {
this.classes.push(script + "_fallback");
}
if (/[îïíì]/.test(this.text)) {
// add ī when we add Extended Latin
this.text = iCombinations[this.text];
}
}
var _proto4 = SymbolNode.prototype;
_proto4.hasClass = function hasClass(className) {
return utils.contains(this.classes, className);
}
/**
* Creates a text node or span from a symbol node. Note that a span is only
* created if it is needed.
*/
;
_proto4.toNode = function toNode() {
var node = document.createTextNode(this.text);
var span = null;
if (this.italic > 0) {
span = document.createElement("span");
span.style.marginRight = makeEm(this.italic);
}
if (this.classes.length > 0) {
span = span || document.createElement("span");
span.className = createClass(this.classes);
}
for (var style in this.style) {
if (this.style.hasOwnProperty(style)) {
span = span || document.createElement("span"); // $FlowFixMe Flow doesn't seem to understand span.style's type.
span.style[style] = this.style[style];
}
}
if (span) {
span.appendChild(node);
return span;
} else {
return node;
}
}
/**
* Creates markup for a symbol node.
*/
;
_proto4.toMarkup = function toMarkup() {
// TODO(alpert): More duplication than I'd like from
// span.prototype.toMarkup and symbolNode.prototype.toNode...
var needsSpan = false;
var markup = "<span";
if (this.classes.length) {
needsSpan = true;
markup += " class=\"";
markup += utils.escape(createClass(this.classes));
markup += "\"";
}
var styles = "";
if (this.italic > 0) {
styles += "margin-right:" + this.italic + "em;";
}
for (var style in this.style) {
if (this.style.hasOwnProperty(style)) {
styles += utils.hyphenate(style) + ":" + this.style[style] + ";";
}
}
if (styles) {
needsSpan = true;
markup += " style=\"" + utils.escape(styles) + "\"";
}
var escaped = utils.escape(this.text);
if (needsSpan) {
markup += ">";
markup += escaped;
markup += "</span>";
return markup;
} else {
return escaped;
}
};
return SymbolNode;
}(); | A symbol node contains information about a single symbol. It either renders
to a single text node, or a span with a single text node in it, depending on
whether it has CSS classes, styles, or needs italic correction. | SymbolNode ( ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var SvgNode = /*#__PURE__*/function () {
function SvgNode(children, attributes) {
this.children = void 0;
this.attributes = void 0;
this.children = children || [];
this.attributes = attributes || {};
}
var _proto5 = SvgNode.prototype;
_proto5.toNode = function toNode() {
var svgNS = "http://www.w3.org/2000/svg";
var node = document.createElementNS(svgNS, "svg"); // Apply attributes
for (var attr in this.attributes) {
if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
node.setAttribute(attr, this.attributes[attr]);
}
}
for (var i = 0; i < this.children.length; i++) {
node.appendChild(this.children[i].toNode());
}
return node;
};
_proto5.toMarkup = function toMarkup() {
var markup = "<svg xmlns=\"http://www.w3.org/2000/svg\""; // Apply attributes
for (var attr in this.attributes) {
if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
markup += " " + attr + "='" + this.attributes[attr] + "'";
}
}
markup += ">";
for (var i = 0; i < this.children.length; i++) {
markup += this.children[i].toMarkup();
}
markup += "</svg>";
return markup;
};
return SvgNode;
}(); | SVG nodes are used to render stretchy wide elements. | SvgNode ( ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var makeSymbol = function makeSymbol(value, fontName, mode, options, classes) {
var lookup = lookupSymbol(value, fontName, mode);
var metrics = lookup.metrics;
value = lookup.value;
var symbolNode;
if (metrics) {
var italic = metrics.italic;
if (mode === "text" || options && options.font === "mathit") {
italic = 0;
}
symbolNode = new SymbolNode(value, metrics.height, metrics.depth, italic, metrics.skew, metrics.width, classes);
} else {
// TODO(emily): Figure out a good way to only print this in development
typeof console !== "undefined" && console.warn("No character metrics " + ("for '" + value + "' in style '" + fontName + "' and mode '" + mode + "'"));
symbolNode = new SymbolNode(value, 0, 0, 0, 0, 0, classes);
}
if (options) {
symbolNode.maxFontSize = options.sizeMultiplier;
if (options.style.isTight()) {
symbolNode.classes.push("mtight");
}
var color = options.getColor();
if (color) {
symbolNode.style.color = color;
}
}
return symbolNode;
}; | Makes a symbolNode after translation via the list of symbols in symbols.js.
Correctly pulls out metrics for the character, and optionally takes a list of
classes to be attached to the node.
TODO: make argument order closer to makeSpan
TODO: add a separate argument for math class (e.g. `mop`, `mbin`), which
should if present come first in `classes`.
TODO(#953): Make `options` mandatory and always pass it in. | makeSymbol ( value , fontName , mode , options , classes ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var mathsym = function mathsym(value, mode, options, classes) {
if (classes === void 0) {
classes = [];
}
// Decide what font to render the symbol in by its entry in the symbols
// table.
// Have a special case for when the value = \ because the \ is used as a
// textord in unsupported command errors but cannot be parsed as a regular
// text ordinal and is therefore not present as a symbol in the symbols
// table for text, as well as a special case for boldsymbol because it
// can be used for bold + and -
if (options.font === "boldsymbol" && lookupSymbol(value, "Main-Bold", mode).metrics) {
return makeSymbol(value, "Main-Bold", mode, options, classes.concat(["mathbf"]));
} else if (value === "\\" || src_symbols[mode][value].font === "main") {
return makeSymbol(value, "Main-Regular", mode, options, classes);
} else {
return makeSymbol(value, "AMS-Regular", mode, options, classes.concat(["amsrm"]));
}
}; | Makes a symbol in Main-Regular or AMS-Regular.
Used for rel, bin, open, close, inner, and punct. | mathsym ( value , mode , options , classes ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var boldsymbol = function boldsymbol(value, mode, options, classes, type) {
if (type !== "textord" && lookupSymbol(value, "Math-BoldItalic", mode).metrics) {
return {
fontName: "Math-BoldItalic",
fontClass: "boldsymbol"
};
} else {
// Some glyphs do not exist in Math-BoldItalic so we need to use
// Main-Bold instead.
return {
fontName: "Main-Bold",
fontClass: "mathbf"
};
}
}; | Determines which of the two font names (Main-Bold and Math-BoldItalic) and
corresponding style tags (mathbf or boldsymbol) to use for font "boldsymbol",
depending on the symbol. Use this function instead of fontMap for font
"boldsymbol". | boldsymbol ( value , mode , options , classes , type ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var makeOrd = function makeOrd(group, options, type) {
var mode = group.mode;
var text = group.text;
var classes = ["mord"]; // Math mode or Old font (i.e. \rm)
var isFont = mode === "math" || mode === "text" && options.font;
var fontOrFamily = isFont ? options.font : options.fontFamily;
if (text.charCodeAt(0) === 0xD835) {
// surrogate pairs get special treatment
var _wideCharacterFont = wideCharacterFont(text, mode),
wideFontName = _wideCharacterFont[0],
wideFontClass = _wideCharacterFont[1];
return makeSymbol(text, wideFontName, mode, options, classes.concat(wideFontClass));
} else if (fontOrFamily) {
var fontName;
var fontClasses;
if (fontOrFamily === "boldsymbol") {
var fontData = boldsymbol(text, mode, options, classes, type);
fontName = fontData.fontName;
fontClasses = [fontData.fontClass];
} else if (isFont) {
fontName = fontMap[fontOrFamily].fontName;
fontClasses = [fontOrFamily];
} else {
fontName = retrieveTextFontName(fontOrFamily, options.fontWeight, options.fontShape);
fontClasses = [fontOrFamily, options.fontWeight, options.fontShape];
}
if (lookupSymbol(text, fontName, mode).metrics) {
return makeSymbol(text, fontName, mode, options, classes.concat(fontClasses));
} else if (ligatures.hasOwnProperty(text) && fontName.slice(0, 10) === "Typewriter") {
// Deconstruct ligatures in monospace fonts (\texttt, \tt).
var parts = [];
for (var i = 0; i < text.length; i++) {
parts.push(makeSymbol(text[i], fontName, mode, options, classes.concat(fontClasses)));
}
return makeFragment(parts);
}
} // Makes a symbol in the default font for mathords and textords.
if (type === "mathord") {
return makeSymbol(text, "Math-Italic", mode, options, classes.concat(["mathnormal"]));
} else if (type === "textord") {
var font = src_symbols[mode][text] && src_symbols[mode][text].font;
if (font === "ams") {
var _fontName = retrieveTextFontName("amsrm", options.fontWeight, options.fontShape);
return makeSymbol(text, _fontName, mode, options, classes.concat("amsrm", options.fontWeight, options.fontShape));
} else if (font === "main" || !font) {
var _fontName2 = retrieveTextFontName("textrm", options.fontWeight, options.fontShape);
return makeSymbol(text, _fontName2, mode, options, classes.concat(options.fontWeight, options.fontShape));
} else {
// fonts added by plugins
var _fontName3 = retrieveTextFontName(font, options.fontWeight, options.fontShape); // We add font name as a css class
return makeSymbol(text, _fontName3, mode, options, classes.concat(_fontName3, options.fontWeight, options.fontShape));
}
} else {
throw new Error("unexpected type: " + type + " in makeOrd");
}
}; | Makes either a mathord or textord in the correct font and color. | makeOrd ( group , options , type ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var canCombine = function canCombine(prev, next) {
if (createClass(prev.classes) !== createClass(next.classes) || prev.skew !== next.skew || prev.maxFontSize !== next.maxFontSize) {
return false;
} // If prev and next both are just "mbin"s or "mord"s we don't combine them
// so that the proper spacing can be preserved.
if (prev.classes.length === 1) {
var cls = prev.classes[0];
if (cls === "mbin" || cls === "mord") {
return false;
}
}
for (var style in prev.style) {
if (prev.style.hasOwnProperty(style) && prev.style[style] !== next.style[style]) {
return false;
}
}
for (var _style in next.style) {
if (next.style.hasOwnProperty(_style) && prev.style[_style] !== next.style[_style]) {
return false;
}
}
return true;
}; | Returns true if subsequent symbolNodes have the same classes, skew, maxFont,
and styles. | canCombine ( prev , next ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var tryCombineChars = function tryCombineChars(chars) {
for (var i = 0; i < chars.length - 1; i++) {
var prev = chars[i];
var next = chars[i + 1];
if (prev instanceof SymbolNode && next instanceof SymbolNode && canCombine(prev, next)) {
prev.text += next.text;
prev.height = Math.max(prev.height, next.height);
prev.depth = Math.max(prev.depth, next.depth); // Use the last character's italic correction since we use
// it to add padding to the right of the span created from
// the combined characters.
prev.italic = next.italic;
chars.splice(i + 1, 1);
i--;
}
}
return chars;
}; | Combine consecutive domTree.symbolNodes into a single symbolNode.
Note: this function mutates the argument. | tryCombineChars ( chars ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var sizeElementFromChildren = function sizeElementFromChildren(elem) {
var height = 0;
var depth = 0;
var maxFontSize = 0;
for (var i = 0; i < elem.children.length; i++) {
var child = elem.children[i];
if (child.height > height) {
height = child.height;
}
if (child.depth > depth) {
depth = child.depth;
}
if (child.maxFontSize > maxFontSize) {
maxFontSize = child.maxFontSize;
}
}
elem.height = height;
elem.depth = depth;
elem.maxFontSize = maxFontSize;
}; | Calculate the height, depth, and maxFontSize of an element based on its
children. | sizeElementFromChildren ( elem ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var makeSpan = function makeSpan(classes, children, options, style) {
var span = new Span(classes, children, options, style);
sizeElementFromChildren(span);
return span;
}; // SVG one is simpler -- doesn't require height, depth, max-font setting. | Makes a span with the given list of classes, list of children, and options.
TODO(#953): Ensure that `options` is always provided (currently some call
sites don't pass it) and make the type below mandatory.
TODO: add a separate argument for math class (e.g. `mop`, `mbin`), which
should if present come first in `classes`. | makeSpan ( classes , children , options , style ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var makeAnchor = function makeAnchor(href, classes, children, options) {
var anchor = new Anchor(href, classes, children, options);
sizeElementFromChildren(anchor);
return anchor;
}; | Makes an anchor with the given href, list of classes, list of children,
and options. | makeAnchor ( href , classes , children , options ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var makeFragment = function makeFragment(children) {
var fragment = new DocumentFragment(children);
sizeElementFromChildren(fragment);
return fragment;
}; | Makes a document fragment with the given list of children. | makeFragment ( children ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var wrapFragment = function wrapFragment(group, options) {
if (group instanceof DocumentFragment) {
return makeSpan([], [group], options);
}
return group;
}; // These are exact object types to catch typos in the names of the optional fields. | Wraps group in a span if it's a document fragment, allowing to apply classes
and styles | wrapFragment ( group , options ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var makeVList = function makeVList(params, options) {
var _getVListChildrenAndD = getVListChildrenAndDepth(params),
children = _getVListChildrenAndD.children,
depth = _getVListChildrenAndD.depth; // Create a strut that is taller than any list item. The strut is added to
// each item, where it will determine the item's baseline. Since it has
// `overflow:hidden`, the strut's top edge will sit on the item's line box's
// top edge and the strut's bottom edge will sit on the item's baseline,
// with no additional line-height spacing. This allows the item baseline to
// be positioned precisely without worrying about font ascent and
// line-height.
var pstrutSize = 0;
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (child.type === "elem") {
var elem = child.elem;
pstrutSize = Math.max(pstrutSize, elem.maxFontSize, elem.height);
}
}
pstrutSize += 2;
var pstrut = makeSpan(["pstrut"], []);
pstrut.style.height = makeEm(pstrutSize); // Create a new list of actual children at the correct offsets
var realChildren = [];
var minPos = depth;
var maxPos = depth;
var currPos = depth;
for (var _i2 = 0; _i2 < children.length; _i2++) {
var _child = children[_i2];
if (_child.type === "kern") {
currPos += _child.size;
} else {
var _elem = _child.elem;
var classes = _child.wrapperClasses || [];
var style = _child.wrapperStyle || {};
var childWrap = makeSpan(classes, [pstrut, _elem], undefined, style);
childWrap.style.top = makeEm(-pstrutSize - currPos - _elem.depth);
if (_child.marginLeft) {
childWrap.style.marginLeft = _child.marginLeft;
}
if (_child.marginRight) {
childWrap.style.marginRight = _child.marginRight;
}
realChildren.push(childWrap);
currPos += _elem.height + _elem.depth;
}
minPos = Math.min(minPos, currPos);
maxPos = Math.max(maxPos, currPos);
} // The vlist contents go in a table-cell with `vertical-align:bottom`.
// This cell's bottom edge will determine the containing table's baseline
// without overly expanding the containing line-box.
var vlist = makeSpan(["vlist"], realChildren);
vlist.style.height = makeEm(maxPos); // A second row is used if necessary to represent the vlist's depth.
var rows;
if (minPos < 0) {
// We will define depth in an empty span with display: table-cell.
// It should render with the height that we define. But Chrome, in
// contenteditable mode only, treats that span as if it contains some
// text content. And that min-height over-rides our desired height.
// So we put another empty span inside the depth strut span.
var emptySpan = makeSpan([], []);
var depthStrut = makeSpan(["vlist"], [emptySpan]);
depthStrut.style.height = makeEm(-minPos); // Safari wants the first row to have inline content; otherwise it
// puts the bottom of the *second* row on the baseline.
var topStrut = makeSpan(["vlist-s"], [new SymbolNode("\u200B")]);
rows = [makeSpan(["vlist-r"], [vlist, topStrut]), makeSpan(["vlist-r"], [depthStrut])];
} else {
rows = [makeSpan(["vlist-r"], [vlist])];
}
var vtable = makeSpan(["vlist-t"], rows);
if (rows.length === 2) {
vtable.classes.push("vlist-t2");
}
vtable.height = maxPos;
vtable.depth = -minPos;
return vtable;
}; // Glue is a concept from TeX which is a flexible space between elements in | Makes a vertical list by stacking elements and kerns on top of each other.
Allows for many different ways of specifying the positioning method.
See VListParam documentation above. | makeVList ( params , options ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
function defineFunctionBuilders(_ref2) {
var type = _ref2.type,
htmlBuilder = _ref2.htmlBuilder,
mathmlBuilder = _ref2.mathmlBuilder;
defineFunction({
type: type,
names: [],
props: {
numArgs: 0
},
handler: function handler() {
throw new Error('Should never be called.');
},
htmlBuilder: htmlBuilder,
mathmlBuilder: mathmlBuilder
});
} | Use this to register only the HTML and MathML builders for a function (e.g.
if the function's ParseNode is generated in Parser.js rather than via a
stand-alone handler provided to `defineFunction`). | defineFunctionBuilders ( _ref2 ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var buildExpression = function buildExpression(expression, options, isRealGroup, surrounding) {
if (surrounding === void 0) {
surrounding = [null, null];
}
// Parse expressions into `groups`.
var groups = [];
for (var i = 0; i < expression.length; i++) {
var output = buildGroup(expression[i], options);
if (output instanceof DocumentFragment) {
var children = output.children;
groups.push.apply(groups, children);
} else {
groups.push(output);
}
} // Combine consecutive domTree.symbolNodes into a single symbolNode.
buildCommon.tryCombineChars(groups); // If `expression` is a partial group, let the parent handle spacings
// to avoid processing groups multiple times.
if (!isRealGroup) {
return groups;
}
var glueOptions = options;
if (expression.length === 1) {
var node = expression[0];
if (node.type === "sizing") {
glueOptions = options.havingSize(node.size);
} else if (node.type === "styling") {
glueOptions = options.havingStyle(styleMap[node.style]);
}
} // Dummy spans for determining spacings between surrounding atoms.
// If `expression` has no atoms on the left or right, class "leftmost"
// or "rightmost", respectively, is used to indicate it.
var dummyPrev = buildHTML_makeSpan([surrounding[0] || "leftmost"], [], options);
var dummyNext = buildHTML_makeSpan([surrounding[1] || "rightmost"], [], options); // TODO: These code assumes that a node's math class is the first element
// of its `classes` array. A later cleanup should ensure this, for
// instance by changing the signature of `makeSpan`.
// Before determining what spaces to insert, perform bin cancellation.
// Binary operators change to ordinary symbols in some contexts.
var isRoot = isRealGroup === "root";
traverseNonSpaceNodes(groups, function (node, prev) {
var prevType = prev.classes[0];
var type = node.classes[0];
if (prevType === "mbin" && utils.contains(binRightCanceller, type)) {
prev.classes[0] = "mord";
} else if (type === "mbin" && utils.contains(binLeftCanceller, prevType)) {
node.classes[0] = "mord";
}
}, {
node: dummyPrev
}, dummyNext, isRoot);
traverseNonSpaceNodes(groups, function (node, prev) {
var prevType = getTypeOfDomTree(prev);
var type = getTypeOfDomTree(node); // 'mtight' indicates that the node is script or scriptscript style.
var space = prevType && type ? node.hasClass("mtight") ? tightSpacings[prevType][type] : spacings[prevType][type] : null;
if (space) {
// Insert glue (spacing) after the `prev`.
return buildCommon.makeGlue(space, glueOptions);
}
}, {
node: dummyPrev
}, dummyNext, isRoot);
return groups;
}; // Depth-first traverse non-space `nodes`, calling `callback` with the current and | Take a list of nodes, build them in order, and return a list of the built
nodes. documentFragments are flattened into their contents, so the
returned list contains no fragments. `isRealGroup` is true if `expression`
is a real group (no atoms will be added on either side), as opposed to
a partial group (e.g. one created by \color). `surrounding` is an array
consisting type of nodes that will be added to the left and right. | buildExpression ( expression , options , isRealGroup , surrounding ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var buildGroup = function buildGroup(group, options, baseOptions) {
if (!group) {
return buildHTML_makeSpan();
}
if (_htmlGroupBuilders[group.type]) {
// Call the groupBuilders function
// $FlowFixMe
var groupNode = _htmlGroupBuilders[group.type](group, options); // If the size changed between the parent and the current group, account
// for that size difference.
if (baseOptions && options.size !== baseOptions.size) {
groupNode = buildHTML_makeSpan(options.sizingClasses(baseOptions), [groupNode], options);
var multiplier = options.sizeMultiplier / baseOptions.sizeMultiplier;
groupNode.height *= multiplier;
groupNode.depth *= multiplier;
}
return groupNode;
} else {
throw new src_ParseError("Got group of unknown type: '" + group.type + "'");
}
}; | buildGroup is the function that takes a group and calls the correct groupType
function for it. It also handles the interaction of size and style changes
between parents and children. | buildGroup ( group , options , baseOptions ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
function buildHTMLUnbreakable(children, options) {
// Compute height and depth of this chunk.
var body = buildHTML_makeSpan(["base"], children, options); // Add strut, which ensures that the top of the HTML element falls at
// the height of the expression, and the bottom of the HTML element
// falls at the depth of the expression.
var strut = buildHTML_makeSpan(["strut"]);
strut.style.height = makeEm(body.height + body.depth);
if (body.depth) {
strut.style.verticalAlign = makeEm(-body.depth);
}
body.children.unshift(strut);
return body;
} | Combine an array of HTML DOM nodes (e.g., the output of `buildExpression`)
into an unbreakable HTML node of class .base, with proper struts to
guarantee correct vertical extent. `buildHTML` calls this repeatedly to
make up the entire expression as a sequence of unbreakable units. | buildHTMLUnbreakable ( children , options ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
function buildHTML(tree, options) {
// Strip off outer tag wrapper for processing below.
var tag = null;
if (tree.length === 1 && tree[0].type === "tag") {
tag = tree[0].tag;
tree = tree[0].body;
} // Build the expression contained in the tree
var expression = buildExpression(tree, options, "root");
var eqnNum;
if (expression.length === 2 && expression[1].hasClass("tag")) {
// An environment with automatic equation numbers, e.g. {gather}.
eqnNum = expression.pop();
}
var children = []; // Create one base node for each chunk between potential line breaks.
// The TeXBook [p.173] says "A formula will be broken only after a
// relation symbol like $=$ or $<$ or $\rightarrow$, or after a binary
// operation symbol like $+$ or $-$ or $\times$, where the relation or
// binary operation is on the ``outer level'' of the formula (i.e., not
// enclosed in {...} and not part of an \over construction)."
var parts = [];
for (var i = 0; i < expression.length; i++) {
parts.push(expression[i]);
if (expression[i].hasClass("mbin") || expression[i].hasClass("mrel") || expression[i].hasClass("allowbreak")) {
// Put any post-operator glue on same line as operator.
// Watch for \nobreak along the way, and stop at \newline.
var nobreak = false;
while (i < expression.length - 1 && expression[i + 1].hasClass("mspace") && !expression[i + 1].hasClass("newline")) {
i++;
parts.push(expression[i]);
if (expression[i].hasClass("nobreak")) {
nobreak = true;
}
} // Don't allow break if \nobreak among the post-operator glue.
if (!nobreak) {
children.push(buildHTMLUnbreakable(parts, options));
parts = [];
}
} else if (expression[i].hasClass("newline")) {
// Write the line except the newline
parts.pop();
if (parts.length > 0) {
children.push(buildHTMLUnbreakable(parts, options));
parts = [];
} // Put the newline at the top level
children.push(expression[i]);
}
}
if (parts.length > 0) {
children.push(buildHTMLUnbreakable(parts, options));
} // Now, if there was a tag, build it too and append it as a final child.
var tagChild;
if (tag) {
tagChild = buildHTMLUnbreakable(buildExpression(tag, options, true));
tagChild.classes = ["tag"];
children.push(tagChild);
} else if (eqnNum) {
children.push(eqnNum);
}
var htmlNode = buildHTML_makeSpan(["katex-html"], children);
htmlNode.setAttribute("aria-hidden", "true"); // Adjust the strut of the tag to be the maximum height of all children
// (the height of the enclosing htmlNode) for proper vertical alignment.
if (tagChild) {
var strut = tagChild.children[0];
strut.style.height = makeEm(htmlNode.height + htmlNode.depth);
if (htmlNode.depth) {
strut.style.verticalAlign = makeEm(-htmlNode.depth);
}
}
return htmlNode;
} | Take an entire parse tree, and build it into an appropriate set of HTML
nodes. | buildHTML ( tree , options ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
function newDocumentFragment(children) {
return new DocumentFragment(children);
} | These objects store data about MathML nodes. This is the MathML equivalent
of the types in domTree.js. Since MathML handles its own rendering, and
since we're mainly using MathML to improve accessibility, we don't manage
any of the styling state that the plain DOM nodes do.
The `toNode` and `toMarkup` functions work similarly to how they do in
domTree.js, creating namespaced DOM nodes and HTML text markup respectively. | newDocumentFragment ( children ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var MathNode = /*#__PURE__*/function () {
function MathNode(type, children, classes) {
this.type = void 0;
this.attributes = void 0;
this.children = void 0;
this.classes = void 0;
this.type = type;
this.attributes = {};
this.children = children || [];
this.classes = classes || [];
}
/**
* Sets an attribute on a MathML node. MathML depends on attributes to convey a
* semantic content, so this is used heavily.
*/
var _proto = MathNode.prototype;
_proto.setAttribute = function setAttribute(name, value) {
this.attributes[name] = value;
}
/**
* Gets an attribute on a MathML node.
*/
;
_proto.getAttribute = function getAttribute(name) {
return this.attributes[name];
}
/**
* Converts the math node into a MathML-namespaced DOM element.
*/
;
_proto.toNode = function toNode() {
var node = document.createElementNS("http://www.w3.org/1998/Math/MathML", this.type);
for (var attr in this.attributes) {
if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
node.setAttribute(attr, this.attributes[attr]);
}
}
if (this.classes.length > 0) {
node.className = createClass(this.classes);
}
for (var i = 0; i < this.children.length; i++) {
node.appendChild(this.children[i].toNode());
}
return node;
}
/**
* Converts the math node into an HTML markup string.
*/
;
_proto.toMarkup = function toMarkup() {
var markup = "<" + this.type; // Add the attributes
for (var attr in this.attributes) {
if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
markup += " " + attr + "=\"";
markup += utils.escape(this.attributes[attr]);
markup += "\"";
}
}
if (this.classes.length > 0) {
markup += " class =\"" + utils.escape(createClass(this.classes)) + "\"";
}
markup += ">";
for (var i = 0; i < this.children.length; i++) {
markup += this.children[i].toMarkup();
}
markup += "</" + this.type + ">";
return markup;
}
/**
* Converts the math node into a string, similar to innerText, but escaped.
*/
;
_proto.toText = function toText() {
return this.children.map(function (child) {
return child.toText();
}).join("");
};
return MathNode;
}(); | This node represents a general purpose MathML node of any type. The
constructor requires the type of node to create (for example, `"mo"` or
`"mspace"`, corresponding to `<mo>` and `<mspace>` tags). | MathNode ( ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var TextNode = /*#__PURE__*/function () {
function TextNode(text) {
this.text = void 0;
this.text = text;
}
/**
* Converts the text node into a DOM text node.
*/
var _proto2 = TextNode.prototype;
_proto2.toNode = function toNode() {
return document.createTextNode(this.text);
}
/**
* Converts the text node into escaped HTML markup
* (representing the text itself).
*/
;
_proto2.toMarkup = function toMarkup() {
return utils.escape(this.toText());
}
/**
* Converts the text node into a string
* (representing the text itself).
*/
;
_proto2.toText = function toText() {
return this.text;
};
return TextNode;
}(); | This node represents a piece of text. | TextNode ( ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
function SpaceNode(width) {
this.width = void 0;
this.character = void 0;
this.width = width; // See https://www.w3.org/TR/2000/WD-MathML2-20000328/chapter6.html
// for a table of space-like characters. We use Unicode
// representations instead of &LongNames; as it's not clear how to
// make the latter via document.createTextNode.
if (width >= 0.05555 && width <= 0.05556) {
this.character = "\u200A"; //  
} else if (width >= 0.1666 && width <= 0.1667) {
this.character = "\u2009"; //  
} else if (width >= 0.2222 && width <= 0.2223) {
this.character = "\u2005"; //  
} else if (width >= 0.2777 && width <= 0.2778) {
this.character = "\u2005\u200A"; //   
} else if (width >= -0.05556 && width <= -0.05555) {
this.character = "\u200A\u2063"; // ​
} else if (width >= -0.1667 && width <= -0.1666) {
this.character = "\u2009\u2063"; // ​
} else if (width >= -0.2223 && width <= -0.2222) {
this.character = "\u205F\u2063"; // ​
} else if (width >= -0.2778 && width <= -0.2777) {
this.character = "\u2005\u2063"; // ​
} else {
this.character = null;
}
} | Create a Space node with width given in CSS ems. | SpaceNode ( width ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var SpaceNode = /*#__PURE__*/function () {
/**
* Create a Space node with width given in CSS ems.
*/
function SpaceNode(width) {
this.width = void 0;
this.character = void 0;
this.width = width; // See https://www.w3.org/TR/2000/WD-MathML2-20000328/chapter6.html
// for a table of space-like characters. We use Unicode
// representations instead of &LongNames; as it's not clear how to
// make the latter via document.createTextNode.
if (width >= 0.05555 && width <= 0.05556) {
this.character = "\u200A"; //  
} else if (width >= 0.1666 && width <= 0.1667) {
this.character = "\u2009"; //  
} else if (width >= 0.2222 && width <= 0.2223) {
this.character = "\u2005"; //  
} else if (width >= 0.2777 && width <= 0.2778) {
this.character = "\u2005\u200A"; //   
} else if (width >= -0.05556 && width <= -0.05555) {
this.character = "\u200A\u2063"; // ​
} else if (width >= -0.1667 && width <= -0.1666) {
this.character = "\u2009\u2063"; // ​
} else if (width >= -0.2223 && width <= -0.2222) {
this.character = "\u205F\u2063"; // ​
} else if (width >= -0.2778 && width <= -0.2777) {
this.character = "\u2005\u2063"; // ​
} else {
this.character = null;
}
}
/**
* Converts the math node into a MathML-namespaced DOM element.
*/
var _proto3 = SpaceNode.prototype;
_proto3.toNode = function toNode() {
if (this.character) {
return document.createTextNode(this.character);
} else {
var node = document.createElementNS("http://www.w3.org/1998/Math/MathML", "mspace");
node.setAttribute("width", makeEm(this.width));
return node;
}
}
/**
* Converts the math node into an HTML markup string.
*/
;
_proto3.toMarkup = function toMarkup() {
if (this.character) {
return "<mtext>" + this.character + "</mtext>";
} else {
return "<mspace width=\"" + makeEm(this.width) + "\"/>";
}
}
/**
* Converts the math node into a string, similar to innerText.
*/
;
_proto3.toText = function toText() {
if (this.character) {
return this.character;
} else {
return " ";
}
};
return SpaceNode;
}(); | This node represents a space, but may render as <mspace.../> or as text,
depending on the width. | SpaceNode ( ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var makeText = function makeText(text, mode, options) {
if (src_symbols[mode][text] && src_symbols[mode][text].replace && text.charCodeAt(0) !== 0xD835 && !(ligatures.hasOwnProperty(text) && options && (options.fontFamily && options.fontFamily.slice(4, 6) === "tt" || options.font && options.font.slice(4, 6) === "tt"))) {
text = src_symbols[mode][text].replace;
}
return new mathMLTree.TextNode(text);
}; | Takes a symbol and converts it into a MathML text node after performing
optional replacement from symbols.js. | makeText ( text , mode , options ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var makeRow = function makeRow(body) {
if (body.length === 1) {
return body[0];
} else {
return new mathMLTree.MathNode("mrow", body);
}
}; | Wrap the given array of nodes in an <mrow> node if needed, i.e.,
unless the array has length 1. Always returns a single node. | makeRow ( body ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var getVariant = function getVariant(group, options) {
// Handle \text... font specifiers as best we can.
// MathML has a limited list of allowable mathvariant specifiers; see
// https://www.w3.org/TR/MathML3/chapter3.html#presm.commatt
if (options.fontFamily === "texttt") {
return "monospace";
} else if (options.fontFamily === "textsf") {
if (options.fontShape === "textit" && options.fontWeight === "textbf") {
return "sans-serif-bold-italic";
} else if (options.fontShape === "textit") {
return "sans-serif-italic";
} else if (options.fontWeight === "textbf") {
return "bold-sans-serif";
} else {
return "sans-serif";
}
} else if (options.fontShape === "textit" && options.fontWeight === "textbf") {
return "bold-italic";
} else if (options.fontShape === "textit") {
return "italic";
} else if (options.fontWeight === "textbf") {
return "bold";
}
var font = options.font;
if (!font || font === "mathnormal") {
return null;
}
var mode = group.mode;
if (font === "mathit") {
return "italic";
} else if (font === "boldsymbol") {
return group.type === "textord" ? "bold" : "bold-italic";
} else if (font === "mathbf") {
return "bold";
} else if (font === "mathbb") {
return "double-struck";
} else if (font === "mathfrak") {
return "fraktur";
} else if (font === "mathscr" || font === "mathcal") {
// MathML makes no distinction between script and calligraphic
return "script";
} else if (font === "mathsf") {
return "sans-serif";
} else if (font === "mathtt") {
return "monospace";
}
var text = group.text;
if (utils.contains(["\\imath", "\\jmath"], text)) {
return null;
}
if (src_symbols[mode][text] && src_symbols[mode][text].replace) {
text = src_symbols[mode][text].replace;
}
var fontName = buildCommon.fontMap[font].fontName;
if (getCharacterMetrics(text, fontName, mode)) {
return buildCommon.fontMap[font].variant;
}
return null;
}; | Returns the math variant as a string or null if none is required. | getVariant ( group , options ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var buildMathML_buildExpression = function buildExpression(expression, options, isOrdgroup) {
if (expression.length === 1) {
var group = buildMathML_buildGroup(expression[0], options);
if (isOrdgroup && group instanceof MathNode && group.type === "mo") {
// When TeX writers want to suppress spacing on an operator,
// they often put the operator by itself inside braces.
group.setAttribute("lspace", "0em");
group.setAttribute("rspace", "0em");
}
return [group];
}
var groups = [];
var lastGroup;
for (var i = 0; i < expression.length; i++) {
var _group = buildMathML_buildGroup(expression[i], options);
if (_group instanceof MathNode && lastGroup instanceof MathNode) {
// Concatenate adjacent <mtext>s
if (_group.type === 'mtext' && lastGroup.type === 'mtext' && _group.getAttribute('mathvariant') === lastGroup.getAttribute('mathvariant')) {
var _lastGroup$children;
(_lastGroup$children = lastGroup.children).push.apply(_lastGroup$children, _group.children);
continue; // Concatenate adjacent <mn>s
} else if (_group.type === 'mn' && lastGroup.type === 'mn') {
var _lastGroup$children2;
(_lastGroup$children2 = lastGroup.children).push.apply(_lastGroup$children2, _group.children);
continue; // Concatenate <mn>...</mn> followed by <mi>.</mi>
} else if (_group.type === 'mi' && _group.children.length === 1 && lastGroup.type === 'mn') {
var child = _group.children[0];
if (child instanceof TextNode && child.text === '.') {
var _lastGroup$children3;
(_lastGroup$children3 = lastGroup.children).push.apply(_lastGroup$children3, _group.children);
continue;
}
} else if (lastGroup.type === 'mi' && lastGroup.children.length === 1) {
var lastChild = lastGroup.children[0];
if (lastChild instanceof TextNode && lastChild.text === "\u0338" && (_group.type === 'mo' || _group.type === 'mi' || _group.type === 'mn')) {
var _child = _group.children[0];
if (_child instanceof TextNode && _child.text.length > 0) {
// Overlay with combining character long solidus
_child.text = _child.text.slice(0, 1) + "\u0338" + _child.text.slice(1);
groups.pop();
}
}
}
}
groups.push(_group);
lastGroup = _group;
}
return groups;
}; | Takes a list of nodes, builds them, and returns a list of the generated
MathML nodes. Also combine consecutive <mtext> outputs into a single
<mtext> tag. | buildExpression ( expression , options , isOrdgroup ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var buildExpressionRow = function buildExpressionRow(expression, options, isOrdgroup) {
return makeRow(buildMathML_buildExpression(expression, options, isOrdgroup));
}; | Equivalent to buildExpression, but wraps the elements in an <mrow>
if there's more than one. Returns a single node instead of an array. | buildExpressionRow ( expression , options , isOrdgroup ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var buildMathML_buildGroup = function buildGroup(group, options) {
if (!group) {
return new mathMLTree.MathNode("mrow");
}
if (_mathmlGroupBuilders[group.type]) {
// Call the groupBuilders function
// $FlowFixMe
var result = _mathmlGroupBuilders[group.type](group, options); // $FlowFixMe
return result;
} else {
throw new src_ParseError("Got group of unknown type: '" + group.type + "'");
}
}; | Takes a group from the parser and calls the appropriate groupBuilders function
on it to produce a MathML node. | buildGroup ( group , options ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
function buildMathML(tree, texExpression, options, isDisplayMode, forMathmlOnly) {
var expression = buildMathML_buildExpression(tree, options); // TODO: Make a pass thru the MathML similar to buildHTML.traverseNonSpaceNodes
// and add spacing nodes. This is necessary only adjacent to math operators
// like \sin or \lim or to subsup elements that contain math operators.
// MathML takes care of the other spacing issues.
// Wrap up the expression in an mrow so it is presented in the semantics
// tag correctly, unless it's a single <mrow> or <mtable>.
var wrapper;
if (expression.length === 1 && expression[0] instanceof MathNode && utils.contains(["mrow", "mtable"], expression[0].type)) {
wrapper = expression[0];
} else {
wrapper = new mathMLTree.MathNode("mrow", expression);
} // Build a TeX annotation of the source
var annotation = new mathMLTree.MathNode("annotation", [new mathMLTree.TextNode(texExpression)]);
annotation.setAttribute("encoding", "application/x-tex");
var semantics = new mathMLTree.MathNode("semantics", [wrapper, annotation]);
var math = new mathMLTree.MathNode("math", [semantics]);
math.setAttribute("xmlns", "http://www.w3.org/1998/Math/MathML");
if (isDisplayMode) {
math.setAttribute("display", "block");
} // You can't style <math> nodes, so we wrap the node in a span.
// NOTE: The span class is not typed to have <math> nodes as children, and
// we don't want to make the children type more generic since the children
// of span are expected to have more fields in `buildHtml` contexts.
var wrapperClass = forMathmlOnly ? "katex" : "katex-mathml"; // $FlowFixMe
return buildCommon.makeSpan([wrapperClass], [math]);
} | Takes a full parse tree and settings and builds a MathML representation of
it. In particular, we put the elements from building the parse tree into a
<semantics> tag so we can also include that TeX source as an annotation.
Note that we actually return a domTree element with a `<math>` inside it so
we can do appropriate styling. | buildMathML ( tree , texExpression , options , isDisplayMode , forMathmlOnly ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
function assertNodeType(node, type) {
if (!node || node.type !== type) {
throw new Error("Expected node of type " + type + ", but got " + (node ? "node of type " + node.type : String(node)));
} // $FlowFixMe, >=0.125
return node;
} | Asserts that the node is of the given type and returns it with stricter
typing. Throws if the node's type does not match. | assertNodeType ( node , type ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
function assertSymbolNodeType(node) {
var typedNode = checkSymbolNodeType(node);
if (!typedNode) {
throw new Error("Expected node of symbol group type, but got " + (node ? "node of type " + node.type : String(node)));
}
return typedNode;
} | Returns the node more strictly typed iff it is of the given type. Otherwise,
returns null. | assertSymbolNodeType ( node ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
SourceLocation.range = function range(first, second) {
if (!second) {
return first && first.loc;
} else if (!first || !first.loc || !second.loc || first.loc.lexer !== second.loc.lexer) {
return null;
} else {
return new SourceLocation(first.loc.lexer, first.loc.start, second.loc.end);
} | Merges two `SourceLocation`s from location providers, given they are
provided in order of appearance.
- Returns the first one's location if only the first is provided.
- Returns a merged range of the first and the last if both are provided
and their lexers match.
- Otherwise, returns null. | range ( first , second ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
;
_proto.isDefined = function isDefined(name) { | Determine whether a command is currently "defined" (has some
functionality), meaning that it's a macro (in the current group),
a function, a symbol, or one of the special commands listed in
`implicitCommands`. | isDefined ( name ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
;
_proto.isExpandable = function isExpandable(name) {
var macro = this.macros.get(name); | Determine whether a command is expandable. | isExpandable ( name ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
var _proto = Parser.prototype;
_proto.expect = function expect(text, consume) {
if (consume === void 0) {
consume = true;
}
if (this.fetch().text !== text) {
throw new src_ParseError("Expected '" + text + "', got '" + this.fetch().text + "'", this.fetch());
}
if (consume) {
this.consume(); | Checks a result to make sure it has the right type, and throws an
appropriate error otherwise. | expect ( text , consume ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
;
_proto.consume = function consume() { | Discards the current lookahead token, considering it consumed. | consume ( ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
;
_proto.fetch = function fetch() {
if (this.nextToken == null) {
this.nextToken = this.gullet.expandNextToken();
}
| Return the current lookahead token, or if there isn't one (at the
beginning, or if the previous lookahead token was consume()d),
fetch the next token as the new lookahead token and return it. | fetch ( ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
;
_proto.switchMode = function switchMode(newMode) {
this.mode = newMode; | Switches between "text" and "math" modes. | switchMode ( newMode ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
;
_proto.subparse = function subparse(tokens) {
// Save the next token from the current job.
var oldToken = this.nextToken;
this.consume(); // Run the new job, terminating it with an excess '}'
this.gullet.pushToken(new Token("}"));
this.gullet.pushTokens(tokens);
var parse = this.parseExpression(false);
this.expect("}"); // Restore the next token from the current job.
this.nextToken = oldToken; | Fully parse a separate sequence of tokens as a separate job.
Tokens should be specified in reverse order, as in a MacroDefinition. | subparse ( tokens ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
;
_proto.handleInfixNodes = function handleInfixNodes(body) {
var overIndex = -1;
var funcName;
for (var i = 0; i < body.length; i++) {
if (body[i].type === "infix") {
if (overIndex !== -1) {
throw new src_ParseError("only one infix operator per group", body[i].token);
}
overIndex = i;
funcName = body[i].replaceWith;
}
}
if (overIndex !== -1 && funcName) {
var numerNode;
var denomNode;
var numerBody = body.slice(0, overIndex);
var denomBody = body.slice(overIndex + 1);
if (numerBody.length === 1 && numerBody[0].type === "ordgroup") {
numerNode = numerBody[0];
} else {
numerNode = {
type: "ordgroup",
mode: this.mode,
body: numerBody
};
}
if (denomBody.length === 1 && denomBody[0].type === "ordgroup") {
denomNode = denomBody[0];
} else {
denomNode = {
type: "ordgroup",
mode: this.mode,
body: denomBody
};
}
var node;
if (funcName === "\\\\abovefrac") {
node = this.callFunction(funcName, [numerNode, body[overIndex], denomNode], []);
} else {
node = this.callFunction(funcName, [numerNode, denomNode], []);
}
return [node];
} else {
return body; | Rewrites infix operators such as \over with corresponding commands such
as \frac.
There can only be one infix operator per group. If there's more than one
then the expression is ambiguous. This can be resolved by adding {}. | handleInfixNodes ( body ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
;
_proto.handleSupSubscript = function handleSupSubscript(name // For error reporting.
) {
var symbolToken = this.fetch();
var symbol = symbolToken.text;
this.consume();
this.consumeSpaces(); // ignore spaces before sup/subscript argument
var group = this.parseGroup(name);
if (!group) {
throw new src_ParseError("Expected group after '" + symbol + "'", symbolToken);
}
| Handle a subscript or superscript with nice errors. | handleSupSubscript ( name ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
;
_proto.formatUnsupportedCmd = function formatUnsupportedCmd(text) {
var textordArray = [];
for (var i = 0; i < text.length; i++) {
textordArray.push({
type: "textord",
mode: "text",
text: text[i]
});
}
var textNode = {
type: "text",
mode: this.mode,
body: textordArray
};
var colorNode = {
type: "color",
mode: this.mode,
color: this.settings.errorColor,
body: [textNode]
}; | Converts the textual input of an unsupported command into a text node
contained within a color node whose color is determined by errorColor | formatUnsupportedCmd ( text ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
;
_proto.parseAtom = function parseAtom(breakOnTokenText) {
// The body of an atom is an implicit group, so that things like
// \left(x\right)^2 work correctly.
var base = this.parseGroup("atom", breakOnTokenText); // In text mode, we don't have superscripts or subscripts
if (this.mode === "text") {
return base;
} // Note that base may be empty (i.e. null) at this point.
var superscript;
var subscript;
while (true) {
// Guaranteed in math mode, so eat any spaces first.
this.consumeSpaces(); // Lex the first token
var lex = this.fetch();
if (lex.text === "\\limits" || lex.text === "\\nolimits") {
// We got a limit control
if (base && base.type === "op") {
var limits = lex.text === "\\limits";
base.limits = limits;
base.alwaysHandleSupSub = true;
} else if (base && base.type === "operatorname") {
if (base.alwaysHandleSupSub) {
base.limits = lex.text === "\\limits";
}
} else {
throw new src_ParseError("Limit controls must follow a math operator", lex);
}
this.consume();
} else if (lex.text === "^") {
// We got a superscript start
if (superscript) {
throw new src_ParseError("Double superscript", lex);
}
superscript = this.handleSupSubscript("superscript");
} else if (lex.text === "_") {
// We got a subscript start
if (subscript) {
throw new src_ParseError("Double subscript", lex);
}
subscript = this.handleSupSubscript("subscript");
} else if (lex.text === "'") {
// We got a prime
if (superscript) {
throw new src_ParseError("Double superscript", lex);
}
var prime = {
type: "textord",
mode: this.mode,
text: "\\prime"
}; // Many primes can be grouped together, so we handle this here
var primes = [prime];
this.consume(); // Keep lexing tokens until we get something that's not a prime
while (this.fetch().text === "'") {
// For each one, add another prime to the list
primes.push(prime);
this.consume();
} // If there's a superscript following the primes, combine that
// superscript in with the primes.
if (this.fetch().text === "^") {
primes.push(this.handleSupSubscript("superscript"));
} // Put everything into an ordgroup as the superscript
superscript = {
type: "ordgroup",
mode: this.mode,
body: primes
};
} else if (uSubsAndSups[lex.text]) {
// A Unicode subscript or superscript character.
// We treat these similarly to the unicode-math package.
// So we render a string of Unicode (sub|super)scripts the
// same as a (sub|super)script of regular characters.
var str = uSubsAndSups[lex.text];
var isSub = unicodeSubRegEx.test(lex.text);
this.consume(); // Continue fetching tokens to fill out the string.
while (true) {
var token = this.fetch().text;
if (!uSubsAndSups[token]) {
break;
}
if (unicodeSubRegEx.test(token) !== isSub) {
break;
}
this.consume();
str += uSubsAndSups[token];
} // Now create a (sub|super)script.
var body = new Parser(str, this.settings).parse();
if (isSub) {
subscript = {
type: "ordgroup",
mode: "math",
body: body
};
} else {
superscript = {
type: "ordgroup",
mode: "math",
body: body
};
}
} else {
// If it wasn't ^, _, or ', stop parsing super/subscripts
break;
}
} // Base must be set if superscript or subscript are set per logic above,
// but need to check here for type check to pass.
if (superscript || subscript) {
// If we got either a superscript or subscript, create a supsub
return {
type: "supsub",
mode: this.mode,
base: base,
sup: superscript,
sub: subscript
};
} else {
// Otherwise return the original body
return base; | Parses a group with optional super/subscripts. | parseAtom ( breakOnTokenText ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
;
_proto.callFunction = function callFunction(name, args, optArgs, token, breakOnTokenText) {
var context = {
funcName: name,
parser: this,
token: token,
breakOnTokenText: breakOnTokenText
};
var func = src_functions[name];
if (func && func.handler) {
return func.handler(context, args, optArgs);
} else {
throw new src_ParseError("No function handler for " + name); | Call a function handler with a suitable context and arguments. | callFunction ( name , args , optArgs , token , breakOnTokenText ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
;
_proto.parseArguments = function parseArguments(func, // Should look like "\name" or "\begin{name}".
funcData) {
var totalArgs = funcData.numArgs + funcData.numOptionalArgs;
if (totalArgs === 0) {
return {
args: [],
optArgs: []
};
}
var args = [];
var optArgs = [];
for (var i = 0; i < totalArgs; i++) {
var argType = funcData.argTypes && funcData.argTypes[i];
var isOptional = i < funcData.numOptionalArgs;
if (funcData.primitive && argType == null || // \sqrt expands into primitive if optional argument doesn't exist
funcData.type === "sqrt" && i === 1 && optArgs[0] == null) {
argType = "primitive";
}
var arg = this.parseGroupOfType("argument to '" + func + "'", argType, isOptional);
if (isOptional) {
optArgs.push(arg);
} else if (arg != null) {
args.push(arg);
} else {
// should be unreachable
throw new src_ParseError("Null argument, please report this as a bug");
}
}
return {
args: args,
optArgs: optArgs | Parses the arguments of a function or environment | parseArguments ( func , funcData ) | javascript | colinwilson/lotusdocs | assets/docs/js/katex.js | https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js | MIT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.