id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
8,100
dfahlander/Dexie.js
src/helpers/promise.js
function (callback, args) { microtickQueue.push([callback, args]); if (needsNewPhysicalTick) { schedulePhysicalTick(); needsNewPhysicalTick = false; } }
javascript
function (callback, args) { microtickQueue.push([callback, args]); if (needsNewPhysicalTick) { schedulePhysicalTick(); needsNewPhysicalTick = false; } }
[ "function", "(", "callback", ",", "args", ")", "{", "microtickQueue", ".", "push", "(", "[", "callback", ",", "args", "]", ")", ";", "if", "(", "needsNewPhysicalTick", ")", "{", "schedulePhysicalTick", "(", ")", ";", "needsNewPhysicalTick", "=", "false", ";", "}", "}" ]
Configurable through Promise.scheduler. Don't export because it would be unsafe to let unknown code call it unless they do try..catch within their callback. This function can be retrieved through getter of Promise.scheduler though, but users must not do Promise.scheduler = myFuncThatThrowsException
[ "Configurable", "through", "Promise", ".", "scheduler", ".", "Don", "t", "export", "because", "it", "would", "be", "unsafe", "to", "let", "unknown", "code", "call", "it", "unless", "they", "do", "try", "..", "catch", "within", "their", "callback", ".", "This", "function", "can", "be", "retrieved", "through", "getter", "of", "Promise", ".", "scheduler", "though", "but", "users", "must", "not", "do", "Promise", ".", "scheduler", "=", "myFuncThatThrowsException" ]
80b53e4df4ec82e5902d12eb8f3db5369b9bd6a8
https://github.com/dfahlander/Dexie.js/blob/80b53e4df4ec82e5902d12eb8f3db5369b9bd6a8/src/helpers/promise.js#L99-L105
8,101
dfahlander/Dexie.js
samples/remote-sync/websocket/websocketserver-shim.js
EmulatedWebSocketServerFactory
function EmulatedWebSocketServerFactory() { this.createServer = function (connectCallback) { var server = { _connect: function (socket) { var conn = { _client: socket, _listeners: { "text": [], "close": [] }, on: function (type, listener) { conn._listeners[type].push(listener); }, _fire: function (type, args) { conn._listeners[type].forEach(function (listener) { listener.apply(null, args); }); }, _text: function (msg) { conn._fire("text", [msg]); }, sendText: function (msg) { setTimeout(function () { conn._client._text(msg); }, 0); }, close: function (code, reason) { setTimeout(function () { conn._client._disconnect(code, reason); }, 0); }, _disconnect: function (code, reason) { conn._fire("close", [code, reason]); } }; connectCallback(conn); return conn; }, listen: function (port) { EmulatedWebSocketServerFactory.listeners[port] = this; return this; } } return server; } }
javascript
function EmulatedWebSocketServerFactory() { this.createServer = function (connectCallback) { var server = { _connect: function (socket) { var conn = { _client: socket, _listeners: { "text": [], "close": [] }, on: function (type, listener) { conn._listeners[type].push(listener); }, _fire: function (type, args) { conn._listeners[type].forEach(function (listener) { listener.apply(null, args); }); }, _text: function (msg) { conn._fire("text", [msg]); }, sendText: function (msg) { setTimeout(function () { conn._client._text(msg); }, 0); }, close: function (code, reason) { setTimeout(function () { conn._client._disconnect(code, reason); }, 0); }, _disconnect: function (code, reason) { conn._fire("close", [code, reason]); } }; connectCallback(conn); return conn; }, listen: function (port) { EmulatedWebSocketServerFactory.listeners[port] = this; return this; } } return server; } }
[ "function", "EmulatedWebSocketServerFactory", "(", ")", "{", "this", ".", "createServer", "=", "function", "(", "connectCallback", ")", "{", "var", "server", "=", "{", "_connect", ":", "function", "(", "socket", ")", "{", "var", "conn", "=", "{", "_client", ":", "socket", ",", "_listeners", ":", "{", "\"text\"", ":", "[", "]", ",", "\"close\"", ":", "[", "]", "}", ",", "on", ":", "function", "(", "type", ",", "listener", ")", "{", "conn", ".", "_listeners", "[", "type", "]", ".", "push", "(", "listener", ")", ";", "}", ",", "_fire", ":", "function", "(", "type", ",", "args", ")", "{", "conn", ".", "_listeners", "[", "type", "]", ".", "forEach", "(", "function", "(", "listener", ")", "{", "listener", ".", "apply", "(", "null", ",", "args", ")", ";", "}", ")", ";", "}", ",", "_text", ":", "function", "(", "msg", ")", "{", "conn", ".", "_fire", "(", "\"text\"", ",", "[", "msg", "]", ")", ";", "}", ",", "sendText", ":", "function", "(", "msg", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "conn", ".", "_client", ".", "_text", "(", "msg", ")", ";", "}", ",", "0", ")", ";", "}", ",", "close", ":", "function", "(", "code", ",", "reason", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "conn", ".", "_client", ".", "_disconnect", "(", "code", ",", "reason", ")", ";", "}", ",", "0", ")", ";", "}", ",", "_disconnect", ":", "function", "(", "code", ",", "reason", ")", "{", "conn", ".", "_fire", "(", "\"close\"", ",", "[", "code", ",", "reason", "]", ")", ";", "}", "}", ";", "connectCallback", "(", "conn", ")", ";", "return", "conn", ";", "}", ",", "listen", ":", "function", "(", "port", ")", "{", "EmulatedWebSocketServerFactory", ".", "listeners", "[", "port", "]", "=", "this", ";", "return", "this", ";", "}", "}", "return", "server", ";", "}", "}" ]
To be able to test both server and client in a browser, emulate a WebSocketServer in the browser, and replace the WebSocket api with an emulated WebSocket that communicates with emulated WebSocketServer.
[ "To", "be", "able", "to", "test", "both", "server", "and", "client", "in", "a", "browser", "emulate", "a", "WebSocketServer", "in", "the", "browser", "and", "replace", "the", "WebSocket", "api", "with", "an", "emulated", "WebSocket", "that", "communicates", "with", "emulated", "WebSocketServer", "." ]
80b53e4df4ec82e5902d12eb8f3db5369b9bd6a8
https://github.com/dfahlander/Dexie.js/blob/80b53e4df4ec82e5902d12eb8f3db5369b9bd6a8/samples/remote-sync/websocket/websocketserver-shim.js#L15-L58
8,102
bda-research/node-crawler
lib/crawler.js
getCharset
function getCharset(str){ var charset = (str && str.match(/charset=['"]?([\w.-]+)/i) || [0, null])[1]; return charset && charset.replace(/:\d{4}$|[^0-9a-z]/g, '') == 'gb2312' ? 'gbk' : charset; }
javascript
function getCharset(str){ var charset = (str && str.match(/charset=['"]?([\w.-]+)/i) || [0, null])[1]; return charset && charset.replace(/:\d{4}$|[^0-9a-z]/g, '') == 'gb2312' ? 'gbk' : charset; }
[ "function", "getCharset", "(", "str", ")", "{", "var", "charset", "=", "(", "str", "&&", "str", ".", "match", "(", "/", "charset=['\"]?([\\w.-]+)", "/", "i", ")", "||", "[", "0", ",", "null", "]", ")", "[", "1", "]", ";", "return", "charset", "&&", "charset", ".", "replace", "(", "/", ":\\d{4}$|[^0-9a-z]", "/", "g", ",", "''", ")", "==", "'gb2312'", "?", "'gbk'", ":", "charset", ";", "}" ]
Browsers treat gb2312 as gbk, but iconv-lite not. Replace gb2312 with gbk, in order to parse the pages which say gb2312 but actually are gbk.
[ "Browsers", "treat", "gb2312", "as", "gbk", "but", "iconv", "-", "lite", "not", ".", "Replace", "gb2312", "with", "gbk", "in", "order", "to", "parse", "the", "pages", "which", "say", "gb2312", "but", "actually", "are", "gbk", "." ]
9b77f9a8fa995cb431c7cbf5c033c0856583746b
https://github.com/bda-research/node-crawler/blob/9b77f9a8fa995cb431c7cbf5c033c0856583746b/lib/crawler.js#L439-L442
8,103
marmelab/gremlins.js
examples/touch/hammer.js
extend
function extend(dest, src, merge) { for(var key in src) { if(dest[key] !== undefined && merge) { continue; } dest[key] = src[key]; } return dest; }
javascript
function extend(dest, src, merge) { for(var key in src) { if(dest[key] !== undefined && merge) { continue; } dest[key] = src[key]; } return dest; }
[ "function", "extend", "(", "dest", ",", "src", ",", "merge", ")", "{", "for", "(", "var", "key", "in", "src", ")", "{", "if", "(", "dest", "[", "key", "]", "!==", "undefined", "&&", "merge", ")", "{", "continue", ";", "}", "dest", "[", "key", "]", "=", "src", "[", "key", "]", ";", "}", "return", "dest", ";", "}" ]
extend method, also used for cloning when dest is an empty object @param {Object} dest @param {Object} src @parm {Boolean} merge do a merge @returns {Object} dest
[ "extend", "method", "also", "used", "for", "cloning", "when", "dest", "is", "an", "empty", "object" ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/examples/touch/hammer.js#L126-L134
8,104
marmelab/gremlins.js
examples/touch/hammer.js
getVelocity
function getVelocity(delta_time, delta_x, delta_y) { return { x: Math.abs(delta_x / delta_time) || 0, y: Math.abs(delta_y / delta_time) || 0 }; }
javascript
function getVelocity(delta_time, delta_x, delta_y) { return { x: Math.abs(delta_x / delta_time) || 0, y: Math.abs(delta_y / delta_time) || 0 }; }
[ "function", "getVelocity", "(", "delta_time", ",", "delta_x", ",", "delta_y", ")", "{", "return", "{", "x", ":", "Math", ".", "abs", "(", "delta_x", "/", "delta_time", ")", "||", "0", ",", "y", ":", "Math", ".", "abs", "(", "delta_y", "/", "delta_time", ")", "||", "0", "}", ";", "}" ]
calculate the velocity between two points @param {Number} delta_time @param {Number} delta_x @param {Number} delta_y @returns {Object} velocity
[ "calculate", "the", "velocity", "between", "two", "points" ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/examples/touch/hammer.js#L231-L236
8,105
marmelab/gremlins.js
examples/touch/hammer.js
toggleDefaultBehavior
function toggleDefaultBehavior(element, css_props, toggle) { if(!css_props || !element || !element.style) { return; } // with css properties for modern browsers Utils.each(['webkit', 'moz', 'Moz', 'ms', 'o', ''], function setStyle(vendor) { Utils.each(css_props, function(value, prop) { // vender prefix at the property if(vendor) { prop = vendor + prop.substring(0, 1).toUpperCase() + prop.substring(1); } // set the style if(prop in element.style) { element.style[prop] = !toggle && value; } }); }); var false_fn = function(){ return false; }; // also the disable onselectstart if(css_props.userSelect == 'none') { element.onselectstart = !toggle && false_fn; } // and disable ondragstart if(css_props.userDrag == 'none') { element.ondragstart = !toggle && false_fn; } }
javascript
function toggleDefaultBehavior(element, css_props, toggle) { if(!css_props || !element || !element.style) { return; } // with css properties for modern browsers Utils.each(['webkit', 'moz', 'Moz', 'ms', 'o', ''], function setStyle(vendor) { Utils.each(css_props, function(value, prop) { // vender prefix at the property if(vendor) { prop = vendor + prop.substring(0, 1).toUpperCase() + prop.substring(1); } // set the style if(prop in element.style) { element.style[prop] = !toggle && value; } }); }); var false_fn = function(){ return false; }; // also the disable onselectstart if(css_props.userSelect == 'none') { element.onselectstart = !toggle && false_fn; } // and disable ondragstart if(css_props.userDrag == 'none') { element.ondragstart = !toggle && false_fn; } }
[ "function", "toggleDefaultBehavior", "(", "element", ",", "css_props", ",", "toggle", ")", "{", "if", "(", "!", "css_props", "||", "!", "element", "||", "!", "element", ".", "style", ")", "{", "return", ";", "}", "// with css properties for modern browsers", "Utils", ".", "each", "(", "[", "'webkit'", ",", "'moz'", ",", "'Moz'", ",", "'ms'", ",", "'o'", ",", "''", "]", ",", "function", "setStyle", "(", "vendor", ")", "{", "Utils", ".", "each", "(", "css_props", ",", "function", "(", "value", ",", "prop", ")", "{", "// vender prefix at the property", "if", "(", "vendor", ")", "{", "prop", "=", "vendor", "+", "prop", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "prop", ".", "substring", "(", "1", ")", ";", "}", "// set the style", "if", "(", "prop", "in", "element", ".", "style", ")", "{", "element", ".", "style", "[", "prop", "]", "=", "!", "toggle", "&&", "value", ";", "}", "}", ")", ";", "}", ")", ";", "var", "false_fn", "=", "function", "(", ")", "{", "return", "false", ";", "}", ";", "// also the disable onselectstart", "if", "(", "css_props", ".", "userSelect", "==", "'none'", ")", "{", "element", ".", "onselectstart", "=", "!", "toggle", "&&", "false_fn", ";", "}", "// and disable ondragstart", "if", "(", "css_props", ".", "userDrag", "==", "'none'", ")", "{", "element", ".", "ondragstart", "=", "!", "toggle", "&&", "false_fn", ";", "}", "}" ]
toggle browser default behavior with css props @param {HtmlElement} element @param {Object} css_props @param {Boolean} toggle
[ "toggle", "browser", "default", "behavior", "with", "css", "props" ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/examples/touch/hammer.js#L328-L357
8,106
marmelab/gremlins.js
examples/touch/hammer.js
dispose
function dispose() { var i, eh; // undo all changes made by stop_browser_behavior if(this.options.stop_browser_behavior) { Utils.toggleDefaultBehavior(this.element, this.options.stop_browser_behavior, true); } // unbind all custom event handlers for(i=-1; (eh=this.eventHandlers[++i]);) { this.element.removeEventListener(eh.gesture, eh.handler, false); } this.eventHandlers = []; // unbind the start event listener Event.unbindDom(this.element, Hammer.EVENT_TYPES[EVENT_START], this.eventStartHandler); return null; }
javascript
function dispose() { var i, eh; // undo all changes made by stop_browser_behavior if(this.options.stop_browser_behavior) { Utils.toggleDefaultBehavior(this.element, this.options.stop_browser_behavior, true); } // unbind all custom event handlers for(i=-1; (eh=this.eventHandlers[++i]);) { this.element.removeEventListener(eh.gesture, eh.handler, false); } this.eventHandlers = []; // unbind the start event listener Event.unbindDom(this.element, Hammer.EVENT_TYPES[EVENT_START], this.eventStartHandler); return null; }
[ "function", "dispose", "(", ")", "{", "var", "i", ",", "eh", ";", "// undo all changes made by stop_browser_behavior", "if", "(", "this", ".", "options", ".", "stop_browser_behavior", ")", "{", "Utils", ".", "toggleDefaultBehavior", "(", "this", ".", "element", ",", "this", ".", "options", ".", "stop_browser_behavior", ",", "true", ")", ";", "}", "// unbind all custom event handlers", "for", "(", "i", "=", "-", "1", ";", "(", "eh", "=", "this", ".", "eventHandlers", "[", "++", "i", "]", ")", ";", ")", "{", "this", ".", "element", ".", "removeEventListener", "(", "eh", ".", "gesture", ",", "eh", ".", "handler", ",", "false", ")", ";", "}", "this", ".", "eventHandlers", "=", "[", "]", ";", "// unbind the start event listener", "Event", ".", "unbindDom", "(", "this", ".", "element", ",", "Hammer", ".", "EVENT_TYPES", "[", "EVENT_START", "]", ",", "this", ".", "eventStartHandler", ")", ";", "return", "null", ";", "}" ]
dispose this hammer instance @returns {Hammer.Instance}
[ "dispose", "this", "hammer", "instance" ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/examples/touch/hammer.js#L490-L508
8,107
marmelab/gremlins.js
examples/touch/hammer.js
collectEventData
function collectEventData(element, eventType, touches, ev) { // find out pointerType var pointerType = POINTER_TOUCH; if(Utils.inStr(ev.type, 'mouse') || PointerEvent.matchType(POINTER_MOUSE, ev)) { pointerType = POINTER_MOUSE; } return { center : Utils.getCenter(touches), timeStamp : new Date().getTime(), target : ev.target, touches : touches, eventType : eventType, pointerType: pointerType, srcEvent : ev, /** * prevent the browser default actions * mostly used to disable scrolling of the browser */ preventDefault: function() { var srcEvent = this.srcEvent; srcEvent.preventManipulation && srcEvent.preventManipulation(); srcEvent.preventDefault && srcEvent.preventDefault(); }, /** * stop bubbling the event up to its parents */ stopPropagation: function() { this.srcEvent.stopPropagation(); }, /** * immediately stop gesture detection * might be useful after a swipe was detected * @return {*} */ stopDetect: function() { return Detection.stopDetect(); } }; }
javascript
function collectEventData(element, eventType, touches, ev) { // find out pointerType var pointerType = POINTER_TOUCH; if(Utils.inStr(ev.type, 'mouse') || PointerEvent.matchType(POINTER_MOUSE, ev)) { pointerType = POINTER_MOUSE; } return { center : Utils.getCenter(touches), timeStamp : new Date().getTime(), target : ev.target, touches : touches, eventType : eventType, pointerType: pointerType, srcEvent : ev, /** * prevent the browser default actions * mostly used to disable scrolling of the browser */ preventDefault: function() { var srcEvent = this.srcEvent; srcEvent.preventManipulation && srcEvent.preventManipulation(); srcEvent.preventDefault && srcEvent.preventDefault(); }, /** * stop bubbling the event up to its parents */ stopPropagation: function() { this.srcEvent.stopPropagation(); }, /** * immediately stop gesture detection * might be useful after a swipe was detected * @return {*} */ stopDetect: function() { return Detection.stopDetect(); } }; }
[ "function", "collectEventData", "(", "element", ",", "eventType", ",", "touches", ",", "ev", ")", "{", "// find out pointerType", "var", "pointerType", "=", "POINTER_TOUCH", ";", "if", "(", "Utils", ".", "inStr", "(", "ev", ".", "type", ",", "'mouse'", ")", "||", "PointerEvent", ".", "matchType", "(", "POINTER_MOUSE", ",", "ev", ")", ")", "{", "pointerType", "=", "POINTER_MOUSE", ";", "}", "return", "{", "center", ":", "Utils", ".", "getCenter", "(", "touches", ")", ",", "timeStamp", ":", "new", "Date", "(", ")", ".", "getTime", "(", ")", ",", "target", ":", "ev", ".", "target", ",", "touches", ":", "touches", ",", "eventType", ":", "eventType", ",", "pointerType", ":", "pointerType", ",", "srcEvent", ":", "ev", ",", "/**\n * prevent the browser default actions\n * mostly used to disable scrolling of the browser\n */", "preventDefault", ":", "function", "(", ")", "{", "var", "srcEvent", "=", "this", ".", "srcEvent", ";", "srcEvent", ".", "preventManipulation", "&&", "srcEvent", ".", "preventManipulation", "(", ")", ";", "srcEvent", ".", "preventDefault", "&&", "srcEvent", ".", "preventDefault", "(", ")", ";", "}", ",", "/**\n * stop bubbling the event up to its parents\n */", "stopPropagation", ":", "function", "(", ")", "{", "this", ".", "srcEvent", ".", "stopPropagation", "(", ")", ";", "}", ",", "/**\n * immediately stop gesture detection\n * might be useful after a swipe was detected\n * @return {*}\n */", "stopDetect", ":", "function", "(", ")", "{", "return", "Detection", ".", "stopDetect", "(", ")", ";", "}", "}", ";", "}" ]
collect event data for Hammer js @param {HTMLElement} element @param {String} eventType like EVENT_MOVE @param {Object} eventData
[ "collect", "event", "data", "for", "Hammer", "js" ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/examples/touch/hammer.js#L726-L768
8,108
marmelab/gremlins.js
examples/touch/hammer.js
getInterimData
function getInterimData(ev) { var lastEvent = this.current.lastEvent , angle , direction; // end events (e.g. dragend) don't have useful values for interimDirection & interimAngle // because the previous event has exactly the same coordinates // so for end events, take the previous values of interimDirection & interimAngle // instead of recalculating them and getting a spurious '0' if(ev.eventType == EVENT_END) { angle = lastEvent && lastEvent.interimAngle; direction = lastEvent && lastEvent.interimDirection; } else { angle = lastEvent && Utils.getAngle(lastEvent.center, ev.center); direction = lastEvent && Utils.getDirection(lastEvent.center, ev.center); } ev.interimAngle = angle; ev.interimDirection = direction; }
javascript
function getInterimData(ev) { var lastEvent = this.current.lastEvent , angle , direction; // end events (e.g. dragend) don't have useful values for interimDirection & interimAngle // because the previous event has exactly the same coordinates // so for end events, take the previous values of interimDirection & interimAngle // instead of recalculating them and getting a spurious '0' if(ev.eventType == EVENT_END) { angle = lastEvent && lastEvent.interimAngle; direction = lastEvent && lastEvent.interimDirection; } else { angle = lastEvent && Utils.getAngle(lastEvent.center, ev.center); direction = lastEvent && Utils.getDirection(lastEvent.center, ev.center); } ev.interimAngle = angle; ev.interimDirection = direction; }
[ "function", "getInterimData", "(", "ev", ")", "{", "var", "lastEvent", "=", "this", ".", "current", ".", "lastEvent", ",", "angle", ",", "direction", ";", "// end events (e.g. dragend) don't have useful values for interimDirection & interimAngle", "// because the previous event has exactly the same coordinates", "// so for end events, take the previous values of interimDirection & interimAngle", "// instead of recalculating them and getting a spurious '0'", "if", "(", "ev", ".", "eventType", "==", "EVENT_END", ")", "{", "angle", "=", "lastEvent", "&&", "lastEvent", ".", "interimAngle", ";", "direction", "=", "lastEvent", "&&", "lastEvent", ".", "interimDirection", ";", "}", "else", "{", "angle", "=", "lastEvent", "&&", "Utils", ".", "getAngle", "(", "lastEvent", ".", "center", ",", "ev", ".", "center", ")", ";", "direction", "=", "lastEvent", "&&", "Utils", ".", "getDirection", "(", "lastEvent", ".", "center", ",", "ev", ".", "center", ")", ";", "}", "ev", ".", "interimAngle", "=", "angle", ";", "ev", ".", "interimDirection", "=", "direction", ";", "}" ]
calculate interim angle and direction @param {Object} ev
[ "calculate", "interim", "angle", "and", "direction" ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/examples/touch/hammer.js#L987-L1007
8,109
marmelab/gremlins.js
examples/touch/main.js
round
function round(float, digits) { if(digits == null) { return Math.round(float); } var round = 10 * digits; return Math.round(float * round) / round; }
javascript
function round(float, digits) { if(digits == null) { return Math.round(float); } var round = 10 * digits; return Math.round(float * round) / round; }
[ "function", "round", "(", "float", ",", "digits", ")", "{", "if", "(", "digits", "==", "null", ")", "{", "return", "Math", ".", "round", "(", "float", ")", ";", "}", "var", "round", "=", "10", "*", "digits", ";", "return", "Math", ".", "round", "(", "float", "*", "round", ")", "/", "round", ";", "}" ]
round to 1 digit @param float @param [digits] @returns {number}
[ "round", "to", "1", "digit" ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/examples/touch/main.js#L35-L41
8,110
marmelab/gremlins.js
examples/touch/main.js
logHammerEvent
function logHammerEvent(ev) { if(!ev.gesture) { return; } // store last event, that should might match the gremlin if(ev.gesture.eventType == 'end') { testLogger.lastEvent = ev; } // highlight gesture var event_el = getLogElement('gesture', ev.type); event_el.className = 'active'; for(var i = 0, len = hammerProps.length; i < len; i++) { var prop = hammerProps[i]; var value = ev.gesture[prop]; switch(prop) { case 'center': value = value.pageX + 'x' + value.pageY; break; case 'gesture': value = ev.type; break; case 'target': value = ev.gesture.target.tagName; break; case 'touches': value = ev.gesture.touches.length; break; } getLogElement('prop', prop).innerHTML = value; } }
javascript
function logHammerEvent(ev) { if(!ev.gesture) { return; } // store last event, that should might match the gremlin if(ev.gesture.eventType == 'end') { testLogger.lastEvent = ev; } // highlight gesture var event_el = getLogElement('gesture', ev.type); event_el.className = 'active'; for(var i = 0, len = hammerProps.length; i < len; i++) { var prop = hammerProps[i]; var value = ev.gesture[prop]; switch(prop) { case 'center': value = value.pageX + 'x' + value.pageY; break; case 'gesture': value = ev.type; break; case 'target': value = ev.gesture.target.tagName; break; case 'touches': value = ev.gesture.touches.length; break; } getLogElement('prop', prop).innerHTML = value; } }
[ "function", "logHammerEvent", "(", "ev", ")", "{", "if", "(", "!", "ev", ".", "gesture", ")", "{", "return", ";", "}", "// store last event, that should might match the gremlin", "if", "(", "ev", ".", "gesture", ".", "eventType", "==", "'end'", ")", "{", "testLogger", ".", "lastEvent", "=", "ev", ";", "}", "// highlight gesture", "var", "event_el", "=", "getLogElement", "(", "'gesture'", ",", "ev", ".", "type", ")", ";", "event_el", ".", "className", "=", "'active'", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "hammerProps", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "prop", "=", "hammerProps", "[", "i", "]", ";", "var", "value", "=", "ev", ".", "gesture", "[", "prop", "]", ";", "switch", "(", "prop", ")", "{", "case", "'center'", ":", "value", "=", "value", ".", "pageX", "+", "'x'", "+", "value", ".", "pageY", ";", "break", ";", "case", "'gesture'", ":", "value", "=", "ev", ".", "type", ";", "break", ";", "case", "'target'", ":", "value", "=", "ev", ".", "gesture", ".", "target", ".", "tagName", ";", "break", ";", "case", "'touches'", ":", "value", "=", "ev", ".", "gesture", ".", "touches", ".", "length", ";", "break", ";", "}", "getLogElement", "(", "'prop'", ",", "prop", ")", ".", "innerHTML", "=", "value", ";", "}", "}" ]
highlight the triggered event and update the log values @param ev
[ "highlight", "the", "triggered", "event", "and", "update", "the", "log", "values" ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/examples/touch/main.js#L48-L81
8,111
marmelab/gremlins.js
examples/TodoMVC/bower_components/backbone/backbone.js
function(attrs, options) { if (!options.validate || !this.validate) return true; attrs = _.extend({}, this.attributes, attrs); var error = this.validationError = this.validate(attrs, options) || null; if (!error) return true; this.trigger('invalid', this, error, _.extend(options, {validationError: error})); return false; }
javascript
function(attrs, options) { if (!options.validate || !this.validate) return true; attrs = _.extend({}, this.attributes, attrs); var error = this.validationError = this.validate(attrs, options) || null; if (!error) return true; this.trigger('invalid', this, error, _.extend(options, {validationError: error})); return false; }
[ "function", "(", "attrs", ",", "options", ")", "{", "if", "(", "!", "options", ".", "validate", "||", "!", "this", ".", "validate", ")", "return", "true", ";", "attrs", "=", "_", ".", "extend", "(", "{", "}", ",", "this", ".", "attributes", ",", "attrs", ")", ";", "var", "error", "=", "this", ".", "validationError", "=", "this", ".", "validate", "(", "attrs", ",", "options", ")", "||", "null", ";", "if", "(", "!", "error", ")", "return", "true", ";", "this", ".", "trigger", "(", "'invalid'", ",", "this", ",", "error", ",", "_", ".", "extend", "(", "options", ",", "{", "validationError", ":", "error", "}", ")", ")", ";", "return", "false", ";", "}" ]
Run validation against the next complete set of model attributes, returning `true` if all is well. Otherwise, fire an `"invalid"` event.
[ "Run", "validation", "against", "the", "next", "complete", "set", "of", "model", "attributes", "returning", "true", "if", "all", "is", "well", ".", "Otherwise", "fire", "an", "invalid", "event", "." ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/examples/TodoMVC/bower_components/backbone/backbone.js#L559-L566
8,112
marmelab/gremlins.js
examples/TodoMVC/bower_components/backbone/backbone.js
function(models, options) { return this.set(models, _.extend({merge: false}, options, addOptions)); }
javascript
function(models, options) { return this.set(models, _.extend({merge: false}, options, addOptions)); }
[ "function", "(", "models", ",", "options", ")", "{", "return", "this", ".", "set", "(", "models", ",", "_", ".", "extend", "(", "{", "merge", ":", "false", "}", ",", "options", ",", "addOptions", ")", ")", ";", "}" ]
Add a model, or list of models to the set.
[ "Add", "a", "model", "or", "list", "of", "models", "to", "the", "set", "." ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/examples/TodoMVC/bower_components/backbone/backbone.js#L631-L633
8,113
marmelab/gremlins.js
src/mogwais/gizmo.js
incrementNbErrors
function incrementNbErrors() { nbErrors++; if (nbErrors == config.maxErrors) { horde.stop(); if (!config.logger) return; window.setTimeout(function() { // display the mogwai error after the caught error config.logger.warn('mogwai ', 'gizmo ', 'stopped test execution after ', config.maxErrors, 'errors'); }, 4); } }
javascript
function incrementNbErrors() { nbErrors++; if (nbErrors == config.maxErrors) { horde.stop(); if (!config.logger) return; window.setTimeout(function() { // display the mogwai error after the caught error config.logger.warn('mogwai ', 'gizmo ', 'stopped test execution after ', config.maxErrors, 'errors'); }, 4); } }
[ "function", "incrementNbErrors", "(", ")", "{", "nbErrors", "++", ";", "if", "(", "nbErrors", "==", "config", ".", "maxErrors", ")", "{", "horde", ".", "stop", "(", ")", ";", "if", "(", "!", "config", ".", "logger", ")", "return", ";", "window", ".", "setTimeout", "(", "function", "(", ")", "{", "// display the mogwai error after the caught error", "config", ".", "logger", ".", "warn", "(", "'mogwai '", ",", "'gizmo '", ",", "'stopped test execution after '", ",", "config", ".", "maxErrors", ",", "'errors'", ")", ";", "}", ",", "4", ")", ";", "}", "}" ]
this is exceptional - don't use 'this' for mogwais in general
[ "this", "is", "exceptional", "-", "don", "t", "use", "this", "for", "mogwais", "in", "general" ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/src/mogwais/gizmo.js#L45-L55
8,114
marmelab/gremlins.js
src/utils/executeInSeries.js
executeInSeries
function executeInSeries(callbacks, args, context, done) { var nbArguments = args.length; callbacks = callbacks.slice(0); // clone the array to avoid modifying the original var iterator = function(callbacks, args) { if (!callbacks.length) { return typeof done === 'function' ? done() : true; } var callback = callbacks.shift(); callback.apply(context, args); // Is the callback synchronous ? if (callback.length === nbArguments) { iterator(callbacks, args, done); } }; args.push(function(){ iterator(callbacks, args, done); }); iterator(callbacks, args, done); }
javascript
function executeInSeries(callbacks, args, context, done) { var nbArguments = args.length; callbacks = callbacks.slice(0); // clone the array to avoid modifying the original var iterator = function(callbacks, args) { if (!callbacks.length) { return typeof done === 'function' ? done() : true; } var callback = callbacks.shift(); callback.apply(context, args); // Is the callback synchronous ? if (callback.length === nbArguments) { iterator(callbacks, args, done); } }; args.push(function(){ iterator(callbacks, args, done); }); iterator(callbacks, args, done); }
[ "function", "executeInSeries", "(", "callbacks", ",", "args", ",", "context", ",", "done", ")", "{", "var", "nbArguments", "=", "args", ".", "length", ";", "callbacks", "=", "callbacks", ".", "slice", "(", "0", ")", ";", "// clone the array to avoid modifying the original", "var", "iterator", "=", "function", "(", "callbacks", ",", "args", ")", "{", "if", "(", "!", "callbacks", ".", "length", ")", "{", "return", "typeof", "done", "===", "'function'", "?", "done", "(", ")", ":", "true", ";", "}", "var", "callback", "=", "callbacks", ".", "shift", "(", ")", ";", "callback", ".", "apply", "(", "context", ",", "args", ")", ";", "// Is the callback synchronous ?", "if", "(", "callback", ".", "length", "===", "nbArguments", ")", "{", "iterator", "(", "callbacks", ",", "args", ",", "done", ")", ";", "}", "}", ";", "args", ".", "push", "(", "function", "(", ")", "{", "iterator", "(", "callbacks", ",", "args", ",", "done", ")", ";", "}", ")", ";", "iterator", "(", "callbacks", ",", "args", ",", "done", ")", ";", "}" ]
Execute a list of functions one after the other. Functions can be asynchronous or asynchronous, they will always be executed in the order of the list. @param {Function[]} callbacks - The functions to execute @param {Array} args - The arguments passed to each function @param {Object|null} context - The object the functions must be bound to @param {Function} done - The final callback to execute once all functions are executed
[ "Execute", "a", "list", "of", "functions", "one", "after", "the", "other", "." ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/src/utils/executeInSeries.js#L15-L38
8,115
marmelab/gremlins.js
src/utils/executeInSeries.js
function(callbacks, args) { if (!callbacks.length) { return typeof done === 'function' ? done() : true; } var callback = callbacks.shift(); callback.apply(context, args); // Is the callback synchronous ? if (callback.length === nbArguments) { iterator(callbacks, args, done); } }
javascript
function(callbacks, args) { if (!callbacks.length) { return typeof done === 'function' ? done() : true; } var callback = callbacks.shift(); callback.apply(context, args); // Is the callback synchronous ? if (callback.length === nbArguments) { iterator(callbacks, args, done); } }
[ "function", "(", "callbacks", ",", "args", ")", "{", "if", "(", "!", "callbacks", ".", "length", ")", "{", "return", "typeof", "done", "===", "'function'", "?", "done", "(", ")", ":", "true", ";", "}", "var", "callback", "=", "callbacks", ".", "shift", "(", ")", ";", "callback", ".", "apply", "(", "context", ",", "args", ")", ";", "// Is the callback synchronous ?", "if", "(", "callback", ".", "length", "===", "nbArguments", ")", "{", "iterator", "(", "callbacks", ",", "args", ",", "done", ")", ";", "}", "}" ]
clone the array to avoid modifying the original
[ "clone", "the", "array", "to", "avoid", "modifying", "the", "original" ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/src/utils/executeInSeries.js#L19-L31
8,116
marmelab/gremlins.js
src/vendor/chance.js
initOptions
function initOptions(options, defaults) { options || (options = {}); if (!defaults) { return options; } for (var i in defaults) { if (typeof options[i] === 'undefined') { options[i] = defaults[i]; } } return options; }
javascript
function initOptions(options, defaults) { options || (options = {}); if (!defaults) { return options; } for (var i in defaults) { if (typeof options[i] === 'undefined') { options[i] = defaults[i]; } } return options; }
[ "function", "initOptions", "(", "options", ",", "defaults", ")", "{", "options", "||", "(", "options", "=", "{", "}", ")", ";", "if", "(", "!", "defaults", ")", "{", "return", "options", ";", "}", "for", "(", "var", "i", "in", "defaults", ")", "{", "if", "(", "typeof", "options", "[", "i", "]", "===", "'undefined'", ")", "{", "options", "[", "i", "]", "=", "defaults", "[", "i", "]", ";", "}", "}", "return", "options", ";", "}" ]
Random helper functions
[ "Random", "helper", "functions" ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/src/vendor/chance.js#L37-L48
8,117
marmelab/gremlins.js
src/species/toucher.js
triggerTouch
function triggerTouch(touches, element, type) { var touchlist = [], event = document.createEvent('Event'); event.initEvent('touch' + type, true, true); touchlist.identifiedTouch = touchlist.item = function(index) { return this[index] || {}; }; touches.forEach(function(touch, i) { var x = Math.round(touch.x), y = Math.round(touch.y); touchlist.push({ pageX: x, pageY: y, clientX: x, clientY: y, screenX: x, screenY: y, target: element, identifier: i }); }); event.touches = (type == 'end') ? [] : touchlist; event.targetTouches = (type == 'end') ? [] : touchlist; event.changedTouches = touchlist; element.dispatchEvent(event); config.showAction(touches); }
javascript
function triggerTouch(touches, element, type) { var touchlist = [], event = document.createEvent('Event'); event.initEvent('touch' + type, true, true); touchlist.identifiedTouch = touchlist.item = function(index) { return this[index] || {}; }; touches.forEach(function(touch, i) { var x = Math.round(touch.x), y = Math.round(touch.y); touchlist.push({ pageX: x, pageY: y, clientX: x, clientY: y, screenX: x, screenY: y, target: element, identifier: i }); }); event.touches = (type == 'end') ? [] : touchlist; event.targetTouches = (type == 'end') ? [] : touchlist; event.changedTouches = touchlist; element.dispatchEvent(event); config.showAction(touches); }
[ "function", "triggerTouch", "(", "touches", ",", "element", ",", "type", ")", "{", "var", "touchlist", "=", "[", "]", ",", "event", "=", "document", ".", "createEvent", "(", "'Event'", ")", ";", "event", ".", "initEvent", "(", "'touch'", "+", "type", ",", "true", ",", "true", ")", ";", "touchlist", ".", "identifiedTouch", "=", "touchlist", ".", "item", "=", "function", "(", "index", ")", "{", "return", "this", "[", "index", "]", "||", "{", "}", ";", "}", ";", "touches", ".", "forEach", "(", "function", "(", "touch", ",", "i", ")", "{", "var", "x", "=", "Math", ".", "round", "(", "touch", ".", "x", ")", ",", "y", "=", "Math", ".", "round", "(", "touch", ".", "y", ")", ";", "touchlist", ".", "push", "(", "{", "pageX", ":", "x", ",", "pageY", ":", "y", ",", "clientX", ":", "x", ",", "clientY", ":", "y", ",", "screenX", ":", "x", ",", "screenY", ":", "y", ",", "target", ":", "element", ",", "identifier", ":", "i", "}", ")", ";", "}", ")", ";", "event", ".", "touches", "=", "(", "type", "==", "'end'", ")", "?", "[", "]", ":", "touchlist", ";", "event", ".", "targetTouches", "=", "(", "type", "==", "'end'", ")", "?", "[", "]", ":", "touchlist", ";", "event", ".", "changedTouches", "=", "touchlist", ";", "element", ".", "dispatchEvent", "(", "event", ")", ";", "config", ".", "showAction", "(", "touches", ")", ";", "}" ]
trigger a touchevent @param touches @param element @param type
[ "trigger", "a", "touchevent" ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/src/species/toucher.js#L147-L178
8,118
marmelab/gremlins.js
src/species/toucher.js
tap
function tap(position, element, done) { var touches = getTouches(position, 1); var gesture = { duration: config.randomizer.integer({ min: 20, max: 700 }) }; triggerTouch(touches, element, 'start'); setTimeout(function() { triggerTouch(touches, element, 'end'); done(touches, gesture); }, gesture.duration); }
javascript
function tap(position, element, done) { var touches = getTouches(position, 1); var gesture = { duration: config.randomizer.integer({ min: 20, max: 700 }) }; triggerTouch(touches, element, 'start'); setTimeout(function() { triggerTouch(touches, element, 'end'); done(touches, gesture); }, gesture.duration); }
[ "function", "tap", "(", "position", ",", "element", ",", "done", ")", "{", "var", "touches", "=", "getTouches", "(", "position", ",", "1", ")", ";", "var", "gesture", "=", "{", "duration", ":", "config", ".", "randomizer", ".", "integer", "(", "{", "min", ":", "20", ",", "max", ":", "700", "}", ")", "}", ";", "triggerTouch", "(", "touches", ",", "element", ",", "'start'", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "triggerTouch", "(", "touches", ",", "element", ",", "'end'", ")", ";", "done", "(", "touches", ",", "gesture", ")", ";", "}", ",", "gesture", ".", "duration", ")", ";", "}" ]
tap, like a click event, only 1 touch could also be a slow tap, that could turn out to be a hold
[ "tap", "like", "a", "click", "event", "only", "1", "touch", "could", "also", "be", "a", "slow", "tap", "that", "could", "turn", "out", "to", "be", "a", "hold" ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/src/species/toucher.js#L227-L239
8,119
marmelab/gremlins.js
src/species/toucher.js
doubletap
function doubletap(position, element, done) { touchTypes.tap(position, element, function() { setTimeout(function() { touchTypes.tap(position, element, done); }, 30); }); }
javascript
function doubletap(position, element, done) { touchTypes.tap(position, element, function() { setTimeout(function() { touchTypes.tap(position, element, done); }, 30); }); }
[ "function", "doubletap", "(", "position", ",", "element", ",", "done", ")", "{", "touchTypes", ".", "tap", "(", "position", ",", "element", ",", "function", "(", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "touchTypes", ".", "tap", "(", "position", ",", "element", ",", "done", ")", ";", "}", ",", "30", ")", ";", "}", ")", ";", "}" ]
doubletap, like a dblclick event, only 1 touch could also be a slow doubletap, that could turn out to be a hold
[ "doubletap", "like", "a", "dblclick", "event", "only", "1", "touch", "could", "also", "be", "a", "slow", "doubletap", "that", "could", "turn", "out", "to", "be", "a", "hold" ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/src/species/toucher.js#L243-L249
8,120
marmelab/gremlins.js
src/species/toucher.js
gesture
function gesture(position, element, done) { var gesture = { distanceX: config.randomizer.integer({ min: -100, max: 200 }), distanceY: config.randomizer.integer({ min: -100, max: 200 }), duration: config.randomizer.integer({ min: 20, max: 500 }) }; var touches = getTouches(position, 1, gesture.radius); triggerGesture(element, position, touches, gesture, function(touches) { done(touches, gesture); }); }
javascript
function gesture(position, element, done) { var gesture = { distanceX: config.randomizer.integer({ min: -100, max: 200 }), distanceY: config.randomizer.integer({ min: -100, max: 200 }), duration: config.randomizer.integer({ min: 20, max: 500 }) }; var touches = getTouches(position, 1, gesture.radius); triggerGesture(element, position, touches, gesture, function(touches) { done(touches, gesture); }); }
[ "function", "gesture", "(", "position", ",", "element", ",", "done", ")", "{", "var", "gesture", "=", "{", "distanceX", ":", "config", ".", "randomizer", ".", "integer", "(", "{", "min", ":", "-", "100", ",", "max", ":", "200", "}", ")", ",", "distanceY", ":", "config", ".", "randomizer", ".", "integer", "(", "{", "min", ":", "-", "100", ",", "max", ":", "200", "}", ")", ",", "duration", ":", "config", ".", "randomizer", ".", "integer", "(", "{", "min", ":", "20", ",", "max", ":", "500", "}", ")", "}", ";", "var", "touches", "=", "getTouches", "(", "position", ",", "1", ",", "gesture", ".", "radius", ")", ";", "triggerGesture", "(", "element", ",", "position", ",", "touches", ",", "gesture", ",", "function", "(", "touches", ")", "{", "done", "(", "touches", ",", "gesture", ")", ";", "}", ")", ";", "}" ]
single touch gesture, could be a drag and swipe, with 1 points
[ "single", "touch", "gesture", "could", "be", "a", "drag", "and", "swipe", "with", "1", "points" ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/src/species/toucher.js#L252-L263
8,121
marmelab/gremlins.js
src/species/toucher.js
multitouch
function multitouch(position, element, done) { var points = config.randomizer.integer({ min: 2, max: config.maxTouches}); var gesture = { scale: config.randomizer.floating({ min: 0, max: 2 }), rotation: config.randomizer.natural({ min: -100, max: 100 }), radius: config.randomizer.integer({ min: 50, max: 200 }), distanceX: config.randomizer.integer({ min: -20, max: 20 }), distanceY: config.randomizer.integer({ min: -20, max: 20 }), duration: config.randomizer.integer({ min: 100, max: 1500 }) }; var touches = getTouches(position, points, gesture.radius); triggerGesture(element, position, touches, gesture, function(touches) { done(touches, gesture); }); }
javascript
function multitouch(position, element, done) { var points = config.randomizer.integer({ min: 2, max: config.maxTouches}); var gesture = { scale: config.randomizer.floating({ min: 0, max: 2 }), rotation: config.randomizer.natural({ min: -100, max: 100 }), radius: config.randomizer.integer({ min: 50, max: 200 }), distanceX: config.randomizer.integer({ min: -20, max: 20 }), distanceY: config.randomizer.integer({ min: -20, max: 20 }), duration: config.randomizer.integer({ min: 100, max: 1500 }) }; var touches = getTouches(position, points, gesture.radius); triggerGesture(element, position, touches, gesture, function(touches) { done(touches, gesture); }); }
[ "function", "multitouch", "(", "position", ",", "element", ",", "done", ")", "{", "var", "points", "=", "config", ".", "randomizer", ".", "integer", "(", "{", "min", ":", "2", ",", "max", ":", "config", ".", "maxTouches", "}", ")", ";", "var", "gesture", "=", "{", "scale", ":", "config", ".", "randomizer", ".", "floating", "(", "{", "min", ":", "0", ",", "max", ":", "2", "}", ")", ",", "rotation", ":", "config", ".", "randomizer", ".", "natural", "(", "{", "min", ":", "-", "100", ",", "max", ":", "100", "}", ")", ",", "radius", ":", "config", ".", "randomizer", ".", "integer", "(", "{", "min", ":", "50", ",", "max", ":", "200", "}", ")", ",", "distanceX", ":", "config", ".", "randomizer", ".", "integer", "(", "{", "min", ":", "-", "20", ",", "max", ":", "20", "}", ")", ",", "distanceY", ":", "config", ".", "randomizer", ".", "integer", "(", "{", "min", ":", "-", "20", ",", "max", ":", "20", "}", ")", ",", "duration", ":", "config", ".", "randomizer", ".", "integer", "(", "{", "min", ":", "100", ",", "max", ":", "1500", "}", ")", "}", ";", "var", "touches", "=", "getTouches", "(", "position", ",", "points", ",", "gesture", ".", "radius", ")", ";", "triggerGesture", "(", "element", ",", "position", ",", "touches", ",", "gesture", ",", "function", "(", "touches", ")", "{", "done", "(", "touches", ",", "gesture", ")", ";", "}", ")", ";", "}" ]
multitouch gesture, could be a drag, swipe, pinch and rotate, with 2 or more points
[ "multitouch", "gesture", "could", "be", "a", "drag", "swipe", "pinch", "and", "rotate", "with", "2", "or", "more", "points" ]
2735fa5253cbefcb8848ea40825a6426fc04c398
https://github.com/marmelab/gremlins.js/blob/2735fa5253cbefcb8848ea40825a6426fc04c398/src/species/toucher.js#L266-L281
8,122
hoodiehq/hoodie
cli/parse-options.js
parseOptions
function parseOptions (options) { var dbOptions = {} var config = { name: options.name, loglevel: options.loglevel, paths: { data: options.data, public: options.public }, plugins: options.plugins, app: options.app, inMemory: Boolean(options.inMemory), client: options.client } log.level = config.loglevel if (options.url) { config.url = options.url } if (options.adminPassword) { config.adminPassword = options.adminPassword } PouchDB.plugin(require('pouchdb-mapreduce')) options.dbUrl = createAuthDbUrl(log, options.dbUrlUsername, options.dbUrlPassword, options.dbUrl) if (options.dbUrl) { PouchDB.plugin(require('pouchdb-adapter-http')) dbOptions.prefix = options.dbUrl log.info('config', 'Storing all data in ' + options.dbUrl) } else if (options.inMemory) { PouchDB.plugin(require('pouchdb-adapter-memory')) config.inMemory = true log.info('config', 'Storing all data in memory only') } else { PouchDB.plugin(require(options.dbAdapter)) dbOptions.prefix = path.join(config.paths.data, 'data') + path.sep log.info('config', 'Storing all data in ' + dbOptions.prefix + ' using ' + options.dbAdapter) } config.PouchDB = PouchDB.defaults(dbOptions) return config }
javascript
function parseOptions (options) { var dbOptions = {} var config = { name: options.name, loglevel: options.loglevel, paths: { data: options.data, public: options.public }, plugins: options.plugins, app: options.app, inMemory: Boolean(options.inMemory), client: options.client } log.level = config.loglevel if (options.url) { config.url = options.url } if (options.adminPassword) { config.adminPassword = options.adminPassword } PouchDB.plugin(require('pouchdb-mapreduce')) options.dbUrl = createAuthDbUrl(log, options.dbUrlUsername, options.dbUrlPassword, options.dbUrl) if (options.dbUrl) { PouchDB.plugin(require('pouchdb-adapter-http')) dbOptions.prefix = options.dbUrl log.info('config', 'Storing all data in ' + options.dbUrl) } else if (options.inMemory) { PouchDB.plugin(require('pouchdb-adapter-memory')) config.inMemory = true log.info('config', 'Storing all data in memory only') } else { PouchDB.plugin(require(options.dbAdapter)) dbOptions.prefix = path.join(config.paths.data, 'data') + path.sep log.info('config', 'Storing all data in ' + dbOptions.prefix + ' using ' + options.dbAdapter) } config.PouchDB = PouchDB.defaults(dbOptions) return config }
[ "function", "parseOptions", "(", "options", ")", "{", "var", "dbOptions", "=", "{", "}", "var", "config", "=", "{", "name", ":", "options", ".", "name", ",", "loglevel", ":", "options", ".", "loglevel", ",", "paths", ":", "{", "data", ":", "options", ".", "data", ",", "public", ":", "options", ".", "public", "}", ",", "plugins", ":", "options", ".", "plugins", ",", "app", ":", "options", ".", "app", ",", "inMemory", ":", "Boolean", "(", "options", ".", "inMemory", ")", ",", "client", ":", "options", ".", "client", "}", "log", ".", "level", "=", "config", ".", "loglevel", "if", "(", "options", ".", "url", ")", "{", "config", ".", "url", "=", "options", ".", "url", "}", "if", "(", "options", ".", "adminPassword", ")", "{", "config", ".", "adminPassword", "=", "options", ".", "adminPassword", "}", "PouchDB", ".", "plugin", "(", "require", "(", "'pouchdb-mapreduce'", ")", ")", "options", ".", "dbUrl", "=", "createAuthDbUrl", "(", "log", ",", "options", ".", "dbUrlUsername", ",", "options", ".", "dbUrlPassword", ",", "options", ".", "dbUrl", ")", "if", "(", "options", ".", "dbUrl", ")", "{", "PouchDB", ".", "plugin", "(", "require", "(", "'pouchdb-adapter-http'", ")", ")", "dbOptions", ".", "prefix", "=", "options", ".", "dbUrl", "log", ".", "info", "(", "'config'", ",", "'Storing all data in '", "+", "options", ".", "dbUrl", ")", "}", "else", "if", "(", "options", ".", "inMemory", ")", "{", "PouchDB", ".", "plugin", "(", "require", "(", "'pouchdb-adapter-memory'", ")", ")", "config", ".", "inMemory", "=", "true", "log", ".", "info", "(", "'config'", ",", "'Storing all data in memory only'", ")", "}", "else", "{", "PouchDB", ".", "plugin", "(", "require", "(", "options", ".", "dbAdapter", ")", ")", "dbOptions", ".", "prefix", "=", "path", ".", "join", "(", "config", ".", "paths", ".", "data", ",", "'data'", ")", "+", "path", ".", "sep", "log", ".", "info", "(", "'config'", ",", "'Storing all data in '", "+", "dbOptions", ".", "prefix", "+", "' using '", "+", "options", ".", "dbAdapter", ")", "}", "config", ".", "PouchDB", "=", "PouchDB", ".", "defaults", "(", "dbOptions", ")", "return", "config", "}" ]
Parse options into internal config structure. Options are all the things that users can pass in to Hoodie as described at https://github.com/hoodiehq/hoodie#usage. All these options are flat, while internally we group theem into db, connection and path options. `appOptions` are app-specific default options configured in the app’s package.json (on the `"hoodie"` key). The parsing of the database configuration is a bit more complex. If `dbUrl` is passed it means that a remote CouchDB is used for persistance, otherwise PouchDB is being used. A shortcut to set PouchDB’s adapter to memdown is to passe set the `inMemory: true` option. If it’s not set, leveldown is used with the prefix set to `options.data` + 'data' (`.hoodie/data` by default).
[ "Parse", "options", "into", "internal", "config", "structure", "." ]
f1c0e2f5c94ec4041bdb078ed5af21e6ad188156
https://github.com/hoodiehq/hoodie/blob/f1c0e2f5c94ec4041bdb078ed5af21e6ad188156/cli/parse-options.js#L29-L75
8,123
danielcaldas/react-d3-graph
src/components/marker/marker.helper.js
_getMarkerSize
function _getMarkerSize(transform, mMax, lMax) { if (transform < mMax) { return SIZES.S; } else if (transform >= mMax && transform < lMax) { return SIZES.M; } else { return SIZES.L; } }
javascript
function _getMarkerSize(transform, mMax, lMax) { if (transform < mMax) { return SIZES.S; } else if (transform >= mMax && transform < lMax) { return SIZES.M; } else { return SIZES.L; } }
[ "function", "_getMarkerSize", "(", "transform", ",", "mMax", ",", "lMax", ")", "{", "if", "(", "transform", "<", "mMax", ")", "{", "return", "SIZES", ".", "S", ";", "}", "else", "if", "(", "transform", ">=", "mMax", "&&", "transform", "<", "lMax", ")", "{", "return", "SIZES", ".", "M", ";", "}", "else", "{", "return", "SIZES", ".", "L", ";", "}", "}" ]
This functions returns the proper marker size given the inputs that describe the scenario where the marker is to be applied. @param {number} transform - the delta zoom value to calculate resize transformations. @param {number} mMax - a derived value from the max zoom config. @param {number} lMax - a derived value from the min zoom config. @returns {string} the size. @memberof Marker/helper
[ "This", "functions", "returns", "the", "proper", "marker", "size", "given", "the", "inputs", "that", "describe", "the", "scenario", "where", "the", "marker", "is", "to", "be", "applied", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/components/marker/marker.helper.js#L29-L37
8,124
danielcaldas/react-d3-graph
src/components/marker/marker.helper.js
_computeMarkerId
function _computeMarkerId(highlight, transform, { maxZoom }) { const mMax = maxZoom / 4; const lMax = maxZoom / 2; const size = _getMarkerSize(transform, mMax, lMax); const highlighted = highlight ? HIGHLIGHTED : ""; const markerKey = _markerKeyBuilder(size, highlighted); return MARKERS[markerKey]; }
javascript
function _computeMarkerId(highlight, transform, { maxZoom }) { const mMax = maxZoom / 4; const lMax = maxZoom / 2; const size = _getMarkerSize(transform, mMax, lMax); const highlighted = highlight ? HIGHLIGHTED : ""; const markerKey = _markerKeyBuilder(size, highlighted); return MARKERS[markerKey]; }
[ "function", "_computeMarkerId", "(", "highlight", ",", "transform", ",", "{", "maxZoom", "}", ")", "{", "const", "mMax", "=", "maxZoom", "/", "4", ";", "const", "lMax", "=", "maxZoom", "/", "2", ";", "const", "size", "=", "_getMarkerSize", "(", "transform", ",", "mMax", ",", "lMax", ")", ";", "const", "highlighted", "=", "highlight", "?", "HIGHLIGHTED", ":", "\"\"", ";", "const", "markerKey", "=", "_markerKeyBuilder", "(", "size", ",", "highlighted", ")", ";", "return", "MARKERS", "[", "markerKey", "]", ";", "}" ]
This function holds logic to retrieve the appropriate marker id that reflects the input parameters, markers can vary with highlight and transform value. @param {boolean} highlight - tells us whether or not some element (link or node) is highlighted. @param {number} transform - the delta zoom value to calculate resize transformations. @param {Object} config - the graph config object. @returns {string} the id of the result marker. @memberof Marker/helper
[ "This", "function", "holds", "logic", "to", "retrieve", "the", "appropriate", "marker", "id", "that", "reflects", "the", "input", "parameters", "markers", "can", "vary", "with", "highlight", "and", "transform", "value", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/components/marker/marker.helper.js#L48-L56
8,125
danielcaldas/react-d3-graph
src/components/marker/marker.helper.js
_memoizedComputeMarkerId
function _memoizedComputeMarkerId() { let cache = {}; return (highlight, transform, { maxZoom }) => { const cacheKey = `${highlight};${transform};${maxZoom}`; if (cache[cacheKey]) { return cache[cacheKey]; } const markerId = _computeMarkerId(highlight, transform, { maxZoom }); cache[cacheKey] = markerId; return markerId; }; }
javascript
function _memoizedComputeMarkerId() { let cache = {}; return (highlight, transform, { maxZoom }) => { const cacheKey = `${highlight};${transform};${maxZoom}`; if (cache[cacheKey]) { return cache[cacheKey]; } const markerId = _computeMarkerId(highlight, transform, { maxZoom }); cache[cacheKey] = markerId; return markerId; }; }
[ "function", "_memoizedComputeMarkerId", "(", ")", "{", "let", "cache", "=", "{", "}", ";", "return", "(", "highlight", ",", "transform", ",", "{", "maxZoom", "}", ")", "=>", "{", "const", "cacheKey", "=", "`", "${", "highlight", "}", "${", "transform", "}", "${", "maxZoom", "}", "`", ";", "if", "(", "cache", "[", "cacheKey", "]", ")", "{", "return", "cache", "[", "cacheKey", "]", ";", "}", "const", "markerId", "=", "_computeMarkerId", "(", "highlight", ",", "transform", ",", "{", "maxZoom", "}", ")", ";", "cache", "[", "cacheKey", "]", "=", "markerId", ";", "return", "markerId", ";", "}", ";", "}" ]
This function memoize results for _computeMarkerId since many of the times user will be playing around with the same zoom factor, we can take advantage of this and cache the results for a given combination of highlight state, zoom transform value and maxZoom config. @returns{Function} memoize wrapper to the _computeMarkerId operation. @memberof Marker/helper
[ "This", "function", "memoize", "results", "for", "_computeMarkerId", "since", "many", "of", "the", "times", "user", "will", "be", "playing", "around", "with", "the", "same", "zoom", "factor", "we", "can", "take", "advantage", "of", "this", "and", "cache", "the", "results", "for", "a", "given", "combination", "of", "highlight", "state", "zoom", "transform", "value", "and", "maxZoom", "config", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/components/marker/marker.helper.js#L66-L82
8,126
danielcaldas/react-d3-graph
src/components/link/link.helper.js
smoothCurveRadius
function smoothCurveRadius(x1, y1, x2, y2) { const dx = x2 - x1; const dy = y2 - y1; return Math.sqrt(dx * dx + dy * dy); }
javascript
function smoothCurveRadius(x1, y1, x2, y2) { const dx = x2 - x1; const dy = y2 - y1; return Math.sqrt(dx * dx + dy * dy); }
[ "function", "smoothCurveRadius", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ")", "{", "const", "dx", "=", "x2", "-", "x1", ";", "const", "dy", "=", "y2", "-", "y1", ";", "return", "Math", ".", "sqrt", "(", "dx", "*", "dx", "+", "dy", "*", "dy", ")", ";", "}" ]
Computes radius for a smooth curve effect. @param {number} x1 - x value for point 1 @param {number} y1 - y value for point 1 @param {number} x2 - y value for point 2 @param {number} y2 - y value for point 2 @returns{number} value of radius. @memberof Link/helper
[ "Computes", "radius", "for", "a", "smooth", "curve", "effect", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/components/link/link.helper.js#L26-L31
8,127
danielcaldas/react-d3-graph
cypress/page-objects/node.po.js
NodePO
function NodePO(id) { this.id = id; this.g = `#${this.id}`; this.path = `#${this.id} > path`; this.text = `#${this.id} > text`; this.image = `#${this.id} > image`; this.getPath = () => cy.get(this.path); this.getLabel = () => cy.get(this.text); this.getColor = () => cy.get(this.path).invoke("attr", "fill"); this.getFontSize = () => cy.get(this.text).invoke("attr", "font-size"); this.getFontWeight = () => cy.get(this.text).invoke("attr", "font-weight"); this.getImage = () => cy.get(this.image); this.getImageHref = () => cy.get(this.image).invoke("attr", "href"); this.getImageWidth = () => cy.get(this.image).invoke("attr", "width"); this.getImageHeight = () => cy.get(this.image).invoke("attr", "height"); this.getOpacity = () => cy.get(this.path).invoke("attr", "opacity"); }
javascript
function NodePO(id) { this.id = id; this.g = `#${this.id}`; this.path = `#${this.id} > path`; this.text = `#${this.id} > text`; this.image = `#${this.id} > image`; this.getPath = () => cy.get(this.path); this.getLabel = () => cy.get(this.text); this.getColor = () => cy.get(this.path).invoke("attr", "fill"); this.getFontSize = () => cy.get(this.text).invoke("attr", "font-size"); this.getFontWeight = () => cy.get(this.text).invoke("attr", "font-weight"); this.getImage = () => cy.get(this.image); this.getImageHref = () => cy.get(this.image).invoke("attr", "href"); this.getImageWidth = () => cy.get(this.image).invoke("attr", "width"); this.getImageHeight = () => cy.get(this.image).invoke("attr", "height"); this.getOpacity = () => cy.get(this.path).invoke("attr", "opacity"); }
[ "function", "NodePO", "(", "id", ")", "{", "this", ".", "id", "=", "id", ";", "this", ".", "g", "=", "`", "${", "this", ".", "id", "}", "`", ";", "this", ".", "path", "=", "`", "${", "this", ".", "id", "}", "`", ";", "this", ".", "text", "=", "`", "${", "this", ".", "id", "}", "`", ";", "this", ".", "image", "=", "`", "${", "this", ".", "id", "}", "`", ";", "this", ".", "getPath", "=", "(", ")", "=>", "cy", ".", "get", "(", "this", ".", "path", ")", ";", "this", ".", "getLabel", "=", "(", ")", "=>", "cy", ".", "get", "(", "this", ".", "text", ")", ";", "this", ".", "getColor", "=", "(", ")", "=>", "cy", ".", "get", "(", "this", ".", "path", ")", ".", "invoke", "(", "\"attr\"", ",", "\"fill\"", ")", ";", "this", ".", "getFontSize", "=", "(", ")", "=>", "cy", ".", "get", "(", "this", ".", "text", ")", ".", "invoke", "(", "\"attr\"", ",", "\"font-size\"", ")", ";", "this", ".", "getFontWeight", "=", "(", ")", "=>", "cy", ".", "get", "(", "this", ".", "text", ")", ".", "invoke", "(", "\"attr\"", ",", "\"font-weight\"", ")", ";", "this", ".", "getImage", "=", "(", ")", "=>", "cy", ".", "get", "(", "this", ".", "image", ")", ";", "this", ".", "getImageHref", "=", "(", ")", "=>", "cy", ".", "get", "(", "this", ".", "image", ")", ".", "invoke", "(", "\"attr\"", ",", "\"href\"", ")", ";", "this", ".", "getImageWidth", "=", "(", ")", "=>", "cy", ".", "get", "(", "this", ".", "image", ")", ".", "invoke", "(", "\"attr\"", ",", "\"width\"", ")", ";", "this", ".", "getImageHeight", "=", "(", ")", "=>", "cy", ".", "get", "(", "this", ".", "image", ")", ".", "invoke", "(", "\"attr\"", ",", "\"height\"", ")", ";", "this", ".", "getOpacity", "=", "(", ")", "=>", "cy", ".", "get", "(", "this", ".", "path", ")", ".", "invoke", "(", "\"attr\"", ",", "\"opacity\"", ")", ";", "}" ]
Page Object for interacting with Node component. @param {string} id the id of the node. @returns {undefined}
[ "Page", "Object", "for", "interacting", "with", "Node", "component", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/cypress/page-objects/node.po.js#L6-L23
8,128
danielcaldas/react-d3-graph
src/components/node/node.helper.js
buildSvgSymbol
function buildSvgSymbol(size = CONST.DEFAULT_NODE_SIZE, symbolTypeDesc = CONST.SYMBOLS.CIRCLE) { return d3Symbol() .size(() => size) .type(() => _convertTypeToD3Symbol(symbolTypeDesc))(); }
javascript
function buildSvgSymbol(size = CONST.DEFAULT_NODE_SIZE, symbolTypeDesc = CONST.SYMBOLS.CIRCLE) { return d3Symbol() .size(() => size) .type(() => _convertTypeToD3Symbol(symbolTypeDesc))(); }
[ "function", "buildSvgSymbol", "(", "size", "=", "CONST", ".", "DEFAULT_NODE_SIZE", ",", "symbolTypeDesc", "=", "CONST", ".", "SYMBOLS", ".", "CIRCLE", ")", "{", "return", "d3Symbol", "(", ")", ".", "size", "(", "(", ")", "=>", "size", ")", ".", "type", "(", "(", ")", "=>", "_convertTypeToD3Symbol", "(", "symbolTypeDesc", ")", ")", "(", ")", ";", "}" ]
Build a d3 svg symbol based on passed symbol and symbol type. @param {number} [size=80] - the size of the symbol. @param {string} [symbolTypeDesc='circle'] - the string containing the type of symbol that we want to build (should be one of {@link #node-symbol-type|node.symbolType}). @returns {Object} concrete instance of d3 symbol. @memberof Node/helper
[ "Build", "a", "d3", "svg", "symbol", "based", "on", "passed", "symbol", "and", "symbol", "type", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/components/node/node.helper.js#L56-L60
8,129
danielcaldas/react-d3-graph
src/components/graph/graph.builder.js
_getNodeOpacity
function _getNodeOpacity(node, highlightedNode, highlightedLink, config) { const highlight = node.highlighted || node.id === (highlightedLink && highlightedLink.source) || node.id === (highlightedLink && highlightedLink.target); const someNodeHighlighted = !!( highlightedNode || (highlightedLink && highlightedLink.source && highlightedLink.target) ); let opacity; if (someNodeHighlighted && config.highlightDegree === 0) { opacity = highlight ? config.node.opacity : config.highlightOpacity; } else if (someNodeHighlighted) { opacity = highlight ? config.node.opacity : config.highlightOpacity; } else { opacity = node.opacity || config.node.opacity; } return opacity; }
javascript
function _getNodeOpacity(node, highlightedNode, highlightedLink, config) { const highlight = node.highlighted || node.id === (highlightedLink && highlightedLink.source) || node.id === (highlightedLink && highlightedLink.target); const someNodeHighlighted = !!( highlightedNode || (highlightedLink && highlightedLink.source && highlightedLink.target) ); let opacity; if (someNodeHighlighted && config.highlightDegree === 0) { opacity = highlight ? config.node.opacity : config.highlightOpacity; } else if (someNodeHighlighted) { opacity = highlight ? config.node.opacity : config.highlightOpacity; } else { opacity = node.opacity || config.node.opacity; } return opacity; }
[ "function", "_getNodeOpacity", "(", "node", ",", "highlightedNode", ",", "highlightedLink", ",", "config", ")", "{", "const", "highlight", "=", "node", ".", "highlighted", "||", "node", ".", "id", "===", "(", "highlightedLink", "&&", "highlightedLink", ".", "source", ")", "||", "node", ".", "id", "===", "(", "highlightedLink", "&&", "highlightedLink", ".", "target", ")", ";", "const", "someNodeHighlighted", "=", "!", "!", "(", "highlightedNode", "||", "(", "highlightedLink", "&&", "highlightedLink", ".", "source", "&&", "highlightedLink", ".", "target", ")", ")", ";", "let", "opacity", ";", "if", "(", "someNodeHighlighted", "&&", "config", ".", "highlightDegree", "===", "0", ")", "{", "opacity", "=", "highlight", "?", "config", ".", "node", ".", "opacity", ":", "config", ".", "highlightOpacity", ";", "}", "else", "if", "(", "someNodeHighlighted", ")", "{", "opacity", "=", "highlight", "?", "config", ".", "node", ".", "opacity", ":", "config", ".", "highlightOpacity", ";", "}", "else", "{", "opacity", "=", "node", ".", "opacity", "||", "config", ".", "node", ".", "opacity", ";", "}", "return", "opacity", ";", "}" ]
Get the correct node opacity in order to properly make decisions based on context such as currently highlighted node. @param {Object} node - the node object for whom we will generate properties. @param {string} highlightedNode - same as {@link #graphrenderer|highlightedNode in renderGraph}. @param {Object} highlightedLink - same as {@link #graphrenderer|highlightedLink in renderGraph}. @param {Object} config - same as {@link #graphrenderer|config in renderGraph}. @returns {number} the opacity value for the given node. @memberof Graph/builder
[ "Get", "the", "correct", "node", "opacity", "in", "order", "to", "properly", "make", "decisions", "based", "on", "context", "such", "as", "currently", "highlighted", "node", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/components/graph/graph.builder.js#L20-L40
8,130
danielcaldas/react-d3-graph
src/components/graph/graph.builder.js
buildNodeProps
function buildNodeProps(node, config, nodeCallbacks = {}, highlightedNode, highlightedLink, transform) { const highlight = node.highlighted || (node.id === (highlightedLink && highlightedLink.source) || node.id === (highlightedLink && highlightedLink.target)); const opacity = _getNodeOpacity(node, highlightedNode, highlightedLink, config); let fill = node.color || config.node.color; if (highlight && config.node.highlightColor !== CONST.KEYWORDS.SAME) { fill = config.node.highlightColor; } let stroke = node.strokeColor || config.node.strokeColor; if (highlight && config.node.highlightStrokeColor !== CONST.KEYWORDS.SAME) { stroke = config.node.highlightStrokeColor; } let label = node[config.node.labelProperty] || node.id; if (typeof config.node.labelProperty === "function") { label = config.node.labelProperty(node); } let strokeWidth = node.strokeWidth || config.node.strokeWidth; if (highlight && config.node.highlightStrokeWidth !== CONST.KEYWORDS.SAME) { strokeWidth = config.node.highlightStrokeWidth; } const t = 1 / transform; const nodeSize = node.size || config.node.size; const fontSize = highlight ? config.node.highlightFontSize : config.node.fontSize; const dx = fontSize * t + nodeSize / 100 + 1.5; const svg = node.svg || config.node.svg; const fontColor = node.fontColor || config.node.fontColor; return { ...node, className: CONST.NODE_CLASS_NAME, cursor: config.node.mouseCursor, cx: (node && node.x) || "0", cy: (node && node.y) || "0", fill, fontColor, fontSize: fontSize * t, dx, fontWeight: highlight ? config.node.highlightFontWeight : config.node.fontWeight, id: node.id, label, onClickNode: nodeCallbacks.onClickNode, onRightClickNode: nodeCallbacks.onRightClickNode, onMouseOverNode: nodeCallbacks.onMouseOverNode, onMouseOut: nodeCallbacks.onMouseOut, opacity, renderLabel: config.node.renderLabel, size: nodeSize * t, stroke, strokeWidth: strokeWidth * t, svg, type: node.symbolType || config.node.symbolType, viewGenerator: node.viewGenerator || config.node.viewGenerator, overrideGlobalViewGenerator: !node.viewGenerator && node.svg, }; }
javascript
function buildNodeProps(node, config, nodeCallbacks = {}, highlightedNode, highlightedLink, transform) { const highlight = node.highlighted || (node.id === (highlightedLink && highlightedLink.source) || node.id === (highlightedLink && highlightedLink.target)); const opacity = _getNodeOpacity(node, highlightedNode, highlightedLink, config); let fill = node.color || config.node.color; if (highlight && config.node.highlightColor !== CONST.KEYWORDS.SAME) { fill = config.node.highlightColor; } let stroke = node.strokeColor || config.node.strokeColor; if (highlight && config.node.highlightStrokeColor !== CONST.KEYWORDS.SAME) { stroke = config.node.highlightStrokeColor; } let label = node[config.node.labelProperty] || node.id; if (typeof config.node.labelProperty === "function") { label = config.node.labelProperty(node); } let strokeWidth = node.strokeWidth || config.node.strokeWidth; if (highlight && config.node.highlightStrokeWidth !== CONST.KEYWORDS.SAME) { strokeWidth = config.node.highlightStrokeWidth; } const t = 1 / transform; const nodeSize = node.size || config.node.size; const fontSize = highlight ? config.node.highlightFontSize : config.node.fontSize; const dx = fontSize * t + nodeSize / 100 + 1.5; const svg = node.svg || config.node.svg; const fontColor = node.fontColor || config.node.fontColor; return { ...node, className: CONST.NODE_CLASS_NAME, cursor: config.node.mouseCursor, cx: (node && node.x) || "0", cy: (node && node.y) || "0", fill, fontColor, fontSize: fontSize * t, dx, fontWeight: highlight ? config.node.highlightFontWeight : config.node.fontWeight, id: node.id, label, onClickNode: nodeCallbacks.onClickNode, onRightClickNode: nodeCallbacks.onRightClickNode, onMouseOverNode: nodeCallbacks.onMouseOverNode, onMouseOut: nodeCallbacks.onMouseOut, opacity, renderLabel: config.node.renderLabel, size: nodeSize * t, stroke, strokeWidth: strokeWidth * t, svg, type: node.symbolType || config.node.symbolType, viewGenerator: node.viewGenerator || config.node.viewGenerator, overrideGlobalViewGenerator: !node.viewGenerator && node.svg, }; }
[ "function", "buildNodeProps", "(", "node", ",", "config", ",", "nodeCallbacks", "=", "{", "}", ",", "highlightedNode", ",", "highlightedLink", ",", "transform", ")", "{", "const", "highlight", "=", "node", ".", "highlighted", "||", "(", "node", ".", "id", "===", "(", "highlightedLink", "&&", "highlightedLink", ".", "source", ")", "||", "node", ".", "id", "===", "(", "highlightedLink", "&&", "highlightedLink", ".", "target", ")", ")", ";", "const", "opacity", "=", "_getNodeOpacity", "(", "node", ",", "highlightedNode", ",", "highlightedLink", ",", "config", ")", ";", "let", "fill", "=", "node", ".", "color", "||", "config", ".", "node", ".", "color", ";", "if", "(", "highlight", "&&", "config", ".", "node", ".", "highlightColor", "!==", "CONST", ".", "KEYWORDS", ".", "SAME", ")", "{", "fill", "=", "config", ".", "node", ".", "highlightColor", ";", "}", "let", "stroke", "=", "node", ".", "strokeColor", "||", "config", ".", "node", ".", "strokeColor", ";", "if", "(", "highlight", "&&", "config", ".", "node", ".", "highlightStrokeColor", "!==", "CONST", ".", "KEYWORDS", ".", "SAME", ")", "{", "stroke", "=", "config", ".", "node", ".", "highlightStrokeColor", ";", "}", "let", "label", "=", "node", "[", "config", ".", "node", ".", "labelProperty", "]", "||", "node", ".", "id", ";", "if", "(", "typeof", "config", ".", "node", ".", "labelProperty", "===", "\"function\"", ")", "{", "label", "=", "config", ".", "node", ".", "labelProperty", "(", "node", ")", ";", "}", "let", "strokeWidth", "=", "node", ".", "strokeWidth", "||", "config", ".", "node", ".", "strokeWidth", ";", "if", "(", "highlight", "&&", "config", ".", "node", ".", "highlightStrokeWidth", "!==", "CONST", ".", "KEYWORDS", ".", "SAME", ")", "{", "strokeWidth", "=", "config", ".", "node", ".", "highlightStrokeWidth", ";", "}", "const", "t", "=", "1", "/", "transform", ";", "const", "nodeSize", "=", "node", ".", "size", "||", "config", ".", "node", ".", "size", ";", "const", "fontSize", "=", "highlight", "?", "config", ".", "node", ".", "highlightFontSize", ":", "config", ".", "node", ".", "fontSize", ";", "const", "dx", "=", "fontSize", "*", "t", "+", "nodeSize", "/", "100", "+", "1.5", ";", "const", "svg", "=", "node", ".", "svg", "||", "config", ".", "node", ".", "svg", ";", "const", "fontColor", "=", "node", ".", "fontColor", "||", "config", ".", "node", ".", "fontColor", ";", "return", "{", "...", "node", ",", "className", ":", "CONST", ".", "NODE_CLASS_NAME", ",", "cursor", ":", "config", ".", "node", ".", "mouseCursor", ",", "cx", ":", "(", "node", "&&", "node", ".", "x", ")", "||", "\"0\"", ",", "cy", ":", "(", "node", "&&", "node", ".", "y", ")", "||", "\"0\"", ",", "fill", ",", "fontColor", ",", "fontSize", ":", "fontSize", "*", "t", ",", "dx", ",", "fontWeight", ":", "highlight", "?", "config", ".", "node", ".", "highlightFontWeight", ":", "config", ".", "node", ".", "fontWeight", ",", "id", ":", "node", ".", "id", ",", "label", ",", "onClickNode", ":", "nodeCallbacks", ".", "onClickNode", ",", "onRightClickNode", ":", "nodeCallbacks", ".", "onRightClickNode", ",", "onMouseOverNode", ":", "nodeCallbacks", ".", "onMouseOverNode", ",", "onMouseOut", ":", "nodeCallbacks", ".", "onMouseOut", ",", "opacity", ",", "renderLabel", ":", "config", ".", "node", ".", "renderLabel", ",", "size", ":", "nodeSize", "*", "t", ",", "stroke", ",", "strokeWidth", ":", "strokeWidth", "*", "t", ",", "svg", ",", "type", ":", "node", ".", "symbolType", "||", "config", ".", "node", ".", "symbolType", ",", "viewGenerator", ":", "node", ".", "viewGenerator", "||", "config", ".", "node", ".", "viewGenerator", ",", "overrideGlobalViewGenerator", ":", "!", "node", ".", "viewGenerator", "&&", "node", ".", "svg", ",", "}", ";", "}" ]
Build some Node properties based on given parameters. @param {Object} node - the node object for whom we will generate properties. @param {Object} config - same as {@link #graphrenderer|config in renderGraph}. @param {Function[]} nodeCallbacks - same as {@link #graphrenderer|nodeCallbacks in renderGraph}. @param {string} highlightedNode - same as {@link #graphrenderer|highlightedNode in renderGraph}. @param {Object} highlightedLink - same as {@link #graphrenderer|highlightedLink in renderGraph}. @param {number} transform - value that indicates the amount of zoom transformation. @returns {Object} returns object that contain Link props ready to be feeded to the Link component. @memberof Graph/builder
[ "Build", "some", "Node", "properties", "based", "on", "given", "parameters", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/components/graph/graph.builder.js#L152-L217
8,131
danielcaldas/react-d3-graph
sandbox/utils.js
formMap
function formMap(k, v) { // customized props switch (k) { case "link.type": { return { type: "array", title: "link.type", items: { enum: Object.keys(LINE_TYPES), }, uniqueItems: true, }; } } return { title: k, type: typeof v, default: v, }; }
javascript
function formMap(k, v) { // customized props switch (k) { case "link.type": { return { type: "array", title: "link.type", items: { enum: Object.keys(LINE_TYPES), }, uniqueItems: true, }; } } return { title: k, type: typeof v, default: v, }; }
[ "function", "formMap", "(", "k", ",", "v", ")", "{", "// customized props", "switch", "(", "k", ")", "{", "case", "\"link.type\"", ":", "{", "return", "{", "type", ":", "\"array\"", ",", "title", ":", "\"link.type\"", ",", "items", ":", "{", "enum", ":", "Object", ".", "keys", "(", "LINE_TYPES", ")", ",", "}", ",", "uniqueItems", ":", "true", ",", "}", ";", "}", "}", "return", "{", "title", ":", "k", ",", "type", ":", "typeof", "v", ",", "default", ":", "v", ",", "}", ";", "}" ]
This two functions generate the react-jsonschema-form schema from some passed graph configuration.
[ "This", "two", "functions", "generate", "the", "react", "-", "jsonschema", "-", "form", "schema", "from", "some", "passed", "graph", "configuration", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/sandbox/utils.js#L11-L31
8,132
danielcaldas/react-d3-graph
cypress/page-objects/sandbox.po.js
SandboxPO
function SandboxPO() { // whitelist checkbox inputs this.checkboxes = ["link.renderLabel", "node.renderLabel", "staticGraph", "collapsible", "directed"]; // actions this.fullScreenMode = () => cy.get(".container__graph > :nth-child(1) > :nth-child(1)"); this.playGraph = () => cy.get(".container__graph > :nth-child(1) > :nth-child(2)").click(); this.pauseGraph = () => cy.get(".container__graph > :nth-child(1) > :nth-child(3)").click(); this.addNode = () => cy.get(".container__graph > :nth-child(1) > :nth-child(5)").click(); this.removeNode = () => cy.get(".container__graph > :nth-child(1) > :nth-child(6)").click(); this.clickJsonTreeNodes = () => { cy.get(".container__graph-data") .contains("root") .scrollIntoView(); cy.get(".container__graph-data") .contains("nodes") .click(); }; // must be collapsed this.clickJsonTreeFirstNode = () => cy .get( ":nth-child(2) > .rejt-not-collapsed > .rejt-not-collapsed-list > :nth-child(1) > .rejt-collapsed > .rejt-collapsed-text" ) .click(); this.addJsonTreeFirstNodeProp = () => cy.get(":nth-child(2) > :nth-child(1) > .rejt-not-collapsed > :nth-child(4) > .rejt-plus-menu").click(); this.deleteJsonTreeFirstNodeProp = () => cy.get(".rejt-not-collapsed-list > :nth-child(2) > .rejt-minus-menu").click(); // element getters this.getFieldInput = field => this.checkboxes.includes(field) ? cy.contains(field).children("input") : cy.contains(field).siblings(".form-control"); this.getGraphNumbers = () => cy.get(".container__graph-info"); }
javascript
function SandboxPO() { // whitelist checkbox inputs this.checkboxes = ["link.renderLabel", "node.renderLabel", "staticGraph", "collapsible", "directed"]; // actions this.fullScreenMode = () => cy.get(".container__graph > :nth-child(1) > :nth-child(1)"); this.playGraph = () => cy.get(".container__graph > :nth-child(1) > :nth-child(2)").click(); this.pauseGraph = () => cy.get(".container__graph > :nth-child(1) > :nth-child(3)").click(); this.addNode = () => cy.get(".container__graph > :nth-child(1) > :nth-child(5)").click(); this.removeNode = () => cy.get(".container__graph > :nth-child(1) > :nth-child(6)").click(); this.clickJsonTreeNodes = () => { cy.get(".container__graph-data") .contains("root") .scrollIntoView(); cy.get(".container__graph-data") .contains("nodes") .click(); }; // must be collapsed this.clickJsonTreeFirstNode = () => cy .get( ":nth-child(2) > .rejt-not-collapsed > .rejt-not-collapsed-list > :nth-child(1) > .rejt-collapsed > .rejt-collapsed-text" ) .click(); this.addJsonTreeFirstNodeProp = () => cy.get(":nth-child(2) > :nth-child(1) > .rejt-not-collapsed > :nth-child(4) > .rejt-plus-menu").click(); this.deleteJsonTreeFirstNodeProp = () => cy.get(".rejt-not-collapsed-list > :nth-child(2) > .rejt-minus-menu").click(); // element getters this.getFieldInput = field => this.checkboxes.includes(field) ? cy.contains(field).children("input") : cy.contains(field).siblings(".form-control"); this.getGraphNumbers = () => cy.get(".container__graph-info"); }
[ "function", "SandboxPO", "(", ")", "{", "// whitelist checkbox inputs", "this", ".", "checkboxes", "=", "[", "\"link.renderLabel\"", ",", "\"node.renderLabel\"", ",", "\"staticGraph\"", ",", "\"collapsible\"", ",", "\"directed\"", "]", ";", "// actions", "this", ".", "fullScreenMode", "=", "(", ")", "=>", "cy", ".", "get", "(", "\".container__graph > :nth-child(1) > :nth-child(1)\"", ")", ";", "this", ".", "playGraph", "=", "(", ")", "=>", "cy", ".", "get", "(", "\".container__graph > :nth-child(1) > :nth-child(2)\"", ")", ".", "click", "(", ")", ";", "this", ".", "pauseGraph", "=", "(", ")", "=>", "cy", ".", "get", "(", "\".container__graph > :nth-child(1) > :nth-child(3)\"", ")", ".", "click", "(", ")", ";", "this", ".", "addNode", "=", "(", ")", "=>", "cy", ".", "get", "(", "\".container__graph > :nth-child(1) > :nth-child(5)\"", ")", ".", "click", "(", ")", ";", "this", ".", "removeNode", "=", "(", ")", "=>", "cy", ".", "get", "(", "\".container__graph > :nth-child(1) > :nth-child(6)\"", ")", ".", "click", "(", ")", ";", "this", ".", "clickJsonTreeNodes", "=", "(", ")", "=>", "{", "cy", ".", "get", "(", "\".container__graph-data\"", ")", ".", "contains", "(", "\"root\"", ")", ".", "scrollIntoView", "(", ")", ";", "cy", ".", "get", "(", "\".container__graph-data\"", ")", ".", "contains", "(", "\"nodes\"", ")", ".", "click", "(", ")", ";", "}", ";", "// must be collapsed", "this", ".", "clickJsonTreeFirstNode", "=", "(", ")", "=>", "cy", ".", "get", "(", "\":nth-child(2) > .rejt-not-collapsed > .rejt-not-collapsed-list > :nth-child(1) > .rejt-collapsed > .rejt-collapsed-text\"", ")", ".", "click", "(", ")", ";", "this", ".", "addJsonTreeFirstNodeProp", "=", "(", ")", "=>", "cy", ".", "get", "(", "\":nth-child(2) > :nth-child(1) > .rejt-not-collapsed > :nth-child(4) > .rejt-plus-menu\"", ")", ".", "click", "(", ")", ";", "this", ".", "deleteJsonTreeFirstNodeProp", "=", "(", ")", "=>", "cy", ".", "get", "(", "\".rejt-not-collapsed-list > :nth-child(2) > .rejt-minus-menu\"", ")", ".", "click", "(", ")", ";", "// element getters", "this", ".", "getFieldInput", "=", "field", "=>", "this", ".", "checkboxes", ".", "includes", "(", "field", ")", "?", "cy", ".", "contains", "(", "field", ")", ".", "children", "(", "\"input\"", ")", ":", "cy", ".", "contains", "(", "field", ")", ".", "siblings", "(", "\".form-control\"", ")", ";", "this", ".", "getGraphNumbers", "=", "(", ")", "=>", "cy", ".", "get", "(", "\".container__graph-info\"", ")", ";", "}" ]
Page Object for interacting with sandbox interface. @returns {undefined}
[ "Page", "Object", "for", "interacting", "with", "sandbox", "interface", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/cypress/page-objects/sandbox.po.js#L5-L41
8,133
danielcaldas/react-d3-graph
cypress/page-objects/link.po.js
LinkPO
function LinkPO(index) { this.index = index; this.getLine = () => cy.get('path[class="link"]').then(lines => lines[this.index]); this.getStyle = () => this.getLine().invoke("attr", "style"); this.shouldHaveColor = color => this.getStyle().should("contain", `stroke: ${color};`); this.shouldHaveOpacity = opacity => this.getStyle().should("contain", `opacity: ${opacity};`); this.hasMarker = () => this.getLine() .invoke("attr", "marker-end") .should("contain", "url(#marker-"); this.getLabel = () => this.getLine().siblings(); }
javascript
function LinkPO(index) { this.index = index; this.getLine = () => cy.get('path[class="link"]').then(lines => lines[this.index]); this.getStyle = () => this.getLine().invoke("attr", "style"); this.shouldHaveColor = color => this.getStyle().should("contain", `stroke: ${color};`); this.shouldHaveOpacity = opacity => this.getStyle().should("contain", `opacity: ${opacity};`); this.hasMarker = () => this.getLine() .invoke("attr", "marker-end") .should("contain", "url(#marker-"); this.getLabel = () => this.getLine().siblings(); }
[ "function", "LinkPO", "(", "index", ")", "{", "this", ".", "index", "=", "index", ";", "this", ".", "getLine", "=", "(", ")", "=>", "cy", ".", "get", "(", "'path[class=\"link\"]'", ")", ".", "then", "(", "lines", "=>", "lines", "[", "this", ".", "index", "]", ")", ";", "this", ".", "getStyle", "=", "(", ")", "=>", "this", ".", "getLine", "(", ")", ".", "invoke", "(", "\"attr\"", ",", "\"style\"", ")", ";", "this", ".", "shouldHaveColor", "=", "color", "=>", "this", ".", "getStyle", "(", ")", ".", "should", "(", "\"contain\"", ",", "`", "${", "color", "}", "`", ")", ";", "this", ".", "shouldHaveOpacity", "=", "opacity", "=>", "this", ".", "getStyle", "(", ")", ".", "should", "(", "\"contain\"", ",", "`", "${", "opacity", "}", "`", ")", ";", "this", ".", "hasMarker", "=", "(", ")", "=>", "this", ".", "getLine", "(", ")", ".", "invoke", "(", "\"attr\"", ",", "\"marker-end\"", ")", ".", "should", "(", "\"contain\"", ",", "\"url(#marker-\"", ")", ";", "this", ".", "getLabel", "=", "(", ")", "=>", "this", ".", "getLine", "(", ")", ".", "siblings", "(", ")", ";", "}" ]
Page Object for interacting with Link component. @param {number} index - the index of the link. @returns {undefined}
[ "Page", "Object", "for", "interacting", "with", "Link", "component", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/cypress/page-objects/link.po.js#L6-L18
8,134
danielcaldas/react-d3-graph
src/utils.js
_isPropertyNestedObject
function _isPropertyNestedObject(o, k) { return !!o && o.hasOwnProperty(k) && typeof o[k] === "object" && o[k] !== null && !isEmptyObject(o[k]); }
javascript
function _isPropertyNestedObject(o, k) { return !!o && o.hasOwnProperty(k) && typeof o[k] === "object" && o[k] !== null && !isEmptyObject(o[k]); }
[ "function", "_isPropertyNestedObject", "(", "o", ",", "k", ")", "{", "return", "!", "!", "o", "&&", "o", ".", "hasOwnProperty", "(", "k", ")", "&&", "typeof", "o", "[", "k", "]", "===", "\"object\"", "&&", "o", "[", "k", "]", "!==", "null", "&&", "!", "isEmptyObject", "(", "o", "[", "k", "]", ")", ";", "}" ]
Checks whether a certain object property is from object type and is a non empty object. @param {Object} o - the object. @param {string} k - the object property. @returns {boolean} returns true if o[k] is an non empty object. @memberof utils
[ "Checks", "whether", "a", "certain", "object", "property", "is", "from", "object", "type", "and", "is", "a", "non", "empty", "object", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/utils.js#L19-L21
8,135
danielcaldas/react-d3-graph
src/utils.js
isDeepEqual
function isDeepEqual(o1, o2, _depth = 0) { let diffs = []; if (_depth === 0 && o1 === o2) { return true; } if ((isEmptyObject(o1) && !isEmptyObject(o2)) || (!isEmptyObject(o1) && isEmptyObject(o2))) { return false; } const o1Keys = Object.keys(o1); const o2Keys = Object.keys(o2); if (o1Keys.length !== o2Keys.length) { return false; } for (let k of o1Keys) { const nestedO = _isPropertyNestedObject(o1, k) && _isPropertyNestedObject(o2, k); if (nestedO && _depth < MAX_DEPTH) { diffs.push(isDeepEqual(o1[k], o2[k], _depth + 1)); } else { const r = (isEmptyObject(o1[k]) && isEmptyObject(o2[k])) || (o2.hasOwnProperty(k) && o2[k] === o1[k]); diffs.push(r); if (!r) { break; } } } return diffs.indexOf(false) === -1; }
javascript
function isDeepEqual(o1, o2, _depth = 0) { let diffs = []; if (_depth === 0 && o1 === o2) { return true; } if ((isEmptyObject(o1) && !isEmptyObject(o2)) || (!isEmptyObject(o1) && isEmptyObject(o2))) { return false; } const o1Keys = Object.keys(o1); const o2Keys = Object.keys(o2); if (o1Keys.length !== o2Keys.length) { return false; } for (let k of o1Keys) { const nestedO = _isPropertyNestedObject(o1, k) && _isPropertyNestedObject(o2, k); if (nestedO && _depth < MAX_DEPTH) { diffs.push(isDeepEqual(o1[k], o2[k], _depth + 1)); } else { const r = (isEmptyObject(o1[k]) && isEmptyObject(o2[k])) || (o2.hasOwnProperty(k) && o2[k] === o1[k]); diffs.push(r); if (!r) { break; } } } return diffs.indexOf(false) === -1; }
[ "function", "isDeepEqual", "(", "o1", ",", "o2", ",", "_depth", "=", "0", ")", "{", "let", "diffs", "=", "[", "]", ";", "if", "(", "_depth", "===", "0", "&&", "o1", "===", "o2", ")", "{", "return", "true", ";", "}", "if", "(", "(", "isEmptyObject", "(", "o1", ")", "&&", "!", "isEmptyObject", "(", "o2", ")", ")", "||", "(", "!", "isEmptyObject", "(", "o1", ")", "&&", "isEmptyObject", "(", "o2", ")", ")", ")", "{", "return", "false", ";", "}", "const", "o1Keys", "=", "Object", ".", "keys", "(", "o1", ")", ";", "const", "o2Keys", "=", "Object", ".", "keys", "(", "o2", ")", ";", "if", "(", "o1Keys", ".", "length", "!==", "o2Keys", ".", "length", ")", "{", "return", "false", ";", "}", "for", "(", "let", "k", "of", "o1Keys", ")", "{", "const", "nestedO", "=", "_isPropertyNestedObject", "(", "o1", ",", "k", ")", "&&", "_isPropertyNestedObject", "(", "o2", ",", "k", ")", ";", "if", "(", "nestedO", "&&", "_depth", "<", "MAX_DEPTH", ")", "{", "diffs", ".", "push", "(", "isDeepEqual", "(", "o1", "[", "k", "]", ",", "o2", "[", "k", "]", ",", "_depth", "+", "1", ")", ")", ";", "}", "else", "{", "const", "r", "=", "(", "isEmptyObject", "(", "o1", "[", "k", "]", ")", "&&", "isEmptyObject", "(", "o2", "[", "k", "]", ")", ")", "||", "(", "o2", ".", "hasOwnProperty", "(", "k", ")", "&&", "o2", "[", "k", "]", "===", "o1", "[", "k", "]", ")", ";", "diffs", ".", "push", "(", "r", ")", ";", "if", "(", "!", "r", ")", "{", "break", ";", "}", "}", "}", "return", "diffs", ".", "indexOf", "(", "false", ")", "===", "-", "1", ";", "}" ]
Generic deep comparison between javascript simple or complex objects. @param {Object} o1 - one of the objects to be compared. @param {Object} o2 - second object to compare with first. @param {number} [_depth=0] - this parameter serves only for internal usage. @returns {boolean} returns true if o1 and o2 have exactly the same content, or are exactly the same object reference. @memberof utils
[ "Generic", "deep", "comparison", "between", "javascript", "simple", "or", "complex", "objects", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/utils.js#L31-L66
8,136
danielcaldas/react-d3-graph
src/utils.js
deepClone
function deepClone(o, _clone = {}, _depth = 0) { // TODO: Handle invalid input o is null, undefined, empty object const oKeys = Object.keys(o); // TODO: handle arrays for (let k of oKeys) { const nested = _isPropertyNestedObject(o, k); _clone[k] = nested && _depth < MAX_DEPTH ? deepClone(o[k], {}, _depth + 1) : o[k]; } return _clone; }
javascript
function deepClone(o, _clone = {}, _depth = 0) { // TODO: Handle invalid input o is null, undefined, empty object const oKeys = Object.keys(o); // TODO: handle arrays for (let k of oKeys) { const nested = _isPropertyNestedObject(o, k); _clone[k] = nested && _depth < MAX_DEPTH ? deepClone(o[k], {}, _depth + 1) : o[k]; } return _clone; }
[ "function", "deepClone", "(", "o", ",", "_clone", "=", "{", "}", ",", "_depth", "=", "0", ")", "{", "// TODO: Handle invalid input o is null, undefined, empty object", "const", "oKeys", "=", "Object", ".", "keys", "(", "o", ")", ";", "// TODO: handle arrays", "for", "(", "let", "k", "of", "oKeys", ")", "{", "const", "nested", "=", "_isPropertyNestedObject", "(", "o", ",", "k", ")", ";", "_clone", "[", "k", "]", "=", "nested", "&&", "_depth", "<", "MAX_DEPTH", "?", "deepClone", "(", "o", "[", "k", "]", ",", "{", "}", ",", "_depth", "+", "1", ")", ":", "o", "[", "k", "]", ";", "}", "return", "_clone", ";", "}" ]
Function to deep clone plain javascript objects. @param {Object} o - the object to clone. @param {Object} _clone - carries the cloned output throughout the recursive calls. Parameter serves only for internal usage. @param {number} _depth - this parameter serves only for internal usage. @returns {Object} - the cloned object. @memberof utils
[ "Function", "to", "deep", "clone", "plain", "javascript", "objects", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/utils.js#L88-L100
8,137
danielcaldas/react-d3-graph
src/utils.js
merge
function merge(o1 = {}, o2 = {}, _depth = 0) { let o = {}; if (Object.keys(o1 || {}).length === 0) { return o2 && !isEmptyObject(o2) ? o2 : {}; } for (let k of Object.keys(o1)) { const nestedO = !!(o2[k] && typeof o2[k] === "object" && typeof o1[k] === "object" && _depth < MAX_DEPTH); if (nestedO) { const r = merge(o1[k], o2[k], _depth + 1); o[k] = o1[k].hasOwnProperty("length") && o2[k].hasOwnProperty("length") ? Object.keys(r).map(rk => r[rk]) : r; } else { o[k] = o2.hasOwnProperty(k) ? o2[k] : o1[k]; } } return o; }
javascript
function merge(o1 = {}, o2 = {}, _depth = 0) { let o = {}; if (Object.keys(o1 || {}).length === 0) { return o2 && !isEmptyObject(o2) ? o2 : {}; } for (let k of Object.keys(o1)) { const nestedO = !!(o2[k] && typeof o2[k] === "object" && typeof o1[k] === "object" && _depth < MAX_DEPTH); if (nestedO) { const r = merge(o1[k], o2[k], _depth + 1); o[k] = o1[k].hasOwnProperty("length") && o2[k].hasOwnProperty("length") ? Object.keys(r).map(rk => r[rk]) : r; } else { o[k] = o2.hasOwnProperty(k) ? o2[k] : o1[k]; } } return o; }
[ "function", "merge", "(", "o1", "=", "{", "}", ",", "o2", "=", "{", "}", ",", "_depth", "=", "0", ")", "{", "let", "o", "=", "{", "}", ";", "if", "(", "Object", ".", "keys", "(", "o1", "||", "{", "}", ")", ".", "length", "===", "0", ")", "{", "return", "o2", "&&", "!", "isEmptyObject", "(", "o2", ")", "?", "o2", ":", "{", "}", ";", "}", "for", "(", "let", "k", "of", "Object", ".", "keys", "(", "o1", ")", ")", "{", "const", "nestedO", "=", "!", "!", "(", "o2", "[", "k", "]", "&&", "typeof", "o2", "[", "k", "]", "===", "\"object\"", "&&", "typeof", "o1", "[", "k", "]", "===", "\"object\"", "&&", "_depth", "<", "MAX_DEPTH", ")", ";", "if", "(", "nestedO", ")", "{", "const", "r", "=", "merge", "(", "o1", "[", "k", "]", ",", "o2", "[", "k", "]", ",", "_depth", "+", "1", ")", ";", "o", "[", "k", "]", "=", "o1", "[", "k", "]", ".", "hasOwnProperty", "(", "\"length\"", ")", "&&", "o2", "[", "k", "]", ".", "hasOwnProperty", "(", "\"length\"", ")", "?", "Object", ".", "keys", "(", "r", ")", ".", "map", "(", "rk", "=>", "r", "[", "rk", "]", ")", ":", "r", ";", "}", "else", "{", "o", "[", "k", "]", "=", "o2", ".", "hasOwnProperty", "(", "k", ")", "?", "o2", "[", "k", "]", ":", "o1", "[", "k", "]", ";", "}", "}", "return", "o", ";", "}" ]
This function merges two objects o1 and o2, where o2 properties override existent o1 properties, and if o2 doesn't posses some o1 property the fallback will be the o1 property. @param {Object} o1 - object. @param {Object} o2 - object that will override o1 properties. @param {int} [_depth=0] - the depth at which we are merging the object. @returns {Object} object that is the result of merging o1 and o2, being o2 properties priority overriding existent o1 properties. @memberof utils
[ "This", "function", "merges", "two", "objects", "o1", "and", "o2", "where", "o2", "properties", "override", "existent", "o1", "properties", "and", "if", "o2", "doesn", "t", "posses", "some", "o1", "property", "the", "fallback", "will", "be", "the", "o1", "property", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/utils.js#L112-L133
8,138
danielcaldas/react-d3-graph
src/utils.js
pick
function pick(o, props = []) { return props.reduce((acc, k) => { if (o.hasOwnProperty(k)) { acc[k] = o[k]; } return acc; }, {}); }
javascript
function pick(o, props = []) { return props.reduce((acc, k) => { if (o.hasOwnProperty(k)) { acc[k] = o[k]; } return acc; }, {}); }
[ "function", "pick", "(", "o", ",", "props", "=", "[", "]", ")", "{", "return", "props", ".", "reduce", "(", "(", "acc", ",", "k", ")", "=>", "{", "if", "(", "o", ".", "hasOwnProperty", "(", "k", ")", ")", "{", "acc", "[", "k", "]", "=", "o", "[", "k", "]", ";", "}", "return", "acc", ";", "}", ",", "{", "}", ")", ";", "}" ]
Create new object from the inputted one only with the props passed in the props list. @param {Object} o - the object to pick props from. @param {Array.<string>} props - list of props that we want to pick from o. @returns {Object} the object resultant from the picking operation. @memberof utils
[ "Create", "new", "object", "from", "the", "inputted", "one", "only", "with", "the", "props", "passed", "in", "the", "props", "list", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/utils.js#L143-L151
8,139
danielcaldas/react-d3-graph
src/utils.js
antiPick
function antiPick(o, props = []) { const wanted = Object.keys(o).filter(k => !props.includes(k)); return pick(o, wanted); }
javascript
function antiPick(o, props = []) { const wanted = Object.keys(o).filter(k => !props.includes(k)); return pick(o, wanted); }
[ "function", "antiPick", "(", "o", ",", "props", "=", "[", "]", ")", "{", "const", "wanted", "=", "Object", ".", "keys", "(", "o", ")", ".", "filter", "(", "k", "=>", "!", "props", ".", "includes", "(", "k", ")", ")", ";", "return", "pick", "(", "o", ",", "wanted", ")", ";", "}" ]
Picks all props except the ones passed in the props array. @param {Object} o - the object to pick props from. @param {Array.<string>} props - list of props that we DON'T want to pick from o. @returns {Object} the object resultant from the anti picking operation. @memberof utils
[ "Picks", "all", "props", "except", "the", "ones", "passed", "in", "the", "props", "array", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/utils.js#L160-L164
8,140
danielcaldas/react-d3-graph
src/components/graph/graph.helper.js
_initializeNodes
function _initializeNodes(graphNodes) { let nodes = {}; const n = graphNodes.length; for (let i = 0; i < n; i++) { const node = graphNodes[i]; node.highlighted = false; if (!node.hasOwnProperty("x")) { node.x = 0; } if (!node.hasOwnProperty("y")) { node.y = 0; } nodes[node.id.toString()] = node; } return nodes; }
javascript
function _initializeNodes(graphNodes) { let nodes = {}; const n = graphNodes.length; for (let i = 0; i < n; i++) { const node = graphNodes[i]; node.highlighted = false; if (!node.hasOwnProperty("x")) { node.x = 0; } if (!node.hasOwnProperty("y")) { node.y = 0; } nodes[node.id.toString()] = node; } return nodes; }
[ "function", "_initializeNodes", "(", "graphNodes", ")", "{", "let", "nodes", "=", "{", "}", ";", "const", "n", "=", "graphNodes", ".", "length", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "const", "node", "=", "graphNodes", "[", "i", "]", ";", "node", ".", "highlighted", "=", "false", ";", "if", "(", "!", "node", ".", "hasOwnProperty", "(", "\"x\"", ")", ")", "{", "node", ".", "x", "=", "0", ";", "}", "if", "(", "!", "node", ".", "hasOwnProperty", "(", "\"y\"", ")", ")", "{", "node", ".", "y", "=", "0", ";", "}", "nodes", "[", "node", ".", "id", ".", "toString", "(", ")", "]", "=", "node", ";", "}", "return", "nodes", ";", "}" ]
Method that initialize graph nodes provided by rd3g consumer and adds additional default mandatory properties that are optional for the user. Also it generates an index mapping, this maps nodes ids the their index in the array of nodes. This is needed because d3 callbacks such as node click and link click return the index of the node. @param {Array.<Node>} graphNodes - the array of nodes provided by the rd3g consumer. @returns {Object.<string, Object>} returns the nodes ready to be used within rd3g with additional properties such as x, y and highlighted values. @memberof Graph/helper
[ "Method", "that", "initialize", "graph", "nodes", "provided", "by", "rd3g", "consumer", "and", "adds", "additional", "default", "mandatory", "properties", "that", "are", "optional", "for", "the", "user", ".", "Also", "it", "generates", "an", "index", "mapping", "this", "maps", "nodes", "ids", "the", "their", "index", "in", "the", "array", "of", "nodes", ".", "This", "is", "needed", "because", "d3", "callbacks", "such", "as", "node", "click", "and", "link", "click", "return", "the", "index", "of", "the", "node", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/components/graph/graph.helper.js#L105-L125
8,141
danielcaldas/react-d3-graph
src/components/graph/graph.helper.js
_tagOrphanNodes
function _tagOrphanNodes(nodes, linksMatrix) { return Object.keys(nodes).reduce((acc, nodeId) => { const { inDegree, outDegree } = computeNodeDegree(nodeId, linksMatrix); const node = nodes[nodeId]; const taggedNode = inDegree === 0 && outDegree === 0 ? { ...node, _orphan: true } : node; acc[nodeId] = taggedNode; return acc; }, {}); }
javascript
function _tagOrphanNodes(nodes, linksMatrix) { return Object.keys(nodes).reduce((acc, nodeId) => { const { inDegree, outDegree } = computeNodeDegree(nodeId, linksMatrix); const node = nodes[nodeId]; const taggedNode = inDegree === 0 && outDegree === 0 ? { ...node, _orphan: true } : node; acc[nodeId] = taggedNode; return acc; }, {}); }
[ "function", "_tagOrphanNodes", "(", "nodes", ",", "linksMatrix", ")", "{", "return", "Object", ".", "keys", "(", "nodes", ")", ".", "reduce", "(", "(", "acc", ",", "nodeId", ")", "=>", "{", "const", "{", "inDegree", ",", "outDegree", "}", "=", "computeNodeDegree", "(", "nodeId", ",", "linksMatrix", ")", ";", "const", "node", "=", "nodes", "[", "nodeId", "]", ";", "const", "taggedNode", "=", "inDegree", "===", "0", "&&", "outDegree", "===", "0", "?", "{", "...", "node", ",", "_orphan", ":", "true", "}", ":", "node", ";", "acc", "[", "nodeId", "]", "=", "taggedNode", ";", "return", "acc", ";", "}", ",", "{", "}", ")", ";", "}" ]
Tags orphan nodes with a `_orphan` flag. @param {Object.<string, Object>} nodes - nodes mapped by their id. @param {Object.<string, Object>} linksMatrix - an object containing a matrix of connections of the graph, for each nodeId, there is an object that maps adjacent nodes ids (string) and their values (number). @returns {Object.<string, Object>} same input nodes structure with tagged orphans nodes where applicable. @memberof Graph/helper
[ "Tags", "orphan", "nodes", "with", "a", "_orphan", "flag", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/components/graph/graph.helper.js#L187-L197
8,142
danielcaldas/react-d3-graph
src/components/graph/graph.helper.js
_validateGraphData
function _validateGraphData(data) { if (!data.nodes || !data.nodes.length) { utils.throwErr("Graph", ERRORS.INSUFFICIENT_DATA); } const n = data.links.length; for (let i = 0; i < n; i++) { const l = data.links[i]; if (!data.nodes.find(n => n.id === l.source)) { utils.throwErr("Graph", `${ERRORS.INVALID_LINKS} - "${l.source}" is not a valid source node id`); } if (!data.nodes.find(n => n.id === l.target)) { utils.throwErr("Graph", `${ERRORS.INVALID_LINKS} - "${l.target}" is not a valid target node id`); } if (l && l.value !== undefined && typeof l.value !== "number") { utils.throwErr( "Graph", `${ERRORS.INVALID_LINK_VALUE} - found in link with source "${l.source}" and target "${l.target}"` ); } } }
javascript
function _validateGraphData(data) { if (!data.nodes || !data.nodes.length) { utils.throwErr("Graph", ERRORS.INSUFFICIENT_DATA); } const n = data.links.length; for (let i = 0; i < n; i++) { const l = data.links[i]; if (!data.nodes.find(n => n.id === l.source)) { utils.throwErr("Graph", `${ERRORS.INVALID_LINKS} - "${l.source}" is not a valid source node id`); } if (!data.nodes.find(n => n.id === l.target)) { utils.throwErr("Graph", `${ERRORS.INVALID_LINKS} - "${l.target}" is not a valid target node id`); } if (l && l.value !== undefined && typeof l.value !== "number") { utils.throwErr( "Graph", `${ERRORS.INVALID_LINK_VALUE} - found in link with source "${l.source}" and target "${l.target}"` ); } } }
[ "function", "_validateGraphData", "(", "data", ")", "{", "if", "(", "!", "data", ".", "nodes", "||", "!", "data", ".", "nodes", ".", "length", ")", "{", "utils", ".", "throwErr", "(", "\"Graph\"", ",", "ERRORS", ".", "INSUFFICIENT_DATA", ")", ";", "}", "const", "n", "=", "data", ".", "links", ".", "length", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "const", "l", "=", "data", ".", "links", "[", "i", "]", ";", "if", "(", "!", "data", ".", "nodes", ".", "find", "(", "n", "=>", "n", ".", "id", "===", "l", ".", "source", ")", ")", "{", "utils", ".", "throwErr", "(", "\"Graph\"", ",", "`", "${", "ERRORS", ".", "INVALID_LINKS", "}", "${", "l", ".", "source", "}", "`", ")", ";", "}", "if", "(", "!", "data", ".", "nodes", ".", "find", "(", "n", "=>", "n", ".", "id", "===", "l", ".", "target", ")", ")", "{", "utils", ".", "throwErr", "(", "\"Graph\"", ",", "`", "${", "ERRORS", ".", "INVALID_LINKS", "}", "${", "l", ".", "target", "}", "`", ")", ";", "}", "if", "(", "l", "&&", "l", ".", "value", "!==", "undefined", "&&", "typeof", "l", ".", "value", "!==", "\"number\"", ")", "{", "utils", ".", "throwErr", "(", "\"Graph\"", ",", "`", "${", "ERRORS", ".", "INVALID_LINK_VALUE", "}", "${", "l", ".", "source", "}", "${", "l", ".", "target", "}", "`", ")", ";", "}", "}", "}" ]
Some integrity validations on links and nodes structure. If some validation fails the function will throw an error. @param {Object} data - Same as {@link #initializeGraphState|data in initializeGraphState}. @throws can throw the following error msg: INSUFFICIENT_DATA - msg if no nodes are provided INVALID_LINKS - if links point to nonexistent nodes @returns {undefined} @memberof Graph/helper
[ "Some", "integrity", "validations", "on", "links", "and", "nodes", "structure", ".", "If", "some", "validation", "fails", "the", "function", "will", "throw", "an", "error", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/components/graph/graph.helper.js#L209-L234
8,143
danielcaldas/react-d3-graph
src/components/graph/graph.helper.js
checkForGraphConfigChanges
function checkForGraphConfigChanges(nextProps, currentState) { const newConfig = nextProps.config || {}; const configUpdated = newConfig && !utils.isEmptyObject(newConfig) && !utils.isDeepEqual(newConfig, currentState.config); const d3ConfigUpdated = newConfig && newConfig.d3 && !utils.isDeepEqual(newConfig.d3, currentState.config.d3); return { configUpdated, d3ConfigUpdated }; }
javascript
function checkForGraphConfigChanges(nextProps, currentState) { const newConfig = nextProps.config || {}; const configUpdated = newConfig && !utils.isEmptyObject(newConfig) && !utils.isDeepEqual(newConfig, currentState.config); const d3ConfigUpdated = newConfig && newConfig.d3 && !utils.isDeepEqual(newConfig.d3, currentState.config.d3); return { configUpdated, d3ConfigUpdated }; }
[ "function", "checkForGraphConfigChanges", "(", "nextProps", ",", "currentState", ")", "{", "const", "newConfig", "=", "nextProps", ".", "config", "||", "{", "}", ";", "const", "configUpdated", "=", "newConfig", "&&", "!", "utils", ".", "isEmptyObject", "(", "newConfig", ")", "&&", "!", "utils", ".", "isDeepEqual", "(", "newConfig", ",", "currentState", ".", "config", ")", ";", "const", "d3ConfigUpdated", "=", "newConfig", "&&", "newConfig", ".", "d3", "&&", "!", "utils", ".", "isDeepEqual", "(", "newConfig", ".", "d3", ",", "currentState", ".", "config", ".", "d3", ")", ";", "return", "{", "configUpdated", ",", "d3ConfigUpdated", "}", ";", "}" ]
Logic to check for changes in graph config. @param {Object} nextProps - nextProps that graph will receive. @param {Object} currentState - the current state of the graph. @returns {Object.<string, boolean>} returns object containing update check flags: - configUpdated - global flag that indicates if any property was updated. - d3ConfigUpdated - specific flag that indicates changes in d3 configurations. @memberof Graph/helper
[ "Logic", "to", "check", "for", "changes", "in", "graph", "config", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/components/graph/graph.helper.js#L282-L289
8,144
danielcaldas/react-d3-graph
src/components/graph/graph.helper.js
getCenterAndZoomTransformation
function getCenterAndZoomTransformation(d3Node, config) { if (!d3Node) { return; } const { width, height, focusZoom } = config; return ` translate(${width / 2}, ${height / 2}) scale(${focusZoom}) translate(${-d3Node.x}, ${-d3Node.y}) `; }
javascript
function getCenterAndZoomTransformation(d3Node, config) { if (!d3Node) { return; } const { width, height, focusZoom } = config; return ` translate(${width / 2}, ${height / 2}) scale(${focusZoom}) translate(${-d3Node.x}, ${-d3Node.y}) `; }
[ "function", "getCenterAndZoomTransformation", "(", "d3Node", ",", "config", ")", "{", "if", "(", "!", "d3Node", ")", "{", "return", ";", "}", "const", "{", "width", ",", "height", ",", "focusZoom", "}", "=", "config", ";", "return", "`", "${", "width", "/", "2", "}", "${", "height", "/", "2", "}", "${", "focusZoom", "}", "${", "-", "d3Node", ".", "x", "}", "${", "-", "d3Node", ".", "y", "}", "`", ";", "}" ]
Returns the transformation to apply in order to center the graph on the selected node. @param {Object} d3Node - node to focus the graph view on. @param {Object} config - same as {@link #graphrenderer|config in renderGraph}. @returns {string} transform rule to apply. @memberof Graph/helper
[ "Returns", "the", "transformation", "to", "apply", "in", "order", "to", "center", "the", "graph", "on", "the", "selected", "node", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/components/graph/graph.helper.js#L299-L311
8,145
danielcaldas/react-d3-graph
src/components/graph/graph.helper.js
initializeGraphState
function initializeGraphState({ data, id, config }, state) { _validateGraphData(data); let graph; if (state && state.nodes) { graph = { nodes: data.nodes.map(n => state.nodes[n.id] ? Object.assign({}, n, utils.pick(state.nodes[n.id], NODE_PROPS_WHITELIST)) : Object.assign({}, n) ), links: data.links.map((l, index) => _mapDataLinkToD3Link(l, index, state && state.d3Links, config, state)), }; } else { graph = { nodes: data.nodes.map(n => Object.assign({}, n)), links: data.links.map(l => Object.assign({}, l)), }; } let newConfig = Object.assign({}, utils.merge(DEFAULT_CONFIG, config || {})); let links = _initializeLinks(graph.links, newConfig); // matrix of graph connections let nodes = _tagOrphanNodes(_initializeNodes(graph.nodes), links); const { nodes: d3Nodes, links: d3Links } = graph; const formatedId = id.replace(/ /g, "_"); const simulation = _createForceSimulation(newConfig.width, newConfig.height, newConfig.d3 && newConfig.d3.gravity); const { minZoom, maxZoom, focusZoom } = newConfig; if (focusZoom > maxZoom) { newConfig.focusZoom = maxZoom; } else if (focusZoom < minZoom) { newConfig.focusZoom = minZoom; } return { id: formatedId, config: newConfig, links, d3Links, nodes, d3Nodes, highlightedNode: "", simulation, newGraphElements: false, configUpdated: false, transform: 1, }; }
javascript
function initializeGraphState({ data, id, config }, state) { _validateGraphData(data); let graph; if (state && state.nodes) { graph = { nodes: data.nodes.map(n => state.nodes[n.id] ? Object.assign({}, n, utils.pick(state.nodes[n.id], NODE_PROPS_WHITELIST)) : Object.assign({}, n) ), links: data.links.map((l, index) => _mapDataLinkToD3Link(l, index, state && state.d3Links, config, state)), }; } else { graph = { nodes: data.nodes.map(n => Object.assign({}, n)), links: data.links.map(l => Object.assign({}, l)), }; } let newConfig = Object.assign({}, utils.merge(DEFAULT_CONFIG, config || {})); let links = _initializeLinks(graph.links, newConfig); // matrix of graph connections let nodes = _tagOrphanNodes(_initializeNodes(graph.nodes), links); const { nodes: d3Nodes, links: d3Links } = graph; const formatedId = id.replace(/ /g, "_"); const simulation = _createForceSimulation(newConfig.width, newConfig.height, newConfig.d3 && newConfig.d3.gravity); const { minZoom, maxZoom, focusZoom } = newConfig; if (focusZoom > maxZoom) { newConfig.focusZoom = maxZoom; } else if (focusZoom < minZoom) { newConfig.focusZoom = minZoom; } return { id: formatedId, config: newConfig, links, d3Links, nodes, d3Nodes, highlightedNode: "", simulation, newGraphElements: false, configUpdated: false, transform: 1, }; }
[ "function", "initializeGraphState", "(", "{", "data", ",", "id", ",", "config", "}", ",", "state", ")", "{", "_validateGraphData", "(", "data", ")", ";", "let", "graph", ";", "if", "(", "state", "&&", "state", ".", "nodes", ")", "{", "graph", "=", "{", "nodes", ":", "data", ".", "nodes", ".", "map", "(", "n", "=>", "state", ".", "nodes", "[", "n", ".", "id", "]", "?", "Object", ".", "assign", "(", "{", "}", ",", "n", ",", "utils", ".", "pick", "(", "state", ".", "nodes", "[", "n", ".", "id", "]", ",", "NODE_PROPS_WHITELIST", ")", ")", ":", "Object", ".", "assign", "(", "{", "}", ",", "n", ")", ")", ",", "links", ":", "data", ".", "links", ".", "map", "(", "(", "l", ",", "index", ")", "=>", "_mapDataLinkToD3Link", "(", "l", ",", "index", ",", "state", "&&", "state", ".", "d3Links", ",", "config", ",", "state", ")", ")", ",", "}", ";", "}", "else", "{", "graph", "=", "{", "nodes", ":", "data", ".", "nodes", ".", "map", "(", "n", "=>", "Object", ".", "assign", "(", "{", "}", ",", "n", ")", ")", ",", "links", ":", "data", ".", "links", ".", "map", "(", "l", "=>", "Object", ".", "assign", "(", "{", "}", ",", "l", ")", ")", ",", "}", ";", "}", "let", "newConfig", "=", "Object", ".", "assign", "(", "{", "}", ",", "utils", ".", "merge", "(", "DEFAULT_CONFIG", ",", "config", "||", "{", "}", ")", ")", ";", "let", "links", "=", "_initializeLinks", "(", "graph", ".", "links", ",", "newConfig", ")", ";", "// matrix of graph connections", "let", "nodes", "=", "_tagOrphanNodes", "(", "_initializeNodes", "(", "graph", ".", "nodes", ")", ",", "links", ")", ";", "const", "{", "nodes", ":", "d3Nodes", ",", "links", ":", "d3Links", "}", "=", "graph", ";", "const", "formatedId", "=", "id", ".", "replace", "(", "/", " ", "/", "g", ",", "\"_\"", ")", ";", "const", "simulation", "=", "_createForceSimulation", "(", "newConfig", ".", "width", ",", "newConfig", ".", "height", ",", "newConfig", ".", "d3", "&&", "newConfig", ".", "d3", ".", "gravity", ")", ";", "const", "{", "minZoom", ",", "maxZoom", ",", "focusZoom", "}", "=", "newConfig", ";", "if", "(", "focusZoom", ">", "maxZoom", ")", "{", "newConfig", ".", "focusZoom", "=", "maxZoom", ";", "}", "else", "if", "(", "focusZoom", "<", "minZoom", ")", "{", "newConfig", ".", "focusZoom", "=", "minZoom", ";", "}", "return", "{", "id", ":", "formatedId", ",", "config", ":", "newConfig", ",", "links", ",", "d3Links", ",", "nodes", ",", "d3Nodes", ",", "highlightedNode", ":", "\"\"", ",", "simulation", ",", "newGraphElements", ":", "false", ",", "configUpdated", ":", "false", ",", "transform", ":", "1", ",", "}", ";", "}" ]
Encapsulates common procedures to initialize graph. @param {Object} props - Graph component props, object that holds data, id and config. @param {Object} props.data - Data object holds links (array of **Link**) and nodes (array of **Node**). @param {string} props.id - the graph id. @param {Object} props.config - same as {@link #graphrenderer|config in renderGraph}. @param {Object} state - Graph component current state (same format as returned object on this function). @returns {Object} a fully (re)initialized graph state object. @memberof Graph/helper
[ "Encapsulates", "common", "procedures", "to", "initialize", "graph", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/components/graph/graph.helper.js#L323-L372
8,146
danielcaldas/react-d3-graph
src/components/graph/graph.helper.js
updateNodeHighlightedValue
function updateNodeHighlightedValue(nodes, links, config, id, value = false) { const highlightedNode = value ? id : ""; const node = Object.assign({}, nodes[id], { highlighted: value }); let updatedNodes = Object.assign({}, nodes, { [id]: node }); // when highlightDegree is 0 we want only to highlight selected node if (links[id] && config.highlightDegree !== 0) { updatedNodes = Object.keys(links[id]).reduce((acc, linkId) => { const updatedNode = Object.assign({}, updatedNodes[linkId], { highlighted: value }); return Object.assign(acc, { [linkId]: updatedNode }); }, updatedNodes); } return { nodes: updatedNodes, highlightedNode, }; }
javascript
function updateNodeHighlightedValue(nodes, links, config, id, value = false) { const highlightedNode = value ? id : ""; const node = Object.assign({}, nodes[id], { highlighted: value }); let updatedNodes = Object.assign({}, nodes, { [id]: node }); // when highlightDegree is 0 we want only to highlight selected node if (links[id] && config.highlightDegree !== 0) { updatedNodes = Object.keys(links[id]).reduce((acc, linkId) => { const updatedNode = Object.assign({}, updatedNodes[linkId], { highlighted: value }); return Object.assign(acc, { [linkId]: updatedNode }); }, updatedNodes); } return { nodes: updatedNodes, highlightedNode, }; }
[ "function", "updateNodeHighlightedValue", "(", "nodes", ",", "links", ",", "config", ",", "id", ",", "value", "=", "false", ")", "{", "const", "highlightedNode", "=", "value", "?", "id", ":", "\"\"", ";", "const", "node", "=", "Object", ".", "assign", "(", "{", "}", ",", "nodes", "[", "id", "]", ",", "{", "highlighted", ":", "value", "}", ")", ";", "let", "updatedNodes", "=", "Object", ".", "assign", "(", "{", "}", ",", "nodes", ",", "{", "[", "id", "]", ":", "node", "}", ")", ";", "// when highlightDegree is 0 we want only to highlight selected node", "if", "(", "links", "[", "id", "]", "&&", "config", ".", "highlightDegree", "!==", "0", ")", "{", "updatedNodes", "=", "Object", ".", "keys", "(", "links", "[", "id", "]", ")", ".", "reduce", "(", "(", "acc", ",", "linkId", ")", "=>", "{", "const", "updatedNode", "=", "Object", ".", "assign", "(", "{", "}", ",", "updatedNodes", "[", "linkId", "]", ",", "{", "highlighted", ":", "value", "}", ")", ";", "return", "Object", ".", "assign", "(", "acc", ",", "{", "[", "linkId", "]", ":", "updatedNode", "}", ")", ";", "}", ",", "updatedNodes", ")", ";", "}", "return", "{", "nodes", ":", "updatedNodes", ",", "highlightedNode", ",", "}", ";", "}" ]
This function updates the highlighted value for a given node and also updates highlight props. @param {Object.<string, Object>} nodes - an object containing all nodes mapped by their id. @param {Object.<string, Object>} links - an object containing a matrix of connections of the graph. @param {Object} config - an object containing rd3g consumer defined configurations {@link #config config} for the graph. @param {string} id - identifier of node to update. @param {string} value - new highlight value for given node. @returns {Object} returns an object containing the updated nodes and the id of the highlighted node. @memberof Graph/helper
[ "This", "function", "updates", "the", "highlighted", "value", "for", "a", "given", "node", "and", "also", "updates", "highlight", "props", "." ]
d7911aef4eb79a5c2fd0368b39640b654dabfea4
https://github.com/danielcaldas/react-d3-graph/blob/d7911aef4eb79a5c2fd0368b39640b654dabfea4/src/components/graph/graph.helper.js#L385-L403
8,147
blockchain/service-my-wallet-v3
src/create.js
function (uuids) { var guid = uuids[0] var sharedKey = uuids[1] if (!guid || !sharedKey || guid.length !== 36 || sharedKey.length !== 36) { throw 'Error generating wallet identifier' } return { guid: guid, sharedKey: sharedKey } }
javascript
function (uuids) { var guid = uuids[0] var sharedKey = uuids[1] if (!guid || !sharedKey || guid.length !== 36 || sharedKey.length !== 36) { throw 'Error generating wallet identifier' } return { guid: guid, sharedKey: sharedKey } }
[ "function", "(", "uuids", ")", "{", "var", "guid", "=", "uuids", "[", "0", "]", "var", "sharedKey", "=", "uuids", "[", "1", "]", "if", "(", "!", "guid", "||", "!", "sharedKey", "||", "guid", ".", "length", "!==", "36", "||", "sharedKey", ".", "length", "!==", "36", ")", "{", "throw", "'Error generating wallet identifier'", "}", "return", "{", "guid", ":", "guid", ",", "sharedKey", ":", "sharedKey", "}", "}" ]
Handle response from WalletNetwork
[ "Handle", "response", "from", "WalletNetwork" ]
5af1ca6195a883cb6736e0f55f257d04147b0312
https://github.com/blockchain/service-my-wallet-v3/blob/5af1ca6195a883cb6736e0f55f257d04147b0312/src/create.js#L44-L53
8,148
blockchain/service-my-wallet-v3
src/create.js
function (uuids) { var walletJSON = { guid: uuids.guid, sharedKey: uuids.sharedKey, double_encryption: false, options: { pbkdf2_iterations: 5000, html5_notifications: false, fee_per_kb: 10000, logout_time: 600000 } } var createHdWallet = function (label) { label = label == null ? 'My Bitcoin Wallet' : label var mnemonic = BIP39.generateMnemonic(undefined, Blockchain.RNG.run.bind(Blockchain.RNG)) var hd = HDWallet.new(mnemonic) hd.newAccount(label) return hd } var createLegacyAddress = function (priv, label) { return priv ? Address.import(priv, label) : Address.new(label) } if (isHdWallet) { var hdJSON = createHdWallet(firstLabel).toJSON() hdJSON.accounts = hdJSON.accounts.map(function (a) { return a.toJSON() }) walletJSON.hd_wallets = [hdJSON] } else { winston.warn(warnings.CREATED_NON_HD) var firstAddress = createLegacyAddress(privateKey, firstLabel) walletJSON.keys = [firstAddress.toJSON()] } if (typeof secPass === 'string' && secPass.length) { walletJSON = JSON.parse(JSON.stringify(new Wallet(walletJSON).encrypt(secPass))) } return walletJSON }
javascript
function (uuids) { var walletJSON = { guid: uuids.guid, sharedKey: uuids.sharedKey, double_encryption: false, options: { pbkdf2_iterations: 5000, html5_notifications: false, fee_per_kb: 10000, logout_time: 600000 } } var createHdWallet = function (label) { label = label == null ? 'My Bitcoin Wallet' : label var mnemonic = BIP39.generateMnemonic(undefined, Blockchain.RNG.run.bind(Blockchain.RNG)) var hd = HDWallet.new(mnemonic) hd.newAccount(label) return hd } var createLegacyAddress = function (priv, label) { return priv ? Address.import(priv, label) : Address.new(label) } if (isHdWallet) { var hdJSON = createHdWallet(firstLabel).toJSON() hdJSON.accounts = hdJSON.accounts.map(function (a) { return a.toJSON() }) walletJSON.hd_wallets = [hdJSON] } else { winston.warn(warnings.CREATED_NON_HD) var firstAddress = createLegacyAddress(privateKey, firstLabel) walletJSON.keys = [firstAddress.toJSON()] } if (typeof secPass === 'string' && secPass.length) { walletJSON = JSON.parse(JSON.stringify(new Wallet(walletJSON).encrypt(secPass))) } return walletJSON }
[ "function", "(", "uuids", ")", "{", "var", "walletJSON", "=", "{", "guid", ":", "uuids", ".", "guid", ",", "sharedKey", ":", "uuids", ".", "sharedKey", ",", "double_encryption", ":", "false", ",", "options", ":", "{", "pbkdf2_iterations", ":", "5000", ",", "html5_notifications", ":", "false", ",", "fee_per_kb", ":", "10000", ",", "logout_time", ":", "600000", "}", "}", "var", "createHdWallet", "=", "function", "(", "label", ")", "{", "label", "=", "label", "==", "null", "?", "'My Bitcoin Wallet'", ":", "label", "var", "mnemonic", "=", "BIP39", ".", "generateMnemonic", "(", "undefined", ",", "Blockchain", ".", "RNG", ".", "run", ".", "bind", "(", "Blockchain", ".", "RNG", ")", ")", "var", "hd", "=", "HDWallet", ".", "new", "(", "mnemonic", ")", "hd", ".", "newAccount", "(", "label", ")", "return", "hd", "}", "var", "createLegacyAddress", "=", "function", "(", "priv", ",", "label", ")", "{", "return", "priv", "?", "Address", ".", "import", "(", "priv", ",", "label", ")", ":", "Address", ".", "new", "(", "label", ")", "}", "if", "(", "isHdWallet", ")", "{", "var", "hdJSON", "=", "createHdWallet", "(", "firstLabel", ")", ".", "toJSON", "(", ")", "hdJSON", ".", "accounts", "=", "hdJSON", ".", "accounts", ".", "map", "(", "function", "(", "a", ")", "{", "return", "a", ".", "toJSON", "(", ")", "}", ")", "walletJSON", ".", "hd_wallets", "=", "[", "hdJSON", "]", "}", "else", "{", "winston", ".", "warn", "(", "warnings", ".", "CREATED_NON_HD", ")", "var", "firstAddress", "=", "createLegacyAddress", "(", "privateKey", ",", "firstLabel", ")", "walletJSON", ".", "keys", "=", "[", "firstAddress", ".", "toJSON", "(", ")", "]", "}", "if", "(", "typeof", "secPass", "===", "'string'", "&&", "secPass", ".", "length", ")", "{", "walletJSON", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "new", "Wallet", "(", "walletJSON", ")", ".", "encrypt", "(", "secPass", ")", ")", ")", "}", "return", "walletJSON", "}" ]
Generate new Wallet JSON, add first key
[ "Generate", "new", "Wallet", "JSON", "add", "first", "key" ]
5af1ca6195a883cb6736e0f55f257d04147b0312
https://github.com/blockchain/service-my-wallet-v3/blob/5af1ca6195a883cb6736e0f55f257d04147b0312/src/create.js#L56-L96
8,149
blockchain/service-my-wallet-v3
src/create.js
function (wallet) { var data = JSON.stringify(wallet, null, 2) var enc = Blockchain.WalletCrypto.encryptWallet(data, password, wallet.options.pbkdf2_iterations, 2.0) var check = sha256(enc).toString('hex') // Throws if there is an encryption error Blockchain.WalletCrypto.decryptWallet(enc, password, function () {}, function () { throw 'Failed to confirm successful encryption when generating new wallet' }) var postData = { guid: wallet.guid, sharedKey: wallet.sharedKey, length: enc.length, payload: enc, checksum: check, method: 'insert', format: 'plain' } if (email) postData.email = email return Blockchain.API.securePost('wallet', postData).then(function () { if (isHdWallet) { var account = wallet.hd_wallets[0].accounts[0] return { guid: wallet.guid, address: account.xpub, label: account.label } } else { var firstKey = wallet.keys[0] return { guid: wallet.guid, address: firstKey.addr, label: firstKey.label, warning: warnings.CREATED_NON_HD } } }) }
javascript
function (wallet) { var data = JSON.stringify(wallet, null, 2) var enc = Blockchain.WalletCrypto.encryptWallet(data, password, wallet.options.pbkdf2_iterations, 2.0) var check = sha256(enc).toString('hex') // Throws if there is an encryption error Blockchain.WalletCrypto.decryptWallet(enc, password, function () {}, function () { throw 'Failed to confirm successful encryption when generating new wallet' }) var postData = { guid: wallet.guid, sharedKey: wallet.sharedKey, length: enc.length, payload: enc, checksum: check, method: 'insert', format: 'plain' } if (email) postData.email = email return Blockchain.API.securePost('wallet', postData).then(function () { if (isHdWallet) { var account = wallet.hd_wallets[0].accounts[0] return { guid: wallet.guid, address: account.xpub, label: account.label } } else { var firstKey = wallet.keys[0] return { guid: wallet.guid, address: firstKey.addr, label: firstKey.label, warning: warnings.CREATED_NON_HD } } }) }
[ "function", "(", "wallet", ")", "{", "var", "data", "=", "JSON", ".", "stringify", "(", "wallet", ",", "null", ",", "2", ")", "var", "enc", "=", "Blockchain", ".", "WalletCrypto", ".", "encryptWallet", "(", "data", ",", "password", ",", "wallet", ".", "options", ".", "pbkdf2_iterations", ",", "2.0", ")", "var", "check", "=", "sha256", "(", "enc", ")", ".", "toString", "(", "'hex'", ")", "// Throws if there is an encryption error", "Blockchain", ".", "WalletCrypto", ".", "decryptWallet", "(", "enc", ",", "password", ",", "function", "(", ")", "{", "}", ",", "function", "(", ")", "{", "throw", "'Failed to confirm successful encryption when generating new wallet'", "}", ")", "var", "postData", "=", "{", "guid", ":", "wallet", ".", "guid", ",", "sharedKey", ":", "wallet", ".", "sharedKey", ",", "length", ":", "enc", ".", "length", ",", "payload", ":", "enc", ",", "checksum", ":", "check", ",", "method", ":", "'insert'", ",", "format", ":", "'plain'", "}", "if", "(", "email", ")", "postData", ".", "email", "=", "email", "return", "Blockchain", ".", "API", ".", "securePost", "(", "'wallet'", ",", "postData", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "isHdWallet", ")", "{", "var", "account", "=", "wallet", ".", "hd_wallets", "[", "0", "]", ".", "accounts", "[", "0", "]", "return", "{", "guid", ":", "wallet", ".", "guid", ",", "address", ":", "account", ".", "xpub", ",", "label", ":", "account", ".", "label", "}", "}", "else", "{", "var", "firstKey", "=", "wallet", ".", "keys", "[", "0", "]", "return", "{", "guid", ":", "wallet", ".", "guid", ",", "address", ":", "firstKey", ".", "addr", ",", "label", ":", "firstKey", ".", "label", ",", "warning", ":", "warnings", ".", "CREATED_NON_HD", "}", "}", "}", ")", "}" ]
Encrypt and push new wallet to server
[ "Encrypt", "and", "push", "new", "wallet", "to", "server" ]
5af1ca6195a883cb6736e0f55f257d04147b0312
https://github.com/blockchain/service-my-wallet-v3/blob/5af1ca6195a883cb6736e0f55f257d04147b0312/src/create.js#L99-L130
8,150
google/traceur-compiler
demo/generators.js
fib
function fib(max) { var a = 0, b = 1; var results = []; while (b < max) { results.push(b); [a, b] = [b, a + b]; } return results; }
javascript
function fib(max) { var a = 0, b = 1; var results = []; while (b < max) { results.push(b); [a, b] = [b, a + b]; } return results; }
[ "function", "fib", "(", "max", ")", "{", "var", "a", "=", "0", ",", "b", "=", "1", ";", "var", "results", "=", "[", "]", ";", "while", "(", "b", "<", "max", ")", "{", "results", ".", "push", "(", "b", ")", ";", "[", "a", ",", "b", "]", "=", "[", "b", ",", "a", "+", "b", "]", ";", "}", "return", "results", ";", "}" ]
Example 2. Fibonacci precomputes a fixed set
[ "Example", "2", ".", "Fibonacci", "precomputes", "a", "fixed", "set" ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/demo/generators.js#L26-L34
8,151
google/traceur-compiler
demo/generators.js
tree
function tree(list) { var n = list.length; if (n == 0) { return null; } var i = Math.floor(n / 2); return new Tree(list[i], tree(list.slice(0, i)), tree(list.slice(i + 1))); }
javascript
function tree(list) { var n = list.length; if (n == 0) { return null; } var i = Math.floor(n / 2); return new Tree(list[i], tree(list.slice(0, i)), tree(list.slice(i + 1))); }
[ "function", "tree", "(", "list", ")", "{", "var", "n", "=", "list", ".", "length", ";", "if", "(", "n", "==", "0", ")", "{", "return", "null", ";", "}", "var", "i", "=", "Math", ".", "floor", "(", "n", "/", "2", ")", ";", "return", "new", "Tree", "(", "list", "[", "i", "]", ",", "tree", "(", "list", ".", "slice", "(", "0", ",", "i", ")", ")", ",", "tree", "(", "list", ".", "slice", "(", "i", "+", "1", ")", ")", ")", ";", "}" ]
Create a Tree from a list.
[ "Create", "a", "Tree", "from", "a", "list", "." ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/demo/generators.js#L56-L63
8,152
google/traceur-compiler
src/runtime/polyfills/ArrayIterator.js
createArrayIterator
function createArrayIterator(array, kind) { var object = toObject(array); var iterator = new ArrayIterator; iterator.iteratorObject_ = object; iterator.arrayIteratorNextIndex_ = 0; iterator.arrayIterationKind_ = kind; return iterator; }
javascript
function createArrayIterator(array, kind) { var object = toObject(array); var iterator = new ArrayIterator; iterator.iteratorObject_ = object; iterator.arrayIteratorNextIndex_ = 0; iterator.arrayIterationKind_ = kind; return iterator; }
[ "function", "createArrayIterator", "(", "array", ",", "kind", ")", "{", "var", "object", "=", "toObject", "(", "array", ")", ";", "var", "iterator", "=", "new", "ArrayIterator", ";", "iterator", ".", "iteratorObject_", "=", "object", ";", "iterator", ".", "arrayIteratorNextIndex_", "=", "0", ";", "iterator", ".", "arrayIterationKind_", "=", "kind", ";", "return", "iterator", ";", "}" ]
15.4.5.1 CreateArrayIterator Abstract Operation
[ "15", ".", "4", ".", "5", ".", "1", "CreateArrayIterator", "Abstract", "Operation" ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/src/runtime/polyfills/ArrayIterator.js#L66-L73
8,153
google/traceur-compiler
third_party/es6-module-loader/system.js
traverse
function traverse(object, iterator, parent, parentProperty) { var key, child; if (iterator(object, parent, parentProperty) === false) return; for (key in object) { if (!object.hasOwnProperty(key)) continue; if (key == 'location' || key == 'type') continue; child = object[key]; if (typeof child == 'object' && child !== null) traverse(child, iterator, object, key); } }
javascript
function traverse(object, iterator, parent, parentProperty) { var key, child; if (iterator(object, parent, parentProperty) === false) return; for (key in object) { if (!object.hasOwnProperty(key)) continue; if (key == 'location' || key == 'type') continue; child = object[key]; if (typeof child == 'object' && child !== null) traverse(child, iterator, object, key); } }
[ "function", "traverse", "(", "object", ",", "iterator", ",", "parent", ",", "parentProperty", ")", "{", "var", "key", ",", "child", ";", "if", "(", "iterator", "(", "object", ",", "parent", ",", "parentProperty", ")", "===", "false", ")", "return", ";", "for", "(", "key", "in", "object", ")", "{", "if", "(", "!", "object", ".", "hasOwnProperty", "(", "key", ")", ")", "continue", ";", "if", "(", "key", "==", "'location'", "||", "key", "==", "'type'", ")", "continue", ";", "child", "=", "object", "[", "key", "]", ";", "if", "(", "typeof", "child", "==", "'object'", "&&", "child", "!==", "null", ")", "traverse", "(", "child", ",", "iterator", ",", "object", ",", "key", ")", ";", "}", "}" ]
tree traversal, NB should use visitor pattern here
[ "tree", "traversal", "NB", "should", "use", "visitor", "pattern", "here" ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/third_party/es6-module-loader/system.js#L136-L149
8,154
google/traceur-compiler
third_party/es6-module-loader/system.js
__eval
function __eval(__source, __global, load) { // Hijack System.register to set declare function System.__curRegister = System.register; System.register = function(name, deps, declare) { // store the registered declaration as load.declare load.declare = typeof name == 'string' ? declare : deps; } eval('var __moduleName = "' + (load.name || '').replace('"', '\"') + '"; (function() { ' + __source + ' \n }).call(__global);'); System.register = System.__curRegister; delete System.__curRegister; }
javascript
function __eval(__source, __global, load) { // Hijack System.register to set declare function System.__curRegister = System.register; System.register = function(name, deps, declare) { // store the registered declaration as load.declare load.declare = typeof name == 'string' ? declare : deps; } eval('var __moduleName = "' + (load.name || '').replace('"', '\"') + '"; (function() { ' + __source + ' \n }).call(__global);'); System.register = System.__curRegister; delete System.__curRegister; }
[ "function", "__eval", "(", "__source", ",", "__global", ",", "load", ")", "{", "// Hijack System.register to set declare function", "System", ".", "__curRegister", "=", "System", ".", "register", ";", "System", ".", "register", "=", "function", "(", "name", ",", "deps", ",", "declare", ")", "{", "// store the registered declaration as load.declare", "load", ".", "declare", "=", "typeof", "name", "==", "'string'", "?", "declare", ":", "deps", ";", "}", "eval", "(", "'var __moduleName = \"'", "+", "(", "load", ".", "name", "||", "''", ")", ".", "replace", "(", "'\"'", ",", "'\\\"'", ")", "+", "'\"; (function() { '", "+", "__source", "+", "' \\n }).call(__global);'", ")", ";", "System", ".", "register", "=", "System", ".", "__curRegister", ";", "delete", "System", ".", "__curRegister", ";", "}" ]
Define our eval outside of the scope of any other reference defined in this file to avoid adding those references to the evaluation scope.
[ "Define", "our", "eval", "outside", "of", "the", "scope", "of", "any", "other", "reference", "defined", "in", "this", "file", "to", "avoid", "adding", "those", "references", "to", "the", "evaluation", "scope", "." ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/third_party/es6-module-loader/system.js#L367-L378
8,155
google/traceur-compiler
src/node/deferred.js
wrapModule
function wrapModule(module, functions) { if (typeof module === 'string') module = require(module); if (!functions) { for (var k in module) { // HACK: wrap all functions with a fnSync variant. if (typeof module[k] === 'function' && typeof module[k + 'Sync'] === 'function') module[k] = wrapFunction(module[k]); } } else { for (var i = 0, k; i < functions.length; i++) { var k = functions[i]; module[k] = wrapFunction(module[k]); } } return module; }
javascript
function wrapModule(module, functions) { if (typeof module === 'string') module = require(module); if (!functions) { for (var k in module) { // HACK: wrap all functions with a fnSync variant. if (typeof module[k] === 'function' && typeof module[k + 'Sync'] === 'function') module[k] = wrapFunction(module[k]); } } else { for (var i = 0, k; i < functions.length; i++) { var k = functions[i]; module[k] = wrapFunction(module[k]); } } return module; }
[ "function", "wrapModule", "(", "module", ",", "functions", ")", "{", "if", "(", "typeof", "module", "===", "'string'", ")", "module", "=", "require", "(", "module", ")", ";", "if", "(", "!", "functions", ")", "{", "for", "(", "var", "k", "in", "module", ")", "{", "// HACK: wrap all functions with a fnSync variant.", "if", "(", "typeof", "module", "[", "k", "]", "===", "'function'", "&&", "typeof", "module", "[", "k", "+", "'Sync'", "]", "===", "'function'", ")", "module", "[", "k", "]", "=", "wrapFunction", "(", "module", "[", "k", "]", ")", ";", "}", "}", "else", "{", "for", "(", "var", "i", "=", "0", ",", "k", ";", "i", "<", "functions", ".", "length", ";", "i", "++", ")", "{", "var", "k", "=", "functions", "[", "i", "]", ";", "module", "[", "k", "]", "=", "wrapFunction", "(", "module", "[", "k", "]", ")", ";", "}", "}", "return", "module", ";", "}" ]
Wrap async functions in a module to enable the use of await. If no function name array is provided, every function with a fnSync variant will be wrapped. @param {string|Object} module The exports of the module or a string that will be passed to require to get the module. @param {Array.<string>} functions Function names to wrap. @return {object} The module.
[ "Wrap", "async", "functions", "in", "a", "module", "to", "enable", "the", "use", "of", "await", ".", "If", "no", "function", "name", "array", "is", "provided", "every", "function", "with", "a", "fnSync", "variant", "will", "be", "wrapped", "." ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/src/node/deferred.js#L76-L95
8,156
google/traceur-compiler
build/minifier.js
printCompilerMsg
function printCompilerMsg(msg, file) { console.error('%s:%d:%d %s - %s', file || msg.file, msg.lineno + 1, msg.charno + 1, msg.type, msg.error); console.error('%s\n%s^', msg.line, Array(msg.charno + 1).join(' ')); }
javascript
function printCompilerMsg(msg, file) { console.error('%s:%d:%d %s - %s', file || msg.file, msg.lineno + 1, msg.charno + 1, msg.type, msg.error); console.error('%s\n%s^', msg.line, Array(msg.charno + 1).join(' ')); }
[ "function", "printCompilerMsg", "(", "msg", ",", "file", ")", "{", "console", ".", "error", "(", "'%s:%d:%d %s - %s'", ",", "file", "||", "msg", ".", "file", ",", "msg", ".", "lineno", "+", "1", ",", "msg", ".", "charno", "+", "1", ",", "msg", ".", "type", ",", "msg", ".", "error", ")", ";", "console", ".", "error", "(", "'%s\\n%s^'", ",", "msg", ".", "line", ",", "Array", "(", "msg", ".", "charno", "+", "1", ")", ".", "join", "(", "' '", ")", ")", ";", "}" ]
Prints a formatted error or warning message. @param {CompilerMsg} msg An error or warning message as returned by the Closure Compiler Service's JSON output format. @param {string|null} file The filename to refer to in error messages. If null, then msg.file is used instead.
[ "Prints", "a", "formatted", "error", "or", "warning", "message", "." ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/build/minifier.js#L29-L35
8,157
google/traceur-compiler
build/minifier.js
mergedCompilerMsgLists
function mergedCompilerMsgLists(list1, list2) { var list = []; list1 = list1 || []; list2 = list2 || []; function lessThan(e1, e2) { if (e1.lineno < e2.lineno) return true; return e1.lineno === e2.lineno && e1.charno < e2.charno; } var i1 = 0, i2 = 0; while (true) { if (i1 >= list1.length) return list.concat(list2.slice(i2)); if (i2 >= list2.length) return list.concat(list1.slice(i1)); if (lessThan(list1[i1], list2[i2])) list.push(list1[i1++]); else list.push(list2[i2++]); } }
javascript
function mergedCompilerMsgLists(list1, list2) { var list = []; list1 = list1 || []; list2 = list2 || []; function lessThan(e1, e2) { if (e1.lineno < e2.lineno) return true; return e1.lineno === e2.lineno && e1.charno < e2.charno; } var i1 = 0, i2 = 0; while (true) { if (i1 >= list1.length) return list.concat(list2.slice(i2)); if (i2 >= list2.length) return list.concat(list1.slice(i1)); if (lessThan(list1[i1], list2[i2])) list.push(list1[i1++]); else list.push(list2[i2++]); } }
[ "function", "mergedCompilerMsgLists", "(", "list1", ",", "list2", ")", "{", "var", "list", "=", "[", "]", ";", "list1", "=", "list1", "||", "[", "]", ";", "list2", "=", "list2", "||", "[", "]", ";", "function", "lessThan", "(", "e1", ",", "e2", ")", "{", "if", "(", "e1", ".", "lineno", "<", "e2", ".", "lineno", ")", "return", "true", ";", "return", "e1", ".", "lineno", "===", "e2", ".", "lineno", "&&", "e1", ".", "charno", "<", "e2", ".", "charno", ";", "}", "var", "i1", "=", "0", ",", "i2", "=", "0", ";", "while", "(", "true", ")", "{", "if", "(", "i1", ">=", "list1", ".", "length", ")", "return", "list", ".", "concat", "(", "list2", ".", "slice", "(", "i2", ")", ")", ";", "if", "(", "i2", ">=", "list2", ".", "length", ")", "return", "list", ".", "concat", "(", "list1", ".", "slice", "(", "i1", ")", ")", ";", "if", "(", "lessThan", "(", "list1", "[", "i1", "]", ",", "list2", "[", "i2", "]", ")", ")", "list", ".", "push", "(", "list1", "[", "i1", "++", "]", ")", ";", "else", "list", ".", "push", "(", "list2", "[", "i2", "++", "]", ")", ";", "}", "}" ]
Used to merge the warning and error lists so that everything can be printed in lineno and charno order. If lineno and charno match, then list2 is chosen first. @param {Array.<CompilerMsg>} list1 @param {Array.<CompilerMsg>} list2
[ "Used", "to", "merge", "the", "warning", "and", "error", "lists", "so", "that", "everything", "can", "be", "printed", "in", "lineno", "and", "charno", "order", ".", "If", "lineno", "and", "charno", "match", "then", "list2", "is", "chosen", "first", "." ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/build/minifier.js#L44-L67
8,158
google/traceur-compiler
src/node/file-util.js
mkdirRecursive
function mkdirRecursive(dir) { var parts = path.normalize(dir).split(path.sep); dir = ''; for (var i = 0; i < parts.length; i++) { dir += parts[i] + path.sep; if (!existsSync(dir)) { fs.mkdirSync(dir, 0x1FD); // 0775 permissions } } }
javascript
function mkdirRecursive(dir) { var parts = path.normalize(dir).split(path.sep); dir = ''; for (var i = 0; i < parts.length; i++) { dir += parts[i] + path.sep; if (!existsSync(dir)) { fs.mkdirSync(dir, 0x1FD); // 0775 permissions } } }
[ "function", "mkdirRecursive", "(", "dir", ")", "{", "var", "parts", "=", "path", ".", "normalize", "(", "dir", ")", ".", "split", "(", "path", ".", "sep", ")", ";", "dir", "=", "''", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "dir", "+=", "parts", "[", "i", "]", "+", "path", ".", "sep", ";", "if", "(", "!", "existsSync", "(", "dir", ")", ")", "{", "fs", ".", "mkdirSync", "(", "dir", ",", "0x1FD", ")", ";", "// 0775 permissions", "}", "}", "}" ]
Recursively makes all directoires, similar to mkdir -p @param {string} dir
[ "Recursively", "makes", "all", "directoires", "similar", "to", "mkdir", "-", "p" ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/src/node/file-util.js#L26-L35
8,159
google/traceur-compiler
src/node/file-util.js
removeCommonPrefix
function removeCommonPrefix(basedir, filedir) { var baseparts = basedir.split(path.sep); var fileparts = filedir.split(path.sep); var i = 0; while (i < fileparts.length && fileparts[i] === baseparts[i]) { i++; } return fileparts.slice(i).join(path.sep); }
javascript
function removeCommonPrefix(basedir, filedir) { var baseparts = basedir.split(path.sep); var fileparts = filedir.split(path.sep); var i = 0; while (i < fileparts.length && fileparts[i] === baseparts[i]) { i++; } return fileparts.slice(i).join(path.sep); }
[ "function", "removeCommonPrefix", "(", "basedir", ",", "filedir", ")", "{", "var", "baseparts", "=", "basedir", ".", "split", "(", "path", ".", "sep", ")", ";", "var", "fileparts", "=", "filedir", ".", "split", "(", "path", ".", "sep", ")", ";", "var", "i", "=", "0", ";", "while", "(", "i", "<", "fileparts", ".", "length", "&&", "fileparts", "[", "i", "]", "===", "baseparts", "[", "i", "]", ")", "{", "i", "++", ";", "}", "return", "fileparts", ".", "slice", "(", "i", ")", ".", "join", "(", "path", ".", "sep", ")", ";", "}" ]
Removes the common prefix of basedir and filedir from filedir @param {string} basedir @param {string} filedir
[ "Removes", "the", "common", "prefix", "of", "basedir", "and", "filedir", "from", "filedir" ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/src/node/file-util.js#L42-L51
8,160
google/traceur-compiler
src/syntax/Scanner.js
scanTemplateStart
function scanTemplateStart(beginIndex) { if (isAtEnd()) { reportError('Unterminated template literal', beginIndex, index); return lastToken = createToken(END_OF_FILE, beginIndex); } return nextTemplateLiteralTokenShared(NO_SUBSTITUTION_TEMPLATE, TEMPLATE_HEAD); }
javascript
function scanTemplateStart(beginIndex) { if (isAtEnd()) { reportError('Unterminated template literal', beginIndex, index); return lastToken = createToken(END_OF_FILE, beginIndex); } return nextTemplateLiteralTokenShared(NO_SUBSTITUTION_TEMPLATE, TEMPLATE_HEAD); }
[ "function", "scanTemplateStart", "(", "beginIndex", ")", "{", "if", "(", "isAtEnd", "(", ")", ")", "{", "reportError", "(", "'Unterminated template literal'", ",", "beginIndex", ",", "index", ")", ";", "return", "lastToken", "=", "createToken", "(", "END_OF_FILE", ",", "beginIndex", ")", ";", "}", "return", "nextTemplateLiteralTokenShared", "(", "NO_SUBSTITUTION_TEMPLATE", ",", "TEMPLATE_HEAD", ")", ";", "}" ]
Either returns a NO_SUBSTITUTION_TEMPLATE or TEMPLATE_HEAD token.
[ "Either", "returns", "a", "NO_SUBSTITUTION_TEMPLATE", "or", "TEMPLATE_HEAD", "token", "." ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/src/syntax/Scanner.js#L444-L452
8,161
google/traceur-compiler
src/syntax/Scanner.js
scanJsxToken
function scanJsxToken() { skipComments(); let beginIndex = index; switch (currentCharCode) { case 34: // " case 39: // ' return scanJsxStringLiteral(beginIndex, currentCharCode); case 62: // > next(); return createToken(CLOSE_ANGLE, beginIndex); // case 123: // { // case 125: // } } if (!isIdentifierStart(currentCharCode)) { return scanToken(); } next(); while (isIdentifierPart(currentCharCode) || currentCharCode === 45) { // '-' next(); } let value = input.slice(beginIndex, index); return new JsxIdentifierToken(getTokenRange(beginIndex), value); }
javascript
function scanJsxToken() { skipComments(); let beginIndex = index; switch (currentCharCode) { case 34: // " case 39: // ' return scanJsxStringLiteral(beginIndex, currentCharCode); case 62: // > next(); return createToken(CLOSE_ANGLE, beginIndex); // case 123: // { // case 125: // } } if (!isIdentifierStart(currentCharCode)) { return scanToken(); } next(); while (isIdentifierPart(currentCharCode) || currentCharCode === 45) { // '-' next(); } let value = input.slice(beginIndex, index); return new JsxIdentifierToken(getTokenRange(beginIndex), value); }
[ "function", "scanJsxToken", "(", ")", "{", "skipComments", "(", ")", ";", "let", "beginIndex", "=", "index", ";", "switch", "(", "currentCharCode", ")", "{", "case", "34", ":", "// \"", "case", "39", ":", "// '", "return", "scanJsxStringLiteral", "(", "beginIndex", ",", "currentCharCode", ")", ";", "case", "62", ":", "// >", "next", "(", ")", ";", "return", "createToken", "(", "CLOSE_ANGLE", ",", "beginIndex", ")", ";", "// case 123: // {", "// case 125: // }", "}", "if", "(", "!", "isIdentifierStart", "(", "currentCharCode", ")", ")", "{", "return", "scanToken", "(", ")", ";", "}", "next", "(", ")", ";", "while", "(", "isIdentifierPart", "(", "currentCharCode", ")", "||", "currentCharCode", "===", "45", ")", "{", "// '-'", "next", "(", ")", ";", "}", "let", "value", "=", "input", ".", "slice", "(", "beginIndex", ",", "index", ")", ";", "return", "new", "JsxIdentifierToken", "(", "getTokenRange", "(", "beginIndex", ")", ",", "value", ")", ";", "}" ]
Used to scan for a JSXIdentifier.
[ "Used", "to", "scan", "for", "a", "JSXIdentifier", "." ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/src/syntax/Scanner.js#L520-L543
8,162
google/traceur-compiler
src/codegeneration/BlockBindingTransformer.js
varNeedsInitializer
function varNeedsInitializer(tree, loopTree) { if (loopTree === null) return false; // Loop initializers for for-in/for-of must not have an initializer RHS. let type = loopTree.type; if (type !== FOR_IN_STATEMENT && type !== FOR_OF_STATEMENT) return true; return loopTree.initializer.declarations[0] !== tree; }
javascript
function varNeedsInitializer(tree, loopTree) { if (loopTree === null) return false; // Loop initializers for for-in/for-of must not have an initializer RHS. let type = loopTree.type; if (type !== FOR_IN_STATEMENT && type !== FOR_OF_STATEMENT) return true; return loopTree.initializer.declarations[0] !== tree; }
[ "function", "varNeedsInitializer", "(", "tree", ",", "loopTree", ")", "{", "if", "(", "loopTree", "===", "null", ")", "return", "false", ";", "// Loop initializers for for-in/for-of must not have an initializer RHS.", "let", "type", "=", "loopTree", ".", "type", ";", "if", "(", "type", "!==", "FOR_IN_STATEMENT", "&&", "type", "!==", "FOR_OF_STATEMENT", ")", "return", "true", ";", "return", "loopTree", ".", "initializer", ".", "declarations", "[", "0", "]", "!==", "tree", ";", "}" ]
Transforms the block bindings from traceur to js. In most cases, let can be transformed to var straight away and renamed to avoid name collisions. Making a if (true) { let t = 5; } Become a if (true) { var t$__0 = 5; } The only special case is in Iterable statements. For those, we only use a different strategy if they use let in them and they define functions that use those block binded variables. In that case, the loop content is extracted to a function, that gets called on every iteration with its arguments being any variable declared in the loop initializer. If the loop contained any break/continue statements, they get extracted and transformed to return statements of numbers, that correspond to the correct statement in a switch case. Example: for (let i = 0; i < 5; i++) { if (i === 3) break; setTimeout(function () { log(i); }); } Becomes: // the loop content extracted to a function var $__2 = function (i) { if (i === 3) return 0; setTimeout(function () { log(i); }); }, $__3; // the loop gets labelled if needed (it is here) $__1: for (var i$__0 = 0; i$__0 < 5; i$__0++) { $__3 = $__2(i$__0); switch($__3) { case 0: break $__1; // breaks the loop } } If the loop contained return statements, they get transformed to returning object which preserver the scope in which the expression get executed. Example: for (let i = 0; i < 5; i++) { if (i === 3) return i + 10; // without this the let would just become a var setTimeout(function () { log(i) }); } Becomes: var $__1 = function(i) { if (i === 3) return {v: i + 10}; setTimeout(function() { log(i); }); }, $__2; for (var i$__0 = 0; i$__0 < 5; i$__0++) { $__2 = $__1(i$__0); if (typeof $__2 === "object") return $__2.v; } If a loop contained both break/continue and return statements, the if-typeof statement from the second example would be added as a default clause to the switch statement of the first example. const variables are handled the same way. The block binding rewrite pass assumes that deconstructing assignments and variable declarations have already been desugared. See getVariableName_. Note: If the transformation happens inside a generator, the inner function becomes an inner generator.
[ "Transforms", "the", "block", "bindings", "from", "traceur", "to", "js", "." ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/src/codegeneration/BlockBindingTransformer.js#L152-L159
8,163
google/traceur-compiler
src/node/recursiveModuleCompile.js
recursiveModuleCompile
function recursiveModuleCompile(fileNamesAndTypes, options) { var referrerName = options && options.referrer; var basePath = path.resolve('./') + '/'; basePath = basePath.replace(/\\/g, '/'); var elements = []; var loaderCompiler = new InlineLoaderCompiler(elements); var loader = new TraceurLoader(nodeLoader, basePath, loaderCompiler); function appendEvaluateModule(name) { var normalizedName = $traceurRuntime.ModuleStore.normalize(name, referrerName); // Create tree for $traceurRuntime.getModule('normalizedName'); var moduleModule = traceur.codegeneration.module; var tree = moduleModule.createModuleEvaluationStatement(normalizedName); elements.push(tree); } function loadInput(input) { var doEvaluateModule = false; var loadFunction = loader.import; var name = input.name; var optionsCopy = new Options(options); // Give each load a copy of options. if (input.type === 'script') { loadFunction = loader.loadAsScript; } else if (optionsCopy.modules === 'bootstrap') { doEvaluateModule = true; } var loadOptions = { referrerName: referrerName, metadata: { traceurOptions: optionsCopy, rootModule: input.rootModule && input.name } }; return loadFunction.call(loader, name, loadOptions).then(function() { if (doEvaluateModule) { appendEvaluateModule(name); } }); } return sequencePromises(fileNamesAndTypes, loadInput).then(function() { return loaderCompiler.toTree(); }); }
javascript
function recursiveModuleCompile(fileNamesAndTypes, options) { var referrerName = options && options.referrer; var basePath = path.resolve('./') + '/'; basePath = basePath.replace(/\\/g, '/'); var elements = []; var loaderCompiler = new InlineLoaderCompiler(elements); var loader = new TraceurLoader(nodeLoader, basePath, loaderCompiler); function appendEvaluateModule(name) { var normalizedName = $traceurRuntime.ModuleStore.normalize(name, referrerName); // Create tree for $traceurRuntime.getModule('normalizedName'); var moduleModule = traceur.codegeneration.module; var tree = moduleModule.createModuleEvaluationStatement(normalizedName); elements.push(tree); } function loadInput(input) { var doEvaluateModule = false; var loadFunction = loader.import; var name = input.name; var optionsCopy = new Options(options); // Give each load a copy of options. if (input.type === 'script') { loadFunction = loader.loadAsScript; } else if (optionsCopy.modules === 'bootstrap') { doEvaluateModule = true; } var loadOptions = { referrerName: referrerName, metadata: { traceurOptions: optionsCopy, rootModule: input.rootModule && input.name } }; return loadFunction.call(loader, name, loadOptions).then(function() { if (doEvaluateModule) { appendEvaluateModule(name); } }); } return sequencePromises(fileNamesAndTypes, loadInput).then(function() { return loaderCompiler.toTree(); }); }
[ "function", "recursiveModuleCompile", "(", "fileNamesAndTypes", ",", "options", ")", "{", "var", "referrerName", "=", "options", "&&", "options", ".", "referrer", ";", "var", "basePath", "=", "path", ".", "resolve", "(", "'./'", ")", "+", "'/'", ";", "basePath", "=", "basePath", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "'/'", ")", ";", "var", "elements", "=", "[", "]", ";", "var", "loaderCompiler", "=", "new", "InlineLoaderCompiler", "(", "elements", ")", ";", "var", "loader", "=", "new", "TraceurLoader", "(", "nodeLoader", ",", "basePath", ",", "loaderCompiler", ")", ";", "function", "appendEvaluateModule", "(", "name", ")", "{", "var", "normalizedName", "=", "$traceurRuntime", ".", "ModuleStore", ".", "normalize", "(", "name", ",", "referrerName", ")", ";", "// Create tree for $traceurRuntime.getModule('normalizedName');", "var", "moduleModule", "=", "traceur", ".", "codegeneration", ".", "module", ";", "var", "tree", "=", "moduleModule", ".", "createModuleEvaluationStatement", "(", "normalizedName", ")", ";", "elements", ".", "push", "(", "tree", ")", ";", "}", "function", "loadInput", "(", "input", ")", "{", "var", "doEvaluateModule", "=", "false", ";", "var", "loadFunction", "=", "loader", ".", "import", ";", "var", "name", "=", "input", ".", "name", ";", "var", "optionsCopy", "=", "new", "Options", "(", "options", ")", ";", "// Give each load a copy of options.", "if", "(", "input", ".", "type", "===", "'script'", ")", "{", "loadFunction", "=", "loader", ".", "loadAsScript", ";", "}", "else", "if", "(", "optionsCopy", ".", "modules", "===", "'bootstrap'", ")", "{", "doEvaluateModule", "=", "true", ";", "}", "var", "loadOptions", "=", "{", "referrerName", ":", "referrerName", ",", "metadata", ":", "{", "traceurOptions", ":", "optionsCopy", ",", "rootModule", ":", "input", ".", "rootModule", "&&", "input", ".", "name", "}", "}", ";", "return", "loadFunction", ".", "call", "(", "loader", ",", "name", ",", "loadOptions", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "doEvaluateModule", ")", "{", "appendEvaluateModule", "(", "name", ")", ";", "}", "}", ")", ";", "}", "return", "sequencePromises", "(", "fileNamesAndTypes", ",", "loadInput", ")", ".", "then", "(", "function", "(", ")", "{", "return", "loaderCompiler", ".", "toTree", "(", ")", ";", "}", ")", ";", "}" ]
Compiles the files in "fileNamesAndTypes" along with any associated modules, into a single js file, in module dependency order. @param {Array<Object>} fileNamesAndTypes The list of {name, type} to compile and concat; type is 'module' or 'script' @param {Object} options A container for misc options. 'referrer' is the only currently available option. @param {Function} callback Callback used to return the result. A null result indicates that recursiveModuleCompile has returned successfully from a non-compile request. @param {Function} errback Callback used to return errors.
[ "Compiles", "the", "files", "in", "fileNamesAndTypes", "along", "with", "any", "associated", "modules", "into", "a", "single", "js", "file", "in", "module", "dependency", "order", "." ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/src/node/recursiveModuleCompile.js#L111-L162
8,164
google/traceur-compiler
third_party/es6-module-loader/loader.js
proceedToLocate
function proceedToLocate(loader, load) { proceedToFetch(loader, load, Promise.resolve() // 15.2.4.3.1 CallLocate .then(function() { return loader.loaderObj.locate({ name: load.name, metadata: load.metadata }); }) ); }
javascript
function proceedToLocate(loader, load) { proceedToFetch(loader, load, Promise.resolve() // 15.2.4.3.1 CallLocate .then(function() { return loader.loaderObj.locate({ name: load.name, metadata: load.metadata }); }) ); }
[ "function", "proceedToLocate", "(", "loader", ",", "load", ")", "{", "proceedToFetch", "(", "loader", ",", "load", ",", "Promise", ".", "resolve", "(", ")", "// 15.2.4.3.1 CallLocate", ".", "then", "(", "function", "(", ")", "{", "return", "loader", ".", "loaderObj", ".", "locate", "(", "{", "name", ":", "load", ".", "name", ",", "metadata", ":", "load", ".", "metadata", "}", ")", ";", "}", ")", ")", ";", "}" ]
15.2.4.3
[ "15", ".", "2", ".", "4", ".", "3" ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/third_party/es6-module-loader/loader.js#L214-L222
8,165
google/traceur-compiler
third_party/es6-module-loader/loader.js
proceedToFetch
function proceedToFetch(loader, load, p) { proceedToTranslate(loader, load, p // 15.2.4.4.1 CallFetch .then(function(address) { // adjusted, see https://bugs.ecmascript.org/show_bug.cgi?id=2602 if (load.status != 'loading') return; load.address = address; return loader.loaderObj.fetch({ name: load.name, metadata: load.metadata, address: address }); }) ); }
javascript
function proceedToFetch(loader, load, p) { proceedToTranslate(loader, load, p // 15.2.4.4.1 CallFetch .then(function(address) { // adjusted, see https://bugs.ecmascript.org/show_bug.cgi?id=2602 if (load.status != 'loading') return; load.address = address; return loader.loaderObj.fetch({ name: load.name, metadata: load.metadata, address: address }); }) ); }
[ "function", "proceedToFetch", "(", "loader", ",", "load", ",", "p", ")", "{", "proceedToTranslate", "(", "loader", ",", "load", ",", "p", "// 15.2.4.4.1 CallFetch", ".", "then", "(", "function", "(", "address", ")", "{", "// adjusted, see https://bugs.ecmascript.org/show_bug.cgi?id=2602", "if", "(", "load", ".", "status", "!=", "'loading'", ")", "return", ";", "load", ".", "address", "=", "address", ";", "return", "loader", ".", "loaderObj", ".", "fetch", "(", "{", "name", ":", "load", ".", "name", ",", "metadata", ":", "load", ".", "metadata", ",", "address", ":", "address", "}", ")", ";", "}", ")", ")", ";", "}" ]
15.2.4.4
[ "15", ".", "2", ".", "4", ".", "4" ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/third_party/es6-module-loader/loader.js#L225-L238
8,166
google/traceur-compiler
third_party/es6-module-loader/loader.js
addLoadToLinkSet
function addLoadToLinkSet(linkSet, load) { console.assert(load.status == 'loading' || load.status == 'loaded', 'loading or loaded on link set'); for (var i = 0, l = linkSet.loads.length; i < l; i++) if (linkSet.loads[i] == load) return; linkSet.loads.push(load); load.linkSets.push(linkSet); // adjustment, see https://bugs.ecmascript.org/show_bug.cgi?id=2603 if (load.status != 'loaded') { linkSet.loadingCount++; } var loader = linkSet.loader; for (var i = 0, l = load.dependencies.length; i < l; i++) { var name = load.dependencies[i].value; if (loader.modules[name]) continue; for (var j = 0, d = loader.loads.length; j < d; j++) { if (loader.loads[j].name != name) continue; addLoadToLinkSet(linkSet, loader.loads[j]); break; } } // console.log('add to linkset ' + load.name); // snapshot(linkSet.loader); }
javascript
function addLoadToLinkSet(linkSet, load) { console.assert(load.status == 'loading' || load.status == 'loaded', 'loading or loaded on link set'); for (var i = 0, l = linkSet.loads.length; i < l; i++) if (linkSet.loads[i] == load) return; linkSet.loads.push(load); load.linkSets.push(linkSet); // adjustment, see https://bugs.ecmascript.org/show_bug.cgi?id=2603 if (load.status != 'loaded') { linkSet.loadingCount++; } var loader = linkSet.loader; for (var i = 0, l = load.dependencies.length; i < l; i++) { var name = load.dependencies[i].value; if (loader.modules[name]) continue; for (var j = 0, d = loader.loads.length; j < d; j++) { if (loader.loads[j].name != name) continue; addLoadToLinkSet(linkSet, loader.loads[j]); break; } } // console.log('add to linkset ' + load.name); // snapshot(linkSet.loader); }
[ "function", "addLoadToLinkSet", "(", "linkSet", ",", "load", ")", "{", "console", ".", "assert", "(", "load", ".", "status", "==", "'loading'", "||", "load", ".", "status", "==", "'loaded'", ",", "'loading or loaded on link set'", ")", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "linkSet", ".", "loads", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "if", "(", "linkSet", ".", "loads", "[", "i", "]", "==", "load", ")", "return", ";", "linkSet", ".", "loads", ".", "push", "(", "load", ")", ";", "load", ".", "linkSets", ".", "push", "(", "linkSet", ")", ";", "// adjustment, see https://bugs.ecmascript.org/show_bug.cgi?id=2603", "if", "(", "load", ".", "status", "!=", "'loaded'", ")", "{", "linkSet", ".", "loadingCount", "++", ";", "}", "var", "loader", "=", "linkSet", ".", "loader", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "load", ".", "dependencies", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "name", "=", "load", ".", "dependencies", "[", "i", "]", ".", "value", ";", "if", "(", "loader", ".", "modules", "[", "name", "]", ")", "continue", ";", "for", "(", "var", "j", "=", "0", ",", "d", "=", "loader", ".", "loads", ".", "length", ";", "j", "<", "d", ";", "j", "++", ")", "{", "if", "(", "loader", ".", "loads", "[", "j", "]", ".", "name", "!=", "name", ")", "continue", ";", "addLoadToLinkSet", "(", "linkSet", ",", "loader", ".", "loads", "[", "j", "]", ")", ";", "break", ";", "}", "}", "// console.log('add to linkset ' + load.name);", "// snapshot(linkSet.loader);", "}" ]
15.2.5.2.2
[ "15", ".", "2", ".", "5", ".", "2", ".", "2" ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/third_party/es6-module-loader/loader.js#L409-L442
8,167
google/traceur-compiler
third_party/es6-module-loader/loader.js
updateLinkSetOnLoad
function updateLinkSetOnLoad(linkSet, load) { // console.log('update linkset on load ' + load.name); // snapshot(linkSet.loader); console.assert(load.status == 'loaded' || load.status == 'linked', 'loaded or linked'); linkSet.loadingCount--; if (linkSet.loadingCount > 0) return; // adjusted for spec bug https://bugs.ecmascript.org/show_bug.cgi?id=2995 var startingLoad = linkSet.startingLoad; // non-executing link variation for loader tracing // on the server. Not in spec. /***/ if (linkSet.loader.loaderObj.execute === false) { var loads = [].concat(linkSet.loads); for (var i = 0, l = loads.length; i < l; i++) { var load = loads[i]; load.module = load.kind == 'dynamic' ? { module: _newModule({}) } : { name: load.name, module: _newModule({}), evaluated: true }; load.status = 'linked'; finishLoad(linkSet.loader, load); } return linkSet.resolve(startingLoad); } /***/ var abrupt = doLink(linkSet); if (abrupt) return; console.assert(linkSet.loads.length == 0, 'loads cleared'); linkSet.resolve(startingLoad); }
javascript
function updateLinkSetOnLoad(linkSet, load) { // console.log('update linkset on load ' + load.name); // snapshot(linkSet.loader); console.assert(load.status == 'loaded' || load.status == 'linked', 'loaded or linked'); linkSet.loadingCount--; if (linkSet.loadingCount > 0) return; // adjusted for spec bug https://bugs.ecmascript.org/show_bug.cgi?id=2995 var startingLoad = linkSet.startingLoad; // non-executing link variation for loader tracing // on the server. Not in spec. /***/ if (linkSet.loader.loaderObj.execute === false) { var loads = [].concat(linkSet.loads); for (var i = 0, l = loads.length; i < l; i++) { var load = loads[i]; load.module = load.kind == 'dynamic' ? { module: _newModule({}) } : { name: load.name, module: _newModule({}), evaluated: true }; load.status = 'linked'; finishLoad(linkSet.loader, load); } return linkSet.resolve(startingLoad); } /***/ var abrupt = doLink(linkSet); if (abrupt) return; console.assert(linkSet.loads.length == 0, 'loads cleared'); linkSet.resolve(startingLoad); }
[ "function", "updateLinkSetOnLoad", "(", "linkSet", ",", "load", ")", "{", "// console.log('update linkset on load ' + load.name);", "// snapshot(linkSet.loader);", "console", ".", "assert", "(", "load", ".", "status", "==", "'loaded'", "||", "load", ".", "status", "==", "'linked'", ",", "'loaded or linked'", ")", ";", "linkSet", ".", "loadingCount", "--", ";", "if", "(", "linkSet", ".", "loadingCount", ">", "0", ")", "return", ";", "// adjusted for spec bug https://bugs.ecmascript.org/show_bug.cgi?id=2995", "var", "startingLoad", "=", "linkSet", ".", "startingLoad", ";", "// non-executing link variation for loader tracing", "// on the server. Not in spec.", "/***/", "if", "(", "linkSet", ".", "loader", ".", "loaderObj", ".", "execute", "===", "false", ")", "{", "var", "loads", "=", "[", "]", ".", "concat", "(", "linkSet", ".", "loads", ")", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "loads", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "load", "=", "loads", "[", "i", "]", ";", "load", ".", "module", "=", "load", ".", "kind", "==", "'dynamic'", "?", "{", "module", ":", "_newModule", "(", "{", "}", ")", "}", ":", "{", "name", ":", "load", ".", "name", ",", "module", ":", "_newModule", "(", "{", "}", ")", ",", "evaluated", ":", "true", "}", ";", "load", ".", "status", "=", "'linked'", ";", "finishLoad", "(", "linkSet", ".", "loader", ",", "load", ")", ";", "}", "return", "linkSet", ".", "resolve", "(", "startingLoad", ")", ";", "}", "/***/", "var", "abrupt", "=", "doLink", "(", "linkSet", ")", ";", "if", "(", "abrupt", ")", "return", ";", "console", ".", "assert", "(", "linkSet", ".", "loads", ".", "length", "==", "0", ",", "'loads cleared'", ")", ";", "linkSet", ".", "resolve", "(", "startingLoad", ")", ";", "}" ]
15.2.5.2.3
[ "15", ".", "2", ".", "5", ".", "2", ".", "3" ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/third_party/es6-module-loader/loader.js#L455-L498
8,168
google/traceur-compiler
third_party/es6-module-loader/loader.js
finishLoad
function finishLoad(loader, load) { // add to global trace if tracing if (loader.loaderObj.trace) { if (!loader.loaderObj.loads) loader.loaderObj.loads = {}; var depMap = {}; load.dependencies.forEach(function(dep) { depMap[dep.key] = dep.value; }); loader.loaderObj.loads[load.name] = { name: load.name, deps: load.dependencies.map(function(dep){ return dep.key }), depMap: depMap, address: load.address, metadata: load.metadata, source: load.source, kind: load.kind }; } // if not anonymous, add to the module table if (load.name) { console.assert(!loader.modules[load.name], 'load not in module table'); loader.modules[load.name] = load.module; } var loadIndex = indexOf.call(loader.loads, load); if (loadIndex != -1) loader.loads.splice(loadIndex, 1); for (var i = 0, l = load.linkSets.length; i < l; i++) { loadIndex = indexOf.call(load.linkSets[i].loads, load); if (loadIndex != -1) load.linkSets[i].loads.splice(loadIndex, 1); } load.linkSets.splice(0, load.linkSets.length); }
javascript
function finishLoad(loader, load) { // add to global trace if tracing if (loader.loaderObj.trace) { if (!loader.loaderObj.loads) loader.loaderObj.loads = {}; var depMap = {}; load.dependencies.forEach(function(dep) { depMap[dep.key] = dep.value; }); loader.loaderObj.loads[load.name] = { name: load.name, deps: load.dependencies.map(function(dep){ return dep.key }), depMap: depMap, address: load.address, metadata: load.metadata, source: load.source, kind: load.kind }; } // if not anonymous, add to the module table if (load.name) { console.assert(!loader.modules[load.name], 'load not in module table'); loader.modules[load.name] = load.module; } var loadIndex = indexOf.call(loader.loads, load); if (loadIndex != -1) loader.loads.splice(loadIndex, 1); for (var i = 0, l = load.linkSets.length; i < l; i++) { loadIndex = indexOf.call(load.linkSets[i].loads, load); if (loadIndex != -1) load.linkSets[i].loads.splice(loadIndex, 1); } load.linkSets.splice(0, load.linkSets.length); }
[ "function", "finishLoad", "(", "loader", ",", "load", ")", "{", "// add to global trace if tracing", "if", "(", "loader", ".", "loaderObj", ".", "trace", ")", "{", "if", "(", "!", "loader", ".", "loaderObj", ".", "loads", ")", "loader", ".", "loaderObj", ".", "loads", "=", "{", "}", ";", "var", "depMap", "=", "{", "}", ";", "load", ".", "dependencies", ".", "forEach", "(", "function", "(", "dep", ")", "{", "depMap", "[", "dep", ".", "key", "]", "=", "dep", ".", "value", ";", "}", ")", ";", "loader", ".", "loaderObj", ".", "loads", "[", "load", ".", "name", "]", "=", "{", "name", ":", "load", ".", "name", ",", "deps", ":", "load", ".", "dependencies", ".", "map", "(", "function", "(", "dep", ")", "{", "return", "dep", ".", "key", "}", ")", ",", "depMap", ":", "depMap", ",", "address", ":", "load", ".", "address", ",", "metadata", ":", "load", ".", "metadata", ",", "source", ":", "load", ".", "source", ",", "kind", ":", "load", ".", "kind", "}", ";", "}", "// if not anonymous, add to the module table", "if", "(", "load", ".", "name", ")", "{", "console", ".", "assert", "(", "!", "loader", ".", "modules", "[", "load", ".", "name", "]", ",", "'load not in module table'", ")", ";", "loader", ".", "modules", "[", "load", ".", "name", "]", "=", "load", ".", "module", ";", "}", "var", "loadIndex", "=", "indexOf", ".", "call", "(", "loader", ".", "loads", ",", "load", ")", ";", "if", "(", "loadIndex", "!=", "-", "1", ")", "loader", ".", "loads", ".", "splice", "(", "loadIndex", ",", "1", ")", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "load", ".", "linkSets", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "loadIndex", "=", "indexOf", ".", "call", "(", "load", ".", "linkSets", "[", "i", "]", ".", "loads", ",", "load", ")", ";", "if", "(", "loadIndex", "!=", "-", "1", ")", "load", ".", "linkSets", "[", "i", "]", ".", "loads", ".", "splice", "(", "loadIndex", ",", "1", ")", ";", "}", "load", ".", "linkSets", ".", "splice", "(", "0", ",", "load", ".", "linkSets", ".", "length", ")", ";", "}" ]
15.2.5.2.5
[ "15", ".", "2", ".", "5", ".", "2", ".", "5" ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/third_party/es6-module-loader/loader.js#L525-L558
8,169
google/traceur-compiler
third_party/es6-module-loader/loader.js
linkDeclarativeModule
function linkDeclarativeModule(load, loads, loader) { if (load.module) return; var module = load.module = getOrCreateModuleRecord(load.name); var moduleObj = load.module.module; var registryEntry = load.declare.call(__global, function(name, value) { // NB This should be an Object.defineProperty, but that is very slow. // By disaling this module write-protection we gain performance. // It could be useful to allow an option to enable or disable this. // bulk export object if (typeof name == 'object') { for (var p in name) moduleObj[p] = name[p]; } // single export name / value pair else { moduleObj[name] = value; } for (var i = 0, l = module.importers.length; i < l; i++) { var importerModule = module.importers[i]; if (importerModule.setters) { var importerIndex = importerModule.dependencies.indexOf(module); if (importerIndex != -1) { var setter = importerModule.setters[importerIndex]; setter(moduleObj); } } } return value; }, {id: load.name}); // setup our setters and execution function load.module.setters = registryEntry.setters; load.module.execute = registryEntry.execute; // now link all the module dependencies // amending the depMap as we go for (var i = 0, l = load.dependencies.length; i < l; i++) { var depName = load.dependencies[i].value; var depModule = getOrCreateModuleRecord(depName); depModule.importers.push(module); // if not already a module in the registry, try and link it now if (!loader.modules[depName]) { // get the dependency load record for (var j = 0; j < loads.length; j++) { if (loads[j].name != depName) continue; // only link if already not already started linking (stops at circular / dynamic) if (!loads[j].module) linkDeclarativeModule(loads[j], loads, loader); } } console.assert(depModule, 'Dependency module not found!'); module.dependencies.push(depModule); // run the setter for this dependency if (module.setters[i]) module.setters[i](depModule.module); } load.status = 'linked'; }
javascript
function linkDeclarativeModule(load, loads, loader) { if (load.module) return; var module = load.module = getOrCreateModuleRecord(load.name); var moduleObj = load.module.module; var registryEntry = load.declare.call(__global, function(name, value) { // NB This should be an Object.defineProperty, but that is very slow. // By disaling this module write-protection we gain performance. // It could be useful to allow an option to enable or disable this. // bulk export object if (typeof name == 'object') { for (var p in name) moduleObj[p] = name[p]; } // single export name / value pair else { moduleObj[name] = value; } for (var i = 0, l = module.importers.length; i < l; i++) { var importerModule = module.importers[i]; if (importerModule.setters) { var importerIndex = importerModule.dependencies.indexOf(module); if (importerIndex != -1) { var setter = importerModule.setters[importerIndex]; setter(moduleObj); } } } return value; }, {id: load.name}); // setup our setters and execution function load.module.setters = registryEntry.setters; load.module.execute = registryEntry.execute; // now link all the module dependencies // amending the depMap as we go for (var i = 0, l = load.dependencies.length; i < l; i++) { var depName = load.dependencies[i].value; var depModule = getOrCreateModuleRecord(depName); depModule.importers.push(module); // if not already a module in the registry, try and link it now if (!loader.modules[depName]) { // get the dependency load record for (var j = 0; j < loads.length; j++) { if (loads[j].name != depName) continue; // only link if already not already started linking (stops at circular / dynamic) if (!loads[j].module) linkDeclarativeModule(loads[j], loads, loader); } } console.assert(depModule, 'Dependency module not found!'); module.dependencies.push(depModule); // run the setter for this dependency if (module.setters[i]) module.setters[i](depModule.module); } load.status = 'linked'; }
[ "function", "linkDeclarativeModule", "(", "load", ",", "loads", ",", "loader", ")", "{", "if", "(", "load", ".", "module", ")", "return", ";", "var", "module", "=", "load", ".", "module", "=", "getOrCreateModuleRecord", "(", "load", ".", "name", ")", ";", "var", "moduleObj", "=", "load", ".", "module", ".", "module", ";", "var", "registryEntry", "=", "load", ".", "declare", ".", "call", "(", "__global", ",", "function", "(", "name", ",", "value", ")", "{", "// NB This should be an Object.defineProperty, but that is very slow.", "// By disaling this module write-protection we gain performance.", "// It could be useful to allow an option to enable or disable this.", "// bulk export object", "if", "(", "typeof", "name", "==", "'object'", ")", "{", "for", "(", "var", "p", "in", "name", ")", "moduleObj", "[", "p", "]", "=", "name", "[", "p", "]", ";", "}", "// single export name / value pair", "else", "{", "moduleObj", "[", "name", "]", "=", "value", ";", "}", "for", "(", "var", "i", "=", "0", ",", "l", "=", "module", ".", "importers", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "importerModule", "=", "module", ".", "importers", "[", "i", "]", ";", "if", "(", "importerModule", ".", "setters", ")", "{", "var", "importerIndex", "=", "importerModule", ".", "dependencies", ".", "indexOf", "(", "module", ")", ";", "if", "(", "importerIndex", "!=", "-", "1", ")", "{", "var", "setter", "=", "importerModule", ".", "setters", "[", "importerIndex", "]", ";", "setter", "(", "moduleObj", ")", ";", "}", "}", "}", "return", "value", ";", "}", ",", "{", "id", ":", "load", ".", "name", "}", ")", ";", "// setup our setters and execution function", "load", ".", "module", ".", "setters", "=", "registryEntry", ".", "setters", ";", "load", ".", "module", ".", "execute", "=", "registryEntry", ".", "execute", ";", "// now link all the module dependencies", "// amending the depMap as we go", "for", "(", "var", "i", "=", "0", ",", "l", "=", "load", ".", "dependencies", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "depName", "=", "load", ".", "dependencies", "[", "i", "]", ".", "value", ";", "var", "depModule", "=", "getOrCreateModuleRecord", "(", "depName", ")", ";", "depModule", ".", "importers", ".", "push", "(", "module", ")", ";", "// if not already a module in the registry, try and link it now", "if", "(", "!", "loader", ".", "modules", "[", "depName", "]", ")", "{", "// get the dependency load record", "for", "(", "var", "j", "=", "0", ";", "j", "<", "loads", ".", "length", ";", "j", "++", ")", "{", "if", "(", "loads", "[", "j", "]", ".", "name", "!=", "depName", ")", "continue", ";", "// only link if already not already started linking (stops at circular / dynamic)", "if", "(", "!", "loads", "[", "j", "]", ".", "module", ")", "linkDeclarativeModule", "(", "loads", "[", "j", "]", ",", "loads", ",", "loader", ")", ";", "}", "}", "console", ".", "assert", "(", "depModule", ",", "'Dependency module not found!'", ")", ";", "module", ".", "dependencies", ".", "push", "(", "depModule", ")", ";", "// run the setter for this dependency", "if", "(", "module", ".", "setters", "[", "i", "]", ")", "module", ".", "setters", "[", "i", "]", "(", "depModule", ".", "module", ")", ";", "}", "load", ".", "status", "=", "'linked'", ";", "}" ]
custom declarative linking function
[ "custom", "declarative", "linking", "function" ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/third_party/es6-module-loader/loader.js#L679-L750
8,170
google/traceur-compiler
third_party/es6-module-loader/loader.js
evaluateLoadedModule
function evaluateLoadedModule(loader, load) { console.assert(load.status == 'linked', 'is linked ' + load.name); doEnsureEvaluated(load.module, [], loader); return load.module.module; }
javascript
function evaluateLoadedModule(loader, load) { console.assert(load.status == 'linked', 'is linked ' + load.name); doEnsureEvaluated(load.module, [], loader); return load.module.module; }
[ "function", "evaluateLoadedModule", "(", "loader", ",", "load", ")", "{", "console", ".", "assert", "(", "load", ".", "status", "==", "'linked'", ",", "'is linked '", "+", "load", ".", "name", ")", ";", "doEnsureEvaluated", "(", "load", ".", "module", ",", "[", "]", ",", "loader", ")", ";", "return", "load", ".", "module", ".", "module", ";", "}" ]
15.2.5.5.1 LinkImports not implemented 15.2.5.7 ResolveExportEntries not implemented 15.2.5.8 ResolveExports not implemented 15.2.5.9 ResolveExport not implemented 15.2.5.10 ResolveImportEntries not implemented 15.2.6.1
[ "15", ".", "2", ".", "5", ".", "5", ".", "1", "LinkImports", "not", "implemented", "15", ".", "2", ".", "5", ".", "7", "ResolveExportEntries", "not", "implemented", "15", ".", "2", ".", "5", ".", "8", "ResolveExports", "not", "implemented", "15", ".", "2", ".", "5", ".", "9", "ResolveExport", "not", "implemented", "15", ".", "2", ".", "5", ".", "10", "ResolveImportEntries", "not", "implemented", "15", ".", "2", ".", "6", ".", "1" ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/third_party/es6-module-loader/loader.js#L761-L766
8,171
google/traceur-compiler
third_party/es6-module-loader/loader.js
ensureEvaluated
function ensureEvaluated(module, seen, loader) { if (module.evaluated || !module.dependencies) return; seen.push(module); var deps = module.dependencies; var err; for (var i = 0, l = deps.length; i < l; i++) { var dep = deps[i]; if (indexOf.call(seen, dep) == -1) { err = ensureEvaluated(dep, seen, loader); // stop on error, see https://bugs.ecmascript.org/show_bug.cgi?id=2996 if (err) return err + '\n in module ' + dep.name; } } if (module.failed) return new Error('Module failed execution.'); if (module.evaluated) return; module.evaluated = true; err = doExecute(module); if (err) module.failed = true; // spec variation // we don't create a new module here because it was created and ammended // we just disable further extensions instead if (Object.preventExtensions) Object.preventExtensions(module.module); module.execute = undefined; return err; }
javascript
function ensureEvaluated(module, seen, loader) { if (module.evaluated || !module.dependencies) return; seen.push(module); var deps = module.dependencies; var err; for (var i = 0, l = deps.length; i < l; i++) { var dep = deps[i]; if (indexOf.call(seen, dep) == -1) { err = ensureEvaluated(dep, seen, loader); // stop on error, see https://bugs.ecmascript.org/show_bug.cgi?id=2996 if (err) return err + '\n in module ' + dep.name; } } if (module.failed) return new Error('Module failed execution.'); if (module.evaluated) return; module.evaluated = true; err = doExecute(module); if (err) module.failed = true; // spec variation // we don't create a new module here because it was created and ammended // we just disable further extensions instead if (Object.preventExtensions) Object.preventExtensions(module.module); module.execute = undefined; return err; }
[ "function", "ensureEvaluated", "(", "module", ",", "seen", ",", "loader", ")", "{", "if", "(", "module", ".", "evaluated", "||", "!", "module", ".", "dependencies", ")", "return", ";", "seen", ".", "push", "(", "module", ")", ";", "var", "deps", "=", "module", ".", "dependencies", ";", "var", "err", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "deps", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "dep", "=", "deps", "[", "i", "]", ";", "if", "(", "indexOf", ".", "call", "(", "seen", ",", "dep", ")", "==", "-", "1", ")", "{", "err", "=", "ensureEvaluated", "(", "dep", ",", "seen", ",", "loader", ")", ";", "// stop on error, see https://bugs.ecmascript.org/show_bug.cgi?id=2996", "if", "(", "err", ")", "return", "err", "+", "'\\n in module '", "+", "dep", ".", "name", ";", "}", "}", "if", "(", "module", ".", "failed", ")", "return", "new", "Error", "(", "'Module failed execution.'", ")", ";", "if", "(", "module", ".", "evaluated", ")", "return", ";", "module", ".", "evaluated", "=", "true", ";", "err", "=", "doExecute", "(", "module", ")", ";", "if", "(", "err", ")", "module", ".", "failed", "=", "true", ";", "// spec variation", "// we don't create a new module here because it was created and ammended", "// we just disable further extensions instead", "if", "(", "Object", ".", "preventExtensions", ")", "Object", ".", "preventExtensions", "(", "module", ".", "module", ")", ";", "module", ".", "execute", "=", "undefined", ";", "return", "err", ";", "}" ]
15.2.6.2 EnsureEvaluated adjusted
[ "15", ".", "2", ".", "6", ".", "2", "EnsureEvaluated", "adjusted" ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/third_party/es6-module-loader/loader.js#L794-L832
8,172
google/traceur-compiler
third_party/es6-module-loader/loader.js
function(key) { if (!this._loader.modules[key]) return; doEnsureEvaluated(this._loader.modules[key], [], this); return this._loader.modules[key].module; }
javascript
function(key) { if (!this._loader.modules[key]) return; doEnsureEvaluated(this._loader.modules[key], [], this); return this._loader.modules[key].module; }
[ "function", "(", "key", ")", "{", "if", "(", "!", "this", ".", "_loader", ".", "modules", "[", "key", "]", ")", "return", ";", "doEnsureEvaluated", "(", "this", ".", "_loader", ".", "modules", "[", "key", "]", ",", "[", "]", ",", "this", ")", ";", "return", "this", ".", "_loader", ".", "modules", "[", "key", "]", ".", "module", ";", "}" ]
26.3.3.4 entries not implemented 26.3.3.5
[ "26", ".", "3", ".", "3", ".", "4", "entries", "not", "implemented", "26", ".", "3", ".", "3", ".", "5" ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/third_party/es6-module-loader/loader.js#L906-L911
8,173
google/traceur-compiler
third_party/es6-module-loader/loader.js
function(name, module) { if (!(module instanceof Module)) throw new TypeError('Set must be a module'); this._loader.modules[name] = { module: module }; }
javascript
function(name, module) { if (!(module instanceof Module)) throw new TypeError('Set must be a module'); this._loader.modules[name] = { module: module }; }
[ "function", "(", "name", ",", "module", ")", "{", "if", "(", "!", "(", "module", "instanceof", "Module", ")", ")", "throw", "new", "TypeError", "(", "'Set must be a module'", ")", ";", "this", ".", "_loader", ".", "modules", "[", "name", "]", "=", "{", "module", ":", "module", "}", ";", "}" ]
26.3.3.14
[ "26", ".", "3", ".", "3", ".", "14" ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/third_party/es6-module-loader/loader.js#L988-L994
8,174
google/traceur-compiler
src/codegeneration/TemplateLiteralTransformer.js
createGetTemplateObject
function createGetTemplateObject(elements, getTemplateObject) { let cooked = []; let raw = []; let same = true; for (let i = 0; i < elements.length; i += 2) { let loc = elements[i].location; let str = elements[i].value.value; let cookedStr = toCookedString(str); let rawStr = toRawString(str); let cookedLiteral = createStringLiteralExpression(loc, cookedStr); cooked.push(cookedLiteral); if (cookedStr !== rawStr) { same = false; let rawLiteral = createStringLiteralExpression(loc, rawStr); raw.push(rawLiteral); } else { raw.push(cookedLiteral); } } maybeAddEmptyStringAtEnd(elements, cooked); let cookedLiteral = createArrayLiteral(cooked); let args = [cookedLiteral]; if (!same) { maybeAddEmptyStringAtEnd(elements, raw); let rawLiteral = createArrayLiteral(raw); args.unshift(rawLiteral); } return createCallExpression( getTemplateObject, createArgumentList(args)); }
javascript
function createGetTemplateObject(elements, getTemplateObject) { let cooked = []; let raw = []; let same = true; for (let i = 0; i < elements.length; i += 2) { let loc = elements[i].location; let str = elements[i].value.value; let cookedStr = toCookedString(str); let rawStr = toRawString(str); let cookedLiteral = createStringLiteralExpression(loc, cookedStr); cooked.push(cookedLiteral); if (cookedStr !== rawStr) { same = false; let rawLiteral = createStringLiteralExpression(loc, rawStr); raw.push(rawLiteral); } else { raw.push(cookedLiteral); } } maybeAddEmptyStringAtEnd(elements, cooked); let cookedLiteral = createArrayLiteral(cooked); let args = [cookedLiteral]; if (!same) { maybeAddEmptyStringAtEnd(elements, raw); let rawLiteral = createArrayLiteral(raw); args.unshift(rawLiteral); } return createCallExpression( getTemplateObject, createArgumentList(args)); }
[ "function", "createGetTemplateObject", "(", "elements", ",", "getTemplateObject", ")", "{", "let", "cooked", "=", "[", "]", ";", "let", "raw", "=", "[", "]", ";", "let", "same", "=", "true", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "elements", ".", "length", ";", "i", "+=", "2", ")", "{", "let", "loc", "=", "elements", "[", "i", "]", ".", "location", ";", "let", "str", "=", "elements", "[", "i", "]", ".", "value", ".", "value", ";", "let", "cookedStr", "=", "toCookedString", "(", "str", ")", ";", "let", "rawStr", "=", "toRawString", "(", "str", ")", ";", "let", "cookedLiteral", "=", "createStringLiteralExpression", "(", "loc", ",", "cookedStr", ")", ";", "cooked", ".", "push", "(", "cookedLiteral", ")", ";", "if", "(", "cookedStr", "!==", "rawStr", ")", "{", "same", "=", "false", ";", "let", "rawLiteral", "=", "createStringLiteralExpression", "(", "loc", ",", "rawStr", ")", ";", "raw", ".", "push", "(", "rawLiteral", ")", ";", "}", "else", "{", "raw", ".", "push", "(", "cookedLiteral", ")", ";", "}", "}", "maybeAddEmptyStringAtEnd", "(", "elements", ",", "cooked", ")", ";", "let", "cookedLiteral", "=", "createArrayLiteral", "(", "cooked", ")", ";", "let", "args", "=", "[", "cookedLiteral", "]", ";", "if", "(", "!", "same", ")", "{", "maybeAddEmptyStringAtEnd", "(", "elements", ",", "raw", ")", ";", "let", "rawLiteral", "=", "createArrayLiteral", "(", "raw", ")", ";", "args", ".", "unshift", "(", "rawLiteral", ")", ";", "}", "return", "createCallExpression", "(", "getTemplateObject", ",", "createArgumentList", "(", "args", ")", ")", ";", "}" ]
Generetes the runtime call to create the template object. The tagged template literal f `a${42}\n` gets compiled into: f($traceurRuntime.getTemplateObject(['a', '\\n], ['a', '\n']), 42) Note that if the cooked and the raw strings are identical the runtime call only pass one array. @param {Array<ParseTree>} elements @return {ParseTree}
[ "Generetes", "the", "runtime", "call", "to", "create", "the", "template", "object", ".", "The", "tagged", "template", "literal" ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/src/codegeneration/TemplateLiteralTransformer.js#L67-L99
8,175
google/traceur-compiler
src/codegeneration/TemplateLiteralTransformer.js
maybeAddEmptyStringAtEnd
function maybeAddEmptyStringAtEnd(elements, items) { let length = elements.length; if (!length || elements[length - 1].type !== TEMPLATE_LITERAL_PORTION) { items.push(createStringLiteralExpression(null, '""')); } }
javascript
function maybeAddEmptyStringAtEnd(elements, items) { let length = elements.length; if (!length || elements[length - 1].type !== TEMPLATE_LITERAL_PORTION) { items.push(createStringLiteralExpression(null, '""')); } }
[ "function", "maybeAddEmptyStringAtEnd", "(", "elements", ",", "items", ")", "{", "let", "length", "=", "elements", ".", "length", ";", "if", "(", "!", "length", "||", "elements", "[", "length", "-", "1", "]", ".", "type", "!==", "TEMPLATE_LITERAL_PORTION", ")", "{", "items", ".", "push", "(", "createStringLiteralExpression", "(", "null", ",", "'\"\"'", ")", ")", ";", "}", "}" ]
Adds an empty string at the end if needed. This is needed in case the template literal does not end with a literal portion. @param {Array<ParseTree>} elements @param {Array<ParseTree>} items This is the array that gets mutated.
[ "Adds", "an", "empty", "string", "at", "the", "end", "if", "needed", ".", "This", "is", "needed", "in", "case", "the", "template", "literal", "does", "not", "end", "with", "a", "literal", "portion", "." ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/src/codegeneration/TemplateLiteralTransformer.js#L107-L112
8,176
google/traceur-compiler
src/codegeneration/TemplateLiteralTransformer.js
toCookedString
function toCookedString(s) { let sb = ['"']; let i = 0, k = 1, c, c2; while (i < s.length) { c = s[i++]; switch (c) { case '\\': c2 = s[i++]; switch (c2) { // Strip line continuation. case '\n': case '\u2028': case '\u2029': break; case '\r': // \ \r \n should be stripped as one if (s[i + 1] === '\n') { i++; } break; default: sb[k++] = c; sb[k++] = c2; } break; // Since we wrap the string in " we need to escape those. case '"': sb[k++] = '\\"'; break; // Whitespace case '\n': sb[k++] = '\\n'; break; // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> // for both TV and TRV. case '\r': if (s[i] === '\n') i++; sb[k++] = '\\n'; break; case '\t': sb[k++] = '\\t'; break; case '\f': sb[k++] = '\\f'; break; case '\b': sb[k++] = '\\b'; break; case '\u2028': sb[k++] = '\\u2028'; break; case '\u2029': sb[k++] = '\\u2029'; break; default: sb[k++] = c; } } sb[k++] = '"'; return sb.join(''); }
javascript
function toCookedString(s) { let sb = ['"']; let i = 0, k = 1, c, c2; while (i < s.length) { c = s[i++]; switch (c) { case '\\': c2 = s[i++]; switch (c2) { // Strip line continuation. case '\n': case '\u2028': case '\u2029': break; case '\r': // \ \r \n should be stripped as one if (s[i + 1] === '\n') { i++; } break; default: sb[k++] = c; sb[k++] = c2; } break; // Since we wrap the string in " we need to escape those. case '"': sb[k++] = '\\"'; break; // Whitespace case '\n': sb[k++] = '\\n'; break; // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> // for both TV and TRV. case '\r': if (s[i] === '\n') i++; sb[k++] = '\\n'; break; case '\t': sb[k++] = '\\t'; break; case '\f': sb[k++] = '\\f'; break; case '\b': sb[k++] = '\\b'; break; case '\u2028': sb[k++] = '\\u2028'; break; case '\u2029': sb[k++] = '\\u2029'; break; default: sb[k++] = c; } } sb[k++] = '"'; return sb.join(''); }
[ "function", "toCookedString", "(", "s", ")", "{", "let", "sb", "=", "[", "'\"'", "]", ";", "let", "i", "=", "0", ",", "k", "=", "1", ",", "c", ",", "c2", ";", "while", "(", "i", "<", "s", ".", "length", ")", "{", "c", "=", "s", "[", "i", "++", "]", ";", "switch", "(", "c", ")", "{", "case", "'\\\\'", ":", "c2", "=", "s", "[", "i", "++", "]", ";", "switch", "(", "c2", ")", "{", "// Strip line continuation.", "case", "'\\n'", ":", "case", "'\\u2028'", ":", "case", "'\\u2029'", ":", "break", ";", "case", "'\\r'", ":", "// \\ \\r \\n should be stripped as one", "if", "(", "s", "[", "i", "+", "1", "]", "===", "'\\n'", ")", "{", "i", "++", ";", "}", "break", ";", "default", ":", "sb", "[", "k", "++", "]", "=", "c", ";", "sb", "[", "k", "++", "]", "=", "c2", ";", "}", "break", ";", "// Since we wrap the string in \" we need to escape those.", "case", "'\"'", ":", "sb", "[", "k", "++", "]", "=", "'\\\\\"'", ";", "break", ";", "// Whitespace", "case", "'\\n'", ":", "sb", "[", "k", "++", "]", "=", "'\\\\n'", ";", "break", ";", "// <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF>", "// for both TV and TRV.", "case", "'\\r'", ":", "if", "(", "s", "[", "i", "]", "===", "'\\n'", ")", "i", "++", ";", "sb", "[", "k", "++", "]", "=", "'\\\\n'", ";", "break", ";", "case", "'\\t'", ":", "sb", "[", "k", "++", "]", "=", "'\\\\t'", ";", "break", ";", "case", "'\\f'", ":", "sb", "[", "k", "++", "]", "=", "'\\\\f'", ";", "break", ";", "case", "'\\b'", ":", "sb", "[", "k", "++", "]", "=", "'\\\\b'", ";", "break", ";", "case", "'\\u2028'", ":", "sb", "[", "k", "++", "]", "=", "'\\\\u2028'", ";", "break", ";", "case", "'\\u2029'", ":", "sb", "[", "k", "++", "]", "=", "'\\\\u2029'", ";", "break", ";", "default", ":", "sb", "[", "k", "++", "]", "=", "c", ";", "}", "}", "sb", "[", "k", "++", "]", "=", "'\"'", ";", "return", "sb", ".", "join", "(", "''", ")", ";", "}" ]
Takes a raw string and returns a string that is suitable for the cooked value. This involves removing line continuations, escaping double quotes and escaping whitespace. @param {string} s @return {string}
[ "Takes", "a", "raw", "string", "and", "returns", "a", "string", "that", "is", "suitable", "for", "the", "cooked", "value", ".", "This", "involves", "removing", "line", "continuations", "escaping", "double", "quotes", "and", "escaping", "whitespace", "." ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/src/codegeneration/TemplateLiteralTransformer.js#L138-L204
8,177
google/traceur-compiler
demo/repl.js
setDebugLevel
function setDebugLevel(level, printf) { var outLevel = 0; debug = debug2 = debug3 = debugTree = function() {}; switch (String(level)) { case '3': debug3 = printf; outLevel++; // fall through case '2': debugTree = function (fmt, tree) { printf(fmt, util.inspect(tree.toJSON(), false, 64)); }; debug2 = printf; outLevel++; // fall through case '1': debug = printf; outLevel++; // fall through default: return outLevel; } }
javascript
function setDebugLevel(level, printf) { var outLevel = 0; debug = debug2 = debug3 = debugTree = function() {}; switch (String(level)) { case '3': debug3 = printf; outLevel++; // fall through case '2': debugTree = function (fmt, tree) { printf(fmt, util.inspect(tree.toJSON(), false, 64)); }; debug2 = printf; outLevel++; // fall through case '1': debug = printf; outLevel++; // fall through default: return outLevel; } }
[ "function", "setDebugLevel", "(", "level", ",", "printf", ")", "{", "var", "outLevel", "=", "0", ";", "debug", "=", "debug2", "=", "debug3", "=", "debugTree", "=", "function", "(", ")", "{", "}", ";", "switch", "(", "String", "(", "level", ")", ")", "{", "case", "'3'", ":", "debug3", "=", "printf", ";", "outLevel", "++", ";", "// fall through", "case", "'2'", ":", "debugTree", "=", "function", "(", "fmt", ",", "tree", ")", "{", "printf", "(", "fmt", ",", "util", ".", "inspect", "(", "tree", ".", "toJSON", "(", ")", ",", "false", ",", "64", ")", ")", ";", "}", ";", "debug2", "=", "printf", ";", "outLevel", "++", ";", "// fall through", "case", "'1'", ":", "debug", "=", "printf", ";", "outLevel", "++", ";", "// fall through", "default", ":", "return", "outLevel", ";", "}", "}" ]
Selectively enables and disables the debug functions. @param {number|string} level The debug level to set (0-3). @param {function} printf The printf-style function to use. @return {number} The level that was set.
[ "Selectively", "enables", "and", "disables", "the", "debug", "functions", "." ]
caa7b751d5150622e13cdd18865e09681d8c6691
https://github.com/google/traceur-compiler/blob/caa7b751d5150622e13cdd18865e09681d8c6691/demo/repl.js#L32-L56
8,178
jaames/iro.js
dist/iro.es.js
usePlugins
function usePlugins(core) { var installedPlugins = []; /** * @desc Register iro.js plugin * @param {Function} plugin = plugin constructor * @param {Object} pluginOptions = plugin options passed to constructor */ core.use = function(plugin, pluginOptions) { if ( pluginOptions === void 0 ) pluginOptions = {}; // Check that the plugin hasn't already been registered if (!(installedPlugins.indexOf(plugin) > -1)) { // Init plugin // TODO: consider collection of plugin utils, which are passed as a thrid param plugin(core, pluginOptions); // Register plugin installedPlugins.push(plugin); } }; core.installedPlugins = installedPlugins; return core; }
javascript
function usePlugins(core) { var installedPlugins = []; /** * @desc Register iro.js plugin * @param {Function} plugin = plugin constructor * @param {Object} pluginOptions = plugin options passed to constructor */ core.use = function(plugin, pluginOptions) { if ( pluginOptions === void 0 ) pluginOptions = {}; // Check that the plugin hasn't already been registered if (!(installedPlugins.indexOf(plugin) > -1)) { // Init plugin // TODO: consider collection of plugin utils, which are passed as a thrid param plugin(core, pluginOptions); // Register plugin installedPlugins.push(plugin); } }; core.installedPlugins = installedPlugins; return core; }
[ "function", "usePlugins", "(", "core", ")", "{", "var", "installedPlugins", "=", "[", "]", ";", "/**\n * @desc Register iro.js plugin\n * @param {Function} plugin = plugin constructor\n * @param {Object} pluginOptions = plugin options passed to constructor\n */", "core", ".", "use", "=", "function", "(", "plugin", ",", "pluginOptions", ")", "{", "if", "(", "pluginOptions", "===", "void", "0", ")", "pluginOptions", "=", "{", "}", ";", "// Check that the plugin hasn't already been registered", "if", "(", "!", "(", "installedPlugins", ".", "indexOf", "(", "plugin", ")", ">", "-", "1", ")", ")", "{", "// Init plugin", "// TODO: consider collection of plugin utils, which are passed as a thrid param", "plugin", "(", "core", ",", "pluginOptions", ")", ";", "// Register plugin", "installedPlugins", ".", "push", "(", "plugin", ")", ";", "}", "}", ";", "core", ".", "installedPlugins", "=", "installedPlugins", ";", "return", "core", ";", "}" ]
iro.js plugins API This provides the iro.use method, which can be used to register plugins which extend the iro.js core
[ "iro", ".", "js", "plugins", "API", "This", "provides", "the", "iro", ".", "use", "method", "which", "can", "be", "used", "to", "register", "plugins", "which", "extend", "the", "iro", ".", "js", "core" ]
6d193f0e68fbf9cac6b850ddbc87abfac28bdd7a
https://github.com/jaames/iro.js/blob/6d193f0e68fbf9cac6b850ddbc87abfac28bdd7a/dist/iro.es.js#L1778-L1802
8,179
vpulim/node-soap
soap-stub.js
createClient
function createClient(wsdlUrl, options, cb) { if (!cb) { cb = options; options = {}; } if (this.errOnCreateClient) { return setTimeout(cb.bind(null, new Error('forced error on createClient'))); } var client = getStub(wsdlUrl); if (client) { resetStubbedMethods(client); setTimeout(cb.bind(null, null, client)); } else { setTimeout(cb.bind(null, new Error('no client stubbed for ' + wsdlUrl))); } }
javascript
function createClient(wsdlUrl, options, cb) { if (!cb) { cb = options; options = {}; } if (this.errOnCreateClient) { return setTimeout(cb.bind(null, new Error('forced error on createClient'))); } var client = getStub(wsdlUrl); if (client) { resetStubbedMethods(client); setTimeout(cb.bind(null, null, client)); } else { setTimeout(cb.bind(null, new Error('no client stubbed for ' + wsdlUrl))); } }
[ "function", "createClient", "(", "wsdlUrl", ",", "options", ",", "cb", ")", "{", "if", "(", "!", "cb", ")", "{", "cb", "=", "options", ";", "options", "=", "{", "}", ";", "}", "if", "(", "this", ".", "errOnCreateClient", ")", "{", "return", "setTimeout", "(", "cb", ".", "bind", "(", "null", ",", "new", "Error", "(", "'forced error on createClient'", ")", ")", ")", ";", "}", "var", "client", "=", "getStub", "(", "wsdlUrl", ")", ";", "if", "(", "client", ")", "{", "resetStubbedMethods", "(", "client", ")", ";", "setTimeout", "(", "cb", ".", "bind", "(", "null", ",", "null", ",", "client", ")", ")", ";", "}", "else", "{", "setTimeout", "(", "cb", ".", "bind", "(", "null", ",", "new", "Error", "(", "'no client stubbed for '", "+", "wsdlUrl", ")", ")", ")", ";", "}", "}" ]
Return a stubbed client based on the value of wsdlUrl. @throws if wsdlUrl is unknown. @param {String} wsdlUrl @param {Object} options @param {Function} cb @return {Object}
[ "Return", "a", "stubbed", "client", "based", "on", "the", "value", "of", "wsdlUrl", "." ]
b0891343da75ab1b31d539812d5f3fb3a89ea15c
https://github.com/vpulim/node-soap/blob/b0891343da75ab1b31d539812d5f3fb3a89ea15c/soap-stub.js#L42-L60
8,180
vpulim/node-soap
soap-stub.js
createErroringStub
function createErroringStub(err) { return function() { this.args.forEach(function(argSet) { setTimeout(argSet[1].bind(null, err)); }); this.yields(err); }; }
javascript
function createErroringStub(err) { return function() { this.args.forEach(function(argSet) { setTimeout(argSet[1].bind(null, err)); }); this.yields(err); }; }
[ "function", "createErroringStub", "(", "err", ")", "{", "return", "function", "(", ")", "{", "this", ".", "args", ".", "forEach", "(", "function", "(", "argSet", ")", "{", "setTimeout", "(", "argSet", "[", "1", "]", ".", "bind", "(", "null", ",", "err", ")", ")", ";", "}", ")", ";", "this", ".", "yields", "(", "err", ")", ";", "}", ";", "}" ]
Returns a method that calls all callbacks given to the method it is attached to with the given error. <pre> myClientStub.someMethod.errorOnCall = createErroringStub(error); // elsewhere myClientStub.someMethod.errorOnCall(); </pre> @param {?} object anything @return {Function}
[ "Returns", "a", "method", "that", "calls", "all", "callbacks", "given", "to", "the", "method", "it", "is", "attached", "to", "with", "the", "given", "error", "." ]
b0891343da75ab1b31d539812d5f3fb3a89ea15c
https://github.com/vpulim/node-soap/blob/b0891343da75ab1b31d539812d5f3fb3a89ea15c/soap-stub.js#L77-L84
8,181
vpulim/node-soap
soap-stub.js
createRespondingStub
function createRespondingStub(object, body) { return function() { this.args.forEach(function(argSet) { setTimeout(argSet[1].bind(null, null, object)); }); this.yields(null, object, body); }; }
javascript
function createRespondingStub(object, body) { return function() { this.args.forEach(function(argSet) { setTimeout(argSet[1].bind(null, null, object)); }); this.yields(null, object, body); }; }
[ "function", "createRespondingStub", "(", "object", ",", "body", ")", "{", "return", "function", "(", ")", "{", "this", ".", "args", ".", "forEach", "(", "function", "(", "argSet", ")", "{", "setTimeout", "(", "argSet", "[", "1", "]", ".", "bind", "(", "null", ",", "null", ",", "object", ")", ")", ";", "}", ")", ";", "this", ".", "yields", "(", "null", ",", "object", ",", "body", ")", ";", "}", ";", "}" ]
Returns a method that calls all callbacks given to the method it is attached to with the given response. <pre> myClientStub.someMethod.respondWithError = createRespondingStub(errorResponse); // elsewhere myClientStub.someMethod.respondWithError(); </pre> @param {?} object anything @return {Function}
[ "Returns", "a", "method", "that", "calls", "all", "callbacks", "given", "to", "the", "method", "it", "is", "attached", "to", "with", "the", "given", "response", "." ]
b0891343da75ab1b31d539812d5f3fb3a89ea15c
https://github.com/vpulim/node-soap/blob/b0891343da75ab1b31d539812d5f3fb3a89ea15c/soap-stub.js#L101-L108
8,182
vpulim/node-soap
soap-stub.js
registerClient
function registerClient(alias, urlToWsdl, clientStub) { aliasedClientStubs[alias] = clientStub; clientStubs[urlToWsdl] = clientStub; }
javascript
function registerClient(alias, urlToWsdl, clientStub) { aliasedClientStubs[alias] = clientStub; clientStubs[urlToWsdl] = clientStub; }
[ "function", "registerClient", "(", "alias", ",", "urlToWsdl", ",", "clientStub", ")", "{", "aliasedClientStubs", "[", "alias", "]", "=", "clientStub", ";", "clientStubs", "[", "urlToWsdl", "]", "=", "clientStub", ";", "}" ]
Registers a stubbed client with soap-stub. urlToWsdl is the path you will use in your app. @param {String} alias A simple name to refer to the clientStub as. @param {String} urlToWsdl May be file system URL or http URL. @param {Object} clientStub A client with stubbed methods.
[ "Registers", "a", "stubbed", "client", "with", "soap", "-", "stub", ".", "urlToWsdl", "is", "the", "path", "you", "will", "use", "in", "your", "app", "." ]
b0891343da75ab1b31d539812d5f3fb3a89ea15c
https://github.com/vpulim/node-soap/blob/b0891343da75ab1b31d539812d5f3fb3a89ea15c/soap-stub.js#L118-L121
8,183
gilbitron/Raneto
themes/default/public/scripts/ghostdown.js
loadMode
function loadMode(cm) { cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); cm.doc.iter(function(line) { if (line.stateAfter) line.stateAfter = null; if (line.styles) line.styles = null; }); cm.doc.frontier = cm.doc.first; startWorker(cm, 100); cm.state.modeGen++; if (cm.curOp) regChange(cm); }
javascript
function loadMode(cm) { cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); cm.doc.iter(function(line) { if (line.stateAfter) line.stateAfter = null; if (line.styles) line.styles = null; }); cm.doc.frontier = cm.doc.first; startWorker(cm, 100); cm.state.modeGen++; if (cm.curOp) regChange(cm); }
[ "function", "loadMode", "(", "cm", ")", "{", "cm", ".", "doc", ".", "mode", "=", "CodeMirror", ".", "getMode", "(", "cm", ".", "options", ",", "cm", ".", "doc", ".", "modeOption", ")", ";", "cm", ".", "doc", ".", "iter", "(", "function", "(", "line", ")", "{", "if", "(", "line", ".", "stateAfter", ")", "line", ".", "stateAfter", "=", "null", ";", "if", "(", "line", ".", "styles", ")", "line", ".", "styles", "=", "null", ";", "}", ")", ";", "cm", ".", "doc", ".", "frontier", "=", "cm", ".", "doc", ".", "first", ";", "startWorker", "(", "cm", ",", "100", ")", ";", "cm", ".", "state", ".", "modeGen", "++", ";", "if", "(", "cm", ".", "curOp", ")", "regChange", "(", "cm", ")", ";", "}" ]
STATE UPDATES Used to get the editor into a consistent state again when options change.
[ "STATE", "UPDATES", "Used", "to", "get", "the", "editor", "into", "a", "consistent", "state", "again", "when", "options", "change", "." ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/themes/default/public/scripts/ghostdown.js#L195-L205
8,184
gilbitron/Raneto
themes/default/public/scripts/ghostdown.js
setGuttersForLineNumbers
function setGuttersForLineNumbers(options) { var found = false; for (var i = 0; i < options.gutters.length; ++i) { if (options.gutters[i] == "CodeMirror-linenumbers") { if (options.lineNumbers) found = true; else options.gutters.splice(i--, 1); } } if (!found && options.lineNumbers) options.gutters.push("CodeMirror-linenumbers"); }
javascript
function setGuttersForLineNumbers(options) { var found = false; for (var i = 0; i < options.gutters.length; ++i) { if (options.gutters[i] == "CodeMirror-linenumbers") { if (options.lineNumbers) found = true; else options.gutters.splice(i--, 1); } } if (!found && options.lineNumbers) options.gutters.push("CodeMirror-linenumbers"); }
[ "function", "setGuttersForLineNumbers", "(", "options", ")", "{", "var", "found", "=", "false", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "options", ".", "gutters", ".", "length", ";", "++", "i", ")", "{", "if", "(", "options", ".", "gutters", "[", "i", "]", "==", "\"CodeMirror-linenumbers\"", ")", "{", "if", "(", "options", ".", "lineNumbers", ")", "found", "=", "true", ";", "else", "options", ".", "gutters", ".", "splice", "(", "i", "--", ",", "1", ")", ";", "}", "}", "if", "(", "!", "found", "&&", "options", ".", "lineNumbers", ")", "options", ".", "gutters", ".", "push", "(", "\"CodeMirror-linenumbers\"", ")", ";", "}" ]
Make sure the gutters options contains the element "CodeMirror-linenumbers" when the lineNumbers option is true.
[ "Make", "sure", "the", "gutters", "options", "contains", "the", "element", "CodeMirror", "-", "linenumbers", "when", "the", "lineNumbers", "option", "is", "true", "." ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/themes/default/public/scripts/ghostdown.js#L309-L319
8,185
gilbitron/Raneto
themes/default/public/scripts/ghostdown.js
updateScrollbars
function updateScrollbars(cm) { var d = cm.display, docHeight = cm.doc.height; var totalHeight = docHeight + paddingVert(d); d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px"; d.gutters.style.height = Math.max(totalHeight, d.scroller.clientHeight - scrollerCutOff) + "px"; var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight); var needsH = d.scroller.scrollWidth > (d.scroller.clientWidth + 1); var needsV = scrollHeight > (d.scroller.clientHeight + 1); if (needsV) { d.scrollbarV.style.display = "block"; d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0"; d.scrollbarV.firstChild.style.height = (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px"; } else d.scrollbarV.style.display = ""; if (needsH) { d.scrollbarH.style.display = "block"; d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0"; d.scrollbarH.firstChild.style.width = (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px"; } else d.scrollbarH.style.display = ""; if (needsH && needsV) { d.scrollbarFiller.style.display = "block"; d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px"; } else d.scrollbarFiller.style.display = ""; if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { d.gutterFiller.style.display = "block"; d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px"; d.gutterFiller.style.width = d.gutters.offsetWidth + "px"; } else d.gutterFiller.style.display = ""; if (mac_geLion && scrollbarWidth(d.measure) === 0) d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px"; }
javascript
function updateScrollbars(cm) { var d = cm.display, docHeight = cm.doc.height; var totalHeight = docHeight + paddingVert(d); d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px"; d.gutters.style.height = Math.max(totalHeight, d.scroller.clientHeight - scrollerCutOff) + "px"; var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight); var needsH = d.scroller.scrollWidth > (d.scroller.clientWidth + 1); var needsV = scrollHeight > (d.scroller.clientHeight + 1); if (needsV) { d.scrollbarV.style.display = "block"; d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0"; d.scrollbarV.firstChild.style.height = (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px"; } else d.scrollbarV.style.display = ""; if (needsH) { d.scrollbarH.style.display = "block"; d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0"; d.scrollbarH.firstChild.style.width = (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px"; } else d.scrollbarH.style.display = ""; if (needsH && needsV) { d.scrollbarFiller.style.display = "block"; d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px"; } else d.scrollbarFiller.style.display = ""; if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { d.gutterFiller.style.display = "block"; d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px"; d.gutterFiller.style.width = d.gutters.offsetWidth + "px"; } else d.gutterFiller.style.display = ""; if (mac_geLion && scrollbarWidth(d.measure) === 0) d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px"; }
[ "function", "updateScrollbars", "(", "cm", ")", "{", "var", "d", "=", "cm", ".", "display", ",", "docHeight", "=", "cm", ".", "doc", ".", "height", ";", "var", "totalHeight", "=", "docHeight", "+", "paddingVert", "(", "d", ")", ";", "d", ".", "sizer", ".", "style", ".", "minHeight", "=", "d", ".", "heightForcer", ".", "style", ".", "top", "=", "totalHeight", "+", "\"px\"", ";", "d", ".", "gutters", ".", "style", ".", "height", "=", "Math", ".", "max", "(", "totalHeight", ",", "d", ".", "scroller", ".", "clientHeight", "-", "scrollerCutOff", ")", "+", "\"px\"", ";", "var", "scrollHeight", "=", "Math", ".", "max", "(", "totalHeight", ",", "d", ".", "scroller", ".", "scrollHeight", ")", ";", "var", "needsH", "=", "d", ".", "scroller", ".", "scrollWidth", ">", "(", "d", ".", "scroller", ".", "clientWidth", "+", "1", ")", ";", "var", "needsV", "=", "scrollHeight", ">", "(", "d", ".", "scroller", ".", "clientHeight", "+", "1", ")", ";", "if", "(", "needsV", ")", "{", "d", ".", "scrollbarV", ".", "style", ".", "display", "=", "\"block\"", ";", "d", ".", "scrollbarV", ".", "style", ".", "bottom", "=", "needsH", "?", "scrollbarWidth", "(", "d", ".", "measure", ")", "+", "\"px\"", ":", "\"0\"", ";", "d", ".", "scrollbarV", ".", "firstChild", ".", "style", ".", "height", "=", "(", "scrollHeight", "-", "d", ".", "scroller", ".", "clientHeight", "+", "d", ".", "scrollbarV", ".", "clientHeight", ")", "+", "\"px\"", ";", "}", "else", "d", ".", "scrollbarV", ".", "style", ".", "display", "=", "\"\"", ";", "if", "(", "needsH", ")", "{", "d", ".", "scrollbarH", ".", "style", ".", "display", "=", "\"block\"", ";", "d", ".", "scrollbarH", ".", "style", ".", "right", "=", "needsV", "?", "scrollbarWidth", "(", "d", ".", "measure", ")", "+", "\"px\"", ":", "\"0\"", ";", "d", ".", "scrollbarH", ".", "firstChild", ".", "style", ".", "width", "=", "(", "d", ".", "scroller", ".", "scrollWidth", "-", "d", ".", "scroller", ".", "clientWidth", "+", "d", ".", "scrollbarH", ".", "clientWidth", ")", "+", "\"px\"", ";", "}", "else", "d", ".", "scrollbarH", ".", "style", ".", "display", "=", "\"\"", ";", "if", "(", "needsH", "&&", "needsV", ")", "{", "d", ".", "scrollbarFiller", ".", "style", ".", "display", "=", "\"block\"", ";", "d", ".", "scrollbarFiller", ".", "style", ".", "height", "=", "d", ".", "scrollbarFiller", ".", "style", ".", "width", "=", "scrollbarWidth", "(", "d", ".", "measure", ")", "+", "\"px\"", ";", "}", "else", "d", ".", "scrollbarFiller", ".", "style", ".", "display", "=", "\"\"", ";", "if", "(", "needsH", "&&", "cm", ".", "options", ".", "coverGutterNextToScrollbar", "&&", "cm", ".", "options", ".", "fixedGutter", ")", "{", "d", ".", "gutterFiller", ".", "style", ".", "display", "=", "\"block\"", ";", "d", ".", "gutterFiller", ".", "style", ".", "height", "=", "scrollbarWidth", "(", "d", ".", "measure", ")", "+", "\"px\"", ";", "d", ".", "gutterFiller", ".", "style", ".", "width", "=", "d", ".", "gutters", ".", "offsetWidth", "+", "\"px\"", ";", "}", "else", "d", ".", "gutterFiller", ".", "style", ".", "display", "=", "\"\"", ";", "if", "(", "mac_geLion", "&&", "scrollbarWidth", "(", "d", ".", "measure", ")", "===", "0", ")", "d", ".", "scrollbarV", ".", "style", ".", "minWidth", "=", "d", ".", "scrollbarH", ".", "style", ".", "minHeight", "=", "mac_geMountainLion", "?", "\"18px\"", ":", "\"12px\"", ";", "}" ]
Re-synchronize the fake scrollbars with the actual size of the content. Optionally force a scrollTop.
[ "Re", "-", "synchronize", "the", "fake", "scrollbars", "with", "the", "actual", "size", "of", "the", "content", ".", "Optionally", "force", "a", "scrollTop", "." ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/themes/default/public/scripts/ghostdown.js#L325-L357
8,186
gilbitron/Raneto
themes/default/public/scripts/ghostdown.js
updateSelectionCursor
function updateSelectionCursor(cm) { var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div"); display.cursor.style.left = pos.left + "px"; display.cursor.style.top = pos.top + "px"; display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; display.cursor.style.display = ""; if (pos.other) { display.otherCursor.style.display = ""; display.otherCursor.style.left = pos.other.left + "px"; display.otherCursor.style.top = pos.other.top + "px"; display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; } else { display.otherCursor.style.display = "none"; } }
javascript
function updateSelectionCursor(cm) { var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div"); display.cursor.style.left = pos.left + "px"; display.cursor.style.top = pos.top + "px"; display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; display.cursor.style.display = ""; if (pos.other) { display.otherCursor.style.display = ""; display.otherCursor.style.left = pos.other.left + "px"; display.otherCursor.style.top = pos.other.top + "px"; display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; } else { display.otherCursor.style.display = "none"; } }
[ "function", "updateSelectionCursor", "(", "cm", ")", "{", "var", "display", "=", "cm", ".", "display", ",", "pos", "=", "cursorCoords", "(", "cm", ",", "cm", ".", "doc", ".", "sel", ".", "head", ",", "\"div\"", ")", ";", "display", ".", "cursor", ".", "style", ".", "left", "=", "pos", ".", "left", "+", "\"px\"", ";", "display", ".", "cursor", ".", "style", ".", "top", "=", "pos", ".", "top", "+", "\"px\"", ";", "display", ".", "cursor", ".", "style", ".", "height", "=", "Math", ".", "max", "(", "0", ",", "pos", ".", "bottom", "-", "pos", ".", "top", ")", "*", "cm", ".", "options", ".", "cursorHeight", "+", "\"px\"", ";", "display", ".", "cursor", ".", "style", ".", "display", "=", "\"\"", ";", "if", "(", "pos", ".", "other", ")", "{", "display", ".", "otherCursor", ".", "style", ".", "display", "=", "\"\"", ";", "display", ".", "otherCursor", ".", "style", ".", "left", "=", "pos", ".", "other", ".", "left", "+", "\"px\"", ";", "display", ".", "otherCursor", ".", "style", ".", "top", "=", "pos", ".", "other", ".", "top", "+", "\"px\"", ";", "display", ".", "otherCursor", ".", "style", ".", "height", "=", "(", "pos", ".", "other", ".", "bottom", "-", "pos", ".", "other", ".", "top", ")", "*", ".85", "+", "\"px\"", ";", "}", "else", "{", "display", ".", "otherCursor", ".", "style", ".", "display", "=", "\"none\"", ";", "}", "}" ]
No selection, plain cursor
[ "No", "selection", "plain", "cursor" ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/themes/default/public/scripts/ghostdown.js#L783-L796
8,187
gilbitron/Raneto
themes/default/public/scripts/ghostdown.js
operation
function operation(cm1, f) { return function() { var cm = cm1 || this, withOp = !cm.curOp; if (withOp) startOperation(cm); try { var result = f.apply(cm, arguments); } finally { if (withOp) endOperation(cm); } return result; }; }
javascript
function operation(cm1, f) { return function() { var cm = cm1 || this, withOp = !cm.curOp; if (withOp) startOperation(cm); try { var result = f.apply(cm, arguments); } finally { if (withOp) endOperation(cm); } return result; }; }
[ "function", "operation", "(", "cm1", ",", "f", ")", "{", "return", "function", "(", ")", "{", "var", "cm", "=", "cm1", "||", "this", ",", "withOp", "=", "!", "cm", ".", "curOp", ";", "if", "(", "withOp", ")", "startOperation", "(", "cm", ")", ";", "try", "{", "var", "result", "=", "f", ".", "apply", "(", "cm", ",", "arguments", ")", ";", "}", "finally", "{", "if", "(", "withOp", ")", "endOperation", "(", "cm", ")", ";", "}", "return", "result", ";", "}", ";", "}" ]
Wraps a function in an operation. Returns the wrapped function.
[ "Wraps", "a", "function", "in", "an", "operation", ".", "Returns", "the", "wrapped", "function", "." ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/themes/default/public/scripts/ghostdown.js#L1387-L1395
8,188
gilbitron/Raneto
themes/default/public/scripts/ghostdown.js
unregister
function unregister() { for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNode) {} if (p) setTimeout(unregister, 5000); else off(window, "resize", onResize); }
javascript
function unregister() { for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNode) {} if (p) setTimeout(unregister, 5000); else off(window, "resize", onResize); }
[ "function", "unregister", "(", ")", "{", "for", "(", "var", "p", "=", "d", ".", "wrapper", ".", "parentNode", ";", "p", "&&", "p", "!=", "document", ".", "body", ";", "p", "=", "p", ".", "parentNode", ")", "{", "}", "if", "(", "p", ")", "setTimeout", "(", "unregister", ",", "5000", ")", ";", "else", "off", "(", "window", ",", "\"resize\"", ",", "onResize", ")", ";", "}" ]
Above handler holds on to the editor and its data structures. Here we poll to unregister it when the editor is no longer in the document, so that it can be garbage-collected.
[ "Above", "handler", "holds", "on", "to", "the", "editor", "and", "its", "data", "structures", ".", "Here", "we", "poll", "to", "unregister", "it", "when", "the", "editor", "is", "no", "longer", "in", "the", "document", "so", "that", "it", "can", "be", "garbage", "-", "collected", "." ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/themes/default/public/scripts/ghostdown.js#L1567-L1571
8,189
gilbitron/Raneto
themes/default/public/scripts/ghostdown.js
clipPostChange
function clipPostChange(doc, change, pos) { if (!posLess(change.from, pos)) return clipPos(doc, pos); var diff = (change.text.length - 1) - (change.to.line - change.from.line); if (pos.line > change.to.line + diff) { var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1; if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length); return clipToLen(pos, getLine(doc, preLine).text.length); } if (pos.line == change.to.line + diff) return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) + getLine(doc, change.to.line).text.length - change.to.ch); var inside = pos.line - change.from.line; return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch)); }
javascript
function clipPostChange(doc, change, pos) { if (!posLess(change.from, pos)) return clipPos(doc, pos); var diff = (change.text.length - 1) - (change.to.line - change.from.line); if (pos.line > change.to.line + diff) { var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1; if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length); return clipToLen(pos, getLine(doc, preLine).text.length); } if (pos.line == change.to.line + diff) return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) + getLine(doc, change.to.line).text.length - change.to.ch); var inside = pos.line - change.from.line; return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch)); }
[ "function", "clipPostChange", "(", "doc", ",", "change", ",", "pos", ")", "{", "if", "(", "!", "posLess", "(", "change", ".", "from", ",", "pos", ")", ")", "return", "clipPos", "(", "doc", ",", "pos", ")", ";", "var", "diff", "=", "(", "change", ".", "text", ".", "length", "-", "1", ")", "-", "(", "change", ".", "to", ".", "line", "-", "change", ".", "from", ".", "line", ")", ";", "if", "(", "pos", ".", "line", ">", "change", ".", "to", ".", "line", "+", "diff", ")", "{", "var", "preLine", "=", "pos", ".", "line", "-", "diff", ",", "lastLine", "=", "doc", ".", "first", "+", "doc", ".", "size", "-", "1", ";", "if", "(", "preLine", ">", "lastLine", ")", "return", "Pos", "(", "lastLine", ",", "getLine", "(", "doc", ",", "lastLine", ")", ".", "text", ".", "length", ")", ";", "return", "clipToLen", "(", "pos", ",", "getLine", "(", "doc", ",", "preLine", ")", ".", "text", ".", "length", ")", ";", "}", "if", "(", "pos", ".", "line", "==", "change", ".", "to", ".", "line", "+", "diff", ")", "return", "clipToLen", "(", "pos", ",", "lst", "(", "change", ".", "text", ")", ".", "length", "+", "(", "change", ".", "text", ".", "length", "==", "1", "?", "change", ".", "from", ".", "ch", ":", "0", ")", "+", "getLine", "(", "doc", ",", "change", ".", "to", ".", "line", ")", ".", "text", ".", "length", "-", "change", ".", "to", ".", "ch", ")", ";", "var", "inside", "=", "pos", ".", "line", "-", "change", ".", "from", ".", "line", ";", "return", "clipToLen", "(", "pos", ",", "change", ".", "text", "[", "inside", "]", ".", "length", "+", "(", "inside", "?", "0", ":", "change", ".", "from", ".", "ch", ")", ")", ";", "}" ]
Make sure a position will be valid after the given change.
[ "Make", "sure", "a", "position", "will", "be", "valid", "after", "the", "given", "change", "." ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/themes/default/public/scripts/ghostdown.js#L2189-L2202
8,190
gilbitron/Raneto
themes/default/public/scripts/ghostdown.js
function(pos) { if (posLess(pos, change.from)) return pos; if (!posLess(change.to, pos)) return end; var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; if (pos.line == change.to.line) ch += end.ch - change.to.ch; return Pos(line, ch); }
javascript
function(pos) { if (posLess(pos, change.from)) return pos; if (!posLess(change.to, pos)) return end; var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; if (pos.line == change.to.line) ch += end.ch - change.to.ch; return Pos(line, ch); }
[ "function", "(", "pos", ")", "{", "if", "(", "posLess", "(", "pos", ",", "change", ".", "from", ")", ")", "return", "pos", ";", "if", "(", "!", "posLess", "(", "change", ".", "to", ",", "pos", ")", ")", "return", "end", ";", "var", "line", "=", "pos", ".", "line", "+", "change", ".", "text", ".", "length", "-", "(", "change", ".", "to", ".", "line", "-", "change", ".", "from", ".", "line", ")", "-", "1", ",", "ch", "=", "pos", ".", "ch", ";", "if", "(", "pos", ".", "line", "==", "change", ".", "to", ".", "line", ")", "ch", "+=", "end", ".", "ch", "-", "change", ".", "to", ".", "ch", ";", "return", "Pos", "(", "line", ",", "ch", ")", ";", "}" ]
hint is null, leave the selection alone as much as possible
[ "hint", "is", "null", "leave", "the", "selection", "alone", "as", "much", "as", "possible" ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/themes/default/public/scripts/ghostdown.js#L2217-L2224
8,191
gilbitron/Raneto
themes/default/public/scripts/ghostdown.js
extendSelection
function extendSelection(doc, pos, other, bias) { if (doc.sel.shift || doc.sel.extend) { var anchor = doc.sel.anchor; if (other) { var posBefore = posLess(pos, anchor); if (posBefore != posLess(other, anchor)) { anchor = pos; pos = other; } else if (posBefore != posLess(pos, other)) { pos = other; } } setSelection(doc, anchor, pos, bias); } else { setSelection(doc, pos, other || pos, bias); } if (doc.cm) doc.cm.curOp.userSelChange = true; }
javascript
function extendSelection(doc, pos, other, bias) { if (doc.sel.shift || doc.sel.extend) { var anchor = doc.sel.anchor; if (other) { var posBefore = posLess(pos, anchor); if (posBefore != posLess(other, anchor)) { anchor = pos; pos = other; } else if (posBefore != posLess(pos, other)) { pos = other; } } setSelection(doc, anchor, pos, bias); } else { setSelection(doc, pos, other || pos, bias); } if (doc.cm) doc.cm.curOp.userSelChange = true; }
[ "function", "extendSelection", "(", "doc", ",", "pos", ",", "other", ",", "bias", ")", "{", "if", "(", "doc", ".", "sel", ".", "shift", "||", "doc", ".", "sel", ".", "extend", ")", "{", "var", "anchor", "=", "doc", ".", "sel", ".", "anchor", ";", "if", "(", "other", ")", "{", "var", "posBefore", "=", "posLess", "(", "pos", ",", "anchor", ")", ";", "if", "(", "posBefore", "!=", "posLess", "(", "other", ",", "anchor", ")", ")", "{", "anchor", "=", "pos", ";", "pos", "=", "other", ";", "}", "else", "if", "(", "posBefore", "!=", "posLess", "(", "pos", ",", "other", ")", ")", "{", "pos", "=", "other", ";", "}", "}", "setSelection", "(", "doc", ",", "anchor", ",", "pos", ",", "bias", ")", ";", "}", "else", "{", "setSelection", "(", "doc", ",", "pos", ",", "other", "||", "pos", ",", "bias", ")", ";", "}", "if", "(", "doc", ".", "cm", ")", "doc", ".", "cm", ".", "curOp", ".", "userSelChange", "=", "true", ";", "}" ]
If shift is held, this will move the selection anchor. Otherwise, it'll set the whole selection.
[ "If", "shift", "is", "held", "this", "will", "move", "the", "selection", "anchor", ".", "Otherwise", "it", "ll", "set", "the", "whole", "selection", "." ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/themes/default/public/scripts/ghostdown.js#L2460-L2477
8,192
gilbitron/Raneto
themes/default/public/scripts/ghostdown.js
setSelection
function setSelection(doc, anchor, head, bias, checkAtomic) { if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { var filtered = filterSelectionChange(doc, anchor, head); head = filtered.head; anchor = filtered.anchor; } var sel = doc.sel; sel.goalColumn = null; // Skip over atomic spans. if (checkAtomic || !posEq(anchor, sel.anchor)) anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push"); if (checkAtomic || !posEq(head, sel.head)) head = skipAtomic(doc, head, bias, checkAtomic != "push"); if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return; sel.anchor = anchor; sel.head = head; var inv = posLess(head, anchor); sel.from = inv ? head : anchor; sel.to = inv ? anchor : head; if (doc.cm) doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = doc.cm.curOp.cursorActivity = true; signalLater(doc, "cursorActivity", doc); }
javascript
function setSelection(doc, anchor, head, bias, checkAtomic) { if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { var filtered = filterSelectionChange(doc, anchor, head); head = filtered.head; anchor = filtered.anchor; } var sel = doc.sel; sel.goalColumn = null; // Skip over atomic spans. if (checkAtomic || !posEq(anchor, sel.anchor)) anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push"); if (checkAtomic || !posEq(head, sel.head)) head = skipAtomic(doc, head, bias, checkAtomic != "push"); if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return; sel.anchor = anchor; sel.head = head; var inv = posLess(head, anchor); sel.from = inv ? head : anchor; sel.to = inv ? anchor : head; if (doc.cm) doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = doc.cm.curOp.cursorActivity = true; signalLater(doc, "cursorActivity", doc); }
[ "function", "setSelection", "(", "doc", ",", "anchor", ",", "head", ",", "bias", ",", "checkAtomic", ")", "{", "if", "(", "!", "checkAtomic", "&&", "hasHandler", "(", "doc", ",", "\"beforeSelectionChange\"", ")", "||", "doc", ".", "cm", "&&", "hasHandler", "(", "doc", ".", "cm", ",", "\"beforeSelectionChange\"", ")", ")", "{", "var", "filtered", "=", "filterSelectionChange", "(", "doc", ",", "anchor", ",", "head", ")", ";", "head", "=", "filtered", ".", "head", ";", "anchor", "=", "filtered", ".", "anchor", ";", "}", "var", "sel", "=", "doc", ".", "sel", ";", "sel", ".", "goalColumn", "=", "null", ";", "// Skip over atomic spans.", "if", "(", "checkAtomic", "||", "!", "posEq", "(", "anchor", ",", "sel", ".", "anchor", ")", ")", "anchor", "=", "skipAtomic", "(", "doc", ",", "anchor", ",", "bias", ",", "checkAtomic", "!=", "\"push\"", ")", ";", "if", "(", "checkAtomic", "||", "!", "posEq", "(", "head", ",", "sel", ".", "head", ")", ")", "head", "=", "skipAtomic", "(", "doc", ",", "head", ",", "bias", ",", "checkAtomic", "!=", "\"push\"", ")", ";", "if", "(", "posEq", "(", "sel", ".", "anchor", ",", "anchor", ")", "&&", "posEq", "(", "sel", ".", "head", ",", "head", ")", ")", "return", ";", "sel", ".", "anchor", "=", "anchor", ";", "sel", ".", "head", "=", "head", ";", "var", "inv", "=", "posLess", "(", "head", ",", "anchor", ")", ";", "sel", ".", "from", "=", "inv", "?", "head", ":", "anchor", ";", "sel", ".", "to", "=", "inv", "?", "anchor", ":", "head", ";", "if", "(", "doc", ".", "cm", ")", "doc", ".", "cm", ".", "curOp", ".", "updateInput", "=", "doc", ".", "cm", ".", "curOp", ".", "selectionChanged", "=", "doc", ".", "cm", ".", "curOp", ".", "cursorActivity", "=", "true", ";", "signalLater", "(", "doc", ",", "\"cursorActivity\"", ",", "doc", ")", ";", "}" ]
Update the selection. Last two args are only used by updateDoc, since they have to be expressed in the line numbers before the update.
[ "Update", "the", "selection", ".", "Last", "two", "args", "are", "only", "used", "by", "updateDoc", "since", "they", "have", "to", "be", "expressed", "in", "the", "line", "numbers", "before", "the", "update", "." ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/themes/default/public/scripts/ghostdown.js#L2490-L2517
8,193
gilbitron/Raneto
themes/default/public/scripts/ghostdown.js
StringStream
function StringStream(string, tabSize) { this.pos = this.start = 0; this.string = string; this.tabSize = tabSize || 8; this.lastColumnPos = this.lastColumnValue = 0; }
javascript
function StringStream(string, tabSize) { this.pos = this.start = 0; this.string = string; this.tabSize = tabSize || 8; this.lastColumnPos = this.lastColumnValue = 0; }
[ "function", "StringStream", "(", "string", ",", "tabSize", ")", "{", "this", ".", "pos", "=", "this", ".", "start", "=", "0", ";", "this", ".", "string", "=", "string", ";", "this", ".", "tabSize", "=", "tabSize", "||", "8", ";", "this", ".", "lastColumnPos", "=", "this", ".", "lastColumnValue", "=", "0", ";", "}" ]
Fed to the mode parsers, provides helper functions to make parsers more succinct. The character stream used by a mode's parser.
[ "Fed", "to", "the", "mode", "parsers", "provides", "helper", "functions", "to", "make", "parsers", "more", "succinct", ".", "The", "character", "stream", "used", "by", "a", "mode", "s", "parser", "." ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/themes/default/public/scripts/ghostdown.js#L3605-L3610
8,194
gilbitron/Raneto
themes/default/public/scripts/ghostdown.js
copyHistoryArray
function copyHistoryArray(events, newGroup) { for (var i = 0, copy = []; i < events.length; ++i) { var event = events[i], changes = event.changes, newChanges = []; copy.push({changes: newChanges, anchorBefore: event.anchorBefore, headBefore: event.headBefore, anchorAfter: event.anchorAfter, headAfter: event.headAfter}); for (var j = 0; j < changes.length; ++j) { var change = changes[j], m; newChanges.push({from: change.from, to: change.to, text: change.text}); if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { if (indexOf(newGroup, Number(m[1])) > -1) { lst(newChanges)[prop] = change[prop]; delete change[prop]; } } } } return copy; }
javascript
function copyHistoryArray(events, newGroup) { for (var i = 0, copy = []; i < events.length; ++i) { var event = events[i], changes = event.changes, newChanges = []; copy.push({changes: newChanges, anchorBefore: event.anchorBefore, headBefore: event.headBefore, anchorAfter: event.anchorAfter, headAfter: event.headAfter}); for (var j = 0; j < changes.length; ++j) { var change = changes[j], m; newChanges.push({from: change.from, to: change.to, text: change.text}); if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { if (indexOf(newGroup, Number(m[1])) > -1) { lst(newChanges)[prop] = change[prop]; delete change[prop]; } } } } return copy; }
[ "function", "copyHistoryArray", "(", "events", ",", "newGroup", ")", "{", "for", "(", "var", "i", "=", "0", ",", "copy", "=", "[", "]", ";", "i", "<", "events", ".", "length", ";", "++", "i", ")", "{", "var", "event", "=", "events", "[", "i", "]", ",", "changes", "=", "event", ".", "changes", ",", "newChanges", "=", "[", "]", ";", "copy", ".", "push", "(", "{", "changes", ":", "newChanges", ",", "anchorBefore", ":", "event", ".", "anchorBefore", ",", "headBefore", ":", "event", ".", "headBefore", ",", "anchorAfter", ":", "event", ".", "anchorAfter", ",", "headAfter", ":", "event", ".", "headAfter", "}", ")", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "changes", ".", "length", ";", "++", "j", ")", "{", "var", "change", "=", "changes", "[", "j", "]", ",", "m", ";", "newChanges", ".", "push", "(", "{", "from", ":", "change", ".", "from", ",", "to", ":", "change", ".", "to", ",", "text", ":", "change", ".", "text", "}", ")", ";", "if", "(", "newGroup", ")", "for", "(", "var", "prop", "in", "change", ")", "if", "(", "m", "=", "prop", ".", "match", "(", "/", "^spans_(\\d+)$", "/", ")", ")", "{", "if", "(", "indexOf", "(", "newGroup", ",", "Number", "(", "m", "[", "1", "]", ")", ")", ">", "-", "1", ")", "{", "lst", "(", "newChanges", ")", "[", "prop", "]", "=", "change", "[", "prop", "]", ";", "delete", "change", "[", "prop", "]", ";", "}", "}", "}", "}", "return", "copy", ";", "}" ]
Used both to provide a JSON-safe object in .getHistory, and, when detaching a document, to split the history in two
[ "Used", "both", "to", "provide", "a", "JSON", "-", "safe", "object", "in", ".", "getHistory", "and", "when", "detaching", "a", "document", "to", "split", "the", "history", "in", "two" ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/themes/default/public/scripts/ghostdown.js#L5102-L5119
8,195
gilbitron/Raneto
themes/default/public/scripts/ghostdown.js
countColumn
function countColumn(string, end, tabSize, startIndex, startValue) { if (end == null) { end = string.search(/[^\s\u00a0]/); if (end == -1) end = string.length; } for (var i = startIndex || 0, n = startValue || 0; i < end; ++i) { if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); else ++n; } return n; }
javascript
function countColumn(string, end, tabSize, startIndex, startValue) { if (end == null) { end = string.search(/[^\s\u00a0]/); if (end == -1) end = string.length; } for (var i = startIndex || 0, n = startValue || 0; i < end; ++i) { if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); else ++n; } return n; }
[ "function", "countColumn", "(", "string", ",", "end", ",", "tabSize", ",", "startIndex", ",", "startValue", ")", "{", "if", "(", "end", "==", "null", ")", "{", "end", "=", "string", ".", "search", "(", "/", "[^\\s\\u00a0]", "/", ")", ";", "if", "(", "end", "==", "-", "1", ")", "end", "=", "string", ".", "length", ";", "}", "for", "(", "var", "i", "=", "startIndex", "||", "0", ",", "n", "=", "startValue", "||", "0", ";", "i", "<", "end", ";", "++", "i", ")", "{", "if", "(", "string", ".", "charAt", "(", "i", ")", "==", "\"\\t\"", ")", "n", "+=", "tabSize", "-", "(", "n", "%", "tabSize", ")", ";", "else", "++", "n", ";", "}", "return", "n", ";", "}" ]
Counts the column offset in a string, taking tabs into account. Used mostly to find indentation.
[ "Counts", "the", "column", "offset", "in", "a", "string", "taking", "tabs", "into", "account", ".", "Used", "mostly", "to", "find", "indentation", "." ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/themes/default/public/scripts/ghostdown.js#L5298-L5308
8,196
gilbitron/Raneto
themes/default/public/scripts/ghostdown.js
updateWordCount
function updateWordCount() { var wordCount = document.getElementsByClassName('entry-word-count')[0], editorValue = editor.getValue(); if (editorValue.length) { wordCount.innerHTML = editorValue.match(/\S+/g).length + ' words'; } }
javascript
function updateWordCount() { var wordCount = document.getElementsByClassName('entry-word-count')[0], editorValue = editor.getValue(); if (editorValue.length) { wordCount.innerHTML = editorValue.match(/\S+/g).length + ' words'; } }
[ "function", "updateWordCount", "(", ")", "{", "var", "wordCount", "=", "document", ".", "getElementsByClassName", "(", "'entry-word-count'", ")", "[", "0", "]", ",", "editorValue", "=", "editor", ".", "getValue", "(", ")", ";", "if", "(", "editorValue", ".", "length", ")", "{", "wordCount", ".", "innerHTML", "=", "editorValue", ".", "match", "(", "/", "\\S+", "/", "g", ")", ".", "length", "+", "' words'", ";", "}", "}" ]
Really not the best way to do things as it includes Markdown formatting along with words
[ "Really", "not", "the", "best", "way", "to", "do", "things", "as", "it", "includes", "Markdown", "formatting", "along", "with", "words" ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/themes/default/public/scripts/ghostdown.js#L6356-L6363
8,197
gilbitron/Raneto
app/middleware/oauth2.js
function (req, res, next) { if (req.query.return) { req.session.oauth2return = req.query.return; } next(); }
javascript
function (req, res, next) { if (req.query.return) { req.session.oauth2return = req.query.return; } next(); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "req", ".", "query", ".", "return", ")", "{", "req", ".", "session", ".", "oauth2return", "=", "req", ".", "query", ".", "return", ";", "}", "next", "(", ")", ";", "}" ]
Save the url of the user's current page so the app can redirect back to it after authorization
[ "Save", "the", "url", "of", "the", "user", "s", "current", "page", "so", "the", "app", "can", "redirect", "back", "to", "it", "after", "authorization" ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/app/middleware/oauth2.js#L108-L113
8,198
gilbitron/Raneto
app/middleware/oauth2.js
function (req, res) { req.session.loggedIn = true; if (config.oauth2.validateHostedDomain) { req.session.allowedDomain = config.oauth2.hostedDomain; } var redirect = req.session.oauth2return || '/'; delete req.session.oauth2return; res.redirect(redirect); }
javascript
function (req, res) { req.session.loggedIn = true; if (config.oauth2.validateHostedDomain) { req.session.allowedDomain = config.oauth2.hostedDomain; } var redirect = req.session.oauth2return || '/'; delete req.session.oauth2return; res.redirect(redirect); }
[ "function", "(", "req", ",", "res", ")", "{", "req", ".", "session", ".", "loggedIn", "=", "true", ";", "if", "(", "config", ".", "oauth2", ".", "validateHostedDomain", ")", "{", "req", ".", "session", ".", "allowedDomain", "=", "config", ".", "oauth2", ".", "hostedDomain", ";", "}", "var", "redirect", "=", "req", ".", "session", ".", "oauth2return", "||", "'/'", ";", "delete", "req", ".", "session", ".", "oauth2return", ";", "res", ".", "redirect", "(", "redirect", ")", ";", "}" ]
Redirect back to the original page, if any
[ "Redirect", "back", "to", "the", "original", "page", "if", "any" ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/app/middleware/oauth2.js#L130-L138
8,199
gilbitron/Raneto
app/functions/contentProcessors.js
cleanObjectStrings
function cleanObjectStrings (obj) { let cleanObj = {}; for (let field in obj) { if (obj.hasOwnProperty(field)) { cleanObj[cleanString(field, true)] = ('' + obj[field]).trim(); } } return cleanObj; }
javascript
function cleanObjectStrings (obj) { let cleanObj = {}; for (let field in obj) { if (obj.hasOwnProperty(field)) { cleanObj[cleanString(field, true)] = ('' + obj[field]).trim(); } } return cleanObj; }
[ "function", "cleanObjectStrings", "(", "obj", ")", "{", "let", "cleanObj", "=", "{", "}", ";", "for", "(", "let", "field", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "field", ")", ")", "{", "cleanObj", "[", "cleanString", "(", "field", ",", "true", ")", "]", "=", "(", "''", "+", "obj", "[", "field", "]", ")", ".", "trim", "(", ")", ";", "}", "}", "return", "cleanObj", ";", "}" ]
Clean object strings.
[ "Clean", "object", "strings", "." ]
b142a33948bb0e29c77f49bebac6b58f40a4255f
https://github.com/gilbitron/Raneto/blob/b142a33948bb0e29c77f49bebac6b58f40a4255f/app/functions/contentProcessors.js#L32-L40