code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; }
Determines whether an object can have data
createSafeFragment
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; }
Determines whether an object can have data
getAll
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } }
Determines whether an object can have data
fixDefaultChecked
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; }
Determines whether an object can have data
manipulationTarget
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; }
Determines whether an object can have data
disableScript
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; }
Determines whether an object can have data
restoreScript
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } }
Determines whether an object can have data
setGlobalEval
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } }
Determines whether an object can have data
cloneCopyEvent
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } }
Determines whether an object can have data
fixCloneNodeIssues
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function actualDisplay( name, doc ) { var style, elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF style.display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; }
Retrieve the actual display of a element @param {String} name nodeName of the element @param {Object} doc Document object
actualDisplay
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; }
Try to determine the default display value of an element @param {String} nodeName
defaultDisplay
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { var condition = conditionFn(); if ( condition == null ) { // The test was not ready at this point; screw the hook this time // but check again when needed next time. return; } if ( condition ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; }
Try to determine the default display value of an element @param {String} nodeName
addGetHookIf
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function computeStyleTests() { // Minified: var b,c,d,j var div, body, container, contents; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Test fired too early or in an unsupported environment, exit. return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" + "box-sizing:border-box;display:block;margin-top:1%;top:1%;" + "border:1px;padding:1px;width:4px;position:absolute"; // Support: IE<9 // Assume reasonable values in the absence of getComputedStyle pixelPositionVal = boxSizingReliableVal = false; reliableMarginRightVal = true; // Check for getComputedStyle so that this code is not run in IE<9. if ( window.getComputedStyle ) { pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; boxSizingReliableVal = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // Div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right contents = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding contents.style.cssText = div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;padding:0"; contents.style.marginRight = contents.style.width = "0"; div.style.width = "1px"; reliableMarginRightVal = !parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight ); } // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; contents = div.getElementsByTagName( "td" ); contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none"; reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0; if ( reliableHiddenOffsetsVal ) { contents[ 0 ].style.display = ""; contents[ 1 ].style.display = "none"; reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0; } body.removeChild( container ); }
Try to determine the default display value of an element @param {String} nodeName
computeStyleTests
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; }
Try to determine the default display value of an element @param {String} nodeName
vendorPropName
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; }
Try to determine the default display value of an element @param {String} nodeName
showHide
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; }
Try to determine the default display value of an element @param {String} nodeName
setPositiveNumber
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; }
Try to determine the default display value of an element @param {String} nodeName
augmentWidthOrHeight
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; }
Try to determine the default display value of an element @param {String} nodeName
getWidthOrHeight
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); }
Try to determine the default display value of an element @param {String} nodeName
Tween
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); }
Try to determine the default display value of an element @param {String} nodeName
createFxNow
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; }
Try to determine the default display value of an element @param {String} nodeName
genFx
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } }
Try to determine the default display value of an element @param {String} nodeName
createTween
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); // Test default display if display is currently "none" checkDisplay = display === "none" ? jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !support.shrinkWrapBlocks() ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); // Any non-fx value stops us from restoring the original display value } else { display = undefined; } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } // If this is a noop like .hide().hide(), restore an overwritten display value } else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) { style.display = display; } }
Try to determine the default display value of an element @param {String} nodeName
defaultPrefilter
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } }
Try to determine the default display value of an element @param {String} nodeName
propFilter
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); }
Try to determine the default display value of an element @param {String} nodeName
Animation
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }
Try to determine the default display value of an element @param {String} nodeName
tick
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }
Try to determine the default display value of an element @param {String} nodeName
doAnimation
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }
Try to determine the default display value of an element @param {String} nodeName
stopQueue
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType.charAt( 0 ) === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; }
Try to determine the default display value of an element @param {String} nodeName
addToPrefiltersOrTransports
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); }
Try to determine the default display value of an element @param {String} nodeName
inspectPrefiltersOrTransports
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; }
Try to determine the default display value of an element @param {String} nodeName
inspect
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; }
Try to determine the default display value of an element @param {String} nodeName
ajaxExtend
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } }
Try to determine the default display value of an element @param {String} nodeName
ajaxHandleResponses
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; }
Try to determine the default display value of an element @param {String} nodeName
ajaxConvert
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } }
Try to determine the default display value of an element @param {String} nodeName
done
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } }
Try to determine the default display value of an element @param {String} nodeName
buildParams
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }
Try to determine the default display value of an element @param {String} nodeName
add
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} }
Try to determine the default display value of an element @param {String} nodeName
createStandardXHR
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} }
Try to determine the default display value of an element @param {String} nodeName
createActiveXHR
javascript
lodge/lodge
public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
https://github.com/lodge/lodge/blob/master/public/assets/application-ad2df1dd7a2bc3c99128f6e5716010ee.js
MIT
function addStyleSheet(ownerDocument, cssText) { var p = ownerDocument.createElement('p'), parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement; p.innerHTML = 'x<style>' + cssText + '</style>'; return parent.insertBefore(p.lastChild, parent.firstChild); }
Creates a style sheet with the given CSS text and adds it to the document. @private @param {Document} ownerDocument The document. @param {String} cssText The CSS text. @returns {StyleSheet} The style element.
addStyleSheet
javascript
lodge/lodge
vendor/assets/javascripts/externals/html5shiv.js
https://github.com/lodge/lodge/blob/master/vendor/assets/javascripts/externals/html5shiv.js
MIT
function getElements() { var elements = html5.elements; return typeof elements == 'string' ? elements.split(' ') : elements; }
Returns the value of `html5.elements` as an array. @private @returns {Array} An array of shived element node names.
getElements
javascript
lodge/lodge
vendor/assets/javascripts/externals/html5shiv.js
https://github.com/lodge/lodge/blob/master/vendor/assets/javascripts/externals/html5shiv.js
MIT
function addElements(newElements, ownerDocument) { var elements = html5.elements; if(typeof elements != 'string'){ elements = elements.join(' '); } if(typeof newElements != 'string'){ newElements = newElements.join(' '); } html5.elements = elements +' '+ newElements; shivDocument(ownerDocument); }
Extends the built-in list of html5 elements @memberOf html5 @param {String|Array} newElements whitespace separated list or array of new element names to shiv @param {Document} ownerDocument The context document.
addElements
javascript
lodge/lodge
vendor/assets/javascripts/externals/html5shiv.js
https://github.com/lodge/lodge/blob/master/vendor/assets/javascripts/externals/html5shiv.js
MIT
function getExpandoData(ownerDocument) { var data = expandoData[ownerDocument[expando]]; if (!data) { data = {}; expanID++; ownerDocument[expando] = expanID; expandoData[expanID] = data; } return data; }
Returns the data associated to the given document @private @param {Document} ownerDocument The document. @returns {Object} An object of data.
getExpandoData
javascript
lodge/lodge
vendor/assets/javascripts/externals/html5shiv.js
https://github.com/lodge/lodge/blob/master/vendor/assets/javascripts/externals/html5shiv.js
MIT
function createElement(nodeName, ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createElement(nodeName); } if (!data) { data = getExpandoData(ownerDocument); } var node; if (data.cache[nodeName]) { node = data.cache[nodeName].cloneNode(); } else if (saveClones.test(nodeName)) { node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode(); } else { node = data.createElem(nodeName); } // Avoid adding some elements to fragments in IE < 9 because // * Attributes like `name` or `type` cannot be set/changed once an element // is inserted into a document/fragment // * Link elements with `src` attributes that are inaccessible, as with // a 403 response, will cause the tab/window to crash // * Script elements appended to fragments will execute when their `src` // or `text` property is set return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node; }
returns a shived element for the given nodeName and document @memberOf html5 @param {String} nodeName name of the element @param {Document} ownerDocument The context document. @returns {Object} The shived element.
createElement
javascript
lodge/lodge
vendor/assets/javascripts/externals/html5shiv.js
https://github.com/lodge/lodge/blob/master/vendor/assets/javascripts/externals/html5shiv.js
MIT
function createDocumentFragment(ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createDocumentFragment(); } data = data || getExpandoData(ownerDocument); var clone = data.frag.cloneNode(), i = 0, elems = getElements(), l = elems.length; for(;i<l;i++){ clone.createElement(elems[i]); } return clone; }
returns a shived DocumentFragment for the given document @memberOf html5 @param {Document} ownerDocument The context document. @returns {Object} The shived DocumentFragment.
createDocumentFragment
javascript
lodge/lodge
vendor/assets/javascripts/externals/html5shiv.js
https://github.com/lodge/lodge/blob/master/vendor/assets/javascripts/externals/html5shiv.js
MIT
function shivMethods(ownerDocument, data) { if (!data.cache) { data.cache = {}; data.createElem = ownerDocument.createElement; data.createFrag = ownerDocument.createDocumentFragment; data.frag = data.createFrag(); } ownerDocument.createElement = function(nodeName) { //abort shiv if (!html5.shivMethods) { return data.createElem(nodeName); } return createElement(nodeName, ownerDocument, data); }; ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' + 'var n=f.cloneNode(),c=n.createElement;' + 'h.shivMethods&&(' + // unroll the `createElement` calls getElements().join().replace(/[\w\-:]+/g, function(nodeName) { data.createElem(nodeName); data.frag.createElement(nodeName); return 'c("' + nodeName + '")'; }) + ');return n}' )(html5, data.frag); }
Shivs the `createElement` and `createDocumentFragment` methods of the document. @private @param {Document|DocumentFragment} ownerDocument The document. @param {Object} data of the document.
shivMethods
javascript
lodge/lodge
vendor/assets/javascripts/externals/html5shiv.js
https://github.com/lodge/lodge/blob/master/vendor/assets/javascripts/externals/html5shiv.js
MIT
function shivDocument(ownerDocument) { if (!ownerDocument) { ownerDocument = document; } var data = getExpandoData(ownerDocument); if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) { data.hasCSS = !!addStyleSheet(ownerDocument, // corrects block display not defined in IE6/7/8/9 'article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}' + // adds styling not present in IE6/7/8/9 'mark{background:#FF0;color:#000}' + // hides non-rendered elements 'template{display:none}' ); } if (!supportsUnknownElements) { shivMethods(ownerDocument, data); } return ownerDocument; }
Shivs the given document. @memberOf html5 @param {Document} ownerDocument The document to shiv. @returns {Document} The shived document.
shivDocument
javascript
lodge/lodge
vendor/assets/javascripts/externals/html5shiv.js
https://github.com/lodge/lodge/blob/master/vendor/assets/javascripts/externals/html5shiv.js
MIT
function TimeSeries(options) { this.options = Util.extend({}, TimeSeries.defaultOptions, options); this.clear(); }
Initialises a new <code>TimeSeries</code> with optional data options. Options are of the form (defaults shown): <pre> { resetBounds: true, // enables/disables automatic scaling of the y-axis resetBoundsInterval: 3000 // the period between scaling calculations, in millis } </pre> Presentation options for TimeSeries are specified as an argument to <code>SmoothieChart.addTimeSeries</code>. @constructor
TimeSeries
javascript
01alchemist/TurboScript
benchmark/web-dsp/demo/smoothie.js
https://github.com/01alchemist/TurboScript/blob/master/benchmark/web-dsp/demo/smoothie.js
Apache-2.0
function SmoothieChart(options) { this.options = Util.extend({}, SmoothieChart.defaultChartOptions, options); this.seriesSet = []; this.currentValueRange = 1; this.currentVisMinValue = 0; this.lastRenderTimeMillis = 0; }
Initialises a new <code>SmoothieChart</code>. Options are optional, and should be of the form below. Just specify the values you need and the rest will be given sensible defaults as shown: <pre> { minValue: undefined, // specify to clamp the lower y-axis to a given value maxValue: undefined, // specify to clamp the upper y-axis to a given value maxValueScale: 1, // allows proportional padding to be added above the chart. for 10% padding, specify 1.1. minValueScale: 1, // allows proportional padding to be added below the chart. for 10% padding, specify 1.1. yRangeFunction: undefined, // function({min: , max: }) { return {min: , max: }; } scaleSmoothing: 0.125, // controls the rate at which y-value zoom animation occurs millisPerPixel: 20, // sets the speed at which the chart pans by enableDpiScaling: true, // support rendering at different DPI depending on the device yMinFormatter: function(min, precision) { // callback function that formats the min y value label return parseFloat(min).toFixed(precision); }, yMaxFormatter: function(max, precision) { // callback function that formats the max y value label return parseFloat(max).toFixed(precision); }, maxDataSetLength: 2, interpolation: 'bezier' // one of 'bezier', 'linear', or 'step' timestampFormatter: null, // optional function to format time stamps for bottom of chart // you may use SmoothieChart.timeFormatter, or your own: function(date) { return ''; } scrollBackwards: false, // reverse the scroll direction of the chart horizontalLines: [], // [ { value: 0, color: '#ffffff', lineWidth: 1 } ] grid: { fillStyle: '#000000', // the background colour of the chart lineWidth: 1, // the pixel width of grid lines strokeStyle: '#777777', // colour of grid lines millisPerLine: 1000, // distance between vertical grid lines sharpLines: false, // controls whether grid lines are 1px sharp, or softened verticalSections: 2, // number of vertical sections marked out by horizontal grid lines borderVisible: true // whether the grid lines trace the border of the chart or not }, labels { disabled: false, // enables/disables labels showing the min/max values fillStyle: '#ffffff', // colour for text of labels, fontSize: 15, fontFamily: 'sans-serif', precision: 2 } } </pre> @constructor
SmoothieChart
javascript
01alchemist/TurboScript
benchmark/web-dsp/demo/smoothie.js
https://github.com/01alchemist/TurboScript/blob/master/benchmark/web-dsp/demo/smoothie.js
Apache-2.0
requestAnimationFrame = function(callback, element) { var requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { return window.setTimeout(function() { callback(new Date().getTime()); }, 16); }; return requestAnimationFrame.call(window, callback, element); }
Initialises a new <code>SmoothieChart</code>. Options are optional, and should be of the form below. Just specify the values you need and the rest will be given sensible defaults as shown: <pre> { minValue: undefined, // specify to clamp the lower y-axis to a given value maxValue: undefined, // specify to clamp the upper y-axis to a given value maxValueScale: 1, // allows proportional padding to be added above the chart. for 10% padding, specify 1.1. minValueScale: 1, // allows proportional padding to be added below the chart. for 10% padding, specify 1.1. yRangeFunction: undefined, // function({min: , max: }) { return {min: , max: }; } scaleSmoothing: 0.125, // controls the rate at which y-value zoom animation occurs millisPerPixel: 20, // sets the speed at which the chart pans by enableDpiScaling: true, // support rendering at different DPI depending on the device yMinFormatter: function(min, precision) { // callback function that formats the min y value label return parseFloat(min).toFixed(precision); }, yMaxFormatter: function(max, precision) { // callback function that formats the max y value label return parseFloat(max).toFixed(precision); }, maxDataSetLength: 2, interpolation: 'bezier' // one of 'bezier', 'linear', or 'step' timestampFormatter: null, // optional function to format time stamps for bottom of chart // you may use SmoothieChart.timeFormatter, or your own: function(date) { return ''; } scrollBackwards: false, // reverse the scroll direction of the chart horizontalLines: [], // [ { value: 0, color: '#ffffff', lineWidth: 1 } ] grid: { fillStyle: '#000000', // the background colour of the chart lineWidth: 1, // the pixel width of grid lines strokeStyle: '#777777', // colour of grid lines millisPerLine: 1000, // distance between vertical grid lines sharpLines: false, // controls whether grid lines are 1px sharp, or softened verticalSections: 2, // number of vertical sections marked out by horizontal grid lines borderVisible: true // whether the grid lines trace the border of the chart or not }, labels { disabled: false, // enables/disables labels showing the min/max values fillStyle: '#ffffff', // colour for text of labels, fontSize: 15, fontFamily: 'sans-serif', precision: 2 } } </pre> @constructor
requestAnimationFrame
javascript
01alchemist/TurboScript
benchmark/web-dsp/demo/smoothie.js
https://github.com/01alchemist/TurboScript/blob/master/benchmark/web-dsp/demo/smoothie.js
Apache-2.0
cancelAnimationFrame = function(id) { var cancelAnimationFrame = window.cancelAnimationFrame || function(id) { clearTimeout(id); }; return cancelAnimationFrame.call(window, id); }
Initialises a new <code>SmoothieChart</code>. Options are optional, and should be of the form below. Just specify the values you need and the rest will be given sensible defaults as shown: <pre> { minValue: undefined, // specify to clamp the lower y-axis to a given value maxValue: undefined, // specify to clamp the upper y-axis to a given value maxValueScale: 1, // allows proportional padding to be added above the chart. for 10% padding, specify 1.1. minValueScale: 1, // allows proportional padding to be added below the chart. for 10% padding, specify 1.1. yRangeFunction: undefined, // function({min: , max: }) { return {min: , max: }; } scaleSmoothing: 0.125, // controls the rate at which y-value zoom animation occurs millisPerPixel: 20, // sets the speed at which the chart pans by enableDpiScaling: true, // support rendering at different DPI depending on the device yMinFormatter: function(min, precision) { // callback function that formats the min y value label return parseFloat(min).toFixed(precision); }, yMaxFormatter: function(max, precision) { // callback function that formats the max y value label return parseFloat(max).toFixed(precision); }, maxDataSetLength: 2, interpolation: 'bezier' // one of 'bezier', 'linear', or 'step' timestampFormatter: null, // optional function to format time stamps for bottom of chart // you may use SmoothieChart.timeFormatter, or your own: function(date) { return ''; } scrollBackwards: false, // reverse the scroll direction of the chart horizontalLines: [], // [ { value: 0, color: '#ffffff', lineWidth: 1 } ] grid: { fillStyle: '#000000', // the background colour of the chart lineWidth: 1, // the pixel width of grid lines strokeStyle: '#777777', // colour of grid lines millisPerLine: 1000, // distance between vertical grid lines sharpLines: false, // controls whether grid lines are 1px sharp, or softened verticalSections: 2, // number of vertical sections marked out by horizontal grid lines borderVisible: true // whether the grid lines trace the border of the chart or not }, labels { disabled: false, // enables/disables labels showing the min/max values fillStyle: '#ffffff', // colour for text of labels, fontSize: 15, fontFamily: 'sans-serif', precision: 2 } } </pre> @constructor
cancelAnimationFrame
javascript
01alchemist/TurboScript
benchmark/web-dsp/demo/smoothie.js
https://github.com/01alchemist/TurboScript/blob/master/benchmark/web-dsp/demo/smoothie.js
Apache-2.0
timeToXPixel = function(t) { if(chartOptions.scrollBackwards) { return Math.round((time - t) / chartOptions.millisPerPixel); } return Math.round(dimensions.width - ((time - t) / chartOptions.millisPerPixel)); }
Stops the animation of this chart.
timeToXPixel
javascript
01alchemist/TurboScript
benchmark/web-dsp/demo/smoothie.js
https://github.com/01alchemist/TurboScript/blob/master/benchmark/web-dsp/demo/smoothie.js
Apache-2.0
function deriveConcreteClass(context, type, parameters, scope) { var templateNode = type.resolvedType.pointerTo ? type.resolvedType.pointerTo.symbol.node : type.resolvedType.symbol.node; var templateName = templateNode.stringValue; var typeName = templateNode.stringValue + ("<" + parameters[0].stringValue + ">"); var rename = templateNode.stringValue + ("_" + parameters[0].stringValue); var symbol = scope.parent.findNested(typeName, scope_1.ScopeHint.NORMAL, scope_1.FindNested.NORMAL); if (symbol) { // resolve(context, type.firstChild.firstChild, scope.parent); var genericSymbol = scope.parent.findNested(type.firstChild.firstChild.stringValue, scope_1.ScopeHint.NORMAL, scope_1.FindNested.NORMAL); type.firstChild.firstChild.symbol = genericSymbol; if (genericSymbol.resolvedType.pointerTo) { type.firstChild.firstChild.resolvedType = genericSymbol.resolvedType.pointerType(); } else { type.firstChild.firstChild.resolvedType = genericSymbol.resolvedType; } type.symbol = symbol; if (type.resolvedType.pointerTo) { type.resolvedType = symbol.resolvedType.pointerType(); } else { type.resolvedType = symbol.resolvedType; } return; } var node = templateNode.clone(); // node.parent = templateNode.parent; node.stringValue = typeName; cloneChildren(templateNode.firstChild.nextSibling, node, parameters, templateName, typeName); node.offset = null; //FIXME: we cannot take offset from class template node initialize(context, node, scope.parent, CheckMode.NORMAL); resolve(context, node, scope.parent); node.symbol.flags |= symbol_1.SYMBOL_FLAG_USED; node.constructorFunctionNode.symbol.flags |= symbol_1.SYMBOL_FLAG_USED; type.symbol = node.symbol; node.symbol.rename = rename; if (type.resolvedType.pointerTo) { type.resolvedType = node.symbol.resolvedType.pointerType(); } else { type.resolvedType = node.symbol.resolvedType; } if (templateNode.parent) { templateNode.replaceWith(node); } else { var prevNode = templateNode.derivedNodes[templateNode.derivedNodes.length - 1]; prevNode.parent.insertChildAfter(prevNode, node); } if (templateNode.derivedNodes === undefined) { templateNode.derivedNodes = []; } templateNode.derivedNodes.push(node); //Leave the parameter for the emitter to identify the type type.firstChild.firstChild.kind = node_1.NodeKind.NAME; resolve(context, type.firstChild.firstChild, scope.parent); type.stringValue = node.symbol.name; return; }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
deriveConcreteClass
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function cloneChildren(child, parentNode, parameters, templateName, typeName) { var firstChildNode = null; var lastChildNode = null; while (child) { if (child.stringValue == "this" && child.parent.symbol && child.parent.symbol.kind == symbol_1.SymbolKind.FUNCTION_INSTANCE && child.kind == node_1.NodeKind.TYPE) { child = child.nextSibling; continue; } var childNode = void 0; if (child.kind == node_1.NodeKind.PARAMETERS || child.kind == node_1.NodeKind.PARAMETER) { child = child.nextSibling; continue; } if (child.isGeneric()) { var offset = child.offset; if (child.resolvedType) { offset = child.resolvedType.pointerTo ? child.resolvedType.pointerTo.symbol.node.offset : child.resolvedType.symbol.node.offset; } if (child.symbol && symbol_1.isVariable(child.symbol.kind)) { childNode = child.clone(); } else { childNode = parameters[offset].clone(); } childNode.kind = node_1.NodeKind.NAME; } else { if (child.stringValue == "T") { terminal_1.Terminal.write("Generic type escaped!"); terminal_1.Terminal.write(child); } childNode = child.clone(); if (childNode.stringValue == templateName) { childNode.stringValue = typeName; } } childNode.parent = parentNode; if (childNode.stringValue == "constructor" && childNode.parent.kind == node_1.NodeKind.CLASS) { childNode.parent.constructorFunctionNode = childNode; } if (!firstChildNode) { firstChildNode = childNode; } if (lastChildNode) { lastChildNode.nextSibling = childNode; childNode.previousSibling = lastChildNode; } if (child.firstChild) { cloneChildren(child.firstChild, childNode, parameters, templateName, typeName); } lastChildNode = childNode; child = child.nextSibling; } if (firstChildNode != null) parentNode.firstChild = firstChildNode; if (lastChildNode != null) parentNode.lastChild = lastChildNode; }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
cloneChildren
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function resolveChildren(context, node, parentScope) { var child = node.firstChild; while (child != null) { resolve(context, child, parentScope); assert_1.assert(child.resolvedType != null); child = child.nextSibling; } }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
resolveChildren
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function resolveChildrenAsExpressions(context, node, parentScope) { var child = node.firstChild; while (child != null) { resolveAsExpression(context, child, parentScope); child = child.nextSibling; } }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
resolveChildrenAsExpressions
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function resolveAsExpression(context, node, parentScope) { assert_1.assert(node_1.isExpression(node)); resolve(context, node, parentScope); assert_1.assert(node.resolvedType != null); if (node.resolvedType != context.errorType) { if (node.isType()) { context.log.error(node.range, "Expected expression but found type"); node.resolvedType = context.errorType; } else if (node.resolvedType == context.voidType && node.parent.kind != node_1.NodeKind.EXPRESSION) { context.log.error(node.range, "This expression does not return a value"); node.resolvedType = context.errorType; } } }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
resolveAsExpression
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function resolveAsType(context, node, parentScope) { assert_1.assert(node_1.isExpression(node)); resolve(context, node, parentScope); assert_1.assert(node.resolvedType != null); if (node.resolvedType != context.errorType && !node.isType()) { context.log.error(node.range, "Expected type but found expression"); node.resolvedType = context.errorType; } }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
resolveAsType
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function canConvert(context, node, to, kind) { var from = node.resolvedType; assert_1.assert(node_1.isExpression(node)); assert_1.assert(from != null); assert_1.assert(to != null); //Generic always accept any types if (from.isGeneric() || to.isGeneric()) { return true; } // Early-out if the types are identical or errors if (from == to || from == context.errorType || to == context.errorType) { return true; } else if (from == context.nullType /* && to.isReference()*/) { return true; } else if ((from.isReference() || to.isReference())) { if (kind == type_1.ConversionKind.EXPLICIT) { return true; } } else if (from == context.booleanType) { return true; } else if (from.isInteger() && to.isInteger()) { var mask = to.integerBitMask(context); if (from.isUnsigned() && to.isUnsigned()) { return true; } // Allow implicit conversions between enums and int32 if (from.isEnum() && to == from.underlyingType(context)) { return true; } if (!node.intValue) { return true; } // Only allow lossless conversions implicitly if (kind == type_1.ConversionKind.EXPLICIT || from.symbol.byteSize < to.symbol.byteSize || node.kind == node_1.NodeKind.INT32 && (to.isUnsigned() ? node.intValue >= 0 && node.intValue <= const_1.MAX_UINT32_VALUE : node.intValue >= const_1.MIN_INT32_VALUE && node.intValue <= const_1.MAX_INT32_VALUE)) { return true; } return false; } else if (from.isInteger() && to.isFloat() || from.isInteger() && to.isDouble() || from.isLong() && to.isInteger() || from.isLong() && to.isFloat() || from.isLong() && to.isDouble() || from.isFloat() && to.isInteger() || from.isFloat() && to.isLong() || from.isDouble() && to.isInteger() || from.isDouble() && to.isLong() || from.isDouble() && to.isFloat()) { if (kind == type_1.ConversionKind.IMPLICIT) { return false; } return true; } else if (from.isInteger() && to.isLong() || from.isFloat() && to.isDouble() || from.isFloat() && to.isFloat() || from.isDouble() && to.isDouble()) { return true; } return false; }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
canConvert
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function checkConversion(context, node, to, kind) { if (!canConvert(context, node, to, kind)) { context.log.error(node.range, "Cannot convert from type '" + node.resolvedType.toString() + "' to type '" + to.toString() + "' " + (kind == type_1.ConversionKind.IMPLICIT && canConvert(context, node, to, type_1.ConversionKind.EXPLICIT) ? "without a cast" : "")); node.resolvedType = context.errorType; } }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
checkConversion
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function checkStorage(context, target) { assert_1.assert(node_1.isExpression(target)); if (target.resolvedType != context.errorType && target.kind != node_1.NodeKind.INDEX && target.kind != node_1.NodeKind.POINTER_INDEX && target.kind != node_1.NodeKind.DEREFERENCE && (target.kind != node_1.NodeKind.NAME && target.kind != node_1.NodeKind.DOT || target.symbol != null && (!symbol_1.isVariable(target.symbol.kind) || target.symbol.kind == symbol_1.SymbolKind.VARIABLE_CONSTANT))) { context.log.error(target.range, "Cannot store to this location"); target.resolvedType = context.errorType; } }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
checkStorage
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function createDefaultValueForType(context, type) { if (type.isLong()) { return node_1.createLong(0); } else if (type.isInteger()) { return node_1.createInt(0); } else if (type.isDouble()) { return node_1.createDouble(0); } else if (type.isFloat()) { return node_1.createFloat(0); } if (type == context.booleanType) { return node_1.createboolean(false); } if (type.isClass()) { return node_1.createNull(); } if (type.isGeneric()) { return node_1.createNull(); } assert_1.assert(type.isReference()); return node_1.createNull(); }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
createDefaultValueForType
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function simplifyBinary(node) { var left = node.binaryLeft(); var right = node.binaryRight(); // Canonicalize commutative operators if ((node.kind == node_1.NodeKind.ADD || node.kind == node_1.NodeKind.MULTIPLY || node.kind == node_1.NodeKind.BITWISE_AND || node.kind == node_1.NodeKind.BITWISE_OR || node.kind == node_1.NodeKind.BITWISE_XOR) && left.kind == node_1.NodeKind.INT32 && right.kind != node_1.NodeKind.INT32) { node.appendChild(left.remove()); left = node.binaryLeft(); right = node.binaryRight(); } // Convert multiplication or division by a power of 2 into a shift if ((node.kind == node_1.NodeKind.MULTIPLY || (node.kind == node_1.NodeKind.DIVIDE || node.kind == node_1.NodeKind.REMAINDER) && node.resolvedType.isUnsigned()) && right.kind == node_1.NodeKind.INT32 && utils_1.isPositivePowerOf2(right.intValue)) { // Extract the shift from the value var shift = -1; var value = right.intValue; while (value != 0) { value = value >> 1; shift = shift + 1; } // "x * 16" => "x << 4" if (node.kind == node_1.NodeKind.MULTIPLY) { node.kind = node_1.NodeKind.SHIFT_LEFT; right.intValue = shift; } else if (node.kind == node_1.NodeKind.DIVIDE) { node.kind = node_1.NodeKind.SHIFT_RIGHT; right.intValue = shift; } else if (node.kind == node_1.NodeKind.REMAINDER) { node.kind = node_1.NodeKind.BITWISE_AND; right.intValue = right.intValue - 1; } else { assert_1.assert(false); } } else if (node.kind == node_1.NodeKind.ADD && right.kind == node_1.NodeKind.NEGATIVE) { node.kind = node_1.NodeKind.SUBTRACT; right.replaceWith(right.unaryValue().remove()); } else if (node.kind == node_1.NodeKind.ADD && right.isNegativeInteger()) { node.kind = node_1.NodeKind.SUBTRACT; right.intValue = -right.intValue; } }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
simplifyBinary
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function binaryHasUnsignedArguments(node) { var left = node.binaryLeft(); var right = node.binaryRight(); var leftType = left.resolvedType; var rightType = right.resolvedType; return leftType.isUnsigned() && rightType.isUnsigned() || leftType.isUnsigned() && right.isNonNegativeInteger() || left.isNonNegativeInteger() && rightType.isUnsigned(); }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
binaryHasUnsignedArguments
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function isBinaryLong(node) { var left = node.binaryLeft(); var right = node.binaryRight(); var leftType = left.resolvedType; var rightType = right.resolvedType; return leftType.isLong() || rightType.isLong(); }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
isBinaryLong
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function isBinaryDouble(node) { var left = node.binaryLeft(); var right = node.binaryRight(); var leftType = left.resolvedType; var rightType = right.resolvedType; return leftType.isDouble() || rightType.isDouble(); }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
isBinaryDouble
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function isSymbolAccessAllowed(context, symbol, node, range) { if (symbol.isUnsafe() && !context.isUnsafeAllowed) { context.log.error(range, "Cannot use symbol '" + symbol.name + "' outside an 'unsafe' block"); return false; } if (symbol.node != null && symbol.node.isPrivate()) { var parent = symbol.parent(); if (parent != null && context.enclosingClass != parent) { context.log.error(range, "Cannot access private symbol '" + symbol.name + "' here"); return false; } } if (symbol_1.isFunction(symbol.kind) && (symbol.isSetter() ? !node.isAssignTarget() : !node.isCallValue())) { if (symbol.isSetter()) { context.log.error(range, "Cannot use setter '" + symbol.name + "' here"); } else { context.log.error(range, "Must call function '" + symbol.name + "'"); } return false; } return true; }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
isSymbolAccessAllowed
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function resolve(context, node, parentScope) { var kind = node.kind; assert_1.assert(kind == node_1.NodeKind.FILE || parentScope != null); if (node.resolvedType != null) { return; } node.resolvedType = context.errorType; if (kind == node_1.NodeKind.FILE || kind == node_1.NodeKind.GLOBAL) { resolveChildren(context, node, parentScope); } else if (kind == node_1.NodeKind.MODULE) { var oldEnclosingModule = context.enclosingModule; initializeSymbol(context, node.symbol); context.enclosingModule = node.symbol; resolveChildren(context, node, node.scope); context.enclosingModule = oldEnclosingModule; } else if (kind == node_1.NodeKind.IMPORT || kind == node_1.NodeKind.IMPORT_FROM) { //ignore imports } else if (kind == node_1.NodeKind.CLASS) { var oldEnclosingClass = context.enclosingClass; initializeSymbol(context, node.symbol); context.enclosingClass = node.symbol; resolveChildren(context, node, node.scope); if (!node.isDeclare() && node.constructorFunctionNode === undefined) { node.constructorFunctionNode = node.createEmptyConstructor(); node.appendChild(node.constructorFunctionNode); initialize(context, node.constructorFunctionNode, node.scope, CheckMode.NORMAL); // let firstFunction = node.firstInstanceFunction(); // if(firstFunction === undefined){ // node.insertChildBefore(firstFunction, node.constructorFunctionNode); // } else { // node.insertChildBefore(firstFunction, node.constructorFunctionNode); // } resolve(context, node.constructorFunctionNode, node.scope); } if (node.symbol.kind == symbol_1.SymbolKind.TYPE_CLASS) { node.symbol.determineClassLayout(context); } context.enclosingClass = oldEnclosingClass; } else if (kind == node_1.NodeKind.ENUM) { initializeSymbol(context, node.symbol); resolveChildren(context, node, node.scope); } else if (kind == node_1.NodeKind.FUNCTION) { var body = node.functionBody(); initializeSymbol(context, node.symbol); if (node.stringValue == "constructor" && node.parent.kind == node_1.NodeKind.CLASS) { node.parent.constructorFunctionNode = node; } if (body != null) { var oldReturnType = context.currentReturnType; var oldUnsafeAllowed = context.isUnsafeAllowed; var returnType = node.functionReturnType(); if (returnType.resolvedType.isTemplate() && returnType.hasParameters() && node.parent != returnType.resolvedType.symbol.node) { deriveConcreteClass(context, returnType, [returnType.firstChild.firstChild], returnType.resolvedType.symbol.scope); } context.currentReturnType = returnType.resolvedType; context.isUnsafeAllowed = node.isUnsafe(); resolveChildren(context, body, node.scope); if (oldReturnType && oldReturnType.isTemplate() && returnType.hasParameters() && node.parent != oldReturnType.symbol.node) { deriveConcreteClass(context, returnType, [returnType.firstChild.firstChild], oldReturnType.symbol.scope); } // if (oldReturnType && oldReturnType.isTemplate() && !oldReturnType.symbol.node.hasParameters()) { // deriveConcreteClass(context, oldReturnType.symbol.node, [oldReturnType.symbol.node.firstChild], oldReturnType.symbol.scope); // } context.currentReturnType = oldReturnType; context.isUnsafeAllowed = oldUnsafeAllowed; } } else if (kind == node_1.NodeKind.PARAMETER) { var symbol = node.symbol; } else if (kind == node_1.NodeKind.VARIABLE) { var symbol = node.symbol; initializeSymbol(context, symbol); var oldUnsafeAllowed = context.isUnsafeAllowed; context.isUnsafeAllowed = context.isUnsafeAllowed || node.isUnsafe(); var value = node.variableValue(); if (value != null) { resolveAsExpression(context, value, parentScope); checkConversion(context, value, symbol.resolvedTypeUnderlyingIfEnumValue(context), type_1.ConversionKind.IMPLICIT); if (symbol.resolvedType != value.resolvedType) { value.becomeValueTypeOf(symbol, context); } // Variable initializers must be compile-time constants if (symbol.kind == symbol_1.SymbolKind.VARIABLE_GLOBAL && value.kind != node_1.NodeKind.INT32 && value.kind != node_1.NodeKind.BOOLEAN && value.kind != node_1.NodeKind.NULL) { //context.log.error(value.range, "Global initializers must be compile-time constants"); } } else if (symbol.resolvedType != context.errorType) { value = createDefaultValueForType(context, symbol.resolvedType); resolveAsExpression(context, value, parentScope); node.appendChild(value); } // Allocate global variables if (symbol.kind == symbol_1.SymbolKind.VARIABLE_GLOBAL && symbol.resolvedType != context.errorType) { symbol.offset = context.allocateGlobalVariableOffset(symbol.resolvedType.variableSizeOf(context), symbol.resolvedType.variableAlignmentOf(context)); } context.isUnsafeAllowed = oldUnsafeAllowed; } else if (kind == node_1.NodeKind.BREAK || kind == node_1.NodeKind.CONTINUE) { var found = false; var n = node; while (n != null) { if (n.kind == node_1.NodeKind.WHILE) { found = true; break; } n = n.parent; } if (!found) { context.log.error(node.range, "Cannot use this statement outside of a loop"); } } else if (kind == node_1.NodeKind.BLOCK) { var oldUnsafeAllowed = context.isUnsafeAllowed; if (node.isUnsafe()) context.isUnsafeAllowed = true; resolveChildren(context, node, node.scope); context.isUnsafeAllowed = oldUnsafeAllowed; } else if (kind == node_1.NodeKind.IMPORTS || kind == node_1.NodeKind.CONSTANTS || kind == node_1.NodeKind.VARIABLES) { resolveChildren(context, node, parentScope); } else if (kind == node_1.NodeKind.ANY) { //imported functions have anyType node.kind = node_1.NodeKind.TYPE; node.resolvedType = context.anyType; } else if (kind == node_1.NodeKind.INT32) { // Use the positive flag to differentiate between -2147483648 and 2147483648 node.resolvedType = node.intValue < 0 && !node.isPositive() ? context.uint32Type : context.int32Type; } else if (kind == node_1.NodeKind.INT64) { node.resolvedType = node.intValue < 0 && !node.isPositive() ? context.uint64Type : context.int64Type; } else if (kind == node_1.NodeKind.FLOAT32) { node.resolvedType = context.float32Type; } else if (kind == node_1.NodeKind.FLOAT64) { node.resolvedType = context.float64Type; } else if (kind == node_1.NodeKind.STRING) { node.resolvedType = context.stringType; } else if (kind == node_1.NodeKind.BOOLEAN) { node.resolvedType = context.booleanType; } else if (kind == node_1.NodeKind.NULL) { node.resolvedType = context.nullType; } else if (kind == node_1.NodeKind.INDEX) { resolveChildrenAsExpressions(context, node, parentScope); var target = node.indexTarget(); var type = target.resolvedType; if (type != context.errorType) { var symbol = type.hasInstanceMembers() ? type.findMember("[]", scope_1.ScopeHint.NORMAL) : null; if (symbol == null) { if (target.resolvedType.pointerTo !== undefined) { // convert index to pinter index node.kind = node_1.NodeKind.POINTER_INDEX; node.resolvedType = target.resolvedType.pointerTo.symbol.resolvedType; } else { context.log.error(node.internalRange, "Cannot index into type '" + target.resolvedType.toString() + "'"); } } else { assert_1.assert(symbol.kind == symbol_1.SymbolKind.FUNCTION_INSTANCE || symbol.kind == symbol_1.SymbolKind.FUNCTION_GLOBAL && symbol.shouldConvertInstanceToGlobal()); // Convert to a regular function call and resolve that instead node.kind = node_1.NodeKind.CALL; target.remove(); node.insertChildBefore(node.firstChild, node_1.createMemberReference(target, symbol)); node.resolvedType = null; resolveAsExpression(context, node, parentScope); } } } else if (kind == node_1.NodeKind.ALIGN_OF) { var type = node.alignOfType(); resolveAsType(context, type, parentScope); node.resolvedType = context.int32Type; if (type.resolvedType != context.errorType) { node.becomeIntegerConstant(type.resolvedType.allocationAlignmentOf(context)); } } else if (kind == node_1.NodeKind.SIZE_OF) { var type = node.sizeOfType(); resolveAsType(context, type, parentScope); node.resolvedType = context.int32Type; if (type.resolvedType != context.errorType) { node.becomeIntegerConstant(type.resolvedType.allocationSizeOf(context)); } } else if (kind == node_1.NodeKind.THIS) { var symbol = parentScope.findNested("this", scope_1.ScopeHint.NORMAL, scope_1.FindNested.NORMAL); if (symbol == null) { context.log.error(node.range, "Cannot use 'this' here"); } else { node.becomeSymbolReference(symbol); } } else if (kind == node_1.NodeKind.PARSE_ERROR) { node.resolvedType = context.errorType; } else if (kind == node_1.NodeKind.NAME) { var name = node.stringValue; var symbol = parentScope.findNested(name, scope_1.ScopeHint.NORMAL, scope_1.FindNested.NORMAL); if (symbol == null) { var errorMessage = "No symbol named '" + name + "' here"; // In JavaScript, "this." before instance symbols is required symbol = parentScope.findNested(name, scope_1.ScopeHint.NORMAL, scope_1.FindNested.ALLOW_INSTANCE_ERRORS); if (symbol != null) { errorMessage += ", did you mean 'this." + symbol.name + "'?"; } else if (name == "number") { // TODO: convert to float64 automatically errorMessage += ", you cannot use generic number type from TypeScript!"; } else if (name == "bool") { errorMessage += ", did you mean 'boolean'?"; } context.log.error(node.range, errorMessage); } else if (symbol.state == symbol_1.SymbolState.INITIALIZING) { context.log.error(node.range, "Cyclic reference to symbol '" + name + "' here"); } else if (isSymbolAccessAllowed(context, symbol, node, node.range)) { initializeSymbol(context, symbol); node.symbol = symbol; node.resolvedType = symbol.resolvedType; if (node.resolvedType.isGeneric()) { node.flags |= node_1.NODE_FLAG_GENERIC; } // Inline constants if (symbol.kind == symbol_1.SymbolKind.VARIABLE_CONSTANT) { if (symbol.resolvedType == context.booleanType) { node.becomeBooleanConstant(symbol.offset != 0); } else if (symbol.resolvedType == context.float32Type) { node.becomeFloatConstant(symbol.offset); } else if (symbol.resolvedType == context.float64Type) { node.becomeDoubleConstant(symbol.offset); } else if (symbol.resolvedType == context.int64Type) { node.becomeLongConstant(symbol.offset); } else { node.becomeIntegerConstant(symbol.offset); } } } } else if (kind == node_1.NodeKind.CAST) { var value = node.castValue(); var type = node.castType(); resolveAsExpression(context, value, parentScope); resolveAsType(context, type, parentScope); var castedType = type.resolvedType; checkConversion(context, value, castedType, type_1.ConversionKind.EXPLICIT); node.resolvedType = castedType; // Automatically fold constants if (value.kind == node_1.NodeKind.INT32 && castedType.isInteger()) { var result = value.intValue; var shift = 32 - castedType.integerBitCount(context); node.becomeIntegerConstant(castedType.isUnsigned() ? castedType.integerBitMask(context) & result : result << shift >> shift); } else if (value.kind == node_1.NodeKind.INT32 && castedType.isFloat()) { node.becomeFloatConstant(value.intValue); } else if (value.kind == node_1.NodeKind.INT32 && castedType.isDouble()) { node.becomeDoubleConstant(value.intValue); } else if (value.kind == node_1.NodeKind.FLOAT32 && castedType.isInteger()) { node.becomeIntegerConstant(Math.round(value.floatValue)); } } else if (kind == node_1.NodeKind.DOT) { var target = node.dotTarget(); resolve(context, target, parentScope); if (target.resolvedType != context.errorType) { if (target.isType() && (target.resolvedType.isEnum() || target.resolvedType.hasInstanceMembers()) || !target.isType() && target.resolvedType.hasInstanceMembers()) { var name = node.stringValue; // Empty names are left over from parse errors that have already been reported if (name.length > 0) { var symbol = target.resolvedType.findMember(name, node.isAssignTarget() ? scope_1.ScopeHint.PREFER_SETTER : scope_1.ScopeHint.PREFER_GETTER); if (symbol == null) { context.log.error(node.internalRange, "No member named '" + name + "' on type '" + target.resolvedType.toString() + "'"); } else if (symbol.isGetter()) { if (node.parent.stringValue === node.stringValue && node.parent.kind === node_1.NodeKind.CALL) { node.parent.resolvedType = null; node.symbol = symbol; node.resolvedType = symbol.resolvedType; resolveAsExpression(context, node.parent, parentScope); } else { node.kind = node_1.NodeKind.CALL; node.appendChild(node_1.createMemberReference(target.remove(), symbol)); node.resolvedType = null; resolveAsExpression(context, node, parentScope); } return; } else if (isSymbolAccessAllowed(context, symbol, node, node.internalRange)) { initializeSymbol(context, symbol); node.symbol = symbol; node.resolvedType = symbol.resolvedType; // Inline constants if (symbol.kind == symbol_1.SymbolKind.VARIABLE_CONSTANT) { node.becomeIntegerConstant(symbol.offset); } } } } else { context.log.error(node.internalRange, "The type '" + target.resolvedType.toString() + "' has no members"); } } } else if (kind == node_1.NodeKind.CALL) { var value = node.callValue(); resolveAsExpression(context, value, parentScope); if (value.resolvedType != context.errorType) { var symbol = value.symbol; // Only functions are callable if (symbol == null || !symbol_1.isFunction(symbol.kind)) { context.log.error(value.range, "Cannot call value of type '" + value.resolvedType.toString() + "'"); } else { initializeSymbol(context, symbol); if (symbol.shouldConvertInstanceToGlobal()) { var name = node_1.createSymbolReference(symbol); node.insertChildBefore(value, name.withRange(value.internalRange)); node.insertChildBefore(value, value.dotTarget().remove()); value.remove(); value = name; } if (symbol.name === "malloc") { compiler_1.Compiler.mallocRequired = true; } var returnType = symbol.node.functionReturnType(); var argumentVariable = symbol.node.functionFirstArgumentIgnoringThis(); var argumentValue = value.nextSibling; // Match argument values with variables while (argumentVariable != returnType && argumentValue != null) { resolveAsExpression(context, argumentValue, parentScope); checkConversion(context, argumentValue, argumentVariable.symbol.resolvedType, type_1.ConversionKind.IMPLICIT); argumentVariable = argumentVariable.nextSibling; argumentValue = argumentValue.nextSibling; } // Not enough argumentVariables? if (returnType.resolvedType != context.anyType) { if (argumentVariable != returnType && !argumentVariable.hasVariableValue()) { context.log.error(node.internalRange, "Not enough arguments for function '" + symbol.name + "'"); } else if (argumentValue != null) { while (argumentValue != null) { resolveAsExpression(context, argumentValue, parentScope); argumentValue = argumentValue.nextSibling; } context.log.error(node.internalRange, "Too many arguments for function '" + symbol.name + "'"); } } if (returnType.resolvedType.isArray()) { terminal_1.Terminal.write(returnType); } // Pass the return type along node.resolvedType = returnType.resolvedType; } } } else if (kind == node_1.NodeKind.DELETE) { var value = node.deleteType(); if (value != null) { resolveAsExpression(context, value, parentScope); if (value.resolvedType == null || value.resolvedType == context.voidType) { context.log.error(value.range, "Unexpected delete value 'void'"); } } else { context.log.error(node.range, "Expected delete value '" + context.currentReturnType.toString() + "'"); } } else if (kind == node_1.NodeKind.RETURN) { var value = node.returnValue(); if (value != null) { resolveAsExpression(context, value, parentScope); if (context.currentReturnType != null) { if (context.currentReturnType != context.voidType) { if (value.resolvedType.isTemplate() && value.hasParameters() && node.parent != value.resolvedType.symbol.node) { deriveConcreteClass(context, value, [value.firstChild.firstChild], value.resolvedType.symbol.scope); } checkConversion(context, value, context.currentReturnType, type_1.ConversionKind.IMPLICIT); } else { context.log.error(value.range, "Unexpected return value in function returning 'void'"); } } node.parent.returnNode = node; } else if (context.currentReturnType != null && context.currentReturnType != context.voidType) { context.log.error(node.range, "Expected return value in function returning '" + context.currentReturnType.toString() + "'"); } } else if (kind == node_1.NodeKind.EMPTY) { } else if (kind == node_1.NodeKind.PARAMETERS) { // resolveAsType(context, node.genericType(), parentScope); // resolveAsExpression(context, node.expressionValue(), parentScope); // context.log.error(node.range, "Generics are not implemented yet"); } else if (kind == node_1.NodeKind.EXTENDS) { resolveAsType(context, node.extendsType(), parentScope); //context.log.error(node.range, "Subclassing is not implemented yet"); } else if (kind == node_1.NodeKind.IMPLEMENTS) { var child = node.firstChild; while (child != null) { resolveAsType(context, child, parentScope); child = child.nextSibling; } context.log.error(node.range, "Interfaces are not implemented yet"); } else if (kind == node_1.NodeKind.EXPRESSIONS) { var child = node.firstChild; while (child) { resolveAsExpression(context, child.expressionValue(), parentScope); child = child.nextSibling; } } else if (kind == node_1.NodeKind.EXPRESSION) { resolveAsExpression(context, node.expressionValue(), parentScope); } else if (kind == node_1.NodeKind.WHILE) { var value = node.whileValue(); var body = node.whileBody(); resolveAsExpression(context, value, parentScope); checkConversion(context, value, context.booleanType, type_1.ConversionKind.IMPLICIT); resolve(context, body, parentScope); } else if (kind == node_1.NodeKind.FOR) { var initializationStmt = node.forInitializationStatement(); var terminationStmt = node.forTerminationStatement(); var updateStmts = node.forUpdateStatements(); var body = node.forBody(); resolve(context, initializationStmt, parentScope); resolveAsExpression(context, terminationStmt, parentScope); resolve(context, updateStmts, parentScope); checkConversion(context, terminationStmt, context.booleanType, type_1.ConversionKind.IMPLICIT); resolve(context, body, parentScope); } else if (kind == node_1.NodeKind.IF) { var value = node.ifValue(); var yes = node.ifTrue(); var no = node.ifFalse(); resolveAsExpression(context, value, parentScope); checkConversion(context, value, context.booleanType, type_1.ConversionKind.IMPLICIT); resolve(context, yes, parentScope); if (no != null) { resolve(context, no, parentScope); } } else if (kind == node_1.NodeKind.HOOK) { var value = node.hookValue(); var yes = node.hookTrue(); var no = node.hookFalse(); resolveAsExpression(context, value, parentScope); checkConversion(context, value, context.booleanType, type_1.ConversionKind.IMPLICIT); resolve(context, yes, parentScope); resolve(context, no, parentScope); checkConversion(context, yes, no.resolvedType, type_1.ConversionKind.IMPLICIT); var commonType = (yes.resolvedType == context.nullType ? no : yes).resolvedType; if (yes.resolvedType != commonType && (yes.resolvedType != context.nullType || !commonType.isReference()) && no.resolvedType != commonType && (no.resolvedType != context.nullType || !commonType.isReference())) { context.log.error(log_1.spanRanges(yes.range, no.range), "Type '" + yes.resolvedType.toString() + "' is not the same as type '" + no.resolvedType.toString() + "'"); } node.resolvedType = commonType; } else if (kind == node_1.NodeKind.ASSIGN) { var left = node.binaryLeft(); var right = node.binaryRight(); if (left.kind == node_1.NodeKind.INDEX) { resolveChildrenAsExpressions(context, left, parentScope); var target = left.indexTarget(); var type = target.resolvedType; if (type != context.errorType) { var symbol = type.hasInstanceMembers() ? type.findMember("[]=", scope_1.ScopeHint.NORMAL) : null; if (symbol == null) { if (target.resolvedType.pointerTo != undefined) { left.kind = node_1.NodeKind.POINTER_INDEX; left.resolvedType = target.resolvedType.pointerTo.symbol.resolvedType; } else { context.log.error(left.internalRange, "Cannot index into type '" + target.resolvedType.toString() + "'"); } } else { assert_1.assert(symbol.kind == symbol_1.SymbolKind.FUNCTION_INSTANCE); // Convert to a regular function call and resolve that instead node.kind = node_1.NodeKind.CALL; target.remove(); left.remove(); while (left.lastChild != null) { node.insertChildBefore(node.firstChild, left.lastChild.remove()); } node.insertChildBefore(node.firstChild, node_1.createMemberReference(target, symbol)); node.internalRange = log_1.spanRanges(left.internalRange, right.range); node.resolvedType = null; resolveAsExpression(context, node, parentScope); return; } } } if (!left.resolvedType) { resolveAsExpression(context, left, parentScope); } // Automatically call setters if (left.symbol != null && left.symbol.isSetter()) { node.kind = node_1.NodeKind.CALL; node.internalRange = left.internalRange; node.resolvedType = null; resolveAsExpression(context, node, parentScope); return; } resolveAsExpression(context, right, parentScope); checkConversion(context, right, left.resolvedType, type_1.ConversionKind.IMPLICIT); checkStorage(context, left); node.resolvedType = left.resolvedType; } else if (kind == node_1.NodeKind.NEW) { compiler_1.Compiler.mallocRequired = true; var type = node.newType(); resolveAsType(context, type, parentScope); if (type.resolvedType.isTemplate() && type.hasParameters() && node.parent != type.resolvedType.symbol.node) { deriveConcreteClass(context, type, [type.firstChild.firstChild], type.resolvedType.symbol.scope); } if (type.resolvedType != context.errorType) { if (!type.resolvedType.isClass()) { context.log.error(type.range, "Cannot construct type '" + type.resolvedType.toString() + "'"); } else { node.resolvedType = type.resolvedType; } } //Constructors argumentVariables var child = type.nextSibling; var constructorNode = node.constructorNode(); if (constructorNode !== undefined) { var argumentVariable = constructorNode.functionFirstArgument(); while (child != null) { resolveAsExpression(context, child, parentScope); checkConversion(context, child, argumentVariable.symbol.resolvedType, type_1.ConversionKind.IMPLICIT); child = child.nextSibling; argumentVariable = argumentVariable.nextSibling; } } // Match argument values with variables // while (argumentVariable != returnType && argumentValue != null) { // resolveAsExpression(context, argumentValue, parentScope); // checkConversion(context, argumentValue, argumentVariable.symbol.resolvedType, ConversionKind.IMPLICIT); // argumentVariable = argumentVariable.nextSibling; // argumentValue = argumentValue.nextSibling; // } } else if (kind == node_1.NodeKind.POINTER_TYPE) { var value = node.unaryValue(); resolveAsType(context, value, parentScope); if (context.target == compile_target_1.CompileTarget.JAVASCRIPT) { context.log.error(node.internalRange, "Cannot use pointers when compiling to JavaScript"); } else { var type = value.resolvedType; if (type != context.errorType) { node.resolvedType = type.pointerType(); } } } else if (kind == node_1.NodeKind.POINTER_INDEX) { debugger; } else if (kind == node_1.NodeKind.DEREFERENCE) { var value = node.unaryValue(); resolveAsExpression(context, value, parentScope); var type = value.resolvedType; if (type != context.errorType) { if (type.pointerTo == null) { context.log.error(node.internalRange, "Cannot dereference type '" + type.toString() + "'"); } else { node.resolvedType = type.pointerTo; } } } else if (kind == node_1.NodeKind.ADDRESS_OF) { var value = node.unaryValue(); resolveAsExpression(context, value, parentScope); context.log.error(node.internalRange, "The address-of operator is not supported"); } else if (node_1.isUnary(kind)) { var value = node.unaryValue(); resolveAsExpression(context, value, parentScope); // Operator "!" is hard-coded if (kind == node_1.NodeKind.NOT) { checkConversion(context, value, context.booleanType, type_1.ConversionKind.IMPLICIT); node.resolvedType = context.booleanType; } else if (value.resolvedType.isLong()) { if (value.resolvedType.isUnsigned()) { node.flags = node.flags | node_1.NODE_FLAG_UNSIGNED_OPERATOR; node.resolvedType = context.uint64Type; } else { node.resolvedType = context.int64Type; } // Automatically fold constants if (value.kind == node_1.NodeKind.INT64) { var input = value.longValue; var output = input; if (kind == node_1.NodeKind.COMPLEMENT) output = ~input; else if (kind == node_1.NodeKind.NEGATIVE) output = -input; node.becomeLongConstant(output); } } else if (value.resolvedType.isInteger()) { if (value.resolvedType.isUnsigned()) { node.flags = node.flags | node_1.NODE_FLAG_UNSIGNED_OPERATOR; node.resolvedType = context.uint32Type; } else { node.resolvedType = context.int32Type; } // Automatically fold constants if (value.kind == node_1.NodeKind.INT32) { var input = value.intValue; var output = input; if (kind == node_1.NodeKind.COMPLEMENT) output = ~input; else if (kind == node_1.NodeKind.NEGATIVE) output = -input; node.becomeIntegerConstant(output); } } else if (value.resolvedType.isDouble()) { node.resolvedType = context.float64Type; // Automatically fold constants if (value.kind == node_1.NodeKind.FLOAT64) { var input = value.doubleValue; var output = input; if (kind == node_1.NodeKind.COMPLEMENT) output = ~input; else if (kind == node_1.NodeKind.NEGATIVE) output = -input; node.becomeDoubleConstant(output); } } else if (value.resolvedType.isFloat()) { node.resolvedType = context.float32Type; // Automatically fold constants if (value.kind == node_1.NodeKind.FLOAT32) { var input = value.floatValue; var output = input; if (kind == node_1.NodeKind.COMPLEMENT) output = ~input; else if (kind == node_1.NodeKind.NEGATIVE) output = -input; node.becomeFloatConstant(output); } } else if (value.resolvedType != context.errorType) { var name = node.internalRange.toString(); var symbol = value.resolvedType.findMember(name, scope_1.ScopeHint.NOT_BINARY); // Automatically call the function if (symbol != null) { node.appendChild(node_1.createMemberReference(value.remove(), symbol).withRange(node.range).withInternalRange(node.internalRange)); node.kind = node_1.NodeKind.CALL; node.resolvedType = null; resolveAsExpression(context, node, parentScope); } else { context.log.error(node.internalRange, "Cannot use unary operator '" + name + "' with type '" + value.resolvedType.toString() + "'"); } } } else if (node_1.isBinary(kind)) { var left = node.binaryLeft(); var right = node.binaryRight(); resolveAsExpression(context, left, parentScope); resolveAsExpression(context, right, parentScope); var leftType = left.resolvedType; if ((leftType.isDouble() && right.resolvedType.isFloat()) || (leftType.isLong() && right.resolvedType.isInteger())) { right.becomeTypeOf(left, context); } var rightType = right.resolvedType; // Operators "&&" and "||" are hard-coded if (kind == node_1.NodeKind.LOGICAL_OR || kind == node_1.NodeKind.LOGICAL_AND) { checkConversion(context, left, context.booleanType, type_1.ConversionKind.IMPLICIT); checkConversion(context, right, context.booleanType, type_1.ConversionKind.IMPLICIT); node.resolvedType = context.booleanType; } else if (kind == node_1.NodeKind.ADD && leftType.pointerTo != null && rightType.isInteger()) { node.resolvedType = leftType; } else if ((kind == node_1.NodeKind.LESS_THAN || kind == node_1.NodeKind.LESS_THAN_EQUAL || kind == node_1.NodeKind.GREATER_THAN || kind == node_1.NodeKind.GREATER_THAN_EQUAL) && (leftType.pointerTo != null || rightType.pointerTo != null)) { node.resolvedType = context.booleanType; // Both pointer types must be exactly the same if (leftType != rightType) { context.log.error(node.internalRange, "Cannot compare type '" + leftType.toString() + "' with type '" + rightType.toString() + "'"); } } else if ((leftType.isInteger() || leftType.isLong() || leftType.isFloat() || leftType.isDouble() || (leftType.isGeneric() && rightType.isGeneric())) && kind != node_1.NodeKind.EQUAL && kind != node_1.NodeKind.NOT_EQUAL) { var isFloat = false; var isFloat64 = false; if (leftType.isFloat() || leftType.isDouble()) { isFloat = true; isFloat64 = leftType.isDouble(); } var isUnsigned = binaryHasUnsignedArguments(node); // Arithmetic operators if (kind == node_1.NodeKind.ADD || kind == node_1.NodeKind.SUBTRACT || kind == node_1.NodeKind.MULTIPLY || kind == node_1.NodeKind.DIVIDE || kind == node_1.NodeKind.REMAINDER || kind == node_1.NodeKind.BITWISE_AND || kind == node_1.NodeKind.BITWISE_OR || kind == node_1.NodeKind.BITWISE_XOR || kind == node_1.NodeKind.SHIFT_LEFT || kind == node_1.NodeKind.SHIFT_RIGHT) { var isLong = isBinaryLong(node); var commonType = void 0; if (isFloat) { commonType = isBinaryDouble(node) ? context.float64Type : context.float32Type; } else { commonType = isUnsigned ? (isLong ? context.uint64Type : context.uint32Type) : (isLong ? context.int64Type : context.int32Type); } if (isUnsigned) { node.flags = node.flags | node_1.NODE_FLAG_UNSIGNED_OPERATOR; } checkConversion(context, left, commonType, type_1.ConversionKind.IMPLICIT); checkConversion(context, right, commonType, type_1.ConversionKind.IMPLICIT); node.resolvedType = commonType; // Signature conversion if (commonType == context.int64Type) { if (left.kind == node_1.NodeKind.INT32) { left.kind = node_1.NodeKind.INT64; left.resolvedType = context.int64Type; } else if (right.kind == node_1.NodeKind.INT32) { right.kind = node_1.NodeKind.INT64; right.resolvedType = context.int64Type; } } // Automatically fold constants if ((left.kind == node_1.NodeKind.INT32 || left.kind == node_1.NodeKind.INT64) && (right.kind == node_1.NodeKind.INT32 || right.kind == node_1.NodeKind.INT64)) { var inputLeft = left.intValue; var inputRight = right.intValue; var output = 0; if (kind == node_1.NodeKind.ADD) output = inputLeft + inputRight; else if (kind == node_1.NodeKind.BITWISE_AND) output = inputLeft & inputRight; else if (kind == node_1.NodeKind.BITWISE_OR) output = inputLeft | inputRight; else if (kind == node_1.NodeKind.BITWISE_XOR) output = inputLeft ^ inputRight; else if (kind == node_1.NodeKind.DIVIDE) output = inputLeft / inputRight; else if (kind == node_1.NodeKind.MULTIPLY) output = inputLeft * inputRight; else if (kind == node_1.NodeKind.REMAINDER) output = inputLeft % inputRight; else if (kind == node_1.NodeKind.SHIFT_LEFT) output = inputLeft << inputRight; else if (kind == node_1.NodeKind.SHIFT_RIGHT) output = isUnsigned ? ((inputLeft) >> (inputRight)) : inputLeft >> inputRight; else if (kind == node_1.NodeKind.SUBTRACT) output = inputLeft - inputRight; else return; if (left.kind == node_1.NodeKind.INT32) { node.becomeIntegerConstant(output); } else { node.becomeLongConstant(output); } } else if ((left.kind == node_1.NodeKind.FLOAT32 || left.kind == node_1.NodeKind.FLOAT64) && (right.kind == node_1.NodeKind.FLOAT32 || right.kind == node_1.NodeKind.FLOAT64)) { var inputLeft = left.floatValue; var inputRight = right.floatValue; var output = 0; if (kind == node_1.NodeKind.ADD) output = inputLeft + inputRight; else if (kind == node_1.NodeKind.BITWISE_AND) output = inputLeft & inputRight; else if (kind == node_1.NodeKind.BITWISE_OR) output = inputLeft | inputRight; else if (kind == node_1.NodeKind.BITWISE_XOR) output = inputLeft ^ inputRight; else if (kind == node_1.NodeKind.DIVIDE) output = inputLeft / inputRight; else if (kind == node_1.NodeKind.MULTIPLY) output = inputLeft * inputRight; else if (kind == node_1.NodeKind.REMAINDER) output = inputLeft % inputRight; else if (kind == node_1.NodeKind.SHIFT_LEFT) output = inputLeft << inputRight; else if (kind == node_1.NodeKind.SHIFT_RIGHT) output = inputLeft >> inputRight; else if (kind == node_1.NodeKind.SUBTRACT) output = inputLeft - inputRight; else return; if (left.kind == node_1.NodeKind.FLOAT32) { node.becomeFloatConstant(output); } else { node.becomeDoubleConstant(output); } } else { simplifyBinary(node); } } else if (kind == node_1.NodeKind.LESS_THAN || kind == node_1.NodeKind.LESS_THAN_EQUAL || kind == node_1.NodeKind.GREATER_THAN || kind == node_1.NodeKind.GREATER_THAN_EQUAL) { var expectedType = isFloat ? (isFloat64 ? context.float64Type : context.float32Type) : (isUnsigned ? context.uint32Type : context.int32Type); if (isUnsigned) { node.flags = node.flags | node_1.NODE_FLAG_UNSIGNED_OPERATOR; } if (leftType != rightType) { checkConversion(context, left, expectedType, type_1.ConversionKind.IMPLICIT); checkConversion(context, right, expectedType, type_1.ConversionKind.IMPLICIT); } node.resolvedType = context.booleanType; } else { context.log.error(node.internalRange, "This operator is not currently supported"); } } else if (leftType != context.errorType) { var name = node.internalRange.toString(); var symbol = leftType.findMember(kind == node_1.NodeKind.NOT_EQUAL ? "==" : kind == node_1.NodeKind.LESS_THAN_EQUAL ? ">" : kind == node_1.NodeKind.GREATER_THAN_EQUAL ? "<" : name, scope_1.ScopeHint.NOT_UNARY); // Automatically call the function if (symbol != null) { left = node_1.createMemberReference(left.remove(), symbol).withRange(node.range).withInternalRange(node.internalRange); right.remove(); if (kind == node_1.NodeKind.NOT_EQUAL || kind == node_1.NodeKind.LESS_THAN_EQUAL || kind == node_1.NodeKind.GREATER_THAN_EQUAL) { var call = node_1.createCall(left); call.appendChild(right); node.kind = node_1.NodeKind.NOT; node.appendChild(call.withRange(node.range).withInternalRange(node.range)); } else { node.appendChild(left); node.appendChild(right); node.kind = node_1.NodeKind.CALL; } node.resolvedType = null; resolveAsExpression(context, node, parentScope); } else if (kind == node_1.NodeKind.EQUAL || kind == node_1.NodeKind.NOT_EQUAL) { node.resolvedType = context.booleanType; if (leftType != context.errorType && rightType != context.errorType && leftType != rightType && !canConvert(context, right, leftType, type_1.ConversionKind.IMPLICIT) && !canConvert(context, left, rightType, type_1.ConversionKind.IMPLICIT)) { context.log.error(node.internalRange, "Cannot compare type '" + leftType.toString() + "' with type '" + rightType.toString() + "'"); } } else { context.log.error(node.internalRange, "Cannot use binary operator '" + name + "' with type '" + leftType.toString() + "'"); } } } else if (kind == node_1.NodeKind.TYPE) { //ignore types } else { terminal_1.Terminal.error("Unexpected kind: " + node_1.NodeKind[kind]); assert_1.assert(false); } }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
resolve
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function TouchScroll(/*HTMLElement*/scrollElement, /*Object*/options){ options = options || {}; this.elastic = !!options.elastic, this.snapToGrid = !!options.snapToGrid; this.containerSize = null; this.maxSegments = {e: 1, f: 1}; this.currentSegment = {e: 0, f: 0}; // references to scroll div elements this.scrollers = { container: scrollElement, outer: /*HTMLElement*/null, inner: /*HTMLElement*/null, e: /*HTMLElement*/null, f: /*HTMLElement*/null }; // Whether the scroller scrolls this._scrolls = {e: false, f: false}; // The minimal scroll values (fully scrolled to the bottom/right) // Object with attributes "e" and "f" this._scrollMin = {e: false, f: false}; // References DOM nodes for scrollbar tracks and handles. // Gets set up by "_initDom" // { // container: HTMLElement, // handles:{e: HTMLElement, f: HTMLElement}, // maxOffsets: {e: Number, f: Number}, -> maximum offsets for the handles // offsetRatios: {e: Number, f: Number}, -> Ratio of scroller offset to handle offset // sizes: {e: Number, f: Number}, -> handle sizes // tracks: {e: HTMLElement, f: HTMLElement}, // } this._scrollbars = null, /* ---- SCROLLER STATE ---- */ this._isScrolling = false; this._startEvent = null; // the current scroller offset this._currentOffset = new WebKitCSSMatrix(); // Events tracked during a move action // [ {timeStamp: Number, matrix: WebKitCSSMatrix} ] // The last two events get tracked. this._trackedEvents = /*Array*/null; // Keeps track whether flicking is active this._flicking = {e: false, f: false}; // Queued bounces this._bounces = {e: null, f: null}; // Animation timeouts // This implementation uses timeouts for combined animations, // because the webkitTransitionEnd event fires late on iPhone 3G this._animationTimeouts = {e: [], f: []}; this._initDom(); this.setupScroller(); }
Constructor for scrollers. @constructor @param {HTMLElement} scrollElement The node to make scrollable @param {Object} [options] Options for the scroller- Known options are elastic {Boolean} whether the scroller bounces
TouchScroll
javascript
davidaurelio/TouchScroll
src/touchscroll.js
https://github.com/davidaurelio/TouchScroll/blob/master/src/touchscroll.js
BSD-2-Clause
async viteFinal(config) { // Merge custom configuration into the default config return mergeConfig(config, { assetsInclude: ['**/*.glb', '**/*.hdr', '**/*.glsl'], build: { assetsInlineLimit: 1024, }, }); }
@type { import('@storybook/react-vite').StorybookConfig }
viteFinal
javascript
HamishMW/portfolio
.storybook/main.js
https://github.com/HamishMW/portfolio/blob/master/.storybook/main.js
MIT
async function loadImageFromSrcSet({ src, srcSet, sizes }) { return new Promise((resolve, reject) => { try { if (!src && !srcSet) { throw new Error('No image src or srcSet provided'); } let tempImage = new Image(); if (src) { tempImage.src = src; } if (srcSet) { tempImage.srcset = srcSet; } if (sizes) { tempImage.sizes = sizes; } const onLoad = () => { tempImage.removeEventListener('load', onLoad); const source = tempImage.currentSrc; tempImage = null; resolve(source); }; tempImage.addEventListener('load', onLoad); } catch (error) { reject(`Error loading ${srcSet}: ${error}`); } }); }
Use the browser's image loading to load an image and grab the `src` it chooses from a `srcSet`
loadImageFromSrcSet
javascript
HamishMW/portfolio
app/utils/image.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/image.js
MIT
onLoad = () => { tempImage.removeEventListener('load', onLoad); const source = tempImage.currentSrc; tempImage = null; resolve(source); }
Use the browser's image loading to load an image and grab the `src` it chooses from a `srcSet`
onLoad
javascript
HamishMW/portfolio
app/utils/image.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/image.js
MIT
onLoad = () => { tempImage.removeEventListener('load', onLoad); const source = tempImage.currentSrc; tempImage = null; resolve(source); }
Use the browser's image loading to load an image and grab the `src` it chooses from a `srcSet`
onLoad
javascript
HamishMW/portfolio
app/utils/image.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/image.js
MIT
async function generateImage(width = 1, height = 1) { return new Promise(resolve => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); canvas.width = width; canvas.height = height; ctx.fillStyle = 'rgba(0, 0, 0, 0)'; ctx.fillRect(0, 0, width, height); canvas.toBlob(async blob => { if (!blob) throw new Error('Video thumbnail failed to load'); const image = URL.createObjectURL(blob); canvas.remove(); resolve(image); }); }); }
Generates a transparent png of a given width and height
generateImage
javascript
HamishMW/portfolio
app/utils/image.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/image.js
MIT
async function resolveSrcFromSrcSet({ srcSet, sizes }) { const sources = await Promise.all( srcSet.split(', ').map(async srcString => { const [src, width] = srcString.split(' '); const size = Number(width.replace('w', '')); const image = await generateImage(size); return { src, image, width }; }) ); const fakeSrcSet = sources.map(({ image, width }) => `${image} ${width}`).join(', '); const fakeSrc = await loadImageFromSrcSet({ srcSet: fakeSrcSet, sizes }); const output = sources.find(src => src.image === fakeSrc); return output.src; }
Use native html image `srcSet` resolution for non-html images
resolveSrcFromSrcSet
javascript
HamishMW/portfolio
app/utils/image.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/image.js
MIT
rgbToThreeColor = rgb => rgb?.split(' ').map(value => Number(value) / 255) || []
Convert an rgb theme property (e.g. rgbBlack: '0 0 0') to values that can be spread into a ThreeJS Color class
rgbToThreeColor
javascript
HamishMW/portfolio
app/utils/style.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/style.js
MIT
rgbToThreeColor = rgb => rgb?.split(' ').map(value => Number(value) / 255) || []
Convert an rgb theme property (e.g. rgbBlack: '0 0 0') to values that can be spread into a ThreeJS Color class
rgbToThreeColor
javascript
HamishMW/portfolio
app/utils/style.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/style.js
MIT
function cssProps(props, style = {}) { let result = {}; const keys = Object.keys(props); for (const key of keys) { let value = props[key]; if (typeof value === 'number' && key === 'delay') { value = numToMs(value); } if (typeof value === 'number' && key !== 'opacity') { value = numToPx(value); } if (typeof value === 'number' && key === 'opacity') { value = `${value * 100}%`; } result[`--${key}`] = value; } return { ...result, ...style }; }
Convert a JS object into `--` prefixed css custom properties. Optionally pass a second param for normal styles
cssProps
javascript
HamishMW/portfolio
app/utils/style.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/style.js
MIT
cleanScene = scene => { scene?.traverse(object => { if (!object.isMesh) return; object.geometry.dispose(); if (object.material.isMaterial) { cleanMaterial(object.material); } else { for (const material of object.material) { cleanMaterial(material); } } }); }
Clean up a scene's materials and geometry
cleanScene
javascript
HamishMW/portfolio
app/utils/three.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/three.js
MIT
cleanScene = scene => { scene?.traverse(object => { if (!object.isMesh) return; object.geometry.dispose(); if (object.material.isMaterial) { cleanMaterial(object.material); } else { for (const material of object.material) { cleanMaterial(material); } } }); }
Clean up a scene's materials and geometry
cleanScene
javascript
HamishMW/portfolio
app/utils/three.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/three.js
MIT
cleanMaterial = material => { material.dispose(); for (const key of Object.keys(material)) { const value = material[key]; if (value && typeof value === 'object' && 'minFilter' in value) { value.dispose(); // Close GLTF bitmap textures value.source?.data?.close?.(); } } }
Clean up and dispose of a material
cleanMaterial
javascript
HamishMW/portfolio
app/utils/three.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/three.js
MIT
cleanMaterial = material => { material.dispose(); for (const key of Object.keys(material)) { const value = material[key]; if (value && typeof value === 'object' && 'minFilter' in value) { value.dispose(); // Close GLTF bitmap textures value.source?.data?.close?.(); } } }
Clean up and dispose of a material
cleanMaterial
javascript
HamishMW/portfolio
app/utils/three.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/three.js
MIT
cleanRenderer = renderer => { renderer.dispose(); renderer = null; }
Clean up and dispose of a renderer
cleanRenderer
javascript
HamishMW/portfolio
app/utils/three.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/three.js
MIT
cleanRenderer = renderer => { renderer.dispose(); renderer = null; }
Clean up and dispose of a renderer
cleanRenderer
javascript
HamishMW/portfolio
app/utils/three.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/three.js
MIT
removeLights = lights => { for (const light of lights) { light.parent.remove(light); } }
Clean up lights by removing them from their parent
removeLights
javascript
HamishMW/portfolio
app/utils/three.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/three.js
MIT
removeLights = lights => { for (const light of lights) { light.parent.remove(light); } }
Clean up lights by removing them from their parent
removeLights
javascript
HamishMW/portfolio
app/utils/three.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/three.js
MIT
function formatTimecode(time) { const hours = time / 1000 / 60 / 60; const h = Math.floor(hours); const m = Math.floor((hours - h) * 60); const s = Math.floor(((hours - h) * 60 - m) * 60); const c = Math.floor(((((hours - h) * 60 - m) * 60 - s) * 1000) / 10); return `${zeroPrefix(h)}:${zeroPrefix(m)}:${zeroPrefix(s)}:${zeroPrefix(c)}`; }
Format a timecode intro a hours:minutes:seconds:centiseconds string
formatTimecode
javascript
HamishMW/portfolio
app/utils/timecode.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/timecode.js
MIT
function zeroPrefix(value) { return value < 10 ? `0${value}` : `${value}`; }
Prefix a number with zero as a string if less than 10
zeroPrefix
javascript
HamishMW/portfolio
app/utils/timecode.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/timecode.js
MIT
function readingTime(text) { const wpm = 225; const words = text.trim().split(/\s+/).length; const time = words / wpm; return time * 1000 * 60; }
Prefix a number with zero as a string if less than 10
readingTime
javascript
HamishMW/portfolio
app/utils/timecode.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/timecode.js
MIT
function parse (input, options = {}) { try { options = Object.assign({}, defaultAcornOptions, options) return parser.parse(input, options); } catch (e) { e.message = [ e.message, ' ' + input.split('\n')[e.loc.line - 1], ' ' + '^'.padStart(e.loc.column + 1) ].join('\n'); throw e; } }
@param {string} input @param {object} options @return {any}
parse
javascript
PepsRyuu/nollup
lib/impl/AcornParser.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/AcornParser.js
MIT
static async loadCJS(filepath, code) { // Once transpiled, we temporarily modify the require function // so that when it loads the config file, it will load the transpiled // version instead, and all of the require calls inside that will still work. let defaultLoader = require.extensions['.js']; require.extensions['.js'] = (module, filename) => { if (filename === filepath) { // @ts-ignore module._compile(code, filename); } else { defaultLoader(module, filename); } }; delete require.cache[filepath]; // Load the config file. If it uses ESM export, it will // be exported with a default key, so get that. Otherwise // if it was written in CJS, use the root instead. let config = require(filepath); config = config.default || config; require.extensions['.js'] = defaultLoader; return config; }
Uses compiler to compile rollup.config.js file. This allows config file to use ESM, but compiles to CJS so that import statements change to require statements. @param {string} filepath @param {string} code @return {Promise<object>}
loadCJS
javascript
PepsRyuu/nollup
lib/impl/ConfigLoader.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/ConfigLoader.js
MIT
static async loadESM(filepath, code) { let uri = `data:text/javascript;charset=utf-8,${encodeURIComponent(code)}`; return (await import(uri)).default; }
Directly imports rollup.config.mjs @param {string} filepath @param {string} code @return {Promise<object>}
loadESM
javascript
PepsRyuu/nollup
lib/impl/ConfigLoader.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/ConfigLoader.js
MIT
function blanker (input, start, end) { return input.substring(start, end).replace(/[^\n\r]/g, ' '); }
Setting imports to empty can cause source maps to break. This is because some imports could span across multiple lines when importing named exports. To bypass this problem, this function will replace all text except line breaks with spaces. This will preserve the lines so source maps function correctly. Source maps are ideally the better way to solve this, but trying to maintain performance. @param {string} input @param {number} start @param {number} end @return {string}
blanker
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
function normalizePathDelimiter (id) { return id.replace(/\\/g, '/'); }
Setting imports to empty can cause source maps to break. This is because some imports could span across multiple lines when importing named exports. To bypass this problem, this function will replace all text except line breaks with spaces. This will preserve the lines so source maps function correctly. Source maps are ideally the better way to solve this, but trying to maintain performance. @param {string} input @param {number} start @param {number} end @return {string}
normalizePathDelimiter
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
function escapeCode (code) { // Turning the code into eval statements, so we need // to escape line breaks and quotes. Using a multiline // approach here so that the compiled code is still // readable for advanced debugging situations. return code .replace(/\\/g, '\\\\') .replace(/'/g, '\\\'') .replace(/(\r)?\n/g, '\\n\\\n'); }
Setting imports to empty can cause source maps to break. This is because some imports could span across multiple lines when importing named exports. To bypass this problem, this function will replace all text except line breaks with spaces. This will preserve the lines so source maps function correctly. Source maps are ideally the better way to solve this, but trying to maintain performance. @param {string} input @param {number} start @param {number} end @return {string}
escapeCode
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
function getVariableNames(node) { if (node.type === 'ObjectPattern') { return node.properties.flatMap(p => { if (p.value.type === 'Identifier') { return p.value.name; } else { return getVariableNames(p.value) } }); } if (node.type === 'ArrayPattern') { return node.elements.filter(Boolean).flatMap(e => { if (e.type === 'Identifier') { return e.name; } else { return getVariableNames(e); } }) } return node.name; }
Setting imports to empty can cause source maps to break. This is because some imports could span across multiple lines when importing named exports. To bypass this problem, this function will replace all text except line breaks with spaces. This will preserve the lines so source maps function correctly. Source maps are ideally the better way to solve this, but trying to maintain performance. @param {string} input @param {number} start @param {number} end @return {string}
getVariableNames
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
function getSyntheticExports (synthetic) { if (synthetic === true) { synthetic = 'default'; } return `if (__m__.exports.${synthetic}) { for (let prop in __m__.exports.${synthetic}) { prop !== '${synthetic}' && !__m__.exports.hasOwnProperty(prop) && __e__(prop, function () { return __m__.exports.${synthetic}[prop] }); } }` }
@param {boolean|string} synthetic @return {string}
getSyntheticExports
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
function createExternalImports (chunk, outputOptions, externalImports) { let output = ''; let { format, globals } = outputOptions; output += externalImports.map(ei => { let name = ei.source.replace(/[\W]/g, '_'); let { source, specifiers } = ei; // Bare external import if (specifiers.length === 0) { if (format === 'es') return `import '${source}';` if (format === 'cjs' || format === 'amd') return `require('${source}');` } let iifeName = format === 'iife'? (globals[source] || getIIFEName(ei)) : ''; return specifiers.map(s => { if (s.imported === '*') { if (format === 'es') return `import * as __nollup__external__${name}__ from '${source}';`; if (format === 'cjs' || format === 'amd') return `var __nollup__external__${name}__ = require('${source}');`; if (format === 'iife') return `var __nollup__external__${name}__ = self.${iifeName};` } if (s.imported === 'default') { if (format === 'es') return `import __nollup__external__${name}__default__ from '${source}';`; if (format === 'cjs' || format === 'amd') return `var __nollup__external__${name}__default__ = require('${source}').hasOwnProperty('default')? require('${source}').default : require('${source}');` if (format === 'iife') return `var __nollup__external__${name}__default__ = self.${iifeName} && self.${iifeName}.hasOwnProperty('default')? self.${iifeName}.default : self.${iifeName};` } if (format === 'es') return `import { ${s.imported} as __nollup__external__${name}__${s.imported}__ } from '${source}';`; if (format === 'cjs' || format === 'amd') return `var __nollup__external__${name}__${s.imported}__ = require('${source}').${s.imported};` if (format === 'iife') return `var __nollup__external__${name}__${s.imported}__ = self.${iifeName}.${s.imported};` }).join('\n'); }).join('\n'); return output; }
@param {RollupRenderedChunk} chunk @param {RollupOutputOptions} outputOptions @param {Array<NollupInternalModuleImport>} externalImports @return {string}
createExternalImports
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
function callNollupModuleWrap (plugins, code) { return plugins.filter(p => { return p.nollupModuleWrap }).reduce((code, p) => { return p.nollupModuleWrap(code) }, code); }
@param {NollupPlugin[]} plugins @param {string} code @return {string}
callNollupModuleWrap
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
onESMEnter (code, filePath, ast) { activeModules[filePath] = { output: new MagicString(code), code: code }; }
@param {string} code @param {string} filePath @param {ESTree} ast
onESMEnter
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT