code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
function View(name, options) {
var opts = options || {};
this.defaultEngine = opts.defaultEngine;
this.ext = extname(name);
this.name = name;
this.root = opts.root;
if (!this.ext && !this.defaultEngine) {
throw new Error('No default engine was specified and no extension was provided.');
}
var fileName = name;
if (!this.ext) {
// get extension from default engine name
this.ext = this.defaultEngine[0] !== '.'
? '.' + this.defaultEngine
: this.defaultEngine;
fileName += this.ext;
}
if (!opts.engines[this.ext]) {
// load engine
var mod = this.ext.slice(1)
debug('require "%s"', mod)
// default engine export
var fn = require(mod).__express
if (typeof fn !== 'function') {
throw new Error('Module "' + mod + '" does not provide a view engine.')
}
opts.engines[this.ext] = fn
}
// store loaded engine
this.engine = opts.engines[this.ext];
// lookup path
this.path = this.lookup(fileName);
}
|
Initialize a new `View` with the given `name`.
Options:
- `defaultEngine` the default template engine name
- `engines` template engine require() cache
- `root` root path for view lookup
@param {string} name
@param {object} options
@public
|
View
|
javascript
|
expressjs/express
|
lib/view.js
|
https://github.com/expressjs/express/blob/master/lib/view.js
|
MIT
|
function tryStat(path) {
debug('stat "%s"', path);
try {
return fs.statSync(path);
} catch (e) {
return undefined;
}
}
|
Return a stat, maybe.
@param {string} path
@return {fs.Stats}
@private
|
tryStat
|
javascript
|
expressjs/express
|
lib/view.js
|
https://github.com/expressjs/express/blob/master/lib/view.js
|
MIT
|
function getExpectedClientAddress(server) {
return server.address().address === '::'
? '::ffff:127.0.0.1'
: '127.0.0.1';
}
|
Get the local client address depending on AF_NET of server
|
getExpectedClientAddress
|
javascript
|
expressjs/express
|
test/req.ip.js
|
https://github.com/expressjs/express/blob/master/test/req.ip.js
|
MIT
|
function shouldHaveBody (buf) {
return function (res) {
var body = !Buffer.isBuffer(res.body)
? Buffer.from(res.text)
: res.body
assert.ok(body, 'response has body')
assert.strictEqual(body.toString('hex'), buf.toString('hex'))
}
}
|
Assert that a supertest response has a specific body.
@param {Buffer} buf
@returns {function}
|
shouldHaveBody
|
javascript
|
expressjs/express
|
test/support/utils.js
|
https://github.com/expressjs/express/blob/master/test/support/utils.js
|
MIT
|
function shouldHaveHeader (header) {
return function (res) {
assert.ok((header.toLowerCase() in res.headers), 'should have header ' + header)
}
}
|
Assert that a supertest response does have a header.
@param {string} header Header name to check
@returns {function}
|
shouldHaveHeader
|
javascript
|
expressjs/express
|
test/support/utils.js
|
https://github.com/expressjs/express/blob/master/test/support/utils.js
|
MIT
|
function shouldNotHaveBody () {
return function (res) {
assert.ok(res.text === '' || res.text === undefined)
}
}
|
Assert that a supertest response does not have a body.
@returns {function}
|
shouldNotHaveBody
|
javascript
|
expressjs/express
|
test/support/utils.js
|
https://github.com/expressjs/express/blob/master/test/support/utils.js
|
MIT
|
function shouldNotHaveHeader(header) {
return function (res) {
assert.ok(!(header.toLowerCase() in res.headers), 'should not have header ' + header);
};
}
|
Assert that a supertest response does not have a header.
@param {string} header Header name to check
@returns {function}
|
shouldNotHaveHeader
|
javascript
|
expressjs/express
|
test/support/utils.js
|
https://github.com/expressjs/express/blob/master/test/support/utils.js
|
MIT
|
function getMajorVersion(versionString) {
return versionString.split('.')[0];
}
|
Assert that a supertest response does not have a header.
@param {string} header Header name to check
@returns {function}
|
getMajorVersion
|
javascript
|
expressjs/express
|
test/support/utils.js
|
https://github.com/expressjs/express/blob/master/test/support/utils.js
|
MIT
|
function shouldSkipQuery(versionString) {
// Skipping HTTP QUERY tests below Node 22, QUERY wasn't fully supported by Node until 22
// we could update this implementation to run on supported versions of 21 once they exist
// upstream tracking https://github.com/nodejs/node/issues/51562
// express tracking issue: https://github.com/expressjs/express/issues/5615
return Number(getMajorVersion(versionString)) < 22
}
|
Assert that a supertest response does not have a header.
@param {string} header Header name to check
@returns {function}
|
shouldSkipQuery
|
javascript
|
expressjs/express
|
test/support/utils.js
|
https://github.com/expressjs/express/blob/master/test/support/utils.js
|
MIT
|
unlock = function(e) {
// Create a pool of unlocked HTML5 Audio objects that can
// be used for playing sounds without user interaction. HTML5
// Audio objects must be individually unlocked, as opposed
// to the WebAudio API which only needs a single activation.
// This must occur before WebAudio setup or the source.onended
// event will not fire.
while (self._html5AudioPool.length < self.html5PoolSize) {
try {
var audioNode = new Audio();
// Mark this Audio object as unlocked to ensure it can get returned
// to the unlocked pool when released.
audioNode._unlocked = true;
// Add the audio node to the pool.
self._releaseHtml5Audio(audioNode);
} catch (e) {
self.noAudio = true;
break;
}
}
// Loop through any assigned audio nodes and unlock them.
for (var i=0; i<self._howls.length; i++) {
if (!self._howls[i]._webAudio) {
// Get all of the sounds in this Howl group.
var ids = self._howls[i]._getSoundIds();
// Loop through all sounds and unlock the audio nodes.
for (var j=0; j<ids.length; j++) {
var sound = self._howls[i]._soundById(ids[j]);
if (sound && sound._node && !sound._node._unlocked) {
sound._node._unlocked = true;
sound._node.load();
}
}
}
}
// Fix Android can not play in suspend state.
self._autoResume();
// Create an empty buffer.
var source = self.ctx.createBufferSource();
source.buffer = self._scratchBuffer;
source.connect(self.ctx.destination);
// Play the empty buffer.
if (typeof source.start === 'undefined') {
source.noteOn(0);
} else {
source.start(0);
}
// Calling resume() on a stack initiated by user gesture is what actually unlocks the audio on Android Chrome >= 55.
if (typeof self.ctx.resume === 'function') {
self.ctx.resume();
}
// Setup a timeout to check that we are unlocked on the next event loop.
source.onended = function() {
source.disconnect(0);
// Update the unlocked state and prevent this check from happening again.
self._audioUnlocked = true;
// Remove the touch start listener.
document.removeEventListener('touchstart', unlock, true);
document.removeEventListener('touchend', unlock, true);
document.removeEventListener('click', unlock, true);
document.removeEventListener('keydown', unlock, true);
// Let all sounds know that audio has been unlocked.
for (var i=0; i<self._howls.length; i++) {
self._howls[i]._emit('unlock');
}
};
}
|
Some browsers/devices will only allow audio to be played after a user interaction.
Attempt to automatically unlock audio on the first user interaction.
Concept from: http://paulbakaus.com/tutorials/html5/web-audio-on-ios/
@return {Howler}
|
unlock
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
handleSuspension = function() {
self.state = 'suspended';
if (self._resumeAfterSuspend) {
delete self._resumeAfterSuspend;
self._autoResume();
}
}
|
Automatically suspend the Web Audio AudioContext after no sound has played for 30 seconds.
This saves processing/energy and fixes various browser-specific bugs with audio getting stuck.
@return {Howler}
|
handleSuspension
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
Howl = function(o) {
var self = this;
// Throw an error if no source is provided.
if (!o.src || o.src.length === 0) {
console.error('An array of source files must be passed with any new Howl.');
return;
}
self.init(o);
}
|
Create an audio group controller.
@param {Object} o Passed in properties for this group.
|
Howl
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
setParams = function() {
sound._paused = false;
sound._seek = seek;
sound._start = start;
sound._stop = stop;
sound._loop = !!(sound._loop || self._sprite[sprite][2]);
}
|
Play a sound or resume previous playback.
@param {String/Number} sprite Sprite name for sprite playback or sound id to continue previous.
@param {Boolean} internal Internal Use: true prevents event firing.
@return {Number} Sound ID.
|
setParams
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
playWebAudio = function() {
self._playLock = false;
setParams();
self._refreshBuffer(sound);
// Setup the playback params.
var vol = (sound._muted || self._muted) ? 0 : sound._volume;
node.gain.setValueAtTime(vol, Howler.ctx.currentTime);
sound._playStart = Howler.ctx.currentTime;
// Play the sound using the supported method.
if (typeof node.bufferSource.start === 'undefined') {
sound._loop ? node.bufferSource.noteGrainOn(0, seek, 86400) : node.bufferSource.noteGrainOn(0, seek, duration);
} else {
sound._loop ? node.bufferSource.start(0, seek, 86400) : node.bufferSource.start(0, seek, duration);
}
// Start a new timer if none is present.
if (timeout !== Infinity) {
self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
}
if (!internal) {
setTimeout(function() {
self._emit('play', sound._id);
self._loadQueue();
}, 0);
}
}
|
Play a sound or resume previous playback.
@param {String/Number} sprite Sprite name for sprite playback or sound id to continue previous.
@param {Boolean} internal Internal Use: true prevents event firing.
@return {Number} Sound ID.
|
playWebAudio
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
playHtml5 = function() {
node.currentTime = seek;
node.muted = sound._muted || self._muted || Howler._muted || node.muted;
node.volume = sound._volume * Howler.volume();
node.playbackRate = sound._rate;
// Some browsers will throw an error if this is called without user interaction.
try {
var play = node.play();
// Support older browsers that don't support promises, and thus don't have this issue.
if (play && typeof Promise !== 'undefined' && (play instanceof Promise || typeof play.then === 'function')) {
// Implements a lock to prevent DOMException: The play() request was interrupted by a call to pause().
self._playLock = true;
// Set param values immediately.
setParams();
// Releases the lock and executes queued actions.
play
.then(function() {
self._playLock = false;
node._unlocked = true;
if (!internal) {
self._emit('play', sound._id);
} else {
self._loadQueue();
}
})
.catch(function() {
self._playLock = false;
self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' +
'on mobile devices and Chrome where playback was not within a user interaction.');
// Reset the ended and paused values.
sound._ended = true;
sound._paused = true;
});
} else if (!internal) {
self._playLock = false;
setParams();
self._emit('play', sound._id);
}
// Setting rate before playing won't work in IE, so we set it again here.
node.playbackRate = sound._rate;
// If the node is still paused, then we can assume there was a playback issue.
if (node.paused) {
self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' +
'on mobile devices and Chrome where playback was not within a user interaction.');
return;
}
// Setup the end timer on sprites or listen for the ended event.
if (sprite !== '__default' || sound._loop) {
self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
} else {
self._endTimers[sound._id] = function() {
// Fire ended on this audio node.
self._ended(sound);
// Clear this listener.
node.removeEventListener('ended', self._endTimers[sound._id], false);
};
node.addEventListener('ended', self._endTimers[sound._id], false);
}
} catch (err) {
self._emit('playerror', sound._id, err);
}
}
|
Play a sound or resume previous playback.
@param {String/Number} sprite Sprite name for sprite playback or sound id to continue previous.
@param {Boolean} internal Internal Use: true prevents event firing.
@return {Number} Sound ID.
|
playHtml5
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
listener = function() {
self._state = 'loaded';
// Begin playback.
playHtml5();
// Clear this listener.
node.removeEventListener(Howler._canPlayEvent, listener, false);
}
|
Play a sound or resume previous playback.
@param {String/Number} sprite Sprite name for sprite playback or sound id to continue previous.
@param {Boolean} internal Internal Use: true prevents event firing.
@return {Number} Sound ID.
|
listener
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
seekAndEmit = function() {
// Restart the playback if the sound was playing.
if (playing) {
self.play(id, true);
}
self._emit('seek', id);
}
|
Get/set the seek position of a sound. This method can optionally take 0, 1 or 2 arguments.
seek() -> Returns the first sound node's current seek position.
seek(id) -> Returns the sound id's current seek position.
seek(seek) -> Sets the seek position of the first sound node.
seek(seek, id) -> Sets the seek position of passed sound id.
@return {Howl/Number} Returns self or the current seek position.
|
seekAndEmit
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
emitSeek = function() {
if (!self._playLock) {
seekAndEmit();
} else {
setTimeout(emitSeek, 0);
}
}
|
Get/set the seek position of a sound. This method can optionally take 0, 1 or 2 arguments.
seek() -> Returns the first sound node's current seek position.
seek(id) -> Returns the sound id's current seek position.
seek(seek) -> Sets the seek position of the first sound node.
seek(seek, id) -> Sets the seek position of passed sound id.
@return {Howl/Number} Returns self or the current seek position.
|
emitSeek
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
Sound = function(howl) {
this._parent = howl;
this.init();
}
|
Setup the sound object, which each node attached to a Howl group is contained in.
@param {Object} howl The Howl parent group.
|
Sound
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
loadBuffer = function(self) {
var url = self._src;
// Check if the buffer has already been cached and use it instead.
if (cache[url]) {
// Set the duration from the cache.
self._duration = cache[url].duration;
// Load the sound into this Howl.
loadSound(self);
return;
}
if (/^data:[^;]+;base64,/.test(url)) {
// Decode the base64 data URI without XHR, since some browsers don't support it.
var data = atob(url.split(',')[1]);
var dataView = new Uint8Array(data.length);
for (var i=0; i<data.length; ++i) {
dataView[i] = data.charCodeAt(i);
}
decodeAudioData(dataView.buffer, self);
} else {
// Load the buffer from the URL.
var xhr = new XMLHttpRequest();
xhr.open(self._xhr.method, url, true);
xhr.withCredentials = self._xhr.withCredentials;
xhr.responseType = 'arraybuffer';
// Apply any custom headers to the request.
if (self._xhr.headers) {
Object.keys(self._xhr.headers).forEach(function(key) {
xhr.setRequestHeader(key, self._xhr.headers[key]);
});
}
xhr.onload = function() {
// Make sure we get a successful response back.
var code = (xhr.status + '')[0];
if (code !== '0' && code !== '2' && code !== '3') {
self._emit('loaderror', null, 'Failed loading audio file with status: ' + xhr.status + '.');
return;
}
decodeAudioData(xhr.response, self);
};
xhr.onerror = function() {
// If there is an error, switch to HTML5 Audio.
if (self._webAudio) {
self._html5 = true;
self._webAudio = false;
self._sounds = [];
delete cache[url];
self.load();
}
};
safeXhrSend(xhr);
}
}
|
Buffer a sound from URL, Data URI or cache and decode to audio source (Web Audio API).
@param {Howl} self
|
loadBuffer
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
safeXhrSend = function(xhr) {
try {
xhr.send();
} catch (e) {
xhr.onerror();
}
}
|
Send the XHR request wrapped in a try/catch.
@param {Object} xhr XHR to send.
|
safeXhrSend
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
decodeAudioData = function(arraybuffer, self) {
// Fire a load error if something broke.
var error = function() {
self._emit('loaderror', null, 'Decoding audio data failed.');
};
// Load the sound on success.
var success = function(buffer) {
if (buffer && self._sounds.length > 0) {
cache[self._src] = buffer;
loadSound(self, buffer);
} else {
error();
}
};
// Decode the buffer into an audio source.
if (typeof Promise !== 'undefined' && Howler.ctx.decodeAudioData.length === 1) {
Howler.ctx.decodeAudioData(arraybuffer).then(success).catch(error);
} else {
Howler.ctx.decodeAudioData(arraybuffer, success, error);
}
}
|
Decode audio data from an array buffer.
@param {ArrayBuffer} arraybuffer The audio data.
@param {Howl} self
|
decodeAudioData
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
error = function() {
self._emit('loaderror', null, 'Decoding audio data failed.');
}
|
Decode audio data from an array buffer.
@param {ArrayBuffer} arraybuffer The audio data.
@param {Howl} self
|
error
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
success = function(buffer) {
if (buffer && self._sounds.length > 0) {
cache[self._src] = buffer;
loadSound(self, buffer);
} else {
error();
}
}
|
Decode audio data from an array buffer.
@param {ArrayBuffer} arraybuffer The audio data.
@param {Howl} self
|
success
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
loadSound = function(self, buffer) {
// Set the duration.
if (buffer && !self._duration) {
self._duration = buffer.duration;
}
// Setup a sprite if none is defined.
if (Object.keys(self._sprite).length === 0) {
self._sprite = {__default: [0, self._duration * 1000]};
}
// Fire the loaded event.
if (self._state !== 'loaded') {
self._state = 'loaded';
self._emit('load');
self._loadQueue();
}
}
|
Sound is now loaded, so finish setting everything up and fire the loaded event.
@param {Howl} self
@param {Object} buffer The decoded buffer sound source.
|
loadSound
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
setupAudioContext = function() {
// If we have already detected that Web Audio isn't supported, don't run this step again.
if (!Howler.usingWebAudio) {
return;
}
// Check if we are using Web Audio and setup the AudioContext if we are.
try {
if (typeof AudioContext !== 'undefined') {
Howler.ctx = new AudioContext();
} else if (typeof webkitAudioContext !== 'undefined') {
Howler.ctx = new webkitAudioContext();
} else {
Howler.usingWebAudio = false;
}
} catch(e) {
Howler.usingWebAudio = false;
}
// If the audio context creation still failed, set using web audio to false.
if (!Howler.ctx) {
Howler.usingWebAudio = false;
}
// Check if a webview is being used on iOS8 or earlier (rather than the browser).
// If it is, disable Web Audio as it causes crashing.
var iOS = (/iP(hone|od|ad)/.test(Howler._navigator && Howler._navigator.platform));
var appVersion = Howler._navigator && Howler._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
var version = appVersion ? parseInt(appVersion[1], 10) : null;
if (iOS && version && version < 9) {
var safari = /safari/.test(Howler._navigator && Howler._navigator.userAgent.toLowerCase());
if (Howler._navigator && !safari) {
Howler.usingWebAudio = false;
}
}
// Create and expose the master GainNode when using Web Audio (useful for plugins or advanced usage).
if (Howler.usingWebAudio) {
Howler.masterGain = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain();
Howler.masterGain.gain.setValueAtTime(Howler._muted ? 0 : Howler._volume, Howler.ctx.currentTime);
Howler.masterGain.connect(Howler.ctx.destination);
}
// Re-run the setup on Howler.
Howler._setup();
}
|
Setup the audio context when available, or switch to HTML5 Audio mode.
|
setupAudioContext
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
setupPanner = function(sound, type) {
type = type || 'spatial';
// Create the new panner node.
if (type === 'spatial') {
sound._panner = Howler.ctx.createPanner();
sound._panner.coneInnerAngle = sound._pannerAttr.coneInnerAngle;
sound._panner.coneOuterAngle = sound._pannerAttr.coneOuterAngle;
sound._panner.coneOuterGain = sound._pannerAttr.coneOuterGain;
sound._panner.distanceModel = sound._pannerAttr.distanceModel;
sound._panner.maxDistance = sound._pannerAttr.maxDistance;
sound._panner.refDistance = sound._pannerAttr.refDistance;
sound._panner.rolloffFactor = sound._pannerAttr.rolloffFactor;
sound._panner.panningModel = sound._pannerAttr.panningModel;
if (typeof sound._panner.positionX !== 'undefined') {
sound._panner.positionX.setValueAtTime(sound._pos[0], Howler.ctx.currentTime);
sound._panner.positionY.setValueAtTime(sound._pos[1], Howler.ctx.currentTime);
sound._panner.positionZ.setValueAtTime(sound._pos[2], Howler.ctx.currentTime);
} else {
sound._panner.setPosition(sound._pos[0], sound._pos[1], sound._pos[2]);
}
if (typeof sound._panner.orientationX !== 'undefined') {
sound._panner.orientationX.setValueAtTime(sound._orientation[0], Howler.ctx.currentTime);
sound._panner.orientationY.setValueAtTime(sound._orientation[1], Howler.ctx.currentTime);
sound._panner.orientationZ.setValueAtTime(sound._orientation[2], Howler.ctx.currentTime);
} else {
sound._panner.setOrientation(sound._orientation[0], sound._orientation[1], sound._orientation[2]);
}
} else {
sound._panner = Howler.ctx.createStereoPanner();
sound._panner.pan.setValueAtTime(sound._stereo, Howler.ctx.currentTime);
}
sound._panner.connect(sound._node);
// Update the connections.
if (!sound._paused) {
sound._parent.pause(sound._id, true).play(sound._id, true);
}
}
|
Create a new panner node and save it on the sound.
@param {Sound} sound Specific sound to setup panning on.
@param {String} type Type of panner to create: 'stereo' or 'spatial'.
|
setupPanner
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
Camera = function(resolution) {
this.width = canvas.width = window.innerWidth;
this.height = canvas.height = window.innerHeight;
this.resolution = resolution;
this.spacing = this.width / resolution;
this.focalLen = this.height / this.width;
this.range = isMobile ? 9 : 18;
this.lightRange = 9;
this.scale = canvas.width / 1200;
}
|
Camera that draws everything you see on the screen from the player's perspective.
@param {Number} resolution Resolution to render at (higher has better quality, but lower performance).
|
Camera
|
javascript
|
goldfire/howler.js
|
examples/3d/js/camera.js
|
https://github.com/goldfire/howler.js/blob/master/examples/3d/js/camera.js
|
MIT
|
Controls = function() {
// Define our control key codes and states.
this.codes = {
// Arrows
37: 'left', 39: 'right', 38: 'front', 40: 'back',
// WASD
65: 'left', 68: 'right', 87: 'front', 83: 'back',
};
this.states = {left: false, right: false, front: false, back: false};
// Setup the DOM listeners.
document.addEventListener('keydown', this.key.bind(this, true), false);
document.addEventListener('keyup', this.key.bind(this, false), false);
document.addEventListener('touchstart', this.touch.bind(this), false);
document.addEventListener('touchmove', this.touch.bind(this), false);
document.addEventListener('touchend', this.touchEnd.bind(this), false);
}
|
Defines and handles the various controls.
|
Controls
|
javascript
|
goldfire/howler.js
|
examples/3d/js/controls.js
|
https://github.com/goldfire/howler.js/blob/master/examples/3d/js/controls.js
|
MIT
|
Game = function() {
this.lastTime = 0;
// Setup our different game components.
this.audio = new Sound();
this.player = new Player(10, 26, Math.PI * 1.9, 2.5);
this.controls = new Controls();
this.map = new Map(25);
this.camera = new Camera(isMobile ? 256 : 512);
requestAnimationFrame(this.tick.bind(this));
}
|
Main game class that runs the tick and sets up all other components.
|
Game
|
javascript
|
goldfire/howler.js
|
examples/3d/js/game.js
|
https://github.com/goldfire/howler.js/blob/master/examples/3d/js/game.js
|
MIT
|
Map = function(size) {
this.size = size;
this.grid = new Array(size * size);
this.skybox = new Texture('./assets/skybox.jpg', 4096, 1024);
this.wall = new Texture('./assets/wall.jpg', 1024, 1024);
this.speaker = new Texture('./assets/speaker.jpg', 1024, 1024);
this.light = 0;
// Define the pre-defined map template on a 25x25 grid.
this.grid = [1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1];
}
|
Generates the map and calculates the casting of arrays for the camera to display on screen.
@param {Number} size Grid size of the map to use.
|
Map
|
javascript
|
goldfire/howler.js
|
examples/3d/js/map.js
|
https://github.com/goldfire/howler.js/blob/master/examples/3d/js/map.js
|
MIT
|
Player = function(x, y, dir, speed) {
this.x = x;
this.y = y;
this.dir = dir;
this.speed = speed || 3;
this.steps = 0;
this.hand = new Texture('./assets/gun.png', 512, 360);
// Update the position of the audio listener.
Howler.pos(this.x, this.y, -0.5);
// Update the direction and orientation.
this.rotate(dir);
}
|
The player from which we cast the rays.
@param {Number} x Starting x-position.
@param {Number} y Starting y-position.
@param {Number} dir Direction they are facing in radians.
@param {Number} speed Speed they walk at.
|
Player
|
javascript
|
goldfire/howler.js
|
examples/3d/js/player.js
|
https://github.com/goldfire/howler.js/blob/master/examples/3d/js/player.js
|
MIT
|
Sound = function() {
// Setup the shared Howl.
this.sound = new Howl({
src: ['./assets/sprite.webm', './assets/sprite.mp3'],
sprite: {
lightning: [2000, 4147],
rain: [8000, 9962, true],
thunder: [19000, 13858],
music: [34000, 31994, true]
},
volume: 0
});
// Begin playing background sounds.
this.rain();
this.thunder();
}
|
Setup and control all of the game's audio.
|
Sound
|
javascript
|
goldfire/howler.js
|
examples/3d/js/sound.js
|
https://github.com/goldfire/howler.js/blob/master/examples/3d/js/sound.js
|
MIT
|
Texture = function(src, w, h) {
this.image = new Image();
this.image.src = src;
this.width = w;
this.height = h;
}
|
Load a texture and store its details.
@param {String} src Image URL.
@param {Number} w Image width.
@param {Number} h Image height.
|
Texture
|
javascript
|
goldfire/howler.js
|
examples/3d/js/texture.js
|
https://github.com/goldfire/howler.js/blob/master/examples/3d/js/texture.js
|
MIT
|
Player = function(playlist) {
this.playlist = playlist;
this.index = 0;
// Display the title of the first track.
track.innerHTML = '1. ' + playlist[0].title;
// Setup the playlist display.
playlist.forEach(function(song) {
var div = document.createElement('div');
div.className = 'list-song';
div.innerHTML = song.title;
div.onclick = function() {
player.skipTo(playlist.indexOf(song));
};
list.appendChild(div);
});
}
|
Player class containing the state of our playlist and where we are in it.
Includes all methods for playing, skipping, updating the display, etc.
@param {Array} playlist Array of objects with playlist song details ({title, file, howl}).
|
Player
|
javascript
|
goldfire/howler.js
|
examples/player/player.js
|
https://github.com/goldfire/howler.js/blob/master/examples/player/player.js
|
MIT
|
move = function(event) {
if (window.sliderDown) {
var x = event.clientX || event.touches[0].clientX;
var startX = window.innerWidth * 0.05;
var layerX = x - startX;
var per = Math.min(1, Math.max(0, layerX / parseFloat(barEmpty.scrollWidth)));
player.volume(per);
}
}
|
Format the time from seconds to M:SS.
@param {Number} secs Seconds to format.
@return {String} Formatted time.
|
move
|
javascript
|
goldfire/howler.js
|
examples/player/player.js
|
https://github.com/goldfire/howler.js/blob/master/examples/player/player.js
|
MIT
|
resize = function() {
var height = window.innerHeight * 0.3;
var width = window.innerWidth;
wave.height = height;
wave.height_2 = height / 2;
wave.MAX = wave.height_2 - 4;
wave.width = width;
wave.width_2 = width / 2;
wave.width_4 = width / 4;
wave.canvas.height = height;
wave.canvas.width = width;
wave.container.style.margin = -(height / 2) + 'px auto';
// Update the position of the slider.
var sound = player.playlist[player.index].howl;
if (sound) {
var vol = sound.volume();
var barWidth = (vol * 0.9);
sliderBtn.style.left = (window.innerWidth * barWidth + window.innerWidth * 0.05 - 25) + 'px';
}
}
|
Format the time from seconds to M:SS.
@param {Number} secs Seconds to format.
@return {String} Formatted time.
|
resize
|
javascript
|
goldfire/howler.js
|
examples/player/player.js
|
https://github.com/goldfire/howler.js/blob/master/examples/player/player.js
|
MIT
|
Radio = function(stations) {
var self = this;
self.stations = stations;
self.index = 0;
// Setup the display for each station.
for (var i=0; i<self.stations.length; i++) {
window['title' + i].innerHTML = '<b>' + self.stations[i].freq + '</b> ' + self.stations[i].title;
window['station' + i].addEventListener('click', function(index) {
var isNotPlaying = (self.stations[index].howl && !self.stations[index].howl.playing());
// Stop other sounds or the current one.
radio.stop();
// If the station isn't already playing or it doesn't exist, play it.
if (isNotPlaying || !self.stations[index].howl) {
radio.play(index);
}
}.bind(self, i));
}
}
|
Radio class containing the state of our stations.
Includes all methods for playing, stopping, etc.
@param {Array} stations Array of objects with station details ({title, src, howl, ...}).
|
Radio
|
javascript
|
goldfire/howler.js
|
examples/radio/radio.js
|
https://github.com/goldfire/howler.js/blob/master/examples/radio/radio.js
|
MIT
|
Sprite = function(options) {
var self = this;
self.sounds = [];
// Setup the options to define this sprite display.
self._width = options.width;
self._left = options.left;
self._spriteMap = options.spriteMap;
self._sprite = options.sprite;
self.setupListeners();
// Create our audio sprite definition.
self.sound = new Howl({
src: options.src,
sprite: options.sprite
});
// Setup a resize event and fire it to setup our sprite overlays.
window.addEventListener('resize', function() {
self.resize();
}, false);
self.resize();
// Begin the progress step tick.
requestAnimationFrame(self.step.bind(self));
}
|
Sprite class containing the state of our sprites to play and their progress.
@param {Object} options Settings to pass into and setup the sound and visuals.
|
Sprite
|
javascript
|
goldfire/howler.js
|
examples/sprite/sprite.js
|
https://github.com/goldfire/howler.js/blob/master/examples/sprite/sprite.js
|
MIT
|
unlock = function(e) {
// Create a pool of unlocked HTML5 Audio objects that can
// be used for playing sounds without user interaction. HTML5
// Audio objects must be individually unlocked, as opposed
// to the WebAudio API which only needs a single activation.
// This must occur before WebAudio setup or the source.onended
// event will not fire.
while (self._html5AudioPool.length < self.html5PoolSize) {
try {
var audioNode = new Audio();
// Mark this Audio object as unlocked to ensure it can get returned
// to the unlocked pool when released.
audioNode._unlocked = true;
// Add the audio node to the pool.
self._releaseHtml5Audio(audioNode);
} catch (e) {
self.noAudio = true;
break;
}
}
// Loop through any assigned audio nodes and unlock them.
for (var i=0; i<self._howls.length; i++) {
if (!self._howls[i]._webAudio) {
// Get all of the sounds in this Howl group.
var ids = self._howls[i]._getSoundIds();
// Loop through all sounds and unlock the audio nodes.
for (var j=0; j<ids.length; j++) {
var sound = self._howls[i]._soundById(ids[j]);
if (sound && sound._node && !sound._node._unlocked) {
sound._node._unlocked = true;
sound._node.load();
}
}
}
}
// Fix Android can not play in suspend state.
self._autoResume();
// Create an empty buffer.
var source = self.ctx.createBufferSource();
source.buffer = self._scratchBuffer;
source.connect(self.ctx.destination);
// Play the empty buffer.
if (typeof source.start === 'undefined') {
source.noteOn(0);
} else {
source.start(0);
}
// Calling resume() on a stack initiated by user gesture is what actually unlocks the audio on Android Chrome >= 55.
if (typeof self.ctx.resume === 'function') {
self.ctx.resume();
}
// Setup a timeout to check that we are unlocked on the next event loop.
source.onended = function() {
source.disconnect(0);
// Update the unlocked state and prevent this check from happening again.
self._audioUnlocked = true;
// Remove the touch start listener.
document.removeEventListener('touchstart', unlock, true);
document.removeEventListener('touchend', unlock, true);
document.removeEventListener('click', unlock, true);
document.removeEventListener('keydown', unlock, true);
// Let all sounds know that audio has been unlocked.
for (var i=0; i<self._howls.length; i++) {
self._howls[i]._emit('unlock');
}
};
}
|
Some browsers/devices will only allow audio to be played after a user interaction.
Attempt to automatically unlock audio on the first user interaction.
Concept from: http://paulbakaus.com/tutorials/html5/web-audio-on-ios/
@return {Howler}
|
unlock
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
handleSuspension = function() {
self.state = 'suspended';
if (self._resumeAfterSuspend) {
delete self._resumeAfterSuspend;
self._autoResume();
}
}
|
Automatically suspend the Web Audio AudioContext after no sound has played for 30 seconds.
This saves processing/energy and fixes various browser-specific bugs with audio getting stuck.
@return {Howler}
|
handleSuspension
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
Howl = function(o) {
var self = this;
// Throw an error if no source is provided.
if (!o.src || o.src.length === 0) {
console.error('An array of source files must be passed with any new Howl.');
return;
}
self.init(o);
}
|
Create an audio group controller.
@param {Object} o Passed in properties for this group.
|
Howl
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
setParams = function() {
sound._paused = false;
sound._seek = seek;
sound._start = start;
sound._stop = stop;
sound._loop = !!(sound._loop || self._sprite[sprite][2]);
}
|
Play a sound or resume previous playback.
@param {String/Number} sprite Sprite name for sprite playback or sound id to continue previous.
@param {Boolean} internal Internal Use: true prevents event firing.
@return {Number} Sound ID.
|
setParams
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
playWebAudio = function() {
self._playLock = false;
setParams();
self._refreshBuffer(sound);
// Setup the playback params.
var vol = (sound._muted || self._muted) ? 0 : sound._volume;
node.gain.setValueAtTime(vol, Howler.ctx.currentTime);
sound._playStart = Howler.ctx.currentTime;
// Play the sound using the supported method.
if (typeof node.bufferSource.start === 'undefined') {
sound._loop ? node.bufferSource.noteGrainOn(0, seek, 86400) : node.bufferSource.noteGrainOn(0, seek, duration);
} else {
sound._loop ? node.bufferSource.start(0, seek, 86400) : node.bufferSource.start(0, seek, duration);
}
// Start a new timer if none is present.
if (timeout !== Infinity) {
self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
}
if (!internal) {
setTimeout(function() {
self._emit('play', sound._id);
self._loadQueue();
}, 0);
}
}
|
Play a sound or resume previous playback.
@param {String/Number} sprite Sprite name for sprite playback or sound id to continue previous.
@param {Boolean} internal Internal Use: true prevents event firing.
@return {Number} Sound ID.
|
playWebAudio
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
playHtml5 = function() {
node.currentTime = seek;
node.muted = sound._muted || self._muted || Howler._muted || node.muted;
node.volume = sound._volume * Howler.volume();
node.playbackRate = sound._rate;
// Some browsers will throw an error if this is called without user interaction.
try {
var play = node.play();
// Support older browsers that don't support promises, and thus don't have this issue.
if (play && typeof Promise !== 'undefined' && (play instanceof Promise || typeof play.then === 'function')) {
// Implements a lock to prevent DOMException: The play() request was interrupted by a call to pause().
self._playLock = true;
// Set param values immediately.
setParams();
// Releases the lock and executes queued actions.
play
.then(function() {
self._playLock = false;
node._unlocked = true;
if (!internal) {
self._emit('play', sound._id);
} else {
self._loadQueue();
}
})
.catch(function() {
self._playLock = false;
self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' +
'on mobile devices and Chrome where playback was not within a user interaction.');
// Reset the ended and paused values.
sound._ended = true;
sound._paused = true;
});
} else if (!internal) {
self._playLock = false;
setParams();
self._emit('play', sound._id);
}
// Setting rate before playing won't work in IE, so we set it again here.
node.playbackRate = sound._rate;
// If the node is still paused, then we can assume there was a playback issue.
if (node.paused) {
self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' +
'on mobile devices and Chrome where playback was not within a user interaction.');
return;
}
// Setup the end timer on sprites or listen for the ended event.
if (sprite !== '__default' || sound._loop) {
self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
} else {
self._endTimers[sound._id] = function() {
// Fire ended on this audio node.
self._ended(sound);
// Clear this listener.
node.removeEventListener('ended', self._endTimers[sound._id], false);
};
node.addEventListener('ended', self._endTimers[sound._id], false);
}
} catch (err) {
self._emit('playerror', sound._id, err);
}
}
|
Play a sound or resume previous playback.
@param {String/Number} sprite Sprite name for sprite playback or sound id to continue previous.
@param {Boolean} internal Internal Use: true prevents event firing.
@return {Number} Sound ID.
|
playHtml5
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
listener = function() {
self._state = 'loaded';
// Begin playback.
playHtml5();
// Clear this listener.
node.removeEventListener(Howler._canPlayEvent, listener, false);
}
|
Play a sound or resume previous playback.
@param {String/Number} sprite Sprite name for sprite playback or sound id to continue previous.
@param {Boolean} internal Internal Use: true prevents event firing.
@return {Number} Sound ID.
|
listener
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
seekAndEmit = function() {
// Restart the playback if the sound was playing.
if (playing) {
self.play(id, true);
}
self._emit('seek', id);
}
|
Get/set the seek position of a sound. This method can optionally take 0, 1 or 2 arguments.
seek() -> Returns the first sound node's current seek position.
seek(id) -> Returns the sound id's current seek position.
seek(seek) -> Sets the seek position of the first sound node.
seek(seek, id) -> Sets the seek position of passed sound id.
@return {Howl/Number} Returns self or the current seek position.
|
seekAndEmit
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
emitSeek = function() {
if (!self._playLock) {
seekAndEmit();
} else {
setTimeout(emitSeek, 0);
}
}
|
Get/set the seek position of a sound. This method can optionally take 0, 1 or 2 arguments.
seek() -> Returns the first sound node's current seek position.
seek(id) -> Returns the sound id's current seek position.
seek(seek) -> Sets the seek position of the first sound node.
seek(seek, id) -> Sets the seek position of passed sound id.
@return {Howl/Number} Returns self or the current seek position.
|
emitSeek
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
Sound = function(howl) {
this._parent = howl;
this.init();
}
|
Setup the sound object, which each node attached to a Howl group is contained in.
@param {Object} howl The Howl parent group.
|
Sound
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
loadBuffer = function(self) {
var url = self._src;
// Check if the buffer has already been cached and use it instead.
if (cache[url]) {
// Set the duration from the cache.
self._duration = cache[url].duration;
// Load the sound into this Howl.
loadSound(self);
return;
}
if (/^data:[^;]+;base64,/.test(url)) {
// Decode the base64 data URI without XHR, since some browsers don't support it.
var data = atob(url.split(',')[1]);
var dataView = new Uint8Array(data.length);
for (var i=0; i<data.length; ++i) {
dataView[i] = data.charCodeAt(i);
}
decodeAudioData(dataView.buffer, self);
} else {
// Load the buffer from the URL.
var xhr = new XMLHttpRequest();
xhr.open(self._xhr.method, url, true);
xhr.withCredentials = self._xhr.withCredentials;
xhr.responseType = 'arraybuffer';
// Apply any custom headers to the request.
if (self._xhr.headers) {
Object.keys(self._xhr.headers).forEach(function(key) {
xhr.setRequestHeader(key, self._xhr.headers[key]);
});
}
xhr.onload = function() {
// Make sure we get a successful response back.
var code = (xhr.status + '')[0];
if (code !== '0' && code !== '2' && code !== '3') {
self._emit('loaderror', null, 'Failed loading audio file with status: ' + xhr.status + '.');
return;
}
decodeAudioData(xhr.response, self);
};
xhr.onerror = function() {
// If there is an error, switch to HTML5 Audio.
if (self._webAudio) {
self._html5 = true;
self._webAudio = false;
self._sounds = [];
delete cache[url];
self.load();
}
};
safeXhrSend(xhr);
}
}
|
Buffer a sound from URL, Data URI or cache and decode to audio source (Web Audio API).
@param {Howl} self
|
loadBuffer
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
safeXhrSend = function(xhr) {
try {
xhr.send();
} catch (e) {
xhr.onerror();
}
}
|
Send the XHR request wrapped in a try/catch.
@param {Object} xhr XHR to send.
|
safeXhrSend
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
decodeAudioData = function(arraybuffer, self) {
// Fire a load error if something broke.
var error = function() {
self._emit('loaderror', null, 'Decoding audio data failed.');
};
// Load the sound on success.
var success = function(buffer) {
if (buffer && self._sounds.length > 0) {
cache[self._src] = buffer;
loadSound(self, buffer);
} else {
error();
}
};
// Decode the buffer into an audio source.
if (typeof Promise !== 'undefined' && Howler.ctx.decodeAudioData.length === 1) {
Howler.ctx.decodeAudioData(arraybuffer).then(success).catch(error);
} else {
Howler.ctx.decodeAudioData(arraybuffer, success, error);
}
}
|
Decode audio data from an array buffer.
@param {ArrayBuffer} arraybuffer The audio data.
@param {Howl} self
|
decodeAudioData
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
error = function() {
self._emit('loaderror', null, 'Decoding audio data failed.');
}
|
Decode audio data from an array buffer.
@param {ArrayBuffer} arraybuffer The audio data.
@param {Howl} self
|
error
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
success = function(buffer) {
if (buffer && self._sounds.length > 0) {
cache[self._src] = buffer;
loadSound(self, buffer);
} else {
error();
}
}
|
Decode audio data from an array buffer.
@param {ArrayBuffer} arraybuffer The audio data.
@param {Howl} self
|
success
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
loadSound = function(self, buffer) {
// Set the duration.
if (buffer && !self._duration) {
self._duration = buffer.duration;
}
// Setup a sprite if none is defined.
if (Object.keys(self._sprite).length === 0) {
self._sprite = {__default: [0, self._duration * 1000]};
}
// Fire the loaded event.
if (self._state !== 'loaded') {
self._state = 'loaded';
self._emit('load');
self._loadQueue();
}
}
|
Sound is now loaded, so finish setting everything up and fire the loaded event.
@param {Howl} self
@param {Object} buffer The decoded buffer sound source.
|
loadSound
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
setupAudioContext = function() {
// If we have already detected that Web Audio isn't supported, don't run this step again.
if (!Howler.usingWebAudio) {
return;
}
// Check if we are using Web Audio and setup the AudioContext if we are.
try {
if (typeof AudioContext !== 'undefined') {
Howler.ctx = new AudioContext();
} else if (typeof webkitAudioContext !== 'undefined') {
Howler.ctx = new webkitAudioContext();
} else {
Howler.usingWebAudio = false;
}
} catch(e) {
Howler.usingWebAudio = false;
}
// If the audio context creation still failed, set using web audio to false.
if (!Howler.ctx) {
Howler.usingWebAudio = false;
}
// Check if a webview is being used on iOS8 or earlier (rather than the browser).
// If it is, disable Web Audio as it causes crashing.
var iOS = (/iP(hone|od|ad)/.test(Howler._navigator && Howler._navigator.platform));
var appVersion = Howler._navigator && Howler._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
var version = appVersion ? parseInt(appVersion[1], 10) : null;
if (iOS && version && version < 9) {
var safari = /safari/.test(Howler._navigator && Howler._navigator.userAgent.toLowerCase());
if (Howler._navigator && !safari) {
Howler.usingWebAudio = false;
}
}
// Create and expose the master GainNode when using Web Audio (useful for plugins or advanced usage).
if (Howler.usingWebAudio) {
Howler.masterGain = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain();
Howler.masterGain.gain.setValueAtTime(Howler._muted ? 0 : Howler._volume, Howler.ctx.currentTime);
Howler.masterGain.connect(Howler.ctx.destination);
}
// Re-run the setup on Howler.
Howler._setup();
}
|
Setup the audio context when available, or switch to HTML5 Audio mode.
|
setupAudioContext
|
javascript
|
goldfire/howler.js
|
src/howler.core.js
|
https://github.com/goldfire/howler.js/blob/master/src/howler.core.js
|
MIT
|
setupPanner = function(sound, type) {
type = type || 'spatial';
// Create the new panner node.
if (type === 'spatial') {
sound._panner = Howler.ctx.createPanner();
sound._panner.coneInnerAngle = sound._pannerAttr.coneInnerAngle;
sound._panner.coneOuterAngle = sound._pannerAttr.coneOuterAngle;
sound._panner.coneOuterGain = sound._pannerAttr.coneOuterGain;
sound._panner.distanceModel = sound._pannerAttr.distanceModel;
sound._panner.maxDistance = sound._pannerAttr.maxDistance;
sound._panner.refDistance = sound._pannerAttr.refDistance;
sound._panner.rolloffFactor = sound._pannerAttr.rolloffFactor;
sound._panner.panningModel = sound._pannerAttr.panningModel;
if (typeof sound._panner.positionX !== 'undefined') {
sound._panner.positionX.setValueAtTime(sound._pos[0], Howler.ctx.currentTime);
sound._panner.positionY.setValueAtTime(sound._pos[1], Howler.ctx.currentTime);
sound._panner.positionZ.setValueAtTime(sound._pos[2], Howler.ctx.currentTime);
} else {
sound._panner.setPosition(sound._pos[0], sound._pos[1], sound._pos[2]);
}
if (typeof sound._panner.orientationX !== 'undefined') {
sound._panner.orientationX.setValueAtTime(sound._orientation[0], Howler.ctx.currentTime);
sound._panner.orientationY.setValueAtTime(sound._orientation[1], Howler.ctx.currentTime);
sound._panner.orientationZ.setValueAtTime(sound._orientation[2], Howler.ctx.currentTime);
} else {
sound._panner.setOrientation(sound._orientation[0], sound._orientation[1], sound._orientation[2]);
}
} else {
sound._panner = Howler.ctx.createStereoPanner();
sound._panner.pan.setValueAtTime(sound._stereo, Howler.ctx.currentTime);
}
sound._panner.connect(sound._node);
// Update the connections.
if (!sound._paused) {
sound._parent.pause(sound._id, true).play(sound._id, true);
}
}
|
Create a new panner node and save it on the sound.
@param {Sound} sound Specific sound to setup panning on.
@param {String} type Type of panner to create: 'stereo' or 'spatial'.
|
setupPanner
|
javascript
|
goldfire/howler.js
|
src/plugins/howler.spatial.js
|
https://github.com/goldfire/howler.js/blob/master/src/plugins/howler.spatial.js
|
MIT
|
function innerState(cm, state) {
return CodeMirror.innerMode(cm.getMode(), state).state;
}
|
Array of tag names where an end tag is forbidden.
|
innerState
|
javascript
|
jbt/markdown-editor
|
codemirror/lib/util/closetag.js
|
https://github.com/jbt/markdown-editor/blob/master/codemirror/lib/util/closetag.js
|
ISC
|
function isWhitespace(s) {
return s === ' ' || s === '\t' || s === '\r' || s === '\n' || s === '';
}
|
NB!
The namedEmojiString variable is updated automatically by the
`update.sh` script. Do not remove the markers as this will
cause `update.sh` to stop working.
|
isWhitespace
|
javascript
|
jbt/markdown-editor
|
lib/emojify.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/emojify.js
|
ISC
|
function insertEmojicon(node, match, emojiName) {
var emojiImg = document.createElement('img');
emojiImg.setAttribute('title', ':' + emojiName + ':');
emojiImg.setAttribute('alt', ':' + emojiName + ':');
emojiImg.setAttribute('class', 'emoji');
emojiImg.setAttribute('src', defaultConfig.img_dir + '/' + emojiName + '.png');
emojiImg.setAttribute('align', 'absmiddle');
node.splitText(match.index);
node.nextSibling.nodeValue = node.nextSibling.nodeValue.substr(match[0].length, node.nextSibling.nodeValue.length);
emojiImg.appendChild(node.splitText(match.index));
node.parentNode.insertBefore(emojiImg, node.nextSibling);
}
|
NB!
The namedEmojiString variable is updated automatically by the
`update.sh` script. Do not remove the markers as this will
cause `update.sh` to stop working.
|
insertEmojicon
|
javascript
|
jbt/markdown-editor
|
lib/emojify.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/emojify.js
|
ISC
|
function getEmojiNameForMatch(match) {
/* Special case for named emoji */
if(match[1] && match[2]) {
var named = match[2];
if(namedMatchHash[named]) { return named; }
return;
}
for(var i = 3; i < match.length - 1; i++) {
if(match[i]) {
return emoticonsProcessed[i - 2][1];
}
}
}
|
NB!
The namedEmojiString variable is updated automatically by the
`update.sh` script. Do not remove the markers as this will
cause `update.sh` to stop working.
|
getEmojiNameForMatch
|
javascript
|
jbt/markdown-editor
|
lib/emojify.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/emojify.js
|
ISC
|
function defaultReplacer(emoji, name) {
return "<img title=':" + name + ":' alt=':" + name + ":' class='emoji' src='" + defaultConfig.img_dir + '/' + name + ".png' align='absmiddle' />";
}
|
NB!
The namedEmojiString variable is updated automatically by the
`update.sh` script. Do not remove the markers as this will
cause `update.sh` to stop working.
|
defaultReplacer
|
javascript
|
jbt/markdown-editor
|
lib/emojify.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/emojify.js
|
ISC
|
function Validator() {
this.lastEmojiTerminatedAt = -1;
}
|
NB!
The namedEmojiString variable is updated automatically by the
`update.sh` script. Do not remove the markers as this will
cause `update.sh` to stop working.
|
Validator
|
javascript
|
jbt/markdown-editor
|
lib/emojify.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/emojify.js
|
ISC
|
function success() {
self.lastEmojiTerminatedAt = length + index;
return emojiName;
}
|
NB!
The namedEmojiString variable is updated automatically by the
`update.sh` script. Do not remove the markers as this will
cause `update.sh` to stop working.
|
success
|
javascript
|
jbt/markdown-editor
|
lib/emojify.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/emojify.js
|
ISC
|
function emojifyString (htmlString, replacer) {
if(!htmlString) { return htmlString; }
if(!replacer) { replacer = defaultReplacer; }
var validator = new Validator();
return htmlString.replace(emojiMegaRe, function() {
var matches = Array.prototype.slice.call(arguments, 0, -2);
var index = arguments[arguments.length - 2];
var input = arguments[arguments.length - 1];
var emojiName = validator.validate(matches, index, input);
if(emojiName) {
return replacer(arguments[0], emojiName);
}
/* Did not validate, return the original value */
return arguments[0];
});
}
|
NB!
The namedEmojiString variable is updated automatically by the
`update.sh` script. Do not remove the markers as this will
cause `update.sh` to stop working.
|
emojifyString
|
javascript
|
jbt/markdown-editor
|
lib/emojify.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/emojify.js
|
ISC
|
function run(el) {
// Check if an element was not passed.
if(typeof el === 'undefined'){
// Check if an element was configured. If not, default to the body.
if (defaultConfig.only_crawl_id) {
el = document.getElementById(defaultConfig.only_crawl_id);
} else {
el = document.body;
}
}
var ignoredTags = defaultConfig.ignored_tags;
var nodeIterator = document.createTreeWalker(
el,
NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT,
function(node) {
if(node.nodeType !== 1) {
/* Text Node? Good! */
return NodeFilter.FILTER_ACCEPT;
}
if(ignoredTags[node.tagName] || node.classList.contains('no-emojify')) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_SKIP;
},
false);
var nodeList = [];
var node;
while((node = nodeIterator.nextNode()) !== null) {
nodeList.push(node);
}
nodeList.forEach(function(node) {
var match;
var matches = [];
var validator = new Validator();
while ((match = emojiMegaRe.exec(node.data)) !== null) {
if(validator.validate(match, match.index, match.input)) {
matches.push(match);
}
}
for (var i = matches.length; i-- > 0;) {
/* Replace the text with the emoji */
var emojiName = getEmojiNameForMatch(matches[i]);
insertEmojicon(node, matches[i], emojiName);
}
});
}
|
NB!
The namedEmojiString variable is updated automatically by the
`update.sh` script. Do not remove the markers as this will
cause `update.sh` to stop working.
|
run
|
javascript
|
jbt/markdown-editor
|
lib/emojify.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/emojify.js
|
ISC
|
function Renderer() {
/**
* Renderer#rules -> Object
*
* Contains render rules for tokens. Can be updated and extended.
*
* ##### Example
*
* ```javascript
* var md = require('markdown-it')();
*
* md.renderer.rules.strong_open = function () { return '<b>'; };
* md.renderer.rules.strong_close = function () { return '</b>'; };
*
* var result = md.renderInline(...);
* ```
*
* Each rule is called as independed static function with fixed signature:
*
* ```javascript
* function my_token_render(tokens, idx, options, env, renderer) {
* // ...
* return renderedHTML;
* }
* ```
*
* See [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.js)
* for more details and examples.
**/
this.rules = assign({}, default_rules);
}
|
new Renderer()
Creates new [[Renderer]] instance and fill [[Renderer#rules]] with defaults.
|
Renderer
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function isLetter(ch) {
/*eslint no-bitwise:0*/
var lc = ch | 0x20; // to lower case
return (lc >= 0x61/* a */) && (lc <= 0x7a/* z */);
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
isLetter
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function skipBulletListMarker(state, startLine) {
var marker, pos, max;
pos = state.bMarks[startLine] + state.tShift[startLine];
max = state.eMarks[startLine];
marker = state.src.charCodeAt(pos++);
// Check bullet
if (marker !== 0x2A/* * */ &&
marker !== 0x2D/* - */ &&
marker !== 0x2B/* + */) {
return -1;
}
if (pos < max && state.src.charCodeAt(pos) !== 0x20) {
// " 1.test " - is not a list item
return -1;
}
return pos;
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
skipBulletListMarker
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function skipOrderedListMarker(state, startLine) {
var ch,
pos = state.bMarks[startLine] + state.tShift[startLine],
max = state.eMarks[startLine];
// List marker should have at least 2 chars (digit + dot)
if (pos + 1 >= max) { return -1; }
ch = state.src.charCodeAt(pos++);
if (ch < 0x30/* 0 */ || ch > 0x39/* 9 */) { return -1; }
for (;;) {
// EOL -> fail
if (pos >= max) { return -1; }
ch = state.src.charCodeAt(pos++);
if (ch >= 0x30/* 0 */ && ch <= 0x39/* 9 */) {
continue;
}
// found valid marker
if (ch === 0x29/* ) */ || ch === 0x2e/* . */) {
break;
}
return -1;
}
if (pos < max && state.src.charCodeAt(pos) !== 0x20/* space */) {
// " 1.test " - is not a list item
return -1;
}
return pos;
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
skipOrderedListMarker
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function markTightParagraphs(state, idx) {
var i, l,
level = state.level + 2;
for (i = idx + 2, l = state.tokens.length - 2; i < l; i++) {
if (state.tokens[i].level === level && state.tokens[i].type === 'paragraph_open') {
state.tokens[i + 2].hidden = true;
state.tokens[i].hidden = true;
i += 2;
}
}
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
markTightParagraphs
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function StateBlock(src, md, env, tokens) {
var ch, s, start, pos, len, indent, indent_found;
this.src = src;
// link to parser instance
this.md = md;
this.env = env;
//
// Internal state vartiables
//
this.tokens = tokens;
this.bMarks = []; // line begin offsets for fast jumps
this.eMarks = []; // line end offsets for fast jumps
this.tShift = []; // indent for each line
// block parser variables
this.blkIndent = 0; // required block content indent
// (for example, if we are in list)
this.line = 0; // line index in src
this.lineMax = 0; // lines count
this.tight = false; // loose/tight mode for lists
this.parentType = 'root'; // if `list`, block parser stops on two newlines
this.ddIndent = -1; // indent of the current dd block (-1 if there isn't any)
this.level = 0;
// renderer
this.result = '';
// Create caches
// Generate markers.
s = this.src;
indent = 0;
indent_found = false;
for (start = pos = indent = 0, len = s.length; pos < len; pos++) {
ch = s.charCodeAt(pos);
if (!indent_found) {
if (ch === 0x20/* space */) {
indent++;
continue;
} else {
indent_found = true;
}
}
if (ch === 0x0A || pos === len - 1) {
if (ch !== 0x0A) { pos++; }
this.bMarks.push(start);
this.eMarks.push(pos);
this.tShift.push(indent);
indent_found = false;
indent = 0;
start = pos + 1;
}
}
// Push fake entry to simplify cache bounds checks
this.bMarks.push(s.length);
this.eMarks.push(s.length);
this.tShift.push(0);
this.lineMax = this.bMarks.length - 1; // don't count last fake line
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
StateBlock
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function getLine(state, line) {
var pos = state.bMarks[line] + state.blkIndent,
max = state.eMarks[line];
return state.src.substr(pos, max - pos);
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
getLine
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function escapedSplit(str) {
var result = [],
pos = 0,
max = str.length,
ch,
escapes = 0,
lastPos = 0,
backTicked = false,
lastBackTick = 0;
ch = str.charCodeAt(pos);
while (pos < max) {
if (ch === 0x60/* ` */ && (escapes % 2 === 0)) {
backTicked = !backTicked;
lastBackTick = pos;
} else if (ch === 0x7c/* | */ && (escapes % 2 === 0) && !backTicked) {
result.push(str.substring(lastPos, pos));
lastPos = pos + 1;
} else if (ch === 0x5c/* \ */) {
escapes++;
} else {
escapes = 0;
}
pos++;
// If there was an un-closed backtick, go back to just after
// the last backtick, but as if it was a normal character
if (pos === max && backTicked) {
backTicked = false;
pos = lastBackTick + 1;
}
ch = str.charCodeAt(pos);
}
result.push(str.substring(lastPos));
return result;
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
escapedSplit
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function isLinkOpen(str) {
return /^<a[>\s]/i.test(str);
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
isLinkOpen
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function isLinkClose(str) {
return /^<\/a\s*>/i.test(str);
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
isLinkClose
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function replaceFn(match, name) {
return SCOPED_ABBR[name.toLowerCase()];
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
replaceFn
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function replace_scoped(inlineTokens) {
var i, token;
for (i = inlineTokens.length - 1; i >= 0; i--) {
token = inlineTokens[i];
if (token.type === 'text') {
token.content = token.content.replace(SCOPED_ABBR_RE, replaceFn);
}
}
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
replace_scoped
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function replaceAt(str, index, ch) {
return str.substr(0, index) + ch + str.substr(index + 1);
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
replaceAt
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function process_inlines(tokens, state) {
var i, token, text, t, pos, max, thisLevel, item, lastChar, nextChar,
isLastPunctChar, isNextPunctChar, isLastWhiteSpace, isNextWhiteSpace,
canOpen, canClose, j, isSingle, stack;
stack = [];
for (i = 0; i < tokens.length; i++) {
token = tokens[i];
thisLevel = tokens[i].level;
for (j = stack.length - 1; j >= 0; j--) {
if (stack[j].level <= thisLevel) { break; }
}
stack.length = j + 1;
if (token.type !== 'text') { continue; }
text = token.content;
pos = 0;
max = text.length;
/*eslint no-labels:0,block-scoped-var:0*/
OUTER:
while (pos < max) {
QUOTE_RE.lastIndex = pos;
t = QUOTE_RE.exec(text);
if (!t) { break; }
canOpen = canClose = true;
pos = t.index + 1;
isSingle = (t[0] === "'");
// treat begin/end of the line as a whitespace
lastChar = t.index - 1 >= 0 ? text.charCodeAt(t.index - 1) : 0x20;
nextChar = pos < max ? text.charCodeAt(pos) : 0x20;
isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar));
isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar));
isLastWhiteSpace = isWhiteSpace(lastChar);
isNextWhiteSpace = isWhiteSpace(nextChar);
if (isNextWhiteSpace) {
canOpen = false;
} else if (isNextPunctChar) {
if (!(isLastWhiteSpace || isLastPunctChar)) {
canOpen = false;
}
}
if (isLastWhiteSpace) {
canClose = false;
} else if (isLastPunctChar) {
if (!(isNextWhiteSpace || isNextPunctChar)) {
canClose = false;
}
}
if (nextChar === 0x22 /* " */ && t[0] === '"') {
if (lastChar >= 0x30 /* 0 */ && lastChar <= 0x39 /* 9 */) {
// special case: 1"" - count first quote as an inch
canClose = canOpen = false;
}
}
if (canOpen && canClose) {
// treat this as the middle of the word
canOpen = false;
canClose = isNextPunctChar;
}
if (!canOpen && !canClose) {
// middle of word
if (isSingle) {
token.content = replaceAt(token.content, t.index, APOSTROPHE);
}
continue;
}
if (canClose) {
// this could be a closing quote, rewind the stack to get a match
for (j = stack.length - 1; j >= 0; j--) {
item = stack[j];
if (stack[j].level < thisLevel) { break; }
if (item.single === isSingle && stack[j].level === thisLevel) {
item = stack[j];
if (isSingle) {
tokens[item.token].content = replaceAt(
tokens[item.token].content, item.pos, state.md.options.quotes[2]);
token.content = replaceAt(
token.content, t.index, state.md.options.quotes[3]);
} else {
tokens[item.token].content = replaceAt(
tokens[item.token].content, item.pos, state.md.options.quotes[0]);
token.content = replaceAt(token.content, t.index, state.md.options.quotes[1]);
}
stack.length = j;
continue OUTER;
}
}
}
if (canOpen) {
stack.push({
token: i,
pos: t.index,
single: isSingle,
level: thisLevel
});
} else if (canClose && isSingle) {
token.content = replaceAt(token.content, t.index, APOSTROPHE);
}
}
}
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
process_inlines
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function StateCore(src, md, env) {
this.src = src;
this.env = env;
this.tokens = [];
this.inlineMode = false;
this.md = md; // link to parser instance
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
StateCore
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function scanDelims(state, start) {
var pos = start, lastChar, nextChar, count,
isLastWhiteSpace, isLastPunctChar,
isNextWhiteSpace, isNextPunctChar,
can_open = true,
can_close = true,
max = state.posMax,
marker = state.src.charCodeAt(start);
// treat beginning of the line as a whitespace
lastChar = start > 0 ? state.src.charCodeAt(start - 1) : 0x20;
while (pos < max && state.src.charCodeAt(pos) === marker) { pos++; }
if (pos >= max) {
can_open = false;
}
count = pos - start;
// treat end of the line as a whitespace
nextChar = pos < max ? state.src.charCodeAt(pos) : 0x20;
isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar));
isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar));
isLastWhiteSpace = isWhiteSpace(lastChar);
isNextWhiteSpace = isWhiteSpace(nextChar);
if (isNextWhiteSpace) {
can_open = false;
} else if (isNextPunctChar) {
if (!(isLastWhiteSpace || isLastPunctChar)) {
can_open = false;
}
}
if (isLastWhiteSpace) {
can_close = false;
} else if (isLastPunctChar) {
if (!(isNextWhiteSpace || isNextPunctChar)) {
can_close = false;
}
}
if (marker === 0x5F /* _ */) {
if (can_open && can_close) {
// "_" inside a word can neither open nor close an emphasis
can_open = false;
can_close = isNextPunctChar;
}
}
return {
can_open: can_open,
can_close: can_close,
delims: count
};
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
scanDelims
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function isLetter(ch) {
/*eslint no-bitwise:0*/
var lc = ch | 0x20; // to lower case
return (lc >= 0x61/* a */) && (lc <= 0x7a/* z */);
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
isLetter
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function StateInline(src, md, env, outTokens) {
this.src = src;
this.env = env;
this.md = md;
this.tokens = outTokens;
this.pos = 0;
this.posMax = this.src.length;
this.level = 0;
this.pending = '';
this.pendingLevel = 0;
this.cache = {}; // Stores { start: end } pairs. Useful for backtrack
// optimization of pairs parse (emphasis, strikes).
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
StateInline
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function scanDelims(state, start) {
var pos = start, lastChar, nextChar, count,
isLastWhiteSpace, isLastPunctChar,
isNextWhiteSpace, isNextPunctChar,
can_open = true,
can_close = true,
max = state.posMax,
marker = state.src.charCodeAt(start);
// treat beginning of the line as a whitespace
lastChar = start > 0 ? state.src.charCodeAt(start - 1) : 0x20;
while (pos < max && state.src.charCodeAt(pos) === marker) { pos++; }
if (pos >= max) {
can_open = false;
}
count = pos - start;
// treat end of the line as a whitespace
nextChar = pos < max ? state.src.charCodeAt(pos) : 0x20;
isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar));
isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar));
isLastWhiteSpace = isWhiteSpace(lastChar);
isNextWhiteSpace = isWhiteSpace(nextChar);
if (isNextWhiteSpace) {
can_open = false;
} else if (isNextPunctChar) {
if (!(isLastWhiteSpace || isLastPunctChar)) {
can_open = false;
}
}
if (isLastWhiteSpace) {
can_close = false;
} else if (isLastPunctChar) {
if (!(isNextWhiteSpace || isNextPunctChar)) {
can_close = false;
}
}
return {
can_open: can_open,
can_close: can_close,
delims: count
};
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
scanDelims
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function isTerminatorChar(ch) {
switch (ch) {
case 0x0A/* \n */:
case 0x21/* ! */:
case 0x23/* # */:
case 0x24/* $ */:
case 0x25/* % */:
case 0x26/* & */:
case 0x2A/* * */:
case 0x2B/* + */:
case 0x2D/* - */:
case 0x3A/* : */:
case 0x3C/* < */:
case 0x3D/* = */:
case 0x3E/* > */:
case 0x40/* @ */:
case 0x5B/* [ */:
case 0x5C/* \ */:
case 0x5D/* ] */:
case 0x5E/* ^ */:
case 0x5F/* _ */:
case 0x60/* ` */:
case 0x7B/* { */:
case 0x7D/* } */:
case 0x7E/* ~ */:
return true;
default:
return false;
}
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
isTerminatorChar
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function Token(type, tag, nesting) {
/**
* Token#type -> String
*
* Type of the token (string, e.g. "paragraph_open")
**/
this.type = type;
/**
* Token#tag -> String
*
* html tag name, e.g. "p"
**/
this.tag = tag;
/**
* Token#attrs -> Array
*
* Html attributes. Format: `[ [ name1, value1 ], [ name2, value2 ] ]`
**/
this.attrs = null;
/**
* Token#map -> Array
*
* Source map info. Format: `[ line_begin, line_end ]`
**/
this.map = null;
/**
* Token#nesting -> Number
*
* Level change (number in {-1, 0, 1} set), where:
*
* - `1` means the tag is opening
* - `0` means the tag is self-closing
* - `-1` means the tag is closing
**/
this.nesting = nesting;
/**
* Token#level -> Number
*
* nesting level, the same as `state.level`
**/
this.level = 0;
/**
* Token#children -> Array
*
* An array of child nodes (inline and img tokens)
**/
this.children = null;
/**
* Token#content -> String
*
* In a case of self-closing tag (code, html, fence, etc.),
* it has contents of this tag.
**/
this.content = '';
/**
* Token#markup -> String
*
* '*' or '_' for emphasis, fence string for fence, etc.
**/
this.markup = '';
/**
* Token#info -> String
*
* fence infostring
**/
this.info = '';
/**
* Token#meta -> Object
*
* A place for plugins to store an arbitrary data
**/
this.meta = null;
/**
* Token#block -> Boolean
*
* True for block-level tokens, false for inline tokens.
* Used in renderer to calculate line breaks
**/
this.block = false;
/**
* Token#hidden -> Boolean
*
* If it's true, ignore this element when rendering. Used for tight lists
* to hide paragraphs.
**/
this.hidden = false;
}
|
new Token(type, tag, nesting)
Create new token and fill passed properties.
|
Token
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function error(type) {
throw RangeError(errors[type]);
}
|
A generic error utility function.
@private
@param {String} type The error type.
@returns {Error} Throws a `RangeError` with the applicable error message.
|
error
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function map(array, fn) {
var length = array.length;
while (length--) {
array[length] = fn(array[length]);
}
return array;
}
|
A generic `Array#map` utility function.
@private
@param {Array} array The array to iterate over.
@param {Function} callback The function that gets called for every array
item.
@returns {Array} A new array of values returned by the callback function.
|
map
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function mapDomain(string, fn) {
return map(string.split(regexSeparators), fn).join('.');
}
|
A simple `Array#map`-like wrapper to work with domain name strings.
@private
@param {String} domain The domain name.
@param {Function} callback The function that gets called for every
character.
@returns {Array} A new string of characters returned by the callback
function.
|
mapDomain
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
|
Creates an array containing the numeric code points of each Unicode
character in the string. While JavaScript uses UCS-2 internally,
this function will convert a pair of surrogate halves (each of which
UCS-2 exposes as separate characters) into a single code point,
matching UTF-16.
@see `punycode.ucs2.encode`
@see <http://mathiasbynens.be/notes/javascript-encoding>
@memberOf punycode.ucs2
@name decode
@param {String} string The Unicode input string (UCS-2).
@returns {Array} The new array of code points.
|
ucs2decode
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
|
Creates a string based on an array of numeric code points.
@see `punycode.ucs2.decode`
@memberOf punycode.ucs2
@name encode
@param {Array} codePoints The array of numeric code points.
@returns {String} The new Unicode string (UCS-2).
|
ucs2encode
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
|
Converts a basic code point into a digit/integer.
@see `digitToBasic()`
@private
@param {Number} codePoint The basic numeric code point value.
@returns {Number} The numeric value of a basic code point (for use in
representing integers) in the range `0` to `base - 1`, or `base` if
the code point does not represent a value.
|
basicToDigit
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
|
Converts a digit/integer into a basic code point.
@see `basicToDigit()`
@private
@param {Number} digit The numeric value of a basic code point.
@returns {Number} The basic code point whose value (when used for
representing integers) is `digit`, which needs to be in the range
`0` to `base - 1`. If `flag` is non-zero, the uppercase form is
used; else, the lowercase form is used. The behavior is undefined
if `flag` is non-zero and `digit` has no uppercase form.
|
digitToBasic
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
|
Bias adaptation function as per section 3.4 of RFC 3492.
http://tools.ietf.org/html/rfc3492#section-3.4
@private
|
adapt
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
|
Converts a Punycode string of ASCII-only symbols to a string of Unicode
symbols.
@memberOf punycode
@param {String} input The Punycode string of ASCII-only symbols.
@returns {String} The resulting string of Unicode symbols.
|
decode
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
|
Converts a string of Unicode symbols to a Punycode string of ASCII-only
symbols.
@memberOf punycode
@param {String} input The string of Unicode symbols.
@returns {String} The resulting Punycode string of ASCII-only symbols.
|
encode
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function toUnicode(domain) {
return mapDomain(domain, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
|
Converts a Punycode string representing a domain name to Unicode. Only the
Punycoded parts of the domain name will be converted, i.e. it doesn't
matter if you call it on a string that has already been converted to
Unicode.
@memberOf punycode
@param {String} domain The Punycode domain name to convert to Unicode.
@returns {String} The Unicode representation of the given Punycode
string.
|
toUnicode
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function toASCII(domain) {
return mapDomain(domain, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
|
Converts a Unicode string representing a domain name to Punycode. Only the
non-ASCII parts of the domain name will be converted, i.e. it doesn't
matter if you call it with a domain that's already in ASCII.
@memberOf punycode
@param {String} domain The domain name to convert, as a Unicode string.
@returns {String} The Punycode representation of the given domain name.
|
toASCII
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function Match(self, shift) {
var start = self.__index__,
end = self.__last_index__,
text = self.__text_cache__.slice(start, end);
/**
* Match#schema -> String
*
* Prefix (protocol) for matched string.
**/
this.schema = self.__schema__.toLowerCase();
/**
* Match#index -> Number
*
* First position of matched string.
**/
this.index = start + shift;
/**
* Match#lastIndex -> Number
*
* Next position after matched string.
**/
this.lastIndex = end + shift;
/**
* Match#raw -> String
*
* Matched string.
**/
this.raw = text;
/**
* Match#text -> String
*
* Notmalized text of matched string.
**/
this.text = text;
/**
* Match#url -> String
*
* Normalized url of matched string.
**/
this.url = text;
}
|
class Match
Match result. Single element of array, returned by [[LinkifyIt#match]]
|
Match
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.