code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function render_tree( jsonml ) { // basic case if ( typeof jsonml === "string" ) { return escapeHTML( jsonml ); } var tag = jsonml.shift(), attributes = {}, content = []; if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) { attributes = jsonml.shift(); } while ( jsonml.length ) { content.push( render_tree( jsonml.shift() ) ); } var tag_attrs = ""; for ( var a in attributes ) { tag_attrs += " " + a + '="' + escapeHTML( attributes[ a ] ) + '"'; } // be careful about adding whitespace here for inline elements if ( tag == "img" || tag == "br" || tag == "hr" ) { return "<"+ tag + tag_attrs + "/>"; } else { return "<"+ tag + tag_attrs + ">" + content.join( "" ) + "</" + tag + ">"; } }
renderJsonML( jsonml[, options] ) -> String - jsonml (Array): JsonML array to render to XML - options (Object): options Converts the given JsonML into well-formed XML. The options currently understood are: - root (Boolean): wether or not the root node should be included in the output, or just its children. The default `false` is to not include the root itself.
render_tree
javascript
CartoDB/cartodb
vendor/assets/javascripts/markdown.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/markdown.js
BSD-3-Clause
function convert_tree_to_html( tree, references, options ) { var i; options = options || {}; // shallow clone var jsonml = tree.slice( 0 ); if ( typeof options.preprocessTreeNode === "function" ) { jsonml = options.preprocessTreeNode(jsonml, references); } // Clone attributes if they exist var attrs = extract_attr( jsonml ); if ( attrs ) { jsonml[ 1 ] = {}; for ( i in attrs ) { jsonml[ 1 ][ i ] = attrs[ i ]; } attrs = jsonml[ 1 ]; } // basic case if ( typeof jsonml === "string" ) { return jsonml; } // convert this node switch ( jsonml[ 0 ] ) { case "header": jsonml[ 0 ] = "h" + jsonml[ 1 ].level; delete jsonml[ 1 ].level; break; case "bulletlist": jsonml[ 0 ] = "ul"; break; case "numberlist": jsonml[ 0 ] = "ol"; break; case "listitem": jsonml[ 0 ] = "li"; break; case "para": jsonml[ 0 ] = "p"; break; case "markdown": jsonml[ 0 ] = "html"; if ( attrs ) delete attrs.references; break; case "code_block": jsonml[ 0 ] = "pre"; i = attrs ? 2 : 1; var code = [ "code" ]; code.push.apply( code, jsonml.splice( i, jsonml.length - i ) ); jsonml[ i ] = code; break; case "inlinecode": jsonml[ 0 ] = "code"; break; case "img": jsonml[ 1 ].src = jsonml[ 1 ].href; delete jsonml[ 1 ].href; break; case "linebreak": jsonml[ 0 ] = "br"; break; case "link": jsonml[ 0 ] = "a"; break; case "link_ref": jsonml[ 0 ] = "a"; // grab this ref and clean up the attribute node var ref = references[ attrs.ref ]; // if the reference exists, make the link if ( ref ) { delete attrs.ref; // add in the href and title, if present attrs.href = ref.href; if ( ref.title ) { attrs.title = ref.title; } // get rid of the unneeded original text delete attrs.original; } // the reference doesn't exist, so revert to plain text else { return attrs.original; } break; case "img_ref": jsonml[ 0 ] = "img"; // grab this ref and clean up the attribute node var ref = references[ attrs.ref ]; // if the reference exists, make the link if ( ref ) { delete attrs.ref; // add in the href and title, if present attrs.src = ref.href; if ( ref.title ) { attrs.title = ref.title; } // get rid of the unneeded original text delete attrs.original; } // the reference doesn't exist, so revert to plain text else { return attrs.original; } break; } // convert all the children i = 1; // deal with the attribute node, if it exists if ( attrs ) { // if there are keys, skip over it for ( var key in jsonml[ 1 ] ) { i = 2; break; } // if there aren't, remove it if ( i === 1 ) { jsonml.splice( i, 1 ); } } for ( ; i < jsonml.length; ++i ) { jsonml[ i ] = convert_tree_to_html( jsonml[ i ], references, options ); } return jsonml; }
renderJsonML( jsonml[, options] ) -> String - jsonml (Array): JsonML array to render to XML - options (Object): options Converts the given JsonML into well-formed XML. The options currently understood are: - root (Boolean): wether or not the root node should be included in the output, or just its children. The default `false` is to not include the root itself.
convert_tree_to_html
javascript
CartoDB/cartodb
vendor/assets/javascripts/markdown.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/markdown.js
BSD-3-Clause
function merge_text_nodes( jsonml ) { // skip the tag name and attribute hash var i = extract_attr( jsonml ) ? 2 : 1; while ( i < jsonml.length ) { // if it's a string check the next item too if ( typeof jsonml[ i ] === "string" ) { if ( i + 1 < jsonml.length && typeof jsonml[ i + 1 ] === "string" ) { // merge the second string into the first and remove it jsonml[ i ] += jsonml.splice( i + 1, 1 )[ 0 ]; } else { ++i; } } // if it's not a string recurse else { merge_text_nodes( jsonml[ i ] ); ++i; } } }
renderJsonML( jsonml[, options] ) -> String - jsonml (Array): JsonML array to render to XML - options (Object): options Converts the given JsonML into well-formed XML. The options currently understood are: - root (Boolean): wether or not the root node should be included in the output, or just its children. The default `false` is to not include the root itself.
merge_text_nodes
javascript
CartoDB/cartodb
vendor/assets/javascripts/markdown.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/markdown.js
BSD-3-Clause
function equal(a, b) { if (a === b) return true; if (a === undefined || b === undefined) return false; if (a === null || b === null) return false; if (a.constructor === String) return a.localeCompare(b) === 0; if (b.constructor === String) return b.localeCompare(a) === 0; return false; }
Compares equality of a and b taking into account that a and b may be strings, in which case localeCompare is used @param a @param b
equal
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function splitVal(string, separator) { var val, i, l; if (string === null || string.length < 1) return []; val = string.split(separator); for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]); return val; }
Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty strings @param string @param separator
splitVal
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function getSideBorderPadding(element) { return element.outerWidth(false) - element.width(); }
Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty strings @param string @param separator
getSideBorderPadding
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function installKeyUpChangeEvent(element) { var key="keyup-change-value"; element.bind("keydown", function () { if ($.data(element, key) === undefined) { $.data(element, key, element.val()); } }); element.bind("keyup", function () { var val= $.data(element, key); if (val !== undefined && element.val() !== val) { $.removeData(element, key); element.trigger("keyup-change"); } }); }
Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty strings @param string @param separator
installKeyUpChangeEvent
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function installFilteredMouseMove(element) { element.bind("mousemove", function (e) { var lastpos = lastMousePosition; if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) { $(e.target).trigger("mousemove-filtered", e); } }); }
filters mouse events so an event is fired only if the mouse moved. filters out mouse events that occur when mouse is stationary but the elements under the pointer are scrolled.
installFilteredMouseMove
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function debounce(quietMillis, fn, ctx) { ctx = ctx || undefined; var timeout; return function () { var args = arguments; window.clearTimeout(timeout); timeout = window.setTimeout(function() { fn.apply(ctx, args); }, quietMillis); }; }
Debounces a function. Returns a function that calls the original fn function only if no invocations have been made within the last quietMillis milliseconds. @param quietMillis number of milliseconds to wait before invoking fn @param fn function to be debounced @param ctx object to be used as this reference within fn @return debounced version of fn
debounce
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function thunk(formula) { var evaluated = false, value; return function() { if (evaluated === false) { value = formula(); evaluated = true; } return value; }; }
A simple implementation of a thunk @param formula function used to lazily initialize the thunk @return {Function}
thunk
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function installDebouncedScroll(threshold, element) { var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);}); element.bind("scroll", function (e) { if (indexOf(e.target, element.get()) >= 0) notify(e); }); }
A simple implementation of a thunk @param formula function used to lazily initialize the thunk @return {Function}
installDebouncedScroll
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function killEvent(event) { event.preventDefault(); event.stopPropagation(); }
A simple implementation of a thunk @param formula function used to lazily initialize the thunk @return {Function}
killEvent
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function killEventImmediately(event) { event.preventDefault(); event.stopImmediatePropagation(); }
A simple implementation of a thunk @param formula function used to lazily initialize the thunk @return {Function}
killEventImmediately
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function measureTextWidth(e) { if (!sizer){ var style = e[0].currentStyle || window.getComputedStyle(e[0], null); sizer = $("<div></div>").css({ position: "absolute", left: "-10000px", top: "-10000px", display: "none", fontSize: style.fontSize, fontFamily: style.fontFamily, fontStyle: style.fontStyle, fontWeight: style.fontWeight, letterSpacing: style.letterSpacing, textTransform: style.textTransform, whiteSpace: "nowrap" }); $("body").append(sizer); } sizer.text(e.val()); return sizer.width(); }
A simple implementation of a thunk @param formula function used to lazily initialize the thunk @return {Function}
measureTextWidth
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function markMatch(text, term, markup) { var match=text.toUpperCase().indexOf(term.toUpperCase()), tl=term.length; if (match<0) { markup.push(text); return; } markup.push(text.substring(0, match)); markup.push("<span class='select2-match'>"); markup.push(text.substring(match, match + tl)); markup.push("</span>"); markup.push(text.substring(match + tl, text.length)); }
A simple implementation of a thunk @param formula function used to lazily initialize the thunk @return {Function}
markMatch
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function ajax(options) { var timeout, // current scheduled but not yet executed request requestSequence = 0, // sequence used to drop out-of-order responses handler = null, quietMillis = options.quietMillis || 100; return function (query) { window.clearTimeout(timeout); timeout = window.setTimeout(function () { requestSequence += 1; // increment the sequence var requestNumber = requestSequence, // this request's sequence number data = options.data, // ajax data function transport = options.transport || $.ajax, traditional = options.traditional || false, type = options.type || 'GET'; // set type of request (GET or POST) data = data.call(this, query.term, query.page, query.context); if( null !== handler) { handler.abort(); } handler = transport.call(null, { url: options.url, dataType: options.dataType, data: data, type: type, traditional: traditional, success: function (data) { if (requestNumber < requestSequence) { return; } // TODO 3.0 - replace query.page with query so users have access to term, page, etc. var results = options.results(data, query.page); query.callback(results); } }); }, quietMillis); }; }
Produces an ajax-based query function @param options object containing configuration paramters @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax @param options.url url for the data @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url. @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified @param options.traditional a boolean flag that should be true if you wish to use the traditional style of param serialization for the ajax request @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2. The expected format is an object containing the following keys: results array of objects that will be used as choices more (optional) boolean indicating whether there are more results available Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
ajax
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function local(options) { var data = options, // data elements dataText, text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search if (!$.isArray(data)) { text = data.text; // if text is not a function we assume it to be a key name if (!$.isFunction(text)) { dataText = data.text; // we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available text = function (item) { return item[dataText]; }; } data = data.results; } return function (query) { var t = query.term, filtered = { results: [] }, process; if (t === "") { query.callback({results: data}); return; } process = function(datum, collection) { var group, attr; datum = datum[0]; if (datum.children) { group = {}; for (attr in datum) { if (datum.hasOwnProperty(attr)) group[attr]=datum[attr]; } group.children=[]; $(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); }); if (group.children.length || query.matcher(t, text(group))) { collection.push(group); } } else { if (query.matcher(t, text(datum))) { collection.push(datum); } } }; $(data).each2(function(i, datum) { process(datum, filtered.results); }); query.callback(filtered); }; }
Produces a query function that works with a local array @param options object containing configuration parameters. The options parameter can either be an array or an object. If the array form is used it is assumed that it contains objects with 'id' and 'text' keys. If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text' key can either be a String in which case it is expected that each element in the 'data' array has a key with the value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract the text.
local
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function tags(data) { // TODO even for a function we should probably return a wrapper that does the same object/string check as // the function for arrays. otherwise only functions that return objects are supported. if ($.isFunction(data)) { return data; } // if not a function we assume it to be an array return function (query) { var t = query.term, filtered = {results: []}; $(data).each(function () { var isObject = this.text !== undefined, text = isObject ? this.text : this; if (t === "" || query.matcher(t, text)) { filtered.results.push(isObject ? this : {id: this, text: this}); } }); query.callback(filtered); }; }
Produces a query function that works with a local array @param options object containing configuration parameters. The options parameter can either be an array or an object. If the array form is used it is assumed that it contains objects with 'id' and 'text' keys. If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text' key can either be a String in which case it is expected that each element in the 'data' array has a key with the value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract the text.
tags
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function checkFormatter(formatter, formatterName) { if ($.isFunction(formatter)) return true; if (!formatter) return false; throw new Error("formatterName must be a function or a falsy value"); }
Checks if the formatter function should be used. Throws an error if it is not a function. Returns true if it should be used, false if no formatting should be performed. @param formatter
checkFormatter
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function evaluate(val) { return $.isFunction(val) ? val() : val; }
Checks if the formatter function should be used. Throws an error if it is not a function. Returns true if it should be used, false if no formatting should be performed. @param formatter
evaluate
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function countResults(results) { var count = 0; $.each(results, function(i, item) { if (item.children) { count += countResults(item.children); } else { count++; } }); return count; }
Checks if the formatter function should be used. Throws an error if it is not a function. Returns true if it should be used, false if no formatting should be performed. @param formatter
countResults
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function defaultTokenizer(input, selection, selectCallback, opts) { var original = input, // store the original so we can compare and know if we need to tell the search to update its text dupe = false, // check for whether a token we extracted represents a duplicate selected choice token, // token index, // position at which the separator was found i, l, // looping variables separator; // the matched separator if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined; while (true) { index = -1; for (i = 0, l = opts.tokenSeparators.length; i < l; i++) { separator = opts.tokenSeparators[i]; index = input.indexOf(separator); if (index >= 0) break; } if (index < 0) break; // did not find any token separator in the input string, bail token = input.substring(0, index); input = input.substring(index + separator.length); if (token.length > 0) { token = opts.createSearchChoice(token, selection); if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) { dupe = false; for (i = 0, l = selection.length; i < l; i++) { if (equal(opts.id(token), opts.id(selection[i]))) { dupe = true; break; } } if (!dupe) selectCallback(token); } } } if (original.localeCompare(input) != 0) return input; }
Default tokenizer. This function uses breaks the input on substring match of any string from the opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those two options have to be defined in order for the tokenizer to work. @param input text user has typed so far or pasted into the search field @param selection currently selected choices @param selectCallback function(choice) callback tho add the choice to selection @param opts select2's opts @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value
defaultTokenizer
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function clazz(SuperClass, methods) { var constructor = function () {}; constructor.prototype = new SuperClass; constructor.prototype.constructor = constructor; constructor.prototype.parent = SuperClass.prototype; constructor.prototype = $.extend(constructor.prototype, methods); return constructor; }
Creates a new class @param superClass @param methods
clazz
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function removeTipsys() { results.find('.select2-result').each(function(i,el){ var $el = $(el); var tipsy = $el.data('tipsy'); if (tipsy) { $el .tipsy('hide') .unbind('mouseleave mouseenter'); } }) }
@param initial whether or not this is the call to this method right after the dropdown has been opened
removeTipsys
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function postRender() { results.scrollTop(0); search.removeClass("select2-active"); self.positionDropdown(); }
@param initial whether or not this is the call to this method right after the dropdown has been opened
postRender
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function render(html) { results.html(self.opts.escapeMarkup(html)); postRender(); }
@param initial whether or not this is the call to this method right after the dropdown has been opened
render
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function resolveContainerWidth() { var style, attrs, matches, i, l; if (this.opts.width === "off") { return null; } else if (this.opts.width === "element"){ return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px'; } else if (this.opts.width === "copy" || this.opts.width === "resolve") { // check if there is inline style on the element that contains width style = this.opts.element.attr('style'); if (style !== undefined) { attrs = style.split(';'); for (i = 0, l = attrs.length; i < l; i = i + 1) { matches = attrs[i].replace(/\s/g, '') .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/); if (matches !== null && matches.length >= 1) return matches[1]; } } if (this.opts.width === "resolve") { // next check if css('width') can resolve a width that is percent based, this is sometimes possible // when attached to input type=hidden or elements hidden via css style = this.opts.element.css('width'); if (style.indexOf("%") > 0) return style; // finally, fallback on the calculated width of the element return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px'); } return null; } else if ($.isFunction(this.opts.width)) { return this.opts.width(); } else { return this.opts.width; } }
Get the desired width for the container element. This is derived first from option `width` passed to select2, then the inline 'style' on the original element, and finally falls back to the jQuery calculated element width.
resolveContainerWidth
javascript
CartoDB/cartodb
vendor/assets/javascripts/select2.min.js
https://github.com/CartoDB/cartodb/blob/master/vendor/assets/javascripts/select2.min.js
BSD-3-Clause
function encode(s) { // Calculate result length and allocate output array. // encodedLength() also validates string and throws errors, // so we don't need repeat validation here. var arr = new Uint8Array(encodedLength(s)); var pos = 0; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i); if (c < 0x80) { arr[pos++] = c; } else if (c < 0x800) { arr[pos++] = 0xc0 | c >> 6; arr[pos++] = 0x80 | c & 0x3f; } else if (c < 0xd800) { arr[pos++] = 0xe0 | c >> 12; arr[pos++] = 0x80 | (c >> 6) & 0x3f; arr[pos++] = 0x80 | c & 0x3f; } else { i++; // get one more character c = (c & 0x3ff) << 10; c |= s.charCodeAt(i) & 0x3ff; c += 0x10000; arr[pos++] = 0xf0 | c >> 18; arr[pos++] = 0x80 | (c >> 12) & 0x3f; arr[pos++] = 0x80 | (c >> 6) & 0x3f; arr[pos++] = 0x80 | c & 0x3f; } } return arr; }
Encodes the given string into UTF-8 byte array. Throws if the source string has invalid UTF-16 encoding.
encode
javascript
pusher/pusher-js
dist/node/pusher.js
https://github.com/pusher/pusher-js/blob/master/dist/node/pusher.js
MIT
function encodedLength(s) { var result = 0; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i); if (c < 0x80) { result += 1; } else if (c < 0x800) { result += 2; } else if (c < 0xd800) { result += 3; } else if (c <= 0xdfff) { if (i >= s.length - 1) { throw new Error(INVALID_UTF16); } i++; // "eat" next character result += 4; } else { throw new Error(INVALID_UTF16); } } return result; }
Returns the number of bytes required to encode the given string into UTF-8. Throws if the source string has invalid UTF-16 encoding.
encodedLength
javascript
pusher/pusher-js
dist/node/pusher.js
https://github.com/pusher/pusher-js/blob/master/dist/node/pusher.js
MIT
function decode(arr) { var chars = []; for (var i = 0; i < arr.length; i++) { var b = arr[i]; if (b & 0x80) { var min = void 0; if (b < 0xe0) { // Need 1 more byte. if (i >= arr.length) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; if ((n1 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x1f) << 6 | (n1 & 0x3f); min = 0x80; } else if (b < 0xf0) { // Need 2 more bytes. if (i >= arr.length - 1) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; var n2 = arr[++i]; if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x0f) << 12 | (n1 & 0x3f) << 6 | (n2 & 0x3f); min = 0x800; } else if (b < 0xf8) { // Need 3 more bytes. if (i >= arr.length - 2) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; var n2 = arr[++i]; var n3 = arr[++i]; if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80 || (n3 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x0f) << 18 | (n1 & 0x3f) << 12 | (n2 & 0x3f) << 6 | (n3 & 0x3f); min = 0x10000; } else { throw new Error(INVALID_UTF8); } if (b < min || (b >= 0xd800 && b <= 0xdfff)) { throw new Error(INVALID_UTF8); } if (b >= 0x10000) { // Surrogate pair. if (b > 0x10ffff) { throw new Error(INVALID_UTF8); } b -= 0x10000; chars.push(String.fromCharCode(0xd800 | (b >> 10))); b = 0xdc00 | (b & 0x3ff); } } chars.push(String.fromCharCode(b)); } return chars.join(""); }
Decodes the given byte array from UTF-8 into a string. Throws if encoding is invalid.
decode
javascript
pusher/pusher-js
dist/node/pusher.js
https://github.com/pusher/pusher-js/blob/master/dist/node/pusher.js
MIT
isAllowedHttpHeader = function(header) { return disableHeaderCheck || (header && forbiddenRequestHeaders.indexOf(header.toLowerCase()) === -1); }
Check if the specified header is allowed. @param string header Header to validate @return boolean False if not allowed, otherwise true
isAllowedHttpHeader
javascript
pusher/pusher-js
dist/node/pusher.js
https://github.com/pusher/pusher-js/blob/master/dist/node/pusher.js
MIT
isAllowedHttpMethod = function(method) { return (method && forbiddenRequestMethods.indexOf(method) === -1); }
Check if the specified method is allowed. @param string method Request method to validate @return boolean False if not allowed, otherwise true
isAllowedHttpMethod
javascript
pusher/pusher-js
dist/node/pusher.js
https://github.com/pusher/pusher-js/blob/master/dist/node/pusher.js
MIT
responseHandler = function responseHandler(resp) { // Set response var to the response we got back // This is so it remains accessable outside this scope response = resp; // Check for redirect // @TODO Prevent looped redirects if (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) { // Change URL to the redirect location settings.url = response.headers.location; var url = Url.parse(settings.url); // Set host var in case it's used later host = url.hostname; // Options for the new request var newOptions = { hostname: url.hostname, port: url.port, path: url.path, method: response.statusCode === 303 ? "GET" : settings.method, headers: headers, withCredentials: self.withCredentials }; // Issue the new request request = doRequest(newOptions, responseHandler).on("error", errorHandler); request.end(); // @TODO Check if an XHR event needs to be fired here return; } response.setEncoding("utf8"); setState(self.HEADERS_RECEIVED); self.status = response.statusCode; response.on("data", function(chunk) { // Make sure there's some data if (chunk) { self.responseText += chunk; } // Don't emit state changes if the connection has been aborted. if (sendFlag) { setState(self.LOADING); } }); response.on("end", function() { if (sendFlag) { // Discard the end event if the connection has been aborted setState(self.DONE); sendFlag = false; } }); response.on("error", function(error) { self.handleError(error); }); }
Sends the request to the server. @param string data Optional data to send as request body.
responseHandler
javascript
pusher/pusher-js
dist/node/pusher.js
https://github.com/pusher/pusher-js/blob/master/dist/node/pusher.js
MIT
setState = function(state) { if (state == self.LOADING || self.readyState !== state) { self.readyState = state; if (settings.async || self.readyState < self.OPENED || self.readyState === self.DONE) { self.dispatchEvent("readystatechange"); } if (self.readyState === self.DONE && !errorFlag) { self.dispatchEvent("load"); // @TODO figure out InspectorInstrumentation::didLoadXHR(cookie) self.dispatchEvent("loadend"); } } }
Changes readyState and calls onreadystatechange. @param int state New state
setState
javascript
pusher/pusher-js
dist/node/pusher.js
https://github.com/pusher/pusher-js/blob/master/dist/node/pusher.js
MIT
function encode(s) { // Calculate result length and allocate output array. // encodedLength() also validates string and throws errors, // so we don't need repeat validation here. var arr = new Uint8Array(encodedLength(s)); var pos = 0; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i); if (c < 0x80) { arr[pos++] = c; } else if (c < 0x800) { arr[pos++] = 0xc0 | c >> 6; arr[pos++] = 0x80 | c & 0x3f; } else if (c < 0xd800) { arr[pos++] = 0xe0 | c >> 12; arr[pos++] = 0x80 | (c >> 6) & 0x3f; arr[pos++] = 0x80 | c & 0x3f; } else { i++; // get one more character c = (c & 0x3ff) << 10; c |= s.charCodeAt(i) & 0x3ff; c += 0x10000; arr[pos++] = 0xf0 | c >> 18; arr[pos++] = 0x80 | (c >> 12) & 0x3f; arr[pos++] = 0x80 | (c >> 6) & 0x3f; arr[pos++] = 0x80 | c & 0x3f; } } return arr; }
Encodes the given string into UTF-8 byte array. Throws if the source string has invalid UTF-16 encoding.
encode
javascript
pusher/pusher-js
dist/web/pusher-with-encryption.js
https://github.com/pusher/pusher-js/blob/master/dist/web/pusher-with-encryption.js
MIT
function encodedLength(s) { var result = 0; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i); if (c < 0x80) { result += 1; } else if (c < 0x800) { result += 2; } else if (c < 0xd800) { result += 3; } else if (c <= 0xdfff) { if (i >= s.length - 1) { throw new Error(INVALID_UTF16); } i++; // "eat" next character result += 4; } else { throw new Error(INVALID_UTF16); } } return result; }
Returns the number of bytes required to encode the given string into UTF-8. Throws if the source string has invalid UTF-16 encoding.
encodedLength
javascript
pusher/pusher-js
dist/web/pusher-with-encryption.js
https://github.com/pusher/pusher-js/blob/master/dist/web/pusher-with-encryption.js
MIT
function decode(arr) { var chars = []; for (var i = 0; i < arr.length; i++) { var b = arr[i]; if (b & 0x80) { var min = void 0; if (b < 0xe0) { // Need 1 more byte. if (i >= arr.length) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; if ((n1 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x1f) << 6 | (n1 & 0x3f); min = 0x80; } else if (b < 0xf0) { // Need 2 more bytes. if (i >= arr.length - 1) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; var n2 = arr[++i]; if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x0f) << 12 | (n1 & 0x3f) << 6 | (n2 & 0x3f); min = 0x800; } else if (b < 0xf8) { // Need 3 more bytes. if (i >= arr.length - 2) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; var n2 = arr[++i]; var n3 = arr[++i]; if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80 || (n3 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x0f) << 18 | (n1 & 0x3f) << 12 | (n2 & 0x3f) << 6 | (n3 & 0x3f); min = 0x10000; } else { throw new Error(INVALID_UTF8); } if (b < min || (b >= 0xd800 && b <= 0xdfff)) { throw new Error(INVALID_UTF8); } if (b >= 0x10000) { // Surrogate pair. if (b > 0x10ffff) { throw new Error(INVALID_UTF8); } b -= 0x10000; chars.push(String.fromCharCode(0xd800 | (b >> 10))); b = 0xdc00 | (b & 0x3ff); } } chars.push(String.fromCharCode(b)); } return chars.join(""); }
Decodes the given byte array from UTF-8 into a string. Throws if encoding is invalid.
decode
javascript
pusher/pusher-js
dist/web/pusher-with-encryption.js
https://github.com/pusher/pusher-js/blob/master/dist/web/pusher-with-encryption.js
MIT
function encode(s) { // Calculate result length and allocate output array. // encodedLength() also validates string and throws errors, // so we don't need repeat validation here. var arr = new Uint8Array(encodedLength(s)); var pos = 0; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i); if (c < 0x80) { arr[pos++] = c; } else if (c < 0x800) { arr[pos++] = 0xc0 | c >> 6; arr[pos++] = 0x80 | c & 0x3f; } else if (c < 0xd800) { arr[pos++] = 0xe0 | c >> 12; arr[pos++] = 0x80 | (c >> 6) & 0x3f; arr[pos++] = 0x80 | c & 0x3f; } else { i++; // get one more character c = (c & 0x3ff) << 10; c |= s.charCodeAt(i) & 0x3ff; c += 0x10000; arr[pos++] = 0xf0 | c >> 18; arr[pos++] = 0x80 | (c >> 12) & 0x3f; arr[pos++] = 0x80 | (c >> 6) & 0x3f; arr[pos++] = 0x80 | c & 0x3f; } } return arr; }
Encodes the given string into UTF-8 byte array. Throws if the source string has invalid UTF-16 encoding.
encode
javascript
pusher/pusher-js
dist/web/pusher.js
https://github.com/pusher/pusher-js/blob/master/dist/web/pusher.js
MIT
function encodedLength(s) { var result = 0; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i); if (c < 0x80) { result += 1; } else if (c < 0x800) { result += 2; } else if (c < 0xd800) { result += 3; } else if (c <= 0xdfff) { if (i >= s.length - 1) { throw new Error(INVALID_UTF16); } i++; // "eat" next character result += 4; } else { throw new Error(INVALID_UTF16); } } return result; }
Returns the number of bytes required to encode the given string into UTF-8. Throws if the source string has invalid UTF-16 encoding.
encodedLength
javascript
pusher/pusher-js
dist/web/pusher.js
https://github.com/pusher/pusher-js/blob/master/dist/web/pusher.js
MIT
function decode(arr) { var chars = []; for (var i = 0; i < arr.length; i++) { var b = arr[i]; if (b & 0x80) { var min = void 0; if (b < 0xe0) { // Need 1 more byte. if (i >= arr.length) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; if ((n1 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x1f) << 6 | (n1 & 0x3f); min = 0x80; } else if (b < 0xf0) { // Need 2 more bytes. if (i >= arr.length - 1) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; var n2 = arr[++i]; if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x0f) << 12 | (n1 & 0x3f) << 6 | (n2 & 0x3f); min = 0x800; } else if (b < 0xf8) { // Need 3 more bytes. if (i >= arr.length - 2) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; var n2 = arr[++i]; var n3 = arr[++i]; if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80 || (n3 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x0f) << 18 | (n1 & 0x3f) << 12 | (n2 & 0x3f) << 6 | (n3 & 0x3f); min = 0x10000; } else { throw new Error(INVALID_UTF8); } if (b < min || (b >= 0xd800 && b <= 0xdfff)) { throw new Error(INVALID_UTF8); } if (b >= 0x10000) { // Surrogate pair. if (b > 0x10ffff) { throw new Error(INVALID_UTF8); } b -= 0x10000; chars.push(String.fromCharCode(0xd800 | (b >> 10))); b = 0xdc00 | (b & 0x3ff); } } chars.push(String.fromCharCode(b)); } return chars.join(""); }
Decodes the given byte array from UTF-8 into a string. Throws if encoding is invalid.
decode
javascript
pusher/pusher-js
dist/web/pusher.js
https://github.com/pusher/pusher-js/blob/master/dist/web/pusher.js
MIT
function encode(s) { // Calculate result length and allocate output array. // encodedLength() also validates string and throws errors, // so we don't need repeat validation here. var arr = new Uint8Array(encodedLength(s)); var pos = 0; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i); if (c < 0x80) { arr[pos++] = c; } else if (c < 0x800) { arr[pos++] = 0xc0 | c >> 6; arr[pos++] = 0x80 | c & 0x3f; } else if (c < 0xd800) { arr[pos++] = 0xe0 | c >> 12; arr[pos++] = 0x80 | (c >> 6) & 0x3f; arr[pos++] = 0x80 | c & 0x3f; } else { i++; // get one more character c = (c & 0x3ff) << 10; c |= s.charCodeAt(i) & 0x3ff; c += 0x10000; arr[pos++] = 0xf0 | c >> 18; arr[pos++] = 0x80 | (c >> 12) & 0x3f; arr[pos++] = 0x80 | (c >> 6) & 0x3f; arr[pos++] = 0x80 | c & 0x3f; } } return arr; }
Encodes the given string into UTF-8 byte array. Throws if the source string has invalid UTF-16 encoding.
encode
javascript
pusher/pusher-js
dist/worker/pusher-with-encryption.worker.js
https://github.com/pusher/pusher-js/blob/master/dist/worker/pusher-with-encryption.worker.js
MIT
function encodedLength(s) { var result = 0; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i); if (c < 0x80) { result += 1; } else if (c < 0x800) { result += 2; } else if (c < 0xd800) { result += 3; } else if (c <= 0xdfff) { if (i >= s.length - 1) { throw new Error(INVALID_UTF16); } i++; // "eat" next character result += 4; } else { throw new Error(INVALID_UTF16); } } return result; }
Returns the number of bytes required to encode the given string into UTF-8. Throws if the source string has invalid UTF-16 encoding.
encodedLength
javascript
pusher/pusher-js
dist/worker/pusher-with-encryption.worker.js
https://github.com/pusher/pusher-js/blob/master/dist/worker/pusher-with-encryption.worker.js
MIT
function decode(arr) { var chars = []; for (var i = 0; i < arr.length; i++) { var b = arr[i]; if (b & 0x80) { var min = void 0; if (b < 0xe0) { // Need 1 more byte. if (i >= arr.length) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; if ((n1 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x1f) << 6 | (n1 & 0x3f); min = 0x80; } else if (b < 0xf0) { // Need 2 more bytes. if (i >= arr.length - 1) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; var n2 = arr[++i]; if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x0f) << 12 | (n1 & 0x3f) << 6 | (n2 & 0x3f); min = 0x800; } else if (b < 0xf8) { // Need 3 more bytes. if (i >= arr.length - 2) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; var n2 = arr[++i]; var n3 = arr[++i]; if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80 || (n3 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x0f) << 18 | (n1 & 0x3f) << 12 | (n2 & 0x3f) << 6 | (n3 & 0x3f); min = 0x10000; } else { throw new Error(INVALID_UTF8); } if (b < min || (b >= 0xd800 && b <= 0xdfff)) { throw new Error(INVALID_UTF8); } if (b >= 0x10000) { // Surrogate pair. if (b > 0x10ffff) { throw new Error(INVALID_UTF8); } b -= 0x10000; chars.push(String.fromCharCode(0xd800 | (b >> 10))); b = 0xdc00 | (b & 0x3ff); } } chars.push(String.fromCharCode(b)); } return chars.join(""); }
Decodes the given byte array from UTF-8 into a string. Throws if encoding is invalid.
decode
javascript
pusher/pusher-js
dist/worker/pusher-with-encryption.worker.js
https://github.com/pusher/pusher-js/blob/master/dist/worker/pusher-with-encryption.worker.js
MIT
function encode(s) { // Calculate result length and allocate output array. // encodedLength() also validates string and throws errors, // so we don't need repeat validation here. var arr = new Uint8Array(encodedLength(s)); var pos = 0; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i); if (c < 0x80) { arr[pos++] = c; } else if (c < 0x800) { arr[pos++] = 0xc0 | c >> 6; arr[pos++] = 0x80 | c & 0x3f; } else if (c < 0xd800) { arr[pos++] = 0xe0 | c >> 12; arr[pos++] = 0x80 | (c >> 6) & 0x3f; arr[pos++] = 0x80 | c & 0x3f; } else { i++; // get one more character c = (c & 0x3ff) << 10; c |= s.charCodeAt(i) & 0x3ff; c += 0x10000; arr[pos++] = 0xf0 | c >> 18; arr[pos++] = 0x80 | (c >> 12) & 0x3f; arr[pos++] = 0x80 | (c >> 6) & 0x3f; arr[pos++] = 0x80 | c & 0x3f; } } return arr; }
Encodes the given string into UTF-8 byte array. Throws if the source string has invalid UTF-16 encoding.
encode
javascript
pusher/pusher-js
dist/worker/pusher.worker.js
https://github.com/pusher/pusher-js/blob/master/dist/worker/pusher.worker.js
MIT
function encodedLength(s) { var result = 0; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i); if (c < 0x80) { result += 1; } else if (c < 0x800) { result += 2; } else if (c < 0xd800) { result += 3; } else if (c <= 0xdfff) { if (i >= s.length - 1) { throw new Error(INVALID_UTF16); } i++; // "eat" next character result += 4; } else { throw new Error(INVALID_UTF16); } } return result; }
Returns the number of bytes required to encode the given string into UTF-8. Throws if the source string has invalid UTF-16 encoding.
encodedLength
javascript
pusher/pusher-js
dist/worker/pusher.worker.js
https://github.com/pusher/pusher-js/blob/master/dist/worker/pusher.worker.js
MIT
function decode(arr) { var chars = []; for (var i = 0; i < arr.length; i++) { var b = arr[i]; if (b & 0x80) { var min = void 0; if (b < 0xe0) { // Need 1 more byte. if (i >= arr.length) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; if ((n1 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x1f) << 6 | (n1 & 0x3f); min = 0x80; } else if (b < 0xf0) { // Need 2 more bytes. if (i >= arr.length - 1) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; var n2 = arr[++i]; if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x0f) << 12 | (n1 & 0x3f) << 6 | (n2 & 0x3f); min = 0x800; } else if (b < 0xf8) { // Need 3 more bytes. if (i >= arr.length - 2) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; var n2 = arr[++i]; var n3 = arr[++i]; if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80 || (n3 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x0f) << 18 | (n1 & 0x3f) << 12 | (n2 & 0x3f) << 6 | (n3 & 0x3f); min = 0x10000; } else { throw new Error(INVALID_UTF8); } if (b < min || (b >= 0xd800 && b <= 0xdfff)) { throw new Error(INVALID_UTF8); } if (b >= 0x10000) { // Surrogate pair. if (b > 0x10ffff) { throw new Error(INVALID_UTF8); } b -= 0x10000; chars.push(String.fromCharCode(0xd800 | (b >> 10))); b = 0xdc00 | (b & 0x3ff); } } chars.push(String.fromCharCode(b)); } return chars.join(""); }
Decodes the given byte array from UTF-8 into a string. Throws if encoding is invalid.
decode
javascript
pusher/pusher-js
dist/worker/pusher.worker.js
https://github.com/pusher/pusher-js/blob/master/dist/worker/pusher.worker.js
MIT
App = function () { this.init.apply(this, arguments); }
@class App @constructor @description Main application object. Acts as view dispatcher
App
javascript
hojberg/cssarrowplease
app/main.js
https://github.com/hojberg/cssarrowplease/blob/master/app/main.js
MIT
function attachModuleSymbols(doclets, modules) { var symbols = {} // build a lookup table doclets.forEach(function(symbol) { symbols[symbol.longname] = symbols[symbol.longname] || [] symbols[symbol.longname].push(symbol) }) modules.forEach(function(module) { if (symbols[module.longname]) { module.modules = symbols[module.longname] // Only show symbols that have a description. Make an exception for classes, because // we want to show the constructor-signature heading no matter what. .filter(function(symbol) { return symbol.description || symbol.kind === 'class' }) .map(function(symbol) { symbol = doop(symbol) if (symbol.kind === 'class' || symbol.kind === 'function') { symbol.name = symbol.name.replace('module:', '(require("') + '"))' } return symbol }) } }) }
Look for classes or functions with the same name as modules (which indicates that the module exports only that class or function), then attach the classes or functions to the `module` property of the appropriate module doclets. The name of each class or function is also updated for display purposes. This function mutates the original arrays. @private @param {Array.<module:jsdoc/doclet.Doclet>} doclets - The array of classes and functions to check. @param {Array.<module:jsdoc/doclet.Doclet>} modules - The array of module doclets to search.
attachModuleSymbols
javascript
SoftwareBrothers/better-docs
publish.js
https://github.com/SoftwareBrothers/better-docs/blob/master/publish.js
MIT
function buildMemberNav(items, itemHeading, itemsSeen, linktoFn) { const subCategories = items.reduce((memo, item) => { const subCategory = item.subCategory || '' memo[subCategory] = memo[subCategory] || [] return { ...memo, [subCategory]: [...memo[subCategory], item] } }, {}) const subCategoryNames = Object.keys(subCategories) var nav = '' subCategoryNames.forEach((subCategoryName) => { const subCategoryItems = subCategories[subCategoryName] if (subCategoryItems.length) { var itemsNav = '' subCategoryItems.forEach(function(item) { var displayName if ( !hasOwnProp.call(item, 'longname') ) { itemsNav += '<li>' + linktoFn('', item.name) + '</li>' } else if ( !hasOwnProp.call(itemsSeen, item.longname) ) { if (env.conf.templates.default.useLongnameInNav) { displayName = item.longname } else { displayName = item.name } itemsNav += '<li>' + linktoFn(item.longname, displayName.replace(/\b(module|event):/g, '')) if (item.children && item.children.length) { itemsNav += '<ul>' item.children.forEach(child => { if (env.conf.templates.default.useLongnameInNav) { displayName = child.longname } else { displayName = child.name } itemsNav += '<li>' + linktoFn(child.longname, displayName.replace(/\b(module|event):/g, '')) + '</li>' }) itemsNav += '</ul>' } itemsNav += '</li>' itemsSeen[item.longname] = true } }) if (itemsNav !== '') { var heading = itemHeading if (subCategoryName) { heading = heading + ' / ' + subCategoryName } nav += '<h3>' + heading + '</h3><ul>' + itemsNav + '</ul>' } } }) return nav }
Look for classes or functions with the same name as modules (which indicates that the module exports only that class or function), then attach the classes or functions to the `module` property of the appropriate module doclets. The name of each class or function is also updated for display purposes. This function mutates the original arrays. @private @param {Array.<module:jsdoc/doclet.Doclet>} doclets - The array of classes and functions to check. @param {Array.<module:jsdoc/doclet.Doclet>} modules - The array of module doclets to search.
buildMemberNav
javascript
SoftwareBrothers/better-docs
publish.js
https://github.com/SoftwareBrothers/better-docs/blob/master/publish.js
MIT
function linktoTutorial(longName, name) { return tutoriallink(name) }
Look for classes or functions with the same name as modules (which indicates that the module exports only that class or function), then attach the classes or functions to the `module` property of the appropriate module doclets. The name of each class or function is also updated for display purposes. This function mutates the original arrays. @private @param {Array.<module:jsdoc/doclet.Doclet>} doclets - The array of classes and functions to check. @param {Array.<module:jsdoc/doclet.Doclet>} modules - The array of module doclets to search.
linktoTutorial
javascript
SoftwareBrothers/better-docs
publish.js
https://github.com/SoftwareBrothers/better-docs/blob/master/publish.js
MIT
function linktoExternal(longName, name) { return linkto(longName, name.replace(/(^"|"$)/g, '')) }
Look for classes or functions with the same name as modules (which indicates that the module exports only that class or function), then attach the classes or functions to the `module` property of the appropriate module doclets. The name of each class or function is also updated for display purposes. This function mutates the original arrays. @private @param {Array.<module:jsdoc/doclet.Doclet>} doclets - The array of classes and functions to check. @param {Array.<module:jsdoc/doclet.Doclet>} modules - The array of module doclets to search.
linktoExternal
javascript
SoftwareBrothers/better-docs
publish.js
https://github.com/SoftwareBrothers/better-docs/blob/master/publish.js
MIT
function buildGroupNav (members, title) { var globalNav var seenTutorials = {} var nav = '' var seen = {} nav += '<div class="category">' if (title) { nav += '<h2>' + title + '</h2>' } nav += buildMemberNav(members.tutorials || [], 'Tutorials', seenTutorials, linktoTutorial) nav += buildMemberNav(members.modules || [], 'Modules', {}, linkto) nav += buildMemberNav(members.externals || [], 'Externals', seen, linktoExternal) nav += buildMemberNav(members.namespaces || [], 'Namespaces', seen, linkto) nav += buildMemberNav(members.classes || [], 'Classes', seen, linkto) nav += buildMemberNav(members.interfaces || [], 'Interfaces', seen, linkto) nav += buildMemberNav(members.events || [], 'Events', seen, linkto) nav += buildMemberNav(members.mixins || [], 'Mixins', seen, linkto) nav += buildMemberNav(members.components || [], 'Components', seen, linkto) if (members.globals && members.globals.length) { globalNav = '' members.globals.forEach(function(g) { if ( g.kind !== 'typedef' && !hasOwnProp.call(seen, g.longname) ) { globalNav += '<li>' + linkto(g.longname, g.name) + '</li>' } seen[g.longname] = true }) if (!globalNav) { // turn the heading into a link so you can actually get to the global page nav += '<h3>' + linkto('global', 'Global') + '</h3>' } else { nav += '<h3>Global</h3><ul>' + globalNav + '</ul>' } } nav += '</div>' return nav }
Look for classes or functions with the same name as modules (which indicates that the module exports only that class or function), then attach the classes or functions to the `module` property of the appropriate module doclets. The name of each class or function is also updated for display purposes. This function mutates the original arrays. @private @param {Array.<module:jsdoc/doclet.Doclet>} doclets - The array of classes and functions to check. @param {Array.<module:jsdoc/doclet.Doclet>} modules - The array of module doclets to search.
buildGroupNav
javascript
SoftwareBrothers/better-docs
publish.js
https://github.com/SoftwareBrothers/better-docs/blob/master/publish.js
MIT
function buildNav(members, navTypes = null, betterDocs) { const href = betterDocs.landing ? 'docs.html' : 'index.html' var nav = navTypes ? '' : `<h2><a href="${href}">Documentation</a></h2>` var categorised = {} var rootScope = {} var types = navTypes || ['modules', 'externals', 'namespaces', 'classes', 'components', 'interfaces', 'events', 'mixins', 'globals'] types.forEach(function(type) { if (!members[type]) { return } members[type].forEach(function(element) { if (element.access && element.access === 'private') { return } if (element.category) { if (!categorised[element.category]){ categorised[element.category] = [] } if (!categorised[element.category][type]){ categorised[element.category][type] = [] } categorised[element.category][type].push(element) } else { rootScope[type] ? rootScope[type].push(element) : rootScope[type] = [element] } }) }) nav += buildGroupNav(rootScope) Object.keys(categorised).sort().forEach(function (category) { nav += buildGroupNav(categorised[category], category) }) return nav }
Create the navigation sidebar. @param {object} members The members that will be used to create the sidebar. @param {array<object>} members.classes @param {array<object>} members.components @param {array<object>} members.externals @param {array<object>} members.globals @param {array<object>} members.mixins @param {array<object>} members.modules @param {array<object>} members.namespaces @param {array<object>} members.tutorials @param {array<object>} members.events @param {array<object>} members.interfaces @return {string} The HTML for the navigation sidebar.
buildNav
javascript
SoftwareBrothers/better-docs
publish.js
https://github.com/SoftwareBrothers/better-docs/blob/master/publish.js
MIT
function generateTutorial(title, subtitle, tutorial, filename) { var tutorialData = { title: title, subtitle: subtitle, header: tutorial.title, content: tutorial.parse(), children: tutorial.children } var tutorialPath = path.join(outdir, filename) var html = view.render('tutorial.tmpl', tutorialData) // yes, you can use {@link} in tutorials too! html = helper.resolveLinks(html) // turn {@link foo} into <a href="foodoc.html">foo</a> fs.writeFileSync(tutorialPath, html, 'utf8') }
@param {TAFFY} taffyData See <http://taffydb.com/>. @param {object} opts @param {Tutorial} tutorials
generateTutorial
javascript
SoftwareBrothers/better-docs
publish.js
https://github.com/SoftwareBrothers/better-docs/blob/master/publish.js
MIT
function saveChildren(node) { node.children.forEach(function(child) { generateTutorial(child.title, 'Tutorial', child, helper.tutorialToUrl(child.name)) saveChildren(child) }) }
@param {TAFFY} taffyData See <http://taffydb.com/>. @param {object} opts @param {Tutorial} tutorials
saveChildren
javascript
SoftwareBrothers/better-docs
publish.js
https://github.com/SoftwareBrothers/better-docs/blob/master/publish.js
MIT
function saveLandingPage() { const content = fs.readFileSync(conf.betterDocs.landing, 'utf8') var landingPageData = { title: 'Home', content, } var homePath = path.join(outdir, 'index.html') var docsPath = path.join(outdir, 'docs.html') fs.renameSync(homePath, docsPath) view.layout = 'landing.tmpl' var html = view.render('content.tmpl', landingPageData) // yes, you can use {@link} in tutorials too! html = helper.resolveLinks(html) // turn {@link foo} into <a href="foodoc.html">foo</a> fs.writeFileSync(homePath, html, 'utf8') }
@param {TAFFY} taffyData See <http://taffydb.com/>. @param {object} opts @param {Tutorial} tutorials
saveLandingPage
javascript
SoftwareBrothers/better-docs
publish.js
https://github.com/SoftwareBrothers/better-docs/blob/master/publish.js
MIT
selectOnScroll = () => { const position = core.scrollTop() let activeSet = false for (let index = (links.length-1); index >= 0; index--) { const link = links[index] link.link.removeClass('is-active') if ((position + OFFSET) >= link.offset) { if (!activeSet) { link.link.addClass('is-active') activeSet = true } else { link.link.addClass('is-past') } } else { link.link.removeClass('is-past') } } }
@type {Array<{link: El, offset: number}>}
selectOnScroll
javascript
SoftwareBrothers/better-docs
scripts/side-nav.js
https://github.com/SoftwareBrothers/better-docs/blob/master/scripts/side-nav.js
MIT
selectOnScroll = () => { const position = core.scrollTop() let activeSet = false for (let index = (links.length-1); index >= 0; index--) { const link = links[index] link.link.removeClass('is-active') if ((position + OFFSET) >= link.offset) { if (!activeSet) { link.link.addClass('is-active') activeSet = true } else { link.link.addClass('is-past') } } else { link.link.removeClass('is-past') } } }
@type {Array<{link: El, offset: number}>}
selectOnScroll
javascript
SoftwareBrothers/better-docs
scripts/side-nav.js
https://github.com/SoftwareBrothers/better-docs/blob/master/scripts/side-nav.js
MIT
getTypeName = (type, src) => { if(!type) { return ''} if (type.typeName && type.typeName.escapedText) { const typeName = type.typeName.escapedText if(type.typeArguments && type.typeArguments.length) { const args = type.typeArguments.map(subType => getTypeName(subType, src)).join(', ') return `${typeName}<${args}>` } else { return typeName } } if(ts.isFunctionTypeNode(type) || ts.isFunctionLike(type)) { // it replaces ():void => {} (and other) to simple function return 'function' } if (ts.isArrayTypeNode(type)) { return 'Array' } if (type.types) { return type.types.map(subType => getTypeName(subType, src)).join(' | ') } if (type.members && type.members.length) { return 'object' } return src.substring(type.pos, type.end).trim() }
Get type from a node @param {ts.TypeNode} type which should be parsed to string @param {string} src source for an entire parsed file @returns {string} node type
getTypeName
javascript
SoftwareBrothers/better-docs
typescript/type-converter.js
https://github.com/SoftwareBrothers/better-docs/blob/master/typescript/type-converter.js
MIT
getTypeName = (type, src) => { if(!type) { return ''} if (type.typeName && type.typeName.escapedText) { const typeName = type.typeName.escapedText if(type.typeArguments && type.typeArguments.length) { const args = type.typeArguments.map(subType => getTypeName(subType, src)).join(', ') return `${typeName}<${args}>` } else { return typeName } } if(ts.isFunctionTypeNode(type) || ts.isFunctionLike(type)) { // it replaces ():void => {} (and other) to simple function return 'function' } if (ts.isArrayTypeNode(type)) { return 'Array' } if (type.types) { return type.types.map(subType => getTypeName(subType, src)).join(' | ') } if (type.members && type.members.length) { return 'object' } return src.substring(type.pos, type.end).trim() }
Get type from a node @param {ts.TypeNode} type which should be parsed to string @param {string} src source for an entire parsed file @returns {string} node type
getTypeName
javascript
SoftwareBrothers/better-docs
typescript/type-converter.js
https://github.com/SoftwareBrothers/better-docs/blob/master/typescript/type-converter.js
MIT
function checkType(node) { console.group(node.name?.escapedText); const predictedTypes = Object.keys(ts).reduce((acc, key) => { if (typeof ts[key] !== "function" && !key.startsWith("is")) { return acc; } try { if (ts[key](node) === true) { acc.push(key); } } catch (error) { return acc; } return acc; }, []); console.log(predictedTypes); console.groupEnd(); }
Check type of node (dev only) @param {node} node @return {void} Console log predicted types
checkType
javascript
SoftwareBrothers/better-docs
typescript/type-converter.js
https://github.com/SoftwareBrothers/better-docs/blob/master/typescript/type-converter.js
MIT
fillMethodComment = (comment, member, src) => { if (!comment.includes('@method')) { comment = appendComment(comment, '@method') } if (!comment.includes('@param')) { comment = convertParams(comment, member, src) } if (member.type && ts.isArrayTypeNode(member.type)) { comment = convertMembers(comment, member.type, src) } if (member.type && !comment.includes('@return')) { const returnType = getTypeName(member.type, src) comment = appendComment(comment, `@return {${returnType}}`) } return comment }
Fill missing method declaration @param {string} comment @param member @param {string} src @return {string}
fillMethodComment
javascript
SoftwareBrothers/better-docs
typescript/type-converter.js
https://github.com/SoftwareBrothers/better-docs/blob/master/typescript/type-converter.js
MIT
fillMethodComment = (comment, member, src) => { if (!comment.includes('@method')) { comment = appendComment(comment, '@method') } if (!comment.includes('@param')) { comment = convertParams(comment, member, src) } if (member.type && ts.isArrayTypeNode(member.type)) { comment = convertMembers(comment, member.type, src) } if (member.type && !comment.includes('@return')) { const returnType = getTypeName(member.type, src) comment = appendComment(comment, `@return {${returnType}}`) } return comment }
Fill missing method declaration @param {string} comment @param member @param {string} src @return {string}
fillMethodComment
javascript
SoftwareBrothers/better-docs
typescript/type-converter.js
https://github.com/SoftwareBrothers/better-docs/blob/master/typescript/type-converter.js
MIT
convertParams = (jsDoc = '', node, src) => { const parameters = node.type?.parameters || node.parameters if(!parameters) { return } parameters.forEach(parameter => { let name = getName(parameter, src) let comment = getCommentAsString(parameter, src) if (parameter.questionToken) { name = ['[', name, ']'].join('') } let type = getTypeName(parameter.type, src) jsDoc = appendComment(jsDoc, `@param {${type}} ${name} ${comment}`) }) return jsDoc }
converts function parameters to @params @param {string} [jsDoc] existing jsdoc text where all @param comments should be appended @param {ts.FunctionDeclaration} wrapper ts node which has to be parsed @param {string} src source for an entire parsed file (we are fetching substrings from it) @param {string} parentName name of a parent element - NOT IMPLEMENTED YET @returns {string} modified jsDoc comment with appended @param tags
convertParams
javascript
SoftwareBrothers/better-docs
typescript/type-converter.js
https://github.com/SoftwareBrothers/better-docs/blob/master/typescript/type-converter.js
MIT
convertParams = (jsDoc = '', node, src) => { const parameters = node.type?.parameters || node.parameters if(!parameters) { return } parameters.forEach(parameter => { let name = getName(parameter, src) let comment = getCommentAsString(parameter, src) if (parameter.questionToken) { name = ['[', name, ']'].join('') } let type = getTypeName(parameter.type, src) jsDoc = appendComment(jsDoc, `@param {${type}} ${name} ${comment}`) }) return jsDoc }
converts function parameters to @params @param {string} [jsDoc] existing jsdoc text where all @param comments should be appended @param {ts.FunctionDeclaration} wrapper ts node which has to be parsed @param {string} src source for an entire parsed file (we are fetching substrings from it) @param {string} parentName name of a parent element - NOT IMPLEMENTED YET @returns {string} modified jsDoc comment with appended @param tags
convertParams
javascript
SoftwareBrothers/better-docs
typescript/type-converter.js
https://github.com/SoftwareBrothers/better-docs/blob/master/typescript/type-converter.js
MIT
convertMembers = (jsDoc = '', type, src, parentName = null) => { // type could be an array of types like: `{sth: 1} | string` - so we parse // each type separately const typesToCheck = [type] if (type.types && type.types.length) { typesToCheck.push(...type.types) } typesToCheck.forEach(type => { // Handling array defined like this: {element1: 'something'}[] if(ts.isArrayTypeNode(type) && type.elementType) { jsDoc = convertMembers(jsDoc, type.elementType, src, parentName ? parentName + '[]' : '[]') } // Handling Array<{element1: 'something'}> if (type.typeName && type.typeName.escapedText === 'Array') { if(type.typeArguments && type.typeArguments.length) { type.typeArguments.forEach(subType => { jsDoc = convertMembers(jsDoc, subType, src, parentName ? parentName + '[]' : '' // when there is no parent - jsdoc cannot parse [].name ) }) } } // Handling {property1: "value"} (type.members || []).filter(m => ts.isTypeElement(m)).forEach(member => { let name = getName(member, src) let comment = getCommentAsString(member, src) const members = member.type.members || [] let typeName = members.length ? 'object' : getTypeName(member.type, src) if (parentName) { name = [parentName, name].join('.') } // optional const nameToPlace = member.questionToken ? `[${name}]` : name jsDoc = appendComment(jsDoc, `@property {${typeName}} ${nameToPlace} ${comment}`) jsDoc = convertMembers(jsDoc, member.type, src, name) }) }) return jsDoc }
Convert type properties to @property @param {string} [jsDoc] existing jsdoc text where all @param comments should be appended @param {ts.TypeNode} wrapper ts node which has to be parsed @param {string} src source for an entire parsed file (we are fetching substrings from it) @param {string} parentName name of a parent element @returns {string} modified jsDoc comment with appended @param tags
convertMembers
javascript
SoftwareBrothers/better-docs
typescript/type-converter.js
https://github.com/SoftwareBrothers/better-docs/blob/master/typescript/type-converter.js
MIT
convertMembers = (jsDoc = '', type, src, parentName = null) => { // type could be an array of types like: `{sth: 1} | string` - so we parse // each type separately const typesToCheck = [type] if (type.types && type.types.length) { typesToCheck.push(...type.types) } typesToCheck.forEach(type => { // Handling array defined like this: {element1: 'something'}[] if(ts.isArrayTypeNode(type) && type.elementType) { jsDoc = convertMembers(jsDoc, type.elementType, src, parentName ? parentName + '[]' : '[]') } // Handling Array<{element1: 'something'}> if (type.typeName && type.typeName.escapedText === 'Array') { if(type.typeArguments && type.typeArguments.length) { type.typeArguments.forEach(subType => { jsDoc = convertMembers(jsDoc, subType, src, parentName ? parentName + '[]' : '' // when there is no parent - jsdoc cannot parse [].name ) }) } } // Handling {property1: "value"} (type.members || []).filter(m => ts.isTypeElement(m)).forEach(member => { let name = getName(member, src) let comment = getCommentAsString(member, src) const members = member.type.members || [] let typeName = members.length ? 'object' : getTypeName(member.type, src) if (parentName) { name = [parentName, name].join('.') } // optional const nameToPlace = member.questionToken ? `[${name}]` : name jsDoc = appendComment(jsDoc, `@property {${typeName}} ${nameToPlace} ${comment}`) jsDoc = convertMembers(jsDoc, member.type, src, name) }) }) return jsDoc }
Convert type properties to @property @param {string} [jsDoc] existing jsdoc text where all @param comments should be appended @param {ts.TypeNode} wrapper ts node which has to be parsed @param {string} src source for an entire parsed file (we are fetching substrings from it) @param {string} parentName name of a parent element @returns {string} modified jsDoc comment with appended @param tags
convertMembers
javascript
SoftwareBrothers/better-docs
typescript/type-converter.js
https://github.com/SoftwareBrothers/better-docs/blob/master/typescript/type-converter.js
MIT
function getCommentAsString(member, src) { if (member.jsDoc && member.jsDoc[0] && member.jsDoc[0].comment) { const comment = member.jsDoc[0].comment; if (Array.isArray(comment)) { return comment .map((c) => c.text.length ? c.text : src.substring(c.pos, c.end)) .join(''); } return member.jsDoc[0].comment; } return ''; }
Extract comment from member jsDoc as string @param member @param {string} src @returns {string}
getCommentAsString
javascript
SoftwareBrothers/better-docs
typescript/type-converter.js
https://github.com/SoftwareBrothers/better-docs/blob/master/typescript/type-converter.js
MIT
function main() { var display = gamejs.display.getSurface(); console.log(display.getRect().width) var spear = gamejs.image.load('./spear.png'); var unit = gamejs.image.load('./unit.png'); // create image masks from surface var mUnit = new pixelcollision.Mask(unit); var mSpear = new pixelcollision.Mask(spear); var unitPosition = [20, 20]; var spearPosition = [6, 0]; var font = new gamejs.font.Font('20px monospace'); var direction = {}; direction[gamejs.event.K_UP] = [0, -1]; direction[gamejs.event.K_DOWN] = [0, 1]; direction[gamejs.event.K_LEFT] = [-1, 0]; direction[gamejs.event.K_RIGHT] = [1, 0]; gamejs.event.onKeyUp(function(event) { }); gamejs.event.onKeyDown(function(event) { var delta = direction[event.key]; if (delta) { spearPosition = $v.add(spearPosition, delta); } }) gamejs.event.onMouseMotion(function(event) { if (display.rect.collidePoint(event.pos)) { spearPosition = $v.subtract(event.pos, spear.getSize()); } }); gamejs.onTick(function() { // draw display.clear(); display.blit(unit, unitPosition); display.blit(spear, spearPosition); // collision // the relative offset is automatically calculated by // the higher-level gamejs.sprite.collideMask(spriteA, spriteB) var relativeOffset = $v.subtract(spearPosition, unitPosition); var hasMaskOverlap = mUnit.overlap(mSpear, relativeOffset); if (hasMaskOverlap) { display.blit(font.render('COLLISION', '#ff0000'), [250, 50]); } }); }
@fileoverview Demonstrates pixel perfect collision detection utilizing image masks. A 'spear' is moved around with mouse or cursors keys - the text 'COLLISION' appears if the spear pixel collides with the unit. gamejs.mask.fromSurface is used to create two pixel masks that do the actual collision detection.
main
javascript
GameJs/gamejs
examples/collisionmask/main.js
https://github.com/GameJs/gamejs/blob/master/examples/collisionmask/main.js
MIT
function main() { // set resolution & title var display = gamejs.display.getSurface(); gamejs.display.setCaption("Example Draw"); var colorOne = '#ff0000'; var colorTwo = 'rgb(255, 50, 60)'; var colorThree = 'rgba(50, 0, 150, 0.8)'; // All gamejs.draw methods share the same parameter order: // // * surface // * color // * position related: gamejs.Rect or [x,y] or array of [x, y] // * [second position if line] // * [radius if circle] // * line width; 0 line width = fill the structure // surface, color, startPos, endPos, width draw.line(display, colorOne, [0,0], [100,100], 1); draw.lines(display, colorOne, true, [[50,50], [100,50], [100,100], [50,100]], 4); draw.polygon(display, colorTwo, [[155,35], [210,50], [200,100]], 0); // surface, color, center, radius, width draw.circle(display, colorThree, [150, 150], 50, 10); draw.circle(display, '#ff0000', [250, 250], 50, 0); // surface, color, rect, width draw.rect(display, '#aaaaaa', new gamejs.Rect([10, 150], [20, 20]), 2); draw.rect(display, '#555555', new gamejs.Rect([50, 150], [20, 20]), 0); draw.rect(display, '#aaaaaa', new gamejs.Rect([90, 150], [20, 20]), 10); // surface, color, startPos, endPos, controlPos, width draw.quadraticCurve(display, "#00ff00", [100, 350], [400, 350], [250, 30], 3); // surface, color, startPos, endPos, firstControlPos, secondControlPos, width draw.bezierCurve(display, "#7EC736", [100, 300], [400, 300], [110, 350], [390, 350], 4); // Font object, create with css font definition var defaultFont = new font.Font("20px Verdana"); // render() returns a white transparent Surface containing the text (default color: black) var textSurface = defaultFont.render("Example Draw Test 101", "#bbbbbb"); display.blit(textSurface, [300, 50]); }
@fileoverview Draw lines, polygons, circles, etc on the screen. Render text in a certain font to the screen.
main
javascript
GameJs/gamejs
examples/draw/main.js
https://github.com/GameJs/gamejs/blob/master/examples/draw/main.js
MIT
function main() { var display = gamejs.display.getSurface(); gamejs.display.setCaption('example event'); var starImage = gamejs.image.load('./sparkle.png'); var instructionFont = new gamejs.font.Font('30px monospace'); var displayRect = display.rect; var sparkles = []; // to keep track of pointer position after it is locked var absolutePosition = [400, 300]; gamejs.event.onKeyUp(function(event) { if (event.key === gamejs.event.K_UP) { // reverse Y direction of sparkles sparkles.forEach(function(sparkle) { sparkle.deltaY *= -1; }); }; }); gamejs.event.onMouseMotion(function(event) { // if mouse is over display surface var pos = event.pos; if (displayRect.collidePoint(pos)) { // add sparkle at mouse position sparkles.push({ left: pos[0], top: pos[1], alpha: Math.random(), deltaX: 30 - Math.random() * 60, deltaY: 80 + Math.random() * 40, }); } }) gamejs.onTick(function(msDuration) { // update sparkle position & alpha sparkles.forEach(function(sparkle) { // msDuration makes is frame rate independant: we don't want // the sparkles to move faster on a superfast computer. var r = (msDuration/1000); sparkle.left += sparkle.deltaX * r; sparkle.top += sparkle.deltaY * r; }); // remove sparkles that are offscreen or invisible sparkles = sparkles.filter(function(sparkle) { return sparkle.top < displayRect.height && sparkle.top > 0; }) // draw sparkles display.fill('#000000'); display.blit(instructionFont.render('Move mouse. Press Cursor up.', '#ffffff'), [20, 20]); sparkles.forEach(function(sparkle) { starImage.setAlpha(sparkle.alpha); display.blit(starImage, [sparkle.left, sparkle.top]); }); }); }
@fileoverview Sparkles with position and alpha are created by mouse movement. The sparkles position is updated in a time-dependant way. A sparkle is removed from the simulation once it leaves the screen. Additionally, by pressing the cursor UP key the existing sparkles will move upwards (movement vecor inverted).
main
javascript
GameJs/gamejs
examples/event/main.js
https://github.com/GameJs/gamejs/blob/master/examples/event/main.js
MIT
function Ball(center) { this.center = center; this.growPerSec = Ball.GROW_PER_SEC; this.radius = this.growPerSec * 2; this.color = 0; return this; }
@fileoverview Minimal is the smalles GameJs app I could think of, which still shows off most of the concepts GameJs introduces. It's a pulsating, colored circle. You can make the circle change color by clicking.
Ball
javascript
GameJs/gamejs
examples/minimal/main.js
https://github.com/GameJs/gamejs/blob/master/examples/minimal/main.js
MIT
function main() { // setup screen and ball. // ball in screen center. // start game loop. var display = gamejs.display.getSurface(); var ballCenter = [display.getRect().width / 2, display.getRect().height / 2]; var ball = new Ball(ballCenter); // ball changes color on mouse up gamejs.event.onMouseUp(function() { ball.nextColor(); }); // update ball position // clear display // draw gamejs.onTick(function(msDuration) { ball.update(msDuration); display.clear(); ball.draw(display); }); gamejs.event.onDisplayResize(function(event) { ball.center = display.getRect().center; }); }
@fileoverview Minimal is the smalles GameJs app I could think of, which still shows off most of the concepts GameJs introduces. It's a pulsating, colored circle. You can make the circle change color by clicking.
main
javascript
GameJs/gamejs
examples/minimal/main.js
https://github.com/GameJs/gamejs/blob/master/examples/minimal/main.js
MIT
function main() { // screen setup var display = gamejs.display.getSurface(); gamejs.display.setCaption("Example Workers"); var font = new gamejs.font.Font(); // create a background worker var primeWorker = new gamejs.thread.Worker('./prime-worker'); // send a question to the worker var startNumber = parseInt(1230023 + (Math.random() * 10000)); primeWorker.post({ todo: "nextprimes", start: startNumber }); // wait for results... var primes = []; primeWorker.onEvent(function(event) { primes.push(event.prime); }); // draw resutls gamejs.onTick(function(msDuration) { var yOffset = 56; display.clear(); display.blit(font.render('Worker is producing primes bigger than ' + startNumber), [10,30]); primes.forEach(function(p, idx) { display.blit(font.render('#' + idx + ': ' + p), [10, yOffset]) yOffset += 20; }); }); }
Creates a Worker which - given a starting number - will produce primes coming after that number. This examples shows how messages are being sent from and to a worker, and that the number-crunching worker does not block the browser's UI (like a normal script running this long would).
main
javascript
GameJs/gamejs
examples/thread/main.js
https://github.com/GameJs/gamejs/blob/master/examples/thread/main.js
MIT
handleEvent = function(data) { if (data.todo === 'nextprimes') { var foundPrime = false; var n = data.start; var primes = []; var x = 10000; search: while(primes.length < 5) { n += 1; for (var i = 2; i <= Math.sqrt(n); i += 1) { if (n % i == 0) { continue search; } } if (x-- < 0) { primes.push(n); // found the next prime gamejs.thread.post({ prime: n }); x = 10000; } }; } else { gamejs.logging.log('unknown todo'); } }
This worker responds to a message `{todo: "nextprimes", start: 123}` and will return five primes after the `start` number. It will skip 100.000 primes between each of those five. (arbitrary algorithm, designed to be long running)
handleEvent
javascript
GameJs/gamejs
examples/thread/prime-worker.js
https://github.com/GameJs/gamejs/blob/master/examples/thread/prime-worker.js
MIT
function _ready() { if (!document.body) { return window.setTimeout(_ready, 50); } getImageProgress = gamejs.image.preload(RESOURCES); try { getMixerProgress = gamejs.audio.preload(RESOURCES); } catch (e) { gamejs.debug('Error loading audio files ', e); } window.setTimeout(_readyResources, 50); }
ReadyFn is called once all modules and assets are loaded. @param {Function} callbackFunction the function to be called once gamejs finished loading @name ready
_ready
javascript
GameJs/gamejs
src/gamejs.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs.js
MIT
function _readyResources() { if (getImageProgress() < 1 || getMixerProgress() < 1) { return window.setTimeout(_readyResources, 100); } gamejs.display.init(); gamejs.image.init(); gamejs.audio.init(); gamejs.event.init(); gamejs.math.random.init(); readyFn(); }
ReadyFn is called once all modules and assets are loaded. @param {Function} callbackFunction the function to be called once gamejs finished loading @name ready
_readyResources
javascript
GameJs/gamejs
src/gamejs.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs.js
MIT
function getLoadProgress() { if (getImageProgress) { return (0.5 * getImageProgress()) + (0.5 * getMixerProgress()); } return 0.1; }
ReadyFn is called once all modules and assets are loaded. @param {Function} callbackFunction the function to be called once gamejs finished loading @name ready
getLoadProgress
javascript
GameJs/gamejs
src/gamejs.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs.js
MIT
resourceBaseHref = function() { return (window.$g && window.$g.resourceBaseHref) || document.location.href; }
Initialize all gamejs modules. This is automatically called by `gamejs.ready()`. @returns {Object} the properties of this objecte are the moduleIds that failed, they value are the exceptions @ignore
resourceBaseHref
javascript
GameJs/gamejs
src/gamejs.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs.js
MIT
function linePosition(point) { var x = point[0]; var y = point[1]; return (y2 - y1) * x + (x1 - x2) * y + (x2 * y1 - x1 * y2); }
@param {Array} pointA start point of the line @param {Array} pointB end point of the line @returns true if the line intersects with the rectangle @see http://stackoverflow.com/questions/99353/how-to-test-if-a-line-segment-intersects-an-axis-aligned-rectange-in-2d/293052#293052
linePosition
javascript
GameJs/gamejs
src/gamejs.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs.js
MIT
function incrementLoaded() { countLoaded++; if (countLoaded == countTotal) { _PRELOADING = false; } }
Preload the audios into cache @param {String[]} List of audio URIs to load @returns {Function} which returns 0-1 for preload progress @ignore
incrementLoaded
javascript
GameJs/gamejs
src/gamejs/audio.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/audio.js
MIT
function getProgress() { return countTotal > 0 ? countLoaded / countTotal : 1; }
Preload the audios into cache @param {String[]} List of audio URIs to load @returns {Function} which returns 0-1 for preload progress @ignore
getProgress
javascript
GameJs/gamejs
src/gamejs/audio.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/audio.js
MIT
function successHandler() { addToCache(this); incrementLoaded(); }
Preload the audios into cache @param {String[]} List of audio URIs to load @returns {Function} which returns 0-1 for preload progress @ignore
successHandler
javascript
GameJs/gamejs
src/gamejs/audio.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/audio.js
MIT
function errorHandler() { incrementLoaded(); throw new Error('Error loading ' + this.src); }
Preload the audios into cache @param {String[]} List of audio URIs to load @returns {Function} which returns 0-1 for preload progress @ignore
errorHandler
javascript
GameJs/gamejs
src/gamejs/audio.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/audio.js
MIT
function addToCache(audios) { if (!(audios instanceof Array)) { audios = [audios]; } var docLoc = document.location.href; audios.forEach(function(audio) { CACHE[audio.gamejsKey] = audio; }); return; }
@param {dom.ImgElement} audios the <audio> elements to put into cache @ignore
addToCache
javascript
GameJs/gamejs
src/gamejs/audio.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/audio.js
MIT
getFullScreenToggle = function() { var fullScreenButton = document.getElementById('gjs-fullscreen-toggle'); if (!fullScreenButton) { // before canvas fullScreenButton = document.createElement('button'); fullScreenButton.innerHTML = 'Fullscreen'; fullScreenButton.id = 'gjs-fullscreen-toggle'; var canvas = getCanvas(); canvas.parentNode.insertBefore(fullScreenButton, canvas); canvas.parentNode.insertBefore(document.createElement('br'), canvas); } return fullScreenButton; }
@returns {document.Element} the canvas dom element @ignore
getFullScreenToggle
javascript
GameJs/gamejs
src/gamejs/display.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/display.js
MIT
fullScreenChange = function(event) { var gjsEvent ={ type: isFullScreen() ? require('./event').DISPLAY_FULLSCREEN_ENABLED : require('./event').DISPLAY_FULLSCREEN_DISABLED }; if (isFullScreen()) { if (_flags & POINTERLOCK) { enablePointerLock(); } } require('./event')._triggerCallbacks(gjsEvent); }
@returns {document.Element} the canvas dom element @ignore
fullScreenChange
javascript
GameJs/gamejs
src/gamejs/display.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/display.js
MIT
function onResize(event) { var canvas = getCanvas(); SURFACE._canvas.width = canvas.clientWidth; SURFACE._canvas.height = canvas.clientHeight; require('./event')._triggerCallbacks({ type: require('./event').DISPLAY_RESIZE }); }
@returns {document.Element} the canvas dom element @ignore
onResize
javascript
GameJs/gamejs
src/gamejs/display.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/display.js
MIT
enableFullScreen = function(event) { var wrapper = getCanvas(); wrapper.requestFullScreen = wrapper.requestFullScreen || wrapper.mozRequestFullScreen || wrapper.webkitRequestFullScreen; if (!wrapper.requestFullScreen) { return false; } // @xbrowser chrome allows keboard input onl if ask for it (why oh why?) if (Element.ALLOW_KEYBOARD_INPUT) { wrapper.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); } else { wrapper.requestFullScreen(); } return true; }
Switches the display window normal browser mode and fullscreen. @ignore @returns {Boolean} true if operation was successfull, false otherwise
enableFullScreen
javascript
GameJs/gamejs
src/gamejs/display.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/display.js
MIT
enablePointerLock = function() { var wrapper = getCanvas(); wrapper.requestPointerLock = wrapper.requestPointerLock || wrapper.mozRequestPointerLock || wrapper.webkitRequestPointerLock; if (wrapper.requestPointerLock) { wrapper.requestPointerLock(); } }
Switches the display window normal browser mode and fullscreen. @ignore @returns {Boolean} true if operation was successfull, false otherwise
enablePointerLock
javascript
GameJs/gamejs
src/gamejs/display.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/display.js
MIT
function stringify(response) { /* jshint ignore:start */ return eval('(' + response.responseText + ')'); /* jshint ignore:end */ }
Make http POST request to server-side @param {String} url @param {String|Object} data @param {String|Object} type "Accept" header value @returns {Response}
stringify
javascript
GameJs/gamejs
src/gamejs/http.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/http.js
MIT
function ajaxBaseHref() { return (window.$g && window.$g.ajaxBaseHref) || './'; }
Make http POST request to server-side @param {String} url @param {String|Object} data @param {String|Object} type "Accept" header value @returns {Response}
ajaxBaseHref
javascript
GameJs/gamejs
src/gamejs/http.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/http.js
MIT
function incrementLoaded() { countLoaded++; if (countLoaded == countTotal) { _PRELOADING = false; } if (countLoaded % 10 === 0) { gamejs.logging.debug('gamejs.image: preloaded ' + countLoaded + ' of ' + countTotal); } }
preload the given img URIs @returns {Function} which returns 0-1 for preload progress @ignore
incrementLoaded
javascript
GameJs/gamejs
src/gamejs/image.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/image.js
MIT
function getProgress() { return countTotal > 0 ? countLoaded / countTotal : 1; }
preload the given img URIs @returns {Function} which returns 0-1 for preload progress @ignore
getProgress
javascript
GameJs/gamejs
src/gamejs/image.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/image.js
MIT
function successHandler() { addToCache(this); incrementLoaded(); }
preload the given img URIs @returns {Function} which returns 0-1 for preload progress @ignore
successHandler
javascript
GameJs/gamejs
src/gamejs/image.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/image.js
MIT
function errorHandler() { incrementLoaded(); throw new Error('Error loading ' + this.src); }
preload the given img URIs @returns {Function} which returns 0-1 for preload progress @ignore
errorHandler
javascript
GameJs/gamejs
src/gamejs/image.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/image.js
MIT
addToCache = function(img) { CACHE[img.gamejsKey] = img; return; }
add the given <img> dom elements into the cache. @private
addToCache
javascript
GameJs/gamejs
src/gamejs/image.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/image.js
MIT
function routeScore(route) { if (route.score === undefined) { route.score = map.estimatedDistance(route.point, to) + route.length; } return route.score; }
A* search function. This function expects a `Map` implementation and the origin and destination points given. If there is a path between the two it will return the optimal path as a linked list. If there is no path it will return null. The linked list is in reverse order: the first item is the destination and the path to the origin follows. @param {Map} map map instance, must follow interface defined in {Map} @param {Array} origin @param {Array} destination @param {Number} timeout milliseconds after which search should be canceled @returns {Object} the linked list leading from `to` to `from` (sic!).
routeScore
javascript
GameJs/gamejs
src/gamejs/pathfinding.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/pathfinding.js
MIT
function addOpenRoute(route) { open.push(route); reached.store(route.point, route); }
A* search function. This function expects a `Map` implementation and the origin and destination points given. If there is a path between the two it will return the optimal path as a linked list. If there is no path it will return null. The linked list is in reverse order: the first item is the destination and the path to the origin follows. @param {Map} map map instance, must follow interface defined in {Map} @param {Array} origin @param {Array} destination @param {Number} timeout milliseconds after which search should be canceled @returns {Object} the linked list leading from `to` to `from` (sic!).
addOpenRoute
javascript
GameJs/gamejs
src/gamejs/pathfinding.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/pathfinding.js
MIT
function processNewPoints(direction) { var known = reached.find(direction); var newLength = route.length + map.actualDistance(route.point, direction); if (!known || known.length > newLength){ if (known) { open.remove(known); } addOpenRoute({ point: direction, from: route, length: newLength }); } }
A* search function. This function expects a `Map` implementation and the origin and destination points given. If there is a path between the two it will return the optimal path as a linked list. If there is no path it will return null. The linked list is in reverse order: the first item is the destination and the path to the origin follows. @param {Map} map map instance, must follow interface defined in {Map} @param {Array} origin @param {Array} destination @param {Number} timeout milliseconds after which search should be canceled @returns {Object} the linked list leading from `to` to `from` (sic!).
processNewPoints
javascript
GameJs/gamejs
src/gamejs/pathfinding.js
https://github.com/GameJs/gamejs/blob/master/src/gamejs/pathfinding.js
MIT