Input:
A statistic emphasizes the current value of an attribute . [CODESPLIT] function Statistic ( props ) { const { children , className , color , content , floated , horizontal , inverted , label , size , text , value , } = props const classes = cx ( 'ui' , color , size , useValueAndKey ( floated , 'floated' ) , useKeyOnly ( horizontal , 'horizontal' ) , useKeyOnly ( inverted , 'inverted' ) , 'statistic' , className , ) const rest = getUnhandledProps ( Statistic , props ) const ElementType = getElementType ( Statistic , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } >
         { children }
       < / ElementType > ) } if ( ! childrenUtils . isNil ( content ) ) { return ( < ElementType { ... rest } className = { classes } >
         { content }
       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } >
       { StatisticValue . create ( value , { defaultProps : { text } , autoGenerateKey : false , } ) }
       { StatisticLabel . create ( label , { autoGenerateKey : false } ) }
     < / ElementType > ) }


Input: Returns a createElement () type based on the props of the Component . Useful for calculating what type a component should render as . [CODESPLIT] function getElementType ( Component , props , getDefault ) { const { defaultProps = { } } = Component // ---------------------------------------- // user defined "as" element type if ( props . as && props . as !== defaultProps . as ) return props . as // ---------------------------------------- // computed default element type if ( getDefault ) { const computedDefault = getDefault ( ) if ( computedDefault ) return computedDefault } // ---------------------------------------- // infer anchor links if ( props . href ) return 'a' // ---------------------------------------- // use defaultProp or 'div' return defaultProps . as || 'div' }


Input:
A group of segments can be formatted to appear together . [CODESPLIT] function SegmentGroup ( props ) { const { children , className , compact , content , horizontal , piled , raised , size , stacked } = props const classes = cx ( 'ui' , size , useKeyOnly ( compact , 'compact' ) , useKeyOnly ( horizontal , 'horizontal' ) , useKeyOnly ( piled , 'piled' ) , useKeyOnly ( raised , 'raised' ) , useKeyOnly ( stacked , 'stacked' ) , 'segments' , className , ) const rest = getUnhandledProps ( SegmentGroup , props ) const ElementType = getElementType ( SegmentGroup , props ) return ( < ElementType { ... rest } className = { classes } >
       { childrenUtils . isNil ( children ) ? content : children }
     < / ElementType > ) }


Input: A table can have a header cell . [CODESPLIT] function TableHeaderCell ( props ) { const { as , className , sorted } = props const classes = cx ( useValueAndKey ( sorted , 'sorted' ) , className ) const rest = getUnhandledProps ( TableHeaderCell , props ) return < TableCell { ... rest } as = { as } className = { classes } / > }


Input:
A feed presents user activity chronologically . [CODESPLIT] function Feed ( props ) { const { children , className , events , size } = props const classes = cx ( 'ui' , size , 'feed' , className ) const rest = getUnhandledProps ( Feed , props ) const ElementType = getElementType ( Feed , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } >
         { children }
       < / ElementType > ) } const eventElements = _ . map ( events , ( eventProps ) => { const { childKey , date , meta , summary , ... eventData } = eventProps const finalKey = childKey || [ date , meta , summary ] . join ( '-' ) return < FeedEvent date = { date } key = { finalKey } meta = { meta } summary = { summary } { ... eventData } / > } ) return ( < ElementType { ... rest } className = { classes } >
       { eventElements }
     < / ElementType > ) }


Input:
A label can be grouped . [CODESPLIT] function LabelGroup ( props ) { const { children , circular , className , color , content , size , tag } = props const classes = cx ( 'ui' , color , size , useKeyOnly ( circular , 'circular' ) , useKeyOnly ( tag , 'tag' ) , 'labels' , className , ) const rest = getUnhandledProps ( LabelGroup , props ) const ElementType = getElementType ( LabelGroup , props ) return ( < ElementType { ... rest } className = { classes } >
       { childrenUtils . isNil ( children ) ? content : children }
     < / ElementType > ) }


Input:
A feed can contain an extra content . [CODESPLIT] function FeedExtra ( props ) { const { children , className , content , images , text } = props const classes = cx ( useKeyOnly ( images , 'images' ) , useKeyOnly ( content || text , 'text' ) , 'extra' , className , ) const rest = getUnhandledProps ( FeedExtra , props ) const ElementType = getElementType ( FeedExtra , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } >
         { children }
       < / ElementType > ) } // TODO need a "collection factory" to handle creating multiple image elements and their keys const imageElements = _ . map ( images , ( image , index ) => { const key = [ index , image ] . join ( '-' ) return createHTMLImage ( image , { key } ) } ) return ( < ElementType { ... rest } className = { classes } >
       { content }
       { imageElements }
     < / ElementType > ) }


Input: A dropdown menu can contain dividers to separate related content . [CODESPLIT] function DropdownDivider ( props ) { const { className } = props const classes = cx ( 'divider' , className ) const rest = getUnhandledProps ( DropdownDivider , props ) const ElementType = getElementType ( DropdownDivider , props ) return < ElementType { ... rest } className = { classes } / > }


Input:
A feed can contain a summary . [CODESPLIT] function FeedSummary ( props ) { const { children , className , content , date , user } = props const classes = cx ( 'summary' , className ) const rest = getUnhandledProps ( FeedSummary , props ) const ElementType = getElementType ( FeedSummary , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } >
         { children }
       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } >
       { createShorthand ( FeedUser , val => ( { content : val } ) , user , { autoGenerateKey : false } ) }
       { content }
       { createShorthand ( FeedDate , val => ( { content : val } ) , date , { autoGenerateKey : false } ) }
     < / ElementType > ) }


Input:
A step can contain a content . [CODESPLIT] function StepContent ( props ) { const { children , className , content , description , title } = props const classes = cx ( 'content' , className ) const rest = getUnhandledProps ( StepContent , props ) const ElementType = getElementType ( StepContent , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } >
         { children }
       < / ElementType > ) } if ( ! childrenUtils . isNil ( content ) ) { return ( < ElementType { ... rest } className = { classes } >
         { content }
       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } >
       { StepTitle . create ( title , { autoGenerateKey : false } ) }
       { StepDescription . create ( description , { autoGenerateKey : false } ) }
     < / ElementType > ) }


Input: Sugar for <Form . Field control = { Radio } / > . [CODESPLIT] function FormRadio ( props ) { const { control } = props const rest = getUnhandledProps ( FormRadio , props ) const ElementType = getElementType ( FormRadio , props ) return < ElementType { ... rest } control = { control } / > }


Input:
An image is a graphic representation of something . [CODESPLIT] function Image ( props ) { const { avatar , bordered , centered , children , circular , className , content , dimmer , disabled , floated , fluid , hidden , href , inline , label , rounded , size , spaced , verticalAlign , wrapped , ui , } = props const classes = cx ( useKeyOnly ( ui , 'ui' ) , size , useKeyOnly ( avatar , 'avatar' ) , useKeyOnly ( bordered , 'bordered' ) , useKeyOnly ( circular , 'circular' ) , useKeyOnly ( centered , 'centered' ) , useKeyOnly ( disabled , 'disabled' ) , useKeyOnly ( fluid , 'fluid' ) , useKeyOnly ( hidden , 'hidden' ) , useKeyOnly ( inline , 'inline' ) , useKeyOnly ( rounded , 'rounded' ) , useKeyOrValueAndKey ( spaced , 'spaced' ) , useValueAndKey ( floated , 'floated' ) , useVerticalAlignProp ( verticalAlign , 'aligned' ) , 'image' , className , ) const rest = getUnhandledProps ( Image , props ) const [ imgTagProps , rootProps ] = partitionHTMLProps ( rest , { htmlProps : htmlImageProps } ) const ElementType = getElementType ( Image , props , ( ) => { if ( ! _ . isNil ( dimmer ) || ! _ . isNil ( label ) || ! _ . isNil ( wrapped ) || ! childrenUtils . isNil ( children ) ) { return 'div' } } ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } >
         { children }
       < / ElementType > ) } if ( ! childrenUtils . isNil ( content ) ) { return ( < ElementType { ... rest } className = { classes } >
         { content }
       < / ElementType > ) } if ( ElementType === 'img' ) { return < ElementType { ... rootProps } { ... imgTagProps } className = { classes } / > } return ( < ElementType { ... rootProps } className = { classes } href = { href } >
       { Dimmer . create ( dimmer , { autoGenerateKey : false } ) }
       { Label . create ( label , { autoGenerateKey : false } ) }
       < img { ... imgTagProps } / >
     < / ElementType > ) }


Input: Description [CODESPLIT] function ( width , height ) { var canvas = document . createElement ( 'canvas' ) ; canvas . width = width ; canvas . height = height ; canvas . oncontextmenu = function ( ) { return false ; } ; canvas . onselectstart = function ( ) { return false ; } ; return canvas ; }


Input: Gets the pixel ratio of the canvas . [CODESPLIT] function ( canvas ) { var context = canvas . getContext ( '2d' ) , devicePixelRatio = window . devicePixelRatio || 1 , backingStorePixelRatio = context . webkitBackingStorePixelRatio || context . mozBackingStorePixelRatio || context . msBackingStorePixelRatio || context . oBackingStorePixelRatio || context . backingStorePixelRatio || 1 ; return devicePixelRatio / backingStorePixelRatio ; }


Input: Gets the requested texture ( an Image ) via its path [CODESPLIT] function ( render , imagePath ) { var image = render . textures [ imagePath ] ; if ( image ) return image ; image = render . textures [ imagePath ] = new Image ( ) ; image . src = imagePath ; return image ; }


Input: Applies the background to the canvas using CSS . [CODESPLIT] function ( render , background ) { var cssBackground = background ; if ( / (jpg|gif|png)$ / . test ( background ) ) cssBackground = 'url(' + background + ')' ; render . canvas . style . background = cssBackground ; render . canvas . style . backgroundSize = "contain" ; render . currentBackground = background ; }


Input: Creates a body sprite [CODESPLIT] function ( render , body ) { var bodyRender = body . render , texturePath = bodyRender . sprite . texture , texture = _getTexture ( render , texturePath ) , sprite = new PIXI . Sprite ( texture ) ; sprite . anchor . x = body . render . sprite . xOffset ; sprite . anchor . y = body . render . sprite . yOffset ; return sprite ; }


Input: Creates a body primitive [CODESPLIT] function ( render , body ) { var bodyRender = body . render , options = render . options , primitive = new PIXI . Graphics ( ) , fillStyle = Common . colorToNumber ( bodyRender . fillStyle ) , strokeStyle = Common . colorToNumber ( bodyRender . strokeStyle ) , strokeStyleIndicator = Common . colorToNumber ( bodyRender . strokeStyle ) , strokeStyleWireframe = Common . colorToNumber ( '#bbb' ) , strokeStyleWireframeIndicator = Common . colorToNumber ( '#CD5C5C' ) , part ; primitive . clear ( ) ; // handle compound parts for ( var k = body . parts . length > 1 ? 1 : 0 ; k < body . parts . length ; k ++ ) { part = body . parts [ k ] ; if ( ! options . wireframes ) { primitive . beginFill ( fillStyle , 1 ) ; primitive . lineStyle ( bodyRender . lineWidth , strokeStyle , 1 ) ; } else { primitive . beginFill ( 0 , 0 ) ; primitive . lineStyle ( 1 , strokeStyleWireframe , 1 ) ; } primitive . moveTo ( part . vertices [ 0 ] . x - body . position . x , part . vertices [ 0 ] . y - body . position . y ) ; for ( var j = 1 ; j < part . vertices . length ; j ++ ) { primitive . lineTo ( part . vertices [ j ] . x - body . position . x , part . vertices [ j ] . y - body . position . y ) ; } primitive . lineTo ( part . vertices [ 0 ] . x - body . position . x , part . vertices [ 0 ] . y - body . position . y ) ; primitive . endFill ( ) ; // angle indicator if ( options . showAngleIndicator || options . showAxes ) { primitive . beginFill ( 0 , 0 ) ; if ( options . wireframes ) { primitive . lineStyle ( 1 , strokeStyleWireframeIndicator , 1 ) ; } else { primitive . lineStyle ( 1 , strokeStyleIndicator ) ; } primitive . moveTo ( part . position . x - body . position . x , part . position . y - body . position . y ) ; primitive . lineTo ( ( ( part . vertices [ 0 ] . x + part . vertices [ part . vertices . length - 1 ] . x ) / 2 - body . position . x ) , ( ( part . vertices [ 0 ] . y + part . vertices [ part . vertices . length - 1 ] . y ) / 2 - body . position . y ) ) ; primitive . endFill ( ) ; } } return primitive ; }


Input: Gets the requested texture ( a PIXI . Texture ) via its path [CODESPLIT] function ( render , imagePath ) { var texture = render . textures [ imagePath ] ; if ( ! texture ) texture = render . textures [ imagePath ] = PIXI . Texture . fromImage ( imagePath ) ; return texture ; }


Input: Initialises body properties . [CODESPLIT] function ( body , options ) { options = options || { } ; // init required properties (order is important) Body . set ( body , { bounds : body . bounds || Bounds . create ( body . vertices ) , positionPrev : body . positionPrev || Vector . clone ( body . position ) , anglePrev : body . anglePrev || body . angle , vertices : body . vertices , parts : body . parts || [ body ] , isStatic : body . isStatic , isSleeping : body . isSleeping , parent : body . parent || body } ) ; Vertices . rotate ( body . vertices , body . angle , body . position ) ; Axes . rotate ( body . axes , body . angle ) ; Bounds . update ( body . bounds , body . vertices , body . velocity ) ; // allow options to override the automatically calculated properties Body . set ( body , { axes : options . axes || body . axes , area : options . area || body . area , mass : options . mass || body . mass , inertia : options . inertia || body . inertia } ) ; // render properties var defaultFillStyle = ( body . isStatic ? '#2e2b44' : Common . choose ( [ '#006BA6' , '#0496FF' , '#FFBC42' , '#D81159' , '#8F2D56' ] ) ) , defaultStrokeStyle = '#000' ; body . render . fillStyle = body . render . fillStyle || defaultFillStyle ; body . render . strokeStyle = body . render . strokeStyle || defaultStrokeStyle ; body . render . sprite . xOffset += - ( body . bounds . min . x - body . position . x ) / ( body . bounds . max . x - body . bounds . min . x ) ; body . render . sprite . yOffset += - ( body . bounds . min . y - body . position . y ) / ( body . bounds . max . y - body . bounds . min . y ) ; }


Input: Dynamically creates pages in the static website [CODESPLIT] async function createPages ( { actions , graphql } ) { const retrieveMarkdownPages = ( ) => graphql ( ` ` ) const exampleTemplate = path . resolve ( ` ` ) const docTemplate = path . resolve ( ` ` ) const result = await retrieveMarkdownPages ( ) if ( result . errors ) { console . error ( 'graphql error' , result . errors ) throw new Error ( 'Error invoking graphql for pages' ) } result . data . allMarkdownRemark . edges . forEach ( ( { node } ) => { const { frontmatter : { path : pagePath } , } = node const category = ( pagePath || '/' ) . split ( '/' ) . filter ( t => ! ! t ) [ 0 ] const isExample = category === 'examples' console . log ( ` ${ pagePath } ${ category } ` ) actions . createPage ( { path : pagePath , component : isExample ? exampleTemplate : docTemplate , context : { } , // additional data can be passed via context } ) } ) }


Input: https : // html . spec . whatwg . org / multipage / common - microsyntaxes . html#parse - a - month - string [CODESPLIT] function parseMonthString ( str ) { const matches = monthRe . exec ( str ) ; if ( ! matches ) { return null ; } const year = Number ( matches [ 1 ] ) ; if ( year <= 0 ) { return null ; } const month = Number ( matches [ 2 ] ) ; if ( month < 1 || month > 12 ) { return null ; } return { year , month } ; }


Input: https : // html . spec . whatwg . org / multipage / common - microsyntaxes . html#parse - a - date - string [CODESPLIT] function parseDateString ( str ) { const matches = dateRe . exec ( str ) ; if ( ! matches ) { return null ; } const year = Number ( matches [ 1 ] ) ; if ( year <= 0 ) { return null ; } const month = Number ( matches [ 2 ] ) ; if ( month < 1 || month > 12 ) { return null ; } const day = Number ( matches [ 3 ] ) ; if ( day < 1 || day > numberOfDaysInMonthOfYear ( month , year ) ) { return null ; } return { year , month , day } ; }


Input: https : // html . spec . whatwg . org / multipage / common - microsyntaxes . html#parse - a - yearless - date - string [CODESPLIT] function parseYearlessDateString ( str ) { const matches = yearlessDateRe . exec ( str ) ; if ( ! matches ) { return null ; } const month = Number ( matches [ 1 ] ) ; if ( month < 1 || month > 12 ) { return null ; } const day = Number ( matches [ 2 ] ) ; if ( day < 1 || day > numberOfDaysInMonthOfYear ( month , 4 ) ) { return null ; } return { month , day } ; }


Input: https : // html . spec . whatwg . org / multipage / common - microsyntaxes . html#parse - a - time - string [CODESPLIT] function parseTimeString ( str ) { const matches = timeRe . exec ( str ) ; if ( ! matches ) { return null ; } const hour = Number ( matches [ 1 ] ) ; if ( hour < 0 || hour > 23 ) { return null ; } const minute = Number ( matches [ 2 ] ) ; if ( minute < 0 || minute > 59 ) { return null ; } const second = matches [ 3 ] !== undefined ? Math . trunc ( Number ( matches [ 3 ] ) ) : 0 ; if ( second < 0 || second >= 60 ) { return null ; } const millisecond = matches [ 4 ] !== undefined ? Number ( matches [ 4 ] ) : 0 ; return { hour , minute , second , millisecond } ; }


Input: https : // html . spec . whatwg . org / multipage / common - microsyntaxes . html#parse - a - local - date - and - time - string [CODESPLIT] function parseLocalDateAndTimeString ( str , normalized = false ) { let separatorIdx = str . indexOf ( "T" ) ; if ( separatorIdx < 0 && ! normalized ) { separatorIdx = str . indexOf ( " " ) ; } if ( separatorIdx < 0 ) { return null ; } const date = parseDateString ( str . slice ( 0 , separatorIdx ) ) ; if ( date === null ) { return null ; } const time = parseTimeString ( str . slice ( separatorIdx + 1 ) ) ; if ( time === null ) { return null ; } return { date , time } ; }


Input: https : // html . spec . whatwg . org / multipage / common - microsyntaxes . html#week - number - of - the - last - day https : // stackoverflow . com / a / 18538272 / 1937836 [CODESPLIT] function weekNumberOfLastDay ( year ) { const jan1 = new Date ( year , 0 ) ; return jan1 . getDay ( ) === 4 || ( isLeapYear ( year ) && jan1 . getDay ( ) === 3 ) ? 53 : 52 ; }


Input: https : // html . spec . whatwg . org / multipage / common - microsyntaxes . html#parse - a - week - string [CODESPLIT] function parseWeekString ( str ) { const matches = weekRe . exec ( str ) ; if ( ! matches ) { return null ; } const year = Number ( matches [ 1 ] ) ; if ( year <= 0 ) { return null ; } const week = Number ( matches [ 2 ] ) ; if ( week < 1 || week > weekNumberOfLastDay ( year ) ) { return null ; } return { year , week } ; }


Input: We need to wrap the methods that receive an image or canvas object ( luckily always as the first argument ) so that these objects can be unwrapped an the expected types passed . [CODESPLIT] function wrapNodeCanvasMethod ( ctx , name ) { const prev = ctx [ name ] ; ctx [ name ] = function ( image ) { const impl = idlUtils . implForWrapper ( image ) ; if ( impl ) { arguments [ 0 ] = impl . _image || impl . _canvas ; } return prev . apply ( ctx , arguments ) ; } ; }


Input: NOTE : per https : // heycam . github . io / webidl / #Global all properties on the Window object must be own - properties . That is why we assign everything inside of the constructor instead of using a shared prototype . You can verify this in e . g . Firefox or Internet Explorer which do a good job with Web IDL compliance . [CODESPLIT] function Window ( options ) { EventTarget . setup ( this ) ; const rawPerformance = new RawPerformance ( ) ; const windowInitialized = rawPerformance . now ( ) ; const window = this ; mixin ( window , WindowEventHandlersImpl . prototype ) ; mixin ( window , GlobalEventHandlersImpl . prototype ) ; this . _initGlobalEvents ( ) ; ///// INTERFACES FROM THE DOM // TODO: consider a mode of some sort where these are not shared between all DOM instances // It'd be very memory-expensive in most cases, though. for ( const name in dom ) { Object . defineProperty ( window , name , { enumerable : false , configurable : true , writable : true , value : dom [ name ] } ) ; } ///// PRIVATE DATA PROPERTIES this . _resourceLoader = options . resourceLoader ; // vm initialization is deferred until script processing is activated this . _globalProxy = this ; Object . defineProperty ( idlUtils . implForWrapper ( this ) , idlUtils . wrapperSymbol , { get : ( ) => this . _globalProxy } ) ; let timers = Object . create ( null ) ; let animationFrameCallbacks = Object . create ( null ) ; // List options explicitly to be clear which are passed through this . _document = Document . create ( [ ] , { options : { parsingMode : options . parsingMode , contentType : options . contentType , encoding : options . encoding , cookieJar : options . cookieJar , url : options . url , lastModified : options . lastModified , referrer : options . referrer , concurrentNodeIterators : options . concurrentNodeIterators , parseOptions : options . parseOptions , defaultView : this . _globalProxy , global : this } } ) ; // https://html.spec.whatwg.org/#session-history this . _sessionHistory = new SessionHistory ( { document : idlUtils . implForWrapper ( this . _document ) , url : idlUtils . implForWrapper ( this . _document ) . _URL , stateObject : null } , this ) ; this . _virtualConsole = options . virtualConsole ; this . _runScripts = options . runScripts ; if ( this . _runScripts === "outside-only" || this . _runScripts === "dangerously" ) { contextifyWindow ( this ) ; } // Set up the window as if it's a top level window. // If it's not, then references will be corrected by frame/iframe code. this . _parent = this . _top = this . _globalProxy ; this . _frameElement = null ; // This implements window.frames.length, since window.frames returns a // self reference to the window object.  This value is incremented in the // HTMLFrameElement implementation. this . _length = 0 ; this . _pretendToBeVisual = options . pretendToBeVisual ; this . _storageQuota = options . storageQuota ; // Some properties (such as localStorage and sessionStorage) share data // between windows in the same origin. This object is intended // to contain such data. if ( options . commonForOrigin && options . commonForOrigin [ this . _document . origin ] ) { this . _commonForOrigin = options . commonForOrigin ; } else { this . _commonForOrigin = { [ this . _document . origin ] : { localStorageArea : new Map ( ) , sessionStorageArea : new Map ( ) , windowsInSameOrigin : [ this ] } } ; } this . _currentOriginData = this . _commonForOrigin [ this . _document . origin ] ; ///// WEB STORAGE this . _localStorage = Storage . create ( [ ] , { associatedWindow : this , storageArea : this . _currentOriginData . localStorageArea , type : "localStorage" , url : this . _document . documentURI , storageQuota : this . _storageQuota } ) ; this . _sessionStorage = Storage . create ( [ ] , { associatedWindow : this , storageArea : this . _currentOriginData . sessionStorageArea , type : "sessionStorage" , url : this . _document . documentURI , storageQuota : this . _storageQuota } ) ; ///// GETTERS const locationbar = BarProp . create ( ) ; const menubar = BarProp . create ( ) ; const personalbar = BarProp . create ( ) ; const scrollbars = BarProp . create ( ) ; const statusbar = BarProp . create ( ) ; const toolbar = BarProp . create ( ) ; const external = External . create ( ) ; const navigator = Navigator . create ( [ ] , { userAgent : this . _resourceLoader . _userAgent } ) ; const performance = Performance . create ( [ ] , { rawPerformance } ) ; const screen = Screen . create ( ) ; define ( this , { get length ( ) { return window . _length ; } , get window ( ) { return window . _globalProxy ; } , get frameElement ( ) { return idlUtils . wrapperForImpl ( window . _frameElement ) ; } , get frames ( ) { return window . _globalProxy ; } , get self ( ) { return window . _globalProxy ; } , get parent ( ) { return window . _parent ; } , get top ( ) { return window . _top ; } , get document ( ) { return window . _document ; } , get external ( ) { return external ; } , get location ( ) { return idlUtils . wrapperForImpl ( idlUtils . implForWrapper ( window . _document ) . _location ) ; } , get history ( ) { return idlUtils . wrapperForImpl ( idlUtils . implForWrapper ( window . _document ) . _history ) ; } , get navigator ( ) { return navigator ; } , get locationbar ( ) { return locationbar ; } , get menubar ( ) { return menubar ; } , get personalbar ( ) { return personalbar ; } , get scrollbars ( ) { return scrollbars ; } , get statusbar ( ) { return statusbar ; } , get toolbar ( ) { return toolbar ; } , get performance ( ) { return performance ; } , get screen ( ) { return screen ; } , get localStorage ( ) { if ( this . _document . origin === "null" ) { throw new DOMException ( "localStorage is not available for opaque origins" , "SecurityError" ) ; } return this . _localStorage ; } , get sessionStorage ( ) { if ( this . _document . origin === "null" ) { throw new DOMException ( "sessionStorage is not available for opaque origins" , "SecurityError" ) ; } return this . _sessionStorage ; } } ) ; namedPropertiesWindow . initializeWindow ( this , this . _globalProxy ) ; ///// METHODS for [ImplicitThis] hack // See https://lists.w3.org/Archives/Public/public-script-coord/2015JanMar/0109.html this . addEventListener = this . addEventListener . bind ( this ) ; this . removeEventListener = this . removeEventListener . bind ( this ) ; this . dispatchEvent = this . dispatchEvent . bind ( this ) ; ///// METHODS let latestTimerId = 0 ; let latestAnimationFrameCallbackId = 0 ; this . setTimeout = function ( fn , ms ) { const args = [ ] ; for ( let i = 2 ; i < arguments . length ; ++ i ) { args [ i - 2 ] = arguments [ i ] ; } return startTimer ( window , setTimeout , clearTimeout , ++ latestTimerId , fn , ms , timers , args ) ; } ; this . setInterval = function ( fn , ms ) { const args = [ ] ; for ( let i = 2 ; i < arguments . length ; ++ i ) { args [ i - 2 ] = arguments [ i ] ; } return startTimer ( window , setInterval , clearInterval , ++ latestTimerId , fn , ms , timers , args ) ; } ; this . clearInterval = stopTimer . bind ( this , timers ) ; this . clearTimeout = stopTimer . bind ( this , timers ) ; if ( this . _pretendToBeVisual ) { this . requestAnimationFrame = fn => { const timestamp = rawPerformance . now ( ) - windowInitialized ; const fps = 1000 / 60 ; return startTimer ( window , setTimeout , clearTimeout , ++ latestAnimationFrameCallbackId , fn , fps , animationFrameCallbacks , [ timestamp ] ) ; } ; this . cancelAnimationFrame = stopTimer . bind ( this , animationFrameCallbacks ) ; } this . __stopAllTimers = function ( ) { stopAllTimers ( timers ) ; stopAllTimers ( animationFrameCallbacks ) ; latestTimerId = 0 ; latestAnimationFrameCallbackId = 0 ; timers = Object . create ( null ) ; animationFrameCallbacks = Object . create ( null ) ; } ; function Option ( text , value , defaultSelected , selected ) { if ( text === undefined ) { text = "" ; } text = webIDLConversions . DOMString ( text ) ; if ( value !== undefined ) { value = webIDLConversions . DOMString ( value ) ; } defaultSelected = webIDLConversions . boolean ( defaultSelected ) ; selected = webIDLConversions . boolean ( selected ) ; const option = window . _document . createElement ( "option" ) ; const impl = idlUtils . implForWrapper ( option ) ; if ( text !== "" ) { impl . text = text ; } if ( value !== undefined ) { impl . setAttributeNS ( null , "value" , value ) ; } if ( defaultSelected ) { impl . setAttributeNS ( null , "selected" , "" ) ; } impl . _selectedness = selected ; return option ; } Object . defineProperty ( Option , "prototype" , { value : this . HTMLOptionElement . prototype , configurable : false , enumerable : false , writable : false } ) ; Object . defineProperty ( window , "Option" , { value : Option , configurable : true , enumerable : false , writable : true } ) ; function Image ( ) { const img = window . _document . createElement ( "img" ) ; const impl = idlUtils . implForWrapper ( img ) ; if ( arguments . length > 0 ) { impl . setAttributeNS ( null , "width" , String ( arguments [ 0 ] ) ) ; } if ( arguments . length > 1 ) { impl . setAttributeNS ( null , "height" , String ( arguments [ 1 ] ) ) ; } return img ; } Object . defineProperty ( Image , "prototype" , { value : this . HTMLImageElement . prototype , configurable : false , enumerable : false , writable : false } ) ; Object . defineProperty ( window , "Image" , { value : Image , configurable : true , enumerable : false , writable : true } ) ; function Audio ( src ) { const audio = window . _document . createElement ( "audio" ) ; const impl = idlUtils . implForWrapper ( audio ) ; impl . setAttributeNS ( null , "preload" , "auto" ) ; if ( src !== undefined ) { impl . setAttributeNS ( null , "src" , String ( src ) ) ; } return audio ; } Object . defineProperty ( Audio , "prototype" , { value : this . HTMLAudioElement . prototype , configurable : false , enumerable : false , writable : false } ) ; Object . defineProperty ( window , "Audio" , { value : Audio , configurable : true , enumerable : false , writable : true } ) ; this . postMessage = postMessage ; this . atob = function ( str ) { const result = atob ( str ) ; if ( result === null ) { throw new DOMException ( "The string to be decoded contains invalid characters." , "InvalidCharacterError" ) ; } return result ; } ; this . btoa = function ( str ) { const result = btoa ( str ) ; if ( result === null ) { throw new DOMException ( "The string to be encoded contains invalid characters." , "InvalidCharacterError" ) ; } return result ; } ; this . FileReader = createFileReader ( { window : this } ) . interface ; this . WebSocket = createWebSocket ( { window : this } ) . interface ; const AbortSignalWrapper = createAbortSignal ( { window : this } ) ; this . AbortSignal = AbortSignalWrapper . interface ; this . AbortController = createAbortController ( { AbortSignal : AbortSignalWrapper } ) . interface ; this . XMLHttpRequest = createXMLHttpRequest ( this ) ; // TODO: necessary for Blob and FileReader due to different-globals weirdness; investigate how to avoid this. this . ArrayBuffer = ArrayBuffer ; this . Int8Array = Int8Array ; this . Uint8Array = Uint8Array ; this . Uint8ClampedArray = Uint8ClampedArray ; this . Int16Array = Int16Array ; this . Uint16Array = Uint16Array ; this . Int32Array = Int32Array ; this . Uint32Array = Uint32Array ; this . Float32Array = Float32Array ; this . Float64Array = Float64Array ; this . stop = function ( ) { const manager = idlUtils . implForWrapper ( this . _document ) . _requestManager ; if ( manager ) { manager . close ( ) ; } } ; this . close = function ( ) { // Recursively close child frame windows, then ourselves. const currentWindow = this ; ( function windowCleaner ( windowToClean ) { for ( let i = 0 ; i < windowToClean . length ; i ++ ) { windowCleaner ( windowToClean [ i ] ) ; } // We"re already in our own window.close(). if ( windowToClean !== currentWindow ) { windowToClean . close ( ) ; } } ( this ) ) ; // Clear out all listeners. Any in-flight or upcoming events should not get delivered. idlUtils . implForWrapper ( this ) . _eventListeners = Object . create ( null ) ; if ( this . _document ) { if ( this . _document . body ) { this . _document . body . innerHTML = "" ; } if ( this . _document . close ) { // It's especially important to clear out the listeners here because document.close() causes a "load" event to // fire. idlUtils . implForWrapper ( this . _document ) . _eventListeners = Object . create ( null ) ; this . _document . close ( ) ; } const doc = idlUtils . implForWrapper ( this . _document ) ; if ( doc . _requestManager ) { doc . _requestManager . close ( ) ; } delete this . _document ; } this . __stopAllTimers ( ) ; WebSocketImpl . cleanUpWindow ( this ) ; } ; this . getComputedStyle = function ( elt ) { elt = Element . convert ( elt ) ; const declaration = new CSSStyleDeclaration ( ) ; const { forEach , indexOf } = Array . prototype ; const { style } = elt ; function setPropertiesFromRule ( rule ) { if ( ! rule . selectorText ) { return ; } const cssSelectorSplitRe = / ((?:[^,"']|"[^"]*"|'[^']*')+) / ; const selectors = rule . selectorText . split ( cssSelectorSplitRe ) ; let matched = false ; for ( const selectorText of selectors ) { if ( selectorText !== "" && selectorText !== "," && ! matched && matchesDontThrow ( elt , selectorText ) ) { matched = true ; forEach . call ( rule . style , property => { declaration . setProperty ( property , rule . style . getPropertyValue ( property ) , rule . style . getPropertyPriority ( property ) ) ; } ) ; } } } function readStylesFromStyleSheet ( sheet ) { forEach . call ( sheet . cssRules , rule => { if ( rule . media ) { if ( indexOf . call ( rule . media , "screen" ) !== - 1 ) { forEach . call ( rule . cssRules , setPropertiesFromRule ) ; } } else { setPropertiesFromRule ( rule ) ; } } ) ; } if ( ! parsedDefaultStyleSheet ) { parsedDefaultStyleSheet = cssom . parse ( defaultStyleSheet ) ; } readStylesFromStyleSheet ( parsedDefaultStyleSheet ) ; forEach . call ( elt . ownerDocument . styleSheets , readStylesFromStyleSheet ) ; forEach . call ( style , property => { declaration . setProperty ( property , style . getPropertyValue ( property ) , style . getPropertyPriority ( property ) ) ; } ) ; return declaration ; } ; // The captureEvents() and releaseEvents() methods must do nothing this . captureEvents = function ( ) { } ; this . releaseEvents = function ( ) { } ; ///// PUBLIC DATA PROPERTIES (TODO: should be getters) function wrapConsoleMethod ( method ) { return ( ... args ) => { window . _virtualConsole . emit ( method , ... args ) ; } ; } this . console = { assert : wrapConsoleMethod ( "assert" ) , clear : wrapConsoleMethod ( "clear" ) , count : wrapConsoleMethod ( "count" ) , countReset : wrapConsoleMethod ( "countReset" ) , debug : wrapConsoleMethod ( "debug" ) , dir : wrapConsoleMethod ( "dir" ) , dirxml : wrapConsoleMethod ( "dirxml" ) , error : wrapConsoleMethod ( "error" ) , group : wrapConsoleMethod ( "group" ) , groupCollapsed : wrapConsoleMethod ( "groupCollapsed" ) , groupEnd : wrapConsoleMethod ( "groupEnd" ) , info : wrapConsoleMethod ( "info" ) , log : wrapConsoleMethod ( "log" ) , table : wrapConsoleMethod ( "table" ) , time : wrapConsoleMethod ( "time" ) , timeEnd : wrapConsoleMethod ( "timeEnd" ) , trace : wrapConsoleMethod ( "trace" ) , warn : wrapConsoleMethod ( "warn" ) } ; function notImplementedMethod ( name ) { return function ( ) { notImplemented ( name , window ) ; } ; } define ( this , { name : "" , status : "" , devicePixelRatio : 1 , innerWidth : 1024 , innerHeight : 768 , outerWidth : 1024 , outerHeight : 768 , pageXOffset : 0 , pageYOffset : 0 , screenX : 0 , screenLeft : 0 , screenY : 0 , screenTop : 0 , scrollX : 0 , scrollY : 0 , alert : notImplementedMethod ( "window.alert" ) , blur : notImplementedMethod ( "window.blur" ) , confirm : notImplementedMethod ( "window.confirm" ) , focus : notImplementedMethod ( "window.focus" ) , moveBy : notImplementedMethod ( "window.moveBy" ) , moveTo : notImplementedMethod ( "window.moveTo" ) , open : notImplementedMethod ( "window.open" ) , print : notImplementedMethod ( "window.print" ) , prompt : notImplementedMethod ( "window.prompt" ) , resizeBy : notImplementedMethod ( "window.resizeBy" ) , resizeTo : notImplementedMethod ( "window.resizeTo" ) , scroll : notImplementedMethod ( "window.scroll" ) , scrollBy : notImplementedMethod ( "window.scrollBy" ) , scrollTo : notImplementedMethod ( "window.scrollTo" ) } ) ; ///// INITIALIZATION process . nextTick ( ( ) => { if ( ! window . document ) { return ; // window might've been closed already } if ( window . document . readyState === "complete" ) { fireAnEvent ( "load" , window , undefined , { } , window . document ) ; } else { window . document . addEventListener ( "load" , ( ) => { fireAnEvent ( "load" , window , undefined , { } , window . document ) ; if ( ! idlUtils . implForWrapper ( window . _document ) . _pageShowingFlag ) { idlUtils . implForWrapper ( window . _document ) . _pageShowingFlag = true ; fireAnEvent ( "pageshow" , window , PageTransitionEvent , { persisted : false } , window . document ) ; } } ) ; } } ) ; }


Input: https : // dom . spec . whatwg . org / #concept - tree - host - including - inclusive - ancestor [CODESPLIT] function isHostInclusiveAncestor ( nodeImplA , nodeImplB ) { for ( const ancestor of domSymbolTree . ancestorsIterator ( nodeImplB ) ) { if ( ancestor === nodeImplA ) { return true ; } } const rootImplB = getRoot ( nodeImplB ) ; if ( rootImplB . _host ) { return isHostInclusiveAncestor ( nodeImplA , rootImplB . _host ) ; } return false ; }


Input: Until webidl2js gains support for checking for Window this would have to do . [CODESPLIT] function isWindow ( val ) { if ( typeof val !== "object" ) { return false ; } const wrapper = idlUtils . wrapperForImpl ( val ) ; if ( typeof wrapper === "object" ) { return wrapper === wrapper . _globalProxy ; } // `val` may be either impl or wrapper currently, because webidl2js currently unwraps Window objects (and their global // proxies) to their underlying EventTargetImpl during conversion, which is not what we want. But at the same time, // some internal usage call this constructor with the actual global proxy. return isWindow ( idlUtils . implForWrapper ( val ) ) ; }


Input: return a request client object or an event emitter matching the same behaviour for unsupported protocols the callback should be called with a request response object or an event emitter matching the same behaviour too [CODESPLIT] function createClient ( xhr ) { const flag = xhr [ xhrSymbols . flag ] ; const properties = xhr [ xhrSymbols . properties ] ; const urlObj = new URL ( flag . uri ) ; const uri = urlObj . href ; const ucMethod = flag . method . toUpperCase ( ) ; const { requestManager } = flag ; if ( urlObj . protocol === "file:" ) { const response = new EventEmitter ( ) ; response . statusCode = 200 ; response . rawHeaders = [ ] ; response . headers = { } ; response . request = { uri : urlObj } ; const filePath = urlObj . pathname . replace ( / ^file:\/\/ / , "" ) . replace ( / ^\/([a-z]):\/ / i , "$1:/" ) . replace ( / %20 / g , " " ) ; const client = new EventEmitter ( ) ; const readableStream = fs . createReadStream ( filePath , { encoding : null } ) ; readableStream . on ( "data" , chunk => { response . emit ( "data" , chunk ) ; client . emit ( "data" , chunk ) ; } ) ; readableStream . on ( "end" , ( ) => { response . emit ( "end" ) ; client . emit ( "end" ) ; } ) ; readableStream . on ( "error" , err => { client . emit ( "error" , err ) ; } ) ; client . abort = function ( ) { readableStream . destroy ( ) ; client . emit ( "abort" ) ; } ; if ( requestManager ) { const req = { abort ( ) { properties . abortError = true ; xhr . abort ( ) ; } } ; requestManager . add ( req ) ; const rmReq = requestManager . remove . bind ( requestManager , req ) ; client . on ( "abort" , rmReq ) ; client . on ( "error" , rmReq ) ; client . on ( "end" , rmReq ) ; } process . nextTick ( ( ) => client . emit ( "response" , response ) ) ; return client ; } if ( urlObj . protocol === "data:" ) { const response = new EventEmitter ( ) ; response . request = { uri : urlObj } ; const client = new EventEmitter ( ) ; let buffer ; try { const parsed = parseDataURL ( uri ) ; const contentType = parsed . mimeType . toString ( ) ; buffer = parsed . body ; response . statusCode = 200 ; response . rawHeaders = [ "Content-Type" , contentType ] ; response . headers = { "content-type" : contentType } ; } catch ( err ) { process . nextTick ( ( ) => client . emit ( "error" , err ) ) ; return client ; } client . abort = ( ) => { // do nothing } ; process . nextTick ( ( ) => { client . emit ( "response" , response ) ; process . nextTick ( ( ) => { response . emit ( "data" , buffer ) ; client . emit ( "data" , buffer ) ; response . emit ( "end" ) ; client . emit ( "end" ) ; } ) ; } ) ; return client ; } const requestHeaders = { } ; for ( const header in flag . requestHeaders ) { requestHeaders [ header ] = flag . requestHeaders [ header ] ; } if ( getRequestHeader ( flag . requestHeaders , "referer" ) === null ) { requestHeaders . Referer = flag . referrer ; } if ( getRequestHeader ( flag . requestHeaders , "user-agent" ) === null ) { requestHeaders [ "User-Agent" ] = flag . userAgent ; } if ( getRequestHeader ( flag . requestHeaders , "accept-language" ) === null ) { requestHeaders [ "Accept-Language" ] = "en" ; } if ( getRequestHeader ( flag . requestHeaders , "accept" ) === null ) { requestHeaders . Accept = "*/*" ; } const crossOrigin = flag . origin !== urlObj . origin ; if ( crossOrigin ) { requestHeaders . Origin = flag . origin ; } const options = { uri , method : flag . method , headers : requestHeaders , gzip : true , maxRedirects : 21 , followAllRedirects : true , encoding : null , strictSSL : flag . strictSSL , proxy : flag . proxy , forever : true } ; if ( flag . auth ) { options . auth = { user : flag . auth . user || "" , pass : flag . auth . pass || "" , sendImmediately : false } ; } if ( flag . cookieJar && ( ! crossOrigin || flag . withCredentials ) ) { options . jar = wrapCookieJarForRequest ( flag . cookieJar ) ; } const { body } = flag ; const hasBody = body !== undefined && body !== null && body !== "" && ! ( ucMethod === "HEAD" || ucMethod === "GET" ) ; if ( hasBody && ! flag . formData ) { options . body = body ; } if ( hasBody && getRequestHeader ( flag . requestHeaders , "content-type" ) === null ) { requestHeaders [ "Content-Type" ] = "text/plain;charset=UTF-8" ; } function doRequest ( ) { try { const client = request ( options ) ; if ( hasBody && flag . formData ) { const form = client . form ( ) ; for ( const entry of body ) { form . append ( entry . name , entry . value , entry . options ) ; } } return client ; } catch ( e ) { const client = new EventEmitter ( ) ; process . nextTick ( ( ) => client . emit ( "error" , e ) ) ; return client ; } } let client ; const nonSimpleHeaders = Object . keys ( flag . requestHeaders ) . filter ( header => ! simpleHeaders . has ( header . toLowerCase ( ) ) ) ; if ( crossOrigin && ( ! simpleMethods . has ( ucMethod ) || nonSimpleHeaders . length > 0 || properties . uploadListener ) ) { client = new EventEmitter ( ) ; const preflightRequestHeaders = [ ] ; for ( const header in requestHeaders ) { // the only existing request headers the cors spec allows on the preflight request are Origin and Referrer const lcHeader = header . toLowerCase ( ) ; if ( lcHeader === "origin" || lcHeader === "referrer" ) { preflightRequestHeaders [ header ] = requestHeaders [ header ] ; } } preflightRequestHeaders [ "Access-Control-Request-Method" ] = flag . method ; if ( nonSimpleHeaders . length > 0 ) { preflightRequestHeaders [ "Access-Control-Request-Headers" ] = nonSimpleHeaders . join ( ", " ) ; } preflightRequestHeaders [ "User-Agent" ] = flag . userAgent ; flag . preflight = true ; const preflightOptions = { uri , method : "OPTIONS" , headers : preflightRequestHeaders , followRedirect : false , encoding : null , pool : flag . pool , strictSSL : flag . strictSSL , proxy : flag . proxy , forever : true } ; const preflightClient = request ( preflightOptions ) ; preflightClient . on ( "response" , resp => { // don't send the real request if the preflight request returned an error if ( resp . statusCode < 200 || resp . statusCode > 299 ) { client . emit ( "error" , new Error ( "Response for preflight has invalid HTTP status code " + resp . statusCode ) ) ; return ; } // don't send the real request if we aren't allowed to use the headers if ( ! validCORSPreflightHeaders ( xhr , resp , flag , properties ) ) { setResponseToNetworkError ( xhr ) ; return ; } const realClient = doRequest ( ) ; realClient . on ( "response" , res => { for ( const header in resp . headers ) { if ( preflightHeaders . has ( header ) ) { res . headers [ header ] = Object . prototype . hasOwnProperty . call ( res . headers , header ) ? mergeHeaders ( res . headers [ header ] , resp . headers [ header ] ) : resp . headers [ header ] ; } } client . emit ( "response" , res ) ; } ) ; realClient . on ( "data" , chunk => client . emit ( "data" , chunk ) ) ; realClient . on ( "end" , ( ) => client . emit ( "end" ) ) ; realClient . on ( "abort" , ( ) => client . emit ( "abort" ) ) ; realClient . on ( "request" , req => { client . headers = realClient . headers ; client . emit ( "request" , req ) ; } ) ; realClient . on ( "redirect" , ( ) => { client . response = realClient . response ; client . emit ( "redirect" ) ; } ) ; realClient . on ( "error" , err => client . emit ( "error" , err ) ) ; client . abort = ( ) => { realClient . abort ( ) ; } ; } ) ; preflightClient . on ( "error" , err => client . emit ( "error" , err ) ) ; client . abort = ( ) => { preflightClient . abort ( ) ; } ; } else { client = doRequest ( ) ; } if ( requestManager ) { const req = { abort ( ) { properties . abortError = true ; xhr . abort ( ) ; } } ; requestManager . add ( req ) ; const rmReq = requestManager . remove . bind ( requestManager , req ) ; client . on ( "abort" , rmReq ) ; client . on ( "error" , rmReq ) ; client . on ( "end" , rmReq ) ; } return client ; }


Input: https : // w3c . github . io / DOM - Parsing / #dfn - fragment - parsing - algorithm [CODESPLIT] function parseFragment ( markup , contextElement ) { const { _parsingMode } = contextElement . _ownerDocument ; let parseAlgorithm ; if ( _parsingMode === "html" ) { parseAlgorithm = htmlParser . parseFragment ; } else if ( _parsingMode === "xml" ) { parseAlgorithm = xmlParser . parseFragment ; } // Note: HTML and XML fragment parsing algorithm already return a document fragments; no need to do steps 3 and 4 return parseAlgorithm ( markup , contextElement ) ; }


Input: / * eslint - disable no - console / * eslint - disable no - invalid - this [CODESPLIT] function onError ( event ) { const bench = event . target ; console . error ( "Error in benchmark" , bench . name , ":" , bench . error ) ; }


Input: https : // html . spec . whatwg . org / multipage / webappapis . html#report - the - error Omits script parameter and any check for muted errors . Takes target as an EventTarget impl . Takes error object message and location as params unlike the spec . Returns whether the event was handled or not . [CODESPLIT] function reportAnError ( line , col , target , errorObject , message , location ) { if ( target [ errorReportingMode ] ) { return false ; } target [ errorReportingMode ] = true ; const event = createAnEvent ( "error" , ErrorEvent , { cancelable : true , message , filename : location , lineno : line , colno : col , error : errorObject } ) ; try { target . _dispatch ( event ) ; } finally { target [ errorReportingMode ] = false ; return event . defaultPrevented ; } }


Input: https : // html . spec . whatwg . org / multipage / links . html#link - type - stylesheet [CODESPLIT] function maybeFetchAndProcess ( el ) { if ( ! isExternalResourceLink ( el ) ) { return ; } // Browsing-context connected if ( ! el . isConnected || ! el . _ownerDocument . _defaultView ) { return ; } fetchAndProcess ( el ) ; }


Input: https : // html . spec . whatwg . org / multipage / semantics . html#default - fetch - and - process - the - linked - resource TODO : refactor into general link - fetching like the spec . [CODESPLIT] function fetchAndProcess ( el ) { const href = el . getAttributeNS ( null , "href" ) ; if ( href === null || href === "" ) { return ; } const url = parseURLToResultingURLRecord ( href , el . _ownerDocument ) ; if ( url === null ) { return ; } // TODO handle crossorigin="", nonce, integrity="", referrerpolicy="" const serialized = whatwgURL . serializeURL ( url ) ; fetchStylesheet ( el , serialized ) ; }


Input: https : // dom . spec . whatwg . org / #concept - slotable [CODESPLIT] function isSlotable ( nodeImpl ) { return nodeImpl && ( nodeImpl . nodeType === NODE_TYPE . ELEMENT_NODE || nodeImpl . nodeType === NODE_TYPE . TEXT_NODE ) ; }


Input: https : // dom . spec . whatwg . org / #concept - shadow - including - inclusive - ancestor [CODESPLIT] function isShadowInclusiveAncestor ( ancestor , node ) { while ( isNode ( node ) ) { if ( node === ancestor ) { return true ; } if ( isShadowRoot ( node ) ) { node = node . host ; } else { node = domSymbolTree . parent ( node ) ; } } return false ; }


Input: https : // dom . spec . whatwg . org / #retarget [CODESPLIT] function retarget ( a , b ) { while ( true ) { if ( ! isNode ( a ) ) { return a ; } const aRoot = getRoot ( a ) ; if ( ! isShadowRoot ( aRoot ) || ( isNode ( b ) && isShadowInclusiveAncestor ( aRoot , b ) ) ) { return a ; } a = getRoot ( a ) . host ; } }


Input: https : // dom . spec . whatwg . org / #concept - shadow - including - root [CODESPLIT] function shadowIncludingRoot ( node ) { const root = getRoot ( node ) ; return isShadowRoot ( root ) ? shadowIncludingRoot ( root . host ) : root ; }


Input: https : // dom . spec . whatwg . org / #assign - slotables [CODESPLIT] function assignSlotable ( slot ) { const slotables = findSlotable ( slot ) ; let shouldFireSlotChange = false ; if ( slotables . length !== slot . _assignedNodes . length ) { shouldFireSlotChange = true ; } else { for ( let i = 0 ; i < slotables . length ; i ++ ) { if ( slotables [ i ] !== slot . _assignedNodes [ i ] ) { shouldFireSlotChange = true ; break ; } } } if ( shouldFireSlotChange ) { signalSlotChange ( slot ) ; } slot . _assignedNodes = slotables ; for ( const slotable of slotables ) { slotable . _assignedSlot = slot ; } }


Input: https : // dom . spec . whatwg . org / #assign - slotables - for - a - tree [CODESPLIT] function assignSlotableForTree ( root ) { for ( const slot of domSymbolTree . treeIterator ( root ) ) { if ( isSlot ( slot ) ) { assignSlotable ( slot ) ; } } }


Input: https : // dom . spec . whatwg . org / #find - slotables [CODESPLIT] function findSlotable ( slot ) { const result = [ ] ; const root = getRoot ( slot ) ; if ( ! isShadowRoot ( root ) ) { return result ; } for ( const slotable of domSymbolTree . treeIterator ( root . host ) ) { const foundSlot = findSlot ( slotable ) ; if ( foundSlot === slot ) { result . push ( slotable ) ; } } return result ; }


Input: https : // dom . spec . whatwg . org / #find - flattened - slotables [CODESPLIT] function findFlattenedSlotables ( slot ) { const result = [ ] ; const root = getRoot ( slot ) ; if ( ! isShadowRoot ( root ) ) { return result ; } const slotables = findSlotable ( slot ) ; if ( slotables . length === 0 ) { for ( const child of domSymbolTree . childrenIterator ( slot ) ) { if ( isSlotable ( child ) ) { slotables . push ( child ) ; } } } for ( const node of slotables ) { if ( isSlot ( node ) && isShadowRoot ( getRoot ( node ) ) ) { const temporaryResult = findFlattenedSlotables ( node ) ; result . push ( ... temporaryResult ) ; } else { result . push ( node ) ; } } return result ; }


Input: https : // dom . spec . whatwg . org / #find - a - slot [CODESPLIT] function findSlot ( slotable , openFlag ) { const { parentNode : parent } = slotable ; if ( ! parent ) { return null ; } const shadow = parent . _shadowRoot ; if ( ! shadow || ( openFlag && shadow . mode !== "open" ) ) { return null ; } for ( const child of domSymbolTree . treeIterator ( shadow ) ) { if ( isSlot ( child ) && child . name === slotable . _slotableName ) { return child ; } } return null ; }


Input: https : // dom . spec . whatwg . org / #signal - a - slot - change [CODESPLIT] function signalSlotChange ( slot ) { if ( ! signalSlotList . some ( entry => entry === slot ) ) { signalSlotList . push ( slot ) ; } queueMutationObserverMicrotask ( ) ; }


Input: https : // html . spec . whatwg . org / #scroll - to - fragid [CODESPLIT] function navigateToFragment ( window , newURL , flags ) { const document = idlUtils . implForWrapper ( window . _document ) ; window . _sessionHistory . clearHistoryTraversalTasks ( ) ; if ( ! flags . replacement ) { // handling replacement=true here deviates from spec, but matches real browser behaviour // see https://github.com/whatwg/html/issues/2796 for spec bug window . _sessionHistory . removeAllEntriesAfterCurrentEntry ( ) ; } const newEntry = { document , url : newURL } ; window . _sessionHistory . addEntryAfterCurrentEntry ( newEntry ) ; window . _sessionHistory . traverseHistory ( newEntry , { nonBlockingEvents : true , replacement : flags . replacement } ) ; }


Input: https : // dom . spec . whatwg . org / #concept - event - listener - invoke [CODESPLIT] function invokeEventListeners ( tuple , eventImpl ) { const tupleIndex = eventImpl . _path . indexOf ( tuple ) ; for ( let i = tupleIndex ; i >= 0 ; i -- ) { const t = eventImpl . _path [ i ] ; if ( t . target ) { eventImpl . target = t . target ; break ; } } eventImpl . relatedTarget = idlUtils . wrapperForImpl ( tuple . relatedTarget ) ; if ( eventImpl . _stopPropagationFlag ) { return ; } eventImpl . currentTarget = idlUtils . wrapperForImpl ( tuple . item ) ; const listeners = tuple . item . _eventListeners ; innerInvokeEventListeners ( eventImpl , listeners ) ; }


Input: https : // dom . spec . whatwg . org / #concept - event - listener - inner - invoke [CODESPLIT] function innerInvokeEventListeners ( eventImpl , listeners ) { let found = false ; const { type , target } = eventImpl ; const wrapper = idlUtils . wrapperForImpl ( target ) ; if ( ! listeners || ! listeners [ type ] ) { return found ; } // Copy event listeners before iterating since the list can be modified during the iteration. const handlers = listeners [ type ] . slice ( ) ; for ( let i = 0 ; i < handlers . length ; i ++ ) { const listener = handlers [ i ] ; const { capture , once , passive } = listener . options ; // Check if the event listener has been removed since the listeners has been cloned. if ( ! listeners [ type ] . includes ( listener ) ) { continue ; } found = true ; if ( ( eventImpl . eventPhase === Event . CAPTURING_PHASE && ! capture ) || ( eventImpl . eventPhase === Event . BUBBLING_PHASE && capture ) ) { continue ; } if ( once ) { listeners [ type ] . splice ( listeners [ type ] . indexOf ( listener ) , 1 ) ; } if ( passive ) { eventImpl . _inPassiveListenerFlag = true ; } try { if ( typeof listener . callback === "object" ) { if ( typeof listener . callback . handleEvent === "function" ) { listener . callback . handleEvent ( idlUtils . wrapperForImpl ( eventImpl ) ) ; } } else { listener . callback . call ( eventImpl . currentTarget , idlUtils . wrapperForImpl ( eventImpl ) ) ; } } catch ( e ) { let window = null ; if ( wrapper && wrapper . _document ) { // Triggered by Window window = wrapper ; } else if ( target . _ownerDocument ) { // Triggered by most webidl2js'ed instances window = target . _ownerDocument . _defaultView ; } else if ( wrapper . _ownerDocument ) { // Currently triggered by XHR and some other non-webidl2js things window = wrapper . _ownerDocument . _defaultView ; } if ( window ) { reportException ( window , e ) ; } // Errors in window-less documents just get swallowed... can you think of anything better? } eventImpl . _inPassiveListenerFlag = false ; if ( eventImpl . _stopImmediatePropagationFlag ) { return found ; } } return found ; }


Input: Normalize the event listeners options argument in order to get always a valid options object [CODESPLIT] function normalizeEventHandlerOptions ( options , defaultBoolKeys ) { const returnValue = { } ; // no need to go further here if ( typeof options === "boolean" || options === null || typeof options === "undefined" ) { returnValue . capture = Boolean ( options ) ; return returnValue ; } // non objects options so we typecast its value as "capture" value if ( typeof options !== "object" ) { returnValue . capture = Boolean ( options ) ; // at this point we don't need to loop the "capture" key anymore defaultBoolKeys = defaultBoolKeys . filter ( k => k !== "capture" ) ; } for ( const key of defaultBoolKeys ) { returnValue [ key ] = Boolean ( options [ key ] ) ; } return returnValue ; }


Input: https : // dom . spec . whatwg . org / #concept - event - path - append [CODESPLIT] function appendToEventPath ( eventImpl , target , targetOverride , relatedTarget , touchTargets , slotInClosedTree ) { const itemInShadowTree = isNode ( target ) && isShadowRoot ( getRoot ( target ) ) ; const rootOfClosedTree = isShadowRoot ( target ) && target . mode === "closed" ; eventImpl . _path . push ( { item : target , itemInShadowTree , target : targetOverride , relatedTarget , touchTargets , rootOfClosedTree , slotInClosedTree } ) ; }


Input: https : // dom . spec . whatwg . org / #queue - a - mutation - record [CODESPLIT] function queueMutationRecord ( type , target , name , namespace , oldValue , addedNodes , removedNodes , previousSibling , nextSibling ) { const interestedObservers = new Map ( ) ; const nodes = domSymbolTree . ancestorsToArray ( target ) ; for ( const node of nodes ) { for ( const registered of node . _registeredObserverList ) { const { options , observer : mo } = registered ; if ( ! ( node !== target && options . subtree === false ) && ! ( type === MUTATION_TYPE . ATTRIBUTES && options . attributes !== true ) && ! ( type === MUTATION_TYPE . ATTRIBUTES && options . attributeFilter && ! options . attributeFilter . some ( value => value === name || value === namespace ) ) && ! ( type === MUTATION_TYPE . CHARACTER_DATA && options . characterData !== true ) && ! ( type === MUTATION_TYPE . CHILD_LIST && options . childList === false ) ) { if ( ! interestedObservers . has ( mo ) ) { interestedObservers . set ( mo , null ) ; } if ( ( type === MUTATION_TYPE . ATTRIBUTES && options . attributeOldValue === true ) || ( type === MUTATION_TYPE . CHARACTER_DATA && options . characterDataOldValue === true ) ) { interestedObservers . set ( mo , oldValue ) ; } } } } for ( const [ observer , mappedOldValue ] of interestedObservers . entries ( ) ) { const record = MutationRecord . createImpl ( [ ] , { type , target , attributeName : name , attributeNamespace : namespace , oldValue : mappedOldValue , addedNodes , removedNodes , previousSibling , nextSibling } ) ; observer . _recordQueue . push ( record ) ; activeMutationObservers . add ( observer ) ; } queueMutationObserverMicrotask ( ) ; }


Input: https : // dom . spec . whatwg . org / #queue - a - tree - mutation - record [CODESPLIT] function queueTreeMutationRecord ( target , addedNodes , removedNodes , previousSibling , nextSibling ) { queueMutationRecord ( MUTATION_TYPE . CHILD_LIST , target , null , null , null , addedNodes , removedNodes , previousSibling , nextSibling ) ; }


Input: https : // dom . spec . whatwg . org / #queue - an - attribute - mutation - record [CODESPLIT] function queueAttributeMutationRecord ( target , name , namespace , oldValue ) { queueMutationRecord ( MUTATION_TYPE . ATTRIBUTES , target , name , namespace , oldValue , [ ] , [ ] , null , null ) ; }


Input: https : // dom . spec . whatwg . org / #notify - mutation - observers [CODESPLIT] function notifyMutationObservers ( ) { mutationObserverMicrotaskQueueFlag = false ; const notifyList = [ ... activeMutationObservers ] . sort ( ( a , b ) => a . _id - b . _id ) ; activeMutationObservers . clear ( ) ; const signalList = [ ... signalSlotList ] ; signalSlotList . splice ( 0 , signalSlotList . length ) ; for ( const mo of notifyList ) { const records = [ ... mo . _recordQueue ] ; mo . _recordQueue = [ ] ; for ( const node of mo . _nodeList ) { node . _registeredObserverList = node . _registeredObserverList . filter ( registeredObserver => { return registeredObserver . source !== mo ; } ) ; if ( records . length ) { try { mo . _callback ( records . map ( idlUtils . wrapperForImpl ) , idlUtils . wrapperForImpl ( mo ) ) ; } catch ( e ) { const { target } = records [ 0 ] ; const window = target . _ownerDocument . _defaultView ; reportException ( window , e ) ; } } } } for ( const slot of signalList ) { const slotChangeEvent = Event . createImpl ( [ "slotchange" , { bubbles : true } ] , { isTrusted : true } ) ; slot . _dispatch ( slotChangeEvent ) ; } }


Input: https : // drafts . csswg . org / cssom / #add - a - css - style - sheet [CODESPLIT] function addStylesheet ( sheet , elementImpl ) { elementImpl . _ownerDocument . styleSheets . push ( sheet ) ; // Set the association explicitly; in the spec it's implicit. elementImpl . sheet = sheet ; // TODO: title and disabled stuff }


Input: TODO this is actually really messed up and overwrites the sheet on elementImpl Tracking in https : // github . com / tmpvar / jsdom / issues / 2124 [CODESPLIT] function scanForImportRules ( elementImpl , cssRules , baseURL ) { if ( ! cssRules ) { return ; } for ( let i = 0 ; i < cssRules . length ; ++ i ) { if ( cssRules [ i ] . cssRules ) { // @media rule: keep searching inside it. scanForImportRules ( elementImpl , cssRules [ i ] . cssRules , baseURL ) ; } else if ( cssRules [ i ] . href ) { // @import rule: fetch the resource and evaluate it. // See http://dev.w3.org/csswg/cssom/#css-import-rule //     If loading of the style sheet fails its cssRules list is simply //     empty. I.e. an @import rule always has an associated style sheet. const parsed = whatwgURL . parseURL ( cssRules [ i ] . href , { baseURL } ) ; if ( parsed === null ) { const window = elementImpl . _ownerDocument . _defaultView ; if ( window ) { const error = new Error ( ` ${ cssRules [ i ] . href } ` + ` ${ whatwgURL . serializeURL ( baseURL ) } ` ) ; error . type = "css @import URL parsing" ; window . _virtualConsole . emit ( "jsdomError" , error ) ; } } else { fetchStylesheetInternal ( elementImpl , whatwgURL . serializeURL ( parsed ) , parsed ) ; } } } }


Input: Necessary because Date . UTC () treats year within [ 0 99 ] as [ 1900 1999 ] . [CODESPLIT] function getUTCMs ( year , month = 1 , day = 1 , hour = 0 , minute = 0 , second = 0 , millisecond = 0 ) { if ( year > 99 || year < 0 ) { return Date . UTC ( year , month - 1 , day , hour , minute , second , millisecond ) ; } const d = new Date ( 0 ) ; d . setUTCFullYear ( year ) ; d . setUTCMonth ( month - 1 ) ; d . setUTCDate ( day ) ; d . setUTCHours ( hour ) ; d . setUTCMinutes ( minute ) ; d . setUTCSeconds ( second , millisecond ) ; return d . valueOf ( ) ; }


Input: generate SUMMARY . md by config . json [CODESPLIT] function sammary ( ) { const nodeFn = function ( { parentPaths , lang , item , isDir , result } ) { const navTitle = generateNavTitle ( { parentPaths , item , sign : isDir ? '-' : '*' , lang } ) ; result . push ( navTitle ) ; } ; langs . forEach ( dir => { const SUMMARY = 'SUMMARY.md' ; const targetFile = path . join ( docsDir , ` ${ dir } ${ SUMMARY } ` ) ; const result = walk ( { catalog : docConfig . catalog , lang : dir , result : [ ] , parentPaths : [ ] , fn : nodeFn } ) ; if ( result && result . length ) { result . unshift ( '# whistle\n' ) ; fs . writeFileSync ( targetFile , result . join ( '\n' ) ) ; } } ) ; }


Input: 如果超过最大缓存数，清理如下请求数据： 1 . 已经请求结束且结束时间超过10秒 2 . 请求#1前面的未结束且未被ui读取过的请求 [CODESPLIT] function clearCache ( ) { var overflow = frames . length - MAX_FRAMES_LENGTH ; overflow > 0 && frames . splice ( 0 , overflow + 60 ) ; var len = ids . length ; if ( len <= MAX_LENGTH ) { return ; } var now = Date . now ( ) ; var _ids = [ ] ; var preserveLen = len ; overflow = - 1 ; if ( len >= OVERFLOW_LENGTH ) { overflow = len - MAX_CACHE_SIZE ; preserveLen = len - PRESERVE_LEN ; } for ( var i = 0 ; i < len ; i ++ ) { var id = ids [ i ] ; var curData = reqData [ id ] ; if ( i > overflow && ( i >= preserveLen || ( curData . endTime ? now - curData . endTime < CACHE_TIME : now - curData . startTime < CACHE_TIMEOUT ) ) ) { if ( curData . endTime && curData . abort ) { delete curData . abort ; } _ids . push ( id ) ; } else { delete reqData [ id ] ; } } ids = _ids ; }


Input: options : { startTime : timestamp || timestamp + - + count count : 获取新数据的数量 ids : 请未结束的id列表 } [CODESPLIT] function formatFilter ( filter , clientIp ) { if ( ! filter . url && ! filter . name && ! filter . value && ! filter . ip ) { return ; } var url = util . trimStr ( filter . url ) . toLowerCase ( ) ; var name = util . trimStr ( filter . name ) . toLowerCase ( ) ; var value = util . trimStr ( filter . value ) . toLowerCase ( ) ; var ip = util . trimStr ( filter . ip ) ; var list = [ ] ; if ( ip === 'self' ) { ip = clientIp ; } else if ( ip && ! net . isIP ( ip ) ) { ip . split ( ',' ) . forEach ( function ( item ) { item = item . trim ( ) ; if ( item === 'self' ) { item = clientIp ; } if ( net . isIP ( item ) && list . indexOf ( item ) === - 1 ) { list . push ( item ) ; } } ) ; ip = null ; } var result ; if ( url ) { result = { } ; result . url = url ; } if ( name && value ) { result = result || { } ; result . name = name ; result . value = value ; } if ( ip ) { result = result || { } ; result . ip = ip ; } if ( list . length ) { result = result || { } ; result . ipList = list . slice ( 0 , 16 ) ; } return result ; }


Input: rules [CODESPLIT] function resolveInlineValues ( str ) { str = str && str . replace ( CONTROL_RE , '' ) . trim ( ) ; if ( ! str || str . indexOf ( '```' ) === - 1 ) { return str ; } return str . replace ( MULTI_LINE_VALUE_RE , function ( _ , __ , key , value ) { inlineValues = inlineValues || { } ; if ( ! inlineValues [ key ] ) { inlineValues [ key ] = value ; } return '' ; } ) ; }


Input: / * eslint no - console : off [CODESPLIT] function ( message , filename , lineno , colno , error ) { if ( error ) { wConsole . error ( getErrorStack ( error , message ) ) ; } else { wConsole . error ( 'Error: ' + message + '(' + filename + ':' + lineno + ':' + ( colno || 0 ) + ')' + getPageInfo ( ) ) ; } }


Input: Renders nested values ( eg . objects arrays lists etc . ) [CODESPLIT] function renderChildNodes ( props , from , to ) { var nodeType = props . nodeType , data = props . data , collectionLimit = props . collectionLimit , circularCache = props . circularCache , keyPath = props . keyPath , postprocessValue = props . postprocessValue , sortObjectKeys = props . sortObjectKeys ; var childNodes = [ ] ; ( 0 , _getCollectionEntries2 [ 'default' ] ) ( nodeType , data , sortObjectKeys , collectionLimit , from , to ) . forEach ( function ( entry ) { if ( entry . to ) { childNodes . push ( _react2 [ 'default' ] . createElement ( _ItemRange2 [ 'default' ] , ( 0 , _extends3 [ 'default' ] ) ( { } , props , { key : 'ItemRange--' + entry . from + '-' + entry . to , from : entry . from , to : entry . to , renderChildNodes : renderChildNodes } ) ) ) ; } else { var key = entry . key , value = entry . value ; var isCircular = circularCache . indexOf ( value ) !== - 1 ; var node = _react2 [ 'default' ] . createElement ( _JSONNode2 [ 'default' ] , ( 0 , _extends3 [ 'default' ] ) ( { } , props , { postprocessValue : postprocessValue , collectionLimit : collectionLimit } , { key : 'Node--' + key , keyPath : [ key ] . concat ( keyPath ) , value : postprocessValue ( value ) , circularCache : [ ] . concat ( circularCache , [ value ] ) , isCircular : isCircular , hideRoot : false } ) ) ; if ( node !== false ) { childNodes . push ( node ) ; } } } ) ; return childNodes ; }


Input: Returns the n Items string for this node generating and caching it if it hasn t been created yet . [CODESPLIT] function createItemString ( data , limit ) { var count = 0 ; var hasMore = false ; if ( ( 0 , _isSafeInteger2 [ 'default' ] ) ( data . size ) ) { count = data . size ; } else { for ( var _iterator = data , _isArray = Array . isArray ( _iterator ) , _i = 0 , _iterator = _isArray ? _iterator : ( 0 , _getIterator3 [ 'default' ] ) ( _iterator ) ; ; ) { var _ref ; if ( _isArray ) { if ( _i >= _iterator . length ) break ; _ref = _iterator [ _i ++ ] ; } else { _i = _iterator . next ( ) ; if ( _i . done ) break ; _ref = _i . value ; } var entry = _ref ; // eslint-disable-line no-unused-vars if ( limit && count + 1 > limit ) { hasMore = true ; break ; } count += 1 ; } } return '' + ( hasMore ? '>' : '' ) + count + ' ' + ( count !== 1 ? 'entries' : 'entry' ) ; }


Input: Configures <JSONNestedNode > to render an iterable [CODESPLIT] function JSONIterableNode ( _ref2 ) { var props = ( 0 , _objectWithoutProperties3 [ 'default' ] ) ( _ref2 , [ ] ) ; return _react2 [ 'default' ] . createElement ( _JSONNestedNode2 [ 'default' ] , ( 0 , _extends3 [ 'default' ] ) ( { } , props , { nodeType : 'Iterable' , nodeTypeIndicator : '()' , createItemString : createItemString } ) ) ; }


Input: first : xxxx xxxx? xxx?xxxx second : ?xxx xxx?xxxx [CODESPLIT] function join ( first , second ) { if ( ! first || ! second ) { return first + second ; } var firstIndex = first . indexOf ( '?' ) ; var secondIndex = second . indexOf ( '?' ) ; var firstQuery = '' ; var secondQuery = '' ; if ( firstIndex != - 1 ) { firstQuery = first . substring ( firstIndex ) ; first = first . substring ( 0 , firstIndex ) ; } if ( secondIndex != - 1 ) { secondQuery = second . substring ( secondIndex ) ; second = second . substring ( 0 , secondIndex ) ; } var query = firstQuery && secondQuery ? firstQuery + secondQuery . substring ( 1 ) : ( firstQuery || secondQuery ) ; if ( second ) { var lastIndex = first . length - 1 ; var startWithSep = isPathSeparator ( second [ 0 ] ) ; if ( isPathSeparator ( first [ lastIndex ] ) ) { first = startWithSep ? first . substring ( 0 , lastIndex ) + second : first + second ; } else { first = first + ( startWithSep ? '' : '/' ) + second ; } } return WEB_PROTOCOL_RE . test ( first ) ? formatUrl ( first + query ) : first + query ; }


Input: 处理请求数据 [CODESPLIT] function handleReq ( req , data ) { var method = util . getMethod ( data . method || req . method ) ; req . method = method ; req . timeout = parseInt ( data . timeout , 10 ) ; extend ( req . headers , data . headers ) ; if ( typeof data . charset == 'string' ) { var type = req . headers [ 'content-type' ] ; var charset = '; charset=' + data . charset ; if ( typeof type == 'string' ) { req . headers [ 'content-type' ] = type . split ( ';' ) [ 0 ] + charset ; } else { req . headers [ 'content-type' ] = charset ; } } else { delete data . charset ; } if ( ! util . hasRequestBody ( method ) ) { delete data . top ; delete data . bottom ; delete data . body ; delete req . headers [ 'content-length' ] ; } else if ( data . top || data . bottom || data . body ) { delete req . headers [ 'content-length' ] ; } util . isWhistleTransformData ( data ) && req . addZipTransform ( new WhistleTransform ( data ) ) ; }


Input:
构造函数 / 实例初始化 Constructor / instance initialization [CODESPLIT] function ( id , options ) { options = options || { } ; if ( typeof id === "object" ) { options = id ; } var _this = this ; var classPrefix = this . classPrefix = editormd . classPrefix ; var settings = this . settings = $ . extend ( true , editormd . defaults , options ) ; id = ( typeof id === "object" ) ? settings . id : id ; var editor = this . editor = $ ( "#" + id ) ; this . id = id ; this . lang = settings . lang ; var classNames = this . classNames = { textarea : { html : classPrefix + "html-textarea" , markdown : classPrefix + "markdown-textarea" } } ; settings . pluginPath = ( settings . pluginPath === "" ) ? settings . path + "../plugins/" : settings . pluginPath ; this . state . watching = ( settings . watch ) ? true : false ; if ( ! editor . hasClass ( "editormd" ) ) { editor . addClass ( "editormd" ) ; } editor . css ( { width : ( typeof settings . width === "number" ) ? settings . width + "px" : settings . width , height : ( typeof settings . height === "number" ) ? settings . height + "px" : settings . height } ) ; if ( settings . autoHeight ) { editor . css ( "height" , "auto" ) ; } var markdownTextarea = this . markdownTextarea = editor . children ( "textarea" ) ; if ( markdownTextarea . length < 1 ) { editor . append ( "<textarea></textarea>" ) ; markdownTextarea = this . markdownTextarea = editor . children ( "textarea" ) ; } markdownTextarea . addClass ( classNames . textarea . markdown ) . attr ( "placeholder" , settings . placeholder ) ; if ( typeof markdownTextarea . attr ( "name" ) === "undefined" || markdownTextarea . attr ( "name" ) === "" ) { markdownTextarea . attr ( "name" , ( settings . name !== "" ) ? settings . name : id + "-markdown-doc" ) ; } var appendElements = [ ( ! settings . readOnly ) ? "" : "" , ( ( settings . saveHTMLToTextarea ) ? "<textarea class=\"" + classNames . textarea . html + "\" name=\"" + id + "-html-code\"></textarea>" : "" ) , "

" , "

" , "

" ] . join ( "\n" ) ; editor . append ( appendElements ) . addClass ( classPrefix + "vertical" ) ; if ( settings . theme !== "" ) { editor . addClass ( classPrefix + "theme-" + settings . theme ) ; } this . mask = editor . children ( "." + classPrefix + "mask" ) ; this . containerMask = editor . children ( "." + classPrefix + "container-mask" ) ; if ( settings . markdown !== "" ) { markdownTextarea . val ( settings . markdown ) ; } if ( settings . appendMarkdown !== "" ) { markdownTextarea . val ( markdownTextarea . val ( ) + settings . appendMarkdown ) ; } this . htmlTextarea = editor . children ( "." + classNames . textarea . html ) ; this . preview = editor . children ( "." + classPrefix + "preview" ) ; this . previewContainer = this . preview . children ( "." + classPrefix + "preview-container" ) ; if ( settings . previewTheme !== "" ) { this . preview . addClass ( classPrefix + "preview-theme-" + settings . previewTheme ) ; } if ( typeof define === "function" && define . amd ) { if ( typeof katex !== "undefined" ) { editormd . $katex = katex ; } if ( settings . searchReplace && ! settings . readOnly ) { editormd . loadCSS ( settings . path + "codemirror/addon/dialog/dialog" ) ; editormd . loadCSS ( settings . path + "codemirror/addon/search/matchesonscrollbar" ) ; } } if ( ( typeof define === "function" && define . amd ) || ! settings . autoLoadModules ) { if ( typeof CodeMirror !== "undefined" ) { editormd . $CodeMirror = CodeMirror ; } if ( typeof marked !== "undefined" ) { editormd . $marked = marked ; } this . setCodeMirror ( ) . setToolbar ( ) . loadedDisplay ( ) ; } else { this . loadQueues ( ) ; } return this ; }


Input: 所需组件加载队列 Required components loading queue [CODESPLIT] function ( ) { var _this = this ; var settings = this . settings ; var loadPath = settings . path ; var loadFlowChartOrSequenceDiagram = function ( ) { if ( editormd . isIE8 ) { _this . loadedDisplay ( ) ; return ; } if ( settings . flowChart || settings . sequenceDiagram ) { editormd . loadScript ( loadPath + "raphael.min" , function ( ) { editormd . loadScript ( loadPath + "underscore.min" , function ( ) { if ( ! settings . flowChart && settings . sequenceDiagram ) { editormd . loadScript ( loadPath + "sequence-diagram.min" , function ( ) { _this . loadedDisplay ( ) ; } ) ; } else if ( settings . flowChart && ! settings . sequenceDiagram ) { editormd . loadScript ( loadPath + "flowchart.min" , function ( ) { editormd . loadScript ( loadPath + "jquery.flowchart.min" , function ( ) { _this . loadedDisplay ( ) ; } ) ; } ) ; } else if ( settings . flowChart && settings . sequenceDiagram ) { editormd . loadScript ( loadPath + "flowchart.min" , function ( ) { editormd . loadScript ( loadPath + "jquery.flowchart.min" , function ( ) { editormd . loadScript ( loadPath + "sequence-diagram.min" , function ( ) { _this . loadedDisplay ( ) ; } ) ; } ) ; } ) ; } } ) ; } ) ; } else { _this . loadedDisplay ( ) ; } } ; editormd . loadCSS ( loadPath + "codemirror/codemirror.min" ) ; if ( settings . searchReplace && ! settings . readOnly ) { editormd . loadCSS ( loadPath + "codemirror/addon/dialog/dialog" ) ; editormd . loadCSS ( loadPath + "codemirror/addon/search/matchesonscrollbar" ) ; } if ( settings . codeFold ) { editormd . loadCSS ( loadPath + "codemirror/addon/fold/foldgutter" ) ; } editormd . loadScript ( loadPath + "codemirror/codemirror.min" , function ( ) { editormd . $CodeMirror = CodeMirror ; editormd . loadScript ( loadPath + "codemirror/modes.min" , function ( ) { editormd . loadScript ( loadPath + "codemirror/addons.min" , function ( ) { _this . setCodeMirror ( ) ; if ( settings . mode !== "gfm" && settings . mode !== "markdown" ) { _this . loadedDisplay ( ) ; return false ; } _this . setToolbar ( ) ; editormd . loadScript ( loadPath + "marked.min" , function ( ) { editormd . $marked = marked ; if ( settings . previewCodeHighlight ) { editormd . loadScript ( loadPath + "prettify.min" , function ( ) { loadFlowChartOrSequenceDiagram ( ) ; } ) ; } else { loadFlowChartOrSequenceDiagram ( ) ; } } ) ; } ) ; } ) ; } ) ; return this ; }


Input: 设置 Editor . md 的整体主题，主要是工具栏 Setting Editor . md theme [CODESPLIT] function ( theme ) { var editor = this . editor ; var oldTheme = this . settings . theme ; var themePrefix = this . classPrefix + "theme-" ; editor . removeClass ( themePrefix + oldTheme ) . addClass ( themePrefix + theme ) ; this . settings . theme = theme ; return this ; }


Input: 设置 CodeMirror（编辑区）的主题 Setting CodeMirror ( Editor area ) theme [CODESPLIT] function ( theme ) { var settings = this . settings ; settings . editorTheme = theme ; if ( theme !== "default" ) { editormd . loadCSS ( settings . path + "codemirror/theme/" + settings . editorTheme ) ; } this . cm . setOption ( "theme" , theme ) ; return this ; }


Input: 设置 Editor . md 的主题 Setting Editor . md theme [CODESPLIT] function ( theme ) { var preview = this . preview ; var oldTheme = this . settings . previewTheme ; var themePrefix = this . classPrefix + "preview-theme-" ; preview . removeClass ( themePrefix + oldTheme ) . addClass ( themePrefix + theme ) ; this . settings . previewTheme = theme ; return this ; }


Input: 配置和初始化CodeMirror组件 CodeMirror initialization [CODESPLIT] function ( ) { var settings = this . settings ; var editor = this . editor ; if ( settings . editorTheme !== "default" ) { editormd . loadCSS ( settings . path + "codemirror/theme/" + settings . editorTheme ) ; } var codeMirrorConfig = { mode : settings . mode , theme : settings . editorTheme , tabSize : settings . tabSize , dragDrop : false , autofocus : settings . autoFocus , autoCloseTags : settings . autoCloseTags , readOnly : ( settings . readOnly ) ? "nocursor" : false , indentUnit : settings . indentUnit , lineNumbers : settings . lineNumbers , lineWrapping : settings . lineWrapping , extraKeys : { "Ctrl-Q" : function ( cm ) { cm . foldCode ( cm . getCursor ( ) ) ; } } , foldGutter : settings . codeFold , gutters : [ "CodeMirror-linenumbers" , "CodeMirror-foldgutter" ] , matchBrackets : settings . matchBrackets , indentWithTabs : settings . indentWithTabs , styleActiveLine : settings . styleActiveLine , styleSelectedText : settings . styleSelectedText , autoCloseBrackets : settings . autoCloseBrackets , showTrailingSpace : settings . showTrailingSpace , highlightSelectionMatches : ( ( ! settings . matchWordHighlight ) ? false : { showToken : ( settings . matchWordHighlight === "onselected" ) ? false : / \w / } ) } ; this . codeEditor = this . cm = editormd . $CodeMirror . fromTextArea ( this . markdownTextarea [ 0 ] , codeMirrorConfig ) ; this . codeMirror = this . cmElement = editor . children ( ".CodeMirror" ) ; if ( settings . value !== "" ) { this . cm . setValue ( settings . value ) ; } this . codeMirror . css ( { fontSize : settings . fontSize , width : ( ! settings . watch ) ? "100%" : "50%" } ) ; if ( settings . autoHeight ) { this . codeMirror . css ( "height" , "auto" ) ; this . cm . setOption ( "viewportMargin" , Infinity ) ; } if ( ! settings . lineNumbers ) { this . codeMirror . find ( ".CodeMirror-gutters" ) . css ( "border-right" , "none" ) ; } return this ; }


Input: 跳转到指定的行 Goto CodeMirror line [CODESPLIT] function ( line ) { var settings = this . settings ; if ( ! settings . gotoLine ) { return this ; } var cm = this . cm ; var editor = this . editor ; var count = cm . lineCount ( ) ; var preview = this . preview ; if ( typeof line === "string" ) { if ( line === "last" ) { line = count ; } if ( line === "first" ) { line = 1 ; } } if ( typeof line !== "number" ) { alert ( "Error: The line number must be an integer." ) ; return this ; } line = parseInt ( line ) - 1 ; if ( line > count ) { alert ( "Error: The line number range 1-" + count ) ; return this ; } cm . setCursor ( { line : line , ch : 0 } ) ; var scrollInfo = cm . getScrollInfo ( ) ; var clientHeight = scrollInfo . clientHeight ; var coords = cm . charCoords ( { line : line , ch : 0 } , "local" ) ; cm . scrollTo ( null , ( coords . top + coords . bottom - clientHeight ) / 2 ) ; if ( settings . watch ) { var cmScroll = this . codeMirror . find ( ".CodeMirror-scroll" ) [ 0 ] ; var height = $ ( cmScroll ) . height ( ) ; var scrollTop = cmScroll . scrollTop ; var percent = ( scrollTop / cmScroll . scrollHeight ) ; if ( scrollTop === 0 ) { preview . scrollTop ( 0 ) ; } else if ( scrollTop + height >= cmScroll . scrollHeight - 16 ) { preview . scrollTop ( preview [ 0 ] . scrollHeight ) ; } else { preview . scrollTop ( preview [ 0 ] . scrollHeight * percent ) ; } } cm . focus ( ) ; return this ; }


Input: 扩展当前实例对象，可同时设置多个或者只设置一个 Extend editormd instance object can mutil setting . [CODESPLIT] function ( ) { if ( typeof arguments [ 1 ] !== "undefined" ) { if ( typeof arguments [ 1 ] === "function" ) { arguments [ 1 ] = $ . proxy ( arguments [ 1 ] , this ) ; } this [ arguments [ 0 ] ] = arguments [ 1 ] ; } if ( typeof arguments [ 0 ] === "object" && typeof arguments [ 0 ] . length === "undefined" ) { $ . extend ( true , this , arguments [ 0 ] ) ; } return this ; }


Input: 重新配置 Resetting editor options [CODESPLIT] function ( key , value ) { var settings = this . settings ; if ( typeof key === "object" ) { settings = $ . extend ( true , settings , key ) ; } if ( typeof key === "string" ) { settings [ key ] = value ; } this . settings = settings ; this . recreate ( ) ; return this ; }


Input: 注册事件处理方法 Bind editor event handle [CODESPLIT] function ( eventType , callback ) { var settings = this . settings ; if ( typeof settings [ "on" + eventType ] !== "undefined" ) { settings [ "on" + eventType ] = $ . proxy ( callback , this ) ; } return this ; }


Input: 显示工具栏 Display toolbar [CODESPLIT] function ( callback ) { var settings = this . settings ; if ( settings . readOnly ) { return this ; } if ( settings . toolbar && ( this . toolbar . length < 1 || this . toolbar . find ( "." + this . classPrefix + "menu" ) . html ( ) === "" ) ) { this . setToolbar ( ) ; } settings . toolbar = true ; this . toolbar . show ( ) ; this . resize ( ) ; $ . proxy ( callback || function ( ) { } , this ) ( ) ; return this ; }


Input: 隐藏工具栏 Hide toolbar [CODESPLIT] function ( callback ) { var settings = this . settings ; settings . toolbar = false ; this . toolbar . hide ( ) ; this . resize ( ) ; $ . proxy ( callback || function ( ) { } , this ) ( ) ; return this ; }


Input: 页面滚动时工具栏的固定定位 Set toolbar in window scroll auto fixed position [CODESPLIT] function ( fixed ) { var state = this . state ; var editor = this . editor ; var toolbar = this . toolbar ; var settings = this . settings ; if ( typeof fixed !== "undefined" ) { settings . toolbarAutoFixed = fixed ; } var autoFixedHandle = function ( ) { var $window = $ ( window ) ; var top = $window . scrollTop ( ) ; if ( ! settings . toolbarAutoFixed ) { return false ; } if ( top - editor . offset ( ) . top > 10 && top < editor . height ( ) ) { toolbar . css ( { position : "fixed" , width : editor . width ( ) + "px" , left : ( $window . width ( ) - editor . width ( ) ) / 2 + "px" } ) ; } else { toolbar . css ( { position : "absolute" , width : "100%" , left : 0 } ) ; } } ; if ( ! state . fullscreen && ! state . preview && settings . toolbar && settings . toolbarAutoFixed ) { $ ( window ) . bind ( "scroll" , autoFixedHandle ) ; } return this ; }


Input:
配置和初始化工具栏 Set toolbar and Initialization [CODESPLIT] function ( ) { var settings = this . settings ; if ( settings . readOnly ) { return this ; } var editor = this . editor ; var preview = this . preview ; var classPrefix = this . classPrefix ; var toolbar = this . toolbar = editor . children ( "." + classPrefix + "toolbar" ) ; if ( settings . toolbar && toolbar . length < 1 ) { var toolbarHTML = "

" ; editor . append ( toolbarHTML ) ; toolbar = this . toolbar = editor . children ( "." + classPrefix + "toolbar" ) ; } if ( ! settings . toolbar ) { toolbar . hide ( ) ; return this ; } toolbar . show ( ) ; var icons = ( typeof settings . toolbarIcons === "function" ) ? settings . toolbarIcons ( ) : ( ( typeof settings . toolbarIcons === "string" ) ? editormd . toolbarModes [ settings . toolbarIcons ] : settings . toolbarIcons ) ; var toolbarMenu = toolbar . find ( "." + this . classPrefix + "menu" ) , menu = "" ; var pullRight = false ; for ( var i = 0 , len = icons . length ; i < len ; i ++ ) { var name = icons [ i ] ; if ( name === "||" ) { pullRight = true ; } else if ( name === "|" ) { menu += "
|
" ; } else { var isHeader = ( / h(\d) / . test ( name ) ) ; var index = name ; if ( name === "watch" && ! settings . watch ) { index = "unwatch" ; } var title = settings . lang . toolbar [ index ] ; var iconTexts = settings . toolbarIconTexts [ index ] ; var iconClass = settings . toolbarIconsClass [ index ] ; title = ( typeof title === "undefined" ) ? "" : title ; iconTexts = ( typeof iconTexts === "undefined" ) ? "" : iconTexts ; iconClass = ( typeof iconClass === "undefined" ) ? "" : iconClass ; var menuItem = pullRight ? "
" : "
" ; if ( typeof settings . toolbarCustomIcons [ name ] !== "undefined" && typeof settings . toolbarCustomIcons [ name ] !== "function" ) { menuItem += settings . toolbarCustomIcons [ name ] ; } else { menuItem += "" ; menuItem += "" + ( ( isHeader ) ? name . toUpperCase ( ) : ( ( iconClass === "" ) ? iconTexts : "" ) ) + "" ; menuItem += "" ; } menuItem += "
" ; menu = pullRight ? menuItem + menu : menu + menuItem ; } } toolbarMenu . html ( menu ) ; toolbarMenu . find ( "[title=\"Lowercase\"]" ) . attr ( "title" , settings . lang . toolbar . lowercase ) ; toolbarMenu . find ( "[title=\"ucwords\"]" ) . attr ( "title" , settings . lang . toolbar . ucwords ) ; this . setToolbarHandler ( ) ; this . setToolbarAutoFixed ( ) ; return this ; }


Input: 工具栏图标事件处理器 Bind toolbar icons event handle [CODESPLIT] function ( ) { var _this = this ; var settings = this . settings ; if ( ! settings . toolbar || settings . readOnly ) { return this ; } var toolbar = this . toolbar ; var cm = this . cm ; var classPrefix = this . classPrefix ; var toolbarIcons = this . toolbarIcons = toolbar . find ( "." + classPrefix + "menu > li > a" ) ; var toolbarIconHandlers = this . getToolbarHandles ( ) ; toolbarIcons . bind ( editormd . mouseOrTouch ( "click" , "touchend" ) , function ( event ) { var icon = $ ( this ) . children ( ".fa" ) ; var name = icon . attr ( "name" ) ; var cursor = cm . getCursor ( ) ; var selection = cm . getSelection ( ) ; if ( name === "" ) { return ; } _this . activeIcon = icon ; if ( typeof toolbarIconHandlers [ name ] !== "undefined" ) { $ . proxy ( toolbarIconHandlers [ name ] , _this ) ( cm ) ; } else { if ( typeof settings . toolbarHandlers [ name ] !== "undefined" ) { $ . proxy ( settings . toolbarHandlers [ name ] , _this ) ( cm , icon , cursor , selection ) ; } } if ( name !== "link" && name !== "reference-link" && name !== "image" && name !== "code-block" && name !== "preformatted-text" && name !== "watch" && name !== "preview" && name !== "search" && name !== "fullscreen" && name !== "info" ) { cm . focus ( ) ; } return false ; } ) ; return this ; }


Input:
创建关于Editor . md的对话框 Create about Editor . md dialog [CODESPLIT] function ( ) { var _this = this ; var editor = this . editor ; var classPrefix = this . classPrefix ; var infoDialogHTML = [ "
" , "
" , "
 " + editormd . title + "v" + editormd . version + "
" , "
" + this . lang . description + "
" , "
" + editormd . homePage + "
" , "
Copyright © 2015 Pandao, The MIT License.
" , "
" , "" , "
" ] . join ( "\n" ) ; editor . append ( infoDialogHTML ) ; var infoDialog = this . infoDialog = editor . children ( "." + classPrefix + "dialog-info" ) ; infoDialog . find ( "." + classPrefix + "dialog-close" ) . bind ( editormd . mouseOrTouch ( "click" , "touchend" ) , function ( ) { _this . hideInfoDialog ( ) ; } ) ; infoDialog . css ( "border" , ( editormd . isIE8 ) ? "1px solid #ddd" : "" ) . css ( "z-index" , editormd . dialogZindex ) . show ( ) ; this . infoDialogPosition ( ) ; return this ; }


Input: 关于Editor . md对话居中定位 Editor . md dialog position handle [CODESPLIT] function ( ) { var infoDialog = this . infoDialog ; var _infoDialogPosition = function ( ) { infoDialog . css ( { top : ( $ ( window ) . height ( ) - infoDialog . height ( ) ) / 2 + "px" , left : ( $ ( window ) . width ( ) - infoDialog . width ( ) ) / 2 + "px" } ) ; } ; _infoDialogPosition ( ) ; $ ( window ) . resize ( _infoDialogPosition ) ; return this ; }


Input: 显示关于Editor . md Display about Editor . md dialog [CODESPLIT] function ( ) { $ ( "html,body" ) . css ( "overflow-x" , "hidden" ) ; var _this = this ; var editor = this . editor ; var settings = this . settings ; var infoDialog = this . infoDialog = editor . children ( "." + this . classPrefix + "dialog-info" ) ; if ( infoDialog . length < 1 ) { this . createInfoDialog ( ) ; } this . lockScreen ( true ) ; this . mask . css ( { opacity : settings . dialogMaskOpacity , backgroundColor : settings . dialogMaskBgColor } ) . show ( ) ; infoDialog . css ( "z-index" , editormd . dialogZindex ) . show ( ) ; this . infoDialogPosition ( ) ; return this ; }


Input: 编辑器界面重建，用于动态语言包或模块加载等 Recreate editor [CODESPLIT] function ( ) { var _this = this ; var editor = this . editor ; var settings = this . settings ; this . codeMirror . remove ( ) ; this . setCodeMirror ( ) ; if ( ! settings . readOnly ) { if ( editor . find ( ".editormd-dialog" ) . length > 0 ) { editor . find ( ".editormd-dialog" ) . remove ( ) ; } if ( settings . toolbar ) { this . getToolbarHandles ( ) ; this . setToolbar ( ) ; } } this . loadedDisplay ( true ) ; return this ; }


Input: 高亮预览HTML的pre代码部分 highlight of preview codes [CODESPLIT] function ( ) { var settings = this . settings ; var previewContainer = this . previewContainer ; if ( settings . previewCodeHighlight ) { previewContainer . find ( "pre" ) . addClass ( "prettyprint linenums" ) ; if ( typeof prettyPrint !== "undefined" ) { prettyPrint ( ) ; } } return this ; }


Input: 解析TeX ( KaTeX ) 科学公式 TeX ( KaTeX ) Renderer [CODESPLIT] function ( ) { if ( timer === null ) { return this ; } this . previewContainer . find ( "." + editormd . classNames . tex ) . each ( function ( ) { var tex = $ ( this ) ; editormd . $katex . render ( tex . text ( ) , tex [ 0 ] ) ; tex . find ( ".katex" ) . css ( "font-size" , "1.6em" ) ; } ) ; return this ; }


Input: 解析和渲染流程图及时序图 FlowChart and SequenceDiagram Renderer [CODESPLIT] function ( ) { var $this = this ; var settings = this . settings ; var previewContainer = this . previewContainer ; if ( editormd . isIE8 ) { return this ; } if ( settings . flowChart ) { if ( flowchartTimer === null ) { return this ; } previewContainer . find ( ".flowchart" ) . flowChart ( ) ; } if ( settings . sequenceDiagram ) { previewContainer . find ( ".sequence-diagram" ) . sequenceDiagram ( { theme : "simple" } ) ; } var preview = $this . preview ; var codeMirror = $this . codeMirror ; var codeView = codeMirror . find ( ".CodeMirror-scroll" ) ; var height = codeView . height ( ) ; var scrollTop = codeView . scrollTop ( ) ; var percent = ( scrollTop / codeView [ 0 ] . scrollHeight ) ; var tocHeight = 0 ; preview . find ( ".markdown-toc-list" ) . each ( function ( ) { tocHeight += $ ( this ) . height ( ) ; } ) ; var tocMenuHeight = preview . find ( ".editormd-toc-menu" ) . height ( ) ; tocMenuHeight = ( ! tocMenuHeight ) ? 0 : tocMenuHeight ; if ( scrollTop === 0 ) { preview . scrollTop ( 0 ) ; } else if ( scrollTop + height >= codeView [ 0 ] . scrollHeight - 16 ) { preview . scrollTop ( preview [ 0 ] . scrollHeight ) ; } else { preview . scrollTop ( ( preview [ 0 ] . scrollHeight + tocHeight + tocMenuHeight ) * percent ) ; } return this ; }


Input: 注册键盘快捷键处理 Register CodeMirror keyMaps ( keyboard shortcuts ) . [CODESPLIT] function ( keyMap ) { var _this = this ; var cm = this . cm ; var settings = this . settings ; var toolbarHandlers = editormd . toolbarHandlers ; var disabledKeyMaps = settings . disabledKeyMaps ; keyMap = keyMap || null ; if ( keyMap ) { for ( var i in keyMap ) { if ( $ . inArray ( i , disabledKeyMaps ) < 0 ) { var map = { } ; map [ i ] = keyMap [ i ] ; cm . addKeyMap ( keyMap ) ; } } } else { for ( var k in editormd . keyMaps ) { var _keyMap = editormd . keyMaps [ k ] ; var handle = ( typeof _keyMap === "string" ) ? $ . proxy ( toolbarHandlers [ _keyMap ] , _this ) : $ . proxy ( _keyMap , _this ) ; if ( $ . inArray ( k , [ "F9" , "F10" , "F11" ] ) < 0 && $ . inArray ( k , disabledKeyMaps ) < 0 ) { var _map = { } ; _map [ k ] = handle ; cm . addKeyMap ( _map ) ; } } $ ( window ) . keydown ( function ( event ) { var keymaps = { "120" : "F9" , "121" : "F10" , "122" : "F11" } ; if ( $ . inArray ( keymaps [ event . keyCode ] , disabledKeyMaps ) < 0 ) { switch ( event . keyCode ) { case 120 : $ . proxy ( toolbarHandlers [ "watch" ] , _this ) ( ) ; return false ; break ; case 121 : $ . proxy ( toolbarHandlers [ "preview" ] , _this ) ( ) ; return false ; break ; case 122 : $ . proxy ( toolbarHandlers [ "fullscreen" ] , _this ) ( ) ; return false ; break ; default : break ; } } } ) ; } return this ; }


Input: 绑定同步滚动 [CODESPLIT] function ( ) { var _this = this ; var preview = this . preview ; var settings = this . settings ; var codeMirror = this . codeMirror ; var mouseOrTouch = editormd . mouseOrTouch ; if ( ! settings . syncScrolling ) { return this ; } var cmBindScroll = function ( ) { codeMirror . find ( ".CodeMirror-scroll" ) . bind ( mouseOrTouch ( "scroll" , "touchmove" ) , function ( event ) { var height = $ ( this ) . height ( ) ; var scrollTop = $ ( this ) . scrollTop ( ) ; var percent = ( scrollTop / $ ( this ) [ 0 ] . scrollHeight ) ; var tocHeight = 0 ; preview . find ( ".markdown-toc-list" ) . each ( function ( ) { tocHeight += $ ( this ) . height ( ) ; } ) ; var tocMenuHeight = preview . find ( ".editormd-toc-menu" ) . height ( ) ; tocMenuHeight = ( ! tocMenuHeight ) ? 0 : tocMenuHeight ; if ( scrollTop === 0 ) { preview . scrollTop ( 0 ) ; } else if ( scrollTop + height >= $ ( this ) [ 0 ] . scrollHeight - 16 ) { preview . scrollTop ( preview [ 0 ] . scrollHeight ) ; } else { preview . scrollTop ( ( preview [ 0 ] . scrollHeight + tocHeight + tocMenuHeight ) * percent ) ; } $ . proxy ( settings . onscroll , _this ) ( event ) ; } ) ; } ; var cmUnbindScroll = function ( ) { codeMirror . find ( ".CodeMirror-scroll" ) . unbind ( mouseOrTouch ( "scroll" , "touchmove" ) ) ; } ; var previewBindScroll = function ( ) { preview . bind ( mouseOrTouch ( "scroll" , "touchmove" ) , function ( event ) { var height = $ ( this ) . height ( ) ; var scrollTop = $ ( this ) . scrollTop ( ) ; var percent = ( scrollTop / $ ( this ) [ 0 ] . scrollHeight ) ; var codeView = codeMirror . find ( ".CodeMirror-scroll" ) ; if ( scrollTop === 0 ) { codeView . scrollTop ( 0 ) ; } else if ( scrollTop + height >= $ ( this ) [ 0 ] . scrollHeight ) { codeView . scrollTop ( codeView [ 0 ] . scrollHeight ) ; } else { codeView . scrollTop ( codeView [ 0 ] . scrollHeight * percent ) ; } $ . proxy ( settings . onpreviewscroll , _this ) ( event ) ; } ) ; } ; var previewUnbindScroll = function ( ) { preview . unbind ( mouseOrTouch ( "scroll" , "touchmove" ) ) ; } ; codeMirror . bind ( { mouseover : cmBindScroll , mouseout : cmUnbindScroll , touchstart : cmBindScroll , touchend : cmUnbindScroll } ) ; if ( settings . syncScrolling === "single" ) { return this ; } preview . bind ( { mouseover : previewBindScroll , mouseout : previewUnbindScroll , touchstart : previewBindScroll , touchend : previewUnbindScroll } ) ; return this ; }


Input:
加载队列完成之后的显示处理 Display handle of the module queues loaded after . [CODESPLIT] function ( recreate ) { recreate = recreate || false ; var _this = this ; var editor = this . editor ; var preview = this . preview ; var settings = this . settings ; this . containerMask . hide ( ) ; this . save ( ) ; if ( settings . watch ) { preview . show ( ) ; } editor . data ( "oldWidth" , editor . width ( ) ) . data ( "oldHeight" , editor . height ( ) ) ; // 为了兼容Zepto
 this . resize ( ) ; this . registerKeyMaps ( ) ; $ ( window ) . resize ( function ( ) { _this . resize ( ) ; } ) ; this . bindScrollEvent ( ) . bindChangeEvent ( ) ; if ( ! recreate ) { $ . proxy ( settings . onload , this ) ( ) ; } this . state . loaded = true ; return this ; }