code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
Fontmin.prototype.run = function (cb) {
cb = cb || function () {};
var stream = this.createStream();
stream.on('error', cb);
stream.pipe(concat(cb.bind(null, null)));
return stream;
}; | Optimize files
@param {Function} cb callback
@return {Stream} file stream
@api public | Fontmin.prototype.run ( cb ) | javascript | ecomfe/fontmin | index.js | https://github.com/ecomfe/fontmin/blob/master/index.js | MIT |
Fontmin.prototype.runAsync = function () {
return new Promise((resolve, reject) => {
var stream = this.createStream();
stream.on('error', reject);
stream.pipe(concat(resolve));
});
}; | run Optimize files with return Promise
@return {Array<Buffer>} file result
@api public | Fontmin.prototype.runAsync ( ) | javascript | ecomfe/fontmin | index.js | https://github.com/ecomfe/fontmin/blob/master/index.js | MIT |
Fontmin.prototype.createStream = function () {
this.streams.unshift(this.getFiles());
if (this.streams.length === 1) {
this.use(Fontmin.otf2ttf());
this.use(Fontmin.ttf2eot());
this.use(Fontmin.ttf2woff());
this.use(Fontmin.ttf2woff2());
this.use(Fontmin.ttf2svg());
this.use(Fontmin.css());
}
if (this.dest()) {
this.streams.push(
vfs.dest.apply(vfs, this.dest())
);
}
return combine(this.streams);
}; | Create stream
@return {Stream} file stream
@api private | Fontmin.prototype.createStream ( ) | javascript | ecomfe/fontmin | index.js | https://github.com/ecomfe/fontmin/blob/master/index.js | MIT |
Fontmin.prototype.getFiles = function () {
if (Buffer.isBuffer(this._src[0])) {
return bufferToVinyl.stream(this._src[0]);
}
var [src, options] = this.src();
return vfs.src(src, {encoding: false, ...options});
}; | Get files
@return {Stream} file stream
@api private | Fontmin.prototype.getFiles ( ) | javascript | ecomfe/fontmin | index.js | https://github.com/ecomfe/fontmin/blob/master/index.js | MIT |
Fontmin.prototype.use = function (plugin) {
this.streams.push(typeof plugin === 'function' ? plugin() : plugin);
return this;
};
/**
* Optimize files
*
* @param {Function} cb callback
* @return {Stream} file stream
* @api public
*/
Fontmin.prototype.run = function (cb) {
cb = cb || function () {};
var stream = this.createStream();
stream.on('error', cb);
stream.pipe(concat(cb.bind(null, null)));
return stream;
};
/**
* run Optimize files with return Promise
*
* @return {Array<Buffer>} file result
* @api public
*/
Fontmin.prototype.runAsync = function () {
return new Promise((resolve, reject) => {
var stream = this.createStream();
stream.on('error', reject);
stream.pipe(concat(resolve));
});
};
/**
* Create stream
*
* @return {Stream} file stream
* @api private
*/
Fontmin.prototype.createStream = function () {
this.streams.unshift(this.getFiles());
if (this.streams.length === 1) {
this.use(Fontmin.otf2ttf());
this.use(Fontmin.ttf2eot());
this.use(Fontmin.ttf2woff());
this.use(Fontmin.ttf2woff2());
this.use(Fontmin.ttf2svg());
this.use(Fontmin.css());
}
if (this.dest()) {
this.streams.push(
vfs.dest.apply(vfs, this.dest())
);
}
return combine(this.streams);
};
/**
* Get files
*
* @return {Stream} file stream
* @api private
*/
Fontmin.prototype.getFiles = function () {
if (Buffer.isBuffer(this._src[0])) {
return bufferToVinyl.stream(this._src[0]);
}
var [src, options] = this.src();
return vfs.src(src, {encoding: false, ...options});
};
/**
* plugins
*
* @type {Array}
*/
Fontmin.plugins = [
'glyph',
'ttf2eot',
'ttf2woff',
'ttf2woff2',
'ttf2svg',
'css',
'svg2ttf',
'svgs2ttf',
'otf2ttf'
];
// export pkged plugins
Fontmin.glyph = glyph;
Fontmin.ttf2eot = ttf2eot;
Fontmin.ttf2woff = ttf2woff;
Fontmin.ttf2woff2 = ttf2woff2;
Fontmin.ttf2svg = ttf2svg;
Fontmin.css = css;
Fontmin.svg2ttf = svg2ttf;
Fontmin.svgs2ttf = svgs2ttf;
Fontmin.otf2ttf = otf2ttf;
/**
* Module exports
*/
export { util, mime };
export default Fontmin;
Fontmin.util = util;
Fontmin.mime = mime; | Add a plugin to the middleware stack
@param {Function} plugin plugin
@return {Object} fontmin
@api public | Fontmin.prototype.use ( plugin ) | javascript | ecomfe/fontmin | index.js | https://github.com/ecomfe/fontmin/blob/master/index.js | MIT |
export function getFontFolder() {
return path.resolve({
win32: '/Windows/fonts',
darwin: '/Library/Fonts',
linux: '/usr/share/fonts/truetype'
}[process.platform]);
} | getFontFolder
@return {string} fontFolder | getFontFolder ( ) | javascript | ecomfe/fontmin | lib/util.js | https://github.com/ecomfe/fontmin/blob/master/lib/util.js | MIT |
export function getFonts() {
return fs.readdirSync(getFontFolder());
} | getFonts
@param {string} path path
@return {Array} fonts | getFonts ( ) | javascript | ecomfe/fontmin | lib/util.js | https://github.com/ecomfe/fontmin/blob/master/lib/util.js | MIT |
export function getPureText(str) {
// fix space
var emptyTextMap = {};
function replaceEmpty (word) {
emptyTextMap[word] = 1;
return '';
}
var pureText = String(str)
.replace(/[\s]/g, replaceEmpty)
.trim()
// .replace(/[\f]/g, '')
// .replace(/[\b]/g, '')
// .replace(/[\n]/g, '')
// .replace(/[\t]/g, '')
// .replace(/[\r]/g, '')
.replace(/[\u2028]/g, '')
.replace(/[\u2029]/g, '');
var emptyText = Object.keys(emptyTextMap).join('');
return pureText + emptyText;
} | getPureText
@see https://msdn.microsoft.com/zh-cn/library/ie/2yfce773
@see http://www.unicode.org/charts/
@param {string} str target text
@return {string} pure text | getPureText ( str ) | javascript | ecomfe/fontmin | lib/util.js | https://github.com/ecomfe/fontmin/blob/master/lib/util.js | MIT |
export function getUniqText(str) {
return _.uniq(
str.split('')
).join('');
} | getUniqText
@deprecated since version 0.9.9
@param {string} str target text
@return {string} uniq text | getUniqText ( str ) | javascript | ecomfe/fontmin | lib/util.js | https://github.com/ecomfe/fontmin/blob/master/lib/util.js | MIT |
export function getSubsetText(opts) {
var text = opts.text || '';
// trim
text && opts.trim && (text = getPureText(text));
// basicText
opts.basicText && (text += basicText);
return text;
} | get subset text
@param {Object} opts opts
@return {string} subset text | getSubsetText ( opts ) | javascript | ecomfe/fontmin | lib/util.js | https://github.com/ecomfe/fontmin/blob/master/lib/util.js | MIT |
export function string2unicodes(str) {
return _.uniq(codePoints(str));
} | string to unicodes
@param {string} str string
@return {Array} unicodes | string2unicodes ( str ) | javascript | ecomfe/fontmin | lib/util.js | https://github.com/ecomfe/fontmin/blob/master/lib/util.js | MIT |
export default function (opts) {
opts = _.extend({clone: false, hinting: true}, opts);
// prepare subset
var subsetText = util.getSubsetText(opts);
opts.subset = util.string2unicodes(subsetText);
return through.ctor({
objectMode: true
}, function (file, enc, cb) {
// check null
if (file.isNull()) {
cb(null, file);
return;
}
// check stream
if (file.isStream()) {
cb(new Error('Streaming is not supported'));
return;
}
// check otf
if (!isOtf(file.contents)) {
cb(null, file);
return;
}
// clone
if (opts.clone) {
this.push(file.clone(false));
}
// replace ext
file.path = replaceExt(file.path, '.ttf');
// ttf info
var ttfBuffer;
var ttfObj;
// try otf2ttf
try {
ttfObj = fonteditorCore.otf2ttfobject(b2ab(file.contents), opts);
ttfBuffer = ab2b(new fonteditorCore.TTFWriter(opts).write(ttfObj));
}
catch (ex) {
cb(ex);
}
if (ttfBuffer) {
file.contents = ttfBuffer;
file.ttfObject = ttfObj;
cb(null, file);
}
});
}; | otf2ttf fontmin plugin
@param {Object} opts opts
@return {Object} stream.Transform instance
@api public | (anonymous) ( opts ) | javascript | ecomfe/fontmin | plugins/otf2ttf.js | https://github.com/ecomfe/fontmin/blob/master/plugins/otf2ttf.js | MIT |
function SvgFont(name, opts) {
this.opts = _.extend(
{
adjust: {
leftSideBearing: 0,
rightSideBearing: 0,
ajdustToEmBox: true,
ajdustToEmPadding: 0
},
name: {
fontFamily: name,
fontSubFamily: name,
uniqueSubFamily: name,
postScriptName: name
}
},
opts
);
// empty ttfobj
var ttfobj = getEmptyttfObject.default();
// for save name
ttfobj.post.format = 2;
// new TTF
this.ttf = new fonteditorCore.TTF(ttfobj);
// set name
this.ttf.setName(this.opts.name);
// unicode start
this.startCode = opts.startCode || 0xe001;
} | SvgFont
@constructor
@param {string} name filename
@param {Object} opts opts | SvgFont ( name , opts ) | javascript | ecomfe/fontmin | plugins/svgs2ttf.js | https://github.com/ecomfe/fontmin/blob/master/plugins/svgs2ttf.js | MIT |
SvgFont.prototype.add = function (name, contents) {
var ttfObj = fonteditorCore.svg2ttfobject(
contents.toString('utf-8'),
{
combinePath: true
}
);
var glyf = ttfObj.glyf[0];
glyf.name = path.basename(name, '.svg');
if (!Array.isArray(glyf.unicode)) {
glyf.unicode = [this.startCode++];
}
this.ttf.addGlyf(glyf);
}; | add svg
@param {string} name svg basename
@param {buffer} contents svg contents | SvgFont.prototype.add ( name , contents ) | javascript | ecomfe/fontmin | plugins/svgs2ttf.js | https://github.com/ecomfe/fontmin/blob/master/plugins/svgs2ttf.js | MIT |
export default function (file, opts) {
if (!file) {
throw new Error('Missing file option for fontmin-svg2ttf');
}
opts = _.extend({hinting: true}, opts);
var firstFile;
var fileName;
var svgFont;
if (typeof file === 'string') {
// fix file ext
file = replaceExt(file, '.ttf');
// set file name
fileName = file;
}
else if (typeof file.path === 'string') {
fileName = path.basename(file.path);
firstFile = bufferToVinyl.file(null, fileName);
}
else {
throw new Error('Missing path in file options for fontmin-svg2ttf');
}
function bufferContents(file, enc, cb) {
// ignore empty files
if (file.isNull()) {
cb();
return;
}
// check stream
if (file.isStream()) {
this.emit('error', new Error('Streaming not supported'));
cb();
return;
}
// check svg
if (!isSvg(file.contents.toString())) {
cb();
return;
}
// set first file if not already set
if (!firstFile) {
firstFile = file;
}
// construct SvgFont instance
if (!svgFont) {
var fontName = opts.fontName || path.basename(fileName, '.ttf');
svgFont = new SvgFont(fontName, opts);
}
// add file to SvgFont instance
svgFont.add(file.relative, file.contents);
cb();
}
function endStream(cb) {
// no files passed in, no file goes out
if (!firstFile || !svgFont) {
cb();
return;
}
var joinedFile;
// if file opt was a file path
// clone everything from the first file
if (typeof file === 'string') {
joinedFile = firstFile.clone({
contents: false
});
joinedFile.path = path.join(firstFile.base, file);
}
else {
joinedFile = firstFile;
}
// complie svgfont
svgFont.compile();
// set contents
joinedFile.contents = svgFont.contents;
joinedFile.ttfObject = svgFont.ttf.ttf;
this.push(joinedFile);
cb();
}
return through.obj(bufferContents, endStream);
}; | svgs2ttf fontmin plugin
@param {string} file filename
@param {Object} opts opts
@param {string} opts.fontName font name
@return {Object} stream.Transform instance
@api public | (anonymous) ( file , opts ) | javascript | ecomfe/fontmin | plugins/svgs2ttf.js | https://github.com/ecomfe/fontmin/blob/master/plugins/svgs2ttf.js | MIT |
export default function (opts) {
opts = _.extend({clone: true}, opts);
return through.ctor({
objectMode: true
}, function (file, enc, cb) {
// check null
if (file.isNull()) {
cb(null, file);
return;
}
// check stream
if (file.isStream()) {
cb(new Error('Streaming is not supported'));
return;
}
// check ttf
if (!isTtf(file.contents)) {
cb(null, file);
return;
}
// clone
if (opts.clone) {
this.push(file.clone(false));
}
// ttf2woff2
var ouput;
try {
ouput = ttf2woff2(file.contents);
}
catch (ex) {
cb(ex, file);
}
if (ouput) {
file.path = replaceExt(file.path, '.woff2');
file.contents = ouput;
cb(null, file);
}
});
}; | wawoff2 fontmin plugin
@param {Object} opts opts
@return {Object} stream.Transform instance
@api public | (anonymous) ( opts ) | javascript | ecomfe/fontmin | plugins/ttf2woff2.js | https://github.com/ecomfe/fontmin/blob/master/plugins/ttf2woff2.js | MIT |
export default function (opts) {
opts = _.extend({clone: true}, opts);
return through.ctor({
objectMode: true
}, function (file, enc, cb) {
// check null
if (file.isNull()) {
cb(null, file);
return;
}
// check stream
if (file.isStream()) {
cb(new Error('Streaming is not supported'));
return;
}
// check ttf
if (!isTtf(file.contents)) {
cb(null, file);
return;
}
// clone
if (opts.clone) {
this.push(file.clone(false));
}
// replace ext
file.path = replaceExt(file.path, '.woff');
compileTtf(file.contents, opts, function (err, buffer) {
if (err) {
cb(err);
return;
}
file.contents = buffer;
cb(null, file);
});
});
}; | ttf2woff fontmin plugin
@param {Object} opts opts
@return {Object} stream.Transform instance
@api public | (anonymous) ( opts ) | javascript | ecomfe/fontmin | plugins/ttf2woff.js | https://github.com/ecomfe/fontmin/blob/master/plugins/ttf2woff.js | MIT |
export default function (opts) {
opts = _.extend({clone: true}, opts);
return through.ctor({
objectMode: true
}, function (file, enc, cb) {
// check null
if (file.isNull()) {
cb(null, file);
return;
}
// check stream
if (file.isStream()) {
cb(new Error('Streaming is not supported'));
return;
}
// check ttf
if (!isTtf(file.contents)) {
cb(null, file);
return;
}
// clone
if (opts.clone) {
this.push(file.clone(false));
}
// replace ext
file.path = replaceExt(file.path, '.svg');
compileTtf(file.contents, function (err, buffer) {
if (err) {
cb(err);
return;
}
file.contents = buffer;
cb(null, file);
});
});
}; | ttf2svg fontmin plugin
@param {Object} opts opts
@return {Object} stream.Transform instance
@api public | (anonymous) ( opts ) | javascript | ecomfe/fontmin | plugins/ttf2svg.js | https://github.com/ecomfe/fontmin/blob/master/plugins/ttf2svg.js | MIT |
function listUnicode(unicode) {
return unicode.map(function (u) {
return '\\' + u.toString(16);
}).join(',');
} | listUnicode
@param {Array} unicode unicode
@return {string} unicode string | listUnicode ( unicode ) | javascript | ecomfe/fontmin | plugins/css.js | https://github.com/ecomfe/fontmin/blob/master/plugins/css.js | MIT |
function getFontFamily(fontInfo, ttf, opts) {
var fontFamily = opts.fontFamily;
// Call transform function
if (typeof fontFamily === 'function') {
fontFamily = fontFamily(_.cloneDeep(fontInfo), ttf);
}
return fontFamily || ttf.name.fontFamily || fontInfo.fontFile;
} | get font family name
@param {Object} fontInfo font info object
@param {ttfObject} ttf ttfObject
@param {Object} opts opts
@return {string} font family name | getFontFamily ( fontInfo , ttf , opts ) | javascript | ecomfe/fontmin | plugins/css.js | https://github.com/ecomfe/fontmin/blob/master/plugins/css.js | MIT |
export default function (opts) {
opts = opts || {};
return through.ctor({
objectMode: true
}, function (file, enc, cb) {
// check null
if (file.isNull()) {
cb(null, file);
return;
}
// check stream
if (file.isStream()) {
cb(new Error('Streaming is not supported'));
return;
}
// check ttf
if (!isTtf(file.contents)) {
cb(null, file);
return;
}
// clone
this.push(file.clone(false));
file.path = replaceExt(file.path, '.css');
var fontFile = opts.filename || path.basename(file.path, '.css');
// font data
var fontInfo = {
fontFile: fontFile,
fontPath: '',
base64: '',
glyph: false,
iconPrefix: 'icon',
local: false
};
// opts
_.extend(fontInfo, opts);
// ttf obj
var ttfObject = file.ttfObject || {
name: {}
};
// glyph
if (opts.glyph && ttfObject.glyf) {
_.extend(
fontInfo,
getGlyfList(ttfObject)
);
}
// font family
fontInfo.fontFamily = getFontFamily(fontInfo, ttfObject, opts);
// rewrite font family as filename
if (opts.asFileName) {
fontInfo.fontFamily = fontFile;
}
// base64
if (opts.base64) {
fontInfo.base64 = ''
+ 'data:application/x-font-ttf;charset=utf-8;base64,'
+ b2a(file.contents);
}
// local
if (fontInfo.local === true) {
fontInfo.local = fontInfo.fontFamily;
}
// render
var output = _.attempt(function (data) {
return Buffer.from(renderCss(data));
}, fontInfo);
if (_.isError(output)) {
cb(output, file);
}
else {
file.contents = output;
cb(null, file);
}
});
}; | css fontmin plugin
@param {Object} opts opts
@param {boolean=} opts.glyph generate class for each glyph. default = false
@param {boolean=} opts.base64 inject base64
@param {string=} opts.iconPrefix icon prefix
@param {string=} opts.filename set filename
@param {(string|FontFamilyTransform)=} opts.fontFamily fontFamily
@return {Object} stream.Transform instance
@api public | (anonymous) ( opts ) | javascript | ecomfe/fontmin | plugins/css.js | https://github.com/ecomfe/fontmin/blob/master/plugins/css.js | MIT |
export default function (opts) {
opts = _.extend({clone: true, hinting: true}, opts);
return through.ctor({
objectMode: true
}, function (file, enc, cb) {
// check null
if (file.isNull()) {
cb(null, file);
return;
}
// check stream
if (file.isStream()) {
cb(new Error('Streaming is not supported'));
return;
}
// check svg
if (!isSvg(file.contents.toString())) {
cb(null, file);
return;
}
// clone
if (opts.clone) {
this.push(file.clone(false));
}
// replace ext
file.path = replaceExt(file.path, '.ttf');
// ttf buffer
var output;
try {
var ttfObj = fonteditorCore.svg2ttfobject(
file.contents.toString('utf-8')
);
output = ab2b(new fonteditorCore.TTFWriter(opts).write(ttfObj));
}
catch (ex) {
cb(ex);
}
if (output) {
file.contents = output;
cb(null, file);
}
});
}; | svg2ttf fontmin plugin
@param {Object} opts opts
@return {Object} stream.Transform instance
@api public | (anonymous) ( opts ) | javascript | ecomfe/fontmin | plugins/svg2ttf.js | https://github.com/ecomfe/fontmin/blob/master/plugins/svg2ttf.js | MIT |
function getSubsetGlyfs(ttf, subset) {
var glyphs = [];
var indexList = ttf.findGlyf({
unicode: subset || []
});
if (indexList.length) {
glyphs = ttf.getGlyf(indexList);
}
glyphs.unshift(ttf.get().glyf[0]);
return glyphs;
} | getSubsetGlyfs
@param {ttfObject} ttf ttfobj
@param {Array} subset subset unicode
@return {Array} glyfs array | getSubsetGlyfs ( ttf , subset ) | javascript | ecomfe/fontmin | plugins/glyph.js | https://github.com/ecomfe/fontmin/blob/master/plugins/glyph.js | MIT |
function minifyFontObject(ttfObject, subset, plugin) {
// check null
if (subset.length === 0) {
return ttfObject;
}
// new TTF Object
var ttf = new fonteditorCore.TTF(ttfObject);
// get target glyfs then set
ttf.setGlyf(getSubsetGlyfs(ttf, subset));
// use plugin
if (_.isFunction(plugin)) {
plugin(ttf);
}
return ttf.get();
} | minifyFontObject
@param {Object} ttfObject ttfObject
@param {Array} subset subset
@param {Function=} plugin use plugin
@return {Object} ttfObject | minifyFontObject ( ttfObject , subset , plugin ) | javascript | ecomfe/fontmin | plugins/glyph.js | https://github.com/ecomfe/fontmin/blob/master/plugins/glyph.js | MIT |
function minifyTtf(contents, opts) {
opts = opts || {};
var ttfobj = contents;
if (Buffer.isBuffer(contents)) {
ttfobj = new fonteditorCore.TTFReader(opts).read(b2ab(contents));
}
var miniObj = minifyFontObject(
ttfobj,
opts.subset,
opts.use
);
var ttfBuffer = ab2b(
new fonteditorCore.TTFWriter(Object.assign({writeZeroContoursGlyfData: true}, opts)).write(miniObj)
);
return {
object: miniObj,
buffer: ttfBuffer
};
} | minifyTtf
@param {Buffer|Object} contents contents
@param {Object} opts opts
@return {Buffer} buffer | minifyTtf ( contents , opts ) | javascript | ecomfe/fontmin | plugins/glyph.js | https://github.com/ecomfe/fontmin/blob/master/plugins/glyph.js | MIT |
export default function (opts) {
opts = _.extend({hinting: true, trim: true}, opts);
// prepare subset
var subsetText = util.getSubsetText(opts);
opts.subset = util.string2unicodes(subsetText);
return through.ctor({
objectMode: true
}, function (file, enc, cb) {
// check null
if (file.isNull()) {
cb(null, file);
return;
}
// check stream
if (file.isStream()) {
cb(new Error('Streaming is not supported'));
return;
}
// check ttf
if (!isTtf(file.contents)) {
cb(null, file);
return;
}
try {
// write file buffer
var miniTtf = minifyTtf(
file.ttfObject || file.contents,
opts
);
file.contents = miniTtf.buffer;
file.ttfObject = miniTtf.object;
cb(null, file);
}
catch (err) {
cb(err);
}
});
}; | glyph fontmin plugin
@param {Object} opts opts
@param {string=} opts.text text
@param {boolean=} opts.basicText useBasicText
@param {boolean=} opts.hinting hint
@param {Function=} opts.use plugin
@return {Object} stream.Transform instance
@api public | (anonymous) ( opts ) | javascript | ecomfe/fontmin | plugins/glyph.js | https://github.com/ecomfe/fontmin/blob/master/plugins/glyph.js | MIT |
export default function (opts) {
opts = _.extend({clone: true}, opts);
return through.ctor({
objectMode: true
}, function (file, enc, cb) {
// check null
if (file.isNull()) {
cb(null, file);
return;
}
// check stream
if (file.isStream()) {
cb(new Error('Streaming is not supported'));
return;
}
// check ttf
if (!isTtf(file.contents)) {
cb(null, file);
return;
}
// clone
if (opts.clone) {
this.push(file.clone(false));
}
// replace ext
file.path = replaceExt(file.path, '.eot');
compileTtf(file.contents, function (err, buffer) {
if (err) {
cb(err);
return;
}
file.contents = buffer;
cb(null, file);
});
});
}; | ttf2eot fontmin plugin
@param {Object} opts opts
@return {Object} stream.Transform instance
@api public | (anonymous) ( opts ) | javascript | ecomfe/fontmin | plugins/ttf2eot.js | https://github.com/ecomfe/fontmin/blob/master/plugins/ttf2eot.js | MIT |
function isElement(element) {
return !!(element && element.nodeType === Node.ELEMENT_NODE && // element instanceof HTMLElement &&
typeof element.getBoundingClientRect === 'function' && !(element.compareDocumentPosition(document) & Node.DOCUMENT_POSITION_DISCONNECTED));
} | @param {Element} element - A target element.
@returns {boolean} `true` if connected element. | isElement ( element ) | javascript | anseki/plain-draggable | plain-draggable-limit-debug.esm.js | https://github.com/anseki/plain-draggable/blob/master/plain-draggable-limit-debug.esm.js | MIT |
function validBBox(bBox) {
if (!isObject(bBox)) {
return null;
}
var value;
if (isFinite(value = bBox.left) || isFinite(value = bBox.x)) {
bBox.left = bBox.x = value;
} else {
return null;
}
if (isFinite(value = bBox.top) || isFinite(value = bBox.y)) {
bBox.top = bBox.y = value;
} else {
return null;
}
if (isFinite(bBox.width) && bBox.width >= 0) {
bBox.right = bBox.left + bBox.width;
} else if (isFinite(bBox.right) && bBox.right >= bBox.left) {
bBox.width = bBox.right - bBox.left;
} else {
return null;
}
if (isFinite(bBox.height) && bBox.height >= 0) {
bBox.bottom = bBox.top + bBox.height;
} else if (isFinite(bBox.bottom) && bBox.bottom >= bBox.top) {
bBox.height = bBox.bottom - bBox.top;
} else {
return null;
}
return bBox;
} | @param {Object} bBox - A target object.
@returns {(BBox|null)} A normalized `BBox`, or null if `bBox` is invalid. | validBBox ( bBox ) | javascript | anseki/plain-draggable | plain-draggable-limit-debug.esm.js | https://github.com/anseki/plain-draggable/blob/master/plain-draggable-limit-debug.esm.js | MIT |
function validPPBBox(bBox) {
if (!isObject(bBox)) {
return null;
}
var ppValue;
if ((ppValue = validPPValue(bBox.left)) || (ppValue = validPPValue(bBox.x))) {
bBox.left = bBox.x = ppValue;
} else {
return null;
}
if ((ppValue = validPPValue(bBox.top)) || (ppValue = validPPValue(bBox.y))) {
bBox.top = bBox.y = ppValue;
} else {
return null;
}
if ((ppValue = validPPValue(bBox.width)) && ppValue.value >= 0) {
bBox.width = ppValue;
delete bBox.right;
} else if (ppValue = validPPValue(bBox.right)) {
bBox.right = ppValue;
delete bBox.width;
} else {
return null;
}
if ((ppValue = validPPValue(bBox.height)) && ppValue.value >= 0) {
bBox.height = ppValue;
delete bBox.bottom;
} else if (ppValue = validPPValue(bBox.bottom)) {
bBox.bottom = ppValue;
delete bBox.height;
} else {
return null;
}
return bBox;
} | @param {Object} bBox - A target object.
@returns {(PPBBox|null)} A normalized `PPBBox`, or null if `bBox` is invalid. | validPPBBox ( bBox ) | javascript | anseki/plain-draggable | plain-draggable-limit-debug.esm.js | https://github.com/anseki/plain-draggable/blob/master/plain-draggable-limit-debug.esm.js | MIT |
function getBBox(element, getPaddingBox) {
var rect = element.getBoundingClientRect(),
bBox = {
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height
};
bBox.left += window.pageXOffset;
bBox.top += window.pageYOffset;
if (getPaddingBox) {
var style = window.getComputedStyle(element, ''),
borderTop = parseFloat(style.borderTopWidth) || 0,
borderRight = parseFloat(style.borderRightWidth) || 0,
borderBottom = parseFloat(style.borderBottomWidth) || 0,
borderLeft = parseFloat(style.borderLeftWidth) || 0;
bBox.left += borderLeft;
bBox.top += borderTop;
bBox.width -= borderLeft + borderRight;
bBox.height -= borderTop + borderBottom;
}
return validBBox(bBox);
} | @param {Element} element - A target element.
@param {?boolean} getPaddingBox - Get padding-box instead of border-box as bounding-box.
@returns {BBox} A bounding-box of `element`. | getBBox ( element , getPaddingBox ) | javascript | anseki/plain-draggable | plain-draggable-limit-debug.esm.js | https://github.com/anseki/plain-draggable/blob/master/plain-draggable-limit-debug.esm.js | MIT |
function initAnim(element, gpuTrigger) {
var style = element.style;
style.webkitTapHighlightColor = 'transparent'; // Only when it has no shadow
var cssPropBoxShadow = CSSPrefix.getName('boxShadow'),
boxShadow = window.getComputedStyle(element, '')[cssPropBoxShadow];
if (!boxShadow || boxShadow === 'none') {
style[cssPropBoxShadow] = '0 0 1px transparent';
}
if (gpuTrigger && cssPropTransform) {
style[cssPropTransform] = 'translateZ(0)';
}
return element;
} | Optimize an element for animation.
@param {Element} element - A target element.
@param {?boolean} gpuTrigger - Initialize for SVGElement if `true`.
@returns {Element} A target element. | initAnim ( element , gpuTrigger ) | javascript | anseki/plain-draggable | plain-draggable-limit-debug.esm.js | https://github.com/anseki/plain-draggable/blob/master/plain-draggable-limit-debug.esm.js | MIT |
function moveTranslate(props, position) {
var elementBBox = props.elementBBox;
if (position.left !== elementBBox.left || position.top !== elementBBox.top) {
var offset = props.htmlOffset;
props.elementStyle[cssPropTransform] = "translate(".concat(position.left + offset.left, "px, ").concat(position.top + offset.top, "px)");
return true;
}
return false;
} | Move by `translate`.
@param {props} props - `props` of instance.
@param {{left: number, top: number}} position - New position.
@returns {boolean} `true` if it was moved. | moveTranslate ( props , position ) | javascript | anseki/plain-draggable | plain-draggable-limit-debug.esm.js | https://github.com/anseki/plain-draggable/blob/master/plain-draggable-limit-debug.esm.js | MIT |
function move(props, position, cbCheck) {
var elementBBox = props.elementBBox;
function fix() {
if (props.minLeft >= props.maxLeft) {
// Disabled
position.left = elementBBox.left;
} else if (position.left < props.minLeft) {
position.left = props.minLeft;
} else if (position.left > props.maxLeft) {
position.left = props.maxLeft;
}
if (props.minTop >= props.maxTop) {
// Disabled
position.top = elementBBox.top;
} else if (position.top < props.minTop) {
position.top = props.minTop;
} else if (position.top > props.maxTop) {
position.top = props.maxTop;
}
}
fix();
if (cbCheck) {
if (cbCheck(position) === false) {
return false;
}
fix(); // Again
}
var moved = props.moveElm(props, position);
if (moved) {
// Update elementBBox
props.elementBBox = validBBox({
left: position.left,
top: position.top,
width: elementBBox.width,
height: elementBBox.height
});
}
return moved;
} | Set `props.element` position.
@param {props} props - `props` of instance.
@param {{left: number, top: number}} position - New position.
@param {function} [cbCheck] - Callback that is called with valid position, cancel moving if it returns `false`.
@returns {boolean} `true` if it was moved. | move ( props , position , cbCheck ) | javascript | anseki/plain-draggable | plain-draggable-limit-debug.esm.js | https://github.com/anseki/plain-draggable/blob/master/plain-draggable-limit-debug.esm.js | MIT |
function initTranslate(props) {
var element = props.element,
elementStyle = props.elementStyle,
curPosition = getBBox(element),
// Get BBox before change style.
RESTORE_PROPS = ['display', 'marginTop', 'marginBottom', 'width', 'height'];
RESTORE_PROPS.unshift(cssPropTransform); // Reset `transition-property` every time because it might be changed frequently.
var orgTransitionProperty = elementStyle[cssPropTransitionProperty];
elementStyle[cssPropTransitionProperty] = 'none'; // Disable animation
var fixPosition = getBBox(element);
if (!props.orgStyle) {
props.orgStyle = RESTORE_PROPS.reduce(function (orgStyle, prop) {
orgStyle[prop] = elementStyle[prop] || '';
return orgStyle;
}, {});
props.lastStyle = {};
} else {
RESTORE_PROPS.forEach(function (prop) {
// Skip this if it seems user changed it. (it can't check perfectly.)
if (props.lastStyle[prop] == null || elementStyle[prop] === props.lastStyle[prop]) {
elementStyle[prop] = props.orgStyle[prop];
}
});
}
var orgSize = getBBox(element),
cmpStyle = window.getComputedStyle(element, ''); // https://www.w3.org/TR/css-transforms-1/#transformable-element
if (cmpStyle.display === 'inline') {
elementStyle.display = 'inline-block';
['Top', 'Bottom'].forEach(function (dirProp) {
var padding = parseFloat(cmpStyle["padding".concat(dirProp)]); // paddingTop/Bottom make padding but don't make space -> negative margin in inline-block
// marginTop/Bottom don't work in inline element -> `0` in inline-block
elementStyle["margin".concat(dirProp)] = padding ? "-".concat(padding, "px") : '0';
});
}
elementStyle[cssPropTransform] = 'translate(0, 0)'; // Get document offset.
var newBBox = getBBox(element);
var offset = props.htmlOffset = {
left: newBBox.left ? -newBBox.left : 0,
top: newBBox.top ? -newBBox.top : 0
}; // avoid `-0`
// Restore position
elementStyle[cssPropTransform] = "translate(".concat(curPosition.left + offset.left, "px, ").concat(curPosition.top + offset.top, "px)"); // Restore size
['width', 'height'].forEach(function (prop) {
if (newBBox[prop] !== orgSize[prop]) {
// Ignore `box-sizing`
elementStyle[prop] = orgSize[prop] + 'px';
newBBox = getBBox(element);
if (newBBox[prop] !== orgSize[prop]) {
// Retry
elementStyle[prop] = orgSize[prop] - (newBBox[prop] - orgSize[prop]) + 'px';
}
}
props.lastStyle[prop] = elementStyle[prop];
}); // Restore `transition-property`
element.offsetWidth;
/* force reflow */
// eslint-disable-line no-unused-expressions
elementStyle[cssPropTransitionProperty] = orgTransitionProperty;
if (fixPosition.left !== curPosition.left || fixPosition.top !== curPosition.top) {
// It seems that it is moving.
elementStyle[cssPropTransform] = "translate(".concat(fixPosition.left + offset.left, "px, ").concat(fixPosition.top + offset.top, "px)");
}
return fixPosition;
} | Initialize HTMLElement for `translate`, and get `offset` that is used by `moveTranslate`.
@param {props} props - `props` of instance.
@returns {BBox} Current BBox without animation, i.e. left/top properties. | initTranslate ( props ) | javascript | anseki/plain-draggable | plain-draggable-limit-debug.esm.js | https://github.com/anseki/plain-draggable/blob/master/plain-draggable-limit-debug.esm.js | MIT |
function initBBox(props, eventType) {
// eslint-disable-line no-unused-vars
var docBBox = getBBox(document.documentElement),
elementBBox = props.elementBBox = props.initElm(props),
// reset offset etc.
containmentBBox = props.containmentBBox = props.containmentIsBBox ? resolvePPBBox(props.options.containment, docBBox) || docBBox : getBBox(props.options.containment, true);
props.minLeft = containmentBBox.left;
props.maxLeft = containmentBBox.right - elementBBox.width;
props.minTop = containmentBBox.top;
props.maxTop = containmentBBox.bottom - elementBBox.height; // Adjust position
move(props, {
left: elementBBox.left,
top: elementBBox.top
});
window.initBBoxDone = true; // [DEBUG/]
} | Set `elementBBox`, `containmentBBox`, `min/max``Left/Top` and `snapTargets`.
@param {props} props - `props` of instance.
@param {string} [eventType] - A type of event that kicked this method.
@returns {void} | initBBox ( props , eventType ) | javascript | anseki/plain-draggable | plain-draggable-limit-debug.esm.js | https://github.com/anseki/plain-draggable/blob/master/plain-draggable-limit-debug.esm.js | MIT |
function dragEnd(props) {
setDraggableCursor(props.options.handle, props.orgCursor);
body.style.cursor = cssOrgValueBodyCursor;
if (props.options.zIndex !== false) {
props.elementStyle.zIndex = props.orgZIndex;
}
if (cssPropUserSelect) {
body.style[cssPropUserSelect] = cssOrgValueBodyUserSelect;
}
var classList = mClassList(props.element);
if (movingClass) {
classList.remove(movingClass);
}
if (draggingClass) {
classList.remove(draggingClass);
}
activeProps = null;
pointerEvent.cancel(); // Reset pointer (activeProps must be null because this calls endHandler)
if (props.onDragEnd) {
props.onDragEnd({
left: props.elementBBox.left,
top: props.elementBBox.top
});
}
} | @param {props} props - `props` of instance.
@returns {void} | dragEnd ( props ) | javascript | anseki/plain-draggable | plain-draggable-limit-debug.esm.js | https://github.com/anseki/plain-draggable/blob/master/plain-draggable-limit-debug.esm.js | MIT |
function dragStart(props, pointerXY) {
if (props.disabled) {
return false;
}
if (props.onDragStart && props.onDragStart(pointerXY) === false) {
return false;
}
if (activeProps) {
dragEnd(activeProps);
} // activeItem is normally null by pointerEvent.end.
setDraggingCursor(props.options.handle);
body.style.cursor = cssValueDraggingCursor || // If it is `false` or `''`
window.getComputedStyle(props.options.handle, '').cursor;
if (props.options.zIndex !== false) {
props.elementStyle.zIndex = props.options.zIndex;
}
if (cssPropUserSelect) {
body.style[cssPropUserSelect] = 'none';
}
if (draggingClass) {
mClassList(props.element).add(draggingClass);
}
activeProps = props;
hasMoved = false;
pointerOffset.left = props.elementBBox.left - (pointerXY.clientX + window.pageXOffset);
pointerOffset.top = props.elementBBox.top - (pointerXY.clientY + window.pageYOffset);
return true;
} | @param {props} props - `props` of instance.
@param {{clientX, clientY}} pointerXY - This might be MouseEvent, Touch of TouchEvent or Object.
@returns {boolean} `true` if it started. | dragStart ( props , pointerXY ) | javascript | anseki/plain-draggable | plain-draggable-limit-debug.esm.js | https://github.com/anseki/plain-draggable/blob/master/plain-draggable-limit-debug.esm.js | MIT |
function _setOptions(props, newOptions) {
var options = props.options;
var needsInitBBox; // containment
if (newOptions.containment) {
var bBox;
if (isElement(newOptions.containment)) {
// Specific element
if (newOptions.containment !== options.containment) {
options.containment = newOptions.containment;
props.containmentIsBBox = false;
needsInitBBox = true;
}
} else if ((bBox = validPPBBox(copyTree(newOptions.containment))) && // bBox
hasChanged(bBox, options.containment)) {
options.containment = bBox;
props.containmentIsBBox = true;
needsInitBBox = true;
}
}
if (needsInitBBox) {
initBBox(props);
} // handle
if (isElement(newOptions.handle) && newOptions.handle !== options.handle) {
if (options.handle) {
// Restore
options.handle.style.cursor = props.orgCursor;
if (cssPropUserSelect) {
options.handle.style[cssPropUserSelect] = props.orgUserSelect;
}
pointerEvent.removeStartHandler(options.handle, props.pointerEventHandlerId);
}
var handle = options.handle = newOptions.handle;
props.orgCursor = handle.style.cursor;
setDraggableCursor(handle, props.orgCursor);
if (cssPropUserSelect) {
props.orgUserSelect = handle.style[cssPropUserSelect];
handle.style[cssPropUserSelect] = 'none';
}
pointerEvent.addStartHandler(handle, props.pointerEventHandlerId);
} // zIndex
if (isFinite(newOptions.zIndex) || newOptions.zIndex === false) {
options.zIndex = newOptions.zIndex;
if (props === activeProps) {
props.elementStyle.zIndex = options.zIndex === false ? props.orgZIndex : options.zIndex;
}
} // left/top
var position = {
left: props.elementBBox.left,
top: props.elementBBox.top
};
var needsMove;
if (isFinite(newOptions.left) && newOptions.left !== position.left) {
position.left = newOptions.left;
needsMove = true;
}
if (isFinite(newOptions.top) && newOptions.top !== position.top) {
position.top = newOptions.top;
needsMove = true;
}
if (needsMove) {
move(props, position);
} // Event listeners
['onDrag', 'onMove', 'onDragStart', 'onMoveStart', 'onDragEnd'].forEach(function (option) {
if (typeof newOptions[option] === 'function') {
options[option] = newOptions[option];
props[option] = options[option].bind(props.ins);
} else if (newOptions.hasOwnProperty(option) && newOptions[option] == null) {
options[option] = props[option] = void 0;
}
});
} | @param {props} props - `props` of instance.
@param {Object} newOptions - New options.
@returns {void} | _setOptions ( props , newOptions ) | javascript | anseki/plain-draggable | plain-draggable-limit-debug.esm.js | https://github.com/anseki/plain-draggable/blob/master/plain-draggable-limit-debug.esm.js | MIT |
function PlainDraggable(element, options) {
_classCallCheck(this, PlainDraggable);
var props = {
ins: this,
options: {
// Initial options (not default)
zIndex: ZINDEX // Initial state.
},
disabled: false
};
Object.defineProperty(this, '_id', {
value: ++insId
});
props._id = this._id;
insProps[this._id] = props;
props.initArguments = Array.prototype.slice.call(arguments); // [DEBUG/]
if (!isElement(element) || element === body) {
throw new Error('This element is not accepted.');
}
if (!options) {
options = {};
} else if (!isObject(options)) {
throw new Error('Invalid options.');
}
var gpuTrigger = true;
var cssPropWillChange = CSSPrefix.getName('willChange');
if (cssPropWillChange) {
gpuTrigger = false;
}
if (!options.leftTop && cssPropTransform) {
// translate
if (cssPropWillChange) {
element.style[cssPropWillChange] = 'transform';
}
props.initElm = initTranslate;
props.moveElm = moveTranslate;
} else {
// left and top
throw new Error('`transform` is not supported.');
}
props.element = initAnim(element, gpuTrigger);
props.elementStyle = element.style;
props.orgZIndex = props.elementStyle.zIndex;
if (draggableClass) {
mClassList(element).add(draggableClass);
}
props.pointerEventHandlerId = pointerEvent.regStartHandler(function (pointerXY) {
return dragStart(props, pointerXY);
}); // Default options
if (!options.containment) {
var parent;
options.containment = (parent = element.parentNode) && isElement(parent) ? parent : body;
}
if (!options.handle) {
options.handle = element;
}
_setOptions(props, options);
} | Create a `PlainDraggable` instance.
@param {Element} element - Target element.
@param {Object} [options] - Options. | PlainDraggable ( element , options ) | javascript | anseki/plain-draggable | plain-draggable-limit-debug.esm.js | https://github.com/anseki/plain-draggable/blob/master/plain-draggable-limit-debug.esm.js | MIT |
add: function add(listener) {
var task;
if (indexOfTasks(listener) === -1) {
tasks.push(task = {
listener: listener
});
return function (event) {
task.event = event;
if (!requestID) {
step();
}
};
}
return null;
}, | @param {function} listener - An event listener.
@returns {(function|null)} A wrapped event listener. | add ( listener ) | javascript | anseki/plain-draggable | test/plain-draggable-limit.js | https://github.com/anseki/plain-draggable/blob/master/test/plain-draggable-limit.js | MIT |
scrollFrame.move = (element, xyMoveArgs, scrollXY) => {
cancelAnim.call(window, requestID);
frameUpdate(); // Update current data now because it might be not continuation.
// Re-use lastValue
if (curElement === element) {
if (xyMoveArgs.x && curXyMoveArgs.x) { xyMoveArgs.x.lastValue = curXyMoveArgs.x.lastValue; }
if (xyMoveArgs.y && curXyMoveArgs.y) { xyMoveArgs.y.lastValue = curXyMoveArgs.y.lastValue; }
}
curElement = element;
curXyMoveArgs = xyMoveArgs;
curScrollXY = scrollXY;
const now = Date.now();
['x', 'y'].forEach(xy => {
const moveArgs = curXyMoveArgs[xy];
if (moveArgs) { moveArgs.lastFrameTime = now; }
});
requestID = requestAnim.call(window, frame);
}; | @param {Element} element - A target element.
@param {{x: ?MoveArgs, y: ?MoveArgs}} xyMoveArgs - MoveArgs for x and y
@param {function} scrollXY - (element: Element, xy: string, value: number) => number
@returns {void} | = | javascript | anseki/plain-draggable | src/plain-draggable.proc.js | https://github.com/anseki/plain-draggable/blob/master/src/plain-draggable.proc.js | MIT |
function viewPoint2SvgPoint(props, clientX, clientY) {
const svgPoint = props.svgPoint;
svgPoint.x = clientX;
svgPoint.y = clientY;
return svgPoint.matrixTransform(props.svgCtmElement.getScreenCTM().inverse());
} | Get SVG coordinates from viewport coordinates.
@param {props} props - `props` of instance.
@param {number} clientX - viewport X.
@param {number} clientY - viewport Y.
@returns {SVGPoint} SVG coordinates. | viewPoint2SvgPoint ( props , clientX , clientY ) | javascript | anseki/plain-draggable | src/plain-draggable.proc.js | https://github.com/anseki/plain-draggable/blob/master/src/plain-draggable.proc.js | MIT |
function moveLeftTop(props, position) {
const elementBBox = props.elementBBox,
elementStyle = props.elementStyle,
offset = props.htmlOffset;
let moved = false;
if (position.left !== elementBBox.left) {
elementStyle.left = position.left + offset.left + 'px';
moved = true;
}
if (position.top !== elementBBox.top) {
elementStyle.top = position.top + offset.top + 'px';
moved = true;
}
return moved;
} | Move by `left` and `top`.
@param {props} props - `props` of instance.
@param {{left: number, top: number}} position - New position.
@returns {boolean} `true` if it was moved. | moveLeftTop ( props , position ) | javascript | anseki/plain-draggable | src/plain-draggable.proc.js | https://github.com/anseki/plain-draggable/blob/master/src/plain-draggable.proc.js | MIT |
function moveSvg(props, position) {
const elementBBox = props.elementBBox;
if (position.left !== elementBBox.left || position.top !== elementBBox.top) {
const offset = props.svgOffset,
originBBox = props.svgOriginBBox,
point = viewPoint2SvgPoint(props,
position.left - window.pageXOffset, position.top - window.pageYOffset);
props.svgTransform.setTranslate(point.x + offset.x - originBBox.x, point.y + offset.y - originBBox.y);
return true;
}
return false;
} | Move SVGElement.
@param {props} props - `props` of instance.
@param {{left: number, top: number}} position - New position.
@returns {boolean} `true` if it was moved. | moveSvg ( props , position ) | javascript | anseki/plain-draggable | src/plain-draggable.proc.js | https://github.com/anseki/plain-draggable/blob/master/src/plain-draggable.proc.js | MIT |
function initLeftTop(props) {
const element = props.element,
elementStyle = props.elementStyle,
curPosition = getBBox(element), // Get BBox before change style.
RESTORE_PROPS = ['position', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'width', 'height'];
// Reset `transition-property` every time because it might be changed frequently.
const orgTransitionProperty = elementStyle[cssPropTransitionProperty];
elementStyle[cssPropTransitionProperty] = 'none'; // Disable animation
const fixPosition = getBBox(element);
if (!props.orgStyle) {
props.orgStyle = RESTORE_PROPS.reduce((orgStyle, prop) => {
orgStyle[prop] = elementStyle[prop] || '';
return orgStyle;
}, {});
props.lastStyle = {};
} else {
RESTORE_PROPS.forEach(prop => {
// Skip this if it seems user changed it. (it can't check perfectly.)
if (props.lastStyle[prop] == null || elementStyle[prop] === props.lastStyle[prop]) {
elementStyle[prop] = props.orgStyle[prop];
}
});
}
const orgSize = getBBox(element);
elementStyle.position = 'absolute';
elementStyle.left = elementStyle.top = elementStyle.margin = '0';
// Get document offset.
let newBBox = getBBox(element);
const offset = props.htmlOffset =
{left: newBBox.left ? -newBBox.left : 0, top: newBBox.top ? -newBBox.top : 0}; // avoid `-0`
// Restore position
elementStyle.left = curPosition.left + offset.left + 'px';
elementStyle.top = curPosition.top + offset.top + 'px';
// Restore size
['width', 'height'].forEach(prop => {
if (newBBox[prop] !== orgSize[prop]) {
// Ignore `box-sizing`
elementStyle[prop] = orgSize[prop] + 'px';
newBBox = getBBox(element);
if (newBBox[prop] !== orgSize[prop]) { // Retry
elementStyle[prop] = orgSize[prop] - (newBBox[prop] - orgSize[prop]) + 'px';
}
}
props.lastStyle[prop] = elementStyle[prop];
});
// Restore `transition-property`
element.offsetWidth; /* force reflow */ // eslint-disable-line no-unused-expressions
elementStyle[cssPropTransitionProperty] = orgTransitionProperty;
if (fixPosition.left !== curPosition.left || fixPosition.top !== curPosition.top) {
// It seems that it is moving.
elementStyle.left = fixPosition.left + offset.left + 'px';
elementStyle.top = fixPosition.top + offset.top + 'px';
}
return fixPosition;
} | Initialize HTMLElement for `left` and `top`, and get `offset` that is used by `moveLeftTop`.
@param {props} props - `props` of instance.
@returns {BBox} Current BBox without animation, i.e. left/top properties. | initLeftTop ( props ) | javascript | anseki/plain-draggable | src/plain-draggable.proc.js | https://github.com/anseki/plain-draggable/blob/master/src/plain-draggable.proc.js | MIT |
function initSvg(props) {
const element = props.element,
svgTransform = props.svgTransform,
curRect = element.getBoundingClientRect(), // Get Rect before change position.
fixPosition = getBBox(element);
svgTransform.setTranslate(0, 0);
const originBBox = props.svgOriginBBox = element.getBBox(),
// Try to get SVG coordinates of current position.
newRect = element.getBoundingClientRect(),
originPoint = viewPoint2SvgPoint(props, newRect.left, newRect.top),
// Gecko bug, getScreenCTM returns incorrect CTM, and originPoint might not be current position.
offset = props.svgOffset = {x: originBBox.x - originPoint.x, y: originBBox.y - originPoint.y},
// Restore position
curPoint = viewPoint2SvgPoint(props, curRect.left, curRect.top);
svgTransform.setTranslate(curPoint.x + offset.x - originBBox.x, curPoint.y + offset.y - originBBox.y);
return fixPosition;
} | Initialize SVGElement, and get `offset` that is used by `moveSvg`.
@param {props} props - `props` of instance.
@returns {BBox} Current BBox without animation, i.e. left/top properties. | initSvg ( props ) | javascript | anseki/plain-draggable | src/plain-draggable.proc.js | https://github.com/anseki/plain-draggable/blob/master/src/plain-draggable.proc.js | MIT |
setOptions(options) {
if (isObject(options)) {
setOptions(insProps[this._id], options);
}
return this;
} | @param {Object} options - New options.
@returns {PlainDraggable} Current instance itself. | setOptions ( options ) | javascript | anseki/plain-draggable | src/plain-draggable.proc.js | https://github.com/anseki/plain-draggable/blob/master/src/plain-draggable.proc.js | MIT |
return function (tree) {
const result = toc(tree, settings)
if (
result.endIndex === undefined ||
result.endIndex === -1 ||
result.index === undefined ||
result.index === -1 ||
!result.map
) {
return
}
tree.children = [
...tree.children.slice(0, result.index),
result.map,
...tree.children.slice(result.endIndex)
]
} | Transform.
@param {Root} tree
Tree.
@returns {undefined}
Nothing. | (anonymous) ( tree ) | javascript | remarkjs/remark-toc | lib/index.js | https://github.com/remarkjs/remark-toc/blob/master/lib/index.js | MIT |
function isAnyArray(value) {
return toString.call(value).endsWith('Array]');
} | Checks if an object is an instance of an Array (array or typed array).
@param {any} value - Object to check.
@returns {boolean} True if the object is an array. | isAnyArray ( value ) | javascript | leeoniya/uPlot | demos/lib/sgg.js | https://github.com/leeoniya/uPlot/blob/master/demos/lib/sgg.js | MIT |
function sgg(ys, xs, options = {}) {
let { windowSize = 9, derivative = 0, polynomial = 3 } = options;
if (windowSize % 2 === 0 || windowSize < 5 || !Number.isInteger(windowSize)) {
throw new RangeError('Invalid window size (should be odd and at least 5 integer number)');
}
if (!isAnyArray(ys)) {
throw new TypeError('Y values must be an array');
}
if (typeof xs === 'undefined') {
throw new TypeError('X must be defined');
}
if (windowSize > ys.length) {
throw new RangeError(`Window size is higher than the data length ${windowSize}>${ys.length}`);
}
if (derivative < 0 || !Number.isInteger(derivative)) {
throw new RangeError('Derivative should be a positive integer');
}
if (polynomial < 1 || !Number.isInteger(polynomial)) {
throw new RangeError('Polynomial should be a positive integer');
}
if (polynomial >= 6) {
// eslint-disable-next-line no-console
console.warn('You should not use polynomial grade higher than 5 if you are' +
' not sure that your data arises from such a model. Possible polynomial oscillation problems');
}
let half = Math.floor(windowSize / 2);
let np = ys.length;
let ans = new Float64Array(np);
let weights = fullWeights(windowSize, polynomial, derivative);
let hs = 0;
let constantH = true;
if (isAnyArray(xs)) {
constantH = false;
}
else {
hs = Math.pow(xs, derivative);
}
//For the borders
for (let i = 0; i < half; i++) {
let wg1 = weights[half - i - 1];
let wg2 = weights[half + i + 1];
let d1 = 0;
let d2 = 0;
for (let l = 0; l < windowSize; l++) {
d1 += wg1[l] * ys[l];
d2 += wg2[l] * ys[np - windowSize + l];
}
if (constantH) {
ans[half - i - 1] = d1 / hs;
ans[np - half + i] = d2 / hs;
}
else {
hs = getHs(xs, half - i - 1, half, derivative);
ans[half - i - 1] = d1 / hs;
hs = getHs(xs, np - half + i, half, derivative);
ans[np - half + i] = d2 / hs;
}
}
//For the internal points
let wg = weights[half];
for (let i = windowSize; i <= np; i++) {
let d = 0;
for (let l = 0; l < windowSize; l++) { d += wg[l] * ys[l + i - windowSize]; }
if (!constantH) {
hs = getHs(xs, i - half - 1, half, derivative);
}
ans[i - half - 1] = d / hs;
}
return ans;
} | Apply Savitzky Golay algorithm
@param [ys] Array of y values
@param [xs] Array of X or deltaX
@return Array containing the new ys (same length) | sgg ( ys , xs , options = { } ) | javascript | leeoniya/uPlot | demos/lib/sgg.js | https://github.com/leeoniya/uPlot/blob/master/demos/lib/sgg.js | MIT |
function fullWeights(m, n, s) {
let weights = new Array(m);
let np = Math.floor(m / 2);
for (let t = -np; t <= np; t++) {
weights[t + np] = new Float64Array(m);
for (let j = -np; j <= np; j++) {
weights[t + np][j + np] = weight(j, t, np, n, s);
}
}
return weights;
} | @private
@param m Number of points
@param n Polynomial grade
@param s Derivative | fullWeights ( m , n , s ) | javascript | leeoniya/uPlot | demos/lib/sgg.js | https://github.com/leeoniya/uPlot/blob/master/demos/lib/sgg.js | MIT |
function catmullRomFitting(xCoords, yCoords, moveTo, lineTo, bezierCurveTo, pxRound) {
const alpha = 0.5;
const path = new Path2D();
const dataLen = xCoords.length;
let p0x,
p0y,
p1x,
p1y,
p2x,
p2y,
p3x,
p3y,
bp1x,
bp1y,
bp2x,
bp2y,
d1,
d2,
d3,
A,
B,
N,
M,
d3powA,
d2powA,
d3pow2A,
d2pow2A,
d1pow2A,
d1powA;
moveTo(path, pxRound(xCoords[0]), pxRound(yCoords[0]));
for (let i = 0; i < dataLen - 1; i++) {
let p0i = i == 0 ? 0 : i - 1;
p0x = xCoords[p0i];
p0y = yCoords[p0i];
p1x = xCoords[i];
p1y = yCoords[i];
p2x = xCoords[i + 1];
p2y = yCoords[i + 1];
if (i + 2 < dataLen) {
p3x = xCoords[i + 2];
p3y = yCoords[i + 2];
} else {
p3x = p2x;
p3y = p2y;
}
d1 = sqrt(pow(p0x - p1x, 2) + pow(p0y - p1y, 2));
d2 = sqrt(pow(p1x - p2x, 2) + pow(p1y - p2y, 2));
d3 = sqrt(pow(p2x - p3x, 2) + pow(p2y - p3y, 2));
// Catmull-Rom to Cubic Bezier conversion matrix
// A = 2d1^2a + 3d1^a * d2^a + d3^2a
// B = 2d3^2a + 3d3^a * d2^a + d2^2a
// [ 0 1 0 0 ]
// [ -d2^2a /N A/N d1^2a /N 0 ]
// [ 0 d3^2a /M B/M -d2^2a /M ]
// [ 0 0 1 0 ]
d3powA = pow(d3, alpha);
d3pow2A = pow(d3, alpha * 2);
d2powA = pow(d2, alpha);
d2pow2A = pow(d2, alpha * 2);
d1powA = pow(d1, alpha);
d1pow2A = pow(d1, alpha * 2);
A = 2 * d1pow2A + 3 * d1powA * d2powA + d2pow2A;
B = 2 * d3pow2A + 3 * d3powA * d2powA + d2pow2A;
N = 3 * d1powA * (d1powA + d2powA);
if (N > 0)
N = 1 / N;
M = 3 * d3powA * (d3powA + d2powA);
if (M > 0)
M = 1 / M;
bp1x = (-d2pow2A * p0x + A * p1x + d1pow2A * p2x) * N;
bp1y = (-d2pow2A * p0y + A * p1y + d1pow2A * p2y) * N;
bp2x = (d3pow2A * p1x + B * p2x - d2pow2A * p3x) * M;
bp2y = (d3pow2A * p1y + B * p2y - d2pow2A * p3y) * M;
if (bp1x == 0 && bp1y == 0) {
bp1x = p1x;
bp1y = p1y;
}
if (bp2x == 0 && bp2y == 0) {
bp2x = p2x;
bp2y = p2y;
}
bezierCurveTo(path, bp1x, bp1y, bp2x, bp2y, p2x, p2y);
}
return path;
} | Interpolates a Catmull-Rom Spline through a series of x/y points
Converts the CR Spline to Cubic Beziers for use with SVG items
If 'alpha' is 0.5 then the 'Centripetal' variant is used
If 'alpha' is 1 then the 'Chordal' variant is used | catmullRomFitting ( xCoords , yCoords , moveTo , lineTo , bezierCurveTo , pxRound ) | javascript | leeoniya/uPlot | src/paths/catmullRomCentrip.js | https://github.com/leeoniya/uPlot/blob/master/src/paths/catmullRomCentrip.js | MIT |
get: function get(key) {
if (!Array.isArray(key)) {
return _asyncStorage["default"].getItem(key).then(function (value) {
return JSON.parse(value);
});
} else {
return _asyncStorage["default"].multiGet(key).then(function (values) {
return values.map(function (value) {
return JSON.parse(value[1]);
});
});
}
}, | Get a one or more value for a key or array of keys from AsyncStorage
@param {String|Array} key A key or array of keys
@return {Promise} | get ( key ) | javascript | jasonmerino/react-native-simple-store | dist/index.js | https://github.com/jasonmerino/react-native-simple-store/blob/master/dist/index.js | MIT |
save: function save(key, value) {
if (!Array.isArray(key)) {
return _asyncStorage["default"].setItem(key, JSON.stringify(value));
} else {
var pairs = key.map(function (pair) {
return [pair[0], JSON.stringify(pair[1])];
});
return _asyncStorage["default"].multiSet(pairs);
}
}, | Save a key value pair or a series of key value pairs to AsyncStorage.
@param {String|Array} key The key or an array of key/value pairs
@param {Any} value The value to save
@return {Promise} | save ( key , value ) | javascript | jasonmerino/react-native-simple-store | dist/index.js | https://github.com/jasonmerino/react-native-simple-store/blob/master/dist/index.js | MIT |
update: function update(key, value) {
return deviceStorage.get(key).then(function (item) {
value = typeof value === 'string' ? value : (0, _lodash["default"])({}, item, value);
return _asyncStorage["default"].setItem(key, JSON.stringify(value));
});
}, | Updates the value in the store for a given key in AsyncStorage. If the value is a string it will be replaced. If the value is an object it will be deep merged.
@param {String} key The key
@param {Value} value The value to update with
@return {Promise} | update ( key , value ) | javascript | jasonmerino/react-native-simple-store | dist/index.js | https://github.com/jasonmerino/react-native-simple-store/blob/master/dist/index.js | MIT |
"delete": function _delete(key) {
if (Array.isArray(key)) {
return _asyncStorage["default"].multiRemove(key);
} else {
return _asyncStorage["default"].removeItem(key);
}
}, | Delete the value for a given key in AsyncStorage.
@param {String|Array} key The key or an array of keys to be deleted
@return {Promise} | _delete ( key ) | javascript | jasonmerino/react-native-simple-store | dist/index.js | https://github.com/jasonmerino/react-native-simple-store/blob/master/dist/index.js | MIT |
keys: function keys() {
return _asyncStorage["default"].getAllKeys();
}, | Get all keys in AsyncStorage.
@return {Promise} A promise which when it resolves gets passed the saved keys in AsyncStorage. | keys ( ) | javascript | jasonmerino/react-native-simple-store | dist/index.js | https://github.com/jasonmerino/react-native-simple-store/blob/master/dist/index.js | MIT |
push: function push(key, value) {
return deviceStorage.get(key).then(function (currentValue) {
if (currentValue === null) {
// if there is no current value populate it with the new value
return deviceStorage.save(key, [value]);
}
if (Array.isArray(currentValue)) {
return deviceStorage.save(key, [].concat(_toConsumableArray(currentValue), [value]));
}
throw new Error("Existing value for key \"".concat(key, "\" must be of type null or Array, received ").concat(_typeof(currentValue), "."));
});
} | Push a value onto an array stored in AsyncStorage by key or create a new array in AsyncStorage for a key if it's not yet defined.
@param {String} key They key
@param {Any} value The value to push onto the array
@return {Promise} | push ( key , value ) | javascript | jasonmerino/react-native-simple-store | dist/index.js | https://github.com/jasonmerino/react-native-simple-store/blob/master/dist/index.js | MIT |
function require(name) {
var module = require.modules[name];
if (!module) throw new Error('failed to require "' + name + '"');
if (!('exports' in module) && typeof module.definition === 'function') {
module.client = module.component = true;
module.definition.call(this, module.exports = {}, module);
delete module.definition;
}
return module.exports;
} | Require the module at `name`.
@param {String} name
@return {Object} exports
@api public | require ( name ) | javascript | jalaali/moment-jalaali | build/moment-jalaali.js | https://github.com/jalaali/moment-jalaali/blob/master/build/moment-jalaali.js | MIT |
require.register = function (name, definition) {
require.modules[name] = {
definition: definition
};
}; | Register module at `name` with callback `definition`.
@param {String} name
@param {Function} definition
@api private | require.register ( name , definition ) | javascript | jalaali/moment-jalaali | build/moment-jalaali.js | https://github.com/jalaali/moment-jalaali/blob/master/build/moment-jalaali.js | MIT |
require.define = function (name, exports) {
require.modules[name] = {
exports: exports
};
}; | Define a module's exports immediately with `exports`.
@param {String} name
@param {Generic} exports
@api private | require.define ( name , exports ) | javascript | jalaali/moment-jalaali | build/moment-jalaali.js | https://github.com/jalaali/moment-jalaali/blob/master/build/moment-jalaali.js | MIT |
function jalaaliWeek(jy, jm, jd) {
var dayOfWeek = jalaaliToDateObject(jy, jm, jd).getDay();
var startDayDifference = dayOfWeek == 6 ? 0 : -(dayOfWeek+1);
var endDayDifference = 6+startDayDifference;
return {
saturday: d2j(j2d(jy, jm, jd+startDayDifference)),
friday: d2j(j2d(jy, jm, jd+endDayDifference))
}
} | Return Saturday and Friday day of current week(week start in Saturday)
@param {number} jy jalaali year
@param {number} jm jalaali month
@param {number} jd jalaali day
@returns Saturday and Friday of current week | jalaaliWeek ( jy , jm , jd ) | javascript | jalaali/moment-jalaali | build/moment-jalaali.js | https://github.com/jalaali/moment-jalaali/blob/master/build/moment-jalaali.js | MIT |
function jalaaliToDateObject(
jy,
jm,
jd,
h,
m,
s,
ms
) {
var gregorianCalenderDate = toGregorian(jy, jm, jd);
return new Date(
gregorianCalenderDate.gy,
gregorianCalenderDate.gm - 1,
gregorianCalenderDate.gd,
h || 0,
m || 0,
s || 0,
ms || 0
);
} | Convert Jalaali calendar dates to javascript Date object
@param {number} jy jalaali year
@param {number} jm jalaali month
@param {number} jd jalaali day
@param {number} [h] hours
@param {number} [m] minutes
@param {number} [s] seconds
@param {number} [ms] milliseconds
@returns Date object of the jalaali calendar dates | jalaaliToDateObject ( jy , jm , jd , h , m , s , ms ) | javascript | jalaali/moment-jalaali | build/moment-jalaali.js | https://github.com/jalaali/moment-jalaali/blob/master/build/moment-jalaali.js | MIT |
function callable(value) {
return typeof value === 'function';
} | Returns `true` if the object is a function, otherwise `false`.
@param { any } value
@returns { boolean } | callable ( value ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function defined(value) {
return value !== undefined;
} | Returns `true` if the object is strictly not `undefined`.
@param { any } value
@returns { boolean } | defined ( value ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function divisibleby(one, two) {
return (one % two) === 0;
} | Returns `true` if the operand (one) is divisble by the test's argument
(two).
@param { number } one
@param { number } two
@returns { boolean } | divisibleby ( one , two ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function escaped(value) {
return value instanceof SafeString;
} | Returns true if the string has been escaped (i.e., is a SafeString).
@param { any } value
@returns { boolean } | escaped ( value ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function equalto(one, two) {
return one === two;
} | Returns `true` if the arguments are strictly equal.
@param { any } one
@param { any } two | equalto ( one , two ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function even(value) {
return value % 2 === 0;
} | Returns `true` if the value is evenly divisible by 2.
@param { number } value
@returns { boolean } | even ( value ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function falsy(value) {
return !value;
} | Returns `true` if the value is falsy - if I recall correctly, '', 0, false,
undefined, NaN or null. I don't know if we should stick to the default JS
behavior or attempt to replicate what Python believes should be falsy (i.e.,
empty arrays, empty dicts, not 0...).
@param { any } value
@returns { boolean } | falsy ( value ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function ge(one, two) {
return one >= two;
} | Returns `true` if the operand (one) is greater or equal to the test's
argument (two).
@param { number } one
@param { number } two
@returns { boolean } | ge ( one , two ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function greaterthan(one, two) {
return one > two;
} | Returns `true` if the operand (one) is greater than the test's argument
(two).
@param { number } one
@param { number } two
@returns { boolean } | greaterthan ( one , two ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function le(one, two) {
return one <= two;
} | Returns `true` if the operand (one) is less than or equal to the test's
argument (two).
@param { number } one
@param { number } two
@returns { boolean } | le ( one , two ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function lessthan(one, two) {
return one < two;
} | Returns `true` if the operand (one) is less than the test's passed argument
(two).
@param { number } one
@param { number } two
@returns { boolean } | lessthan ( one , two ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function lower(value) {
return value.toLowerCase() === value;
} | Returns `true` if the string is lowercased.
@param { string } value
@returns { boolean } | lower ( value ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function nullTest(value) {
return value === null;
} | Returns true if the value is strictly equal to `null`.
@param { any }
@returns { boolean } | nullTest ( value ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function number(value) {
return typeof value === 'number';
} | Returns true if value is a number.
@param { any }
@returns { boolean } | number ( value ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function odd(value) {
return value % 2 === 1;
} | Returns `true` if the value is *not* evenly divisible by 2.
@param { number } value
@returns { boolean } | odd ( value ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function string(value) {
return typeof value === 'string';
} | Returns `true` if the value is a string, `false` if not.
@param { any } value
@returns { boolean } | string ( value ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function truthy(value) {
return !!value;
} | Returns `true` if the value is not in the list of things considered falsy:
'', null, undefined, 0, NaN and false.
@param { any } value
@returns { boolean } | truthy ( value ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function undefinedTest(value) {
return value === undefined;
} | Returns `true` if the value is undefined.
@param { any } value
@returns { boolean } | undefinedTest ( value ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function upper(value) {
return value.toUpperCase() === value;
} | Returns `true` if the string is uppercased.
@param { string } value
@returns { boolean } | upper ( value ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function iterable(value) {
if (typeof Symbol !== 'undefined') {
return !!value[Symbol.iterator];
} else {
return Array.isArray(value) || typeof value === 'string';
}
} | If ES6 features are available, returns `true` if the value implements the
`Symbol.iterator` method. If not, it's a string or Array.
Could potentially cause issues if a browser exists that has Set and Map but
not Symbol.
@param { any } value
@returns { boolean } | iterable ( value ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function mapping(value) {
// only maps and object hashes
var bool = value !== null
&& value !== undefined
&& typeof value === 'object'
&& !Array.isArray(value);
if (Set) {
return bool && !(value instanceof Set);
} else {
return bool;
}
} | If ES6 features are available, returns `true` if the value is an object hash
or an ES6 Map. Otherwise just return if it's an object hash.
@param { any } value
@returns { boolean } | mapping ( value ) | javascript | mozilla/nunjucks | nunjucks/src/tests.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/tests.js | BSD-2-Clause |
function getSelectOrReject(expectedTestResult) {
function filter(arr, testName = 'truthy', secondArg) {
const context = this;
const test = context.env.getTest(testName);
return lib.toArray(arr).filter(function examineTestResult(item) {
return test.call(context, item, secondArg) === expectedTestResult;
});
}
return filter;
} | Construct select or reject filter
@param {boolean} expectedTestResult
@returns {function(array, string, *): array} | getSelectOrReject ( expectedTestResult ) | javascript | mozilla/nunjucks | nunjucks/src/filters.js | https://github.com/mozilla/nunjucks/blob/master/nunjucks/src/filters.js | BSD-2-Clause |
it('should have individual lexer tag settings for each environment', function() {
tokens = lexer.lex('{=', {
tags: {
variableStart: '{='
}
});
hasTokens(tokens, lexer.TOKEN_VARIABLE_START);
tokens = lexer.lex('{{');
hasTokens(tokens, lexer.TOKEN_VARIABLE_START);
tokens = lexer.lex('{{', {
tags: {
variableStart: '<<<'
}
});
hasTokens(tokens, lexer.TOKEN_DATA);
tokens = lexer.lex('{{');
hasTokens(tokens, lexer.TOKEN_VARIABLE_START);
}); | Test that this bug is fixed: https://github.com/mozilla/nunjucks/issues/235 | (anonymous) ( ) | javascript | mozilla/nunjucks | tests/lexer.js | https://github.com/mozilla/nunjucks/blob/master/tests/lexer.js | BSD-2-Clause |
it('should have access to "loop" inside an include', function(done) {
equal('{% for item in [1,2,3] %}{% include "include-in-loop.njk" %}{% endfor %}',
'1,0,true\n2,1,false\n3,2,false\n');
equal('{% for k,v in items %}{% include "include-in-loop.njk" %}{% endfor %}',
{
items: {
a: 'A',
b: 'B'
}
},
'1,0,true\n2,1,false\n');
finish(done);
}); | This test checks that this issue is resolved: http://stackoverflow.com/questions/21777058/loop-index-in-included-nunjucks-file | (anonymous) ( done ) | javascript | mozilla/nunjucks | tests/compiler.js | https://github.com/mozilla/nunjucks/blob/master/tests/compiler.js | BSD-2-Clause |
function Readability(doc, options) {
// In some older versions, people passed a URI as the first argument. Cope:
if (options && options.documentElement) {
doc = options;
options = arguments[2];
} else if (!doc || !doc.documentElement) {
throw new Error("First argument to Readability constructor should be a document object.");
}
options = options || {};
this._doc = doc;
this._docJSDOMParser = this._doc.firstChild.__JSDOMParser__;
this._articleTitle = null;
this._articleByline = null;
this._articleDir = null;
this._articleSiteName = null;
this._attempts = [];
// Configurable options
this._debug = !!options.debug;
this._maxElemsToParse = options.maxElemsToParse || this.DEFAULT_MAX_ELEMS_TO_PARSE;
this._nbTopCandidates = options.nbTopCandidates || this.DEFAULT_N_TOP_CANDIDATES;
this._charThreshold = options.charThreshold || this.DEFAULT_CHAR_THRESHOLD;
this._classesToPreserve = this.CLASSES_TO_PRESERVE.concat(options.classesToPreserve || []);
this._keepClasses = !!options.keepClasses;
this._serializer = options.serializer || function(el) {
return el.innerHTML;
};
this._disableJSONLD = !!options.disableJSONLD;
this._allowedVideoRegex = options.allowedVideoRegex || this.REGEXPS.videos;
// Start with all flags set
this._flags = this.FLAG_STRIP_UNLIKELYS |
this.FLAG_WEIGHT_CLASSES |
this.FLAG_CLEAN_CONDITIONALLY;
// Control whether log messages are sent to the console
if (this._debug) {
let logNode = function(node) {
if (node.nodeType == node.TEXT_NODE) {
return `${node.nodeName} ("${node.textContent}")`;
}
let attrPairs = Array.from(node.attributes || [], function(attr) {
return `${attr.name}="${attr.value}"`;
}).join(" ");
return `<${node.localName} ${attrPairs}>`;
};
this.log = function () {
if (typeof console !== "undefined") {
let args = Array.from(arguments, arg => {
if (arg && arg.nodeType == this.ELEMENT_NODE) {
return logNode(arg);
}
return arg;
});
args.unshift("Reader: (Readability)");
console.log.apply(console, args);
} else if (typeof dump !== "undefined") {
/* global dump */
var msg = Array.prototype.map.call(arguments, function(x) {
return (x && x.nodeName) ? logNode(x) : x;
}).join(" ");
dump("Reader: (Readability) " + msg + "\n");
}
};
} else {
this.log = function () {};
}
} | Public constructor.
@param {HTMLDocument} doc The document to parse.
@param {Object} options The options object. | Readability ( doc , options ) | javascript | minbrowser/min | ext/readability-master/Readability.js | https://github.com/minbrowser/min/blob/master/ext/readability-master/Readability.js | Apache-2.0 |
_prepDocument: function() {
var doc = this._doc;
// Remove all style tags in head
this._removeNodes(this._getAllNodesWithTag(doc, ["style"]));
if (doc.body) {
this._replaceBrs(doc.body);
}
this._replaceNodeTags(this._getAllNodesWithTag(doc, ["font"]), "SPAN");
}, | Prepare the HTML document for readability to scrape it.
This includes things like stripping javascript, CSS, and handling terrible markup.
@return void
* | _prepDocument ( ) | javascript | minbrowser/min | ext/readability-master/Readability.js | https://github.com/minbrowser/min/blob/master/ext/readability-master/Readability.js | Apache-2.0 |
_nextNode: function (node) {
var next = node;
while (next
&& (next.nodeType != this.ELEMENT_NODE)
&& this.REGEXPS.whitespace.test(next.textContent)) {
next = next.nextSibling;
}
return next;
}, | Finds the next node, starting from the given node, and ignoring
whitespace in between. If the given node is an element, the same node is
returned. | _nextNode ( node ) | javascript | minbrowser/min | ext/readability-master/Readability.js | https://github.com/minbrowser/min/blob/master/ext/readability-master/Readability.js | Apache-2.0 |
_replaceBrs: function (elem) {
this._forEachNode(this._getAllNodesWithTag(elem, ["br"]), function(br) {
var next = br.nextSibling;
// Whether 2 or more <br> elements have been found and replaced with a
// <p> block.
var replaced = false;
// If we find a <br> chain, remove the <br>s until we hit another node
// or non-whitespace. This leaves behind the first <br> in the chain
// (which will be replaced with a <p> later).
while ((next = this._nextNode(next)) && (next.tagName == "BR")) {
replaced = true;
var brSibling = next.nextSibling;
next.parentNode.removeChild(next);
next = brSibling;
}
// If we removed a <br> chain, replace the remaining <br> with a <p>. Add
// all sibling nodes as children of the <p> until we hit another <br>
// chain.
if (replaced) {
var p = this._doc.createElement("p");
br.parentNode.replaceChild(p, br);
next = p.nextSibling;
while (next) {
// If we've hit another <br><br>, we're done adding children to this <p>.
if (next.tagName == "BR") {
var nextElem = this._nextNode(next.nextSibling);
if (nextElem && nextElem.tagName == "BR")
break;
}
if (!this._isPhrasingContent(next))
break;
// Otherwise, make this node a child of the new <p>.
var sibling = next.nextSibling;
p.appendChild(next);
next = sibling;
}
while (p.lastChild && this._isWhitespace(p.lastChild)) {
p.removeChild(p.lastChild);
}
if (p.parentNode.tagName === "P")
this._setNodeTag(p.parentNode, "DIV");
}
});
}, | Replaces 2 or more successive <br> elements with a single <p>.
Whitespace between <br> elements are ignored. For example:
<div>foo<br>bar<br> <br><br>abc</div>
will become:
<div>foo<br>bar<p>abc</p></div> | _replaceBrs ( elem ) | javascript | minbrowser/min | ext/readability-master/Readability.js | https://github.com/minbrowser/min/blob/master/ext/readability-master/Readability.js | Apache-2.0 |
_hasChildBlockElement: function (element) {
return this._someNode(element.childNodes, function(node) {
return this.DIV_TO_P_ELEMS.has(node.tagName) ||
this._hasChildBlockElement(node); | Determine whether element has any children block level elements.
@param Element | (anonymous) ( node ) | javascript | minbrowser/min | ext/readability-master/Readability.js | https://github.com/minbrowser/min/blob/master/ext/readability-master/Readability.js | Apache-2.0 |
function isProbablyReaderable(doc, options = {}) {
// For backward compatibility reasons 'options' can either be a configuration object or the function used
// to determine if a node is visible.
if (typeof options == "function") {
options = { visibilityChecker: options };
}
var defaultOptions = { minScore: 20, minContentLength: 140, visibilityChecker: isNodeVisible };
options = Object.assign(defaultOptions, options);
var nodes = doc.querySelectorAll("p, pre, article");
// Get <div> nodes which have <br> node(s) and append them into the `nodes` variable.
// Some articles' DOM structures might look like
// <div>
// Sentences<br>
// <br>
// Sentences<br>
// </div>
var brNodes = doc.querySelectorAll("div > br");
if (brNodes.length) {
var set = new Set(nodes);
[].forEach.call(brNodes, function (node) {
set.add(node.parentNode);
});
nodes = Array.from(set);
}
var score = 0;
// This is a little cheeky, we use the accumulator 'score' to decide what to return from
// this callback:
return [].some.call(nodes, function (node) {
if (!options.visibilityChecker(node)) {
return false;
}
var matchString = node.className + " " + node.id;
if (REGEXPS.unlikelyCandidates.test(matchString) &&
!REGEXPS.okMaybeItsACandidate.test(matchString)) {
return false;
}
if (node.matches("li p")) {
return false;
}
var textContentLength = node.textContent.trim().length;
if (textContentLength < options.minContentLength) {
return false;
}
score += Math.sqrt(textContentLength - options.minContentLength);
if (score > options.minScore) {
return true;
}
return false;
});
} | Decides whether or not the document is reader-able without parsing the whole thing.
@param {Object} options Configuration object.
@param {number} [options.minContentLength=140] The minimum node content length used to decide if the document is readerable.
@param {number} [options.minScore=20] The minumum cumulated 'score' used to determine if the document is readerable.
@param {Function} [options.visibilityChecker=isNodeVisible] The function used to determine if a node is visible.
@return {boolean} Whether or not we suspect Readability.parse() will suceeed at returning an article object. | isProbablyReaderable ( doc , options = { } ) | javascript | minbrowser/min | ext/readability-master/Readability-readerable.js | https://github.com/minbrowser/min/blob/master/ext/readability-master/Readability-readerable.js | Apache-2.0 |
function findFirstSeparatorChar (input, startPos) {
for (var i = startPos, len = input.length; i < len; i++) {
if (separatorCharacters.indexOf(input[i]) !== -1) {
return i
}
}
return -1
} | Finds the first separator character in the input string | findFirstSeparatorChar ( input , startPos ) | javascript | minbrowser/min | ext/abp-filter-parser-modified/abp-filter-parser.js | https://github.com/minbrowser/min/blob/master/ext/abp-filter-parser-modified/abp-filter-parser.js | Apache-2.0 |
function getDomainIndex (input) {
var index = input.indexOf(':') + 1
while (input[index] === '/') {
index++
}
return index
} | Obtains the domain index of the input filter line | getDomainIndex ( input ) | javascript | minbrowser/min | ext/abp-filter-parser-modified/abp-filter-parser.js | https://github.com/minbrowser/min/blob/master/ext/abp-filter-parser-modified/abp-filter-parser.js | Apache-2.0 |
function parseDomains (input, options) {
var domains = input.split('|')
var matchDomains = []
var skipDomains = []
for (var i = 0; i < domains.length; i++) {
if (domains[i][0] === '~') {
skipDomains.push(domains[i].substring(1))
} else {
matchDomains.push(domains[i])
}
}
if (matchDomains.length !== 0) {
options.domains = matchDomains
}
if (skipDomains.length !== 0) {
options.skipDomains = skipDomains
}
} | Parses the domain string and fills in options. | parseDomains ( input , options ) | javascript | minbrowser/min | ext/abp-filter-parser-modified/abp-filter-parser.js | https://github.com/minbrowser/min/blob/master/ext/abp-filter-parser-modified/abp-filter-parser.js | Apache-2.0 |
function parseOptions (input) {
var output = {}
var hasValidOptions = false
input.split(',').forEach(function (option) {
if (option.startsWith('domain=')) {
var domainString = option.split('=')[1].trim()
parseDomains(domainString, output)
hasValidOptions = true
} else {
/*
Element types are stored as an int, where each bit is a type (see elementTypesSet)
1 -> the filter should match for this element type
If the filter defines a type to skip, then all other types should implicitly match
If it defines types to match, all other types should implicitly not match
*/
// the option is an element type to skip
if (option[0] === '~' && elementTypes.indexOf(option.substring(1)) !== -1) {
if (output.elementTypes === undefined) {
output.elementTypes = defaultElementTypes
}
output.elementTypes = output.elementTypes & (~elementTypesSet[option.substring(1)])
hasValidOptions = true
// the option is an element type to match
} else if (elementTypes.indexOf(option) !== -1) {
output.elementTypes = (output.elementTypes || 0) | elementTypesSet[option]
hasValidOptions = true
}
if (option === 'third-party') {
output.thirdParty = true
hasValidOptions = true
}
if (option === '~third-party') {
output.notThirdParty = true
hasValidOptions = true
}
}
})
if (hasValidOptions) {
return output
} else {
return null
}
} | Parses options from the passed in input string | parseOptions ( input ) | javascript | minbrowser/min | ext/abp-filter-parser-modified/abp-filter-parser.js | https://github.com/minbrowser/min/blob/master/ext/abp-filter-parser-modified/abp-filter-parser.js | Apache-2.0 |
function parse (input, parserData, callback, options = {}) {
var arrayFilterCategories = ['regex', 'bothAnchored']
var objectFilterCategories = ['hostAnchored']
var trieFilterCategories = ['nonAnchoredString', 'leftAnchored', 'rightAnchored']
parserData.exceptionFilters = parserData.exceptionFilters || {}
for (var i = 0; i < arrayFilterCategories.length; i++) {
parserData[arrayFilterCategories[i]] = parserData[arrayFilterCategories[i]] || []
parserData.exceptionFilters[arrayFilterCategories[i]] = parserData.exceptionFilters[arrayFilterCategories[i]] || []
}
for (var i = 0; i < objectFilterCategories.length; i++) {
parserData[objectFilterCategories[i]] = parserData[objectFilterCategories[i]] || {}
parserData.exceptionFilters[objectFilterCategories[i]] = parserData.exceptionFilters[objectFilterCategories[i]] || {}
}
for (var i = 0; i < trieFilterCategories.length; i++) {
parserData[trieFilterCategories[i]] = parserData[trieFilterCategories[i]] || new Trie()
parserData.exceptionFilters[trieFilterCategories[i]] = parserData.exceptionFilters[trieFilterCategories[i]] || new Trie()
}
var filters = input.split('\n')
function processChunk (start, end) {
for (var i = start, len = end; i < len; i++) {
var filter = filters[i]
if (!filter) {
continue
}
var parsedFilterData = {}
var object
if (parseFilter(filter, parsedFilterData)) {
if (parsedFilterData.isException) {
object = parserData.exceptionFilters
} else {
object = parserData
}
// add the filters to the appropriate category
if (parsedFilterData.leftAnchored) {
if (parsedFilterData.rightAnchored) {
object.bothAnchored.push(parsedFilterData)
} else {
object.leftAnchored.add(parsedFilterData.data, parsedFilterData.options, maybeMergeDuplicateOptions)
}
} else if (parsedFilterData.rightAnchored) {
object.rightAnchored.addReverse(parsedFilterData.data, parsedFilterData.options)
} else if (parsedFilterData.hostAnchored) {
/* add the filters to the object based on the last 6 characters of their domain.
Domains can be just 5 characters long: the TLD is at least 2 characters,
the . character adds one more character, and the domain name must be at least two
characters long. However, slicing the last 6 characters of a 5-character string
will give us the 5 available characters; we can then check for both a
5-character and a 6-character match in matchesFilters. By storing the last
characters in an object, we can skip checking whether every filter's domain
is from the same origin as the URL we are checking. Instead, we can just get
the last characters of the URL to check, get the filters stored in that
property of the object, and then check if the complete domains match.
*/
var ending = parsedFilterData.host.slice(-6)
if (object.hostAnchored[ending]) {
object.hostAnchored[ending].push(parsedFilterData)
} else {
object.hostAnchored[ending] = [parsedFilterData]
}
} else if (parsedFilterData.regex) {
object.regex.push(parsedFilterData)
} else if (parsedFilterData.wildcardMatchParts) {
var wildcardToken = parsedFilterData.wildcardMatchParts[0].split('^')[0].substring(0, 10)
if (wildcardToken.length < 4) {
var wildcardToken2 = parsedFilterData.wildcardMatchParts[1].split('^')[0].substring(0, 10)
if (wildcardToken2 && wildcardToken2.length > wildcardToken.length) {
wildcardToken = wildcardToken2
}
}
if (wildcardToken) {
object.nonAnchoredString.add(wildcardToken, parsedFilterData)
} else {
object.nonAnchoredString.add('', parsedFilterData)
}
} else {
object.nonAnchoredString.add(parsedFilterData.data.split('^')[0].substring(0, 10), parsedFilterData)
}
}
}
}
if (options.async === false) {
processChunk(0, filters.length)
parserData.initialized = true
} else {
/* parse filters in chunks to prevent the main process from freezing */
var filtersLength = filters.length
var lastFilterIdx = 0
var nextChunkSize = 1500
var targetMsPerChunk = 12
function nextChunk () {
var t1 = Date.now()
processChunk(lastFilterIdx, lastFilterIdx + nextChunkSize)
var t2 = Date.now()
lastFilterIdx += nextChunkSize
if (t2 - t1 !== 0) {
nextChunkSize = Math.round(nextChunkSize / ((t2 - t1) / targetMsPerChunk))
}
if (lastFilterIdx < filtersLength) {
setTimeout(nextChunk, 16)
} else {
parserData.initialized = true
if (callback) {
callback()
}
}
}
nextChunk()
}
} | Parses the set of filter rules and fills in parserData
@param input filter rules
@param parserData out parameter which will be filled
with the filters, exceptionFilters and htmlRuleFilters. | parse ( input , parserData , callback , options = { } ) | javascript | minbrowser/min | ext/abp-filter-parser-modified/abp-filter-parser.js | https://github.com/minbrowser/min/blob/master/ext/abp-filter-parser-modified/abp-filter-parser.js | Apache-2.0 |
app.on('activate', function (/* e, hasVisibleWindows */) {
if (!windows.getCurrent() && appIsReady) { // sometimes, the event will be triggered before the app is ready, and creating new windows will fail
createWindow()
}
}) | Emitted when the application is activated, which usually happens when clicks on the applications's dock icon
https://github.com/electron/electron/blob/master/docs/api/app.md#event-activate-os-x
Opens a new tab when all tabs are closed, and min is still open by clicking on the application dock icon | (anonymous) ( ) | javascript | minbrowser/min | main/main.js | https://github.com/minbrowser/min/blob/master/main/main.js | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.