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 |
---|---|---|---|---|---|---|---|
setAttribute = function(element, name, value) {
return jQuery(element).attr(name, value);
}; | Set attribute in the DOM element.
This method will use jQuery's `attr()` method if it is available, otherwise it will set the attribute directly
@function Util.setAttribute
@param {Element} element - the element to set the attribute for
@param {string} name - the name of the attribute
@param {*} value - the value to be set | setAttribute ( element , name , value ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
removeAttribute = function(element, name) {
return jQuery(element).removeAttr(name);
}; | Remove an attribute in the DOM element.
@function Util.removeAttribute
@param {Element} element - the element to set the attribute for
@param {string} name - the name of the attribute | removeAttribute ( element , name ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
setAttributes = function(element, attributes) {
return jQuery(element).attr(attributes);
}; | Set a group of attributes to the element
@function Util.setAttributes
@param {Element} element - the element to set the attributes for
@param {Object} attributes - a hash of attribute names and values | setAttributes ( element , attributes ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
addClass = function(element, name) {
return jQuery(element).addClass(name);
}; | Add class to the element
@function Util.addClass
@param {Element} element - the element
@param {string} name - the class name to add | addClass ( element , name ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
isEmpty = function(item) {
return (item == null) || (jQuery.isArray(item) || Util.isString(item)) && item.length === 0 || (jQuery.isPlainObject(item) && jQuery.isEmptyObject(item));
}; | Returns true if item is empty:
<ul>
<li>item is null or undefined</li>
<li>item is an array or string of length 0</li>
<li>item is an object with no keys</li>
</ul>
@function Util.isEmpty
@param item
@returns {boolean} true if item is empty | isEmpty ( item ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
merge = function() {
var args, i;
args = (function() {
var j, len, results;
results = [];
for (j = 0, len = arguments.length; j < len; j++) {
i = arguments[j];
results.push(i);
}
return results;
}).apply(this, arguments);
args.unshift(true);
return jQuery.extend.apply(this, args);
}; | Recursively assign source properties to destination
@function Util.merge
@param {Object} destination - the object to assign to
@param {...Object} [sources] The source objects. | merge ( ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
compact = function(arr) {
var item, j, len, results;
results = [];
for (j = 0, len = arr.length; j < len; j++) {
item = arr[j];
if (item) {
results.push(item);
}
}
return results;
}; | Creates a new array from the parameter with "falsey" values removed
@function Util.compact
@param {Array} array - the array to remove values from
@return {Array} a new array without falsey values | compact ( arr ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
cloneDeep = function() {
var args;
args = jQuery.makeArray(arguments);
args.unshift({});
args.unshift(true);
return jQuery.extend.apply(this, args);
}; | Create a new copy of the given object, including all internal objects.
@function Util.cloneDeep
@param {Object} value - the object to clone
@return {Object} a new deep copy of the object | cloneDeep ( ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
contains = function(arr, item) {
var i, j, len;
for (j = 0, len = arr.length; j < len; j++) {
i = arr[j];
if (i === item) {
return true;
}
}
return false;
}; | Check if a given item is included in the given array
@function Util.contains
@param {Array} array - the array to search in
@param {*} item - the item to search for
@return {boolean} true if the item is included in the array | contains ( arr , item ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
difference = function(arr, values) {
var item, j, len, results;
results = [];
for (j = 0, len = arr.length; j < len; j++) {
item = arr[j];
if (!contains(values, item)) {
results.push(item);
}
}
return results;
}; | Returns values in the given array that are not included in the other array
@function Util.difference
@param {Array} arr - the array to select from
@param {Array} values - values to filter from arr
@return {Array} the filtered values | difference ( arr , values ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
functions = function(object) {
var i, results;
results = [];
for (i in object) {
if (jQuery.isFunction(object[i])) {
results.push(i);
}
}
return results;
}; | Returns a list of all the function names in obj
@function Util.functions
@param {Object} object - the object to inspect
@return {Array} a list of functions of object | functions ( object ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
identity = function(value) {
return value;
}; | Returns the provided value. This functions is used as a default predicate function.
@function Util.identity
@param {*} value
@return {*} the provided value | identity ( value ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
crc32 = function(str) {
var crc, i, iTop, table, x, y;
str = utf8_encode(str);
table = '00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D';
crc = 0;
x = 0;
y = 0;
crc = crc ^ -1;
i = 0;
iTop = str.length;
while (i < iTop) {
y = (crc ^ str.charCodeAt(i)) & 0xFF;
x = '0x' + table.substr(y * 9, 8);
crc = crc >>> 8 ^ x;
i++;
}
crc = crc ^ -1;
if (crc < 0) {
crc += 4294967296;
}
return crc;
}; | CRC32 calculator
Depends on 'utf8_encode' | crc32 ( str ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
function Layer(options) {
this.options = {};
if (options != null) {
["resourceType", "type", "publicId", "format"].forEach((function(_this) {
return function(key) {
var ref;
return _this.options[key] = (ref = options[key]) != null ? ref : options[Util.snakeCase(key)];
};
})(this));
}
} | Layer
@constructor Layer
@param {Object} options - layer parameters | Layer ( options ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
Layer.prototype.getFullPublicId = function() {
if (this.options.format != null) {
return this.getPublicId() + "." + this.options.format;
} else {
return this.getPublicId();
} | Get the public ID, with format if present
@function Layer#getFullPublicId
@return {String} public ID | Layer.prototype.getFullPublicId ( ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
Layer.prototype.toString = function() {
var components;
components = [];
if (this.options.publicId == null) {
throw "Must supply publicId";
}
if (!(this.options.resourceType === "image")) {
components.push(this.options.resourceType);
}
if (!(this.options.type === "upload")) {
components.push(this.options.type);
}
components.push(this.getFullPublicId());
return Util.compact(components).join(":"); | generate the string representation of the layer
@function Layer#toString | Layer.prototype.toString ( ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
Layer.prototype.getPublicId = function() {
var ref;
return (ref = this.options.publicId) != null ? ref.replace(/\//g, ":") : void 0;
};
/**
* Get the public ID, with format if present
* @function Layer#getFullPublicId
* @return {String} public ID
*/
Layer.prototype.getFullPublicId = function() {
if (this.options.format != null) {
return this.getPublicId() + "." + this.options.format;
} else {
return this.getPublicId();
}
};
Layer.prototype.format = function(value) {
this.options.format = value;
return this;
};
/**
* generate the string representation of the layer
* @function Layer#toString
*/
Layer.prototype.toString = function() {
var components;
components = [];
if (this.options.publicId == null) {
throw "Must supply publicId";
}
if (!(this.options.resourceType === "image")) {
components.push(this.options.resourceType);
}
if (!(this.options.type === "upload")) {
components.push(this.options.type);
}
components.push(this.getFullPublicId());
return Util.compact(components).join(":");
};
return Layer;
| Get the public ID, formatted for layer parameter
@function Layer#getPublicId
@return {String} public ID | Layer.prototype.getPublicId ( ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
FetchLayer.prototype.toString = function() {
return "fetch:" + (cloudinary.Util.base64EncodeURL(this.options.url)); | generate the string representation of the layer
@function FetchLayer#toString
@return {String} | FetchLayer.prototype.toString ( ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
function FetchLayer(options) {
FetchLayer.__super__.constructor.call(this, options);
if (Util.isString(options)) {
this.options.url = options;
} else if (options != null ? options.url : void 0) {
this.options.url = options.url;
}
}
FetchLayer.prototype.url = function(url) {
this.options.url = url;
return this;
};
/**
* generate the string representation of the layer
* @function FetchLayer#toString
* @return {String}
*/
FetchLayer.prototype.toString = function() {
return "fetch:" + (cloudinary.Util.base64EncodeURL(this.options.url));
};
return FetchLayer;
| @constructor FetchLayer
@param {Object|string} options - layer parameters or a url
@param {string} options.url the url of the image to fetch | FetchLayer ( options ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
function TextLayer(options) {
var keys;
TextLayer.__super__.constructor.call(this, options);
keys = ["resourceType", "resourceType", "fontFamily", "fontSize", "fontWeight", "fontStyle", "textDecoration", "textAlign", "stroke", "letterSpacing", "lineSpacing", "text"];
if (options != null) {
keys.forEach((function(_this) {
return function(key) {
var ref;
return _this.options[key] = (ref = options[key]) != null ? ref : options[Util.snakeCase(key)];
};
})(this));
}
this.options.resourceType = "text"; | @constructor TextLayer
@param {Object} options - layer parameters | TextLayer ( options ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
TextLayer.prototype.toString = function() {
var components, hasPublicId, hasStyle, publicId, re, res, start, style, text, textSource;
style = this.textStyleIdentifier();
if (this.options.publicId != null) {
publicId = this.getFullPublicId();
}
if (this.options.text != null) {
hasPublicId = !Util.isEmpty(publicId);
hasStyle = !Util.isEmpty(style);
if (hasPublicId && hasStyle || !hasPublicId && !hasStyle) {
throw "Must supply either style parameters or a public_id when providing text parameter in a text overlay/underlay, but not both!";
}
re = /\$\([a-zA-Z]\w*\)/g;
start = 0;
textSource = Util.smartEscape(this.options.text, /[,\/]/g);
text = "";
while (res = re.exec(textSource)) {
text += Util.smartEscape(textSource.slice(start, res.index));
text += res[0];
start = res.index + res[0].length;
}
text += Util.smartEscape(textSource.slice(start));
}
components = [this.options.resourceType, style, publicId, text];
return Util.compact(components).join(":"); | generate the string representation of the layer
@function TextLayer#toString
@return {String} | TextLayer.prototype.toString ( ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
function SubtitlesLayer(options) {
SubtitlesLayer.__super__.constructor.call(this, options);
this.options.resourceType = "subtitles"; | Represent a subtitles layer
@constructor SubtitlesLayer
@param {Object} options - layer parameters | SubtitlesLayer ( options ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
Param.prototype.set = function(origValue) {
this.origValue = origValue;
return this; | Set a (unprocessed) value for this parameter
@function Param#set
@param {*} origValue - the value of the parameter
@return {Param} self for chaining | Param.prototype.set ( origValue ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
Param.prototype.serialize = function() {
var val, valid;
val = this.value();
valid = cloudinary.Util.isArray(val) || cloudinary.Util.isPlainObject(val) || cloudinary.Util.isString(val) ? !cloudinary.Util.isEmpty(val) : val != null;
if ((this.shortName != null) && valid) {
return this.shortName + "_" + val;
} else {
return '';
} | Generate the serialized form of the parameter
@function Param#serialize
@return {string} the serialized form of the parameter | Param.prototype.serialize ( ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
Param.prototype.value = function() {
return this.process(this.origValue); | Return the processed value of the parameter
@function Param#value | Param.prototype.value ( ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
TransformationBase.prototype.serialize = function() {
var ifParam, j, len, paramList, ref, ref1, ref2, ref3, ref4, resultArray, t, tr, transformationList, transformationString, transformations, value, variables, vars;
resultArray = (function() {
var j, len, ref, results;
ref = this.chained;
results = [];
for (j = 0, len = ref.length; j < len; j++) {
tr = ref[j];
results.push(tr.serialize()); | Generate a string representation of the transformation.
@function Transformation#serialize
@return {string} Returns the transformation as a string | (anonymous) ( ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
HtmlTag.prototype.htmlAttrs = function(attrs) {
var key, pairs, value;
return pairs = ((function() {
var results;
results = [];
for (key in attrs) {
value = attrs[key];
if (value) {
results.push(toAttribute(key, value));
} | combine key and value from the `attr` to generate an HTML tag attributes string.
`Transformation::toHtmlTagOptions` is used to filter out transformation and configuration keys.
@protected
@param {Object} attrs
@return {string} the attributes in the format `'key1="value1" key2="value2"'`
@ignore | (anonymous) ( ) | javascript | iyanuashiri/meethub | static/js/jquery.cloudinary.js | https://github.com/iyanuashiri/meethub/blob/master/static/js/jquery.cloudinary.js | MIT |
;(function($) {
var defaults = {
mouseOutOpacity: 0.67,
mouseOverOpacity: 1.0,
fadeSpeed: 'fast',
exemptionSelector: '.selected'
};
$.fn.opacityrollover = function(settings) {
// Initialize the effect
$.extend(this, defaults, settings);
var config = this;
function fadeTo(element, opacity) {
var $target = $(element);
if (config.exemptionSelector)
$target = $target.not(config.exemptionSelector);
$target.fadeTo(config.fadeSpeed, opacity);
}
this.css('opacity', this.mouseOutOpacity)
.hover(
function () {
fadeTo(this, config.mouseOverOpacity);
},
function () {
fadeTo(this, config.mouseOutOpacity);
});
return this;
};
})(jQuery); | jQuery Opacity Rollover plugin
Copyright (c) 2009 Trent Foley (http://trentacular.com)
Licensed under the MIT License:
http://www.opensource.org/licenses/mit-license.php | (anonymous) ( $ ) | javascript | iyanuashiri/meethub | static/ckeditor/galleriffic/js/jquery.opacityrollover.js | https://github.com/iyanuashiri/meethub/blob/master/static/ckeditor/galleriffic/js/jquery.opacityrollover.js | MIT |
CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
}; | @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license | CKEDITOR.editorConfig ( config ) | javascript | iyanuashiri/meethub | static/ckeditor/ckeditor/config.js | https://github.com/iyanuashiri/meethub/blob/master/static/ckeditor/ckeditor/config.js | MIT |
start (opts) {
opts = this._defaultAnnounceOpts(opts)
opts.event = 'started'
debug('send `start` %o', opts)
this._announce(opts)
// start announcing on intervals
this._trackers.forEach(tracker => {
tracker.setInterval()
})
} | Send a `start` announce to the trackers.
@param {Object} opts
@param {number=} opts.uploaded
@param {number=} opts.downloaded
@param {number=} opts.left (if not set, calculated automatically) | start ( opts ) | javascript | webtorrent/bittorrent-tracker | client.js | https://github.com/webtorrent/bittorrent-tracker/blob/master/client.js | MIT |
stop (opts) {
opts = this._defaultAnnounceOpts(opts)
opts.event = 'stopped'
debug('send `stop` %o', opts)
this._announce(opts)
} | Send a `stop` announce to the trackers.
@param {Object} opts
@param {number=} opts.uploaded
@param {number=} opts.downloaded
@param {number=} opts.numwant
@param {number=} opts.left (if not set, calculated automatically) | stop ( opts ) | javascript | webtorrent/bittorrent-tracker | client.js | https://github.com/webtorrent/bittorrent-tracker/blob/master/client.js | MIT |
complete (opts) {
if (!opts) opts = {}
opts = this._defaultAnnounceOpts(opts)
opts.event = 'completed'
debug('send `complete` %o', opts)
this._announce(opts)
} | Send a `complete` announce to the trackers.
@param {Object} opts
@param {number=} opts.uploaded
@param {number=} opts.downloaded
@param {number=} opts.numwant
@param {number=} opts.left (if not set, calculated automatically) | complete ( opts ) | javascript | webtorrent/bittorrent-tracker | client.js | https://github.com/webtorrent/bittorrent-tracker/blob/master/client.js | MIT |
update (opts) {
opts = this._defaultAnnounceOpts(opts)
if (opts.event) delete opts.event
debug('send `update` %o', opts)
this._announce(opts)
} | Send a `update` announce to the trackers.
@param {Object} opts
@param {number=} opts.uploaded
@param {number=} opts.downloaded
@param {number=} opts.numwant
@param {number=} opts.left (if not set, calculated automatically) | update ( opts ) | javascript | webtorrent/bittorrent-tracker | client.js | https://github.com/webtorrent/bittorrent-tracker/blob/master/client.js | MIT |
scrape (opts) {
debug('send `scrape`')
if (!opts) opts = {}
this._trackers.forEach(tracker => {
// tracker should not modify `opts` object, it's passed to all trackers
tracker.scrape(opts)
})
} | Send a scrape request to the trackers.
@param {Object} opts | scrape ( opts ) | javascript | webtorrent/bittorrent-tracker | client.js | https://github.com/webtorrent/bittorrent-tracker/blob/master/client.js | MIT |
function fromUInt64 (buf) {
const high = buf.readUInt32BE(0) | 0 // force
const low = buf.readUInt32BE(4) | 0
const lowUnsigned = (low >= 0) ? low : TWO_PWR_32 + low
return (high * TWO_PWR_32) + lowUnsigned
} | Return the closest floating-point representation to the buffer value. Precision will be
lost for big numbers. | fromUInt64 ( buf ) | javascript | webtorrent/bittorrent-tracker | lib/server/parse-udp.js | https://github.com/webtorrent/bittorrent-tracker/blob/master/lib/server/parse-udp.js | MIT |
module.exports.queryDisplayConfig = () => {
return new Promise((resolve, reject) => {
const ran = addon.win32_queryDisplayConfig((err, result) => {
if (err !== null) {
reject(new Win32Error(err));
} else {
resolve(result);
}
});
if (!ran) {
resolve(undefined);
}
});
}; | Retrieves low-level information from the Win32 API QueryDisplayConfig.
The output of this function somewhat matches the "output" values of
QueryDisplayConfig, as documented at
https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-querydisplayconfig,
in the pathArray and modeInfoArray results.
Additionally, this function uses the DisplayConfigGetDeviceInfo function over
all resolved displays to return the names, output technology, and manufacturer IDs
in the nameArray results.
@returns {Promise<QueryDisplayConfigResults>}
A Promise, resolving to { pathArray: [...], modeInfoArray: [...], nameArray: [...] },
or rejecting with a {@link Win32Error} if something goes wrong. | module.exports.queryDisplayConfig | javascript | xanderfrangos/twinkle-tray | src/modules/win32-displayconfig/index.js | https://github.com/xanderfrangos/twinkle-tray/blob/master/src/modules/win32-displayconfig/index.js | MIT |
module.exports.extractDisplayConfig = async () => {
const config = await module.exports.queryDisplayConfig();
const ret = [];
for (const { value, buffer: pathBuffer } of config.pathArray) {
let inUse = value.flags & (1 === 1) ? true : false;
const { sourceInfo, targetInfo } = value;
const {
modeInfoIdx: sourceModeIdx,
adapterId: sourceAdapterId,
id: sourceId,
} = sourceInfo;
const {
adapterId,
id,
outputTechnology,
rotation,
scaling,
modeInfoIdx: targetModeIdx,
} = targetInfo;
const sourceConfigId = {
adapterId: sourceAdapterId,
id: sourceId,
};
const targetConfigId = {
adapterId,
id,
};
const displayNameEntry = config.nameArray.find(
(n) =>
n.adapterId.LowPart === adapterId.LowPart &&
n.adapterId.HighPart === adapterId.HighPart &&
n.id === id &&
n.outputTechnology &&
outputTechnology &&
n.monitorDevicePath.length > 0
);
if (displayNameEntry === undefined) {
continue;
}
const sourceMode = config.modeArray[sourceModeIdx];
const targetMode = config.modeArray[targetModeIdx];
if (sourceMode === undefined) {
continue;
}
if (targetMode === undefined) {
// When we can't find the target mode, but _can_
// find the source mode, that just means the monitor is off.
inUse = false;
}
const sourceModeValue = sourceMode.value;
if (sourceModeValue.infoType !== "source") {
continue;
}
const { monitorFriendlyDeviceName, monitorDevicePath } = displayNameEntry;
const output = {
displayName: monitorFriendlyDeviceName,
devicePath: monitorDevicePath,
sourceConfigId,
targetConfigId,
inUse,
outputTechnology,
rotation,
scaling,
sourceMode: sourceModeValue.sourceMode,
pathBuffer,
sourceModeBuffer: sourceMode.buffer,
};
if (targetMode !== undefined) {
const targetModeValue = targetMode.value;
if (targetModeValue.infoType === "target") {
output.targetVideoSignalInfo =
targetModeValue.targetMode.targetVideoSignalInfo;
output.targetModeBuffer = targetMode.buffer;
}
}
ret.push(output);
}
return ret;
}; | Retrieves higher-level information from the Win32 API QueryDisplayConfig.
Unlike {@link queryDisplayConfig}, this function pulls all relevant information
about a device/mode pairing into a single object.
@returns {Promise<ExtractedDisplayConfig>} A Promise, resolving to display configuration information
or rejecting with a {@link Win32Error} if something goes wrong. | module.exports.extractDisplayConfig | javascript | xanderfrangos/twinkle-tray | src/modules/win32-displayconfig/index.js | https://github.com/xanderfrangos/twinkle-tray/blob/master/src/modules/win32-displayconfig/index.js | MIT |
module.exports.toggleEnabledDisplays = async (args) => {
const { persistent, enable: enablePaths, disable: disablePaths } = args;
const enable = [];
const disable = [];
const displayConfig = await module.exports.extractDisplayConfig();
for (const { devicePath, targetConfigId } of displayConfig) {
if (Array.isArray(enablePaths) && enablePaths.indexOf(devicePath) >= 0) {
enable.push(targetConfigId);
}
if (Array.isArray(disablePaths) && disablePaths.indexOf(devicePath) >= 0) {
disable.push(targetConfigId);
}
}
await win32_toggleEnabledDisplays({ enable, disable, persistent });
}; | Toggles enabled/disabled state of the given displays.
If "persistent", then this is saved between restarts.
@param {ToggleEnabledDisplaysArgs} args | module.exports.toggleEnabledDisplays | javascript | xanderfrangos/twinkle-tray | src/modules/win32-displayconfig/index.js | https://github.com/xanderfrangos/twinkle-tray/blob/master/src/modules/win32-displayconfig/index.js | MIT |
module.exports.addDisplayChangeListener = (listener) => {
if (displayChangeCallbacks.size === 0) {
setupListenForDisplayChanges();
}
displayChangeCallbacks.add(listener);
if (currentDisplayConfig !== undefined) {
listener(null, currentDisplayConfig);
}
return listener;
}; | Registers a display change listener.
This function will be called immediately upon registration, receiving the
current display configuration. It will also be called every time the display
configuration changes in Windows, e.g. when users attach or rearrange new
displays, or alter the output resolution of already-attached displays.
Note that the Node event loop will continue executing if any outstanding change
listeners are registered, precluding graceful shutdown. Use {@link removeDisplayChangeListener}
to remove outstanding display change listeners and clear the event loop.
@param {function(Error | null, ExtractedDisplayConfig | undefined): void} listener
@returns {function(Error | null, ExtractedDisplayConfig | undefined): void} the listener argument as passed | module.exports.addDisplayChangeListener | javascript | xanderfrangos/twinkle-tray | src/modules/win32-displayconfig/index.js | https://github.com/xanderfrangos/twinkle-tray/blob/master/src/modules/win32-displayconfig/index.js | MIT |
module.exports.removeDisplayChangeListener = (listener) => {
displayChangeCallbacks.delete(listener);
if (displayChangeCallbacks.size === 0) {
addon.win32_stopListeningForDisplayChanges();
}
}; | De-registers a display change listener.
De-registering all display change listeners clears the event loop of pending
work started by {@link addDisplayChangeListener} to allow for a graceful shutdown.
@param {function(Error | null, ExtractedDisplayConfig | undefined): void} listener previously passed to {@link addDisplayChangeListener} | module.exports.removeDisplayChangeListener | javascript | xanderfrangos/twinkle-tray | src/modules/win32-displayconfig/index.js | https://github.com/xanderfrangos/twinkle-tray/blob/master/src/modules/win32-displayconfig/index.js | MIT |
async findVerticalRefreshRateForDisplayPoint(x, y) {
await this.readyPromise;
let ret;
for (const { top, bottom, left, right, vRefreshRate } of this.geometry) {
if (left <= x && x < right && top <= y && y < bottom) {
ret = ret === undefined ? vRefreshRate : Math.min(ret, vRefreshRate);
}
}
return ret;
} | Computes the vertical refresh rate of the displays at a given display point.
If any displays overlap at the given display point, the return result will
be the minimum of the vertical refresh rates of each physical device displaying
at that effective point.
This method is asynchronous due to the implementation of addDisplayChangeListener;
it waits for a valid display configuration to be captured before returning the
best possible refresh rate.
@param {number} x The vertical offset of the display point
@param {number} y The horizontal offset of the display point
@returns {number | undefined} The vertical refresh rate at the given display point,
or undefined if the given display point is out of bounds of the available display space. | findVerticalRefreshRateForDisplayPoint ( x , y ) | javascript | xanderfrangos/twinkle-tray | src/modules/win32-displayconfig/index.js | https://github.com/xanderfrangos/twinkle-tray/blob/master/src/modules/win32-displayconfig/index.js | MIT |
close() {
module.exports.removeDisplayChangeListener(this.changeListener);
} | Disconnects this instance from display change events.
Disconnecting the instance from display change events will clear relevant
work items off of the event loop as per {@link removeDisplayChangeListener}. | close ( ) | javascript | xanderfrangos/twinkle-tray | src/modules/win32-displayconfig/index.js | https://github.com/xanderfrangos/twinkle-tray/blob/master/src/modules/win32-displayconfig/index.js | MIT |
( function ( THREE ) {
THREE.Raycaster = function ( origin, direction, near, far ) {
this.ray = new THREE.Ray( origin, direction );
// direction is assumed to be normalized (for accurate distance calculations)
this.near = near || 0;
this.far = far || Infinity;
this.params = {
Mesh: {},
Line: {},
LOD: {},
Points: { threshold: 1 },
Sprite: {}
};
Object.defineProperties( this.params, {
PointCloud: {
get: function () {
console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
return this.Points;
}
}
} );
};
function ascSort( a, b ) {
return a.distance - b.distance;
}
function intersectObject( object, raycaster, intersects, recursive ) {
if ( object.visible === false ) return;
object.raycast( raycaster, intersects );
if ( recursive === true ) {
var children = object.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
intersectObject( children[ i ], raycaster, intersects, true );
}
}
}
//
THREE.Raycaster.prototype = {
constructor: THREE.Raycaster,
linePrecision: 1,
set: function ( origin, direction ) {
// direction is assumed to be normalized (for accurate distance calculations)
this.ray.set( origin, direction );
},
setFromCamera: function ( coords, camera ) {
if ( camera instanceof THREE.PerspectiveCamera ) {
this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
} else if ( camera instanceof THREE.OrthographicCamera ) {
this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
} else {
console.error( 'THREE.Raycaster: Unsupported camera type.' );
}
},
intersectObject: function ( object, recursive ) {
var intersects = [];
intersectObject( object, this, intersects, recursive );
intersects.sort( ascSort );
return intersects;
},
intersectObjects: function ( objects, recursive ) {
var intersects = [];
if ( Array.isArray( objects ) === false ) {
console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
return intersects;
}
for ( var i = 0, l = objects.length; i < l; i ++ ) {
intersectObject( objects[ i ], this, intersects, recursive );
}
intersects.sort( ascSort );
return intersects;
}
};
| @author mrdoob / http://mrdoob.com/
@author bhouston / http://clara.io/
@author stephomi / http://stephaneginier.com/ | ; ( function ( THREE ) | javascript | Ovilia/ThreeExample.js | lib/three.js | https://github.com/Ovilia/ThreeExample.js/blob/master/lib/three.js | MIT |
THREE.MTLLoader = function( manager ) {
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
}; | Loads a Wavefront .mtl file specifying materials
@author angelxuanchang | THREE.MTLLoader ( manager ) | javascript | Ovilia/ThreeExample.js | lib/MTLLoader.js | https://github.com/Ovilia/ThreeExample.js/blob/master/lib/MTLLoader.js | MIT |
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var loader = new THREE.XHRLoader( this.manager );
loader.setPath( this.path );
loader.load( url, function ( text ) {
onLoad( scope.parse( text ) );
}, onProgress, onError );
}, | Loads and parses a MTL asset from a URL.
@param {String} url - URL to the MTL file.
@param {Function} [onLoad] - Callback invoked with the loaded object.
@param {Function} [onProgress] - Callback for download progress.
@param {Function} [onError] - Callback for download errors.
@see setPath setTexturePath
@note In order for relative texture references to resolve correctly
you must call setPath and/or setTexturePath explicitly prior to load. | load ( url , onLoad , onProgress , onError ) | javascript | Ovilia/ThreeExample.js | lib/MTLLoader.js | https://github.com/Ovilia/ThreeExample.js/blob/master/lib/MTLLoader.js | MIT |
setPath: function ( path ) {
this.path = path;
}, | Set base path for resolving references.
If set this path will be prepended to each loaded and found reference.
@see setTexturePath
@param {String} path
@example
mtlLoader.setPath( 'assets/obj/' );
mtlLoader.load( 'my.mtl', ... ); | setPath ( path ) | javascript | Ovilia/ThreeExample.js | lib/MTLLoader.js | https://github.com/Ovilia/ThreeExample.js/blob/master/lib/MTLLoader.js | MIT |
setTexturePath: function( path ) {
this.texturePath = path;
}, | Set base path for resolving texture references.
If set this path will be prepended found texture reference.
If not set and setPath is, it will be used as texture base path.
@see setPath
@param {String} path
@example
mtlLoader.setPath( 'assets/obj/' );
mtlLoader.setTexturePath( 'assets/textures/' );
mtlLoader.load( 'my.mtl', ... ); | setTexturePath ( path ) | javascript | Ovilia/ThreeExample.js | lib/MTLLoader.js | https://github.com/Ovilia/ThreeExample.js/blob/master/lib/MTLLoader.js | MIT |
parse: function ( text ) {
var lines = text.split( '\n' );
var info = {};
var delimiter_pattern = /\s+/;
var materialsInfo = {};
for ( var i = 0; i < lines.length; i ++ ) {
var line = lines[ i ];
line = line.trim();
if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
// Blank line or comment ignore
continue;
}
var pos = line.indexOf( ' ' );
var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
key = key.toLowerCase();
var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
value = value.trim();
if ( key === 'newmtl' ) {
// New material
info = { name: value };
materialsInfo[ value ] = info;
} else if ( info ) {
if ( key === 'ka' || key === 'kd' || key === 'ks' ) {
var ss = value.split( delimiter_pattern, 3 );
info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
} else {
info[ key ] = value;
}
}
}
var materialCreator = new THREE.MTLLoader.MaterialCreator( this.texturePath || this.path, this.materialOptions );
materialCreator.setCrossOrigin( this.crossOrigin );
materialCreator.setManager( this.manager );
materialCreator.setMaterials( materialsInfo );
return materialCreator;
} | Parses a MTL file.
@param {String} text - Content of MTL file
@return {THREE.MTLLoader.MaterialCreator}
@see setPath setTexturePath
@note In order for relative texture references to resolve correctly
you must call setPath and/or setTexturePath explicitly prior to parse. | parse ( text ) | javascript | Ovilia/ThreeExample.js | lib/MTLLoader.js | https://github.com/Ovilia/ThreeExample.js/blob/master/lib/MTLLoader.js | MIT |
THREE.MTLLoader.MaterialCreator = function( baseUrl, options ) {
this.baseUrl = baseUrl || '';
this.options = options;
this.materialsInfo = {};
this.materials = {};
this.materialsArray = [];
this.nameLookup = {};
this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
}; | Create a new THREE-MTLLoader.MaterialCreator
@param baseUrl - Url relative to which textures are loaded
@param options - Set of options on how to construct the materials
side: Which side to apply the material
THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
wrap: What type of wrapping to apply for textures
THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
Default: false, assumed to be already normalized
ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
Default: false
@constructor | THREE.MTLLoader.MaterialCreator ( baseUrl , options ) | javascript | Ovilia/ThreeExample.js | lib/MTLLoader.js | https://github.com/Ovilia/ThreeExample.js/blob/master/lib/MTLLoader.js | MIT |
THREE.OBJMTLLoader = function () {}; | Loads a Wavefront .obj file with materials
@author mrdoob / http://mrdoob.com/
@author angelxuanchang | THREE.OBJMTLLoader ( ) | javascript | Ovilia/ThreeExample.js | lib/OBJMTLLoader.js | https://github.com/Ovilia/ThreeExample.js/blob/master/lib/OBJMTLLoader.js | MIT |
load: function ( url, mtlfileurl, options ) {
var scope = this;
var xhr = new XMLHttpRequest();
var mtlDone; // Is the MTL done (true if no MTL, error loading MTL, or MTL actually loaded)
var obj3d; // Loaded model (from obj file)
var materialsCreator; // Material creator is created when MTL file is loaded
// Loader for MTL
var mtlLoader = new THREE.MTLLoader( url.substr( 0, url.lastIndexOf( "/" ) + 1 ), options );
mtlLoader.addEventListener( 'load', waitReady );
mtlLoader.addEventListener( 'error', waitReady );
// Try to load mtlfile
if ( mtlfileurl ) {
mtlLoader.load( mtlfileurl );
mtlDone = false;
} else {
mtlDone = true;
}
function waitReady( event ) {
if ( event.type === 'load' ) {
if ( event.content instanceof THREE.MTLLoader.MaterialCreator ) {
// MTL file is loaded
mtlDone = true;
materialsCreator = event.content;
materialsCreator.preload();
} else {
// OBJ file is loaded
if ( event.target.status === 200 || event.target.status === 0 ) {
var objContent = event.target.responseText;
if ( mtlfileurl ) {
// Parse with passed in MTL file
obj3d = scope.parse( objContent );
} else {
// No passed in MTL file, look for mtlfile in obj file
obj3d = scope.parse( objContent, function( mtlfile ) {
mtlDone = false;
mtlLoader.load( mtlLoader.baseUrl + mtlfile );
} );
}
} else {
// Error loading OBJ file....
scope.dispatchEvent( {
type: 'error',
message: 'Couldn\'t load URL [' + url + ']',
response: event.target.responseText } );
}
}
} else if ( event.type === 'error' ) {
// MTL failed to load -- oh well, we will just not have material ...
mtlDone = true;
}
if ( mtlDone && obj3d ) {
// MTL file is loaded and OBJ file is loaded
// Apply materials to model
if ( materialsCreator ) {
obj3d.traverse( function( object ) {
if ( object instanceof THREE.Mesh ) {
if ( object.material.name ) {
var material = materialsCreator.create( object.material.name );
if ( material ) {
object.material = material;
}
}
}
} );
}
// Notify listeners
scope.dispatchEvent( { type: 'load', content: obj3d } );
}
}
xhr.addEventListener( 'load', waitReady, false );
xhr.addEventListener( 'progress', function ( event ) {
scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
}, false );
xhr.addEventListener( 'error', function () {
scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
}, false );
xhr.open( 'GET', url, true );
xhr.send( null );
}, | Load a Wavefront OBJ file with materials (MTL file)
Loading progress is indicated by the following events:
"load" event (successful loading): type = 'load', content = THREE.Object3D
"error" event (error loading): type = 'load', message
"progress" event (progress loading): type = 'progress', loaded, total
If the MTL file cannot be loaded, then a MeshLambertMaterial is used as a default
@param url - Location of OBJ file to load
@param mtlfileurl - MTL file to load (optional, if not specified, attempts to use MTL specified in OBJ file)
@param options - Options on how to interpret the material (see THREE.MTLLoader.MaterialCreator ) | load ( url , mtlfileurl , options ) | javascript | Ovilia/ThreeExample.js | lib/OBJMTLLoader.js | https://github.com/Ovilia/ThreeExample.js/blob/master/lib/OBJMTLLoader.js | MIT |
parse: function ( data, mtllibCallback ) {
// fixes
data = data.replace( /\ \\\r\n/g, '' ); // rhino adds ' \\r\n' some times.
var replacement = '/f$1$2$4\n/f$2$3$4'; // quads to tris
data = data.replace( /f( +\d+)( +\d+)( +\d+)( +\d+)/g, replacement );
data = data.replace( /f( +\d+\/\d+)( +\d+\/\d+)( +\d+\/\d+)( +\d+\/\d+)/g, replacement );
data = data.replace( /f( +\d+\/\d+\/\d+)( +\d+\/\d+\/\d+)( +\d+\/\d+\/\d+)( +\d+\/\d+\/\d+)/g, replacement );
data = data.replace( /f( +\d+\/\/\d+)( +\d+\/\/\d+)( +\d+\/\/\d+)( +\d+\/\/\d+)/g, replacement );
//
function vector( x, y, z ) {
return new THREE.Vector3( x, y, z );
}
function uv( u, v ) {
return new THREE.Vector2( u, v );
}
function face3( a, b, c, normals ) {
return new THREE.Face3( a, b, c, normals );
}
function meshN( meshName, materialName ) {
if ( geometry.vertices.length > 0 ) {
geometry.mergeVertices();
geometry.computeCentroids();
geometry.computeFaceNormals();
geometry.computeBoundingSphere();
object.add( mesh );
geometry = new THREE.Geometry();
mesh = new THREE.Mesh( geometry, material );
verticesCount = 0;
}
if ( meshName !== undefined ) mesh.name = meshName;
if ( materialName !== undefined ) {
material = new THREE.MeshLambertMaterial();
material.name = materialName;
mesh.material = material;
}
}
var group = new THREE.Object3D();
var object = group;
var geometry = new THREE.Geometry();
var material = new THREE.MeshLambertMaterial();
var mesh = new THREE.Mesh( geometry, material );
var vertices = [];
var verticesCount = 0;
var normals = [];
var uvs = [];
// v float float float
var vertex_pattern = /v( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/;
// vn float float float
var normal_pattern = /vn( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/;
// vt float float
var uv_pattern = /vt( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/
// f vertex vertex vertex
var face_pattern1 = /f( +\d+)( +\d+)( +\d+)/
// f vertex/uv vertex/uv vertex/uv
var face_pattern2 = /f( +(\d+)\/(\d+))( +(\d+)\/(\d+))( +(\d+)\/(\d+))/;
// f vertex/uv/normal vertex/uv/normal vertex/uv/normal
var face_pattern3 = /f( +(\d+)\/(\d+)\/(\d+))( +(\d+)\/(\d+)\/(\d+))( +(\d+)\/(\d+)\/(\d+))/;
// f vertex//normal vertex//normal vertex//normal
var face_pattern4 = /f( +(\d+)\/\/(\d+))( +(\d+)\/\/(\d+))( +(\d+)\/\/(\d+))/;
//
var lines = data.split( "\n" );
for ( var i = 0; i < lines.length; i ++ ) {
var line = lines[ i ];
line = line.trim();
var result;
if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
continue;
} else if ( ( result = vertex_pattern.exec( line ) ) !== null ) {
// ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
vertices.push( vector(
parseFloat( result[ 1 ] ),
parseFloat( result[ 2 ] ),
parseFloat( result[ 3 ] )
) );
} else if ( ( result = normal_pattern.exec( line ) ) !== null ) {
// ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
normals.push( vector(
parseFloat( result[ 1 ] ),
parseFloat( result[ 2 ] ),
parseFloat( result[ 3 ] )
) );
} else if ( ( result = uv_pattern.exec( line ) ) !== null ) {
// ["vt 0.1 0.2", "0.1", "0.2"]
uvs.push( uv(
parseFloat( result[ 1 ] ),
parseFloat( result[ 2 ] )
) );
} else if ( ( result = face_pattern1.exec( line ) ) !== null ) {
// ["f 1 2 3", "1", "2", "3"]
geometry.vertices.push(
vertices[ parseInt( result[ 1 ] ) - 1 ],
vertices[ parseInt( result[ 2 ] ) - 1 ],
vertices[ parseInt( result[ 3 ] ) - 1 ]
);
geometry.faces.push( face3(
verticesCount ++,
verticesCount ++,
verticesCount ++
) );
} else if ( ( result = face_pattern2.exec( line ) ) !== null ) {
// ["f 1/1 2/2 3/3", " 1/1", "1", "1", " 2/2", "2", "2", " 3/3", "3", "3"]
geometry.vertices.push(
vertices[ parseInt( result[ 2 ] ) - 1 ],
vertices[ parseInt( result[ 5 ] ) - 1 ],
vertices[ parseInt( result[ 8 ] ) - 1 ]
);
geometry.faces.push( face3(
verticesCount ++,
verticesCount ++,
verticesCount ++
) );
geometry.faceVertexUvs[ 0 ].push( [
uvs[ parseInt( result[ 3 ] ) - 1 ],
uvs[ parseInt( result[ 6 ] ) - 1 ],
uvs[ parseInt( result[ 9 ] ) - 1 ]
] );
} else if ( ( result = face_pattern3.exec( line ) ) !== null ) {
// ["f 1/1/1 2/2/2 3/3/3", " 1/1/1", "1", "1", "1", " 2/2/2", "2", "2", "2", " 3/3/3", "3", "3", "3"]
geometry.vertices.push(
vertices[ parseInt( result[ 2 ] ) - 1 ],
vertices[ parseInt( result[ 6 ] ) - 1 ],
vertices[ parseInt( result[ 10 ] ) - 1 ]
);
geometry.faces.push( face3(
verticesCount ++,
verticesCount ++,
verticesCount ++,
[
normals[ parseInt( result[ 4 ] ) - 1 ],
normals[ parseInt( result[ 8 ] ) - 1 ],
normals[ parseInt( result[ 12 ] ) - 1 ]
]
) );
geometry.faceVertexUvs[ 0 ].push( [
uvs[ parseInt( result[ 3 ] ) - 1 ],
uvs[ parseInt( result[ 7 ] ) - 1 ],
uvs[ parseInt( result[ 11 ] ) - 1 ]
] );
} else if ( ( result = face_pattern4.exec( line ) ) !== null ) {
// ["f 1//1 2//2 3//3", " 1//1", "1", "1", " 2//2", "2", "2", " 3//3", "3", "3"]
geometry.vertices.push(
vertices[ parseInt( result[ 2 ] ) - 1 ],
vertices[ parseInt( result[ 5 ] ) - 1 ],
vertices[ parseInt( result[ 8 ] ) - 1 ]
);
geometry.faces.push( face3(
verticesCount ++,
verticesCount ++,
verticesCount ++,
[
normals[ parseInt( result[ 3 ] ) - 1 ],
normals[ parseInt( result[ 6 ] ) - 1 ],
normals[ parseInt( result[ 9 ] ) - 1 ]
]
) );
} else if ( /^o /.test( line ) ) {
// object
object = new THREE.Object3D();
object.name = line.substring( 2 ).trim();
group.add( object );
} else if ( /^g /.test( line ) ) {
// group
meshN( line.substring( 2 ).trim(), undefined );
} else if ( /^usemtl /.test( line ) ) {
// material
meshN( undefined, line.substring( 7 ).trim() );
} else if ( /^mtllib /.test( line ) ) {
// mtl file
if ( mtllibCallback ) {
var mtlfile = line.substring( 7 );
mtlfile = mtlfile.trim();
mtllibCallback( mtlfile );
}
} else if ( /^s /.test( line ) ) {
// Smooth shading
} else {
console.log( "THREE.OBJMTLLoader: Unhandled line " + line );
}
}
//Add last object
meshN(undefined, undefined);
return group;
} | Parses loaded .obj file
@param data - content of .obj file
@param mtllibCallback - callback to handle mtllib declaration (optional)
@return {THREE.Object3D} - Object3D (with default material) | parse ( data , mtllibCallback ) | javascript | Ovilia/ThreeExample.js | lib/OBJMTLLoader.js | https://github.com/Ovilia/ThreeExample.js/blob/master/lib/OBJMTLLoader.js | MIT |
export function group(name, fn) {
const s = suite(name)
fn(s)
s.run()
} | Nicer test nesting API.
https://github.com/lukeed/uvu/issues/43
@param {string} name
@param {(test: import('uvu').Test) => void} fn | group ( name , fn ) | javascript | bluwy/whyframe | scripts/uvuUtils.js | https://github.com/bluwy/whyframe/blob/master/scripts/uvuUtils.js | MIT |
export async function groupAsync(name, fn) {
const s = suite(name)
await fn(s)
s.run()
} | Nicer test nesting API.
https://github.com/lukeed/uvu/issues/43
@param {string} name
@param {(test: import('uvu').Test) => Promise<void>} fn | groupAsync ( name , fn ) | javascript | bluwy/whyframe | scripts/uvuUtils.js | https://github.com/bluwy/whyframe/blob/master/scripts/uvuUtils.js | MIT |
export function smartTest(test, name) {
let t = test
if (name.endsWith('.only')) {
// @ts-ignore
t = t.only
} else if (name.endsWith('.skip')) {
// @ts-ignore
t = t.skip
}
return t
} | @param {import('uvu').Test} test
@param {string} name
@returns {import('uvu').Test['only']} | smartTest ( test , name ) | javascript | bluwy/whyframe | scripts/uvuUtils.js | https://github.com/bluwy/whyframe/blob/master/scripts/uvuUtils.js | MIT |
export async function assertFixture(actual, outputFile, msg) {
if (isUpdate) {
await fs.writeFile(outputFile, actual)
} else {
let expects
try {
expects = await fs.readFile(outputFile, 'utf-8')
} catch (e) {
throw new Error(
`Unable to read fixture: ${outputFile}. Did you forget to run "pnpm test:unit-update"?`,
{ cause: e }
)
}
assert.fixture(actual, expects, msg)
}
} | @param {string} actual
@param {string} outputFile
@param {assert.Message} [msg] | assertFixture ( actual , outputFile , msg ) | javascript | bluwy/whyframe | scripts/uvuUtils.js | https://github.com/bluwy/whyframe/blob/master/scripts/uvuUtils.js | MIT |
export function prependComment(code, comment, ext) {
switch (ext) {
case '.svelte':
case '.vue':
case '.html':
return `<!-- ${comment} -->\n${code}`
default:
return `// ${comment}\n${code}`
}
} | @param {string} code
@param {string} comment
@param {string} ext | prependComment ( code , comment , ext ) | javascript | bluwy/whyframe | scripts/uvuUtils.js | https://github.com/bluwy/whyframe/blob/master/scripts/uvuUtils.js | MIT |
async function waitUrlReady(url, request) {
let timeout
const timeoutPromise = new Promise((_, reject) => {
timeout = setTimeout(() => reject(`Timeout for ${url}`), waitUrlTimeout)
})
let interval
const fetchPromise = new Promise((resolve) => {
interval = setInterval(() => {
request
.fetch(url)
.then((res) => {
if (res.ok()) {
resolve()
}
})
.catch(() => {})
}, 1000)
})
return Promise.race([timeoutPromise, fetchPromise]).finally(() => {
clearTimeout(timeout)
clearInterval(interval)
})
} | @param {string} url
@param {import('@playwright/test').APIRequestContext} request | waitUrlReady ( url , request ) | javascript | bluwy/whyframe | tests/testUtils.js | https://github.com/bluwy/whyframe/blob/master/tests/testUtils.js | MIT |
function validateImportSource(framework) {
if (framework === 'solid-js') {
return 'solid'
} else if (framework === 'preact') {
return 'preact'
} else if (framework === 'react') {
return 'react'
}
} | @param {any} framework
@return {import('..').Options['defaultFramework'] | undefined} | validateImportSource ( framework ) | javascript | bluwy/whyframe | packages/jsx/src/shared.js | https://github.com/bluwy/whyframe/blob/master/packages/jsx/src/shared.js | MIT |
function createEntry(entryId, framework) {
switch (framework) {
case 'react':
return `\
import React from 'react'
import ReactDOM from 'react-dom/client'
import { WhyframeApp } from '${entryId}'
export function createApp(el) {
ReactDOM.createRoot(el).render(<WhyframeApp />)
return {
destroy: () => ReactDOM.createRoot(el).unmount()
}
}`
case 'preact':
return `\
import { render } from 'preact'
import { WhyframeApp } from '${entryId}'
export function createApp(el) {
render(<WhyframeApp />, el)
return {
destroy: () => render(null, el)
}
}`
case 'solid':
return `\
import { render } from 'solid-js/web'
import { WhyframeApp } from '${entryId}'
export function createApp(el) {
const destroy = render(() => <WhyframeApp />, el)
return { destroy }
}`
case 'react17':
return `\
import React from 'react'
import ReactDOM from 'react-dom'
import { WhyframeApp } from '${entryId}'
export function createApp(el) {
ReactDOM.render(<WhyframeApp />, el)
return {
destroy: () => ReactDOM.unmountComponentAtNode(el)
}
}`
}
}
// TODO: optimize
function astContainsNode(ast, node) {
let found = false
walk(ast, {
enter(n) {
if (node === n) {
found = true
this.skip()
}
}
})
return found
} | @param {string} entryId
@param {import('..').Options['defaultFramework']} framework | createEntry ( entryId , framework ) | javascript | bluwy/whyframe | packages/jsx/src/shared.js | https://github.com/bluwy/whyframe/blob/master/packages/jsx/src/shared.js | MIT |
export function addAttrs(s, node, attrs, propsIdentifier) {
const attrNames = node.openingElement.attributes.map((a) => a.name.name)
const safeAttrs = []
const mixedAttrs = []
for (const attr of attrs) {
if (attrNames.includes(attr.name)) {
mixedAttrs.push(attr)
} else {
safeAttrs.push(attr)
}
}
s.appendLeft(
node.start + node.openingElement.name.name.length + 1,
safeAttrs
.map((a) => ` ${a.name}={${parseAttrToString(a, propsIdentifier)}}`)
.join('')
)
for (const attr of mixedAttrs) {
const attrNode = node.openingElement.attributes.find(
(a) => a.name.name === attr.name
)
if (!attrNode) continue
const valueNode = attrNode.value
if (!valueNode) continue
if (valueNode.type === 'JSXExpressionContainer') {
// foo={foo && bar} -> foo={(foo && bar) || "fallback"}
const expression = s.original.slice(
valueNode.start + 1,
valueNode.end - 1
)
s.overwrite(
valueNode.start,
valueNode.end,
`{(${expression}) || ${parseAttrToString(attr, propsIdentifier)}}`
)
}
}
} | @param {MagicString} s
@param {any} node
@param {import('@whyframe/core').Attr[]} attrs
@param {string} [propsIdentifier] | addAttrs ( s , node , attrs , propsIdentifier ) | javascript | bluwy/whyframe | packages/jsx/src/shared.js | https://github.com/bluwy/whyframe/blob/master/packages/jsx/src/shared.js | MIT |
export function parseAttrToString(attr, propsIdentifier = 'arguments[0]') {
if (attr.type === 'dynamic' && typeof attr.value === 'string') {
return `${propsIdentifier}.${attr.value}`
} else {
return JSON.stringify(attr.value)
}
} | @param {import('@whyframe/core').Attr} attr | parseAttrToString ( attr , propsIdentifier = 'arguments[0]' ) | javascript | bluwy/whyframe | packages/jsx/src/shared.js | https://github.com/bluwy/whyframe/blob/master/packages/jsx/src/shared.js | MIT |
function hasDynamicAttrs(attrs) {
return attrs.some((attr) => attr.type === 'dynamic')
} | @param {import('@whyframe/core').Attr[]} attrs | hasDynamicAttrs ( attrs ) | javascript | bluwy/whyframe | packages/jsx/src/shared.js | https://github.com/bluwy/whyframe/blob/master/packages/jsx/src/shared.js | MIT |
function getFnFirstParamIdentifier(fn, s, filename) {
// function Hello() {}
// const Hello = function() {}
if (!t.isArrowFunctionExpression(fn)) {
return 'arguments[0]'
}
// const Hello = () => {}
if (fn.params.length === 0) {
// convert as: const Hello = ($$props) => {}
s.appendRight((fn.start ?? 0) + 1, '$$props')
return '$$props'
}
// const Hello = (...args) => {}
if (t.isRestElement(fn.params[0])) {
// NOTE: `argument` may not have `.name` if it's `...{}` for some reason
// @ts-expect-error
return `${fn.params[0].argument.name}[0]`
}
/**
* @param {any} param
*/
const handleFirstParam = (param) => {
// const Hello = (somePropName) => {}
if (t.isIdentifier(param)) {
// NOTE: this would fail if someone shadows the first param identifier for some reason
return param.name
}
// const Hello = ({ something }) => <iframe></iframe>
// const Hello = ({ something }) => {}
if (t.isObjectPattern(param)) {
const firstParamStart = param.start ?? 0
const firstParamEnd = param.end ?? 0
const destructure = s.original.slice(firstParamStart, firstParamEnd)
// convert as: const Hello = ($$props) => ...
s.overwrite(firstParamStart, firstParamEnd, '$$props')
// handle return statement
// const Hello = ($$props) => {}
if (t.isBlockStatement(fn.body)) {
// convert as: const Hello = ($$props) => {const { something } = $$props;...}
s.prependRight(
(fn.body.start ?? 0) + 1,
`const ${destructure} = $$props;`
)
}
// const Hello = ($$props) => <iframe></iframe>
else {
const bodyStart = fn.body.start ?? 0
const bodyEnd = fn.body.end ?? 0
// convert as: const Hello = ($$props) => {const { something } = $$props;return(...)}
s.appendLeft(bodyStart, `{const ${destructure} = $$props;return(`)
s.prependRight(bodyEnd, ')}')
}
return '$$props'
}
console.warn(`[whyframe] unable to transform first param in ${filename}`)
return 'arguments[0]'
}
if (t.isAssignmentPattern(fn.params[0])) {
return handleFirstParam(fn.params[0].left)
}
return handleFirstParam(fn.params[0])
}
/**
* @param {import('@whyframe/core').Attr[]} attrs
*/
function hasDynamicAttrs(attrs) { | @param {t.FunctionDeclaration | t.FunctionExpression | t.ArrowFunctionExpression} fn
@param {MagicString} s
@param {string} filename
@returns {string} | getFnFirstParamIdentifier ( fn , s , filename ) | javascript | bluwy/whyframe | packages/jsx/src/shared.js | https://github.com/bluwy/whyframe/blob/master/packages/jsx/src/shared.js | MIT |
export function addAttrs(s, node, attrs) {
const attrNames = node.attributes.map((a) => a.name)
const safeAttrs = []
const mixedAttrs = []
for (const attr of attrs) {
if (attrNames.includes(attr.name)) {
mixedAttrs.push(attr)
} else {
safeAttrs.push(attr)
}
}
s.appendLeft(
node.start + node.name.length + 1,
safeAttrs.map((a) => ` ${a.name}={${parseAttrToString(a)}}`).join('')
)
for (const attr of mixedAttrs) {
const attrNode = node.attributes.find((a) => a.name === attr.name)
if (!attrNode) continue
const valueNode = attrNode.value?.[0]
if (!valueNode) continue
if (valueNode.type === 'MustacheTag') {
// foo={foo && bar} -> foo={(foo && bar) || "fallback"}
const expression = s.original.slice(
valueNode.start + 1,
valueNode.end - 1
)
s.overwrite(
valueNode.start,
valueNode.end,
`{(${expression}) || ${parseAttrToString(attr)}}`
)
} else if (valueNode.type === 'AttributeShorthand') {
// {foo} -> foo={foo || "fallback"}
const expression = valueNode.expression.name
s.overwrite(
attrNode.start,
attrNode.end,
`${expression}={${expression} || ${parseAttrToString(attr)}}`
)
}
}
} | @param {MagicString} s
@param {any} node
@param {import('@whyframe/core').Attr[]} attrs | addAttrs ( s , node , attrs ) | javascript | bluwy/whyframe | packages/svelte/src/shared.js | https://github.com/bluwy/whyframe/blob/master/packages/svelte/src/shared.js | MIT |
export function addAttrs(s, node, attrs) {
const attrNames = node.props.map((p) =>
p.name !== 'bind' ? p.name : p['arg'].content
)
const safeAttrs = []
const mixedAttrs = []
for (const attr of attrs) {
if (attrNames.includes(attr.name)) {
mixedAttrs.push(attr)
} else {
safeAttrs.push(attr)
}
}
s.appendLeft(
node.loc.start.offset + node.tag.length + 1,
safeAttrs.map((a) => ` :${a.name}="${parseAttrToString(a)}"`).join('')
)
for (const attr of mixedAttrs) {
const attrNode = node.props.find((p) => p['arg']?.content === attr.name)
if (!attrNode) continue
const expNode = attrNode['exp']
if (!expNode) continue
// :foo={foo && bar} -> :foo="(foo && bar) || "fallback""
s.overwrite(
expNode.loc.start.offset,
expNode.loc.end.offset,
`(${expNode.content}) || ${parseAttrToString(attr)}`
)
}
}
/**
* @param {import('@whyframe/core').Attr} attr
*/
export function parseAttrToString(attr) {
if (attr.type === 'dynamic' && typeof attr.value === 'string') {
// TODO: i hate this
const [value, ...extra] = attr.value.split(' ')
return `$attrs.${value} || $props.${value} ${escapeAttr(extra.join(''))}`
} else {
return `${escapeAttr(JSON.stringify(attr.value))}`
}
}
/**
* @param {{ name: string }[]} plugins
* @param {string} pluginAName
* @param {'before' | 'after'} order
* @param {string} pluginBName
*/
// TODO: move this to pluginutils
export function movePlugin(plugins, pluginAName, order, pluginBName) { | @param {MagicString} s
@param {import('@vue/compiler-dom').ElementNode} node
@param {import('@whyframe/core').Attr[]} attrs | addAttrs ( s , node , attrs ) | javascript | bluwy/whyframe | packages/vue/src/shared.js | https://github.com/bluwy/whyframe/blob/master/packages/vue/src/shared.js | MIT |
constructor(cacheFile) {
let cache = undefined
if (cacheFile) {
try {
const data = fs.readFileSync(cacheFile, 'utf-8')
cache = JSON.parse(data)
} catch {}
}
super(cache)
this.cacheFile = cacheFile
} | @param {string | undefined} [cacheFile] | constructor ( cacheFile ) | javascript | bluwy/whyframe | packages/core/src/webpack/mapWithCache.js | https://github.com/bluwy/whyframe/blob/master/packages/core/src/webpack/mapWithCache.js | MIT |
constructor(config) {
for (const key in config) {
if (!Object.prototype.hasOwnProperty.call(config, key)) {
continue
}
this[key] = config[key]
}
} | Create a new stats object.
@param config Stats properties. | constructor ( config ) | javascript | bluwy/whyframe | packages/core/src/webpack/virtualStats.js | https://github.com/bluwy/whyframe/blob/master/packages/core/src/webpack/virtualStats.js | MIT |
set(id, code) {
// webpack needs a full valid fs path
const resolvedId = resolveVirtualId(id)
virtualIdToResolvedId.set(id, resolvedId)
if (typeof code === 'string') {
resolvedIdToCode.set(resolvedId, code)
} else if (code) {
resolvedIdToCodeTemp.set(resolvedId, code)
}
// write the virtual module to fs so webpack don't panic
vmp.writeModule(resolvedId, '')
}, | create or update a virtual module
@param {string} id
@param {string | undefined | Promise<string | undefined> | (() => string | undefined | Promise<string | undefined>)} code | set ( id , code ) | javascript | bluwy/whyframe | packages/core/src/webpack/virtual.js | https://github.com/bluwy/whyframe/blob/master/packages/core/src/webpack/virtual.js | MIT |
delete(id) {
virtualIdToResolvedId.delete(id)
resolvedIdToCode.delete(resolveVirtualId(id))
} | delete a virtual module
@param {string} id | delete ( id ) | javascript | bluwy/whyframe | packages/core/src/webpack/virtual.js | https://github.com/bluwy/whyframe/blob/master/packages/core/src/webpack/virtual.js | MIT |
constructor(modules) {
this._staticModules = modules || null
} | @param {Record<string, string>} [modules] | constructor ( modules ) | javascript | bluwy/whyframe | packages/core/src/webpack/virtualModule.js | https://github.com/bluwy/whyframe/blob/master/packages/core/src/webpack/virtualModule.js | MIT |
export function templatePlugin(options) {
if (!options?.defaultSrc) {
return [templateServePlugin(), templateBuildPlugin()]
} else {
return []
}
} | @param {import('../..').Options} [options]
@returns {import('vite').Plugin[]} | templatePlugin ( options ) | javascript | bluwy/whyframe | packages/core/src/plugins/template.js | https://github.com/bluwy/whyframe/blob/master/packages/core/src/plugins/template.js | MIT |
function trackVirtualId(originalId, virtualId) {
// original id tracking is only needed in dev for hot reloads
if (!isBuild) {
const virtualIds = originalIdToVirtualIds.get(originalId) ?? []
virtualIds.push(virtualId)
originalIdToVirtualIds.set(originalId, virtualIds)
}
} | @param {string} originalId
@param {string} virtualId | trackVirtualId ( originalId , virtualId ) | javascript | bluwy/whyframe | packages/core/src/plugins/api.js | https://github.com/bluwy/whyframe/blob/master/packages/core/src/plugins/api.js | MIT |
export function apiPlugin(options = {}) {
/** @type {Map<string, import('../..').LoadResult>} */
const virtualIdToCode = new Map()
// secondary map to track stale virtual ids on hot update
/** @type {Map<string, string[]>} */
const originalIdToVirtualIds = new Map()
/** @type {boolean} */
let isBuild
/** @type {string} */
let projectRoot
/** @type {string} */
let projectBase = '/'
// used for final import map generation
/** @type {Map<string, string>} */
const hashToEntryIds = new Map()
/**
* @param {string} originalId
* @param {string} virtualId
*/
function trackVirtualId(originalId, virtualId) {
// original id tracking is only needed in dev for hot reloads
if (!isBuild) {
const virtualIds = originalIdToVirtualIds.get(originalId) ?? []
virtualIds.push(virtualId)
originalIdToVirtualIds.set(originalId, virtualIds)
}
}
return {
name: 'whyframe:api',
config(_, { command }) {
isBuild = command === 'build'
},
configResolved(c) {
projectRoot = c.root
projectBase = c.base
},
/** @type {import('../..').Api} */
api: {
_getHashToEntryIds() {
return hashToEntryIds
},
_getVirtualIdToCode() {
return virtualIdToCode
},
getComponent(componentName) {
return options.components?.find((c) => c.name === componentName)
},
moduleMayHaveIframe(id, code) {
return (
!id.includes('__whyframe:') &&
!id.includes('__whyframe-') &&
(code.includes('<iframe') ||
!!options.components?.some((c) => code.includes(`<${c.name}`)))
)
},
getDefaultShowSource() {
return options.defaultShowSource ?? false
},
getMainIframeAttrs(entryId, hash, source, isComponent) {
/** @type {import('../..').Attr[]} */
const attrs = []
attrs.push({
type: 'static',
name: isComponent ? '_why?.src' : 'src',
value: options.defaultSrc || projectBase + templateDefaultId
})
if (isBuild) {
hashToEntryIds.set(hash, entryId)
attrs.push({
type: 'static',
name: isComponent ? '_why?.id' : 'data-why-id',
value: hash
})
} else {
attrs.push({
type: 'static',
name: isComponent ? '_why?.id' : 'data-why-id',
value: `${projectBase}@id/__${entryId}`
})
}
if (source) {
attrs.push({
type: 'static',
name: isComponent ? '_why?.source' : 'data-why-source',
value: source
})
}
if (isComponent) {
const whyProp = {}
for (const attr of attrs) {
whyProp[attr.name.slice('_why?.'.length)] = attr.value
}
return [
{
type: 'dynamic',
name: '_why',
value: whyProp
}
]
} else {
return attrs
}
},
getProxyIframeAttrs() {
/** @type {import('../..').Attr[]} */
return [
{
type: 'dynamic',
name: 'src',
value: `_why?.src || ${JSON.stringify(
options.defaultSrc || projectBase + templateDefaultId
)}`
},
{
type: 'dynamic',
name: 'data-why-id',
value: '_why?.id'
},
{
type: 'dynamic',
name: 'data-why-source',
value: '_why?.source'
}
]
},
createEntry(originalId, hash, ext, code) {
// example: whyframe:entry-123456.jsx
const entryId = `whyframe:entry-${hash}${ext}`
virtualIdToCode.set(entryId, code)
trackVirtualId(originalId, entryId)
return entryId
},
createEntryComponent(originalId, hash, ext, code) {
// example: /User/bjorn/foo/bar/App.svelte__whyframe-123456.svelte
const entryComponentId = `${originalId}__whyframe-${hash}${ext}`
virtualIdToCode.set(entryComponentId, code)
trackVirtualId(originalId, entryComponentId)
return entryComponentId
},
createEntryMetadata(originalId, iframeName, code) {
// example: whyframe:iframe-{iframeName?}__{importer}
const iframeNamePrepend = iframeName ? `-${iframeName}` : ''
const iframeId = `whyframe:iframe${iframeNamePrepend}__${originalId}`
virtualIdToCode.set(iframeId, code)
trackVirtualId(originalId, iframeId)
return iframeId
}
},
resolveId(id, importer) {
// see createEntry for id signature
if (id.startsWith('whyframe:entry')) {
return '__' + id
}
// see createEntryComponent for id signature
if (id.includes('__whyframe-')) {
// NOTE: this gets double resolved for some reason
if (id.startsWith(projectRoot)) {
return id
} else {
return path.join(projectRoot, id)
}
}
// see createIframeMetadata for id signature
if (id.startsWith('whyframe:iframe-')) {
return '__' + id + '__' + importer
}
},
async load(id) {
let virtualId
// see createEntry for id signature
if (id.startsWith('__whyframe:entry')) {
virtualId = id.slice(2)
}
// see createEntryComponent for id signature
if (id.includes('__whyframe-')) {
virtualId = id
}
// see createIframeMetadata for id signature
if (id.startsWith('__whyframe:iframe-')) {
virtualId = id.slice(2)
}
if (virtualId) {
let code = virtualIdToCode.get(virtualId)
// support lazy code
if (typeof code === 'function') {
code = code()
if (code instanceof Promise) {
code = await code
}
virtualIdToCode.set(virtualId, code)
}
// handle rollup result, no sourcemap needed as it's not mapping to anything
if (typeof code === 'string') {
return { code, map: { mappings: '' } }
} else {
return code
}
}
},
handleHotUpdate({ file }) {
// remove stale virtual ids
// NOTE: hot update always come first before transform
if (originalIdToVirtualIds.has(file)) {
const staleVirtualIds = originalIdToVirtualIds.get(file)
// @ts-ignore
for (const id of staleVirtualIds) {
virtualIdToCode.delete(id)
}
originalIdToVirtualIds.delete(file)
}
}
}
} | @param {import('../..').Options} [options]
@returns {import('vite').Plugin} | apiPlugin ( options = { } ) | javascript | bluwy/whyframe | packages/core/src/plugins/api.js | https://github.com/bluwy/whyframe/blob/master/packages/core/src/plugins/api.js | MIT |
function Chart(config) {
this.internal = new ChartInternal(this);
this.internal.loadConfig(config);
this.internal.beforeInit(config);
this.internal.init();
this.internal.afterInit(config);
(function bindThis(fn, target, argThis) {
Object.keys(fn).forEach(function (key) {
target[key] = fn[key].bind(argThis);
if (Object.keys(fn[key]).length > 0) {
bindThis(fn[key], target[key], argThis);
}
});
})(Chart.prototype, this, this);
} | The Chart class
The methods of this class is the public APIs of the chart object. | Chart ( config ) | javascript | c3js/c3 | c3.js | https://github.com/c3js/c3/blob/master/c3.js | MIT |
var isWithinBox = function (point, box, sensitivity) {
if (sensitivity === void 0) { sensitivity = 0; }
var xStart = box.x - sensitivity;
var xEnd = box.x + box.width + sensitivity;
var yStart = box.y + box.height + sensitivity;
var yEnd = box.y - sensitivity;
return (xStart < point[0] && point[0] < xEnd && yEnd < point[1] && point[1] < yStart);
}; | Returns whether the point is within the given box.
@param {Array} point An [x,y] coordinate
@param {Object} box An object with {x, y, width, height} keys
@param {Number} sensitivity An offset to ease check on very small boxes | isWithinBox ( point , box , sensitivity ) | javascript | c3js/c3 | c3.js | https://github.com/c3js/c3/blob/master/c3.js | MIT |
var getIEVersion = function (agent) {
// https://stackoverflow.com/questions/19999388/check-if-user-is-using-ie
if (typeof agent === 'undefined') {
agent = window.navigator.userAgent;
}
var pos = agent.indexOf('MSIE '); // up to IE10
if (pos > 0) {
return parseInt(agent.substring(pos + 5, agent.indexOf('.', pos)), 10);
}
pos = agent.indexOf('Trident/'); // IE11
if (pos > 0) {
pos = agent.indexOf('rv:');
return parseInt(agent.substring(pos + 3, agent.indexOf('.', pos)), 10);
}
return false;
}; | Returns Internet Explorer version number (or false if no Internet Explorer used).
@param string agent Optional parameter to specify user agent | getIEVersion ( agent ) | javascript | c3js/c3 | c3.js | https://github.com/c3js/c3/blob/master/c3.js | MIT |
var isIE = function (version) {
var ver = getIEVersion();
if (typeof version === 'undefined') {
return !!ver;
}
return version === ver;
}; | Returns whether the used browser is Internet Explorer.
@param version Optional parameter to specify IE version | isIE ( version ) | javascript | c3js/c3 | c3.js | https://github.com/c3js/c3/blob/master/c3.js | MIT |
ChartInternal.prototype.bindResize = function () {
var $$ = this, config = $$.config;
$$.resizeFunction = $$.generateResize(); // need to call .remove
$$.resizeFunction.add(function () {
config.onresize.call($$);
});
if (config.resize_auto) {
$$.resizeFunction.add(function () {
if ($$.resizeTimeout !== undefined) {
window.clearTimeout($$.resizeTimeout);
}
$$.resizeTimeout = window.setTimeout(function () {
delete $$.resizeTimeout;
$$.updateAndRedraw({
withUpdateXDomain: false,
withUpdateOrgXDomain: false,
withTransition: false,
withTransitionForTransform: false,
withLegend: true
});
if ($$.brush) {
$$.brush.update();
}
}, 100);
});
}
$$.resizeFunction.add(function () {
config.onresized.call($$);
});
$$.resizeIfElementDisplayed = function () {
// if element not displayed skip it
if ($$.api == null || !$$.api.element.offsetParent) {
return;
}
$$.resizeFunction();
};
window.addEventListener('resize', $$.resizeIfElementDisplayed, false);
}; | Binds handlers to the window resize event. | ChartInternal.prototype.bindResize ( ) | javascript | c3js/c3 | c3.js | https://github.com/c3js/c3/blob/master/c3.js | MIT |
ChartInternal.prototype.bindWindowFocus = function () {
var _this = this;
if (this.windowFocusHandler) {
// The handler is already set
return;
}
this.windowFocusHandler = function () {
_this.redraw();
};
window.addEventListener('focus', this.windowFocusHandler);
}; | Binds handlers to the window focus event. | ChartInternal.prototype.bindWindowFocus ( ) | javascript | c3js/c3 | c3.js | https://github.com/c3js/c3/blob/master/c3.js | MIT |
ChartInternal.prototype.unbindWindowFocus = function () {
window.removeEventListener('focus', this.windowFocusHandler);
delete this.windowFocusHandler;
}; | Unbinds from the window focus event. | ChartInternal.prototype.unbindWindowFocus ( ) | javascript | c3js/c3 | c3.js | https://github.com/c3js/c3/blob/master/c3.js | MIT |
Chart.prototype.data.values = function (targetId, flat) {
if (flat === void 0) { flat = true; }
var values = null;
if (targetId) {
var targets = this.data(targetId);
if (targets && isArray(targets)) {
values = targets.reduce(function (ret, v) {
var dataValue = v.values.map(function (d) { return d.value; });
if (flat) {
ret = ret.concat(dataValue);
}
else {
ret.push(dataValue);
}
return ret;
}, []);
}
}
return values;
}; | Get values of the data loaded in the chart.
@param {String|Array} targetId This API returns the value of specified target.
@param flat
@return {Array} Data values | Chart.prototype.data.values ( targetId , flat ) | javascript | c3js/c3 | c3.js | https://github.com/c3js/c3/blob/master/c3.js | MIT |
ChartInternal.prototype.getArcRatio = function (d) {
return this.getRatio('arc', d);
}; | @deprecated Use `getRatio('arc', d)` instead. | ChartInternal.prototype.getArcRatio ( d ) | javascript | c3js/c3 | c3.js | https://github.com/c3js/c3/blob/master/c3.js | MIT |
ChartInternal.prototype.addToCache = function (key, value) {
this.cache["$" + key] = value;
}; | Store value into cache
@param key
@param value | ChartInternal.prototype.addToCache ( key , value ) | javascript | c3js/c3 | c3.js | https://github.com/c3js/c3/blob/master/c3.js | MIT |
ChartInternal.prototype.getFromCache = function (key) {
return this.cache["$" + key];
}; | Returns a cached value or undefined
@param key
@return {*} | ChartInternal.prototype.getFromCache ( key ) | javascript | c3js/c3 | c3.js | https://github.com/c3js/c3/blob/master/c3.js | MIT |
ChartInternal.prototype.filterByIndex = function (targets, index) { | Returns all the values from the given targets at the given index.
@param {Array} targets
@param {Number} index
@return {Array} | (anonymous) ( v ) | javascript | c3js/c3 | c3.js | https://github.com/c3js/c3/blob/master/c3.js | MIT |
var isIE = function(version) {
const ver = getIEVersion();
if (typeof version === 'undefined') {
return !!ver
}
return version === ver
}; | Returns whether the used browser is Internet Explorer.
@param {Number} version Optional parameter to specify IE version | isIE ( version ) | javascript | c3js/c3 | c3.esm.js | https://github.com/c3js/c3/blob/master/c3.esm.js | MIT |
function shuffle (array) {
return array.sort(() => Math.random() - 0.5)
} | Very basic, non-optimal shuffle function to randomly order the items.
@param {any[]} array
@returns {any[]} | shuffle ( array ) | javascript | supercharge/promise-pool | examples/promise-pool.js | https://github.com/supercharge/promise-pool/blob/master/examples/promise-pool.js | MIT |
module.exports = (options) => apm(options) | New Relic APM custom instrumentation
Supported features:
- route names | module.exports | javascript | BackendStack21/restana | libs/newrelic-apm.js | https://github.com/BackendStack21/restana/blob/master/libs/newrelic-apm.js | MIT |
(function () {
if (typeof $ === 'undefined') {
throw new TypeError('Bootstrap\'s JavaScript requires jQuery. jQuery must be included before Bootstrap\'s JavaScript.');
}
var version = $.fn.jquery.split(' ')[0].split('.');
var minMajor = 1;
var ltMajor = 2;
var minMinor = 9;
var minPatch = 1;
var maxMajor = 4;
if (version[0] < ltMajor && version[1] < minMinor || version[0] === minMajor && version[1] === minMinor && version[2] < minPatch || version[0] >= maxMajor) {
throw new Error('Bootstrap\'s JavaScript requires at least jQuery v1.9.1 but less than v4.0.0');
} | --------------------------------------------------------------------------
Bootstrap (v4.3.1): index.js
Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
-------------------------------------------------------------------------- | (anonymous) ( ) | javascript | Xabaril/Esquio | demos/WebApp/wwwroot/lib/twitter-bootstrap/js/bootstrap.js | https://github.com/Xabaril/Esquio/blob/master/demos/WebApp/wwwroot/lib/twitter-bootstrap/js/bootstrap.js | Apache-2.0 |
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
} | Create key-value caches of limited size
@returns {function(string, object)} Returns the Object data after storing it on itself with
property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
deleting the oldest entry | createCache ( ) | javascript | Xabaril/Esquio | demos/WebApp/wwwroot/lib/jquery/jquery.js | https://github.com/Xabaril/Esquio/blob/master/demos/WebApp/wwwroot/lib/jquery/jquery.js | Apache-2.0 |
function assert( fn ) {
var el = document.createElement("fieldset");
try {
return !!fn( el );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( el.parentNode ) {
el.parentNode.removeChild( el );
}
// release memory in IE
el = null;
}
} | Support testing using an element
@param {Function} fn Passed the created element and returns a boolean result | assert ( fn ) | javascript | Xabaril/Esquio | demos/WebApp/wwwroot/lib/jquery/jquery.js | https://github.com/Xabaril/Esquio/blob/master/demos/WebApp/wwwroot/lib/jquery/jquery.js | Apache-2.0 |
function createDisabledPseudo( disabled ) {
// Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
return function( elem ) {
// Only certain elements can match :enabled or :disabled
// https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
// https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
if ( "form" in elem ) {
// Check for inherited disabledness on relevant non-disabled elements:
// * listed form-associated elements in a disabled fieldset
// https://html.spec.whatwg.org/multipage/forms.html#category-listed
// https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
// * option elements in a disabled optgroup
// https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
// All such elements have a "form" property.
if ( elem.parentNode && elem.disabled === false ) {
// Option elements defer to a parent optgroup if present
if ( "label" in elem ) {
if ( "label" in elem.parentNode ) {
return elem.parentNode.disabled === disabled;
} else {
return elem.disabled === disabled;
}
}
// Support: IE 6 - 11
// Use the isDisabled shortcut property to check for disabled fieldset ancestors
return elem.isDisabled === disabled ||
// Where there is no isDisabled, check manually
/* jshint -W018 */
elem.isDisabled !== !disabled &&
inDisabledFieldset( elem ) === disabled;
}
return elem.disabled === disabled;
// Try to winnow out elements that can't be disabled before trusting the disabled property.
// Some victims get caught in our net (label, legend, menu, track), but it shouldn't
// even exist on them, let alone have a boolean value.
} else if ( "label" in elem ) {
return elem.disabled === disabled;
}
// Remaining elements are neither :enabled nor :disabled
return false;
};
} | Returns a function to use in pseudos for :enabled/:disabled
@param {Boolean} disabled true for :disabled; false for :enabled | createDisabledPseudo ( disabled ) | javascript | Xabaril/Esquio | demos/WebApp/wwwroot/lib/jquery/jquery.js | https://github.com/Xabaril/Esquio/blob/master/demos/WebApp/wwwroot/lib/jquery/jquery.js | Apache-2.0 |
isXML = Sizzle.isXML = function( elem ) {
var namespace = elem.namespaceURI,
docElem = (elem.ownerDocument || elem).documentElement;
// Support: IE <=8
// Assume HTML when documentElement doesn't yet exist, such as inside loading iframes
// https://bugs.jquery.com/ticket/4833
return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" );
}; | Detects XML nodes
@param {Element|Object} elem An element or a document
@returns {Boolean} True iff elem is a non-HTML XML node | Sizzle.isXML ( elem ) | javascript | Xabaril/Esquio | demos/WebApp/wwwroot/lib/jquery/jquery.js | https://github.com/Xabaril/Esquio/blob/master/demos/WebApp/wwwroot/lib/jquery/jquery.js | Apache-2.0 |
$.validator.addMethod( "bic", function( value, element ) {
return this.optional( element ) || /^([A-Z]{6}[A-Z2-9][A-NP-Z1-9])(X{3}|[A-WY-Z0-9][A-Z0-9]{2})?$/.test( value.toUpperCase() );
}, "Please specify a valid BIC code" ); | BIC is the business identifier code (ISO 9362). This BIC check is not a guarantee for authenticity.
BIC pattern: BBBBCCLLbbb (8 or 11 characters long; bbb is optional)
Validation is case-insensitive. Please make sure to normalize input yourself.
BIC definition in detail:
- First 4 characters - bank code (only letters)
- Next 2 characters - ISO 3166-1 alpha-2 country code (only letters)
- Next 2 characters - location code (letters and digits)
a. shall not start with '0' or '1'
b. second character must be a letter ('O' is not allowed) or digit ('0' for test (therefore not allowed), '1' denoting passive participant, '2' typically reverse-billing)
- Last 3 characters - branch code, optional (shall not start with 'X' except in case of 'XXX' for primary office) (letters and digits) | (anonymous) ( value , element ) | javascript | Xabaril/Esquio | samples/GettingStarted.AspNetCore.Toggles/wwwroot/lib/jquery-validation/dist/additional-methods.js | https://github.com/Xabaril/Esquio/blob/master/samples/GettingStarted.AspNetCore.Toggles/wwwroot/lib/jquery-validation/dist/additional-methods.js | Apache-2.0 |
$(document).on(DateTimePicker.Event.CLICK_DATA_API, DateTimePicker.Selector.DATA_TOGGLE, function () {
var $target = getSelectorFromElement($(this));
if ($target.length === 0) {
return;
}
TempusDominusBootstrap4._jQueryInterface.call($target, 'toggle');
}).on(DateTimePicker.Event.CHANGE, '.' + DateTimePicker.ClassName.INPUT, function (event) { | ------------------------------------------------------------------------
jQuery
------------------------------------------------------------------------ | (anonymous) ( ) | javascript | Xabaril/Esquio | src/Esquio.UI.Client/wwwroot/plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.js | https://github.com/Xabaril/Esquio/blob/master/src/Esquio.UI.Client/wwwroot/plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.js | Apache-2.0 |
init: function (is_update) {
this.no_diapason = false;
this.coords.p_step = this.convertToPercent(this.options.step, true);
this.target = "base";
this.toggleInput();
this.append();
this.setMinMax();
if (is_update) {
this.force_redraw = true;
this.calc(true);
// callbacks called
this.callOnUpdate();
} else {
this.force_redraw = true;
this.calc(true);
// callbacks called
this.callOnStart();
}
this.updateScene();
}, | Starts or updates the plugin instance
@param [is_update] {boolean} | init ( is_update ) | javascript | Xabaril/Esquio | src/Esquio.UI.Client/wwwroot/plugins/ion-rangeslider/js/ion.rangeSlider.js | https://github.com/Xabaril/Esquio/blob/master/src/Esquio.UI.Client/wwwroot/plugins/ion-rangeslider/js/ion.rangeSlider.js | Apache-2.0 |
setTopHandler: function () {
var min = this.options.min,
max = this.options.max,
from = this.options.from,
to = this.options.to;
if (from > min && to === max) {
this.$cache.s_from.addClass("type_last");
} else if (to < max) {
this.$cache.s_to.addClass("type_last");
}
}, | Determine which handler has a priority
works only for double slider type | setTopHandler ( ) | javascript | Xabaril/Esquio | src/Esquio.UI.Client/wwwroot/plugins/ion-rangeslider/js/ion.rangeSlider.js | https://github.com/Xabaril/Esquio/blob/master/src/Esquio.UI.Client/wwwroot/plugins/ion-rangeslider/js/ion.rangeSlider.js | Apache-2.0 |
changeLevel: function (target) {
switch (target) {
case "single":
this.coords.p_gap = this.toFixed(this.coords.p_pointer - this.coords.p_single_fake);
this.$cache.s_single.addClass("state_hover");
break;
case "from":
this.coords.p_gap = this.toFixed(this.coords.p_pointer - this.coords.p_from_fake);
this.$cache.s_from.addClass("state_hover");
this.$cache.s_from.addClass("type_last");
this.$cache.s_to.removeClass("type_last");
break;
case "to":
this.coords.p_gap = this.toFixed(this.coords.p_pointer - this.coords.p_to_fake);
this.$cache.s_to.addClass("state_hover");
this.$cache.s_to.addClass("type_last");
this.$cache.s_from.removeClass("type_last");
break;
case "both":
this.coords.p_gap_left = this.toFixed(this.coords.p_pointer - this.coords.p_from_fake);
this.coords.p_gap_right = this.toFixed(this.coords.p_to_fake - this.coords.p_pointer);
this.$cache.s_to.removeClass("type_last");
this.$cache.s_from.removeClass("type_last");
break;
}
}, | Determine which handles was clicked last
and which handler should have hover effect
@param target {String} | changeLevel ( target ) | javascript | Xabaril/Esquio | src/Esquio.UI.Client/wwwroot/plugins/ion-rangeslider/js/ion.rangeSlider.js | https://github.com/Xabaril/Esquio/blob/master/src/Esquio.UI.Client/wwwroot/plugins/ion-rangeslider/js/ion.rangeSlider.js | Apache-2.0 |
appendDisableMask: function () {
this.$cache.cont.append(disable_html);
this.$cache.cont.addClass("irs-disabled");
}, | Then slider is disabled
appends extra layer with opacity | appendDisableMask ( ) | javascript | Xabaril/Esquio | src/Esquio.UI.Client/wwwroot/plugins/ion-rangeslider/js/ion.rangeSlider.js | https://github.com/Xabaril/Esquio/blob/master/src/Esquio.UI.Client/wwwroot/plugins/ion-rangeslider/js/ion.rangeSlider.js | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.