` will be\n passed to the HTML element, allowing you set the `className`, `style`, etc.\n\n ```jsx\n import { InView } from 'react-intersection-observer';\n\n const Component = () => (\n console.log('Inview:', inView)}>\n Plain children are always rendered. Use onChange to monitor state.
\n \n );\n\n export default Component;\n ```\n */\nexport class InView extends React.Component<\n IntersectionObserverProps | PlainChildrenProps,\n State\n> {\n constructor(props: IntersectionObserverProps | PlainChildrenProps) {\n super(props);\n this.state = {\n inView: !!props.initialInView,\n entry: undefined,\n };\n }\n\n componentDidUpdate(prevProps: IntersectionObserverProps) {\n // If a IntersectionObserver option changed, reinit the observer\n if (\n prevProps.rootMargin !== this.props.rootMargin ||\n prevProps.root !== this.props.root ||\n prevProps.threshold !== this.props.threshold ||\n prevProps.skip !== this.props.skip ||\n prevProps.trackVisibility !== this.props.trackVisibility ||\n prevProps.delay !== this.props.delay\n ) {\n this.unobserve();\n this.observeNode();\n }\n }\n\n componentWillUnmount() {\n this.unobserve();\n this.node = null;\n }\n\n node: Element | null = null;\n _unobserveCb: (() => void) | null = null;\n\n observeNode() {\n if (!this.node || this.props.skip) return;\n const {\n threshold,\n root,\n rootMargin,\n trackVisibility,\n delay,\n fallbackInView,\n } = this.props;\n\n this._unobserveCb = observe(\n this.node,\n this.handleChange,\n {\n threshold,\n root,\n rootMargin,\n // @ts-ignore\n trackVisibility,\n // @ts-ignore\n delay,\n },\n fallbackInView,\n );\n }\n\n unobserve() {\n if (this._unobserveCb) {\n this._unobserveCb();\n this._unobserveCb = null;\n }\n }\n\n handleNode = (node?: Element | null) => {\n if (this.node) {\n // Clear the old observer, before we start observing a new element\n this.unobserve();\n\n if (!node && !this.props.triggerOnce && !this.props.skip) {\n // Reset the state if we get a new node, and we aren't ignoring updates\n this.setState({ inView: !!this.props.initialInView, entry: undefined });\n }\n }\n\n this.node = node ? node : null;\n this.observeNode();\n };\n\n handleChange = (inView: boolean, entry: IntersectionObserverEntry) => {\n if (inView && this.props.triggerOnce) {\n // If `triggerOnce` is true, we should stop observing the element.\n this.unobserve();\n }\n if (!isPlainChildren(this.props)) {\n // Store the current State, so we can pass it to the children in the next render update\n // There's no reason to update the state for plain children, since it's not used in the rendering.\n this.setState({ inView, entry });\n }\n if (this.props.onChange) {\n // If the user is actively listening for onChange, always trigger it\n this.props.onChange(inView, entry);\n }\n };\n\n render() {\n if (!isPlainChildren(this.props)) {\n const { inView, entry } = this.state;\n return this.props.children({ inView, entry, ref: this.handleNode });\n }\n\n const {\n children,\n as,\n triggerOnce,\n threshold,\n root,\n rootMargin,\n onChange,\n skip,\n trackVisibility,\n delay,\n initialInView,\n fallbackInView,\n ...props\n } = this.props;\n\n return React.createElement(\n as || 'div',\n { ref: this.handleNode, ...props },\n children,\n );\n }\n}\n","import * as React from 'react';\nimport type { InViewHookResponse, IntersectionOptions } from './index';\nimport { observe } from './observe';\n\ntype State = {\n inView: boolean;\n entry?: IntersectionObserverEntry;\n};\n\n/**\n * React Hooks make it easy to monitor the `inView` state of your components. Call\n * the `useInView` hook with the (optional) [options](#options) you need. It will\n * return an array containing a `ref`, the `inView` status and the current\n * [`entry`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry).\n * Assign the `ref` to the DOM element you want to monitor, and the hook will\n * report the status.\n *\n * @example\n * ```jsx\n * import React from 'react';\n * import { useInView } from 'react-intersection-observer';\n *\n * const Component = () => {\n * const { ref, inView, entry } = useInView({\n * threshold: 0,\n * });\n *\n * return (\n * \n *
{`Header inside viewport ${inView}.`}
\n * \n * );\n * };\n * ```\n */\nexport function useInView({\n threshold,\n delay,\n trackVisibility,\n rootMargin,\n root,\n triggerOnce,\n skip,\n initialInView,\n fallbackInView,\n onChange,\n}: IntersectionOptions = {}): InViewHookResponse {\n const [ref, setRef] = React.useState(null);\n const callback = React.useRef();\n const [state, setState] = React.useState({\n inView: !!initialInView,\n entry: undefined,\n });\n\n // Store the onChange callback in a `ref`, so we can access the latest instance\n // inside the `useEffect`, but without triggering a rerender.\n callback.current = onChange;\n\n React.useEffect(\n () => {\n // Ensure we have node ref, and that we shouldn't skip observing\n if (skip || !ref) return;\n\n let unobserve: (() => void) | undefined = observe(\n ref,\n (inView, entry) => {\n setState({\n inView,\n entry,\n });\n if (callback.current) callback.current(inView, entry);\n\n if (entry.isIntersecting && triggerOnce && unobserve) {\n // If it should only trigger once, unobserve the element after it's inView\n unobserve();\n unobserve = undefined;\n }\n },\n {\n root,\n rootMargin,\n threshold,\n // @ts-ignore\n trackVisibility,\n // @ts-ignore\n delay,\n },\n fallbackInView,\n );\n\n return () => {\n if (unobserve) {\n unobserve();\n }\n };\n },\n // We break the rule here, because we aren't including the actual `threshold` variable\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n // If the threshold is an array, convert it to a string, so it won't change between renders.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n Array.isArray(threshold) ? threshold.toString() : threshold,\n ref,\n root,\n rootMargin,\n triggerOnce,\n skip,\n trackVisibility,\n fallbackInView,\n delay,\n ],\n );\n\n const entryTarget = state.entry?.target;\n\n React.useEffect(() => {\n if (!ref && entryTarget && !triggerOnce && !skip) {\n // If we don't have a node ref, then reset the state (unless the hook is set to only `triggerOnce` or `skip`)\n // This ensures we correctly reflect the current state - If you aren't observing anything, then nothing is inView\n setState({\n inView: !!initialInView,\n entry: undefined,\n });\n }\n }, [ref, entryTarget, triggerOnce, skip, initialInView]);\n\n const result = [setRef, state.inView, state.entry] as InViewHookResponse;\n\n // Support object destructuring, by adding the specific values.\n result.ref = result[0];\n result.inView = result[1];\n result.entry = result[2];\n\n return result;\n}\n"],"names":["factory","modules","installedModules","__webpack_require__","moduleId","exports","module","i","l","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","Common","_nextId","_seed","_nowStartTime","Date","_warnedOnce","_decomp","extend","obj","deep","argsStart","deepClone","arguments","length","source","prop","constructor","clone","keys","push","values","path","begin","end","split","slice","set","val","parts","shuffle","array","j","Math","floor","random","temp","choose","choices","isElement","HTMLElement","nodeType","nodeName","isArray","toString","isFunction","isPlainObject","isString","clamp","min","max","sign","now","window","performance","webkitNow","_seededRandom","colorToNumber","colorString","replace","charAt","parseInt","logLevel","log","console","apply","concat","Array","info","warn","warnOnce","message","join","deprecated","warning","chain","nextId","indexOf","haystack","needle","map","list","func","mapped","topologicalSort","graph","result","visited","node","_topologicalSort","neighbors","neighbor","funcs","_chained","lastResult","args","chainPathBefore","base","chainPathAfter","setDecomp","decomp","getDecomp","global","e","Bounds","vertices","bounds","x","y","update","velocity","Infinity","vertex","contains","point","overlaps","boundsA","boundsB","translate","vector","shift","position","deltaX","deltaY","Vector","magnitude","sqrt","magnitudeSquared","rotate","angle","output","cos","sin","rotateAbout","normalise","dot","vectorA","vectorB","cross","cross3","vectorC","add","sub","mult","scalar","div","perp","negate","neg","atan2","_temp","Vertices","points","body","index","isInternal","fromPath","match","parseFloat","centre","area","mean","average","signed","abs","inertia","mass","numerator","denominator","v","verticesLength","translateX","translateY","dx","dy","pointX","pointY","nextVertex","scale","scaleX","scaleY","delta","chamfer","radius","quality","qualityMin","qualityMax","newVertices","prevVertex","currentRadius","prevNormal","nextNormal","diagonalRadius","pow","radiusVector","midNormal","scaledVertex","precision","theta","acos","clockwiseSort","sort","vertexA","vertexB","isConvex","k","z","flag","hull","upper","lower","pop","Events","on","eventNames","callback","names","events","off","callbacks","newCallbacks","trigger","event","eventClone","Composite","Body","options","id","type","parent","isModified","bodies","constraints","composites","label","plugin","cache","allBodies","allConstraints","allComposites","setModified","composite","updateParents","updateChildren","childComposite","objects","addBody","addConstraint","addComposite","constraint","remove","removeBody","removeConstraint","removeComposite","compositeA","compositeB","removeCompositeAt","splice","removeBodyAt","removeConstraintAt","clear","keepStatic","filter","isStatic","move","rebase","translation","recursive","rotation","setPosition","Sleeping","Axes","_inertiaScale","_nextCollidingGroupId","_nextNonCollidingGroupId","_nextCategory","defaults","force","torque","positionImpulse","constraintImpulse","totalContacts","speed","angularSpeed","angularVelocity","isSensor","isSleeping","motion","sleepThreshold","density","restitution","friction","frictionStatic","frictionAir","collisionFilter","category","mask","group","slop","timeScale","render","visible","opacity","strokeStyle","fillStyle","lineWidth","sprite","xScale","yScale","xOffset","yOffset","circleRadius","positionPrev","anglePrev","axes","_original","_initProperties","nextGroup","isNonColliding","nextCategory","defaultFillStyle","defaultStrokeStyle","defaultLineWidth","settings","setStatic","setMass","setDensity","setInertia","setVertices","setAngle","setVelocity","setAngularVelocity","setParts","setCentre","part","inverseMass","inverseInertia","moment","fromVertices","autoHull","hullCentre","total","_totalProperties","relative","totalArea","totalInertia","deltaTime","correction","deltaTimeSquared","velocityPrevX","velocityPrevY","applyForce","offset","properties","_motionWakeThreshold","_motionSleepThreshold","_minBias","timeFactor","minMotion","maxMotion","sleepCounter","afterCollisions","pairs","pair","isActive","collision","bodyA","bodyB","sleepingBody","movingBody","wasSleeping","Collision","Pair","_supports","_overlapAB","overlap","axis","_overlapBA","collided","parentA","parentB","depth","normal","tangent","penetration","supports","collides","_overlapAxes","minOverlap","table","minAxis","minAxisX","minAxisY","supportsB","_findSupports","supportCount","supportsA","verticesA","verticesB","overlapAB","overlapBA","verticesALength","verticesBLength","verticesAX","verticesAY","verticesBX","verticesBY","axesLength","overlapMin","Number","MAX_VALUE","overlapAxisNumber","axisX","axisY","minA","minB","maxA","maxB","_projectToAxis","projection","direction","vertexC","distance","bodyAPositionX","bodyAPositionY","normalX","normalY","nearestDistance","Contact","timestamp","contacts","activeContacts","separation","confirmedActive","timeCreated","timeUpdated","parentAVerticesLength","support","contactId","contact","setActive","Constraint","_warming","_torqueDampen","_minLength","pointA","pointB","initialPointA","initialPointB","stiffness","damping","angularStiffness","angleA","angleB","anchors","preSolveAll","impulse","solveAll","fixedA","fixedB","solve","pointAWorld","pointBWorld","currentLength","share","normalVelocity","relativeVelocity","difference","massTotal","resistanceTotal","zero","postSolveAll","gradient","toFixed","xx","Bodies","rectangle","width","height","trapezoid","slope","verticesPath","x1","x2","x3","circle","maxSides","sides","ceil","polygon","PI","yy","vertexSets","flagInternal","removeCollinear","minimumArea","removeDuplicatePoints","canDecomp","Boolean","quickDecomp","concave","makeCCW","removeCollinearPoints","decomposed","chunkVertices","partA","partB","pav","pbv","da","db","Mouse","element","mouse","document","absolute","mousedownPosition","mouseupPosition","wheelDelta","button","pixelRatio","getAttribute","sourceEvents","mousemove","mousedown","mouseup","mousewheel","_getRelativeMousePosition","changedTouches","preventDefault","detail","setElement","addEventListener","clearSourceEvents","setOffset","setScale","elementBounds","getBoundingClientRect","rootNode","documentElement","parentNode","scrollX","undefined","pageXOffset","scrollLeft","scrollY","pageYOffset","scrollTop","touches","pageX","left","pageY","top","clientWidth","clientHeight","Detector","setBodies","detector","collisions","bodiesLength","canCollide","_compareBoundsX","boundXMax","boundYMax","boundYMin","bodyAStatic","partsALength","partsASingle","partsBLength","partsBStart","filterA","filterB","Plugin","_registry","register","isPlugin","registered","pluginVersion","versionParse","version","number","registeredVersion","resolve","dependency","dependencyParse","range","install","isUsed","used","isFor","parsed","for","versionSatisfies","use","plugins","uses","dependencies","sortedDependencies","status","_warned","tracked","parsedBase","resolved","test","pattern","exec","major","minor","patch","isRange","operator","prerelease","Render","_requestAnimationFrame","_cancelAnimationFrame","requestAnimationFrame","webkitRequestAnimationFrame","mozRequestAnimationFrame","msRequestAnimationFrame","setTimeout","cancelAnimationFrame","mozCancelAnimationFrame","webkitCancelAnimationFrame","msCancelAnimationFrame","_goodFps","_goodDelta","controller","engine","canvas","frameRequestId","timing","historySize","deltaHistory","lastTime","lastTimestamp","lastElapsed","timestampElapsed","timestampElapsedHistory","engineDeltaHistory","engineElapsedHistory","elapsedHistory","background","wireframeBackground","hasBounds","enabled","wireframes","showSleeping","showDebug","showStats","showPerformance","showBounds","showVelocity","showCollisions","showSeparations","showAxes","showPositions","showAngleIndicator","showIds","showVertexNumbers","showConvexHulls","showInternalEdges","showMousePosition","_createCanvas","context","getContext","textures","showBroadphase","setPixelRatio","appendChild","run","loop","time","_updateTiming","world","stats","stop","_getPixelRatio","setAttribute","style","lookAt","padding","center","viewHeight","outerRatio","innerRatio","startViewTransform","boundsWidth","boundsHeight","boundsScaleX","boundsScaleY","setTransform","endViewTransform","startTime","currentBackground","_applyBackground","globalCompositeOperation","fillRect","enableSleeping","bodyConvexHulls","bodyWireframes","bodyBounds","bodyAxes","bodyPositions","bodyVelocity","bodyIds","separations","vertexNumbers","mousePosition","sections","font","textBaseline","textAlign","section","fillText","lastEngineDelta","lastDelta","deltaMean","_mean","elapsedMean","engineDeltaMean","engineElapsedMean","rateMean","fps","gap","round","count","indicator","plotY","beginPath","moveTo","lineTo","stroke","start","arc","closePath","coils","fill","globalAlpha","texture","_getTexture","drawImage","rect","normalPosX","normalPosY","inspector","selected","item","data","setLineDash","selectStart","selectBounds","unshift","createElement","oncontextmenu","onselectstart","devicePixelRatio","webkitBackingStorePixelRatio","mozBackingStorePixelRatio","msBackingStorePixelRatio","oBackingStorePixelRatio","backingStorePixelRatio","imagePath","image","Image","src","cssBackground","backgroundSize","normalImpulse","tangentImpulse","Engine","Resolver","Pairs","positionIterations","velocityIterations","constraintIterations","gravity","grid","buckets","broadphase","metrics","_bodiesApplyGravity","_bodiesUpdate","collisionStart","preSolvePosition","solvePosition","postSolvePosition","preSolveVelocity","solveVelocity","collisionActive","collisionEnd","_bodiesClearForces","merge","engineA","engineB","gravityScale","worldBounds","_restingThresh","_restingThreshTangent","_positionDampen","_positionWarming","_frictionNormalMultiplier","activeCount","pairsLength","contactShare","positionDampen","positionWarming","verticesTranslate","boundsUpdate","positionImpulseX","positionImpulseY","contactsLength","contactVertex","impulseX","impulseY","maxFriction","timeScaleSquared","restingThresh","frictionNormalMultiplier","restingThreshTangent","NumberMaxValue","bodyAVelocity","bodyBVelocity","tangentX","tangentY","inverseMassTotal","offsetAX","offsetAY","offsetBX","offsetBY","velocityPointAX","velocityPointAY","relativeVelocityX","relativeVelocityY","tangentVelocity","normalOverlap","normalForce","frictionLimit","oAcN","oBcN","contactNormalImpulse","contactTangentImpulse","pairIndex","pairsList","pairsListLength","pairsTable","collisionsLength","removePairIndex","Matter","Composites","Grid","MouseConstraint","Query","Runner","SAT","Svg","World","before","after","stack","columns","rows","columnGap","rowGap","lastBody","row","maxHeight","column","bodyHeight","bodyWidth","xOffsetA","yOffsetA","xOffsetB","yOffsetB","bodyAHeight","bodyAWidth","bodyBHeight","mesh","crossBrace","col","bodyC","pyramid","actualRows","lastBodyWidth","newtonsCradle","size","car","wheelSize","wheelAOffset","wheelBOffset","wheelA","wheelB","axelA","axelB","softBody","particleRadius","particleOptions","constraintOptions","bucketWidth","bucketHeight","forceUpdate","bucket","bucketId","gridChanged","newRegion","_getRegion","region","union","_regionUnion","startCol","endCol","startRow","endRow","_getBucketId","isInsideNewRegion","isInsideOldRegion","_bucketRemoveBody","_createBucket","_bucketAddBody","_createActivePairsList","regionA","regionB","_createRegion","gridPairs","pairId","bucketLength","pairKeys","pairKeysLength","mouseConstraint","_triggerEvents","mouseEvents","partsAStart","ray","startPoint","endPoint","rayWidth","rayAngle","rayLength","rayX","rayY","outside","_frameTimeout","clearTimeout","runner","deltaSampleSize","counterTimestamp","frameCounter","timePrev","timeScalePrev","isFixed","deltaMin","deltaMax","tick","pathToVertices","sampleLength","il","segment","segments","segmentsQueue","lastSegment","lastPoint","lx","ly","addPoint","px","py","pathSegType","isRelative","addSegmentPoint","segType","pathSegTypeAsLetter","toUpperCase","_svgPathToAbsolute","getTotalLength","pathSegList","numberOfItems","getItem","getPathSegAtLength","getPointAtLength","x0","y0","y1","y2","segs","len","seg","replaceItem","createSVGPathSegMovetoAbs","createSVGPathSegLinetoAbs","createSVGPathSegLinetoHorizontalAbs","createSVGPathSegLinetoVerticalAbs","createSVGPathSegCurvetoCubicAbs","createSVGPathSegCurvetoCubicSmoothAbs","createSVGPathSegCurvetoQuadraticAbs","createSVGPathSegCurvetoQuadraticSmoothAbs","createSVGPathSegArcAbs","r1","r2","largeArcFlag","sweepFlag","observerMap","Map","RootIds","WeakMap","rootId","unsupportedValue","optionsToId","root","has","createObserver","instance","thresholds","elements","observer","IntersectionObserver","entries","forEach","entry","inView","isIntersecting","some","threshold","intersectionRatio","trackVisibility","isVisible","target","observe","fallbackInView","boundingClientRect","intersectionRect","rootBounds","delete","unobserve","disconnect","isPlainChildren","props","children","InView","_unobserveCb","handleNode","triggerOnce","skip","setState","initialInView","observeNode","handleChange","onChange","state","componentDidUpdate","prevProps","rootMargin","this","delay","componentWillUnmount","ref","as","React","useInView","setRef","current","entryTarget"],"sourceRoot":""}